diff --git "a/3349.jsonl" "b/3349.jsonl" new file mode 100644--- /dev/null +++ "b/3349.jsonl" @@ -0,0 +1,507 @@ +{"seq_id":"456395817","text":"# -*- coding: utf-8 -*-\n\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import db\nfrom os import listdir\nfrom os.path import isfile, join\nimport json\n\nclass ProgressBar:\n\n def __init__(self, total, prefix='', sufix='', length=100, fill='█'):\n \"\"\"\n :param total: total iterations (Int)\n :param prefix: prefix string (Str)\n :param sufix: suffix string (Str)\n :param length: character length of bar (Int)\n :param fill: bar fill character (Str)\n \"\"\"\n self.total = total\n self.prefix = prefix\n self.sufix = sufix\n self.length = length\n self.fill = fill\n\n def print(self, iteration):\n \"\"\"\n :param iteration: current iteration (Int)\n \"\"\"\n if iteration < 0:\n iteration = 0\n elif iteration > self.total:\n iteration = self.total\n\n percent = '{0:.2f}'.format(100 * (iteration / float(self.total)))\n filledlength = int(self.length * iteration // self.total)\n bar = self.fill * filledlength + '-' * (self.length - filledlength)\n print('\\r%s |%s| %s%% %s' % (self.prefix, bar, percent, self.sufix), end='\\r')\n # Print New Line on Complete\n if iteration == self.total:\n print()\n\n\ndef loadJSONToFireBase(inputpath, key, database, rootitem=''):\n\n # Fetch the service account key JSON file contents\n try:\n cred = credentials.Certificate(key)\n except FileNotFoundError:\n print('key no found {}'.format(key))\n return False\n except ValueError:\n print('Invalid key {}'.format(key))\n return False\n\n # Initialize the application\n print(\"Initializing Firebase application...\")\n app = firebase_admin.initialize_app(cred, {\n 'databaseURL': database\n })\n\n # Get DB reference to read and write data\n ref = db.reference(rootitem)\n\n # Collect file list from the given directory\n files = [f for f in listdir(inputpath) if isfile(join(inputpath, f)) and (f.endswith('.js') or f.endswith('.json'))]\n\n # Create progress bar to show current progress\n progress_bar = ProgressBar(total=len(files), prefix='Progress', sufix='Complete', length=50)\n # Initial call to print 0% progress\n progress_bar.print(0)\n\n # Read each JSON file and push to firebase db\n for i, file in enumerate(files):\n # Open JSON file\n with open(join(inputpath, file)) as json_file:\n # Read data\n data = json.load(json_file)\n\n # Push new data and get ID\n post_ref = ref.push()\n\n # Add ID into the data\n data['id'] = post_ref.key\n\n # Set the data\n post_ref.set(data)\n\n # update progress\n progress_bar.print(i+1)\n\n return True","sub_path":"script/JSON2FireBase.py","file_name":"JSON2FireBase.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"475248938","text":"class SentimentScore(object):\n def __init__(self, data):\n self.label = data[\"label\"]\n\n\nclass SimpleSentiment(object):\n def __init__(self, data):\n self.sentiment = SentimentScore(data[\"sentiment\"])\n self.wordCount = data[\"wordCount\"]\n\n\nclass SentenceSentiment(object):\n def __init__(self, data):\n self.sentiment = SentimentScore(data[\"sentiment\"])\n self.start = data[\"start\"]\n self.end = data[\"end\"]\n self.text = data[\"text\"]\n\nclass WordPolarityTimeline(object):\n def __init__(self, data):\n self.label = data[\"label\"]\n self.timelineY = data[\"timelineY\"]\n\n\nclass WordSentiment(object):\n def __init__(self, data):\n self.sentiment = data[\"sentiment\"]\n self.wordIndex = data[\"wordIndex\"]\n self.text = data[\"text\"]\n\n\nclass EntitySentiment(object):\n def __init__(self, data):\n self.sentiment = SentimentScore(data[\"sentiment\"])\n self.start = data[\"start\"]\n self.end = data[\"end\"]\n self.sentence = data[\"sentence\"]\n self.sentenceHtml = data[\"sentenceHtml\"]\n self.text = data[\"text\"]\n self.headNoun = data[\"headNoun\"]\n self.headNounIndex = data[\"headNounIndex\"]\n self.salience = data[\"salience\"]\n\n\nclass RelatedEntity(object):\n def __init__(self, data):\n self.head = data[\"head\"]\n self.headIndex = data[\"headIndex\"]\n self.text = data[\"text\"]\n\n\nclass EntityRelationSentiment(object):\n def __init__(self, data):\n self.entity1 = RelatedEntity(data[\"entity1\"])\n self.entity2 = RelatedEntity(data[\"entity2\"])\n self.sentiment = SentimentScore(data[\"sentiment\"])\n self.salience = data[\"salience\"]\n self.sentence = data[\"sentence\"]\n self.sentenceHtml = data[\"sentenceHtml\"]\n\n\nclass Speculation(object):\n def __init__(self, data):\n self.start = data[\"start\"]\n self.end = data[\"end\"]\n self.sentenceIndex = data[\"sentenceIndex\"]\n self.speculationType = data[\"speculationType\"]\n self.text = data[\"text\"]\n\n\nclass Intent(object):\n def __init__(self, data):\n self.start = data[\"start\"]\n self.end = data[\"end\"]\n self.sentenceIndex = data[\"sentenceIndex\"]\n self.intentType = data[\"intentType\"]\n self.text = data[\"text\"]\n\n\nclass Risk(object):\n def __init__(self, data):\n self.start = data[\"start\"]\n self.end = data[\"end\"]\n self.sentenceIndex = data[\"sentenceIndex\"]\n self.riskType = data[\"riskType\"]\n self.text = data[\"text\"]\n\n\nclass Comparison(object):\n def __init__(self, data):\n self.start = data[\"start\"]\n self.end = data[\"end\"]\n self.sentenceIndex = data[\"sentenceIndex\"]\n self.comparisonType = data[\"comparisonType\"]\n self.text = data[\"text\"]\n\nclass NamedEntity(object):\n def __init__(self, data):\n self.head = data[\"head\"]\n self.headIndex = data[\"headIndex\"]\n self.start = data[\"start\"]\n self.end = data[\"end\"]\n self.sentence = data[\"sentence\"]\n self.sentenceHtml = data[\"sentenceHtml\"]\n self.text = data[\"text\"]\n self.namedEntityTypes = data[\"namedEntityTypes\"]\n\n\nclass PosTag(object):\n def __init__(self, data):\n self.posTag = data[\"posTag\"]\n self.posTaggedWord = data[\"posTaggedWord\"]\n self.sentenceIndex = data[\"sentenceIndex\"]\n self.stem = data[\"stem\"]\n self.text = data[\"text\"]\n self.wordIndex = data[\"wordIndex\"]\n\n\nclass Dependency(object):\n def __init__(self, data):\n self.predicate = data[\"predicate\"]\n self.relation = data[\"relation\"]\n\n\nclass Dependent(object):\n def __init__(self, data):\n self.text = data[\"text\"]\n self.stem = data[\"stem\"]\n self.wordIndex = data[\"wordIndex\"]\n\n\nclass Governor(object):\n def __init__(self, data):\n self.text = data[\"text\"]\n self.stem = data[\"stem\"]\n self.wordIndex = data[\"wordIndex\"]\n\n\nclass DependencyParse(object):\n def __init__(self, data):\n self.dependency = Dependency(data[\"dependency\"])\n self.dependent = Dependent(data[\"dependent\"])\n if \"governor\" in data:\n self.governor = Governor(data[\"governor\"])\n\n\nclass Chunk(object):\n def __init__(self, data):\n self.chunkType = data[\"chunkType\"]\n self.start = data[\"start\"]\n self.end = data[\"end\"]\n self.text = data[\"text\"]\n self.sentenceIndex = data[\"sentenceIndex\"]\n\n\nclass ChunkHead(object):\n def __init__(self, data):\n self.posTag = data[\"posTag\"]\n self.posTaggedWord = data[\"posTaggedWord\"]\n self.stem = data[\"stem\"]\n self.text = data[\"text\"]\n self.wordIndex = data[\"wordIndex\"]\n\n\nclass ChunkConstituent(object):\n def __init__(self, data):\n self.chunk = Chunk(data[\"chunk\"])\n self.head = ChunkHead(data[\"head\"])","sub_path":"affectr/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"356265958","text":"import time\n\nfrom gui_state.gui_state import GuiState\nfrom gui_state.state_manager import StateManager\nfrom gui_components.grid import Grid\nfrom gui_components.gui_util import *\nfrom sudoku.solver import *\nfrom sudoku.generator import generate_board\n\n\nclass GameState(GuiState):\n solvers = [BacktrackingSolver(), ExactCoverSolver()]\n\n def __init__(self, state_manager: StateManager):\n super().__init__('play_game', state_manager)\n self.level = None\n self.solver_index = 0\n self.solver = self.solvers[self.solver_index]\n self.board = None\n self.grid = None\n self.font = get_font(\"arialblack\", 24)\n self.solving = False\n self.btn_new = PygButton((660, 150, 150, 36), 'New', font=self.font)\n self.btn_reset = PygButton((660, 200, 150, 36), 'Reset', font=self.font)\n self.btn_solve = PygButton((660, 250, 150, 36), 'Solve', font=self.font)\n self.btn_check = PygButton((660, 300, 150, 36), 'Check', font=self.font)\n self.btn_menu = PygButton((660, 350, 150, 36), 'Menu', font=self.font)\n self.btn_solver = PygButton((660, 400, 150, 36), 'Algorithm', font=self.font)\n self.buttons = (self.btn_new, self.btn_solve, self.btn_check, self.btn_reset, self.btn_menu, self.btn_solver)\n self.key = None\n self.start_time = None\n self.solve_event = pygame.USEREVENT + 1\n self.step_timer = 200\n self.steps = []\n self.solving_dots = 0\n self.solved = False\n\n def on_start(self, win):\n self.level = self.data_in[\"diff\"]\n self.solver_index = self.data_in[\"solver_index\"]\n self.solver = self.solvers[self.solver_index]\n self.board = generate_board(self.level)\n self.grid = Grid(self.board, 9, 9, 640, 640)\n pygame.time.set_timer(self.solve_event, self.step_timer)\n self.start_time = time.time()\n pass\n\n def update(self, win, time_delta):\n game_time = round(time.time() - self.start_time)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.quit = True\n if event.type == pygame.KEYDOWN and not self.solving:\n # Numbers 1-9 to set temporary value\n if pygame.K_0 < event.key <= pygame.K_9:\n self.key = event.key - pygame.K_0\n # Delete or 0 to remove temporary\n if event.key == pygame.K_DELETE or event.key == pygame.K_0:\n self.grid.clear()\n self.key = None\n # Set as\n if event.key == pygame.K_RETURN and not self.solving:\n i, j = self.grid.selected\n if self.grid.cells[i][j].temp != 0:\n self.grid.set_value(self.grid.cells[i][j].temp)\n self.key = None\n\n if event.type == pygame.MOUSEBUTTONDOWN and not self.solving:\n pos = pygame.mouse.get_pos()\n clicked = self.grid.on_click(pos)\n if clicked:\n self.grid.select(clicked[0], clicked[1])\n self.key = None\n if 'click' in self.btn_new.handleEvent(event) and not self.solving:\n self.on_start(win)\n if 'click' in self.btn_reset.handleEvent(event) and not self.solving:\n self.start_time = time.time()\n self.solved = False\n self.grid.reset()\n if 'click' in self.btn_solve.handleEvent(event):\n if self.solving:\n self.btn_solve.caption = \"Solve\"\n self.steps.clear()\n self.solving = False\n else:\n self.grid.reset()\n self.btn_solve.caption = \"Solving\" + (\".\" * self.solving_dots)\n self.solver.solve(self.grid.board, lambda r, c, v: self.steps.append((r, c, v)))\n self.solving = True\n if 'click' in self.btn_menu.handleEvent(event) and not self.solving:\n self.next_state = \"main_menu\"\n if 'click' in self.btn_check.handleEvent(event) and not self.solving:\n empty_cell = find_empty_cell(self.grid.board)\n if empty_cell is not None:\n self.grid.select(empty_cell[0], empty_cell[1])\n else:\n for i, j in product(range(len(self.grid.board)), range(len(self.grid.board[0]))):\n if not is_valid(self.grid.board, i, j, self.grid.board[i][j]):\n self.grid.select(i, j)\n break\n if i == 8 and j == 8:\n self.solved = True\n\n if 'click' in self.btn_solver.handleEvent(event) and not self.solving:\n self.solver_index += 1\n if self.solver_index == len(self.solvers):\n self.solver_index = 0\n\n self.solver = self.solvers[self.solver_index]\n if self.solving:\n if event.type == self.solve_event:\n # Go step by step\n if len(self.steps) > 0:\n step = self.steps.pop(0)\n row, col, val = step\n self.grid.select(row, col)\n self.grid.set_value(val, True)\n\n if self.solving_dots == 3:\n self.solving_dots = 0\n else:\n self.solving_dots += 1\n\n self.btn_solve.caption = \"Solving\" + (\".\" * self.solving_dots)\n else:\n self.btn_solve.caption = \"Solve\"\n self.solving = False\n\n if self.grid.selected and self.key is not None:\n self.grid.set_temp(self.key)\n\n # Update board\n self.draw_grid(win, self.grid, game_time)\n\n # Update all buttons\n for btn in self.buttons:\n btn.draw(win)\n\n def draw_grid(self, win, board, game_time):\n win.fill((255, 255, 255))\n # Draw time\n font = get_font(\"segoeui\", 28)\n text = font.render(self.solver.name, 1, BLACK)\n win.blit(text, (660, 450))\n if self.solved:\n text = font.render(\"Solved\", 1, GREEN)\n win.blit(text, (660, 500))\n else:\n text = font.render(\"Time: \" + self.format_time(game_time), 1, BLACK)\n win.blit(text, (660, 500))\n # Draw grid and board\n board.draw(win)\n\n @staticmethod\n def format_time(sec):\n minute = sec // 60\n second = sec % 60\n formatted_time = \" \" + str(minute) + \":\" + str(second)\n return formatted_time\n\n def on_end(self):\n self.level = None\n self.solver = None\n self.board = None\n self.grid = None\n","sub_path":"gui_state/game_state.py","file_name":"game_state.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"465140770","text":"# a function named spelling_corrector that accepts two arguments.\n# The first argument is a sentence (string) and the second argument\n# is a list of words (correct_spells). Your function should check\n# each word in the input string against all the words in the\n# correct_spells list and return a string such that:\n#\n# If a word in the original sentence matches exactly with a word in\n# the correct_spells then the word is not modified and it should be\n# directly copied to the output string.\n#\n# if a word in the sentence can match a word in the correct_spells\n# list by replacing, inserting, or deleting a single character,\n# then that word should be replaced by the correct word in the\n# correct_spelled list.\n#\n# If neither of the two previous conditions is true, then the word in\n# the original string should not be modified and should be directly\n# copied to the output string.\n#\n# Notes:\n#\n# Do not spell check one or two letter words (copy them directly to the output string).\n# In case of a tie use the first word from the correct_spelled list.\n# Ignore capitalization, i.e. consider capital letters to be the same as lower case letters.\n# All characters in the output string should all be in lower case letters.\n# Assume that the input string only includes alphabetic characters and spaces. (a-z and A-Z)\n# Remove extra spaces between the words.\n# Remove spaces at the start and end of the output string.\n\ndef spelling_corrector(input_string, input_list):\n\n input_string = input_string.lower().split()\n output_string = ''\n\n def single_insert_or_delete(string1, string2):\n string1 = string1.lower()\n string2 = string2.lower()\n len_string1 = len(string1)\n len_string2 = len(string2)\n if string1 == string2:\n return 0\n \n if abs(len_string1-len_string2)!=1:\n return 2\n\n if max(len_string1, len_string2) == min(len_string1, len_string2)+1:\n if len_string1 > len_string2:\n maximum_string = string1\n minimum_string = string2\n else:\n maximum_string = string2\n minimum_string = string1\n test_string = ''\n for i in range(len(maximum_string)):\n test_string = maximum_string.replace(maximum_string[i],'',1)\n if test_string == minimum_string:\n return 1\n break\n test_string = ''\n return 2\n\n def find_mismatch(string1, string2):\n string1 = string1.lower()\n string2 = string2.lower()\n if string1 == string2:\n result = 0\n elif len(string1) == len(string2):\n counter = 0\n for i in range(len(string1)):\n if string1[i] != string2[i]:\n counter += 1\n if counter == 1:\n result = 1\n else:\n result = 2\n else:\n result = 2\n return result\n\n for word in input_string:\n\n # Not checking one or two letter words (copy them directly to the output string).\n if len(word) <= 2:\n output_string += word\n if word != input_string[-1]:\n output_string += \" \"\n continue\n \n # Then we check all the words in the list to find exactly the same word\n for item in input_list:\n\n result_find_mismatch = find_mismatch(word, item) # Calling find_mismatch function for the word of string and the word of list\n result_single_insert_or_delete = single_insert_or_delete(word , item) # Calling single_insert_or_delete function for the word of string and the word of list\n counter = 0 # initial value for flag of changes\n \n if result_find_mismatch == 0: # if two words is the same\n output_string += word\n counter += 1 # The flag is up, if the Change has occurred in this condition\n if word != input_string[-1]: # added a space character, if the word is not the last one.\n output_string += \" \"\n break \n\n # If there are no words in the list that match the string word, so check words spelled for other cases\n if counter != 1:\n for item in input_list:\n\n result_find_mismatch = find_mismatch(word, item) # Calling find_mismatch function for the word of string and the word of list\n result_single_insert_or_delete = single_insert_or_delete(word , item) # Calling single_insert_or_delete function for the word of string and the word of list\n counter = 0 # initial value for flag of changes\n\n # if the two strings have the same length and mismatch in only one character.\n # or if the first string can become the same as the second string by inserting or deleting a single character. \n if result_find_mismatch == 1 or result_single_insert_or_delete == 1: \n output_string += item\n counter += 1 # The flag is up, if the Change has occurred in this condition\n if word != input_string[-1]: # added a space character, if the word is not the last one.\n output_string += \" \"\n break # break from this loop for choosen item\n \n # if the two strings have the same length and mismatch in only one character.\n # and if the two strings can become the same by Replacing one character\n elif result_find_mismatch == 1 and result_single_insert_or_delete == 2:\n output_string += item\n counter += 1 # The flag is up, if the Change has occurred in this condition\n if word != input_string[-1]: # added a space character, if the word is not the last one.\n output_string += \" \"\n break # break from this loop for choosen item\n\n # If none of the above conditions apply, move the word from the input string to the output string\n if counter == 0:\n output_string += word\n if word != input_string[-1]: # added a space character, if the word is not the last one.\n output_string += \" \"\n return output_string\n\n\n# driver code tester\nString = \"Asignment three xample inpu\"\ncorrect_spells = ['Assignmen', 'tree', 'three', 'example', 'output', 'input']\nresult = Spelling_corrector(String, correct_spells)\nprint(result)\n\n################### Instructor function ###################\n# def spelling_corrector (s,correct_spelled):\n# words=s.strip().split()\n# output_str=\"\"\n# for current_word in words:\n# if len(current_word)<=2 or (current_word in correct_spelled) :\n# output_str=output_str+\" \"+current_word\n# continue\n# min_mismatch=2\n# replacement_word=current_word\n# for correct_word in correct_spelled:\n# if min(_find_mismatch(current_word,correct_word), _single_insert_or_delete(current_word,correct_word))==1:\n# replacement_word=correct_word\n# break\n# output_str=output_str+\" \"+replacement_word\n# return output_str.strip().lower()\n# def _find_mismatch(s1,s2):\n# if len(s1) != len(s2):\n# return 2\n# s1=s1.lower()\n# s2=s2.lower()\n# number_of_mismatches=0\n# for index in range(len(s1)):\n# if s1[index] != s2[index]:\n# number_of_mismatches=number_of_mismatches+1\n# if number_of_mismatches>1:\n# return 2\n# return number_of_mismatches \n# def _single_insert_or_delete(s1,s2):\n# s1=s1.lower()\n# s2=s2.lower()\n# if s1==s2:\n# return 0\n# if abs(len(s1)-len(s2))!=1:\n# return 2\n\n# if len(s1)>len(s2):\n# # only deletion is possible\n# for k in range(len(s2)):\n# if s1[k]!=s2[k]:\n# if s1[k+1:]==s2[k:]:\n# return 1\n# else:\n# return 2\n# return 1\n# else: # s1 is shorter Only insertion is possible\n# for k in range(len(s1)):\n# if s1[k]!=s2[k]:\n# if s1[k:]==s2[k+1:]:\n# return 1\n# else:\n# return 2\n# return 1","sub_path":"11 - Assignment 2/03_spelling_corrector.py","file_name":"03_spelling_corrector.py","file_ext":"py","file_size_in_byte":8804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"549860257","text":"__author__ = 'yashar'\n\n\ndef BMI_with_pound_and_inch(weight, height):\n print(\"BMI is: \", weight * 703 / height ** 2)\n\n\ndef BMI_with_kilogram_and_meter(weight, height):\n print(\"BMI is: \", weight * 703 / height ** 2)\n\nweight_type = input(\"Enter 1 for pound and inch unit OR 2 for kilogram and meter unit: \")\nif int(weight_type) == 1:\n weight = float(input(\"Enter weight in pound: \"))\n height = float(input(\"Enter height in inch: \"))\n BMI_with_pound_and_inch(weight, height)\nelif int(weight_type) == 2:\n weight = float(input(\"Enter weight in kilogram: \"))\n height = float(input(\"Enter height in mete: \"))\n BMI_with_kilogram_and_meter(weight, height)\nelse:\n print(\"wrong number!\")\n","sub_path":"Python_projects/JavaAssignmentsInPython/Chapter2/Question2.py","file_name":"Question2.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"426482632","text":"# 문제 7-3을 딕셔너리를 사용하여 풀기\n\n# stu_no = [39, 14, 67, 105]\n# stu_name = [\"Justin\", \"John\", \"Mike\", \"Summer\"]\n\ndef find_name(x) :\n name = dict()\n stu_no = [39, 14, 67, 105]\n stu_name = [\"Justin\", \"John\", \"Mike\", \"Summer\"]\n for i in range(4):\n name[stu_no[i]] = stu_name[i]\n if x in name:\n return name[x]\n return \"?\"\n\n\nprint(find_name(39))\nprint(find_name(14))\nprint(find_name(50))","sub_path":"problem/p-14.py","file_name":"p-14.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"488468278","text":"#!/usr/bin/env python37\n# -*- coding: utf-8 -*-\n\"\"\"\n Author : xdong@wandtec.com\n date: 2021/1/30\n Change Activity:\n 2021/1/30:\n\n 没有父控件的窗口默认是顶层窗口,拥有一个特定操作。\n\n setWindowTitle\n windowTitle\n setWindowIcon\n windoIcon\n\n WindowState\n Qt.WindowNoState , Qt.WindowActive , Qt.Min.. , Qt.Max..\n\n 最大化 最小化 状态显示和控制\n showFullScreen() isFullScreen() / min / max\n\"\"\"\n\nfrom PyQt5.Qt import *\nimport sys\n\napp = QApplication(sys.argv)\n\n# 控件操作\n# 创建控件\nwindow = QWidget()\n# 设置控件\nwindow.resize(500, 500)\n\nicon = QIcon('setting-100.png')\nwindow.setWindowIcon(icon)\n\nwindow.setWindowOpacity(0.8)\n\n# 展示控件\n# window.showFullScreen()\nwindow.show()\n# 执行应用程序,进入消息循环\nsys.exit(app.exec())\n","sub_path":"my_notes/14.顶层窗口相关操作.py","file_name":"14.顶层窗口相关操作.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"98383452","text":"import torch\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torchvision.datasets\nfrom torchvision import transforms\nimport matplotlib.pyplot as plt\nimport time\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nepochs = 50\ninchannel = 3\nimage_size = 32\nPREPROCESS = transforms.Compose([transforms.Resize((image_size, image_size)), transforms.ToTensor(),\n transforms.Normalize(mean = [0.485, 0.456, 0.406], std = [1.0, 1.0, 1.0])\n ])\n\nPREPROCESS_TEST = transforms.Compose([transforms.Resize((image_size, image_size)), transforms.ToTensor()])\n\nbatch_size = 256\ntrainset = torchvision.datasets.CIFAR10(root = \".\", train = True, download = True, transform = PREPROCESS)\ntrain_loader = torch.utils.data.DataLoader(trainset, batch_size = batch_size, shuffle=True)\n\ntestset = torchvision.datasets.CIFAR10(root = \".\", train = False, download = True, transform = PREPROCESS_TEST)\ntest_loader = torch.utils.data.DataLoader(testset, batch_size = batch_size, shuffle=True)\n\ntrain_dataset, train_dataset_total = train_loader, len(trainset)\ntest_dataset, test_dataset_total = test_loader, len(testset)\n\nclass DefaultBlock(nn.Module):\n def __init__(self, inchannel, outchannel):\n super(DefaultBlock, self).__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(inchannel, outchannel, kernel_size=3, stride=1, padding=1, bias=False),\n nn.BatchNorm2d(outchannel)\n )\n\n def forward(self, out):\n out = self.conv1(out)\n out = F.relu(out)\n return out\n\n\nclass VGGModel(nn.Module):\n def __init__(self, DefaultBlock, num_classes):\n super(VGGModel, self).__init__()\n self.inchannel = inchannel\n self.layer1 = self.make_layer(DefaultBlock, 64, 2)\n self.layer2 = self.make_layer(DefaultBlock, 128, 2)\n self.layer3 = self.make_layer(DefaultBlock, 256, 3)\n self.layer4 = self.make_layer(DefaultBlock, 512, 3)\n self.layer5 = self.make_layer(DefaultBlock, 512, 3)\n\n self.fc1 = nn.Linear(512, 4096)\n self.bn_fc1 = nn.BatchNorm1d(num_features=4096)\n self.fc2 = nn.Linear(4096, 4096)\n self.bn_fc2 = nn.BatchNorm1d(num_features=4096)\n self.fc3 = nn.Linear(4096, num_classes)\n self.drop = nn.Dropout(0.5)\n\n def make_layer(self, block, out_channels, num_blocks):\n layers = []\n for x in range(num_blocks):\n layers.append(block(self.inchannel, out_channels))\n self.inchannel = out_channels\n layers.append(nn.MaxPool2d(kernel_size=2))\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = self.layer5(out)\n out = out.view(out.size(0), -1)\n out = self.fc1(out)\n out = self.bn_fc1(out)\n out = self.drop(out)\n out = self.fc2(out)\n out = self.bn_fc2(out)\n out = self.drop(out)\n out = self.fc3(out)\n return out\n\n\nmodel = VGGModel(DefaultBlock, num_classes = 10)\nif torch.cuda.is_available():\n model.cuda()\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr = 0.001)\ntrain_accuracy, test_accuracy, train_cost = [], [], []\n\nfor epoch in range(epochs):\n start = time.time()\n correct = 0\n cost = 0\n model.train()\n for (images,target) in train_dataset:\n images = images.to(device)\n target = target.to(device)\n out = model(images)\n loss = criterion(out, target)\n\n # Back-propogation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n _, pred = torch.max(out.data, 1)\n correct += (pred == target).sum().item()\n cost += loss.item()\n\n train_cost.append(cost)\n train_accuracy.append((correct/train_dataset_total) * 100)\n\n model.eval()\n correct_test = 0\n for (images_test, target_test) in test_dataset:\n images_test = images_test.to(device)\n target_test = target_test.to(device)\n\n out_test = model(images_test)\n _, pred_test = torch.max(out_test.data, 1)\n correct_test += (pred_test == target_test).sum().item()\n test_accuracy.append((correct_test/test_dataset_total) * 100)\n print(\"\\nEpoch:\", epoch, \" | Accuracy Train:\", train_accuracy[-1], \" | Accuracy Test:\", test_accuracy[-1], \" | Time:\", time.time() - start)\n\n\ntop5 = []\nfor (images_test, target_test) in test_dataset:\n images_test = images_test.to(device)\n target_test = target_test.to(device)\n out_test = model(images_test)\n out_test, pred_test = torch.sort(out_test, descending=True)\n target_test = target_test.view(-1, 1)\n for i, y in enumerate(pred_test[:,0:5]):\n top5.append(y in target_test[i])\n\n\nprint(\"\\n\\nFinal Train Accuracy:\", train_accuracy[-1])\nprint(\"Final Test Accuracy:\", test_accuracy[-1])\nprint(\"Top-1 error rate:\", 1 - test_accuracy[-1]/100)\nprint(\"Top-5 error rate:\", 1 - sum(top5)/test_dataset_total)\n\n\nfig, ax1 = plt.subplots()\ncolor = 'tab:red'\nax1.plot(train_cost, color=color)\nax1.set_xlabel('Epoch')\nax1.set_ylabel('Cost', color=color)\nax1.tick_params(axis='y', color=color)\nax2 = ax1.twinx() \ncolor = 'tab:orange'\nax2.set_ylabel('Accuracy') \nax2.plot( test_accuracy, color=color) \ncolor = 'tab:blue'\nax2.plot( train_accuracy, color=color)\nfig.tight_layout()\nfig.legend(['cost', 'train', 'test'])\nname = 'VGG - CIFAR10 - SGD - 0.001 - Experiment.jpg'\nplt.savefig(name)\n","sub_path":"src/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":5583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"360755988","text":"import sqlalchemy\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\nfrom sqlalchemy.orm import sessionmaker\r\nimport Classes.DatabaseHandlers.create_table as create_table\r\nimport Classes.DatabaseHandlers.databaseSingleton as SingletonDatabase\r\nfrom Classes import Statics\r\nfrom Classes.DatabaseHandlers import fetch\r\n\r\nBase = declarative_base()\r\n\r\ndatabaseInstance = SingletonDatabase.Database()\r\nengine = databaseInstance.engine\r\n\r\nBase.metadata.create_all(bind=engine)\r\nSession = sessionmaker(bind=engine)\r\n\r\nsession = Session()\r\n\r\ndef Update(table, id, attribute, value):\r\n s = str(table)\r\n if s == \"\":\r\n m = session.query(create_table.Users).filter(create_table.Users.user_id == id).update({attribute: value})\r\n session.commit()\r\n elif s == \"\":\r\n m = session.query(create_table.Vendors).filter(create_table.Vendors.vendor_id == id).update({attribute: value})\r\n session.commit()\r\n elif s == \"\":\r\n m = session.query(create_table.Medicines).filter(create_table.Medicines.medicine_id == id).update({attribute: value})\r\n session.commit()\r\n elif s == \"\":\r\n m = session.query(create_table.Orders).filter(create_table.Orders.order_id == id).update({attribute: value})\r\n session.commit()\r\n elif s == \"\":\r\n m = session.query(create_table.OrdersList).filter(create_table.OrdersList.order_id == id).update(\r\n {attribute: value})\r\n session.commit()\r\n\r\n Statics.userList.clear()\r\n Statics.vendorList.clear()\r\n Statics.medList.clear()\r\n Statics.notificationList.clear()\r\n Statics.orderList.clear()\r\n Statics.sellList.clear()\r\n Statics.expenseList.clear()\r\n Statics.orderlistList.clear()\r\n\r\n fetch.Fetch()\r\n\r\n\r\n#Update(create_table.Medicines, 4, 'medicine_type', 'guuuuuuuu')\r\nsession.close()","sub_path":"Classes/DatabaseHandlers/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"62454565","text":"import unittest\nimport pytest\n\nfrom ui_auto.base.data import Data\nfrom ui_auto.base.logs import get_log_path, log_path\nfrom ui_auto.base.log_decorator import log_decorator\nfrom ui_auto.page_object.page_operation import BaseTestCase\nfrom ui_auto.page_object.element_loc import ElementSelector\n\n\n@pytest.mark.run(order=5)\nclass TestMyCreation(BaseTestCase):\n file_name = __file__\n name = __name__\n case_log_path = log_path(file_name, name)\n\n d = Data()\n student_data = d.student_data()\n work_name = d.work_name\n\n @log_decorator(case_log_path)\n def test_01(self):\n self.step_log_path = self.case_log_path\n self.login(**self.student_data)\n self.click_button(*ElementSelector.bar_creative_space_loc)\n self.click_button(*ElementSelector.works_hall_my_works_tab_loc, loading=True)\n self.click_button(*ElementSelector.my_creation_draft_btn_loc, loading=True)\n self.click_button(*ElementSelector.my_creation_publish_draft_btn_loc, loading=True)\n self.add_work(self.work_name)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"ui_auto/testcase/my_creation_work.py","file_name":"my_creation_work.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"607272038","text":"import Adafruit_DHT\r\nimport datetime\r\nimport RPi.GPIO as GPIO\r\n\r\nGPIO_PIN = 4\r\n\r\ndef getDHT22(): \r\n h, t = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, GPIO_PIN)\r\n if h is not None and t is not None :\r\n id=datetime.datetime.now().strftime(\"%Y%m%d%H%M\")\r\n return id,t,h\r\n else:\r\n print('dht22 讀取失敗。')\r\n return False\r\n\r\n","sub_path":"dht22.py","file_name":"dht22.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"169815459","text":"import unittest\n\nfrom Mariana.layers import *\nfrom Mariana.rules import *\nimport Mariana.decorators as dec\nimport Mariana.costs as MC\nimport Mariana.regularizations as MR\nimport Mariana.scenari as MS\nimport Mariana.activations as MA\n\nimport theano.tensor as tt\nimport numpy as N\n\nclass MLPTests(unittest.TestCase):\n\n\tdef setUp(self) :\n\t\tself.xor_ins = [\n\t\t\t[0, 0],\n\t\t\t[0, 1],\n\t\t\t[1, 0],\n\t\t\t[1, 1]\n\t\t]\n\n\t\tself.xor_outs = [0, 1, 1, 0]\n\n\tdef tearDown(self) :\n\t\tpass\n\n\tdef trainMLP_xor(self) :\n\t\tls = MS.DefaultScenario(lr = 0.1, momentum = 0)\n\t\tcost = MC.NegativeLogLikelihood()\n\n\t\ti = Input(2, 'inp')\n\t\th = Hidden(4, activation = MA.tanh, decorators = [dec.GlorotTanhInit()], regularizations = [MR.L1(0), MR.L2(0)])\n\t\to = SoftmaxClassifier(2, learningScenario = ls, costObject = cost, name = \"out\")\n\n\t\tmlp = i > h > o\n\n\t\tself.xor_ins = N.array(self.xor_ins)\n\t\tself.xor_outs = N.array(self.xor_outs)\n\t\tfor i in xrange(1000) :\n\t\t\tii = i%len(self.xor_ins)\n\t\t\tmlp.train(\"out\", inp = [ self.xor_ins[ ii ] ], target = [ self.xor_outs[ ii ] ] )\n\t\t\n\t\treturn mlp\n\n\t# @unittest.skip(\"skipping\")\n\tdef test_xor(self) :\n\t\tmlp = self.trainMLP_xor()\n\t\tself.assertEqual(mlp.classify( \"out\", inp = [ self.xor_ins[0] ] )[0], 0 )\n\t\tself.assertEqual(mlp.classify( \"out\", inp = [ self.xor_ins[1] ] )[0], 1 )\n\t\tself.assertEqual(mlp.classify( \"out\", inp = [ self.xor_ins[2] ] )[0], 1 )\n\t\tself.assertEqual(mlp.classify( \"out\", inp = [ self.xor_ins[3] ] )[0], 0 )\n\n\t# @unittest.skip(\"skipping\")\n\tdef test_save_load(self) :\n\t\timport cPickle, os\n\n\t\tmlp = self.trainMLP_xor()\n\t\tmlp.save(\"test_save\")\n\t\tmlp2 = cPickle.load(open('test_save.mariana.pkl'))\n\n\t\tself.assertEqual(mlp2.classify( \"out\", inp = [ self.xor_ins[0] ] )[0], 0 )\n\t\tself.assertEqual(mlp2.classify( \"out\", inp = [ self.xor_ins[1] ] )[0], 1 )\n\t\tself.assertEqual(mlp2.classify( \"out\", inp = [ self.xor_ins[2] ] )[0], 1 )\n\t\tself.assertEqual(mlp2.classify( \"out\", inp = [ self.xor_ins[3] ] )[0], 0 )\n\t\t\n\t\tos.remove('test_save.mariana.pkl')\n\n\t# @unittest.skip(\"skipping\")\n\tdef test_composite(self) :\n\t\tls = MS.DefaultScenario(lr = 0.1, momentum = 0)\n\t\tcost = MC.NegativeLogLikelihood()\n\n\t\tinp = Input(2, 'inp')\n\t\th1 = Hidden(2, activation = MA.tanh, name = \"h1\")\n\t\th2 = Hidden(2, activation = MA.tanh, name = \"h2\")\n\t\to = SoftmaxClassifier(2, learningScenario = ls, costObject = cost, name = \"out\")\n\t\tc = Composite(name = \"Comp\")\n\t\t\n\t\tinp > h1 > c\n\t\tinp > h2 > c\n\t\tmlp = c > o\n\t\n\t\tself.xor_ins = N.array(self.xor_ins)\n\t\tself.xor_outs = N.array(self.xor_outs)\n\t\tfor i in xrange(1000) :\n\t\t\tii = i%len(self.xor_ins)\n\t\t\tmlp.train(\"out\", inp = [ self.xor_ins[ ii ] ], target = [ self.xor_outs[ ii ] ])\n\t\t\n\t\tself.assertEqual(mlp.classify( \"out\", inp = [ self.xor_ins[0] ] )[0], 0 )\n\t\tself.assertEqual(mlp.classify( \"out\", inp = [ self.xor_ins[1] ] )[0], 1 )\n\t\tself.assertEqual(mlp.classify( \"out\", inp = [ self.xor_ins[2] ] )[0], 1 )\n\t\tself.assertEqual(mlp.classify( \"out\", inp = [ self.xor_ins[3] ] )[0], 0 )\n\t\t\nif __name__ == '__main__' :\n\tunittest.main()\n","sub_path":"Mariana/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"46763193","text":"from dolfin import * \n\nn = 100 # number of cells \nw = 0.2 # widt \n\nmesh = UnitSquareMesh(n,n) # unit mesh of n lengh and n widt \nsubdomain = CellFunction('size_t', mesh, 0) # Hva skjer her, computer structure\n\nclass Tube(SubDomain): # Tube arver Subdomain, som har en inside metode som definerer en subklasset av unitsquare \n def inside(self, x, on_boundary):\n return 0.5-w-DOLFIN_EPS < x[0] < 0.5 + w + DOLFIN_EPS \n \nTube().mark(subdomain, 0) # mark funksjonen gaar over alle cellene og sjekker om inside metoden for den cellen returnerer true\nplot(subdomain)\ninteractive(True)\n\n\n\nV0 = FunctionSpace(mesh, \"DG\", 1) # Funksjonsrom over meshet med diskontinuerlig galerkin av grad 1 \nf = Expression('(x[0] > 0.3 && x[0] < 0.7 && x[1]< 0.5 ) ? 3.0 : 10.0')\n\n\nk = interpolate(f, V0)\n\nplot(k, interactive = True, title = \"Subdomains\") # Viser homogent omraade, k_values er ikke fordelt ennaa \n\n","sub_path":"backup_August/subdomain_tube.py","file_name":"subdomain_tube.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"512580266","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nCreated on Mo Aug 06 2018\n\n@author: jb4317, Jan-Peter Baehner\n\nProgramme to analyse the pedestal of shots of X-point height variation studies.\nShots loaded (including H-mode phases):\n 13042, 13043, 13044, 13045, 13046, 13047, 26MAY05 (6)\n 13704, 13705, 13706, 13707, 13708, 13709, 13710, 13711, 10AUG05 (8)\n 14545, 14546, 14547, 14548, 14552, 14554, 14555, 08NOV05 (7)\n (23822, 23824, 23825, 23826, 23827, 23832, \n 23835, 23837, 23841, 23842, 23843, 23844 09DEC09 (12))\nShots from 09DEC09 have separate Core TS and Edge TS data - had to be combined in special programme.\nAll other shots are missing the R2_CTS signal, i.e. the time resolved radial positions - use static R_CTS instead.\n\nWith new pedestal fitfunction\n\"\"\"\n\nimport pickle\nimport numpy as np\nimport math\nfrom power_fit import odr_complete\n#import matplotlib.pyplot as plt\n# import data from sessions\nfrom Xpoint_shots import shotnos,data,tLH,tHL,LHdata,HLdata\n\n# select only one session\n#shotnos=shotnos[14:]\n#data=data[14:]\n#tLH=tLH[14:]\n#tHL=tHL[14:]\n#LHdata=LHdata[14:]\n#HLdata=HLdata[14:]\n#%% define modified tanh function for fit on pedestal:\n# new tanh definition:\n# based on definition proposed by Groebner R.J. et al 1998 Plasma Phys. Control. Fusion 40 673\n# with additional quadratic term to account for more complex profiles\n# with location specification 'loc' for determining whether an inboard or an outboard pedestal is to be fitted\n\ndef ped_tanh_odr2(p,x,loc='out'):\n '''Modified tanh for fitting pedestal structures in \n density/temperature/pressure profiles in tokamak plasmas.\n p - list of parameters (len=7)\n x - xdata (usually major radius or normalized flux )\n loc = 'out'/'in' - defines whether outboard or inboard pedestal is to be fitted'''\n # extract function parameters from p\n a=p[0] # >0\n b=p[1] # a+b>0\n x_sym=p[2] # in [0.2,0.8] for inboard or in [0.8,1.5] for outboard in m (range of major radius in plasma)\n width=p[3] # in [0.001,0.5] in m\n slope=p[4] # no constraint\n dwell=p[5] # no constraint\n x_well=p[6] # same as x_sym\n \n # handle constraints \n if width<1e-3 or width>0.5 or a<0 or a+b<0:\n try:\n return np.ones(len(x))*1e200\n except TypeError:\n return 1e200\n \n if loc=='out': # fit outboard pedestal \n # handle constraints \n if x_sym<0.8 or x_sym>1.5 or x_well<0.8 or x_well>1.5:\n try:\n return np.ones(len(x))*1e200\n except TypeError:\n return 1e200\n #calculate parameters specific to outboard pedestal\n x_knee=x_sym-width/2\n c=dwell/(x_knee-x_well)**2\n # calculate function value:\n y=a*np.tanh(2*(x_sym-x)/width) + b\n try: # handle single value for x\n if x0.8 or x_well<0.2 or x_well>0.8:\n try:\n return np.ones(len(x))*1e200\n except TypeError:\n return 1e200\n #calculate parameters specific to inboard pedestal\n x_knee=x_sym+width/2\n c=dwell/(x_knee-x_well)**2\n # calculate function value:\n y=a*np.tanh(2*(x-x_sym)/width) + b\n try: # handle single value for x\n if x>x_knee:\n y+= slope*(x-x_knee) + c*(x-x_well)**2 - dwell\n except ValueError: # handle list or array for x\n for i in range(len(x)): \n if x[i]>x_knee:\n y[i]+= slope*(x[i]-x_knee) + c*(x[i]-x_well)**2 - dwell\n else:\n raise ValueError('loc must be \"in\" for inboard pedestal fit or \"out\" (default) for outboard pedestal fit.')\n return y\n\ndef diff_ped_tanh_odr2(p,x,loc='out'):\n '''Derivative of a modified tanh for fitting pedestal structures in \n density/temperature/pressure profiles in tokamak plasmas.\n p - list of parameters (len=7)\n x - xdata (usually major radius or normalized flux )\n loc = 'out'/'in' - defines whether outboard or inboard pedestal is to be fitted'''\n # extract function parameter from p\n a=p[0]\n #b=p[1] # not needed in derivative\n x_sym=p[2]\n width=p[3]\n slope=p[4]\n dwell=p[5]\n x_well=p[6]\n if loc=='out': # fit outboard pedestal \n x_knee=x_sym-width/2\n c=dwell/(x_knee-x_well)**2\n # calculate function value:\n y=-2*a/width/np.cosh(2*(x_sym-x)/width)**2\n try: # handle single value for x\n if xx_knee:\n y+= 2*c*(x-x_well) + slope\n except ValueError: # handle list or array for x\n for i in range(len(x)):\n if x[i]>x_knee:\n y[i]+= 2*c*(x[i]-x_well) + slope\n else:\n raise ValueError('loc must be \"in\" for inboard pedestal fit or \"out\" (default) for outboard pedestal fit.')\n return y\n\n#%% combine timbases of EFIT LCFS_R_out with timebase of TS - only used for animation\n# create new signal in 'data' called 'LCFS_R_out_TStb' which is EFIT info projected on TS timebase\n# similar for ruby TS but with inboard LCFS\nfor i in range(len(shotnos)):\n LCFS_R_out_i=[]\n for j in range(len(data[i]['NE']['time'])): #loop through TS timebase\n for k in range(len(data[i]['LCFS_R_out']['time'])): #loop through EFIT timebase and break when time gets larger than current timeslot in TS timebase\n if k!=0 and data[i]['LCFS_R_out']['time'][k]>=data[i]['NE']['time'][j]:\n break \n # weighted average of values around current TS time:\n LCFS_R_out_ij=(data[i]['LCFS_R_out']['data'][k]*(data[i]['LCFS_R_out']['time'][k]-data[i]['NE']['time'][j]) + data[i]['LCFS_R_out']['data'][k-1]*(data[i]['NE']['time'][j]-data[i]['LCFS_R_out']['time'][k-1])) / (data[i]['LCFS_R_out']['time'][k]-data[i]['LCFS_R_out']['time'][k-1])\n LCFS_R_out_i.append(LCFS_R_out_ij) \n #add new signal in TS timebase to data\n data[i]['LCFS_R_out_TStb']=dict(data=LCFS_R_out_i,time=data[i]['NE']['time'],errors=None,units=data[i]['LCFS_R_out']['units'])\n \n # Ruby TS time\n t_RTS=data[i]['NE12_R']['time'][0]\n for k in range(len(data[i]['LCFS_R_out']['time'])): #loop through EFIT timebase and break when time gets larger than current timeslot in TS timebase\n #assuming timebase of LCFS_R_out and LCFS_R_in is the same\n if k!=0 and data[i]['LCFS_R_out']['time'][k]>=t_RTS:\n break \n # weighted average of values around current TS time:\n LCFS_R_out_RTS=(data[i]['LCFS_R_out']['data'][k]*(data[i]['LCFS_R_out']['time'][k]-t_RTS) + data[i]['LCFS_R_out']['data'][k-1]*(t_RTS-data[i]['LCFS_R_out']['time'][k-1])) / (data[i]['LCFS_R_out']['time'][k]-data[i]['LCFS_R_out']['time'][k-1])\n LCFS_R_in_RTS=(data[i]['LCFS_R_in']['data'][k]*(data[i]['LCFS_R_in']['time'][k]-t_RTS) + data[i]['LCFS_R_in']['data'][k-1]*(t_RTS-data[i]['LCFS_R_in']['time'][k-1])) / (data[i]['LCFS_R_in']['time'][k]-data[i]['LCFS_R_in']['time'][k-1])\n #add new signals to data\n data[i]['LCFS_R_out_RTS']=dict(data=LCFS_R_out_RTS,time=data[i]['NE']['time'],errors=None,units=data[i]['LCFS_R_out']['units'])\n data[i]['LCFS_R_in_RTS']=dict(data=LCFS_R_in_RTS,time=data[i]['NE']['time'],errors=None,units=data[i]['LCFS_R_in']['units'])\n \n\n#%% fit modified tanh to pedestal in ne, Te and pe measured by the Ruby TS for all shots using odr\n\n# set limits for fitting in- and outboard\nxlims_out=[dict(NE=[1,1.45],\n TE=[1.2,1.45],\n PE=[1.2,1.45]) for shot in shotnos]\nxlims_in=[dict(NE=[0.2,0.6],\n TE=[0.2,0.6],\n PE=[0.2,0.6]) for shot in shotnos]\n\n#set initial guess of form p=[ a, b, x_sym, width, slope, dwell, x_well]\n#outboard pedestal\np0out=[dict(NE=[2.5e19,2.5e19,data[i]['LCFS_R_out_RTS']['data'],0.05,-1e19,1e19,1.1],\n TE=[1e2,1e2,data[i]['LCFS_R_out_RTS']['data'],0.05,-1e4,2.5e2,1.25],\n PE=[1e3,1e3,data[i]['LCFS_R_out_RTS']['data'],0.05,-1e5,1e3,1.25]) for i in range(len(shotnos))]\n#inboard pedestal\np0in=[dict(NE=[2e19,2e19,data[i]['LCFS_R_in_RTS']['data'],0.05,1e19,1e19,0.5],\n TE=[1e2,1e2,data[i]['LCFS_R_in_RTS']['data'],0.05,1e4,2.5e2,0.5],\n PE=[5e2,5e2,data[i]['LCFS_R_in_RTS']['data'],0.05,1e5,1e3,0.5]) for i in range(len(shotnos))]\n# empty lists for saving fit-results:\nne_R_p=[]\nTe_R_p=[]\npe_R_p=[]\nrubyshots=[]\n\nfor i,shot in enumerate(shotnos):\n if data[i]['NE12_R']['time'][0]>tLH[i] and data[i]['NE12_R']['time'][0] tlims[i][0]) & (data[i]['NE']['time'] < tlims[i][1]) )[0] for i in range(len(shotnos))] \nindHmode=[np.where((data[i]['NE']['time'] > tHmode[i][0]) & (data[i]['NE']['time'] < tHmode[i][1]) )[0] for i in range(len(shotnos))] # indices of data points INSIDE of H-mode\n\n# create new pedestal data with deleting 'nan' values from arrays, since they cannot be handled by fitting routines\npedestal_data=[{} for shot in shotnos]\nped_sigs=['NE','TE','PE']\nfor i in [14,15,16,17,18,19,20]: #only for 08NOV05 #range(len(shotnos)):\n for sig in ped_sigs:\n sig_data=[] # list for data\n sig_data_err=[] # list for errors on data\n sig_radii=[] # list for corresponding radii\n sig_radii_err=[] # list of errors on radii\n for j in range(len(ind[i])): # loop through time slots of L-H transition\n sigj=list(data[i][sig]['data'][ind[i][j]]) # density profile for time j\n sigj_err=list(data[i][sig]['errors'][ind[i][j]]) # errors of density profile for time j\n # only R_CTS is availabe for these shots (see comment in file description)\n Rj=list(data[i]['R_CTS']['data'][0]) # radii for time j\n Rj_err=list(data[i]['R_CTS']['errors'][0]) # error of radii for time j\n nan_indices=[]\n for n in range(len(sigj)): # find 'nan' values\n if math.isnan(sigj[n]):\n nan_indices.append(n)\n for k in range(len(nan_indices)): # delete 'nan' entries and corresponding positions in R\n del sigj[nan_indices[k]-k]\n del sigj_err[nan_indices[k]-k]\n del Rj[nan_indices[k]-k]\n del Rj_err[nan_indices[k]-k]\n \n if len(sigj)==0: # for the case that sigj is empty because all value were 'nan', create artificial dataset\n sigj=np.zeros(50) # set data to zero\n sigj_err=np.ones(50)*1e-3 # set error to 1e-3 (ODR cannot handle error 0) \n Rj=np.linspace(0.3,1.4) # linspace for typicall radii\n Rj_err=np.ones(50)*1e-3 # set error to 1e-3 (ODR cannot handle error 0)\n \n sig_data.append(sigj)\n sig_data_err.append(sigj_err)\n sig_radii.append(Rj)\n sig_radii_err.append(Rj_err)\n #create dictionary for data, radii, errors and time for this sig in this shot:\n sig_dict=dict(data=sig_data,data_errors=sig_data_err,radii=sig_radii,radii_errors=sig_radii_err,time=data[i][sig]['time'][ind[i]])\n pedestal_data[i][sig]=sig_dict\n #add plasma current I_p and toroidal magnetic field B_t:\n Ip_=np.mean(data[i]['IP']['data'][np.where((data[i]['IP']['time'] > tHmode[i][0]) & (data[i]['IP']['time'] < tHmode[i][1]) )[0]])\n Bt_=np.mean(data[i]['BT']['data'][np.where((data[i]['BT']['time'] > tHmode[i][0]) & (data[i]['BT']['time'] < tHmode[i][1]) )[0]])\n pedestal_data[i]['IP']=Ip_\n pedestal_data[i]['BT']=Bt_\n\n#%% fit modified tanh to profiles of time interval:\n\n# set initial guess with position of LCFS from EFIT minus about half a width as gues for x_sym\np0=[[dict(NE=[1e19,1e19,data[i]['LCFS_R_out_TStb']['data'][j]-0.01,0.02,-1e19,5e18,1.2],TE=[1e2,1e2,data[i]['LCFS_R_out_TStb']['data'][j]-0.03,0.03,-2.5e3,1e2,1.25],PE=[5e2,5e2,data[i]['LCFS_R_out_TStb']['data'][j]-0.02,0.02,-1e4,50,1.25]) for j in ind[i]] for i in range(len(shotnos))]\n\n#first coarse fit of most of profile to find initial guess for pedestal\nprofile_fits=[{} for shot in shotnos] # for storing fit results\nfor i in [14,15,16,17,18,19,20]: #only for 08NOV05 #[10]: #range(len(shotnos)):#\n for sig in ped_sigs:#['NE']:#\n sig_fits=[] # fit data for the current signal\n for j in range(len(ind[i])):\n sig_fit_data=[pedestal_data[i][sig]['radii'][j],pedestal_data[i][sig]['radii_errors'][j],pedestal_data[i][sig]['data'][j],pedestal_data[i][sig]['data_errors'][j]] # create data for fitting tool\n sig_fits.append(odr_complete(sig_fit_data,ped_tanh_odr2,diff_ped_tanh_odr2,p0[i][j][sig], xlimit=xlims_out[i][sig]\n ,plot=False))#,title='Helium experiment shot #%d \\n %s coarse profile odr fit, t=%.5f s' %(shotnos[i],sig,pedestal_data[i][sig]['time'][j]),xname='major radius [m]',yname='$n_e$ [$10^{19} m^{-3}$]'))\n #plt.axvline(data[i]['LCFS_R_out_TStb']['data'][j],c='0.5', lw=1, ls='--')\n profile_fits[i][sig]=sig_fits#\n\n#%% now fine fit with only pedestal region (selected with result from coarse fit)\n# select region to be fitted by [x_sym-2.5*width,x_sym+1.5*width]\n\nxlims_fine=[[dict(NE=[profile_fits[i]['NE'][j][0][2]-0.1,profile_fits[i]['NE'][j][0][2]+0.1],\n TE=[profile_fits[i]['TE'][j][0][2]-0.1,profile_fits[i]['TE'][j][0][2]+0.1],\n PE=[profile_fits[i]['PE'][j][0][2]-0.1,profile_fits[i]['PE'][j][0][2]+0.1]) \n for j in range(len(ind[i]))] for i in [14,15,16,17,18,19,20]] #only for 08NOV05 #]\n\n# take result from coarse fit as initial gues for fine fit\npedestal_fits=[{} for shot in shotnos] # for storing fit results\nfor i in [14,15,16,17,18,19,20]: #only for 08NOV05 #range(len(shotnos)):#[10]: #\n for sig in ped_sigs:#['NE']:#\n sig_fits=[] # fit data for the current signal\n for j in range(len(ind[i])):\n sig_fit_data=[pedestal_data[i][sig]['radii'][j],pedestal_data[i][sig]['radii_errors'][j],pedestal_data[i][sig]['data'][j],pedestal_data[i][sig]['data_errors'][j]] # create data for fitting tool\n sig_fits.append(odr_complete(sig_fit_data,ped_tanh_odr2,diff_ped_tanh_odr2,profile_fits[i][sig][j][0], xlimit=xlims_fine[i-14][j][sig]\n ,plot=False)) #,title='Helium experiment shot #%d \\n %s edge pedestal odr fit, t=%.3f s' %(shotnos[i],sig,pedestal_data[i][sig]['time'][j]),xname='major radius [m]',yname='$n_e$ [$10^{19} m^{-3}$]'))\n pedestal_fits[i][sig]=sig_fits#\n\n#%% Analyse pedestal fits\n \n# get pedestal L-H and H-L data (height and width)\n# seperate ante transitus (at) and post transitus (pt) #################### \nfor i in [14,15,16,17,18,19,20]: #only for 08NOV05 #range(len(shotnos)):\n for sig in ped_sigs:\n # find index rigth before transitions\n t=0\n # L-H transition:\n while pedestal_data[i][sig]['time'][t] < tLH[i]:\n indLHat = t\n t+=1\n #goodness of fit (residual variance)\n sig_LH_resvarat=pedestal_fits[i][sig][indLHat][2]\n sig_LH_resvarpt=pedestal_fits[i][sig][indLHat+1][2]\n # pedestal height (a(p[0]) + b(p[1]) in ped_tanh_odr2)\n sig_LH_phat=pedestal_fits[i][sig][indLHat][0][0] + pedestal_fits[i][sig][indLHat][0][1]\n sig_LH_ph_errat=np.sqrt(pedestal_fits[i][sig][indLHat][1][0]**2 + pedestal_fits[i][sig][indLHat][1][1]**2)\n sig_LH_phpt=pedestal_fits[i][sig][indLHat+1][0][0] + pedestal_fits[i][sig][indLHat+1][0][1]\n sig_LH_ph_errpt=np.sqrt(pedestal_fits[i][sig][indLHat+1][1][0]**2 + pedestal_fits[i][sig][indLHat+1][1][1]**2)\n # pedestal width (p[3] in ped_tanh_odr2)\n sig_LH_pwat=pedestal_fits[i][sig][indLHat][0][3]\n sig_LH_pw_errat=pedestal_fits[i][sig][indLHat][1][3]\n sig_LH_pwpt=pedestal_fits[i][sig][indLHat+1][0][3]\n sig_LH_pw_errpt=pedestal_fits[i][sig][indLHat+1][1][3]\n # write to LHdata / HLdata\n LHdata[i][sig+'_ped_heightat']=dict(data=sig_LH_phat,errors=sig_LH_ph_errat,units=data[i][sig]['units'],time=tLH[i],resvar=sig_LH_resvarat)\n LHdata[i][sig+'_ped_heightpt']=dict(data=sig_LH_phpt,errors=sig_LH_ph_errpt,units=data[i][sig]['units'],time=tLH[i],resvar=sig_LH_resvarpt)\n LHdata[i][sig+'_ped_widthat']=dict(data=sig_LH_pwat,errors=sig_LH_pw_errat,units=data[i]['R_CTS']['units'],time=tLH[i],resvar=sig_LH_resvarat)\n LHdata[i][sig+'_ped_widthpt']=dict(data=sig_LH_pwpt,errors=sig_LH_pw_errpt,units=data[i]['R_CTS']['units'],time=tLH[i],resvar=sig_LH_resvarpt)\n \n # H-L transition\n \n try:\n while pedestal_data[i][sig]['time'][t] < tHL[i]:\n indHLat = t\n t+=1\n #goodness of fit (residual variance)\n sig_HL_resvarat=pedestal_fits[i][sig][indHLat][2]\n sig_HL_resvarpt=pedestal_fits[i][sig][indHLat+1][2]\n # pedestal height (a(p[0]) + b(p[1]) in ped_tanh_odr2)\n sig_HL_phat=pedestal_fits[i][sig][indHLat][0][0] + pedestal_fits[i][sig][indHLat][0][1]\n sig_HL_ph_errat=np.sqrt(pedestal_fits[i][sig][indHLat][1][0]**2 + pedestal_fits[i][sig][indHLat][1][1]**2)\n sig_HL_phpt=pedestal_fits[i][sig][indHLat+1][0][0] + pedestal_fits[i][sig][indHLat+1][0][1]\n sig_HL_ph_errpt=np.sqrt(pedestal_fits[i][sig][indHLat+1][1][0]**2 + pedestal_fits[i][sig][indHLat+1][1][1]**2)\n # pedestal width (p[3] in ped_tanh_odr2)\n sig_HL_pwat=pedestal_fits[i][sig][indHLat][0][3]\n sig_HL_pw_errat=pedestal_fits[i][sig][indHLat][1][3]\n sig_HL_pwpt=pedestal_fits[i][sig][indHLat+1][0][3]\n sig_HL_pw_errpt=pedestal_fits[i][sig][indHLat+1][1][3]\n # write to LHdata / HLdata\n HLdata[i][sig+'_ped_heightat']=dict(data=sig_HL_phat,errors=sig_HL_ph_errat,units=data[i][sig]['units'],time=tHL[i],resvar=sig_HL_resvarat)\n HLdata[i][sig+'_ped_heightpt']=dict(data=sig_HL_phpt,errors=sig_HL_ph_errpt,units=data[i][sig]['units'],time=tHL[i],resvar=sig_HL_resvarpt)\n HLdata[i][sig+'_ped_widthat']=dict(data=sig_HL_pwat,errors=sig_HL_pw_errat,units=data[i]['R_CTS']['units'],time=tHL[i],resvar=sig_HL_resvarat)\n HLdata[i][sig+'_ped_widthpt']=dict(data=sig_HL_pwpt,errors=sig_HL_pw_errpt,units=data[i]['R_CTS']['units'],time=tHL[i],resvar=sig_HL_resvarpt)\n except IndexError:# when H-L transition is too late and there is no data anymore at that point\n # set data and errors to 'None' value\n HLdata[i][sig+'_ped_heightat']=dict(data=None,errors=None,units=data[i][sig]['units'],time=tHL[i],resvar=None)\n HLdata[i][sig+'_ped_heightpt']=dict(data=None,errors=None,units=data[i][sig]['units'],time=tHL[i],resvar=None)\n HLdata[i][sig+'_ped_widthat']=dict(data=None,errors=None,units=data[i]['R_CTS']['units'],time=tHL[i],resvar=None)\n HLdata[i][sig+'_ped_widthpt']=dict(data=None,errors=None,units=data[i]['R_CTS']['units'],time=tHL[i],resvar=None)\n\n#%% write data to file\nresults=[shotnos,tLH,tHL,data,rubyshots,ne_R_p,Te_R_p,pe_R_p,pedestal_data,pedestal_fits,LHdata,HLdata,xlims_fine]\n\nfilename='Xpoint_pedestal.p'\nfile=open(filename,\"wb\") # generate file\npickle.dump(results,file,pickle.HIGHEST_PROTOCOL) # pickle data and write to file\nfile.close()\n","sub_path":"Scripts/JPwork/Xpoint_shots_pedestals.py","file_name":"Xpoint_shots_pedestals.py","file_ext":"py","file_size_in_byte":22869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"424371984","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib\n\ndata = np.loadtxt('scores.txt', unpack='False')\n\nunique, counts = np.unique(data, return_counts=True)\ncounts = counts/len(data) * 100\ncount = dict(zip(unique, counts))\nprint(\"number of samples where activity score is not \\\"N/A\\\": \", len(data))\nprint(\"percentage of total samples (in percent): \" , count)\n\nbins = [0, 0.5, 1.0, 1.5, 2, 2.5]\n\nplt.hist(data, histtype='bar', bins = bins)\nplt.xlabel('CYP2D6 activity score')\nplt.ylabel('Amount of samples')\nplt.title('Distribution of activity scores')\nplt.legend()\nplt.show()\n","sub_path":"scores/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"633387343","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Examples for the NURBS-Python Package\n Released under MIT License\n Developed by Onur Rauf Bingol (c) 2016-2017\n\"\"\"\n\nfrom nurbs import Curve as ns\nfrom nurbs import utilities as utils\nfrom matplotlib import pyplot as plt\n\n# Create a NURBS curve instance\ncurve = ns.Curve()\n\n# Set up the NURBS curve\ncurve.read_ctrlpts(\"data/CP_Curve3.txt\")\ncurve.degree = 3\n# Auto-generate the knot vector\ncurve.knotvector = utils.knotvector_autogen(curve.degree, len(curve.ctrlpts))\n\n# Evaulate curve\ncurve.evaluate()\n\n# Arrange curve points for plotting\ncurvepts_x = []\ncurvepts_y = []\nfor pt in curve.curvepts:\n curvepts_x.append(pt[0])\n curvepts_y.append(pt[1])\n\n# Arrange tangents for plotting\nX = []\nY = []\nU = []\nV = []\n\n# Evaluate curve tangent at u = 0.0\ncurvetan = curve.tangent(0.0)\nnvec = utils.vector_normalize((curvetan[1][0], curvetan[1][1]))\n\n# Arrange tangent vector for plotting\nX.append(curvetan[0][0])\nY.append(curvetan[0][1])\nU.append(nvec[0])\nV.append(nvec[1])\n\n# Evaluate curve tangent at u = 0.2\ncurvetan = curve.tangent(0.2)\nnvec = utils.vector_normalize((curvetan[1][0], curvetan[1][1]))\n\n# Arrange tangent vector for plotting\nX.append(curvetan[0][0])\nY.append(curvetan[0][1])\nU.append(nvec[0])\nV.append(nvec[1])\n\n# Evaluate curve tangent at u = 0.5\ncurvetan = curve.tangent(0.5)\nnvec = utils.vector_normalize((curvetan[1][0], curvetan[1][1]))\n\n# Arrange tangent vector for plotting\nX.append(curvetan[0][0])\nY.append(curvetan[0][1])\nU.append(nvec[0])\nV.append(nvec[1])\n\n# Evaluate curve tangent at u = 0.6\ncurvetan = curve.tangent(0.6)\nnvec = utils.vector_normalize((curvetan[1][0], curvetan[1][1]))\n\n# Arrange tangent vector for plotting\nX.append(curvetan[0][0])\nY.append(curvetan[0][1])\nU.append(nvec[0])\nV.append(nvec[1])\n\n# Evaluate curve tangent at u = 0.8\ncurvetan = curve.tangent(0.8)\nnvec = utils.vector_normalize((curvetan[1][0], curvetan[1][1]))\n\n# Arrange tangent vector for plotting\nX.append(curvetan[0][0])\nY.append(curvetan[0][1])\nU.append(nvec[0])\nV.append(nvec[1])\n\n# Evaluate curve tangent at u = 1.0\ncurvetan = curve.tangent(1.0)\nnvec = utils.vector_normalize((curvetan[1][0], curvetan[1][1]))\n\n# Arrange tangent vector for plotting\nX.append(curvetan[0][0])\nY.append(curvetan[0][1])\nU.append(nvec[0])\nV.append(nvec[1])\n\n# Arrange control points for plotting\nctrlpts_x = []\nctrlpts_y = []\nfor pt in curve.ctrlpts:\n ctrlpts_x.append(pt[0])\n ctrlpts_y.append(pt[1])\n\n# Plot using Matplotlib\nplt.figure(figsize=(10.67, 8), dpi=96)\nyaxis = plt.plot((-1, 25), (0, 0), \"k-\") # y-axis line\ncppolygon, = plt.plot(ctrlpts_x, ctrlpts_y, \"k-.\") # control points polygon\ncurveplt, = plt.plot(curvepts_x, curvepts_y, \"g-\") # evaluated curve points\ntanline = plt.quiver(X, Y, U, V, color=\"blue\", angles='xy', scale_units='xy', scale=1, width=0.003) # tangents\ntanlinekey = plt.quiverkey(tanline, 23.75, -14.5, 1, \"Tangent Vectors\", coordinates='data', labelpos='W')\nplt.legend([cppolygon, curveplt], [\"Control Points Polygon\", \"Evaluated Curve\"])\nplt.axis([-1, 25, -15, 15])\nplt.show()\n\nprint(\"End of NURBS-Python Example\")\n","sub_path":"ex_curve03.py","file_name":"ex_curve03.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"336400139","text":"#! /usr/bin/env python\n#\n# Load up an SPM MEEG dataset [.mat] and project trial data onto mesh\n#\n# AS2016\n\n\n#import matplotlib\n#matplotlib.use('GTKAgg')\n\nimport scipy.io as sio\nimport numpy as np\nfrom numpy import *\nimport mpl_toolkits.mplot3d.axes3d as p3\nimport pylab as p\nimport sys\nfrom matplotlib.colors import LightSource\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport matplotlib.cm as cm\nfrom mpl_toolkits.mplot3d import Axes3D\n\nwoi = [.1 ,.3] # time window of interest\nti = 0 # trial index (minus 1, so t1==0)\n\n# Input datasets\n#-----------------------\ninp = sys.argv[1:]\n\nif len(inp) > 3:\n\tti = inp[0]\n\twoi[0] = inp[1]\n\twoi[1] = inp[2]\n\tfiles = inp[3:]\nelif len(inp) > 1:\n\tti = inp[0]\n\tfiles = inp[1:]\nelif len(inp) == 1:\n\tfiles = inp[0]\n\nD = sio.loadmat(files,squeeze_me=True,struct_as_record=False)\n\n\n#for n, i in enumerate(x): #[could loop datasets]\t\n\n#D = sio.loadmat('bawinica_efspmeeg_rov_trans_meg14_0473_1',squeeze_me=True,struct_as_record=False)\nI = D['D'].other.inv\n\n# Structue [mesh & faces]\n#-----------------------\nfwd = I.forward\ninv = I.inverse\n\nface = fwd[0].mesh.face\nvert = fwd[0].mesh.vert\n\nx = vert[:,0]\ny = vert[:,1]\nz = vert[:,2]\n\n# Inverse parameters\n#-----------------------\nJ = inv.J # Trial average MAP estimate\nT = inv.T # temporal projector\nU = inv.U # spatial projector[s]\nIs = inv.Is # Indices of ARD vertices\nIc = inv.Ic # Indices of channels\nIt = inv.It # Indices of time bins\npst = inv.pst # peristimulus time (ms)\nNd = inv.Nd # number of mesh dipoles\n\nNb = T.shape[1] # number of time bins\nNc = U.shape[0] # number of channels\nNw = 1 # number of contrast windows\nNj = len(J) # number of conditions\n\n\n# Time indices\nfwhm = np.max(np.diff(woi))\nt = np.exp(-4*np.log(2)*np.square((pst-np.mean(woi))) / (np.square(fwhm)))\n#t = exp(-4*log(2)*(pst(:) - mean(woi)).^2/(fwhm^2));\nt = t/t.sum()\n\n# no foi\nt = np.array(t)\nW = t.T\n\n# calculate temporal projector\nTW = np.inner(T.T,W)\nTTW = np.inner(T,TW)\n\nqV = inv.qV\nqC = inv.qC\n\n# MAP projector\nqC = qC*np.trace(TTW.T*qV*TTW)\n#qC = max(qC,0);\n\nCList = inv.trials\ntrial = CList\n\n# Get per trial data\n#--------------------------\nJW = [0 for x in range(Nj)]\nfor n, i in enumerate(J):\n\t#iw = (w - 1)*Nj + (n+1)\n\t#CW[n] = W\n\tJJ = J[n]\n\ttmp = JJ*TW #(:,1)\n\tJW[n] = tmp.T\n\t\n\n\t\n# which trial to project:\n#--------------------------\nPr = JW[ti]\n\n\n## visvis approach\n#import visvis as vv\n#\n#ax = vv.gca\n#ms = vv.Mesh(ax,vert,face)\n#ms.SetValues(Pr)\n#axes.Draw()\n\n# mplot3d approach\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\n\nfig = plt.figure()\nax = Axes3D(fig)\n\nverts = list(zip(x, y, z))\ncollection = Poly3DCollection([verts],facecolors='w', linewidths=0, alpha=0.5)\n\ncollection.set_verts_and_codes([verts], Pr/Pr.max())\nax.add_collection3d(collection)\nplt.show()\n\n\n\n\n#collection = Poly3DCollection(poly3d, linewidths=1, alpha=0.2)\n#face_color = [0.5, 0.5, 1] # alternative: matplotlib.colors.rgb2hex([0.5, 0.5, 1])\n#collection.set_facecolor(face_color)\n\n#ax = plt.gca(projection='3d')\n#ax.plot_surface(x, y, z, rstride=2, cstride=2,\n# facecolors=Pr)\n#plt.show()\n\n","sub_path":"PyMesh.py","file_name":"PyMesh.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"17277991","text":"from flask import Flask, request, render_template, redirect\nimport pyrebase\n\nconfig = {\n \"apiKey\": \"AIzaSyAepXDhquMDUJgKGPqC9Ljsq6FrwQPu1xs\",\n \"authDomain\": \"pico-be4e4.firebaseapp.com\",\n \"databaseURL\": \"https://pico-be4e4.firebaseio.com/\",\n \"storageBucket\": \"pico-be4e4.appspot.com\",\n \"serviceAccount\": \"pico-be4e4-firebase-adminsdk-3plpk-566f14f751.json\"\n}\n\nfirebase = pyrebase.initialize_app(config)\n\ndb = firebase.database();\n\napp = Flask(__name__, static_folder='static', static_url_path='') # Initialize Flask and serve static folder\n\n@app.route(\"/\")\ndef root():\n # Serve index.html upon request\n return app.send_static_file('index.html')\n\n@app.route(\"/profile\", methods = [\"POST\", \"GET\"])\ndef profile():\n if request.method == \"POST\":\n email = request.form[\"email\"]\n #securityCode = request.form[\"securityCode\"]\n users = db.child(\"users\").get()\n user = None\n for k, v in users.val().items():\n #print(v)\n if v[\"email\"] == email:\n user = v\n name = user[\"firstName\"]\n bio = user[\"description\"]\n image = user[\"profileURL\"]\n if image == \"\":\n image = \"default.jpeg\"\n social_media = user[\"accounts\"]\n return render_template(\"profile.html\", name=name, bio=bio, image=image, social_media = social_media)\n if request.method == \"GET\":\n return redirect(\"/\")\n\n\n# Start app\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"639514955","text":"\"\"\"\nTest conda commandline wrappers\n\"\"\"\nfrom tljh import conda\nimport os\nimport pytest\nimport subprocess\nimport tempfile\n\n\n@pytest.fixture(scope=\"module\")\ndef prefix():\n \"\"\"\n Provide a temporary directory with a mambaforge conda environment\n \"\"\"\n # see https://github.com/conda-forge/miniforge/releases\n mambaforge_version = \"4.10.3-7\"\n if os.uname().machine == \"aarch64\":\n installer_sha256 = (\n \"ac95f137b287b3408e4f67f07a284357b1119ee157373b788b34e770ef2392b2\"\n )\n elif os.uname().machine == \"x86_64\":\n installer_sha256 = (\n \"fc872522ec427fcab10167a93e802efaf251024b58cc27b084b915a9a73c4474\"\n )\n installer_url = \"https://github.com/conda-forge/miniforge/releases/download/{v}/Mambaforge-{v}-Linux-{arch}.sh\".format(\n v=mambaforge_version, arch=os.uname().machine\n )\n with tempfile.TemporaryDirectory() as tmpdir:\n with conda.download_miniconda_installer(\n installer_url, installer_sha256\n ) as installer_path:\n conda.install_miniconda(installer_path, tmpdir)\n conda.ensure_conda_packages(tmpdir, [\"conda==4.10.3\"])\n yield tmpdir\n\n\ndef test_ensure_packages(prefix):\n \"\"\"\n Test installing packages in conda environment\n \"\"\"\n conda.ensure_conda_packages(prefix, [\"numpy\"])\n # Throws an error if this fails\n subprocess.check_call([os.path.join(prefix, \"bin\", \"python\"), \"-c\", \"import numpy\"])\n\n\ndef test_ensure_pip_packages(prefix):\n \"\"\"\n Test installing pip packages in conda environment\n \"\"\"\n conda.ensure_conda_packages(prefix, [\"pip\"])\n conda.ensure_pip_packages(prefix, [\"numpy\"])\n # Throws an error if this fails\n subprocess.check_call([os.path.join(prefix, \"bin\", \"python\"), \"-c\", \"import numpy\"])\n\n\ndef test_ensure_pip_requirements(prefix):\n \"\"\"\n Test installing pip packages with requirements.txt in conda environment\n \"\"\"\n conda.ensure_conda_packages(prefix, [\"pip\"])\n with tempfile.NamedTemporaryFile() as f:\n # Sample small package to test\n f.write(b\"there\")\n f.flush()\n conda.ensure_pip_requirements(prefix, f.name)\n subprocess.check_call([os.path.join(prefix, \"bin\", \"python\"), \"-c\", \"import there\"])\n","sub_path":"tests/test_conda.py","file_name":"test_conda.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"17901610","text":"import sys\n\ninput = sys.stdin.readline\n\ndef find(parent, vertex):\n while parent[vertex] != vertex:\n vertex = parent[vertex]\n\n return vertex\n\ndef union(parent, vertex1, vertex2):\n if vertex1 > vertex2:\n parent[vertex2] = vertex1\n else :\n parent[vertex1] = vertex2\n\ndef solution(num_vertex, num_edge, edges):\n edges.sort(key=lambda e: e[2])\n\n parent = list(range(num_vertex + 1))\n\n count = 0; weight = 0\n for e in edges:\n parent1 = find(parent, e[0])\n parent2 = find(parent, e[1])\n\n if parent1 != parent2:\n count += 1\n union(parent, parent1, parent2)\n\n weight += e[2]\n\n if count == num_vertex - 1: break\n\n return weight\n\nV, E = map(int, input().split())\nedges = []\nfor _ in range(E):\n edges.append(tuple(map(int, input().split())))\n\nprint(solution(V, E, edges))","sub_path":"1~10000/1197/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"497287688","text":"import numpy as np\nimport scipy.constants as const\n\nfrom . import log\n\n\ndef calc_ranges(range_lengths, sample_pitches=[], center_offsets=[]):\n \"\"\"\n calc_ranges(range_lengths, sample_pitches, center_offsets)\n\n returns uniformly spaced ranges of length range_lengths(idx) with a elements spaced by\n sample_pitches(idx) and centered on center_offsets(idx). The center element\n is defined as the one in the center for an odd number of elements and the\n next one for an even number of elements. If a scalar is specified as sample pitch, it is used for all ranges. The\n default sample const.pitch is 1. If a scalar is specified as center_offsets, it is used for the first dimension\n and 0 is used for higher dimensions. The default center offset is 0.\n\n :param range_lengths: A list of the number of elements per dimension.\n :param sample_pitches: The distance between sample points (the dimensions of the n-D voxel). Default: all 1.\n :param center_offsets: Optional offset of the central voxel. The central voxel is the one with equal number of\n voxel at either side in every dimension. If the number of voxels is even, it is the voxel that has one voxel\n more preceeding it than after it.\n :return: a tuple of ranges, one for each range_length.\n If range_lengths is scalar, a single range is returned, not a tuple of a range.\n\n Example:\n\n xRange = calc_ranges(128, 1e-6)\n xRange, yRange = calc_ranges(np.array([128, 128]), np.array([1, 1])*1e-6)\n\n \"\"\"\n is_single_range = np.isscalar(range_lengths)\n # Make sure the vectors are of the same length\n nb_dims = np.max((np.array(range_lengths).size, np.array(sample_pitches).size, np.array(center_offsets).size))\n\n range_lengths = pad_to_length(range_lengths, nb_dims, 1)\n sample_pitches = extend_to_length(sample_pitches, nb_dims)\n center_offsets = pad_to_length(center_offsets, nb_dims, 0)\n\n ranges = [co + sp * (np.arange(0, rl) - np.floor(rl / 2)) for co, sp, rl in\n zip(center_offsets, np.array(sample_pitches), range_lengths)]\n\n if is_single_range:\n return ranges[0]\n else:\n return ranges\n\n\ndef calc_frequency_ranges(*ranges, centered=False):\n \"\"\"\n Determine equivalent frequency ranges for given time ranges.\n The results are ifftshifted so that the zero frequency is in the first\n vector position, unless centered=True.\n This function always returns a tuple\n\n Example usage:\n (xf_range) = calc_frequency_ranges(x_range) # or\n xf_range = calc_frequency_ranges(x_range)[0]\n xf_range, yf_range = calc_frequency_ranges(x_range, y_range)\n xf_range, yf_range = calc_frequency_ranges(x_range, y_range, centered=True)\n\n :param ranges: one or more (spatial) time range vectors\n :param centered: Boolean indicating whether the resulting ranges should have the zero at the center.\n Default False.\n :return: A tuple with one or more (spatial) frequency range vectors\n \"\"\"\n f_ranges = []\n for rng in ranges:\n rng = np.array(rng) # convert python range to numpy range\n nb = len(rng)\n if nb > 1:\n dt = np.array(rng[-1] - rng[0]) / (nb - 1)\n f_range = (np.arange(0, nb) - np.floor(nb / 2)) / (nb * dt)\n else:\n f_range = 0.0 * rng\n\n if not centered:\n f_range = np.fft.ifftshift(f_range)\n\n f_ranges.append(f_range)\n\n return f_ranges\n\n\ndef to_dim(x, n, axis=0):\n \"\"\"\n Adds singleton dimensions to a 1D vector up to dimension n and orients the vector in dimension axis (default 0)\n\n :param x: the input vector\n :param n: the number of desired dimensions\n :param axis: the target axis (default: 0)\n\n :return: a n-dimensional array with all-but-one singleton dimension\n \"\"\"\n x = np.array(x, copy=True)\n indexes = [1]*n\n if x.ndim > 0:\n indexes[axis] = x.shape[0]\n return x.reshape(indexes)\n\n\ndef add_dims(arr, n, total):\n \"\"\"\n Adds n singleton dimension to the right and completes the number of dimensions at the left to makes sure that the\n total number of dimensions equals 'total'.\n\n :param arr: The input array.\n :param n: The number of dimensions to add at the right.\n :param total: The total number of dimensions required.\n\n :return: The reshaped array.\n \"\"\"\n for idx in range(n):\n arr = [arr]\n arr = np.array(arr)\n\n def add_trailing_dims(arr, n):\n \"\"\"\n Adds n singleton dimension to the left\n\n :param arr: The input array.\n :param n: The number of dimensions to add to the left.\n\n :return: The reshaped array.\n \"\"\"\n arr = np.array(arr)\n for idx in range(n):\n arr = np.expand_dims(arr, -1)\n\n return arr\n\n arr = add_trailing_dims(arr, total - arr.ndim)\n\n return arr\n\n\ndef pad_to_length(vec, length, padding_value=0):\n \"\"\"\n Pads a vector on the right-hand side to a given length.\n\n :param vec: The to-be-padded vector. This can be a numpy.ndarray, a range, a list, or a scalar.\n :param length: The length of the to-be-returned vector.\n :param padding_value: The numeric padding value (default: 0).\n\n :return: The padded vector of length 'length' as a numpy ndarray.\n \"\"\"\n values = np.array(vec).flatten()\n\n return np.pad(values, (0, length - values.size), 'constant', constant_values=padding_value)\n\n\ndef extend_to_length(vec, length):\n \"\"\"\n Extends a vector on the right-hand side to a given length using its final value.\n\n :param vec: The to-be-extended vector. This can be a numpy.ndarray, a range, a list, or a scalar.\n :param length: The length of the to-be-returned vector.\n\n :return: The extended vector with length 'length' as a numpy ndarray.\n \"\"\"\n values = np.array(vec).flatten()\n\n return np.pad(values, (0, length - values.size), 'edge')\n\n\ndef complex2rgb(complex_image, normalization=None, inverted=False):\n \"\"\"\n Converts a complex image to a RGB image.\n\n :param complex_image: A 2D array\n :param normalization: An optional scalar to indicate the target magnitude of the maximum value (1.0 is saturation).\n :param inverted: By default 0 is shown as black and amplitudes of 1 as the brightest hues.\n When inverted is True, zeros are shown as white and amplitudes of 1 are shown as black.\n :return: Returns a 3D array representing the red, green, and blue channels of a displayable image.\n \"\"\"\n amp = np.abs(complex_image)\n ph = np.angle(complex_image)\n\n if normalization is not None:\n if normalization is True:\n normalization = 1.0\n if normalization > 0:\n max_value = np.max(amp)\n if max_value > 0:\n amp *= (normalization / max_value)\n else:\n log.warning('Negative normalization factor %d ignored.', normalization)\n\n hue = ph / (2 * const.pi) + 0.5\n if not inverted:\n hsv = np.concatenate(\n (hue[:, :, np.newaxis], np.ones((*hue.shape, 1)), np.minimum(1.0, amp[:, :, np.newaxis])), axis=2)\n else:\n hsv = np.concatenate((hue[:, :, np.newaxis],\n np.minimum(1.0, amp[:, :, np.newaxis]),\n np.maximum(0.0, 1.0 - 0.5 * amp[:, :, np.newaxis])), axis=2)\n\n return hsv2rgb(hsv) # Convert HSV to an RGB image\n\n\ndef hsv2rgb(hsv):\n \"\"\"\n Converts a hue, saturation, and values to an RGB image.\n\n :param hsv: A 3D array with hue, saturation, and values per pixel of a 2D image.\n\n :return: Returns a 3D array representing the red, green, and blue channels of a displayable image.\n \"\"\"\n # Convert hsv to an RGB image\n hue = hsv[:, :, 0]\n sat = hsv[:, :, 1]\n val = hsv[:, :, 2]\n\n hue = 6.0 * hue\n I = np.array(hue, dtype=np.int8)\n F = hue - I\n P = val * (1.0 - sat)\n Q = val * (1.0 - sat * F)\n T = val * (1.0 - (sat * (1.0 - F)))\n\n I %= 6\n red = ((I == 0) | (I == 5)) * val + (I == 1) * Q + ((I == 2) | (I == 3)) * P + (I == 4) * T\n green = (I == 0) * T + ((I == 1) | (I == 2)) * val + (I == 3) * Q + (I >= 4) * P\n blue = (I <= 1) * P + (I == 2) * T + ((I == 3) | (I == 4)) * val + (I == 5) * Q\n rgb = np.concatenate((red[:, :, np.newaxis], green[:, :, np.newaxis], blue[:, :, np.newaxis]), axis=2)\n\n return rgb\n\n\ndef ranges2extent(*ranges):\n \"\"\"\n Utility function to determine extent values for imshow from the ranges of positions at which the pixels are\n specified. The extents are half a pixel larger at each end of the range, for each range.\n\n :param ranges: Monotonically increasing ranges, one per dimension: first vertical, next horizontal.\n Each range may be a numpy.array or a Python range.\n\n :return: An iterable with the extents of each dimension as 4 numerical values: [left, right, bottom, top]\n (assuming origin='lower' on imshow)\n \"\"\"\n extent = []\n for idx, rng in enumerate(ranges[::-1]):\n step = rng[1] - rng[0]\n first, last = rng[0] - 0.5 * step, rng[-1] + 0.5 * step\n if idx == 1:\n first, last = last, first\n extent.append(first)\n extent.append(last)\n\n return np.array(extent)\n\n\ndef word_align(input_array, word_length=32):\n \"\"\"\n Returns a new array thay is byte-aligned to words of length word_length.\n This may be required for libraries such as pyfftw\n\n :param input_array: The input array to align.\n :param word_length: The word length to align to. This must be an integer multiple of the dtype size.\n\n :return: A word-aligned array with the same contents and shape as input_array.\n \"\"\"\n if (input_array.ctypes.data % word_length) == 0:\n aligned_array = input_array\n else:\n extra = int(np.ceil(word_length / input_array.itemsize))\n buffer = np.empty(input_array.size + extra, dtype=input_array.dtype)\n offset = int((-buffer.ctypes.data % word_length) / input_array.itemsize)\n aligned_array = buffer[offset:(offset + input_array.size)].reshape(input_array.shape)\n np.copyto(aligned_array, input_array)\n\n assert (aligned_array.ctypes.data % word_length) == 0\n\n return aligned_array\n\n","sub_path":"python/macromax/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"114952211","text":"import random\r\n\r\nqueAndAns = {\r\n \"the Great Wall of China\":\"China\",\r\n \"the Taj Mahal\":\"India\",\r\n \"the Eiffel Tower\":\"France\",\r\n \"Niagara Falls\":\"Canada\",\r\n \"Patong Beach\":\"Thailand\",\r\n \"Christ the Redeemer, Rio de Janeiro\":\"Brazil\",\r\n \"Old Havana\":\"Cuba\",\r\n \"Burj Khalifa\":\"United Arab Emirates\",\r\n \"the Great Sphinx\":\"Egypt\",\r\n \"Mount Fuji\":\"Japan\",\r\n \"Buckingham Palace\":\"United Kingdom\",\r\n \"Sydney Opera House\":\"Australia\",\r\n \"the Parthenon\":\"Greece\",\r\n \"Salar de Uyuni salt flat\":\"Bolivia\",\r\n \"La Sagrada Família\":\"Spain\",\r\n \"Blue Lagoon\" : \"Iceland\",\r\n \"La Boca, Buenos Aires\":\"Argentina\",\r\n \"Chichen-Itza\":\"Mexico\",\r\n \"Hobbiton\":\"New Zealand\",\r\n \"Dubrovnik Old Town\":\"Croatia\"\r\n}\r\n\r\n\r\n\r\nfor i in range(1,11):\r\n c = 1\r\n que = list(queAndAns.keys())\r\n pname = \"Quiz \"+str(i)+\".txt\"\r\n aname = \"ans \"+str(i)+\".txt\"\r\n q = open(pname,\"w\")\r\n a = open(aname,'w')\r\n random.shuffle(que)\r\n for j in que:\r\n q.write(\"where is \"+j+\" located?\\n\")\r\n ans = list(queAndAns.values())\r\n op = [queAndAns[j]]\r\n ans.remove(queAndAns[j])\r\n op.append(random.choice(ans))\r\n op.append(random.choice(ans))\r\n op.append(random.choice(ans))\r\n random.shuffle(op)\r\n q.write(\"1.\"+op[0]+\"\\n2.\"+op[1]+\"\\n3.\"+op[2]+\"\\n4.\"+op[3]+\"\\n\\n\")\r\n a.write(str(c)+\". \" +queAndAns[j]+\"\\n\")\r\n c+=1\r\n\r\n \r\n \r\n \r\n\r\n\r\n","sub_path":"q4.py","file_name":"q4.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"122914651","text":"# --------------------------------------------------------------------#\n# Run Model\n# --------------------------------------------------------------------#\n\nfrom case_def import *\nfrom z_val import *\nfrom scores import *\nfrom db_scan import *\nfrom i_forest import *\nfrom arima import *\n\nimport os\nimport pandas as pd\n\nprint('Starting ...')\n\ncwd = os.getcwd()\n\nalgo_dict = {1: 'Z Value', 2: 'DB Scan', 3: 'Isolation Forest', 4: 'ARIMA'}\n\ndef run_model(case_type, sub_path):\n '''Run the model'''\n\n case_dict = CaseDefinition(case_type, cwd, sub_path, algo_dict).case_file\n\n all_results = get_run_algos(case_dict)\n all_results_df = pd.DataFrame(all_results)\n print(all_results)\n # make result\n print('Done ... OK')\n # print(f'Please collect results from {case_dict.meta.res_file_dir}')\n\n\n\ndef get_run_algos(case_dict):\n '''Get and run algorithms'''\n result = {}\n if len(case_dict.meta.algorithms_selected) > 1:\n for i in case_dict.meta.algorithms_selected:\n print(f'Now running {i} ...')\n res = switch_algorithms(case_dict, i)\n result.update({i: res})\n else:\n algo = case_dict.meta.algorithms_selected[0]\n print(f'Now running {algo} ...')\n res = switch_algorithms(case_dict, algo)\n result.update({algo: res})\n\n return result\n\n\ndef switch_algorithms(case, case_type):\n '''Define switcher for algorithms to get right function'''\n if case_type == 'Z Value':\n run = get_z_outliers(case, case_type)\n elif case_type == 'DB Scan':\n run = get_db_scan_outliers(case, case_type)\n elif case_type == 'Isolation Forest':\n run = get_isolation_forest_outliers(case, case_type)\n elif case_type == 'ARIMA':\n run = Arima(case, case_type)\n\n return run","sub_path":"code/run_mod.py","file_name":"run_mod.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"6404653","text":"\r\n# standard library imports\r\nimport os\r\n\r\n# 3rd party imports\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n# uraeus imports\r\nfrom uraeus.nmbd.python import (import_source, multibody_system, \r\n simulation, configuration)\r\n\r\n# ================================================================== #\r\n# Helpers\r\n# ================================================================== #\r\n\r\n# getting to the root project directory from this file directory\r\ndir_name = os.path.dirname(__file__)\r\n\r\n# creating the various needed directories references\r\nproject_dir = os.path.abspath(os.path.join(dir_name, '../../'))\r\nsymdata_dir = os.path.join(project_dir, 'symenv/data/')\r\nnumdata_dir = os.path.join(project_dir, 'numenv/python/src/')\r\nresults_dir = os.path.join(project_dir, 'simenv/results/')\r\n\r\n# ================================================================== #\r\n# Initializations\r\n# ================================================================== #\r\n\r\nmodel_name = 'pendulum'\r\n\r\n# getting the configuration .json file\r\nconfig_file = os.path.join(symdata_dir, 'pendulum_cfg.json')\r\n\r\n# Creating a numerical configuration instance\r\nnum_config = configuration('base')\r\n# constructing the numerical configuration instance from\r\n# imported JSON file\r\nnum_config.construct_from_json(config_file)\r\n\r\n# Getting the numrical topology module\r\nmodel = import_source(numdata_dir, model_name)\r\n\r\n# Creating the numerical model from the imported module\r\nnum_model = multibody_system(model)\r\n# Assigning this configuration instance to the numerical model\r\nnum_model.topology.config = num_config\r\n\r\n# ================================================================== #\r\n# Numerical Configuration of the System\r\n# ================================================================== #\r\n\r\nnum_config.hps_p1.flat[:] = 0, 0, 0\r\nnum_config.hps_p2.flat[:] = 0, 200, 0\r\nnum_config.vcs_v.flat[:] = 1, 0, 0\r\n\r\nnum_config.s_radius = 20\r\n\r\n# Assembling the configuration and exporting a .json file that\r\n# holds these numerical values\r\nnum_config.assemble()\r\nnum_config.export_json()\r\n\r\n# ================================================================== #\r\n# Creating the Simulation Instance\r\n# ================================================================== #\r\nsim = simulation('sim', num_model, 'dds')\r\n\r\n# setting the simulation time grid\r\nsim.set_time_array(20, 5e-3)\r\n\r\n# Starting the simulation\r\nsim.solve()\r\n\r\n# Saving the results in the /results directory as csv and npz\r\nsim.save_as_csv(results_dir, 'test_1')\r\nsim.save_as_npz(results_dir, 'test_1')\r\n\r\n# ================================================================== #\r\n# Plotting the Simulation Results\r\n# ================================================================== #\r\n\r\nsim.soln.pos_dataframe.plot(x='time', y=['rbs_body.z', 'rbs_body.y'], grid=True, figsize=(10,4))\r\nsim.soln.vel_dataframe.plot(x='time', y='rbs_body.z', grid=True, figsize=(10,4))\r\nsim.soln.acc_dataframe.plot(x='time', y='rbs_body.z', grid=True, figsize=(10,4))\r\n\r\nplt.show()","sub_path":"standalone_models/pendulum/simenv/python/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"173040211","text":"#Tools for compilation and execution\nfrom vscript.errors import generic, python, internal_error\nfrom vscript.engine import vcompile, vexecute\nimport sys, time\n\nVScriptExecutionError \t= VScriptComlipationError \t= generic\nPythonExecutionError \t= PythonCompilationError \t= python\nVScriptInternalError = internal_error\n\n\ndef safe_execute( routine, timeout, *arguments, **keywords ):\n\t__trace = sys.gettrace()\n\tget_time, deadline = time.time, time.time() + timeout\n\n\tdef trace( frame, event, arguments ):\n\t\tif get_time() > deadline:\n\t\t\traise VScriptExecutionError(\"Execution timeout\")\n\t\treturn trace\n\n\ttry:\n\t\tif not __trace:\n\t\t\tsys.settrace(trace)\n\t\treturn routine(*arguments, **keywords)\n\tfinally:\n\t\tif not __trace:\n\t\t\tsys.settrace( None )\n\n\n\nclass StopExecutionError( python ):\n\tpass\n\n\ndef compile( source_code, environment = None, silent = False, context = None ):\n\ttry:\n\t\treturn vcompile(source_code, anyway = silent, environment = environment)\n\texcept VScriptComlipationError:\n\t\traise\n\texcept PythonCompilationError:\n\t\traise\n\n\nTIME_OUT = 300 #5 minutes\ndef execute( byte_code, source_code, environment = None, safe = True ):\n\ttry:\n\t\tif not safe:\n\t\t\tvexecute( byte_code, source_code, environment = environment )\n\t\telse:\n\t\t\tsafe_execute( vexecute, TIME_OUT, byte_code, source_code, environment = environment )\n\texcept VScriptExecutionError:\n\t\traise\n\texcept PythonExecutionError:\n\t\traise\n\n\ndef register_lib(name, cache, debuginfo, environment, context):\n\tserver.vscript.libraries.register(name, cache, debuginfo, environment=environment, context=context)\n\n\ndef unregister_lib(name, context):\n\ttry:\n\t\tserver.vscript.libraries.unregister(name, context=context)\n\texcept KeyError:\n\t\tpass\n","sub_path":"Libraries/VEE_tools.py","file_name":"VEE_tools.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115588486","text":"from django.conf.urls import url\r\nfrom django.contrib.auth.forms import UserCreationForm\r\nfrom django.views.generic import CreateView\r\n\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n url(r'^$', views.profile_main, name='main'),\r\n url(r'accounts/profile', views.profile_main, name='account'),\r\n url(r'^(?P\\d+)$', views.profile_other, name='other'),\r\n url(r'^editprofile', views.profile_edit, name='edit'),\r\n url('^register/', CreateView.as_view(\r\n template_name='profiles/profile_register.html',\r\n form_class=UserCreationForm,\r\n success_url='/'\r\n )),\r\n]","sub_path":"profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"474278428","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nimport time\nimport os\n\nexecutable_path =r'C:\\Users\\ASUS\\Desktop\\pp\\tpc\\Console\\chromedriver.exe'\n\n\ntry:\n os.makedirs('wiki')\nexcept OSError as e:\n print(\"folder exists\")\ndef Loader(driver):\n while True:\n try:\n print(\"waiting for load\")\n myElem = WebDriverWait(driver, 1).until_not(EC.presence_of_element_located((By.XPATH,\"//img[@src='https://www.wiki.tn/img/loader.gif']\")))\n except TimeoutException:\n print(\"loaded\")\n break\n time.sleep(2)\ndef clicker(driver,c):\n while True:\n try:\n link= driver.find_element_by_link_text(str(c))\n link.click()\n except:\n print(\"couldn't click\")\n else:\n break\ndef file_writer(driver,file_name):\n main = driver.find_element_by_id(\"product_list\")\n titles = main.find_elements_by_xpath(\"//a[@class='product-name']\")\n prices= main.find_elements_by_xpath(\"//span[@itemprop='price']\")\n i=0\n j=0\n\n for title in titles:\n\n\n i=i+1\n try:\n f = open(file_name, \"a\")\n\n\n f.write(title.get_attribute(\"title\")+\"\\n\"+title.get_attribute(\"href\")+\"\\n\")\n print(title.get_attribute(\"title\"))\n f.close()\n except:\n print(\"error typing\")\n for price in prices:\n j=j+1\n if (i==j):\n try:\n f = open(file_name, \"a\")\n f.write(price.text+\"\\n\")\n\n f.close()\n except:\n print(\"error typing\")\n j=0\n break\ndef wiki_composants():\n driver= webdriver.Chrome(executable_path)\n driver.get(\"https://www.wiki.tn/c/telephonie-tablette-15.html\")\n print(\"Wiki \\n Composants:\\n\")\n file_name=\"wiki\\composants.txt\"\n b=35\n\n for c in range(2,b):\n print(\"page:\" ,c-1)\n Loader(driver)\n file_writer(driver,file_name)\n if (c 1e-2])\n\n# rescale data for track 2\ndatas_idx = []\nif track_id == 2:\n if y_id == 0:\n for i in range(train_x.shape[0]):\n v = int(1 / train_y[i] // 5 + 1)\n for _ in range(v):\n datas_idx.append(i)\n elif y_id == 1:\n for i in range(train_x.shape[0]):\n v = int(1 / train_y[i] * 100 + 1)\n for _ in range(v):\n datas_idx.append(i)\n else:\n for i in range(train_x.shape[0]):\n v = int(1 / train_y[i] + 1)\n for _ in range(v):\n datas_idx.append(i)\nelse:\n for i in range(train_x.shape[0]):\n datas_idx.append(i)\ndatas_idx = np.array(datas_idx)\n\nprint(f'features_idx shape {features_idx.shape}')\nprint(f'datas_idx shape {datas_idx.shape}')\n\n# modify train_x, train_y\ntrain_x = train_x[datas_idx][:, features_idx]\ntrain_y = train_y[datas_idx]\n\n# modify test_x\ntest_x = test_x[:, features_idx]\n\nprint(f'train_x shape {train_x.shape}')\nprint(f'train_y shape {train_y.shape}')\nprint(f'test_x shape {test_x.shape}')\n\n# define model\nmodel = ExtraTreesRegressor(n_estimators=n_estimators, criterion=criterion, n_jobs=n_jobs, oob_score=oob_score, bootstrap=bootstrap)\n\n# train model\nmodel.fit(train_x, train_y)\n\n# print informations\nwith open(information_file_name, 'w') as f:\n if oob_score:\n print(f'oob_score: {model.oob_score_}', file=f)\n print(f'track 1 ein: {err1_calc(model.predict(train_x), train_y, y_id)}', file=f)\n print(f'track 2 ein: {err2_calc(model.predict(train_x), train_y)}', file=f)\n\n# write prediction\nwrite_prediction(predict_y_file_name, 'w', model.predict(test_x).reshape((2500, 1)).astype('str'))\n","sub_path":"74/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"291184148","text":"import pandas as pd\nimport numpy as np\nimport xlrd\nimport matplotlib.pyplot as plt\n\n# read the excel file\nb = pd.read_excel('~/Desktop/kc_house_data.xlsx')\n\n# store the data as numpy ndarray\nb = b.values\nprice = b[:,4]\nb = b[:,[0, 1, 2, 3]]\n# print(type(b))\n# \n\n# print(b)\n\n# mean normalization of data\nfor i in range(4):\n\tb[:, i] = np.subtract(b[:, i], np.sum(b, axis=0)[i]/b.shape[0])\n\n# feature scaling the attributes\nfor i in range(4):\n\tb[:, i] = np.divide(b[:, i], np.amax(b[:, i]) - np.amin(b[:, i]))\n\n# Adding a column containing ones for the sake of theta[0]\nx = np.ones((b.shape[0],b.shape[1]+1))\nx[:,:-1] = b\n\n# test = last 20% of the given data\n# x = first 80% of the given data\nn_x = (int)(0.8*x.shape[0])\ntest = x[n_x:, :]\nx = x[:n_x, :]\n\n# hypothesis function:\n# = theta[0] * x[i][0] + theta[1] * x[i][1] + theta[2] * x[i][2] +\n# theta[3] * x[i][3] + theta[4] * x[i][4]\n\nalpha = 0.05\nlambd = [0.001, 0.01, 0.05, 0.1]\n\n# function for evaluation of summation of (h-theta(x[i]) - y[i]) * x[i][0-4]\ndef hypothesis(theta, x, y):\n\tsummation = 0\n\tfor i in range(x.shape[0]):\n\t\tsummation += (np.dot(theta, x[i]) - y[i]) * x[i]\n\treturn summation\n\n# use gradient descent to minimize cost and obtain theta values\n\n# create empty list to store all the errors\nerr=[]\n# do it for each diff value of lambda\nfor lbd in lambd:\n# repeat this until convergence\n\ttheta = np.random.rand(5)\n\tcnt = 0\n\twhile cnt < 50:\n\t\ttemp_theta = np.subtract(theta, alpha * hypothesis(theta, x, price) / x.shape[0])\n\t\tfor i in range(5):\n\t\t\tif i != 4:\n\t\t\t\ttemp_theta[i] = temp_theta[i] - theta[i] * alpha * lbd / x.shape[0]\n\t\ttheta = temp_theta\n\t\tcnt += 1\n\n# test the accuracy:\n\tsummation = 0\n\tfor i in range(test.shape[0]):\n\t\tsummation += (np.dot(theta, test[i]) - price[i+n_x]) ** 2\n\tsummation = summation / (2 * test.shape[0])\n\tRMSE = summation ** 0.5\n\terr.append(RMSE)\n\tprint(\"Finally Learned Values of theta are:\")\n\tprint(theta)\n\tprint(\"RMSE finally obtained is %s\" % (RMSE))\n\n\n# Plot using matplotlib RMSE vs lambda\nplt.plot(lambd, err, '-o')\nplt.xlabel('Lambda values')\nplt.ylabel('RMSE')\nplt.show()\n","sub_path":"1/Ass_1a_ML_reg.py","file_name":"Ass_1a_ML_reg.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"50093166","text":"import datetime, operator\r\nfrom django.shortcuts import render, redirect\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\nfrom .forms import *\r\nfrom report.models import *\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib.auth.models import User\r\n\r\n\r\n\r\n@login_required(login_url = '/account/login/')\r\ndef main(request):\r\n return render(request, 'main.html',)\r\n\r\ndef add_options(request):\r\n return render(request, 'add_options.html',)\r\n\r\ndef report_options(request):\r\n return render(request, 'report_options.html')\r\n\r\n@login_required(login_url = '/account/login/')\r\ndef add(request):\r\n if request.user.has_perm('MPT.add_date'):\r\n form1 = DateForm(request.POST)\r\n form2 = ShiftForm(request.POST)\r\n form3 = VesselForm(request.POST)\r\n form4 = SlotForm(request.POST)\r\n\r\n if request.method == 'POST' :\r\n if form1.is_valid() and form2.is_valid() and form3.is_valid() and form4.is_valid():\r\n date = form1.cleaned_data['date']\r\n\r\n hmc_number = form2.cleaned_data['hmc_number']\r\n shift = form2.cleaned_data['shift']\r\n vessel_name = form3.cleaned_data['vessel_name']\r\n vessel_cargo = form3.cleaned_data['vessel_cargo']\r\n\r\n time_slot_start = form4.cleaned_data['time_slot_start']\r\n time_slot_stop = form4.cleaned_data['time_slot_stop']\r\n reason = form4.cleaned_data['reason']\r\n remark = form4.cleaned_data['remark']\r\n\r\n if Date.objects.filter(date = date): #if list is non empty it will proceed\r\n date_data = Date.objects.filter(date = date)[0]\r\n else:\r\n date_data = Date(\r\n date = date\r\n )\r\n date_data.save()\r\n\r\n if Shift.objects.filter(date__date = date).filter(shift = shift).filter(hmc_number = hmc_number):\r\n shift_data = Shift.objects.filter(date__date = date).filter(shift =shift).filter(hmc_number = hmc_number)[0]\r\n else:\r\n shift_data = Shift(date = date_data, shift = shift, hmc_number = hmc_number, user = request.user)\r\n shift_data.save()\r\n\r\n if shift_data.shift_end_flag == 0:\r\n slot_data = Slot(shift = shift_data, time_slot_start = time_slot_start, time_slot_stop = time_slot_stop,\r\n reason = reason, remark = remark)\r\n slot_data.save()\r\n vessel_data = Vessel(\r\n slot = slot_data,\r\n vessel_name = vessel_name,\r\n vessel_cargo = vessel_cargo\r\n )\r\n vessel_data.save()\r\n return render(request,'message.html',{'message':\"Entry Saved!!! **or Shift already existed\"})\r\n else:\r\n return render(request,'message.html',{'message':\"Shift has already been ended.You can't add data again now.\"})\r\n\r\n else:\r\n\r\n form1 = DateForm()\r\n form2 = ShiftForm()\r\n form3 = VesselForm()\r\n form4 = SlotForm()\r\n\r\n dates = Date.objects.all().order_by('-date')[:2]\r\n return render(request, 'add.html', { 'form1': form1, 'form2': form2, 'form3': form3, 'form4': form4,'dates':dates})\r\n else:\r\n return render(request,'message.html',{'message':\"You don't have permison to add data.\"})\r\n\r\n\r\n@login_required(login_url = '/account/login/')\r\ndef add_shift_end(request):\r\n form = ShiftEndForm(request.POST)\r\n if request.method == \"POST\":\r\n\r\n if form.is_valid():\r\n date = form.cleaned_data['date']\r\n shift = form.cleaned_data['shift']\r\n hmc_number = form.cleaned_data['hmc_number']\r\n diesel_end_hours = form.cleaned_data['diesel_end_hours']\r\n diesel_start_hours = form.cleaned_data['diesel_start_hours']\r\n diesel_start_percentage = form.cleaned_data['diesel_end_percentage']\r\n diesel_end_percentage = form.cleaned_data['diesel_end_percentage']\r\n total_tonnage_or_boxes = form.cleaned_data['total_tonnage_or_boxes']\r\n cycles = form.cleaned_data['cycles']\r\n shift_objects = Shift.objects.filter(date__date = date, shift = shift, hmc_number = hmc_number)\r\n if shift_objects:\r\n shift_object = shift_objects[0]\r\n if shift_object.shift_end_flag == 0:\r\n shift_object.diesel_start_hours = diesel_start_hours\r\n shift_object.diesel_end_hours = diesel_end_hours\r\n shift_object.diesel_start_percentage = diesel_start_percentage\r\n shift_object.diesel_end_percentage = diesel_end_percentage\r\n shift_object.total_tonnage_or_boxes = total_tonnage_or_boxes\r\n shift_object.cycles = cycles\r\n shift_object.user = request.user\r\n shift_object.shift_end_flag = 1\r\n shift_object.save()\r\n return render(request,'message.html',{'message':\"Shift has been ended successfully.\"})\r\n else:\r\n return render(request,'message.html',{'message':\"Shift has already been ended.You can't end it again.\"})\r\n else:\r\n return render(request,'message.html',{'message':\"Shift doesn't exist.\"})\r\n else:\r\n form = ShiftEndForm()\r\n return render(request, 'add_shift_end.html', { 'form': form})\r\n\r\n\r\n@login_required(login_url = '/account/login/')\r\ndef delete_view(request):\r\n if request.user.has_perm('MPT.delete_date'):\r\n form = SearchForm(request.POST)\r\n if request.method == 'POST' :\r\n date_search = request.POST['date_search']\r\n month_search = request.POST['month_search']\r\n year_search = request.POST['year_search']\r\n hmc_search = request.POST['hmc_search']\r\n\r\n if date_search != \"\" and month_search != \"\" and year_search != \"\":\r\n search_results = Shift.objects.filter(date__date__day = date_search).filter(date__date__month = month_search).filter(date__date__year = year_search).filter(hmc_number = hmc_search).order_by('date__date', 'shift')\r\n elif date_search != \"\" and month_search != \"\" and year_search == \"\":\r\n search_results = Shift.objects.filter(date__date__day = date_search).filter(date__date__month = month_search).filter(hmc_number = hmc_search).order_by('date__date', 'shift')\r\n elif date_search != \"\" and month_search == \"\" and year_search != \"\":\r\n search_results = Shift.objects.filter(date__date__day = date_search).filter(date__date__year = year_search).filter(hmc_number = hmc_search).order_by('date__date', 'shift')\r\n elif date_search != \"\" and month_search == \"\" and year_search == \"\":\r\n search_results = Shift.objects.filter(date__date__day = date_search).filter(hmc_number = hmc_search).order_by('date__date', 'shift')\r\n elif date_search == \"\" and month_search != \"\" and year_search != \"\":\r\n search_results = Shift.objects.filter(date__date__month = month_search).filter(date__date__year = year_search).filter(hmc_number = hmc_search).order_by('date__date', 'shift')\r\n elif date_search == \"\" and month_search != \"\" and year_search == \"\":\r\n search_results = Shift.objects.filter(date__date__month = month_search).filter(hmc_number = hmc_search).order_by('date__date', 'shift')\r\n elif date_search == \"\" and month_search == \"\" and year_search != \"\":\r\n search_results = Shift.objects.filter(date__date__year = year_search).filter(hmc_number = hmc_search).order_by('date__date', 'shift')\r\n else:\r\n search_results = []\r\n if search_results:\r\n context = {'search_results': search_results}\r\n return render(request, 'delete_result.html', context)\r\n else:\r\n return render(request,'message.html',{'message':\"No data for given parameters exists.\"})\r\n else:\r\n form = SearchForm()\r\n\r\n return render(request, 'delete.html', {'form': form})\r\n\r\n else:\r\n return render(request,'message.html',{'message':\"You don't have permission to delete data.\"})\r\n\r\n\r\n@login_required(login_url = '/account/login/')\r\ndef delete_date_entry(request, date_id):\r\n date = Date.objects.filter(id = date_id).delete()\r\n return render(request,'message.html',{'message':\"Data has been deleted successfully.\"})\r\n\r\n\r\n@login_required(login_url = '/account/login/')\r\ndef delete_shift_entry(request, shift_id):\r\n to_be_deleted = Shift.objects.filter(id = shift_id)\r\n if to_be_deleted:\r\n date_id = to_be_deleted[0].date.id\r\n else:\r\n return render(request,'message.html',{'message':\"Either Date doesn't exist or has been deleted.\"})\r\n to_be_deleted.delete()\r\n check_empty_date = Shift.objects.filter(date__id = date_id)\r\n if check_empty_date:\r\n pass\r\n else:\r\n Date.objects.filter(id = date_id).delete()\r\n return render(request,'message.html',{'message':\"Shift has been deleted successfully.\"})\r\n\r\n@login_required(login_url = '/account/login/')\r\ndef delete_slot_entry(request, slot_id):\r\n Slot.objects.filter(id = slot_id).delete()\r\n return render(request,'message.html',{'message':\"Slot has been deleted successfully.\"})\r\n\r\n# finish the searching code\r\n@login_required(login_url = '/account/login/')\r\ndef search(request):\r\n form = SearchForm(request.POST)\r\n if request.method == 'POST' :\r\n date_search = request.POST['date_search']\r\n month_search = request.POST['month_search']\r\n year_search = request.POST['year_search']\r\n hmc_search = request.POST['hmc_search']\r\n\r\n if date_search != \"\" and month_search != \"\" and year_search != \"\":\r\n search_results = Shift.objects.filter(date__date__day = date_search).filter(date__date__month = month_search).filter(date__date__year = year_search).filter(hmc_number = hmc_search).order_by('date__date','shift')\r\n elif date_search != \"\" and month_search != \"\" and year_search == \"\":\r\n search_results = Shift.objects.filter(date__date__day = date_search).filter(date__date__month = month_search).filter(hmc_number = hmc_search).order_by('date__date','shift')\r\n elif date_search != \"\" and month_search == \"\" and year_search != \"\":\r\n search_results = Shift.objects.filter(date__date__day = date_search).filter(date__date__year = year_search).filter(hmc_number = hmc_search).order_by('date__date','shift')\r\n elif date_search != \"\" and month_search == \"\" and year_search == \"\":\r\n search_results = Shift.objects.filter(date__date__day = date_search).filter(hmc_number = hmc_search).order_by('date__date','shift')\r\n elif date_search == \"\" and month_search != \"\" and year_search != \"\":\r\n search_results = Shift.objects.filter(date__date__month = month_search).filter(date__date__year = year_search).filter(hmc_number = hmc_search).order_by('date__date','shift')\r\n elif date_search == \"\" and month_search != \"\" and year_search == \"\":\r\n search_results = Shift.objects.filter(date__date__month = month_search).filter(hmc_number = hmc_search).order_by('date__date','shift')\r\n elif date_search == \"\" and month_search == \"\" and year_search != \"\":\r\n search_results = Shift.objects.filter(date__date__year = year_search).filter(hmc_number = hmc_search).order_by('date__date','shift')\r\n else:\r\n search_results = []\r\n if search_results:\r\n context = {'search_results': search_results}\r\n return render(request, 'search_result.html', context)\r\n else:\r\n return render(request,'message.html',{'message':\"No data for given parameters exists.\"})\r\n else:\r\n form = SearchForm()\r\n\r\n return render(request, 'search.html', {'form': form})\r\n\r\n@login_required(login_url = '/account/login/')\r\ndef generate_report(request):\r\n form = ReportGenerationForm(request.POST)\r\n if request.method == 'POST':\r\n month_search = request.POST['month_search']\r\n reason_search = request.POST['reason_search']\r\n year_search = request.POST['year_search']\r\n hmc_search = request.POST['hmc_search']\r\n\r\n if month_search == \"\":\r\n search_results = Slot.objects.filter(reason = reason_search).filter(shift__date__date__year=year_search).filter(shift__hmc_number = hmc_search)\r\n else:\r\n search_results = Slot.objects.filter(reason = reason_search).filter(shift__date__date__year = year_search).filter(shift__hmc_number = hmc_search)\r\n search_results = search_results.filter(shift__date__date__month = month_search).order_by('shift__date__date')\r\n\r\n res = []\r\n for slot in search_results:\r\n data = [slot.shift.date.date.strftime(\"%d.%m.%Y\"), slot.time_slot_start.strftime(\"%H:%M\"), slot.time_slot_stop.strftime(\"%H:%M\"), round(slot.total_time(), 2), slot.reason, slot.remark]\r\n res.append(data)\r\n if res:\r\n context = {'res': res}\r\n return render(request, 'report_generation_result.html', context)\r\n else:\r\n return render(request,'message.html',{'message':\"No data for given parameters exists.\"})\r\n else:\r\n form = ReportGenerationForm()\r\n\r\n return render(request, 'report_generation.html', {'form': form})\r\n\r\n# Make sure that there is only one vessel in a single shift\r\n@login_required(login_url = '/account/login/')\r\ndef vesselwise_tonnage(request):\r\n form = VesselwiseTonnageForm(request.POST)\r\n\r\n if request.method == 'POST':\r\n year_search = request.POST['year_search']\r\n hmc_search = request.POST['hmc_search']\r\n month_search = request.POST['month_search']\r\n\r\n shifts = Shift.objects.filter(date__date__year = year_search).filter(date__date__month = month_search).filter(hmc_number = hmc_search).order_by('date__date')\r\n\r\n res = []\r\n vessels = set()\r\n last_date = dict()\r\n\r\n for shift in shifts:\r\n if shift.slot_set.all():\r\n slot = shift.slot_set.all()[0]\r\n if slot.vessel_set.all():\r\n vessel = slot.vessel_set.all()[0]\r\n vessels.add(vessel.vessel_name)\r\n\r\n for vessel_name in vessels:\r\n # data = [trip, vessel_name, tonnage, cargo, diesel_consumed, diesel_hours]\r\n trip = 1\r\n tonnage = 0\r\n cargo = 0\r\n diesel_consumed = 0\r\n diesel_hours = 0\r\n for i in range(len(shifts)):\r\n if shifts[i].slot_set.all():\r\n slot = shifts[i].slot_set.all()[0]\r\n if slot.vessel_set.all():\r\n vessel = slot.vessel_set.all()[0]\r\n if vessel.vessel_name == vessel_name:\r\n if vessel_name in last_date and shifts[i].date.date - last_date[vessel_name] > datetime.timedelta(7):\r\n data = [trip, vessel_name, tonnage, cargo, diesel_consumed, diesel_hours]\r\n res.append(data)\r\n trip += 1\r\n tonnage = 0\r\n cargo = 0\r\n diesel_consumed = 0\r\n diesel_hours = 0\r\n tonnage += shifts[i].total_tonnage_or_boxes\r\n cargo = shifts[i].slot_set.all()[0].vessel_set.all()[0].vessel_cargo\r\n diesel_consumed += shifts[i].diesel_consumed()\r\n diesel_hours += shifts[i].diesel_hours()\r\n last_date[vessel_name] = shifts[i].date.date\r\n data = [trip, vessel_name, tonnage, cargo, diesel_consumed, diesel_hours]\r\n res.append(data)\r\n res.sort(key = operator.itemgetter(0))\r\n if res:\r\n context = {'res': res}\r\n return render(request, 'vesselwise_tonnage_result.html', context)\r\n else:\r\n return render(request,'message.html',{'message':\"No data for given parameters exists.\"})\r\n else:\r\n form = ReportGenerationForm()\r\n\r\n return render(request, 'vesselwise_tonnage.html', {'form': form})\r\n","sub_path":"report/__pycache__/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"653142828","text":"# coding=utf-8\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utilities supporting data generation code.\"\"\"\n\nimport math\nimport os\nimport io\nfrom io import BytesIO\nimport numpy as np\nfrom scipy import signal\nfrom PIL import Image\n\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\n\nfrom tensor2tensor.layers import common_video\n\n\ndef get_random_index_subinterval(interval_length, subinterval_length,\n num_samples):\n \"\"\"Given length, sample a pair of indicies in [0,length].\n \n Args:\n interval_length(int): The length of an interval to sample.\n subinterval_length(int): The length of the interval to sample,\n e.g. a length=2 sub-interval from a parent interval of\n length=10\n num_samples(int): The number of samples to generate.\n \n Returns:\n list: The sampled sub-interval start and end indices.\n \n \"\"\"\n\n samples = []\n\n if subinterval_length > interval_length:\n raise ValueError(\n \"Can't sample interval of length %s % \" % subinterval_length,\n \"from a larger interval of length %s.\" % duration)\n\n for _ in range(num_samples):\n start = np.random.randint(0, interval_length - subinterval_length)\n end = start + subinterval_length\n samples.append([start, end])\n\n return samples\n\n\ndef get_temporal_subinterval(duration, subinterval_length):\n\n if subinterval_length > duration:\n raise ValueError(\"Can sample interval of length %s % \" % subinterval_length,\n \"from a larger interval of length %s.\" % duration)\n\n start_seconds = np.random.uniform(0, duration - subinterval_length)\n end_seconds = start_seconds + subinterval_length\n\n return start_seconds, end_seconds\n\n\ndef get_input_file_paths(glob_or_file_path, is_training, training_fraction):\n \"\"\"Get a list of input files from `tmp_dir`.\"\"\"\n\n #if not glob_or_file_path.endswith(\"*\"):\n # glob_or_file_path += \"/*\"\n all_files = tf.gfile.Glob(glob_or_file_path)\n\n dividing_index = int(math.floor(len(all_files) * training_fraction))\n\n if is_training:\n return all_files[:dividing_index]\n else:\n return all_files[dividing_index:]\n\n\ndef array2gif(raw_frames):\n frames = []\n for frame in raw_frames:\n frames.append(Image.fromarray(np.uint8(frame)))\n\n with io.BytesIO() as output:\n\n frames[0].save(output,\n format='GIF',\n append_images=frames[1:],\n save_all=True)\n\n return output.getvalue()\n\n\ndef evaluate_tensor(tensor):\n if tf.executing_eagerly():\n return tensor.numpy()\n else:\n sess = ops.get_default_session()\n if sess is None:\n with tf.Session() as sess:\n return sess.run(tensor)\n else:\n return sess.run(tensor)\n\n\ndef gen_gif_encoded_from_field_spec(field_spec, zeros=False):\n mocked = evaluate_tensor(field_spec.mock_one(zeros=zeros))\n encoded = array2gif(mocked)\n return encoded\n\n\ndef gen_dummy_schedule(num_problems, num_steps=10):\n steps = []\n pwf = []\n steps.append(num_steps)\n prob_pwf = [1 / num_problems for _ in range(num_problems)]\n pwf.append(prob_pwf)\n schedule = ('step', tuple(steps), tuple(tuple(thing) for thing in pwf))\n return schedule\n\n\n# -----\n# Old, probably remove.\n\n\ndef normalize_example_multimodal(example,\n task_id,\n example_norm_spec,\n dtype=tf.int64):\n \"\"\"\n \n This expects to receive a single example not a batch of examples.\n \n \"\"\"\n\n # Hack\n max_num_classes = example_norm_spec[\"targets\"]\n xlen = tf.shape(example[\"targets\"])[0]\n x = example[\"targets\"]\n #example[\"targets\"] = tf.pad(x, [[0, max_num_classes - xlen]])\n\n for key, shape in example_norm_spec[\"modalities\"].items():\n if key not in example:\n example[key] = tf.zeros(shape, dtype=dtype)\n\n example[\"task_id\"] = tf.constant([task_id], dtype=dtype)\n\n return example\n\n\ndef sim_dummy_tensor(shape, vocab_size):\n \"\"\"Simulate a dummy tensor of specified `shape` and `vocab_size`.\n \n Zero-based, uses [0, vocab_size).\n \"\"\"\n x = np.random.uniform(0, 1, shape) * vocab_size\n x = x.astype(np.int32).tolist()\n return x\n\n\ndef gen_dummy_encoded_video(shape, vocab_size, sample_fps=1):\n\n def make_frame():\n return (np.random.uniform(0, 1, shape[1:]) * vocab_size).astype(np.int32)\n\n frame_list = np.asarray([make_frame() for _ in range(shape[0])])\n\n return array2gif(frame_list)\n\n\ndef extend_hparams_with_hparams(hp1, hp2):\n \"\"\"Given one set of hparams add to that another.\"\"\"\n for k, v in hp2.__dict__.items():\n setattr(hp1, k, v)\n return hp1\n\n\n# --------\n","sub_path":"clarify/datasets/utils/dataset_utils.py","file_name":"dataset_utils.py","file_ext":"py","file_size_in_byte":5072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"623829796","text":"from tkinter import *\r\nfrom functools import partial # To prevent unwanted windows\r\n\r\nimport random\r\n\r\nif __name__ == '__main__':\r\n class MathTitle:\r\n def __init__(self, parent):\r\n\r\n # Gui to get numbers and choose type of math\r\n self.start_frame = Frame(padx=10, pady=10)\r\n self.start_frame.grid()\r\n\r\n # Myath Heading heading row 1\r\n self.mystery_box_label = Label(self.start_frame, text=\"Math Game Quiz\", font=\"Arial 20 bold\")\r\n self.mystery_box_label.grid(row=1)\r\n\r\n #help button (row 2)\r\n self.help_button = Button(self.start_frame, text=\"Continue\", font=\"Arial 12\", command=self.first_question)\r\n self.help_button.grid(row=2, pady=10)\r\n\r\n def first_question(self):\r\n get_help = Game(self)\r\n\r\nclass Game:\r\n def __init__(self, partner):\r\n\r\n self.true_answer = IntVar()\r\n self.true_answer.set(0)\r\n self.question_number = IntVar()\r\n self.question_number.set(1)\r\n\r\n #disable help button\r\n partner.help_button.config(state=DISABLED)\r\n\r\n # sets up child window (ie: help box)\r\n self.help_box = Toplevel()\r\n\r\n #if user press cross instead of dismiss, close help and release help button\r\n self.help_box.protocol('WM_DELETE_WINDOW', partial(self.close_help, partner))\r\n\r\n thingy = random.randint(1, 4)\r\n\r\n num1 = random.randint(1, 12)\r\n num2 = random.randint(1, 12)\r\n\r\n if thingy == 1:\r\n op_text = \"+\"\r\n answer = num1 + num2\r\n\r\n elif thingy == 2:\r\n op_text = \"-\"\r\n answer = num1 - num2\r\n\r\n elif thingy == 3:\r\n op_text = \"x\"\r\n answer = num1 * num2\r\n\r\n else:\r\n op_text = \"÷\"\r\n num3 = num1 * num2\r\n answer = num1\r\n num1 = num3\r\n\r\n self.true_answer.set(answer)\r\n\r\n # set up gui frame\r\n self.help_frame = Frame(self.help_box, width=300)\r\n self.help_frame.grid()\r\n\r\n self.number_frame = Frame(self.help_frame, width=300)\r\n self.number_frame.grid(row=0)\r\n\r\n # set question number\r\n self.how_heading = Label(self.number_frame, text=\"Question {}:\".format(self.question_number.get()),\r\n font=\"Arial 15\", width=10, anchor=W)\r\n self.how_heading.grid(row=1, column=0, padx=5)\r\n\r\n # show the question\r\n self.first_number = Label(self.number_frame, text=\"{}\".format(num1), font=\"Arial 15\", anchor=W)\r\n self.first_number.grid(row=1, column=1)\r\n\r\n self.symbol = Label(self.number_frame, text=\"{}\".format(op_text), font=\"Arial 15\", anchor=W)\r\n self.symbol.grid(row=1, column=2)\r\n\r\n self.second_number = Label(self.number_frame, text=\"{}\".format(num2), font=\"Arial 15\", anchor=W, width=12)\r\n self.second_number.grid(row=1, column=3)\r\n\r\n # frame for answering question\r\n self.entry_box_frame = Frame(self.help_frame, width=300)\r\n self.entry_box_frame.grid(row=1)\r\n\r\n # Space for answering the question and error when answering\r\n self.answer_entry = Entry(self.entry_box_frame, font=\"Arial 15\", width=10)\r\n self.answer_entry.grid(row=1, column=0, pady=5, padx=15)\r\n\r\n self.entry_error_label = Label(self.entry_box_frame, text=\"\", font=\"Arial 15\")\r\n self.entry_error_label.grid(row=2, column=0, pady=5)\r\n\r\n # Frame for buttons\r\n self.lower_frame = Frame(self.help_frame, width=10)\r\n self.lower_frame.grid(row=5)\r\n\r\n # Submit button\r\n self.answer_question = Button(self.lower_frame, font=\"Arial 15\", text=\"Submit\", width=10,\r\n command=partial(self.check_answer))\r\n self.answer_question.grid(row=0, column=0, pady=15)\r\n\r\n # help button (row 2)\r\n self.help_button = Button(self.lower_frame, text=\"Help\", font=\"Arial 14\", command=self.help2, width=10)\r\n self.help_button.grid(row=1, column=0, pady=15)\r\n\r\n # continue button\r\n self.continue_button = Button(self.lower_frame, text=\"Continue\", font=\"Arial 14\", width=10,\r\n command=partial(self.next_question))\r\n self.continue_button.grid(row=0, column=1, pady=15, padx=2)\r\n self.continue_button.config(state=DISABLED)\r\n\r\n # dismiss button (row 2)\r\n self.dismiss_btn = Button(self.lower_frame, text=\"Stats\", width=10,\r\n bg=\"#660000\", font=\"Arial 14 bold\", fg=\"white\")\r\n self.dismiss_btn.grid(row=1, column=1, pady=15, padx=2)\r\n\r\n print(answer)\r\n\r\n def close_help(self, partner):\r\n root.destroy()\r\n\r\n def help2(self):\r\n get_help = Help2(self)\r\n\r\n def check_answer(self):\r\n\r\n answer = self.true_answer.get()\r\n\r\n user_answer = self.answer_entry.get()\r\n\r\n try:\r\n user_answer = int(user_answer)\r\n answer = int(answer)\r\n\r\n if user_answer == answer:\r\n self.answer_entry.config(bg=\"#3DCE30\")\r\n self.entry_error_label.config(text=\"Correct\")\r\n self.answer_question.config(state=DISABLED)\r\n self.continue_button.config(state=NORMAL)\r\n\r\n else:\r\n self.entry_error_label.config(text=\"Incorrect\")\r\n\r\n # Change entry box background to pink\r\n self.answer_entry.config(bg=\"#ffafaf\")\r\n self.answer_question.config(state=DISABLED)\r\n self.continue_button.config(state=NORMAL)\r\n\r\n except ValueError:\r\n self.entry_error_label.config(text=\"Numbers Only\")\r\n\r\n # Change entry box background to pink\r\n self.answer_entry.config(bg=\"#ffafaf\")\r\n\r\n def next_question(self):\r\n\r\n question_number = self.question_number.get()\r\n question_number = question_number + 1\r\n self.question_number.set(question_number)\r\n\r\n thingy = random.randint(1, 4)\r\n\r\n num1 = random.randint(1, 12)\r\n num2 = random.randint(1, 12)\r\n\r\n if thingy == 1:\r\n op_text = \"+\"\r\n answer = num1 + num2\r\n\r\n elif thingy == 2:\r\n op_text = \"-\"\r\n answer = num1 - num2\r\n\r\n elif thingy == 3:\r\n op_text = \"x\"\r\n answer = num1 * num2\r\n\r\n else:\r\n op_text = \"÷\"\r\n num3 = num1 * num2\r\n answer = num1\r\n num1 = num3\r\n\r\n self.true_answer.set(answer)\r\n\r\n self.first_number.config(text=\"{}\".format(num1))\r\n\r\n self.symbol.config(text=\"{}\".format(op_text))\r\n\r\n self.second_number.config(text=\"{}\".format(num2))\r\n\r\n self.answer_question.config(state=NORMAL)\r\n self.continue_button.config(state=DISABLED)\r\n self.entry_error_label.config(text=\"\")\r\n self.answer_entry.config(bg=\"SystemButtonFace\")\r\n self.answer_entry.delete(0, 'end')\r\n self.how_heading.config(text=\"Question: {}\".format(self.question_number.get()))\r\n print(answer)\r\n\r\n\r\nclass Help2:\r\n def __init__(self, partner):\r\n\r\n #disable help button\r\n partner.help_button.config(state=DISABLED)\r\n\r\n # sets up child window (ie: help box)\r\n self.help_box = Toplevel()\r\n\r\n #if user press cross instead of dismiss, close help and release help button\r\n self.help_box.protocol('WM_DELETE_WINDOW', partial(self.close_help2, partner))\r\n\r\n # set up gui frame\r\n self.help_frame = Frame(self.help_box, width=300)\r\n self.help_frame.grid()\r\n\r\n #set up help heading (row 0)\r\n self.how_heading = Label(self.help_frame, text=\"Help and Instructions\",\r\n font=\"Arial 14 bold\")\r\n self.how_heading.grid(row=0)\r\n\r\n help_text=\"The program will generate a question using numbers \" \\\r\n \"in between the 2 numbers you chose at the start.\" \\\r\n \"\\n\\n\" \\\r\n \"Input the answer into the box and press Enter or click the \" \\\r\n \"submit button.\" \\\r\n \"\\n\\n\" \\\r\n \"The box will turn green if you are correct, \" \\\r\n \"and red if you are incorrect.\" \\\r\n \"\\n\\n\" \\\r\n \"Then press continue to move onto the next question or press \" \\\r\n \"Finish to end the game and go to your results early.\"\r\n\r\n # help text (label, row 1)\r\n self.help_text = Label(self.help_frame, text=help_text,\r\n justify=LEFT, wrap=400, padx=10, pady=10)\r\n self.help_text.grid(row=1)\r\n\r\n #dismiss button (row 2)\r\n self.dismiss_btn = Button(self.help_frame, text=\"Dismiss\", width=10,\r\n bg=\"#660000\", font=\"Arial 14 bold\", fg=\"white\",\r\n command=partial(self.close_help2, partner))\r\n self.dismiss_btn.grid(row=2, pady=10)\r\n\r\n def close_help2(self, partner):\r\n # put help button back to normal\r\n partner.help_button.config(state=NORMAL)\r\n self.help_box.destroy()\r\n\r\n\r\n# main routine\r\nif __name__ == \"__main__\":\r\n root = Tk()\r\n root.title(\"Math Game\")\r\n something = MathTitle(root)\r\n root.mainloop()\r\n","sub_path":"01_game_gui_v3.py","file_name":"01_game_gui_v3.py","file_ext":"py","file_size_in_byte":9279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"42805530","text":"\n\nfrom xai.brain.wordbase.verbs._bode import _BODE\n\n#calss header\nclass _BODING(_BODE, ):\n\tdef __init__(self,): \n\t\t_BODE.__init__(self)\n\t\tself.name = \"BODING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"bode\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_boding.py","file_name":"_boding.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"207438123","text":"# -*- coding: utf-8 -*-\nimport scrapy,json\nfrom quotesbot.Classes import Product\nfrom quotesbot.Classes import Size\nfrom quotesbot.Classes import Picture\nfrom quotesbot.Classes import BreadCrumbCategory\nfrom pymongo import MongoClient\nfrom bs4 import BeautifulSoup\n\nclass RBProductDetail(scrapy.Spider):\n name = \"ReebokProductDetail\"\n\n def start_requests(self):\n client = MongoClient('mongodb://localhost:27017')\n db = client['Vitrin']\n collection = db['Sites']\n for obj in collection.find({\"SiteName\": 'ReebokOfficial'}):\n p = Product()\n p= obj\n yield scrapy.Request('https://www.reebok.com.tr'+obj[\"url\"], meta={'item':p})\n\n def parse(self, response):\n item = response.meta['item']\n \n sizes = []\n for size in response.css(\".size-list li a\").extract():\n a = BeautifulSoup(size, \"lxml\").find('a', class_=\"\")\n if a is not None:\n s = Size()\n s[\"SizeName\"]=a.text\n s[\"SizeStock\"]=a[\"data-stock\"]\n sizes.append(s)\n\n pics = []\n for pic in response.css(\"#thumblist li a img\").extract():\n soup = BeautifulSoup(pic, \"lxml\")\n p=Picture()\n p[\"PicturePath\"]=soup.find('img')[\"src\"]\n pics.append(p)\n\n sCategory = []\n for subCategory in response.css(\"#breadcrumbs ul li a\").extract():\n soup = BeautifulSoup(subCategory, \"lxml\")\n subcat= BeautifulSoup(soup.find('a').text, \"lxml\").text\n if subcat == \"Anasayfa\":\n pass\n elif subcat == \"Geri\":\n pass\n elif subcat == item[\"Name\"]:\n pass\n else:\n b = BreadCrumbCategory()\n b[\"Name\"]= subcat\n b[\"Url\"]= '/'+soup.find('a')[\"href\"]\n sCategory.append(b)\n\n desc=\"\"\n d = response.xpath('//*[@id=\"product-body\"]/div[3]/div/div[1]/div[2]/p/text()').extract_first()\n if d is not None:\n desc = d +\"
\"\n d = response.xpath('//*[@id=\"product-body\"]/div[3]/div/div[1]/div[3]').extract_first()\n if d is not None:\n desc = desc + d\n \n item[\"Desc\"]= desc\n item['Size']= sizes\n item['Picture'] = pics\n item['SubCategory'] = sCategory\n yield item","sub_path":"quotesbot/spiders/Reebok/ProductDetail.py","file_name":"ProductDetail.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"146593674","text":"import numpy as np\n\nfrom scratch.sam.util import *\nfrom scratch.neural_net.lib import *\n\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import optim\n\nimport logging\nmpl_logger = logging.getLogger('matplotlib') \nmpl_logger.setLevel(logging.WARNING)\n\nDTYPE = np.float32\n\n\nfeat_vec, energies, poly, pos_ext, patch_indices, methyl_pos, adj_mat = load_and_prep('data/sam_pattern_data.dat.npz')\n\n\n# Tests that data partitioning works on 1d feature dataset\ndef test_partition1D():\n partition = partition_data(feat_vec, energies, n_groups=2)\n\n X_train1, y_train1, X_test1, y_test1 = next(partition)\n X_train2, y_train2, X_test2, y_test2 = next(partition)\n\n np.testing.assert_array_equal(X_train1, X_test2)\n np.testing.assert_array_equal(X_train2, X_test1)\n\ndef test_partitionND():\n partition = partition_data(feat_vec, poly, n_groups=2)\n\n X_train1, y_train1, X_test1, y_test1 = next(partition)\n X_train2, y_train2, X_test2, y_test2 = next(partition)\n\n assert y_train1.ndim == y_train2.ndim == 2\n\n np.testing.assert_array_equal(X_train1, X_test2)\n np.testing.assert_array_equal(X_train2, X_test1)\n np.testing.assert_array_equal(y_train1, y_test2)\n\ndef test_partition_multi1D():\n partition = partition_data(feat_vec, energies, n_groups=5)\n X_train, y_train, X_test, y_test = next(partition)\n\n expt_cohort_size = feat_vec.shape[0] // 5\n # Training data is everything that's not in testing set\n assert X_train.shape[0] >= expt_cohort_size * 4\n assert X_test.shape[0] == expt_cohort_size\n\ndef test_partition_multiND():\n partition = partition_data(feat_vec, poly, n_groups=5)\n X_train, y_train, X_test, y_test = next(partition)\n\n expt_cohort_size = feat_vec.shape[0] // 5\n assert X_train.shape[0] >= expt_cohort_size * 4\n assert X_test.shape[0] == expt_cohort_size\n \ndef test_SAMdataset1D():\n dataset = SAMDataset(feat_vec, energies)\n\n assert dataset.X_dim == 36\n assert dataset.y_dim == 1\n assert len(dataset) == feat_vec.shape[0]\n\n X, y = dataset[:]\n np.testing.assert_array_almost_equal(feat_vec.astype(np.float32), X)\n np.testing.assert_array_almost_equal(energies.astype(np.float32), y.flatten())\n del dataset\n\n e_max = energies.max()\n e_min = energies.min()\n\n norm_energies = (energies - e_min) / (e_max - e_min)\n\n dataset = SAMDataset(feat_vec, energies, norm_target=True, y_min=e_min, y_max=e_max)\n\n X, y = dataset[:]\n np.testing.assert_array_almost_equal(feat_vec.astype(np.float32), X)\n np.testing.assert_array_almost_equal(norm_energies.astype(np.float32), y.flatten())\n\ndef test_SAMdatasetND():\n dataset = SAMDataset(feat_vec, poly)\n\n assert dataset.X_dim == 36\n assert dataset.y_dim == poly.shape[1]\n assert len(dataset) == feat_vec.shape[0]\n\n X, y = dataset[:]\n np.testing.assert_array_almost_equal(feat_vec.astype(np.float32), X)\n np.testing.assert_array_almost_equal(poly.astype(np.float32), y)\n del dataset\n\n e_max = poly.max(axis=0)\n e_min = poly.min(axis=0)\n\n norm_poly = (poly - e_min) / (e_max - e_min)\n\n dataset = SAMDataset(feat_vec, poly, norm_target=True, y_min=e_min, y_max=e_max)\n\n X, y = dataset[:]\n np.testing.assert_array_almost_equal(feat_vec.astype(np.float32), X)\n np.testing.assert_array_almost_equal(norm_poly.astype(np.float32), y)\n\n\ndef test_Trainer():\n partition = partition_data(feat_vec, energies, n_groups=5)\n X_train, y_train, X_test, y_test = next(partition)\n\n train_dataset = SAMDataset(X_train, y_train)\n test_dataset = SAMDataset(X_test, y_test)\n\n trainer = Trainer(train_dataset, test_dataset, batch_size=200, epochs=10, learning_rate=0.01, n_patience=100)\n\n net = SAMNet(n_hidden=18, n_hidden_layer=2, dropout=0)\n criterion = torch.nn.MSELoss()\n\n trainer(net, criterion)\n\n\n","sub_path":"scratch/neural_net/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"233772784","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\n## CSV読み込み\ntrain = pd.read_csv(\"titanic/train.csv\")\ntest = pd.read_csv(\"titanic/test.csv\")\n\n### セル表示\n# train ## 全体\n# train.head(10) ## 先頭から10行目\n# train.describe() ## 統計量\n# train.info() ## 要約情報\n# train['Age'].isnull().values.sum() ## nullの件数\n\n### ヒストグラム\n# plt.hist(train['Age'].dropna(), bins=20)\n\n### 欠損値補完 (NULL -> AVG)\nmean = np.mean(train['Age'])\ntrain['Age'] = train['Age'].fillna(mean)\n\n### 定量化 (男 -> 1, 女 -> 2)\ntrain['Sex'] = train['Sex'].str.replace('female', '2')\ntrain['Sex'] = train['Sex'].str.replace('male', '1')\n\n### データセットの作成 (説明変数 -> X, 目的変数 -> Y)\nX = pd.DataFrame({'Pclass':train['Pclass'], 'Sex':train['Sex'], 'Age':train['Age']})\ny = pd.DataFrame({'Survived':train['Survived']})\n\n### データセットの分割\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=None)\n\n### 学習\nbest_score = 0\nfor gamma in [0.001, 0.01, 0.1, 1, 10, 100]:\n for C in [0.001, 0.01, 0.1, 1, 10, 100]:\n svm = SVC(gamma=gamma, C=C)\n svm.fit(X_train, y_train)\n score = svm.score(X_test, y_test)\n if score > best_score:\n best_score = score\n best_parameters = {'C':C, 'gamma':gamma}\nprint(\"Best score: \" + str(best_score))\nprint(\"Best parameters: \" + str(best_parameters))\n","sub_path":"Non-Linear-SVC.py","file_name":"Non-Linear-SVC.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"442850138","text":"# reverses the first k elements of an array\ndef flip(arr, k):\n for i in range(k//2):\n arr[i], arr[k-i-1] = arr[k-i-1], arr[i]\n \ndef pancake_sort(nums):\n sorted_nums = sorted(nums)\n k_values = []\n k = -1\n while nums != sorted_nums and k>=(len(nums)*-1):\n max_val = sorted_nums[k]\n if max_val == nums[k]:\n k-=1\n continue\n elif max_val == nums[0]:\n m = len(nums)+k+1\n flip(nums,m)\n k_values.append(m)\n k-=1\n else:\n for i in range(1,len(nums)):\n if nums[i] == max_val:\n flip(nums,i+1)\n k_values.append(i+1)\n break\n \n return(k_values)\n\n\nprint(pancake_sort([5,2,3,4,1,6]))","sub_path":"sort_algo_m6/pancake_sort.py","file_name":"pancake_sort.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"217922833","text":"import csv\nfrom django.core.files.storage import FileSystemStorage\nfrom django.db.utils import IntegrityError\nfrom .models import CodeList\n\n\ndef handle_uploaded_file(f, filename):\n with open(filename, 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n\n\ndef store_file(file_data, filename):\n with FileSystemStorage().open(filename, 'wb+') as f:\n for chunk in file_data.chunks():\n f.write(chunk)\n\n\ndef import_data(filename):\n with FileSystemStorage().open(filename, 'r') as file:\n csvfile = csv.reader(file)\n done = 0\n exist = []\n for row in csvfile:\n card = CodeList(serial_number=row[0], scratch_code=row[1], cost=row[2])\n try:\n card.save()\n done += 1\n except IntegrityError:\n exist.append(row)\n\n return done, exist\n","sub_path":"code_check/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"133133032","text":"\n# coding: utf-8\n\n# # Using conda to manage C++ libraries\n# \n# The [cffi_funs](https://github.com/phaustin/parallel_python_course/tree/master/code_examples/cffi_funs) folder shows how to set up a C++ file so that it compiled with [cmake](http://preshing.com/20170511/how-to-build-a-cmake-based-project/) and also [here](http://preshing.com/20170522/learn-cmakes-scripting-language-in-15-minutes/)\n# \n# The folder contains [these files](https://github.com/phaustin/parallel_python_course/blob/master/code_examples/cffi_funs/Readme_cffi_funs.rst)\n# \n# **Demo**\n# \n# Show how to build a conda archive with:\n# \n# conda build .\n# \n# and then upload it to your [Anaconda channel](https://anaconda.org/phaustin/dashboard)\n# \n# Where it can be installed into a conda environment with:\n# \n# conda install -c phaustin cffi_funs\n\n# # Using conda to manage python libraries\n# \n# The [cffi_practice](https://github.com/phaustin/parallel_python_course/tree/master/code_examples/cffi_practice)\n# folder shows how to install a simple python project using conda and [setuptools](http://setuptools.readthedocs.io/en/latest/setuptools.html)\n# \n# **Demo**\n# \n# Show how to build and upload cffi_practice to my conda channel\n# \n# The purpose of this module is to provide one function:\n# \n# cffi_practice.get_paths()\n# \n# That can be used to locate the library and header from cff_funs\n# \n# The get_paths function is defined in this package in the [__init__.py](https://github.com/phaustin/parallel_python_course/blob/master/code_examples/cffi_practice/cffi_practice/__init__.py) module.\n# \n# Try:\n# \n# conda install cff_practice -c phaustin\n# \n# Then:\n# \n# python -c 'import cffi_practice;print(cffi_practice.get_paths())'\n# \n# Which should output something like:\n# \n# {'libfile': '/Users/phil/mini36/lib/libcffi_funs.so', 'libdir': '/Users/phil/mini36/lib', 'includedir': '/Users/phil/mini36/include'}\n\n# ## Accessing the functions from python using CFFI\n# \n# The [C foreign function interface](https://cffi.readthedocs.io/en/latest/overview.html) provides a way to call the cffi_funs from python\n# \n# Here is an example that exposes the get_thread_id and get_proces_id functions from the cffi_fun package\n\n# In[ ]:\n\n\nfrom cffi import FFI\nfrom cffi_practice import get_paths\nfrom joblib import Parallel\n#\n# locate the library\n#\nlib_so_file=get_paths()['libfile']\nffi=FFI()\nffi.cdef(\"\"\"\n void get_thread_id(char *thread_id);\n void get_process_id(char *process_id);\n\"\"\")\n#\n# open the library file\n#\nlib = ffi.dlopen(lib_so_file)\nprint('found these functions in module: ',dir(lib))\n#\n# create a 25 character C array to hold the ouput\n#\narg_thread = ffi.new(\"char[]\",25) #(C++)\n#\n# copy the bytes into arg_thread (C++)\n#\nlib.get_thread_id(arg_thread) \n#\n# get the bytes into a python byte object\n#\nout_thread=ffi.string(arg_thread) #C++ to python\n#\n# turn the bytes into a utf-8 string\n#\nstr_out=out_thread.decode('utf-8') #python\n#\n# print it out\n#\nprint(f\"Here is the thread id in hex: -{str_out}-\")\n#\n# repeat for the process\n#\narg_process = ffi.new(\"char[]\",25) \nlib.get_process_id(arg_process)\nout_process=ffi.string(arg_process)\nstr_out=out_process.decode('utf-8')\nprint(f\"here is the process ide in base 10: -{str_out}-\")\n\n\n# ### Running this in a threadpool\n# \n# The following script uses joblib to create 10 jobs to call the cffi functions in parallel, returning\n# the pointers to the character array and convertingthem to python strings.\n\n# In[10]:\n\n\nnprocs=10\narg_list=[]\nfun_list=[]\ndict_list=[]\nfor i in range(nprocs):\n fun_list.append(lib.get_thread_id)\n result_var=ffi.new(\"char[]\",25)\n arg_list.append(result_var)\n dict_list.append({})\nptr_list=[[ffi.cast(\"char*\",item)] for item in arg_list]\njobs=list(zip(fun_list,ptr_list,dict_list))\nprint(f'here are the pointers to hold the ids: {ptr_list}\\n')\nwith Parallel(n_jobs=nprocs,backend='threading') as parallel:\n parallel(jobs)\nprint('here are the thread ids')\nfor item in ptr_list:\n out_thread=ffi.string(item[0]).decode('utf-8')\n print('thread id: ',out_thread)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"notebooks/python/04_cffi.py","file_name":"04_cffi.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"278462651","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 5 12:44:42 2019\n\n@author: yinger\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 30 16:44:46 2019\n\n@author: yinger\n\"\"\"\n\n#梯度下降法算\n# loss:\n#随机那种,先判断是否小于1/2,若大于直接成功;若小于,减小1/2-cos的值\n#由原来变化那种\n\nimport numpy as np\nimport random\nfrom scipy.spatial.distance import pdist\nimport copy\nfrom sympy import *\nimport tensorflow as tf\n\ndef grad_rotation(stand,seq_len_valid): \n '''\n in order to generate diverse adversarial sample for a same sample, we use this function to change gradient vector, the cos<> value between the\n new vector and the original one is within a random range(0.7,0.85).\n since vector has 109 demensions, it is difficult to control the vector by setting num randomly ,so we use GD method to find the value fastly. \n \n input: original gradeint in shape of (1,1000,109) ; valid length\n output: generated new gradient\n '''\n for i in range(seq_len_valid):\n delta=0.05\n num=2000\n g1=tf.Graph()\n with g1.as_default():\n vec=stand[0][i] # record the original vector as object \n vec_copy=copy.copy(vec) \n vec_tensor=tf.convert_to_tensor(vec_copy,dtype=tf.float64)\n g=tf.Variable(tf.random_uniform([109,],-1,1,dtype=tf.float64)) # initialize randomly\n numerator=tf.multiply(vec_tensor,g)\n numerator=tf.reduce_sum(numerator,0)\n denominator=(tf.linalg.norm(vec_tensor,ord=2))*(tf.linalg.norm(g,ord=2)) # define the cos=a*b/|a|*|b| in graph\n d=numerator/denominator\n theta=random.uniform(0.7,0.85) # object range\n loss=theta-d \n grad=(tf.gradients(loss,g))[0]\n learning_rate=0.3 \n new_g = tf.assign(g,(g - learning_rate * grad))\n init = tf.global_variables_initializer()\n \n \n with tf.Session(graph=g1) as sess: \n sess.run(init) \n d_origin=sess.run(d)\n if (d_origin>=theta):\n g_value=sess.run(g)\n else:\n while(d_origin<=0): \n sess.run(init)\n d_origin=sess.run(d)\n \n for j in range(num):\n sess.run(new_g) \n d_value=sess.run(d)\n if (theta-d_value 1:\n for f in range(2, n + 1):\n result *= f\n return result\n\ndef factorialRecurse(n):\n if n <= 1:\n return 1\n else:\n return n * factorialRecurse(n-1)\n\ndef fibanacchi(n):\n if n < 2:\n return n\n else:\n return fibanacchi(n - 1) + fibanacchi(n - 2)\n\ndef fibanacchiFast(n):\n if n == 0:\n result = 0\n elif n == 1:\n result = 1\n else:\n n_minus1 = 1\n n_minus2 = 0\n for f in range(1, n):\n result = n_minus2 + n_minus1\n n_minus2 = n_minus1\n n_minus1 = result\n return result\n\n# for i in range(130):\n# print(i, factorialRecurse(i))\n\nfor i in range(36):\n print(i, fibanacchiFast(i))","sub_path":"ModulesAndImport/scope.py","file_name":"scope.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"310857135","text":"clusters_schema = {\n # Schema definition, based on Cerberus grammar. Check the Cerberus project\n # (https://github.com/nicolaiarocci/cerberus) for details.\n 'name': {\n 'type': 'string',\n 'minlength': 1,\n 'maxlength': 20,\n },\n 'cloud': {\n 'type': 'objectid',\n 'data_relation': {\n 'resource': 'clouds',\n 'field': '_id',\n 'embeddable': True,\n },\n },\n 'params': {\n 'type': 'dict',\n },\n 'status': {\n 'type': 'string',\n 'minlength': 1,\n 'maxlength': 20,\n 'allowed': [\"Scheduled\", \"Error\",\n \"Deploying\", \"Available\"],\n 'default': \"Scheduled\",\n },\n\n}\n\nclusters = {\n 'schema': clusters_schema\n}\n","sub_path":"clusters.py","file_name":"clusters.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"579689493","text":"from PySide2 import QtCore, QtWidgets\nfrom PySide2.QtWidgets import QSplitter\nfrom nexus_constructor.instrument_view import InstrumentView\nfrom ui.treeview_tab import ComponentTreeViewTab\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.resize(1280, 720)\n self.central_widget = QtWidgets.QWidget(MainWindow)\n\n self.splitter = QSplitter(self.central_widget)\n self.splitter.setChildrenCollapsible(False)\n self.splitter.setOpaqueResize(True)\n\n self.main_grid_layout = QtWidgets.QGridLayout(self.central_widget)\n self.main_grid_layout.addWidget(self.splitter)\n self.main_grid_layout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)\n\n self.tab_widget = QtWidgets.QTabWidget(self.central_widget)\n self.tab_widget.setMinimumSize(QtCore.QSize(500, 0))\n self._set_up_component_tree_view()\n self._set_up_silx_view()\n self.splitter.addWidget(self.tab_widget)\n\n self._set_up_3d_view()\n\n MainWindow.setCentralWidget(self.central_widget)\n\n self._set_up_menus(MainWindow)\n\n self.retranslateUi(MainWindow)\n self.tab_widget.setCurrentIndex(0)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n self.splitter.setStretchFactor(0, 0)\n self.splitter.setStretchFactor(1, 1)\n\n def _set_up_3d_view(self):\n self.sceneWidget = InstrumentView(self.splitter)\n self.sceneWidget.setMinimumSize(QtCore.QSize(600, 0))\n self.splitter.addWidget(self.sceneWidget)\n\n def _set_up_silx_view(self):\n self.silx_tab = QtWidgets.QWidget()\n self.silx_tab_layout = QtWidgets.QGridLayout(self.silx_tab)\n self.tab_widget.addTab(self.silx_tab, \"\")\n\n def _set_up_component_tree_view(self):\n self.component_tree_view_tab = ComponentTreeViewTab(parent=self)\n self.tab_widget.addTab(self.component_tree_view_tab, \"\")\n\n def _set_up_menus(self, MainWindow):\n self.menu_bar = QtWidgets.QMenuBar()\n self.menu_bar.setGeometry(QtCore.QRect(0, 0, 1280, 720))\n self.file_menu = QtWidgets.QMenu(self.menu_bar)\n MainWindow.setMenuBar(self.menu_bar)\n self.status_bar = QtWidgets.QStatusBar(MainWindow)\n MainWindow.setStatusBar(self.status_bar)\n self.open_nexus_file_action = QtWidgets.QAction(MainWindow)\n self.open_json_file_action = QtWidgets.QAction(MainWindow)\n self.export_to_nexus_file_action = QtWidgets.QAction(MainWindow)\n self.export_to_filewriter_JSON_action = QtWidgets.QAction(MainWindow)\n self.export_to_forwarder_JSON_action = QtWidgets.QAction(MainWindow)\n self.file_menu.addAction(self.open_nexus_file_action)\n self.file_menu.addAction(self.open_json_file_action)\n self.file_menu.addAction(self.export_to_nexus_file_action)\n self.file_menu.addAction(self.export_to_filewriter_JSON_action)\n self.file_menu.addAction(self.export_to_forwarder_JSON_action)\n self.menu_bar.addAction(self.file_menu.menuAction())\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(\n QtWidgets.QApplication.translate(\n \"MainWindow\", \"NeXus Constructor\", None, -1\n )\n )\n self.tab_widget.setTabText(\n self.tab_widget.indexOf(self.component_tree_view_tab),\n QtWidgets.QApplication.translate(\"MainWindow\", \"Components\", None, -1),\n )\n self.tab_widget.setTabText(\n self.tab_widget.indexOf(self.silx_tab),\n QtWidgets.QApplication.translate(\n \"MainWindow\", \"NeXus File Layout\", None, -1\n ),\n )\n self.file_menu.setTitle(\n QtWidgets.QApplication.translate(\"MainWindow\", \"File\", None, -1)\n )\n self.open_nexus_file_action.setText(\n QtWidgets.QApplication.translate(\"MainWindow\", \"Open NeXus file\", None, -1)\n )\n self.open_json_file_action.setText(\n QtWidgets.QApplication.translate(\n \"MainWindow\", \"Open Filewriter JSON file\", None, -1\n )\n )\n self.export_to_nexus_file_action.setText(\n QtWidgets.QApplication.translate(\n \"MainWindow\", \"Export to NeXus file\", None, -1\n )\n )\n self.export_to_filewriter_JSON_action.setText(\n QtWidgets.QApplication.translate(\n \"MainWindow\", \"Export to Filewriter JSON\", None, -1\n )\n )\n self.export_to_forwarder_JSON_action.setText(\n QtWidgets.QApplication.translate(\n \"MainWindow\", \"Export to Forwarder JSON\", None, -1\n )\n )\n","sub_path":"ui/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"444925320","text":"from collections import namedtuple\nfrom pythosport.DAL.sport import Sport\nfrom pythosport.DAL.aliases import Aliases\nfrom pythosport.DAL.util_excel import worksheet_to_iterator\nfrom pythosport.DAL import util_dates\nfrom pythosport.DAL import util_scores\nfrom utils import printtime\n\n\nAllData = namedtuple(\"AllData\", \"sports persons teams\")\n\n\ndef excel_to_data(wb):\n printtime('Start import.')\n sports = import_sports(wb['Sport'])\n import_events(wb['Evenement'], sports=sports)\n import_categories(wb['Categorie'], sports=sports)\n import_disciplines(wb['Discipline'], sports=sports)\n printtime('Sports-events-categories-disciplines done.')\n\n persons = import_aliases(wb['AliasPersoon'])\n teams = import_aliases(wb['AliasTeam'])\n printtime('Aliases done.')\n\n import_results(wb['Resultaat'], sports=sports, persons=persons, teams=teams)\n printtime('Results done.')\n\n run_checks(sports)\n printtime('Checks done.')\n\n util_scores.add_scores(sports)\n printtime('Scores added.')\n\n all_data = AllData(sports=sports, persons=persons, teams=teams)\n\n return all_data\n\n\ndef run_checks(sports):\n for sport in sports.values():\n sport.check_results_roles()\n sport.build_editions()\n\n\ndef import_sports(ws):\n header = [\"Sport\", \"Ploegsport\", \"Seizoen\"]\n iter_rows = worksheet_to_iterator(ws, required_header=header)\n\n d = dict()\n for (name, team_sport_num, season) in iter_rows:\n d[name] = Sport(name=name, team_sport_num=team_sport_num, season=season)\n return d\n\n\ndef import_events(ws, sports=None):\n header = [\"Sport\", \"Evenement\", \"Score\", \"Type\", \"Volgorde\", \"Link\"]\n iter_rows = worksheet_to_iterator(ws, required_header=header)\n\n for (sport_name, event_name, score, event_type, order, link) in iter_rows:\n sport = sports[sport_name]\n sport.add_event(name=event_name, score=score, event_type=event_type, order=order, link=link)\n\n\ndef import_categories(ws, sports=None):\n header = [\"Sport\", \"Naam\", \"Score\", \"RolToegelaten\", \"Volgorde\"]\n iter_rows = worksheet_to_iterator(ws, required_header=header)\n\n for (sport_name, category_name, score, allowed_roles, order) in iter_rows:\n sport = sports[sport_name]\n sport.add_category(name=category_name, score=score, allowed_roles=allowed_roles, order=order)\n\n\ndef import_disciplines(ws, sports=None):\n header = [\"Sport\", \"Discipline\", \"Score\", \"Klassement\", \"Aantal\", \"Volgorde\"]\n iter_rows = worksheet_to_iterator(ws, required_header=header)\n\n for (sport_name, discipline_name, score, score_calc, role_limits, order) in iter_rows:\n sport = sports[sport_name]\n sport.add_discipline(name=discipline_name, score=score, score_calc=score_calc, role_limits=role_limits, order=order)\n\n\ndef import_aliases(ws):\n header = [\"Naam\", \"Alias\"]\n iter_rows = worksheet_to_iterator(ws, required_header=header)\n aliases = Aliases()\n\n for (name, alias) in iter_rows:\n aliases.add_alias(name=name, alias=alias)\n\n return aliases\n\n\ndef import_results(ws, sports=None, persons=None, teams=None):\n header = [\"Sport\", \"Evenement\", \"Datums\", \"Categorie\", \"Discipline\", \"Positie\", \"Exaequo\", \"Geslacht\", \"NaamPersoon\", \"NaamTeam\", \"Commentaar\"]\n iter_rows = worksheet_to_iterator(ws, required_header=header)\n\n for ix, row in enumerate(iter_rows):\n try:\n import_result(row, sports=sports, persons=persons, teams=teams)\n except (ValueError, KeyError) as e:\n print('Excel row: %s' % (ix+1))\n print(row)\n print(e)\n\n\ndef import_result(row, sports=None, persons=None, teams=None):\n\n sport_name, event, dates_xl, category, discipline, position, exaequo, role, person, team, comment = row\n\n sport = sports[sport_name]\n\n sport.add_result(event=str(event),\n dates=util_dates.text_to_yearmonths(dates_xl),\n category=str(category),\n discipline=str(discipline),\n position=position,\n exaequo=exaequo,\n role=role,\n person=person,\n team=team,\n comment=comment,\n persons=persons,\n teams=teams)\n","sub_path":"pythosport/DAL/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"123159237","text":"# 菜品信息管理视图文件\nfrom datetime import datetime\n\nfrom django.core.paginator import Paginator\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\n\nfrom myadmin.models import Product, Shop, Category\nimport time,os\n\n# Create your views here.\n\ndef index(request, pIndex=1):\n # 浏览信息\n umod = Product.objects\n ulist = umod.filter(status__lt=9)\n # 获取并判断搜索条件\n mywhere = []\n kw = request.GET.get('keyword', None)\n if kw:\n ulist = ulist.filter(name__contains=kw)\n mywhere.append('keyword=' + kw)\n # 获取并判断类别搜索条件\n cid = request.GET.get('category_id', None)\n if cid:\n ulist = ulist.filter(category_id=cid)\n mywhere.append('category_id_=' + cid)\n # 执行分页\n pIndex = int(pIndex)\n page = Paginator(ulist,10) # 每页10条数据\n maxpages = page.num_pages # 获取最大页数\n if pIndex > maxpages:\n pIndex = maxpages\n if pIndex < 1:\n pIndex = 1\n list2 = page.page(pIndex)\n plist = page.page_range\n for vo in list2:\n sob = Shop.objects.get(id=vo.shop_id)\n vo.shopname = sob.name\n cob = Category.objects.get(id=vo.category_id)\n vo.categoryname = cob.name\n\n context = {'productlist': list2, 'plist': plist, 'pIndex': pIndex, 'maxpage': maxpages, \"mywhere\": mywhere}\n return render(request, 'myadmin/product/index.html', context)\n\n\ndef add(request):\n # 获取当前所有店铺信息\n slist = Shop.objects.values('id', 'name')\n context = {'shoplist': slist}\n return render(request, 'myadmin/product/add.html', context)\n\n\ndef insert(request):\n # 执行信息添加\n try:\n ob = Product()\n ob.shop_id = request.POST['shop_id']\n ob.name = request.POST['name']\n ob.category_id = request.POST['category_id']\n ob.price = request.POST['price']\n # 封面图片上传\n myfile = request.FILES.get('cover_pic', '')\n if not myfile:\n return HttpResponse(\"没有菜品封面上传文件信息\")\n cover_pic = str(time.time()) + '_' + myfile.name.split('_').pop()\n destination = open('./static/uploads/product/' + cover_pic, 'wb+')\n for chunk in myfile.chunks(): # 分块写入文件\n destination.write(chunk)\n destination.close()\n ob.status = 1\n ob.cover_pic = cover_pic\n ob.create_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n ob.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n ob.save()\n context = {'info': \"添加成功\"}\n except Exception as err:\n print(err)\n context = {'info': \"添加失败\"}\n return render(request, 'myadmin/info.html', context)\n\n\ndef delete(request, pid=0):\n # 执行信息删除\n try:\n ob = Product.objects.get(id=pid)\n ob.status = 9\n ob.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n ob.save()\n context = {'info': \"删除成功\"}\n except Exception as err:\n print(err)\n context = {'info': \"删除失败\"}\n return render(request, 'myadmin/info.html', context)\n\n\ndef edit(request, pid=0):\n # 编辑表单\n try:\n ob = Product.objects.get(id=pid)\n context = {'product': ob}\n # 获取当前所有店铺信息\n slist = Shop.objects.values('id', 'name')\n context['shoplist'] = slist\n return render(request, 'myadmin/product/edit.html', context)\n except Exception as err:\n print(err)\n context = {'info': \"没有找到要修改的信息\"}\n return render(request, 'myadmin/info.html', context)\n\n\ndef update(request, pid=0):\n # 执行信息编辑\n try:\n ob = Product.objects.get(id=pid)\n ob.shop_id = request.POST['shop_id']\n ob.name = request.POST['name']\n ob.category_id = request.POST['category_id']\n ob.price = request.POST['price']\n # 获取原图片\n oldpicname = request.POST['oldpicname']\n # 封面图片上传\n myfile = request.FILES.get('cover_pic', '')\n if not myfile:\n cover_pic = oldpicname\n else:\n cover_pic = str(time.time()) + '_' + myfile.name.split('_').pop()\n destination = open('./static/uploads/product/' + cover_pic, 'wb+')\n for chunk in myfile.chunks(): # 分块写入文件\n destination.write(chunk)\n destination.close()\n ob.cover_pic = cover_pic\n ob.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n ob.save()\n context = {'info': \"修改成功\"}\n # 判断并删除老图片\n if myfile:\n os.remove('./static/uploads/product/' + oldpicname)\n\n except Exception as err:\n print(err)\n context = {'info': \"修改失败\"}\n if myfile:\n os.remove('./static/uploads/product/' + cover_pic)\n return render(request, 'myadmin/info.html', context)\n","sub_path":"myadmin/views/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":4960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"420884723","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$',views.demo, name=\"intro\"),\n url(r'^page=(?P.+)$', views.main, name=\"main\"),\n url(r'^route/addnew$', views.addroute, name=\"addroute\"),\n url(r'^route/(?P.+)/delete$', views.routedelete, name='routedelete'),\n url(r'^route/(?P.+)/edit$', views.routeedit, name='routeedit'),\n url(r'^cargo/$', views.cargo_list, name='cargo'),\n url(r'^cargo/(?P.+)/delete$', views.cargodelete, name='cargodelete'),\n url(r'^cargo/(?P.+)/edit$', views.cargoedit, name='cargoedit'),\n url(r'^cargo/addnew$', views.addcargo, name='addcargo'),\n url(r'^ships/$', views.ships_list, name='ships'),\n url(r'^ships/addnew$', views.addship, name='addships'),\n url(r'^ships/(?P.+)/delete$', views.shipdelete, name='shipdelete'),\n url(r'^ships/(?P.+)/edit$', views.shipedit, name='shipedit'),\n\n url(r'^caps/$', views.caps_list, name='caps'),\n url(r'^caps/addnew$', views.addcap, name='addcap'),\n url(r'^caps/(?P.+)/delete$', views.capdelete, name='capdelete'),\n url(r'^caps/(?P.+)/edit$', views.capedit, name='capedit'),\n\n url(r'^task2/$', views.task2, name=\"task2\")\n]","sub_path":"5th/BD/laba2/ships/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"597611783","text":"from flask import Flask, request, redirect\r\n\r\n\r\nimport socket\r\nlocal_host = socket.gethostbyname(socket.gethostname())\r\ntip = '''Only receive \"content_type='text; charset=utf-8'\" and \"Accept-Encoding='utf-8'\"!!!\r\n[Handle Message & Reply] POST text message to http://{host}:5000/Chat/\r\n[Run Python Codes] POST Python codes to http://{host}:5000/Python/\r\n[Search data] POST key word to http://{host}:5000/Search/'''.format(host=local_host)\r\n\r\n\r\ndef chat_reply(msg):\r\n from __Xiaoya__ import xiaoya\r\n x = xiaoya('xiaoya', 17, 'books')\r\n return x.reply(msg).strip('   \\n ')\r\n\r\ndef chat_send(msg):\r\n from __Message__ import get_message\r\n return get_message()\r\n\r\ndef run_codes(codes):\r\n from __RunPY__ import run_py_codes\r\n return run_py_codes(codes)\r\n\r\ndef decode(data):\r\n try:\r\n codes = data.decode('utf-8')\r\n except:\r\n codes = data.decode('gb2312')\r\n return codes\r\n\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef home_page():\r\n return tip.replace('\\n', '
')\r\n\r\n@app.route('/Chat/', methods=['GET', 'POST'])\r\ndef chat_with_xiaoya():\r\n if request.method =='GET':\r\n return 'Now IP=' + request.remote_addr + ', you can POST a chat-message to me.'\r\n if request.method == 'POST':\r\n msg = decode(request.data)\r\n \r\n if msg == '':\r\n print('Nothing received.')\r\n return ''\r\n else:\r\n return chat_reply(msg)\r\n \r\n@app.route('/Send/', methods=['GET', 'POST'])\r\ndef send_with_xiaoya():\r\n if request.method =='GET':\r\n return 'This is for server itself, other language could POST a message ask me which is needed to send directly.'\r\n if request.method == 'POST':\r\n msg = decode(request.data)\r\n return chat_send(msg)\r\n\r\n@app.route('/Search/', methods=['GET', 'POST'])\r\ndef search_data():\r\n if request.method =='GET':\r\n return 'Now, you can POST search-words to me.'\r\n if request.method == 'POST':\r\n msg = decode(request.data)\r\n\r\n if msg == '':\r\n return ''\r\n else:\r\n from __Analysis__ import search\r\n try:\r\n return search(msg)\r\n except Exception as e:\r\n print(e)\r\n return ''\r\n\r\n@app.route('/Python/', methods=['GET', 'POST'])\r\ndef run_python():\r\n if request.method == 'GET':\r\n return redirect(\"https://docs.python.org/3/library/index.html\", code=302) #\"Now, you can POST codes to me.\"\r\n if request.method == 'POST':\r\n codes = decode(request.data)\r\n\r\n if codes == '':\r\n print('Nothing received.')\r\n return ''\r\n else:\r\n return run_codes(codes)\r\n\r\n\r\ndef split_sentence():\r\n from Plugins.Extensions.GetEnglish.SplitSentence import main as _split\r\n msg = decode(request.data) \r\n return _split(msg.replace(' ', ' '))\r\napp.add_url_rule('/Tools/split', view_func=split_sentence, methods=['POST'])\r\n\r\ndef translate_sentence():\r\n from Plugins.Extensions.GetEnglish.SplitSentenceAndTranslate import main as _translate\r\n msg = decode(request.data)\r\n return _translate(msg.replace(' ', ' '))\r\napp.add_url_rule('/Tools/translate', view_func=translate_sentence, methods=['POST'])\r\n\r\ndef tools_run_python():\r\n msg = decode(request.data)\r\n return run_codes(msg)\r\napp.add_url_rule('/Tools/python', view_func=tools_run_python, methods=['POST'])\r\n\r\n\r\napp.register_error_handler(500, lambda e: '') # Fail to run the codes!\\nPlease check it carefully.\r\n\r\nif __name__ == '__main__':\r\n print(tip)\r\n app.run(host='0.0.0.0')\r\n","sub_path":"@Xiaoya/Python/@API_server.py","file_name":"@API_server.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"600726602","text":"import random\na = int(input(\"Введите длину списка: \"))\nb = int(input(\"Введите минимальное значение списка: \"))\nc = int(input(\"Введите максимальное значение списка: \"))\nlist1 = []\n\ndef rgen():\n for i in range(a):\n if b < c:\n list1.append(random.randint(b, c))\n else:\n list1.append(random.randint(c, b))\n print(list1)\n\ndef nfunc():\n list2 = list1.copy()\n cnum = int(input(\"Введите число от 0 до \" + str(a - 1) + \" \"))\n if cnum >= a:\n print(\"Введенное число выходит за пределы списка!\")\n nfunc()\n else:\n list1.pop(cnum)\n list1.insert(cnum, cnum)\n print(\"Модифицированный список \" + str(list1))\n print(\"Число \" + str(list2[cnum]) + \" замененно на \" + str(cnum))\n\n\nrgen(), nfunc()","sub_path":"HM9_Fchange.py","file_name":"HM9_Fchange.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"619168158","text":"\"\"\"djangostripe URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom payments.views import(home,\n\tstripe_config,\n\tcreate_checkout_session,\n\tSuccess,\n\tCancelled)\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',home,name='home'),\n path('config/',stripe_config,name='stripe_config'),\n path('create-checkout-session/',create_checkout_session,name='create_checkout_session'),\n path('success/',Success,name='Success'),\n path('cancelled/',Cancelled,name='Cancelled'),\n\n]\n","sub_path":"djangostripe/djangostripe/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"557945014","text":"# Copyright (c) 2019 Aiven, Helsinki, Finland. https://aiven.io/\nfrom contextlib import suppress\nfrom distutils.version import LooseVersion # pylint:disable=deprecated-module\nfrom myhoard.errors import XtraBackupError\nfrom myhoard.util import get_mysql_version, mysql_cursor\nfrom rohmu.util import increase_pipe_capacity, set_stream_nonblocking\nfrom typing import Optional\n\nimport base64\nimport logging\nimport os\nimport re\nimport select\nimport shutil\nimport subprocess\nimport tempfile\nimport threading\n\n# Number of seconds to allow for database operations to complete\n# while running the OPTIMIZE TABLE mitigation\nCURSOR_TIMEOUT_DURING_OPTIMIZE: int = 120\n\n\nclass AbortRequested(Exception):\n \"\"\"The base backup operation was aborted by request.\"\"\"\n\n def __init__(self, reason: str) -> None:\n super().__init__(f\"reason: {reason}\")\n self.reason = reason\n\n\nclass BasebackupOperation:\n \"\"\"Creates a new basebackup. Provides callback for getting progress info, extracts\n details of the created backup (like the binlog position up to which the backup has\n data) and executes callback that can read the actual backup data. This class does\n not handle persistence of the backup or any metadata. Note that the stream handler\n callback is executed on another thread so that the main thread can manage backup\n state information while the data is being persisted.\"\"\"\n\n current_file_re = re.compile(r\" Compressing, encrypting and streaming (.*?)( to )?( up to position \\d+)?$\")\n binlog_info_re = re.compile(\n r\"binlog_pos = filename '(?P.+)', position '(?P\\d+)'(, GTID of the last change '(?P.+)')?$\"\n )\n lsn_re = re.compile(r\" Transaction log of lsn \\((\\d+)\\) to \\((\\d+)\\) was copied.$\")\n progress_file_re = re.compile(r\"(ib_buffer_pool$)|(ibdata\\d+$)|(.*\\.CSM$)|(.*\\.CSV$)|(.*\\.ibd$)|(.*\\.sdi$)|(undo_\\d+$)\")\n\n def __init__(\n self,\n *,\n encryption_algorithm,\n encryption_key,\n mysql_client_params,\n mysql_config_file_name,\n mysql_data_directory,\n optimize_tables_before_backup=False,\n progress_callback=None,\n stats,\n stream_handler,\n temp_dir,\n ):\n self.abort_reason = None\n self.binlog_info = None\n self.current_file = None\n self.data_directory_filtered_size = None\n self.data_directory_size_end: Optional[int] = None\n self.data_directory_size_start: Optional[int] = None\n self.encryption_algorithm = encryption_algorithm\n self.encryption_key = encryption_key\n self.log = logging.getLogger(self.__class__.__name__)\n self.lsn_dir = None\n self.lsn_info = None\n self.mysql_client_params = mysql_client_params\n with open(mysql_config_file_name, \"r\") as config:\n self.mysql_config = config.read()\n self.mysql_data_directory = mysql_data_directory\n self.number_of_files = 0\n self.optimize_tables_before_backup = optimize_tables_before_backup\n self.proc = None\n self.processed_original_bytes = 0\n self.progress_callback = progress_callback\n self.stats = stats\n self.stream_handler = stream_handler\n self.temp_dir: Optional[str] = None\n self.temp_dir_base = temp_dir\n\n def abort(self, reason):\n \"\"\"Aborts ongoing backup generation\"\"\"\n self.abort_reason = reason\n\n def create_backup(self):\n self.abort_reason = None\n self.data_directory_size_start, self.data_directory_filtered_size = self._get_data_directory_size()\n self._update_progress()\n if self.optimize_tables_before_backup:\n self._optimize_tables()\n\n # Write encryption key to file to avoid having it on command line. NamedTemporaryFile has mode 0600\n with tempfile.NamedTemporaryFile(\n dir=self.temp_dir_base, delete=True, prefix=\"encrkey\", suffix=\"bin\"\n ) as encryption_key_file:\n encryption_key_file.write(base64.b64encode(self.encryption_key))\n encryption_key_file.flush()\n\n # Create new configuration file that has original MySQL config plus user and password\n # for connecting to it to avoid having those on command line\n with tempfile.NamedTemporaryFile(\n dir=self.temp_dir_base, delete=True, prefix=\"mysql\", mode=\"w\", suffix=\"conf\"\n ) as mysql_config_file:\n mysql_config_file.write(self.mysql_config)\n client_params_str = \"\\n\".join(f\"{k}={v}\" for k, v in self.mysql_client_params.items())\n mysql_config_file.write(f\"\\n[client]\\n{client_params_str}\\n\")\n mysql_config_file.flush()\n\n self.temp_dir = tempfile.mkdtemp(dir=self.temp_dir_base, prefix=\"xtrabackup\")\n self.lsn_dir = tempfile.mkdtemp(dir=self.temp_dir_base, prefix=\"xtrabackupmeta\")\n command_line = [\n \"xtrabackup\",\n # defaults file must be given with --defaults-file=foo syntax, space here does not work\n f\"--defaults-file={mysql_config_file.name}\",\n \"--backup\",\n \"--compress\",\n \"--encrypt\",\n self.encryption_algorithm,\n \"--encrypt-key-file\",\n encryption_key_file.name,\n \"--no-version-check\",\n \"--stream\",\n \"xbstream\",\n \"--target-dir\",\n self.temp_dir,\n \"--extra-lsndir\",\n self.lsn_dir,\n ]\n\n with self.stats.timing_manager(\"myhoard.basebackup.xtrabackup_backup\"):\n with subprocess.Popen(\n command_line, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n ) as xtrabackup:\n self.proc = xtrabackup\n self._process_input_output()\n\n self.data_directory_size_end, self.data_directory_filtered_size = self._get_data_directory_size()\n self._update_progress(estimated_progress=100)\n\n def _optimize_tables(self) -> None:\n params = dict(self.mysql_client_params)\n params[\"timeout\"] = CURSOR_TIMEOUT_DURING_OPTIMIZE\n with mysql_cursor(**params) as cursor:\n version = get_mysql_version(cursor)\n if LooseVersion(version) < LooseVersion(\"8.0.29\"):\n return\n\n # allow OPTIMIZE TABLE to run on tables without primary keys\n cursor.execute(\"SET @@SESSION.sql_require_primary_key = 0;\")\n\n def unescape_to_utf8(escaped: str) -> Optional[str]:\n ret = re.sub(r\"@([0-9a-fA-F]{4})\", lambda m: chr(int(m.group(1), 16)), escaped)\n ret = re.sub(\n r\"@([0-9a-fA-F])([a-zA-Z])\", lambda m: chr(ord(m.group(2)) + 121 + 20 * int(m.group(1), 16)), ret\n )\n if \"`\" in ret or \"\\\\\" in ret:\n # bail out so we don't unescape ourselves below\n return None\n return ret\n\n database_and_tables = []\n cursor.execute(\"SELECT NAME FROM INFORMATION_SCHEMA.INNODB_TABLES WHERE TOTAL_ROW_VERSIONS > 0\")\n while True:\n row = cursor.fetchone()\n if not row:\n break\n db_and_table = row[\"NAME\"].split(\"/\")\n database = unescape_to_utf8(db_and_table[0])\n table = unescape_to_utf8(db_and_table[1])\n if database is None or table is None:\n self.log.warning(\"Could not decode database/table name of '%s'\", row[\"NAME\"])\n continue\n database_and_tables.append((database, table))\n\n for database, table in database_and_tables:\n self.stats.increase(metric=\"myhoard.basebackup.optimize_table\")\n self.log.info(\"Optimizing table %r.%r\", database, table)\n # sending it as parameters doesn't work\n cursor.execute(f\"OPTIMIZE TABLE `{database}`.`{table}`\")\n cursor.execute(\"COMMIT\")\n\n def _get_data_directory_size(self):\n total_filtered_size = 0\n total_size = 0\n for dirpath, _dirnames, filenames in os.walk(self.mysql_data_directory):\n for filename in filenames:\n full_file_name = os.path.join(dirpath, filename)\n try:\n file_size = os.path.getsize(full_file_name)\n total_size += file_size\n if self.progress_file_re.search(filename):\n total_filtered_size += file_size\n except OSError as ex:\n self.log.warning(\"Failed to get size for %r: %r\", full_file_name, ex)\n\n return total_size, total_filtered_size\n\n def _process_input_output(self):\n assert self.proc is not None\n assert self.proc.stdout is not None\n assert self.proc.stderr is not None\n increase_pipe_capacity(self.proc.stdout, self.proc.stderr)\n set_stream_nonblocking(self.proc.stderr)\n\n reader_thread = OutputReaderThread(stats=self.stats, stream_handler=self.stream_handler, stream=self.proc.stdout)\n reader_thread.start()\n\n pending_output = b\"\"\n exit_code = None\n try:\n while exit_code is None:\n rlist, _, _ = select.select([self.proc.stderr], [], [], 0.2)\n for fd in rlist:\n content = fd.read()\n if content:\n if pending_output:\n content = pending_output + content\n lines = content.splitlines(keepends=True)\n for line in lines[:-1]:\n self._process_output_line(line)\n\n # Don't process partial lines\n if b\"\\n\" not in lines[-1]:\n pending_output = lines[-1]\n else:\n self._process_output_line(lines[-1])\n pending_output = b\"\"\n exit_code = self.proc.poll()\n if reader_thread.exception:\n raise reader_thread.exception # pylint: disable=raising-bad-type\n if self.abort_reason:\n raise AbortRequested(self.abort_reason)\n\n pending_output += self.proc.stderr.read() or b\"\"\n if exit_code is not None and pending_output:\n for line in pending_output.splitlines():\n self._process_output_line(line)\n # Process has exited but reader thread might still be processing stdout. Wait for\n # the thread to exit before proceeding\n if exit_code is not None:\n self.log.info(\"Process has exited, joining reader thread\")\n reader_thread.join()\n reader_thread = None\n\n if exit_code == 0:\n self._process_binlog_info()\n\n except AbortRequested as ex:\n self.log.info(\"Abort requested: %s\", ex.reason)\n raise\n except Exception as ex:\n pending_output += self.proc.stderr.read() or b\"\"\n self.log.error(\"Error %r occurred while creating backup, output: %r\", ex, pending_output)\n raise ex\n finally:\n # If the process isn't dead yet make sure it is now\n if exit_code is None:\n with suppress(Exception):\n self.proc.kill()\n with suppress(Exception):\n self.proc.stdout.close()\n with suppress(Exception):\n self.proc.stderr.close()\n self.log.info(\"Joining output reader thread...\")\n # We've closed stdout so the thread is bound to exit without any other calls\n if reader_thread:\n reader_thread.join()\n self.log.info(\"Thread joined\")\n if self.lsn_dir:\n shutil.rmtree(self.lsn_dir)\n if self.temp_dir:\n shutil.rmtree(self.temp_dir)\n self.proc = None\n\n if exit_code != 0:\n self.log.error(\"xtrabackup exited with non-zero exit code %s: %r\", exit_code, pending_output)\n raise XtraBackupError(f\"xtrabackup failed with code {exit_code}\")\n\n # Reader thread might have encountered an exception after xtrabackup exited if it hadn't\n # yet finished storing data to backup location\n if reader_thread and reader_thread.exception:\n raise reader_thread.exception # pylint: disable=raising-bad-type\n\n def _process_output_line(self, line):\n line = line.rstrip()\n if not line:\n return\n\n try:\n line = line.decode(\"utf-8\", \"strict\")\n except UnicodeDecodeError:\n line = line.decode(\"iso-8859-1\")\n\n if (\n not self._process_output_line_new_file(line)\n and not self._process_output_line_file_finished(line)\n and not self._process_output_line_lsn_info(line)\n ):\n if any(key in line for key in [\"[ERROR]\", \" Failed \", \" failed \", \" Invalid \"]):\n self.log.error(\"xtrabackup: %r\", line)\n else:\n self.log.info(\"xtrabackup: %r\", line)\n\n def _process_output_line_new_file(self, line):\n match = self.current_file_re.search(line)\n if match and (\"Done:\" not in line):\n self.current_file = match.group(1)\n if self.current_file != \"\":\n self.log.info(\"Started processing file %r\", self.current_file)\n return True\n return False\n\n def _process_output_line_file_finished(self, line):\n if not (line.endswith(\" ...done\") or (\"Done:\" in line)):\n return False\n\n if not self.current_file:\n self.log.warning(\"Processing of file finished but no file was being tracked: %r\", line)\n elif self.current_file != \"\":\n self.number_of_files += 1\n full_name = os.path.join(self.mysql_data_directory, self.current_file)\n try:\n file_size = os.path.getsize(full_name)\n self.processed_original_bytes += file_size\n self._update_progress(last_file_name=self.current_file, last_file_size=file_size)\n self.log.info(\"Processing %r finished, file size %s bytes\", self.current_file, file_size)\n except OSError as ex:\n self.log.warning(\"Failed to get size for %r to update progress: %r\", full_name, ex)\n\n self.current_file = None\n return True\n\n def _process_binlog_info(self) -> None:\n assert self.lsn_dir\n\n binlog_file_path = os.path.join(self.lsn_dir, \"xtrabackup_info\")\n with open(binlog_file_path, \"r\") as binlog_file:\n for line in binlog_file.readlines():\n match = self.binlog_info_re.search(line)\n if match:\n self.binlog_info = {\n \"file_name\": match.group(\"fn\"),\n \"file_position\": int(match.group(\"pos\")),\n \"gtid\": match.group(\"gtid\"),\n }\n self.log.info(\"binlog info: %r\", self.binlog_info)\n break\n else:\n self.log.warning(\"binlog info wasn't found in `xtrabackup_info` file\")\n\n def _process_output_line_lsn_info(self, line):\n match = self.lsn_re.search(line)\n if match:\n self.lsn_info = {\n \"start\": int(match.group(1)),\n \"end\": int(match.group(2)),\n }\n self.log.info(\"Transaction log lsn info: %r\", self.lsn_info)\n return match\n\n def _update_progress(self, *, last_file_name=None, last_file_size=None, estimated_progress=None):\n estimated_total_bytes = self.data_directory_filtered_size or 0\n\n if estimated_progress is None:\n estimated_progress = 0\n if estimated_total_bytes > 0:\n estimated_progress = min(self.processed_original_bytes / estimated_total_bytes * 100, 100)\n\n self.log.info(\n \"Processed %s bytes of estimated %s total bytes, progress at %.2f%%\",\n self.processed_original_bytes,\n estimated_total_bytes,\n estimated_progress,\n )\n self.stats.gauge_float(\"myhoard.basebackup.estimated_progress\", estimated_progress)\n\n if self.progress_callback:\n self.progress_callback(\n estimated_progress=estimated_progress,\n estimated_total_bytes=estimated_total_bytes,\n last_file_name=last_file_name,\n last_file_size=last_file_size,\n processed_original_bytes=self.processed_original_bytes,\n )\n\n\nclass OutputReaderThread(threading.Thread):\n def __init__(self, *, stats, stream_handler, stream):\n super().__init__()\n self.exception = None\n self.stats = stats\n self.stream_handler = stream_handler\n self.stream = stream\n\n def run(self):\n try:\n self.stream_handler(self.stream)\n except Exception as ex: # pylint: disable=broad-except\n logging.getLogger(self.__class__.__name__).exception(\"Failure while processing backup output\")\n self.stats.increase(\"myhoard.basebackup_read_error\", tags={\"ex\": ex.__class__.__name__})\n self.exception = ex\n","sub_path":"myhoard/basebackup_operation.py","file_name":"basebackup_operation.py","file_ext":"py","file_size_in_byte":17612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"200616503","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# 策略代码总共分为三大部分,1)PARAMS变量 2)initialize函数 3)handle_data函数\n# 请根据指示阅读。或者直接点击运行回测按钮,进行测试,查看策略效果。\n\n# 策略名称:R-Breaker策略\n# 关键词:趋势跟踪、反转。\n# 方法:\n# 1)根据前一个交易日的收盘价、最高价和最低价数据通过一定方式计算出六个价位;\n# 2)同时采取趋势跟踪和反转策略,既抓趋势,也抓反转。\n\nfrom datetime import datetime\n\n# 阅读1,首次阅读可跳过:\n# PARAMS用于设定程序参数,回测的起始时间、结束时间、滑点误差、初始资金和持仓。\n# 可以仿照格式修改,基本都能运行。如果想了解详情请参考新手学堂的API文档。\nPARAMS = {\n \"start_time\": \"2016-09-01 00:00:00\",\n \"end_time\": \"2017-09-07 00:00:00\",\n \"commission\": 0.002,\n \"slippage\": 0.001,\n \"account_initial\": {\"huobi_cny_cash\": 100000,\n \"huobi_cny_ltc\": 0},\n}\n\n\n# 阅读2,遇到不明白的变量可以跳过,需要的时候回来查阅:\n# initialize函数是两大核心函数之一(另一个是handle_data),用于初始化策略变量。\n# 策略变量包含:必填变量,以及非必填(用户自己方便使用)的变量\ndef initialize(context):\n # 设置回测频率, 可选:'1m', '5m', '15m', '30m', '60m', '1d', '1w', '1M', '1y'\n context.frequency = \"4h\"\n # 设置回测基准, 比特币:'huobi_cny_ltc', 莱特币:'huobi_cny_ltc', 以太坊:'huobi_cny_eth'\n context.benchmark = \"huobi_cny_ltc\"\n # 设置回测标的, 比特币:'huobi_cny_ltc', 莱特币:'huobi_cny_ltc', 以太坊:'huobi_cny_eth'\n context.security = \"huobi_cny_ltc\"\n\n\n# 阅读3,策略核心逻辑:\n# handle_data函数定义了策略的执行逻辑,按照frequency生成的bar依次读取并执行策略逻辑,直至程序结束。\n# handle_data和bar的详细说明,请参考新手学堂的解释文档。\ndef handle_data(context):\n # 获取回看时间窗口内的历史数据\n hist = context.data.get_price(context.security, count=1, frequency='1d')\n if len(hist.index) < 1:\n context.log.warn(\"bar的数量不足, 等待下一根bar...\")\n return\n\n # 前日最高价\n high_price = hist['high'][-1]\n # 前日最低价\n low_price = hist['low'][-1]\n # 前日收盘价\n close_price = hist['close'][-1]\n\n # 中心点\n pivot = (high_price + close_price + low_price) / 3\n\n # R-Breaker的阻力线和支撑线\n # 趋势策略-突破买入价\n buy_break = high_price + 2 * (pivot - low_price)\n # 反转策略-观察卖出价\n sell_setup = pivot + (high_price - low_price)\n # 反转策略-反转卖出价\n sell_enter = 2 * pivot - low_price\n # 反转策略-反转买入价\n buy_enter = 2 * pivot - high_price\n # 反转策略-观察买入价\n buy_setup = pivot - (high_price - low_price)\n # 趋势策略-突破卖出价\n sell_break = low_price - 2 * (high_price - pivot)\n\n # 获取当前价格\n current_price = context.data.get_current_price(context.security)\n\n d = context.time.get_current_bar_time().date()\n # 当前bar所在日期的开始时间\n today_start_time = datetime.combine(d, datetime.min.time())\n # 转化为字符串\n today_start_time = today_start_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n # 获取本日历史数据\n today_hist = context.data.get_price(context.security, start_time=today_start_time, frequency=context.frequency)\n\n # 当日最高价\n today_high = today_hist['high'].max()\n # 当日最低价\n today_low = today_hist['low'].min()\n\n context.log.info(\"当前价格=%.2f,日内最高价=%.2f\" % (current_price, today_high))\n context.log.info(\"突破买入价=%.2f,观察卖出价=%.2f,反转卖出价=%.2f,反转买入价=%.2f,观察买入价=%.2f,突破卖出价=%.2f\"\n % (buy_break,sell_setup,sell_enter,buy_enter,buy_setup,sell_break))\n\n # 突破策略信号\n if current_price > buy_break:\n # 盘中价格超过突破买入价,则采取趋势策略,产生买入信号\n context.log.info(\"趋势策略买入信号:当前价格超过了突破买入价\")\n if context.account.huobi_cny_cash >= HUOBI_CNY_LTC_MIN_ORDER_CASH_AMOUNT:\n # 市价单全仓买入\n context.log.info(\"正在买入 %s\" % context.security)\n context.log.info(\"下单金额为 %s 元\" % context.account.huobi_cny_cash)\n context.order.buy(context.security, cash_amount=str(context.account.huobi_cny_cash))\n else:\n context.log.info('现金不足,无法下单')\n elif current_price < sell_break:\n # 盘中价格跌破突破卖出价,则采取趋势策略,产生卖出信号\n context.log.info(\"产生趋势策略卖出信号:当前价格跌破了突破卖出价\")\n if context.account.huobi_cny_ltc >= HUOBI_CNY_LTC_MIN_ORDER_QUANTITY:\n # 市价单全仓卖出\n context.log.info(\"正在卖出 %s\" % context.security)\n context.log.info(\"卖出数量为 %s\" % context.account.huobi_cny_ltc)\n context.order.sell(context.security, quantity=str(context.account.huobi_cny_ltc))\n else:\n context.log.info(\"仓位不足,无法卖出\")\n # 反转策略信号\n elif today_high > sell_setup and current_price < sell_enter:\n # 当日内最高价超过观察卖出价后,盘中价格出现回落,且进一步跌破反转卖出价构成的支撑线,产生卖出信号\n context.log.info(\"反转策略卖出信号: 当前价格跌破反转卖出价,且日内最高价超过观察卖出价\")\n if context.account.huobi_cny_ltc >= HUOBI_CNY_LTC_MIN_ORDER_QUANTITY:\n # 市价单全仓卖出\n context.log.info(\"正在卖出 %s\" % context.security)\n context.log.info(\"卖出数量为 %s\" % context.account.huobi_cny_ltc)\n context.order.sell(context.security, quantity=str(context.account.huobi_cny_ltc))\n else:\n context.log.info(\"仓位不足,无法卖出\")\n elif today_low < buy_setup and current_price > buy_enter:\n # 当日内最低价低于观察买入价后,盘中价格出现反弹,且进一步超过反转买入价构成的阻力线,产生买入信号\n context.log.info(\"反转策略买入信号:当前价格突破了反转买入价,且日内最低价低于观察买入价\")\n if context.account.huobi_cny_cash >= HUOBI_CNY_LTC_MIN_ORDER_CASH_AMOUNT:\n # 市价单全仓买入\n context.log.info(\"正在买入 %s\" % context.security)\n context.log.info(\"下单金额为 %s 元\" % context.account.huobi_cny_cash)\n context.order.buy(context.security, cash_amount=str(context.account.huobi_cny_cash))\n else:\n context.log.info('现金不足,无法下单')\n else:\n context.log.info(\"无交易信号,进入下一根bar\")\n","sub_path":"wequant/r_breaker/ltc.py","file_name":"ltc.py","file_ext":"py","file_size_in_byte":7044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"592925589","text":"import LanguageApp.secret.api_key as secret\nfrom LanguageApp.window import Window\nimport LanguageApp.CONSTANTS as design\nimport firebase_admin\nimport pyrebase\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nfrom LanguageApp.gui import GUI\nimport tkinter as tk\nimport os\n\nclass Director:\n \"\"\"Class to initalize the GUI and Database\"\"\"\n def __init__(self):\n self._app = tk.Tk()\n cwd = os.getcwd()\n icon = tk.PhotoImage(file = f'LanguageApp/icon.png')\n self._app.iconphoto(True,icon)\n\n def initialize_gui_menu(self):\n \"\"\"Initalize the gui menu\n\n Args:\n self (Director): An instance of Director\n \"\"\"\n init_db = self.initalize_database()\n self.db = init_db[0]\n self.auth = init_db[1]\n gui = GUI(self._app, self.db, self.auth)\n self._app.mainloop()\n\n def initalize_database(self):\n \"\"\"Initalize the cloud database\n\n Args:\n self (Director): An instance of Director\n \n return:\n db (Pyrebase): Pyrebase database object\n auth (Pyrebase): Pyrebase authentication object\n \"\"\"\n # Use the application default credentials\n os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = design.database\n cred = credentials.ApplicationDefault()\n firebase_admin.initialize_app(cred, {\n 'projectId': 'language-app-8e630',\n })\n\n \n\n config = {\n \"apiKey\": secret.api_key,\n \"authDomain\": \"language-app-8e630.firebaseapp.com\",\n \"databaseURL\": \"https://language-app-8e630-default-rtdb.firebaseio.com\",\n \"projectId\": \"language-app-8e630\",\n \"storageBucket\": \"language-app-8e630.appspot.com\",\n \"messagingSenderId\": \"1021961728179\",\n \"appId\": \"1:1021961728179:web:570475c6ccd22529f600c6\",\n \"measurementId\": \"G-W4BYKWPGB1\",\n \"serviceAccount\" : design.database\n }\n firebase = pyrebase.initialize_app(config)\n def noquote(s):\n return s\n pyrebase.pyrebase.quote = noquote\n\n auth = firebase.auth()\n db = firebase.database()\n return (db, auth)\n","sub_path":"LanguageApp/director.py","file_name":"director.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"510612243","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, api, _\nfrom openerp.exceptions import UserError\n\n\nclass account_voucher_line(models.Model):\n _inherit = 'account.voucher.line'\n\n @api.multi\n def product_id_change(self, product_id, partner_id=False, price_unit=False, company_id=None, currency_id=None, type=None):\n context = self._context\n company_id = company_id if company_id is not None else context.get('company_id', False)\n company = self.env['res.company'].browse(company_id)\n currency = self.env['res.currency'].browse(currency_id)\n if not partner_id:\n raise UserError(_(\"You must first select a partner!\"))\n part = self.env['res.partner'].browse(partner_id)\n if part.lang:\n self = self.with_context(lang=part.lang)\n\n product = self.env['product.product'].browse(product_id)\n fpos = part.property_account_position_id\n account = self._get_account(product, fpos, type)\n values = {\n 'name': product.partner_ref,\n 'account_id': account.id,\n }\n\n if type == 'purchase':\n values['price_unit'] = price_unit or product.standard_price\n taxes = product.supplier_taxes_id or account.tax_ids\n if product.description_purchase:\n values['name'] += '\\n' + product.description_purchase\n else:\n values['price_unit'] = product.lst_price\n taxes = product.taxes_id or account.tax_ids\n if product.description_sale:\n values['name'] += '\\n' + product.description_sale\n\n values['tax_ids'] = taxes.ids\n\n if company and currency:\n if company.currency_id != currency:\n if type == 'purchase':\n values['price_unit'] = product.standard_price\n values['price_unit'] = values['price_unit'] * currency.rate\n\n return {'value': values, 'domain': {}}\n","sub_path":"interno_pymedigital-9.0/l10n_ec_account_voucher/models/account_voucher.py","file_name":"account_voucher.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"321421649","text":"# -*- coding:utf-8 -*-\nclass Solution:\n def reOrderArray(self, array):\n # write code here\n # 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,\n # 使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,\n # 并保证奇数和奇数,偶数和偶数之间的相对位置不变。\n # 1.要想保证原有次序,则只能顺次移动或相邻交换。\n # 2.i从左向右遍历,找到第一个偶数。\n # 3.j从i+1开始向后找,直到找到第一个奇数。\n # 4.将[i,...,j-1]的元素整体后移一位,最后将找到的奇数放入i位置,然后i++。\n # 5.終止條件:j向後遍歷查找失敗。\n if not array or len(array) == 1:\n return array\n for i in range(len(array)):\n if array[i] % 2 == 0:\n if i+1 > len(array):\n break\n for j in range(i+1, len(array)):\n if array[j] % 2 == 1:\n tmp = array[j]\n array[i+1:j+1] = array[i:j]\n array[i] = tmp\n break\n return array\n \nn = [1,2,3,4,5,6,7]\nSolution().reOrderArray(n)\nprint(n)","sub_path":"OFFER/调整数组顺序使奇数位于偶数前面/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"385488251","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 25 16:22:49 2021\n\n@author: Admin\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#parametros\nL = 1.0 #m\nalpha = 1e-4 #m^2/s\nteta1 = 300.0 #K --> Temperatura inicial\nteta0 = 500.0 #K --> Temperatura ambiente\nnodos = 100\ndt = 1.0 #s\ntf = 1000.0\n\ndx = L/(nodos - 1)\ndX = dx/L\ndtau = alpha*dt/L**2\ngamma = dtau/dX**2\nit = int(tf/dt)\n\n#vetores y matrices\nT = np.zeros(nodos)\nvec_F = np.zeros(nodos)\nmat_futura = np.zeros((nodos,nodos))\nmat_actual = np.zeros((nodos,nodos))\nminv = np.zeros((nodos,nodos))\nmat_T = np.zeros((nodos,it+1))\n\neq = 0\nfor i in range(nodos):\n print(\"Ecuación del nodo: \",eq)\n nc = eq #nodo central\n nl = nc - 1 #nodo izquierdo\n nr = nc + 1 #nodo derecho\n\n if((i==0)): #Nodos tipo 10\n mat_futura[eq,nc] = 1.0\n \n print(\"Nodo en x=0\")\n \n elif((i val_b] \nlegal_tuples = [\"CM\", \"CD\", \"XC\", \"XL\", \"IX\", \"IV\", \"MM\", \"CC\", \"XX\", \"II\"] \\\n + legal_tuples_smaller \\\n + list(roman_numerals_dict.keys())\n\ndef find_next_numeral(arabic):\n \"Finds the next numeral and the corresponding arabic value\"\n for numeral, value in roman_numerals:\n if arabic >= value:\n return numeral, value\n return \"\", 0\n\n\ndef to_roman(arabic):\n \"Converts from arabic numbers to roman numbers. Casts floats to int.\"\n roman = \"\"\n arabic = int(arabic)\n\n while arabic > 0:\n next_numeral, subtractor = find_next_numeral(arabic)\n roman += next_numeral\n arabic -= subtractor\n\n return roman\n\n\ndef to_arabic(roman, last=\"\", firstbutlast=\"\"):\n if type(roman) != str:\n raise NotARomanNumber\n if not roman:\n if last:\n return 0\n else:\n raise NotARomanNumber\n num = roman[0]\n if num in roman_numerals_dict:\n arabic_numeral = roman_numerals_dict[num]\n else:\n raise NotARomanNumber\n if not last + num in legal_tuples:\n raise NotARomanNumber\n if len(firstbutlast)>0 \\\n and roman_numerals_dict[firstbutlast] < arabic_numeral \\\n and roman_numerals_dict[last] <= arabic_numeral:\n raise NotARomanNumber\n\n subtractor = 0\n if last + num in [\"CM\",\"CD\", \"XC\", \"XL\", \"IX\", \"IV\"]:\n subtractor = 2 * roman_numerals_dict[last]\n\n return arabic_numeral - subtractor + to_arabic(roman[1:], num, last)\n\n\nclass NotARomanNumber(Exception):\n pass\n","sub_path":"roman.py","file_name":"roman.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"349700999","text":"from itertools import groupby\nfrom tqdm import tqdm\n\n# source_path = 'gtag_train_0_39999_propsal_list.txt'\n# output_path = 'traindata_1/gtag_train_35000_39999_propsal_list.txt'\n# start_idx = 35000\n# end_idx = 39999\nsource_path = 'gtag_train_slowfast_0_39999_propsal_list.txt'\noutput_path = 'gtag_train_slowfast_35000_39992_propsal_list.txt'\nstart_idx = 35000\nend_idx = 39992\n\nlines = list(open(source_path))\ngroups = groupby(lines, lambda x: x.startswith('#'))\ninfo_list = [[x.strip() for x in list(g)] for k, g in groups if not k]\n\n\nf = open(output_path, 'w')\npbar = tqdm(total=len(info_list[start_idx:end_idx]))\n\nfor v_idx in range(start_idx,end_idx+1):\n pbar.update(1)\n f.write('#{}'.format(str(v_idx))), f.write('\\r\\n')\n for line in info_list[v_idx]:\n \tf.write(line), f.write('\\r\\n')\npbar.close()\nf.close()\n","sub_path":"data/ali_gtag/split_prop_txt.py","file_name":"split_prop_txt.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"355431324","text":"from django.shortcuts import render\nfrom django.conf import settings\nfrom django.shortcuts import redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import redirect, render\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom urllib.parse import urlparse\nfrom swiftclient import client\nimport logging\n\nfrom .forms import CreateContainerForm, UploadFileForm, CreateFolderForm\n\nlogger = logging.getLogger(__name__)\n\ndef replace_hyphens(olddict):\n \"\"\" Replaces all hyphens in dict keys with an underscore.\n\n Needed in Django templates to get a value from a dict by key name. \"\"\"\n newdict = {}\n for key, value in olddict.items():\n key = key.replace('-', '_')\n newdict[key] = value\n return newdict\n\n@login_required\ndef containers(request):\n if 'auth_token' not in request.session.keys():\n logger.info('No auth_token, attempting to authenticate')\n try:\n auth_version = settings.SWIFT_AUTH_VERSION or 1\n conn = client.Connection(authurl=settings.SWIFT_AUTH_URL,\n user=settings.SWIFT_AUTH_USER,\n key=settings.SWIFT_AUTH_KEY,\n auth_version=auth_version,\n insecure=settings.SWIFT_SSL_INSECURE)\n (storage_url, auth_token) = conn.get_auth()\n logger.info('auth_token: %s' % auth_token)\n logger.info('storage_url: %s' % storage_url)\n request.session['storage_url'] = storage_url\n request.session['auth_token'] = auth_token\n except client.ClientException:\n messages.add_message(request, messages.ERROR, \"Login failed.\")\n\n auth_token = request.session['auth_token']\n storage_url = request.session['storage_url']\n\n try:\n http_conn = (urlparse(storage_url),\n client.HTTPConnection(storage_url, insecure=settings.SWIFT_SSL_INSECURE))\n account_stat, containers = client.get_account(storage_url, auth_token, http_conn=http_conn)\n except client.ClientException as exc:\n if exc.http_status == 403:\n account_stat = {}\n containers = []\n msg = 'Container listing failed.'\n messages.add_message(request, messages.ERROR, msg)\n else:\n request.session.flush()\n return redirect(settings.LOGIN_URL)\n\n account_stat = replace_hyphens(account_stat)\n\n return render(request,'containers.html', {\n 'account_stat': account_stat,\n 'containers': containers,\n 'session': request.session,\n })\n\n@login_required\ndef container(request, container=None):\n auth_token = request.session['auth_token']\n storage_url = request.session['storage_url']\n\n if 'container' not in request.GET.keys():\n return redirect(containers)\n container = request.GET['container']\n subdir = ''\n if 'subdir' in request.GET.keys():\n subdir = request.GET['subdir']\n\n try:\n http_conn = (urlparse(storage_url),\n client.HTTPConnection(storage_url, insecure=settings.SWIFT_SSL_INSECURE))\n meta, objects = client.get_container(storage_url, auth_token,\n container, delimiter='/',\n prefix=subdir,\n http_conn=http_conn)\n subdirs = list()\n folder_objects = list()\n for folder_object in objects:\n if 'subdir' in folder_object.keys():\n if folder_object['subdir'].startswith(subdir):\n subdirs.append({\n 'display_name': folder_object['subdir'][len(subdir):],\n 'subdir': folder_object['subdir'],\n })\n else:\n subdirs.append({\n 'display_name': folder_object['subdir'],\n 'subdir': folder_object['subdir'],\n })\n else:\n if folder_object['name'].startswith(subdir):\n folder_object['display_name'] = folder_object['name'][len(subdir):]\n else:\n folder_object['display_name'] = folder_object['name']\n folder_objects.append(folder_object)\n \n account = storage_url.split('/')[-1]\n path = list()\n if subdir:\n current_path = ''\n for path_element in subdir.split('/'):\n if path_element:\n current_path += \"%s/\" % (path_element)\n path.append({ 'subdir': current_path, 'path_element': path_element })\n \n read_acl = meta.get('x-container-read', '').split(',')\n public = False\n required_acl = ['.r:*', '.rlistings']\n if [x for x in read_acl if x in required_acl]:\n public = True\n\n return render(request, \"container.html\", {\n 'container': container,\n 'subdirs': subdirs,\n 'upload_subdir': subdir,\n 'folder_objects': folder_objects,\n 'account': account,\n 'public': public,\n 'session': request.session,\n 'path': path,\n })\n\n except client.ClientException:\n messages.add_message(request, messages.ERROR, \"Access denied.\")\n return redirect(containers)\n\n@login_required\ndef create_container(request):\n auth_token = request.session['auth_token']\n storage_url = request.session['storage_url']\n\n if request.method == 'POST':\n form = CreateContainerForm(request.POST)\n if form.is_valid():\n container = form.cleaned_data['container']\n try:\n http_conn = (urlparse(storage_url),\n client.HTTPConnection(storage_url, insecure=settings.SWIFT_SSL_INSECURE))\n client.put_container(storage_url, auth_token, container, http_conn=http_conn)\n messages.add_message(request, messages.INFO, \"Container created.\")\n except client.ClientException:\n messages.add_message(request, messages.ERROR, \"Access denied.\")\n\n return redirect(containers)\n else:\n form = CreateContainerForm()\n\n return render(request, 'create_container.html', {'form': form})\n\n\n@login_required\ndef delete_container(request):\n auth_token = request.session['auth_token']\n storage_url = request.session['storage_url']\n\n container = ''\n if 'container' in request.GET.keys():\n container = request.GET['container']\n else:\n return redirect(containers)\n\n try:\n http_conn = (urlparse(storage_url),\n client.HTTPConnection(storage_url, insecure=settings.SWIFT_SSL_INSECURE))\n _m, objects = client.get_container(storage_url, auth_token, container, http_conn=http_conn)\n for obj in objects:\n logger.info(\"Deleting object %s in container %s\" % (obj['name'], container))\n client.delete_object(storage_url, auth_token,\n container, obj['name'], http_conn=http_conn)\n logger.info(\"Deleting container %s\" % (container))\n client.delete_container(storage_url, auth_token, container, http_conn=http_conn)\n messages.add_message(request, messages.INFO, \"Container deleted.\")\n except client.ClientException:\n messages.add_message(request, messages.ERROR, \"Access denied.\")\n\n return redirect(containers)\n\n@login_required\ndef upload(request):\n auth_token = request.session['auth_token']\n storage_url = request.session['storage_url']\n\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n container = form.cleaned_data['container']\n object_name = form.cleaned_data['object_name']\n subdir = form.cleaned_data['subdir']\n upload_file = request.FILES['file']\n logger.info(\"File upload for /%s/%s%s\" % (container, subdir, object_name))\n try:\n http_conn = (urlparse(storage_url),\n client.HTTPConnection(storage_url, insecure=settings.SWIFT_SSL_INSECURE))\n client.put_object(storage_url, auth_token,\n container,\n name=subdir + object_name,\n contents=upload_file,\n http_conn=http_conn)\n messages.add_message(request, messages.INFO, \"File uploaded.\")\n except client.ClientException:\n messages.add_message(request, messages.ERROR, \"Access denied.\")\n\n return redirect(reverse('container') + '?container=%s&subdir=%s' % (container, subdir))\n else:\n container = ''\n subdir = ''\n if 'container' in request.GET.keys():\n container = request.GET['container']\n if 'subdir' in request.GET.keys():\n subdir = request.GET['subdir']\n \n path = list()\n if subdir:\n current_path = ''\n for path_element in subdir.split('/'):\n if path_element:\n current_path += \"%s/\" % (path_element)\n path.append({ 'subdir': current_path, 'path_element': path_element })\n\n form = UploadFileForm(initial={\n 'container': container,\n 'subdir': subdir,\n })\n\n return render(request, 'upload_file.html', {\n 'form': form,\n 'path': path,\n 'container': container,\n 'subdir': subdir,\n })\n\n@login_required\ndef delete_object(request):\n auth_token = request.session['auth_token']\n storage_url = request.session['storage_url']\n\n container = ''\n subdir = ''\n object_name = ''\n\n if 'container' in request.GET.keys():\n container = request.GET['container']\n else:\n return redirect(containers)\n\n if 'subdir' in request.GET.keys():\n subdir = request.GET['subdir']\n else:\n return redirect(reverse('container') + '?container=%s' % (container))\n\n if 'object_name' in request.GET.keys():\n object_name = request.GET['object_name']\n else:\n return redirect(reverse('container') + '?container=%s&subdir=%s' % (container, subdir))\n\n logger.info(\"Delete File /%s/%s%s\" % (container, subdir, object_name))\n try:\n http_conn = (urlparse(storage_url),\n client.HTTPConnection(storage_url, insecure=settings.SWIFT_SSL_INSECURE))\n client.delete_object(storage_url, auth_token,\n container, object_name,\n http_conn=http_conn)\n messages.add_message(request, messages.INFO, \"File deleted.\")\n except client.ClientException:\n messages.add_message(request, messages.ERROR, \"Access denied.\")\n\n return redirect(reverse('container') + '?container=%s&subdir=%s' % (container, subdir))\n\n@login_required\ndef create_folder(request):\n auth_token = request.session['auth_token']\n storage_url = request.session['storage_url']\n\n if request.method == 'POST':\n form = CreateFolderForm(request.POST)\n if form.is_valid():\n container = form.cleaned_data['container']\n subdir=''\n if 'subdir' in form.cleaned_data.keys():\n subdir = form.cleaned_data['subdir']\n folder_name = form.cleaned_data['folder_name']\n try:\n object_name = subdir + folder_name + '/'\n logger.info(\"Creating folder %s\" % (object_name))\n http_conn = (urlparse(storage_url),\n client.HTTPConnection(storage_url, insecure=settings.SWIFT_SSL_INSECURE))\n client.put_object(storage_url, auth_token,\n container,\n name=object_name,\n contents=None,\n content_type='application/directory',\n http_conn=http_conn)\n messages.add_message(request, messages.INFO, \"Folder created.\")\n except client.ClientException:\n messages.add_message(request, messages.ERROR, \"Access denied.\")\n return redirect(reverse('container') + '?container=%s&subdir=%s/' % (container, subdir))\n\n return redirect(reverse('container') + '?container=%s&subdir=%s/' % (container, subdir + folder_name))\n else:\n messages.add_message(request, messages.ERROR, \"Invalid input\")\n logger.error(\"Form is not valid: %s\" % form.cleaned_data)\n return redirect(reverse('create_folder') + '?container=%s&subdir=%s/' % (container, subdir))\n else:\n container = ''\n subdir = ''\n if 'container' in request.GET.keys():\n container = request.GET['container']\n if 'subdir' in request.GET.keys():\n subdir = request.GET['subdir']\n \n path = list()\n if subdir:\n current_path = ''\n for path_element in subdir.split('/'):\n if path_element:\n current_path += \"%s/\" % (path_element)\n path.append({ 'subdir': current_path, 'path_element': path_element })\n\n form = CreateFolderForm(initial={\n 'container': container,\n 'subdir': subdir,\n })\n\n return render(request, 'create_folder.html', {\n 'form': form,\n 'container': container,\n 'subdir': subdir,\n 'path': path,\n })\n\n\n","sub_path":"swift_browser/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"121120665","text":"from __future__ import print_function, division\nimport os\nimport torch\nfrom skimage import io, transform\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nfrom scipy import misc\n\nfrom torch.autograd import Variable\n\ndef minidronevideo(frames):\n video = frames[0][0].split('/')[-1].split('-')[0]\n groups = []\n tmp = [frames[0]]\n for c in frames[1:]:\n if c[0].split('/')[-1].split('-')[0] == video:\n tmp.append(c)\n else:\n groups.append(tmp)\n video = c[0].split('/')[-1].split('-')[0]\n tmp = [c]\n groups.append(tmp)\n\n return groups\n\ndef umn(frames):\n pattern = frames[0][0].split('_')[1]\n video = frames[0][0].split('_')[2]\n groups = []\n tmp = [frames[0]]\n for c in frames[1:]:\n if c[0].split('_')[1] == pattern and c[0].split('_')[2] == video:\n tmp.append(c)\n else:\n groups.append(tmp)\n pattern = c[0].split('_')[1]\n video = c[0].split('_')[2]\n tmp = [c]\n groups.append(tmp)\n\n return groups\n\nclass MiniDroneVideoDataset(Dataset):\n \"\"\"\n \"\"\"\n\n def __init__(self, dataset, summary, root_dir, sequence_length, stride, transform=None):\n \"\"\"\n \"\"\"\n\n self.dataset = dataset\n self.root_dir = root_dir\n self.transform = transform\n self.sequence_length = sequence_length\n self.stride = stride\n self.root_dir = root_dir\n with open(summary, 'r') as f:\n content = f.read().split('\\n')[:-1]\n self.content = [c.split('\\t') for c in content]\n #Group frames from the same video\n if self.dataset == 'minidrone':\n groups = minidronevideo(self.content)\n elif self.dataset == 'umn':\n groups = umn(self.content)\n #Build sequences from the same video of length sequence_length\n self.frames = [(['data/' + f[0] + '.png' for f in g[i*self.stride:(i*self.stride)+self.sequence_length]], [int(f[1]) for f in g[i*self.stride:(i*self.stride)+self.sequence_length]])\n for g in groups for i in range(int(len(g) / self.stride))]\n\n def __len__(self):\n return len(self.frames)\n\n def __getitem__(self, idx):\n images = np.array([io.imread(f)*1/255 for f in self.frames[idx][0]], dtype=np.float)\n labels = np.array([f for f in self.frames[idx][1]], dtype=np.float)\n labels = labels.reshape(len(labels), 1)\n names = [os.path.basename(f) for f in self.frames[idx][0]]\n sample = {'images': images, 'labels':labels, 'names':names}\n if self.transform:\n sample = self.transform(sample)\n normalized = []\n for i in sample['images']:\n x = i\n x -= x.mean()\n x /= x.std()\n normalized.append(x)\n sample['images'] = np.array(normalized)\n sample['images'] = sample['images'].transpose((0, 3, 1, 2))\n\n return sample\n\nclass NegativeDataset(Dataset):\n \"\"\"\n \"\"\"\n\n def __init__(self, summary, root_dir):\n \"\"\"\n \"\"\"\n\n self.root_dir = root_dir\n with open(summary, 'r') as f:\n content = f.read().split('\\n')[:-1]\n self.content = [c.split('\\t') for c in content]\n self.normal = ['data/{}.png'.format(c[0]) for c in self.content if c[1] == '0']\n self.abnormal = ['data/{}.png'.format(c[0]) for c in self.content if c[1] == '1']\n self.active = 0\n\n def __len__(self):\n if self.active == 0:\n return len(self.normal)\n else:\n return len(self.abnormal)\n\n def __getitem__(self, idx):\n if self.active == 0:\n dataset = self.normal\n label = 0\n else:\n dataset = self.abnormal\n label = 1\n x = misc.imread(dataset[idx]).astype(np.float32)#.reshape(224, 224, 1)\n #x = (x - x.min()) / (x.max() - x.min())\n name = dataset[idx]\n\n x -= x.mean()\n x /= x.std()\n\n x = x.transpose((2, 0, 1))\n\n sample = {'image': x, 'label':label, 'name': name}\n\n return sample\n\nclass Rescale(object):\n \"\"\"Rescale the image in a sample to a given size.\n\n Args:\n output_size (tuple or tuple): Desired output size. If tuple, output is\n matched to output_size. If int, smaller of image edges is matched\n to output_size keeping aspect ratio the same.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n self.output_size = output_size\n\n def __call__(self, sample):\n images = sample['images']\n h, w = images[0].shape[:2]\n if isinstance(self.output_size, int):\n if h > w:\n new_h, new_w = self.output_size * h / w, self.output_size\n else:\n new_h, new_w = self.output_size, self.output_size * w / h\n else:\n new_h, new_w = self.output_size\n new_h, new_w = int(new_h), int(new_w)\n rescaled = []\n for i in images:\n rescaled.append(transform.resize(i, (new_h, new_w), mode='constant'))\n rescaled = np.array(rescaled)\n\n return {'images': rescaled, 'labels':sample['labels'], 'names':sample['names']}\n\n\nclass RandomCrop(object):\n \"\"\"Crop randomly the image in a sample.\n\n Args:\n output_size (tuple or int): Desired output size. If int, square crop\n is made.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n if isinstance(output_size, int):\n self.output_size = (output_size, output_size)\n else:\n assert len(output_size) == 2\n self.output_size = output_size\n\n def __call__(self, sample):\n images = sample['images']\n if 0.5 > np.random.uniform(0.0, 1.0):\n h, w = images[0].shape[:2]\n new_h, new_w = self.output_size\n top = np.random.randint(0, h - new_h)\n left = np.random.randint(0, w - new_w)\n croped = []\n for i in images:\n croped.append(i[top: top + new_h, left: left + new_w])\n croped = np.array(croped)\n rescale = Rescale((224, 224))\n rescaled = rescale({'images': croped, 'labels': sample['labels'], 'names':sample['names']})\n rescaled = rescaled['images']\n else:\n rescaled = np.array(images)\n\n return {'images': rescaled, 'labels': sample['labels'], 'names':sample['names']}\n\nclass RandomFlip(object):\n \"\"\"Flip randomly the image in a sample.\n \"\"\"\n\n def __init__(self):\n pass\n\n def __call__(self, sample):\n images = sample['images']\n if 0.5 > np.random.uniform(0.0, 1.0):\n fliped = []\n for i in images:\n fliped.append(np.fliplr(i))\n fliped = np.array(fliped)\n else:\n fliped = np.array(images)\n\n return {'images': fliped, 'labels': sample['labels'], 'names':sample['names']}\n\nclass Dropout(object):\n \"\"\"Flip randomly the image in a sample.\n \"\"\"\n\n def __init__(self, amount):\n self.amount = amount\n\n def __call__(self, sample):\n images = sample['images']\n if 0.5 > np.random.uniform(0.0, 1.0):\n droped = []\n num_droped = np.ceil(np.random.uniform(0.0, self.amount) * 224*224)\n coords = [np.random.randint(0, i - 1 , int(num_droped)) for i in images[0].shape]\n for i in images:\n i[coords[:-1]] = (0, 0, 0)\n droped.append(i)\n droped = np.array(droped)\n else:\n droped = np.array(images)\n\n return {'images': droped, 'labels': sample['labels'], 'names':sample['names']}\n\nclass Normalization(object):\n \"\"\"Flip randomly the image in a sample.\n \"\"\"\n\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n\n def __call__(self, sample):\n images = sample['images']\n normalized = []\n for i in images:\n i -= self.mean\n i /= self.std\n normalized.append(i)\n normalized = np.array(normalized)\n\n return {'images': normalized, 'labels': sample['labels'], 'names':sample['names']}\n\nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n return {'images': torch.from_numpy(sample['images']), 'labels': torch.from_numpy(sample['labels']), 'names':sample['names']}\n\n# ds = MiniDroneVideoDataset('umn', 'data/umn_trainset_labels',\n# 'data',\n# 20, 20,\n# transform=transforms.Compose([RandomCrop((160, 160)), RandomFlip(), Dropout(0.2)]))\n# fig = plt.figure()\n# sample = ds[50]\n# #print(max(set(sample['images'][0].flatten())))\n# for i in range(len(sample['images'])):\n# plt.imsave('{}.png'.format(sample['names'][i]), sample['images'][i].transpose(1, 2, 0))\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":9062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"16950125","text":"import numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\n\r\ndf=pd.read_csv(\"mushrooms.csv\")\r\n\r\nX=df.drop(columns=\"class\")\r\ny=df[\"class\"]\r\n\r\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\r\n## X variable label Encoder\r\nlex=LabelEncoder()\r\nfor i in X:\r\n X[i]=lex.fit_transform(X[i])\r\n\r\n## y label Encoder\r\nley=LabelEncoder()\r\ny=ley.fit_transform(y)\r\n\r\nX=pd.get_dummies(X,columns=X.columns,drop_first=True)\r\nfrom sklearn.model_selection import train_test_split\r\nxtrain,xtest,ytrain,ytest=train_test_split(X,y,test_size=0.25)\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc = StandardScaler()\r\nxtrain = sc.fit_transform(xtrain)\r\nxtest = sc.transform(xtest)\r\n\r\nfrom sklearn.decomposition import PCA\r\npca = PCA(n_components=2)\r\nxtrain = pca.fit_transform(xtrain)\r\nxtest = pca.transform(xtest)\r\n\r\nfrom sklearn.svm import SVC\r\nsvm1=SVC(kernel=\"rbf\",random_state=0,gamma=\"scale\")\r\nsvm1.fit(xtrain,ytrain)\r\nypred=svm1.predict(xtest)\r\nprint(\"ypred is: \",ypred)\r\nprint();print();print()\r\n\r\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\r\n\r\nacc=accuracy_score(ypred,ytest)\r\nprint(acc)\r\ncm=confusion_matrix(ytest,ypred)\r\nprint(cm)\r\ncr=classification_report(ytest,ypred)\r\nprint(cr)\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","sub_path":"Project/seprate_algo_Mushroom/svm_apply.py","file_name":"svm_apply.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"563266399","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport tkinter as tk\r\nfrom tkinter import * \r\nfrom tkinter.ttk import *\r\ndef scrapeInstagram(soup1):\r\n data = soup1.find(name=\"meta\",attrs={\"property\":\"og:description\"})\r\n data_info = data['content'].split()\r\n\r\n if '\"overall_category_name\":null,\"is_private\":true' in get_url.text :\r\n private_or_not = \"Private\"\r\n else:\r\n private_or_not= \"Not Private\"\r\n \r\n return data_info,private_or_not\r\n\r\ndef action(account_name):\r\n username_instagram = account_name.get()\r\n global get_url\r\n get_url = requests.get(\"https://www.instagram.com/\"+username_instagram)\r\n soup1 = BeautifulSoup(get_url.content,\"lxml\")\r\n data = scrapeInstagram(soup1)\r\n \r\n followers = f\"{data[0][0]} Followers\"\r\n following = f\"{data[0][2]} Following\"\r\n post = f\"{data[0][4]} Posts\"\r\n private_or_not = data[1]\r\n label([followers,following,post,private_or_not,username_instagram])\r\n account_name.delete(0,END)\r\n \r\ndef widget(): \r\n frame_root1 = tk.Frame(root)\r\n frame_root1.pack()\r\n frame_root2 = tk.Frame(root)\r\n frame_root2.pack()\r\n username_instagram = tk.Entry(frame_root1,insertwidth=5,bd=10,background=\"cyan\",width=20,foreground='darkslategray',font=('arial', 15 , 'bold'),justify=\"center\")\r\n username_instagram.pack()\r\n username_instagram.insert(0,\"Name User\")\r\n username_instagram.focus_set()\r\n username_instagram.select_range(0,END)\r\n \r\n enter = tk.Button(frame_root2,command=lambda : action(username_instagram),\r\n text='ENTER',font=('arial',15,'bold'),fg='darkslategray',relief=\"raised\",\r\n background=\"cyan\",bd=2).pack(side=RIGHT)\r\n root.bind('', (lambda button_enter: action(username_instagram)))\r\n\r\n clears = tk.Button(frame_root2,command= clear,\r\n text='CLEAR',font=('arial',15,'bold'),fg='darkslategray',relief=\"raised\",\r\n background=\"cyan\",bd=2).pack(side=LEFT)\r\n root.bind('', (lambda button_delete : clear()))\r\n\r\ndef clear():\r\n children = root.winfo_children()\r\n for i in range(2,len(children)):\r\n children[i].destroy()\r\ndef label(textnya):\r\n\r\n frame_awal = tk.Frame(root)\r\n frame_awal.pack()\r\n frame_kedua = tk.Frame(root)\r\n frame_kedua.pack()\r\n frame_ketiga = tk.Frame(root)\r\n frame_ketiga.pack()\r\n frame_keempat = tk.Frame(root)\r\n frame_keempat.pack()\r\n frame_kelima = tk.Frame(root)\r\n frame_kelima.pack()\r\n username = Label(frame_awal,font=('arial',20),relief=\"raised\",foreground='darkslategray',text=\"Username : \",background='cyan').pack(side=LEFT)\r\n label_username = Label(frame_awal,font=('arial',20),relief=\"raised\",foreground='darkslategray',text=textnya[4],background='cyan').pack(side=RIGHT)\r\n \r\n follower = Label(frame_kedua,font=('arial',20),relief=\"raised\",foreground='darkslategray',text=\"Followers : \",background='cyan').pack(side=LEFT)\r\n label_follower = Label(frame_kedua,text=textnya[0],font=('arial',20),relief=\"raised\",foreground='darkslategray',background='cyan').pack(side=RIGHT)\r\n \r\n following = Label(frame_ketiga,font=('arial',20),relief=\"raised\",text=\"Following : \",foreground='darkslategray',background='cyan').pack(side=LEFT)\r\n label_following = Label(frame_ketiga,text=textnya[1],font=('arial',20),relief=\"raised\",foreground='darkslategray',background='cyan').pack(side=RIGHT)\r\n \r\n post = Label(frame_keempat,font=('arial',20),relief=\"raised\",text=\"Post : \",foreground='darkslategray',background='cyan').pack(side=LEFT)\r\n label_post = Label(frame_keempat,text=textnya[2],font=('arial',20),relief=\"raised\",foreground='darkslategray',background='cyan').pack(side=RIGHT)\r\n \r\n account_status = Label(frame_kelima,font=('arial',20),relief=\"raised\",text=f\"****{textnya[3]}****\",foreground='darkslategray',background='cyan').pack()\r\n \r\n\r\n \r\n \r\nif __name__ == '__main__':\r\n root = tk.Tk()\r\n # root.geometry(\"250x280\")\r\n root.title(\"Insta_Info\")\r\n root.config(bg=\"deepskyblue\")\r\n root.resizable(False,False)\r\n widget()\r\n root.mainloop()","sub_path":"insta_info_gui.py","file_name":"insta_info_gui.py","file_ext":"py","file_size_in_byte":4068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"608736765","text":"from django.shortcuts import render, redirect, reverse\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom .models import Blog\nfrom .forms import RegisterForm\n\n\ndef index(request):\n blogs = Blog.objects.all().order_by('-votes')\n template = loader.get_template(\"index.html\")\n return HttpResponse(template.render({\"blogs\": blogs}, request))\n\n\ndef get_blog_create(request):\n template = loader.get_template(\"blog_create.html\")\n return HttpResponse(template.render({}, request))\n\n\ndef post_blog_create(request):\n if len(request.POST.get(\"title\").strip()) > 0 and len(request.POST.get(\"text\").strip()) > 0:\n Blog.objects.create(\n title=request.POST.get(\"title\").strip(),\n text=request.POST.get(\"text\").strip()\n )\n return redirect(reverse('main:index', kwargs={}))\n\n\ndef blog_upvote(request, pk):\n blog = Blog.objects.get(pk=pk)\n blog.votes += 1\n blog.save()\n return redirect(reverse('main:index', kwargs={}))\n\n\ndef blog_downvote(request, pk):\n blog = Blog.objects.get(pk=pk)\n blog.votes -= 1\n blog.save()\n return redirect(reverse('main:index', kwargs={}))\n\n\ndef register_view(request):\n template = loader.get_template(\"register.html\")\n return HttpResponse(template.render({}, request))\n\n\ndef login_view(request):\n template = loader.get_template(\"login.html\")\n return HttpResponse(template.render({}, request))\n\n\ndef post_register(request):\n form = RegisterForm(request.POST)\n if form.is_valid():\n User.objects.create_user(\n username=form.cleaned_data[\"username\"],\n password=form.cleaned_data[\"password1\"],\n )\n return redirect(reverse(\"main:index\", kwargs={}))\n template = loader.get_template(\"register.html\")\n return HttpResponse(template.render({\"error\": form.errors}, request))\n","sub_path":"text_analyzer/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"165853876","text":"import theano\nimport numpy as np\nimport theano.tensor as T\n\n# y = T.imatrix('y')\n# x = T.imatrix('x')\n# z = T.concatenate([x,y])\n# a = z.sum(axis=1)\n# f = theano.function(inputs=[x,y], outputs=a)\n# zre = f([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]],[[6,7,8,9,10],[6,7,8,9,10]])\n# print zre\n\n# node_info = T.ivector('x')\n# node_h = T.imatrix('h')\n# child_exists = node_info > -1\n# offset = 5 - child_exists * 1\n# child_h = node_h[node_info] * child_exists.dimshuffle(0, 'x')\n# f = theano.function(inputs=[node_info,node_h], outputs=[])\n# res = f([0,1,2,-1,-1,4],[[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5],[6,6,6],[7,7,7]])\n# print res\n\ndef composition(child_h, child_id, parent_emb):\n W = theano.shared(np.random.normal(size=10))\n res = T.switch(T.lt(-1, child_id),\n T.tanh(T.dot(W, T.concatenate([parent_emb, child_h]))),\n T.zeros(5))\n return res\nchild_h = T.fmatrix('ch')\nnode_info = T.ivector('2')\ncur_emb = T.fvector('c')\n\nz_h,_ = theano.scan(\n fn=composition,\n outputs_info=None,\n sequences=[child_h, node_info],\n non_sequences=[cur_emb]\n)\nf = theano.function(inputs=[child_h,node_info,cur_emb], outputs=[z_h])\nchild_h = np.random.normal(size=[6,5])\ncur_emb = np.random.normal(size=5)\nnode_info = [0,1,3,-1,-1,-1]","sub_path":"Reranker/Test3.py","file_name":"Test3.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"557797969","text":"from distutils.core import setup\n\nwith open(\"README.md\") as f:\n README = f.read()\n\nsetup(\n name = \"sylantro-python\",\n py_modules = [\"sylantro\"],\n version = \"1\",\n install_requires = [\"beautifulsoup4\", \"requests\"],\n\n author = \"btidor\",\n author_email = \"btidor@mit.edu\",\n url = \"https://github.com/btidor/sylantro-python\",\n description = \"A programmatic tool to place calls with MIT's Sylantro VOIP system.\",\n long_description = README,\n license = \"LICENSE\",\n\n keywords = [\"sylantro\", \"voip\", \"telephony\"],\n classifiers = [\n \"Programming Language :: Python\",\n \"Development Status :: 4 - Beta\",\n \"Environment :: Other Environment\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Topic :: Communications :: Internet Phone\",\n \"Topic :: Communications :: Telephony\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"309893997","text":"#!/usr/bin/python3\ndef safe_print_list_integers(my_list=[], x=0):\n\n put = 0\n\n for help in range(x):\n try:\n print(\"{:d}\".format(my_list[help]), end=\"\")\n put += 1\n except TypeError:\n None\n except ValueError:\n None\n print()\n return put\n","sub_path":"0x05-python-exceptions/2-safe_print_list_integers.py","file_name":"2-safe_print_list_integers.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"386923332","text":"class Grade:\n def __init__(self, num, letter):\n self.num = num\n self.letter = letter\n\n def __str__(self):\n return f'{self.num}{self.letter}'\n\n\nclass Person:\n def __init__(self, surname, name):\n self.name = name\n self.surname = surname\n\n def __str__(self):\n return f'{self.surname} {self.name}'\n\n\nclass Student(Person):\n def __init__(self, surname, name, grade, parents):\n Person.__init__(self, surname, name)\n self.grade = grade\n self.parents = parents\n\n\nclass Parents:\n def __init__(self, father, mother):\n self.father = father\n self.mother = mother\n\n def __str__(self):\n return f'отец: {self.father}, мать: {self.mother}'\n\n\nclass Teacher(Person):\n def __init__(self, surname, name, discipline, grades):\n Person.__init__(self, surname, name)\n self.discipline = discipline\n self.grades = grades\n\n\ndiscipline = ['JS',\n 'HTML+CSS',\n 'Django',\n 'Agile',\n 'Python'\n ]\n\ngrade = [Grade(5, 'А'), # 0\n Grade(6, 'А'), # 1\n Grade(7, 'Б'), # 2\n Grade(7, 'А'), # 3\n Grade(7, 'В'), # 4\n Grade(6, 'Б'), # 5\n Grade(8, 'А'), # 6\n Grade(9, 'А'), # 7\n ]\n\nparents = [Parents('Иванов Иван', 'Иванова Мария'), # 0\n Parents('Петров Пётр', 'Петрова Елена'), # 1\n Parents('Сидоров Николай', 'Сидорова Татьяна'), # 2\n Parents('Поляков Михаил', 'Полякова Ольга'), # 3\n Parents('Семёнов Дмитрий', 'Семёнова Ольга'), # 4\n Parents('Дрябезгов Константин', 'Дрябезгова Марина'), # 5\n Parents('Шитов Денис', 'Шитова Наталья'), # 6\n Parents('Жуков Юрий', 'Жукова Светлана'), # 7\n Parents('Тимофеев Сергей', 'Тимофеева Наталья'), # 8\n ]\n\nstudents = [Student('Иванов', 'Сергей', grade[0], parents[0]),\n Student('Иванова', 'Екатерина', grade[0], parents[0]),\n Student('Петров', 'Иван', grade[0], parents[1]),\n Student('Петров', 'Кирилл', grade[1], parents[1]),\n Student('Сидоров', 'Алексей', grade[1], parents[2]),\n Student('Сидорова', 'Евгения', grade[3], parents[2]),\n Student('Поляков', 'Евгений', grade[3], parents[3]),\n Student('Полякова', 'Ольга', grade[4], parents[3]),\n Student('Семёнова', 'Екатерина', grade[4], parents[4]),\n Student('Семёнов', 'Андрей', grade[4], parents[4]),\n Student('Дрябезгов', 'Семён', grade[6], parents[5]),\n Student('Дрябезгов', 'Андрей', grade[6], parents[5]),\n Student('Шитов', 'Демид', grade[6], parents[6]),\n Student('Шитов', 'Меланья', grade[6], parents[6]),\n Student('Шитов', 'Роман', grade[6], parents[6]),\n Student('Жуков', 'Алексей', grade[5], parents[7]),\n Student('Жуков', 'Егор', grade[5], parents[7]),\n Student('Жуков', 'Никита', grade[5], parents[7]),\n Student('Жукова', 'Елена', grade[5], parents[7]),\n Student('Тимофеева', 'Наталья', grade[2], parents[8]),\n Student('Тимофеев', 'Сергей', grade[2], parents[8]),\n Student('Тимофеев', 'Пётр', grade[2], parents[8]),\n Student('Тимофеев', 'Анатолий', grade[2], parents[8]),\n Student('Тимофеева', 'Елена', grade[2], parents[8]),\n ]\n\nteachers = [Teacher('Тарасов', 'Павел', discipline[0], (grade[0], grade[1], grade[4])),\n Teacher('Кадочников', 'Алексей', discipline[1], (grade[0], grade[1], grade[4], grade[2])),\n Teacher('Майков', 'Павел', discipline[2], (grade[0], grade[1], grade[4])),\n Teacher('Доу', 'Джон', discipline[3], (grade[5], grade[6], grade[7])),\n Teacher('Майков', 'Павел', discipline[4], (grade[5], grade[3], grade[2])),\n ]\n\n\ndef get_student_by_name(surname, name):\n student = None\n for stud in students:\n if stud.surname == surname and stud.name == name:\n student = stud\n break\n\n return student\n\n\n# Выбранная и заполненная данными структура должна решать следующие задачи:\n# 1. Получить полный список всех классов школы\ndef print_classes():\n print('Классы в школе')\n for item in grade:\n print(item)\n\n\n# 2. Получить список всех учеников в указанном классе(каждый ученик отображается в формате \"Фамилия И.О.\")\n\ndef get_students_by_grade(grade_num, grade_letter):\n print(f'Ученики {grade_num}{grade_letter} класса:')\n for stud in students:\n if stud.grade.num == grade_num and f'{stud.grade.letter}'.upper() == grade_letter.upper():\n print(stud)\n\n\n# 3. Получить список всех предметов указанного ученика (Ученик --> Класс --> Учителя --\n\ndef get_disciples_by_student(surname, name):\n student = get_student_by_name(surname, name)\n\n if not student:\n print('Нет такого ученика')\n return\n\n st_teachers = []\n for teacher in teachers:\n if student.grade in teacher.grades:\n st_teachers.append(teacher)\n\n print(f'Дисциплины ученика {surname} {name}')\n for item in st_teachers:\n print(item.discipline)\n\n\n# 4. Узнать ФИО родителей указанного ученика\n\ndef get_parents_by_student(surname, name):\n print(f'ученик {surname} {name}')\n student = get_student_by_name(surname, name)\n\n if not student:\n print('Нет такого ученика')\n return\n\n print(student.parents)\n\n\n# 5. Получить список всех Учителей, преподающих в указанном классе\n\ndef get_teacher_by_grade(num, letter):\n st_grade = None\n for item in grade:\n if item.num == num and str(item.letter).upper() == letter.upper():\n st_grade = item\n print(st_grade)\n break\n\n if not st_grade:\n print('нет такого класса в школе')\n return\n\n st_teachers = []\n for teacher in teachers:\n if st_grade in teacher.grades:\n st_teachers.append(teacher)\n\n for i in st_teachers:\n print(i)\n\n\nif __name__ == '__main__':\n print_classes()\n\n get_students_by_grade(5, 'А')\n\n get_disciples_by_student('Шитов', 'Демид')\n get_disciples_by_student('Жуков', 'Егор')\n\n get_parents_by_student('Шитов', 'Демид')\n\n get_teacher_by_grade(7, 'а')\n pass","sub_path":"lesson06/home_work/hw06_normal.py","file_name":"hw06_normal.py","file_ext":"py","file_size_in_byte":7366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"513967997","text":"from bs4 import BeautifulSoup\nimport requests\nimport random\n\n\ndef Movies_finder():\n st_yr = int(input(\"From Year \"))\n en_yr = int(input(\"to year \"))\n list = []\n while st_yr <= en_yr:\n url = \"https://en.wikipedia.org/wiki/\" + str(st_yr) + \"_in_film\"\n web_code = requests.get(url)\n plain_text = web_code.text\n soup = BeautifulSoup(plain_text ,'html.parser')\n for movietable in soup.findAll('tr' ):\n for moviecolumn in movietable.findAll('td'):\n for moviedetails in moviecolumn.findAll('i'):\n for namelink in moviedetails.findAll({'a':'title'}):\n names = namelink.get('title')\n movies = \"https://en.wikipedia.org/wiki/\" + names.replace(\" \", \"_\")\n movieslink = movies.replace(\"'\" , \"%27\")\n Movie_name = names + ' -- ' + movieslink\n try:\n if int(names[-10:-6]) < st_yr:\n pass\n else:\n list.append(str(Movie_name))\n except:\n list.append(str(Movie_name))\n\n st_yr += 1\n\n max_value = len(list)\n user_input = 0\n while user_input == 0:\n random_number = random.randrange(1, max_value)\n print(list[random_number])\n user_input = int(input(\"For next Movie press 0 and Enter else press any other number other than 0 and press Enter :\\n\"))\n\n\nMovies_finder()","sub_path":"Movies-Scraper/Movies scraper.py","file_name":"Movies scraper.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"269245155","text":"import tensorflow as tf\nfrom tensorflow.python.ops import array_ops\nimport numpy as np\nimport keras.backend as K\n\n\ndef focal_loss(y_true, y_pred, gamma=2):\n r\"\"\"Compute focal loss for predictions.\n Multi-labels Focal loss formula:\n FL = -alpha * (z-p)^gamma * log(p) -(1-alpha) * p^gamma * log(1-p)\n ,which alpha = 0.25, gamma = 2, p = sigmoid(x), z = target_tensor.\n Args:\n y_pred: A float tensor of shape [batch_size, num_anchors,\n num_classes] representing the predicted logits for each class\n y_true: A float tensor of shape [batch_size, num_anchors,\n num_classes] representing one-hot encoded classification targets\n alpha: A scalar tensor for focal loss alpha hyper-parameter\n gamma: A scalar tensor for focal loss gamma hyper-parameter\n Returns:\n loss: A (scalar) tensor representing the value of the loss function\n \"\"\"\n # transform back to logits\n zeros = array_ops.zeros_like(y_pred, dtype=y_pred.dtype)\n\n # For poitive prediction, only need consider front part loss, back part is 0;\n # target_tensor > zeros <=> z=1, so poitive coefficient = z - p.\n pos_p_sub = array_ops.where(y_true > zeros, y_true - y_pred, zeros)\n\n # For negative prediction, only need consider back part loss, front part is 0;\n # target_tensor > zeros <=> z=1, so negative coefficient = 0.\n neg_p_sub = array_ops.where(y_true > zeros, zeros, y_pred)\n per_entry_cross_ent = pos_p_sub ** gamma * tf.log(tf.clip_by_value(y_pred, 1e-8, 1.0)) - \\\n neg_p_sub ** gamma * tf.log(tf.clip_by_value(1.0 - y_pred, 1e-8, 1.0))\n\n return K.mean(tf.reduce_sum(per_entry_cross_ent, axis=-1), axis=-1)\n\n\ndef precision_recall_auc_loss(labels, logits, precision_range=(0.0, 1.0),\n num_anchors=20, weights=1.0,\n dual_rate_factor=0.1, label_priors=None,\n surrogate_type='xent',\n lambdas_initializer=tf.constant_initializer(1.0),\n reuse=None, variables_collections=None,\n trainable=True, scope=None):\n \"\"\"Computes precision-recall AUC loss.\n\n The loss is based on a sum of losses for recall at a range of\n precision values (anchor points). This sum is a Riemann sum that\n approximates the area under the precision-recall curve.\n\n The per-example `weights` argument changes not only the coefficients of\n individual training examples, but how the examples are counted toward the\n constraint. If `label_priors` is given, it MUST take `weights` into account.\n That is,\n label_priors = P / (P + N)\n where\n P = sum_i (wt_i on positives)\n N = sum_i (wt_i on negatives).\n\n Args:\n labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels].\n logits: A `Tensor` with the same shape as `labels`.\n precision_range: A length-two tuple, the range of precision values over\n which to compute AUC. The entries must be nonnegative, increasing, and\n less than or equal to 1.0.\n num_anchors: The number of grid points used to approximate the Riemann sum.\n weights: Coefficients for the loss. Must be a scalar or `Tensor` of shape\n [batch_size] or [batch_size, num_labels].\n dual_rate_factor: A floating point value which controls the step size for\n the Lagrange multipliers.\n label_priors: None, or a floating point `Tensor` of shape [num_labels]\n containing the prior probability of each label (i.e. the fraction of the\n training data consisting of positive examples). If None, the label\n priors are computed from `labels` with a moving average. See the notes\n above regarding the interaction with `weights` and do not set this unless\n you have a good reason to do so.\n surrogate_type: Either 'xent' or 'hinge', specifying which upper bound\n should be used for indicator functions.\n lambdas_initializer: An initializer for the Lagrange multipliers.\n reuse: Whether or not the layer and its variables should be reused. To be\n able to reuse the layer scope must be given.\n variables_collections: Optional list of collections for the variables.\n trainable: If `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n scope: Optional scope for `variable_scope`.\n\n Returns:\n loss: A `Tensor` of the same shape as `logits` with the component-wise\n loss.\n other_outputs: A dictionary of useful internal quantities for debugging. For\n more details, see http://arxiv.org/pdf/1608.04802.pdf.\n lambdas: A Tensor of shape [1, num_labels, num_anchors] consisting of the\n Lagrange multipliers.\n biases: A Tensor of shape [1, num_labels, num_anchors] consisting of the\n learned bias term for each.\n label_priors: A Tensor of shape [1, num_labels, 1] consisting of the prior\n probability of each label learned by the loss, if not provided.\n true_positives_lower_bound: Lower bound on the number of true positives\n given `labels` and `logits`. This is the same lower bound which is used\n in the loss expression to be optimized.\n false_positives_upper_bound: Upper bound on the number of false positives\n given `labels` and `logits`. This is the same upper bound which is used\n in the loss expression to be optimized.\n\n Raises:\n ValueError: If `surrogate_type` is not `xent` or `hinge`.\n \"\"\"\n with tf.variable_scope(scope,\n 'precision_recall_auc',\n [labels, logits, label_priors],\n reuse=reuse):\n labels, logits, weights, original_shape = _prepare_labels_logits_weights(\n labels, logits, weights)\n num_labels = get_num_labels(logits)\n\n # Convert other inputs to tensors and standardize dtypes.\n dual_rate_factor = convert_and_cast(\n dual_rate_factor, 'dual_rate_factor', logits.dtype)\n\n # Create Tensor of anchor points and distance between anchors.\n precision_values, delta = _range_to_anchors_and_delta(\n precision_range, num_anchors, logits.dtype)\n # Create lambdas with shape [1, num_labels, num_anchors].\n lambdas, lambdas_variable = _create_dual_variable(\n 'lambdas',\n shape=[1, num_labels, num_anchors],\n dtype=logits.dtype,\n initializer=lambdas_initializer,\n collections=variables_collections,\n trainable=trainable,\n dual_rate_factor=dual_rate_factor)\n # Create biases with shape [1, num_labels, num_anchors].\n biases = tf.contrib.framework.model_variable(\n name='biases',\n shape=[1, num_labels, num_anchors],\n dtype=logits.dtype,\n initializer=tf.zeros_initializer(),\n collections=variables_collections,\n trainable=trainable)\n # Maybe create label_priors.\n label_priors = maybe_create_label_priors(\n label_priors, labels, weights, variables_collections)\n label_priors = tf.reshape(label_priors, [1, num_labels, 1])\n\n # Expand logits, labels, and weights to shape [batch_size, num_labels, 1].\n logits = tf.expand_dims(logits, 2)\n labels = tf.expand_dims(labels, 2)\n weights = tf.expand_dims(weights, 2)\n\n # Calculate weighted loss and other outputs. The log(2.0) term corrects for\n # logloss not being an upper bound on the indicator function.\n loss = weights * weighted_surrogate_loss(\n labels,\n logits + biases,\n surrogate_type=surrogate_type,\n positive_weights=1.0 + lambdas * (1.0 - precision_values),\n negative_weights=lambdas * precision_values)\n maybe_log2 = tf.log(2.0) if surrogate_type == 'xent' else 1.0\n maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype)\n lambda_term = lambdas * (1.0 - precision_values) * label_priors * maybe_log2\n per_anchor_loss = loss - lambda_term\n per_label_loss = delta * tf.reduce_sum(per_anchor_loss, 2)\n # Normalize the AUC such that a perfect score function will have AUC 1.0.\n # Because precision_range is discretized into num_anchors + 1 intervals\n # but only num_anchors terms are included in the Riemann sum, the\n # effective length of the integration interval is `delta` less than the\n # length of precision_range.\n scaled_loss = tf.div(per_label_loss,\n precision_range[1] - precision_range[0] - delta,\n name='AUC_Normalize')\n scaled_loss = tf.reshape(scaled_loss, original_shape)\n\n other_outputs = {\n 'lambdas': lambdas_variable,\n 'biases': biases,\n 'label_priors': label_priors,\n 'true_positives_lower_bound': true_positives_lower_bound(\n labels, logits, weights, surrogate_type),\n 'false_positives_upper_bound': false_positives_upper_bound(\n labels, logits, weights, surrogate_type)}\n\n return scaled_loss\n\n\ndef get_num_labels(labels_or_logits):\n \"\"\"Returns the number of labels inferred from labels_or_logits.\"\"\"\n if labels_or_logits.get_shape().ndims <= 1:\n return 1\n return labels_or_logits.get_shape()[1].value\n\n\ndef _create_dual_variable(name, shape, dtype, initializer, collections,\n trainable, dual_rate_factor):\n \"\"\"Creates a new dual variable.\n\n Dual variables are required to be nonnegative. If trainable, their gradient\n is reversed so that they are maximized (rather than minimized) by the\n optimizer.\n\n Args:\n name: A string, the name for the new variable.\n shape: Shape of the new variable.\n dtype: Data type for the new variable.\n initializer: Initializer for the new variable.\n collections: List of graph collections keys. The new variable is added to\n these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.\n trainable: If `True`, the default, also adds the variable to the graph\n collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as\n the default list of variables to use by the `Optimizer` classes.\n dual_rate_factor: A floating point value or `Tensor`. The learning rate for\n the dual variable is scaled by this factor.\n\n Returns:\n dual_value: An op that computes the absolute value of the dual variable\n and reverses its gradient.\n dual_variable: The underlying variable itself.\n \"\"\"\n # We disable partitioning while constructing dual variables because they will\n # be updated with assign, which is not available for partitioned variables.\n partitioner = tf.get_variable_scope().partitioner\n try:\n tf.get_variable_scope().set_partitioner(None)\n dual_variable = tf.contrib.framework.model_variable(\n name=name,\n shape=shape,\n dtype=dtype,\n initializer=initializer,\n collections=collections,\n trainable=trainable)\n finally:\n tf.get_variable_scope().set_partitioner(partitioner)\n # Using the absolute value enforces nonnegativity.\n dual_value = tf.abs(dual_variable)\n\n if trainable:\n # To reverse the gradient on the dual variable, multiply the gradient by\n # -dual_rate_factor\n dual_value = (tf.stop_gradient((1.0 + dual_rate_factor) * dual_value)\n - dual_rate_factor * dual_value)\n return dual_value, dual_variable\n\n\ndef true_positives_lower_bound(labels, logits, weights, surrogate_type):\n \"\"\"Calculate a lower bound on the number of true positives.\n\n This lower bound on the number of true positives given `logits` and `labels`\n is the same one used in the global objectives loss functions.\n\n Args:\n labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels].\n logits: A `Tensor` of shape [batch_size, num_labels] or\n [batch_size, num_labels, num_anchors]. If the third dimension is present,\n the lower bound is computed on each slice [:, :, k] independently.\n weights: Per-example loss coefficients, with shape broadcast-compatible with\n that of `labels`.\n surrogate_type: Either 'xent' or 'hinge', specifying which upper bound\n should be used for indicator functions.\n\n Returns:\n A `Tensor` of shape [num_labels] or [num_labels, num_anchors].\n \"\"\"\n maybe_log2 = tf.log(2.0) if surrogate_type == 'xent' else 1.0\n maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype)\n if logits.get_shape().ndims == 3 and labels.get_shape().ndims < 3:\n labels = tf.expand_dims(labels, 2)\n loss_on_positives = weighted_surrogate_loss(\n labels, logits, surrogate_type, negative_weights=0.0) / maybe_log2\n return tf.reduce_sum(weights * (labels - loss_on_positives), 0)\n\n\ndef false_positives_upper_bound(labels, logits, weights, surrogate_type):\n \"\"\"Calculate an upper bound on the number of false positives.\n\n This upper bound on the number of false positives given `logits` and `labels`\n is the same one used in the global objectives loss functions.\n\n Args:\n labels: A `Tensor` of shape [batch_size, num_labels]\n logits: A `Tensor` of shape [batch_size, num_labels] or\n [batch_size, num_labels, num_anchors]. If the third dimension is present,\n the lower bound is computed on each slice [:, :, k] independently.\n weights: Per-example loss coefficients, with shape broadcast-compatible with\n that of `labels`.\n surrogate_type: Either 'xent' or 'hinge', specifying which upper bound\n should be used for indicator functions.\n\n Returns:\n A `Tensor` of shape [num_labels] or [num_labels, num_anchors].\n \"\"\"\n maybe_log2 = tf.log(2.0) if surrogate_type == 'xent' else 1.0\n maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype)\n loss_on_negatives = weighted_surrogate_loss(\n labels, logits, surrogate_type, positive_weights=0.0) / maybe_log2\n return tf.reduce_sum(weights * loss_on_negatives, 0)\n\n\ndef maybe_create_label_priors(label_priors,\n labels,\n weights,\n variables_collections):\n \"\"\"Creates moving average ops to track label priors, if necessary.\n\n Args:\n label_priors: As required in e.g. precision_recall_auc_loss.\n labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels].\n weights: As required in e.g. precision_recall_auc_loss.\n variables_collections: Optional list of collections for the variables, if\n any must be created.\n\n Returns:\n label_priors: A Tensor of shape [num_labels] consisting of the\n weighted label priors, after updating with moving average ops if created.\n \"\"\"\n if label_priors is not None:\n label_priors = convert_and_cast(\n label_priors, name='label_priors', dtype=labels.dtype.base_dtype)\n return tf.squeeze(label_priors)\n\n label_priors = build_label_priors(\n labels,\n weights,\n variables_collections=variables_collections)\n return label_priors\n\n\ndef weighted_surrogate_loss(labels,\n logits,\n surrogate_type='xent',\n positive_weights=1.0,\n negative_weights=1.0,\n name=None):\n \"\"\"Returns either weighted cross-entropy or hinge loss.\n\n For example `surrogate_type` is 'xent' returns the weighted cross\n entropy loss.\n\n Args:\n labels: A `Tensor` of type `float32` or `float64`. Each entry must be\n between 0 and 1. `labels` can be a 2D tensor with shape\n [batch_size, num_labels] or a 3D tensor with shape\n [batch_size, num_labels, K].\n logits: A `Tensor` of the same type and shape as `labels`. If `logits` has\n shape [batch_size, num_labels, K], each slice [:, :, k] represents an\n 'attempt' to predict `labels` and the loss is computed per slice.\n surrogate_type: A string that determines which loss to return, supports\n 'xent' for cross-entropy and 'hinge' for hinge loss.\n positive_weights: A `Tensor` that holds positive weights and has the\n following semantics according to its shape:\n scalar - A global positive weight.\n 1D tensor - must be of size K, a weight for each 'attempt'\n 2D tensor - of size [num_labels, K'] where K' is either K or 1.\n The `positive_weights` will be expanded to the left to match the\n dimensions of logits and labels.\n negative_weights: A `Tensor` that holds positive weight and has the\n semantics identical to positive_weights.\n name: A name for the operation (optional).\n\n Returns:\n The weigthed loss.\n\n Raises:\n ValueError: If value of `surrogate_type` is not supported.\n \"\"\"\n with tf.name_scope(\n name, 'weighted_loss',\n [logits, labels, surrogate_type, positive_weights,\n negative_weights]) as name:\n if surrogate_type == 'xent':\n return weighted_sigmoid_cross_entropy_with_logits(\n logits=logits,\n labels=labels,\n positive_weights=positive_weights,\n negative_weights=negative_weights,\n name=name)\n elif surrogate_type == 'hinge':\n return weighted_hinge_loss(\n logits=logits,\n labels=labels,\n positive_weights=positive_weights,\n negative_weights=negative_weights,\n name=name)\n raise ValueError('surrogate_type %s not supported.' % surrogate_type)\n\n\ndef weighted_sigmoid_cross_entropy_with_logits(labels,\n logits,\n positive_weights=1.0,\n negative_weights=1.0,\n name=None):\n \"\"\"Computes a weighting of sigmoid cross entropy given `logits`.\n\n Measures the weighted probability error in discrete classification tasks in\n which classes are independent and not mutually exclusive. For instance, one\n could perform multilabel classification where a picture can contain both an\n elephant and a dog at the same time. The class weight multiplies the\n different types of errors.\n For brevity, let `x = logits`, `z = labels`, `c = positive_weights`,\n `d = negative_weights` The\n weighed logistic loss is\n\n ```\n c * z * -log(sigmoid(x)) + d * (1 - z) * -log(1 - sigmoid(x))\n = c * z * -log(1 / (1 + exp(-x))) - d * (1 - z) * log(exp(-x) / (1 + exp(-x)))\n = c * z * log(1 + exp(-x)) + d * (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))\n = c * z * log(1 + exp(-x)) + d * (1 - z) * (x + log(1 + exp(-x)))\n = (1 - z) * x * d + (1 - z + c * z ) * log(1 + exp(-x))\n = - d * x * z + d * x + (d - d * z + c * z ) * log(1 + exp(-x))\n ```\n\n To ensure stability and avoid overflow, the implementation uses the identity\n log(1 + exp(-x)) = max(0,-x) + log(1 + exp(-abs(x)))\n and the result is computed as\n\n ```\n = -d * x * z + d * x\n + (d - d * z + c * z ) * (max(0,-x) + log(1 + exp(-abs(x))))\n ```\n\n Note that the loss is NOT an upper bound on the 0-1 loss, unless it is divided\n by log(2).\n\n Args:\n labels: A `Tensor` of type `float32` or `float64`. `labels` can be a 2D\n tensor with shape [batch_size, num_labels] or a 3D tensor with shape\n [batch_size, num_labels, K].\n logits: A `Tensor` of the same type and shape as `labels`. If `logits` has\n shape [batch_size, num_labels, K], the loss is computed separately on each\n slice [:, :, k] of `logits`.\n positive_weights: A `Tensor` that holds positive weights and has the\n following semantics according to its shape:\n scalar - A global positive weight.\n 1D tensor - must be of size K, a weight for each 'attempt'\n 2D tensor - of size [num_labels, K'] where K' is either K or 1.\n The `positive_weights` will be expanded to the left to match the\n dimensions of logits and labels.\n negative_weights: A `Tensor` that holds positive weight and has the\n semantics identical to positive_weights.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of the same shape as `logits` with the componentwise\n weighted logistic losses.\n \"\"\"\n with tf.name_scope(\n name,\n 'weighted_logistic_loss',\n [logits, labels, positive_weights, negative_weights]) as name:\n labels, logits, positive_weights, negative_weights = prepare_loss_args(\n labels, logits, positive_weights, negative_weights)\n\n softplus_term = tf.add(tf.maximum(-logits, 0.0),\n tf.log(1.0 + tf.exp(-tf.abs(logits))))\n weight_dependent_factor = (\n negative_weights + (positive_weights - negative_weights) * labels)\n return (negative_weights * (logits - labels * logits) +\n weight_dependent_factor * softplus_term)\n\n\ndef weighted_hinge_loss(labels,\n logits,\n positive_weights=1.0,\n negative_weights=1.0,\n name=None):\n \"\"\"Computes weighted hinge loss given logits `logits`.\n\n The loss applies to multi-label classification tasks where labels are\n independent and not mutually exclusive. See also\n `weighted_sigmoid_cross_entropy_with_logits`.\n\n Args:\n labels: A `Tensor` of type `float32` or `float64`. Each entry must be\n either 0 or 1. `labels` can be a 2D tensor with shape\n [batch_size, num_labels] or a 3D tensor with shape\n [batch_size, num_labels, K].\n logits: A `Tensor` of the same type and shape as `labels`. If `logits` has\n shape [batch_size, num_labels, K], the loss is computed separately on each\n slice [:, :, k] of `logits`.\n positive_weights: A `Tensor` that holds positive weights and has the\n following semantics according to its shape:\n scalar - A global positive weight.\n 1D tensor - must be of size K, a weight for each 'attempt'\n 2D tensor - of size [num_labels, K'] where K' is either K or 1.\n The `positive_weights` will be expanded to the left to match the\n dimensions of logits and labels.\n negative_weights: A `Tensor` that holds positive weight and has the\n semantics identical to positive_weights.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of the same shape as `logits` with the componentwise\n weighted hinge loss.\n \"\"\"\n with tf.name_scope(\n name, 'weighted_hinge_loss',\n [logits, labels, positive_weights, negative_weights]) as name:\n labels, logits, positive_weights, negative_weights = prepare_loss_args(\n labels, logits, positive_weights, negative_weights)\n\n positives_term = positive_weights * labels * tf.maximum(1.0 - logits, 0)\n negatives_term = (negative_weights * (1.0 - labels)\n * tf.maximum(1.0 + logits, 0))\n return positives_term + negatives_term\n\n\ndef prepare_loss_args(labels, logits, positive_weights, negative_weights):\n \"\"\"Prepare arguments for weighted loss functions.\n\n If needed, will convert given arguments to appropriate type and shape.\n\n Args:\n labels: labels or labels of the loss function.\n logits: Logits of the loss function.\n positive_weights: Weight on the positive examples.\n negative_weights: Weight on the negative examples.\n\n Returns:\n Converted labels, logits, positive_weights, negative_weights.\n \"\"\"\n logits = tf.convert_to_tensor(logits, name='logits')\n labels = convert_and_cast(labels, 'labels', logits.dtype)\n if len(labels.get_shape()) == 2 and len(logits.get_shape()) == 3:\n labels = tf.expand_dims(labels, [2])\n\n positive_weights = convert_and_cast(positive_weights, 'positive_weights',\n logits.dtype)\n positive_weights = expand_outer(positive_weights, logits.get_shape().ndims)\n negative_weights = convert_and_cast(negative_weights, 'negative_weights',\n logits.dtype)\n negative_weights = expand_outer(negative_weights, logits.get_shape().ndims)\n return labels, logits, positive_weights, negative_weights\n\n\ndef convert_and_cast(value, name, dtype):\n \"\"\"Convert input to tensor and cast to dtype.\n\n Args:\n value: An object whose type has a registered Tensor conversion function,\n e.g. python numerical type or numpy array.\n name: Name to use for the new Tensor, if one is created.\n dtype: Optional element type for the returned tensor.\n\n Returns:\n A tensor.\n \"\"\"\n return tf.cast(tf.convert_to_tensor(value, name=name), dtype=dtype)\n\n\ndef expand_outer(tensor, rank):\n \"\"\"Expands the given `Tensor` outwards to a target rank.\n\n For example if rank = 3 and tensor.shape is [3, 4], this function will expand\n to such that the resulting shape will be [1, 3, 4].\n\n Args:\n tensor: The tensor to expand.\n rank: The target dimension.\n\n Returns:\n The expanded tensor.\n\n Raises:\n ValueError: If rank of `tensor` is unknown, or if `rank` is smaller than\n the rank of `tensor`.\n \"\"\"\n if tensor.get_shape().ndims is None:\n raise ValueError('tensor dimension must be known.')\n if len(tensor.get_shape()) > rank:\n raise ValueError(\n '`rank` must be at least the current tensor dimension: (%s vs %s).' %\n (rank, len(tensor.get_shape())))\n while len(tensor.get_shape()) < rank:\n tensor = tf.expand_dims(tensor, 0)\n return tensor\n\n\ndef build_label_priors(labels,\n weights=None,\n positive_pseudocount=1.0,\n negative_pseudocount=1.0,\n variables_collections=None):\n \"\"\"Creates an op to maintain and update label prior probabilities.\n\n For each label, the label priors are estimated as\n (P + sum_i w_i y_i) / (P + N + sum_i w_i),\n where y_i is the ith label, w_i is the ith weight, P is a pseudo-count of\n positive labels, and N is a pseudo-count of negative labels. The index i\n ranges over all labels observed during all evaluations of the returned op.\n\n Args:\n labels: A `Tensor` with shape [batch_size, num_labels]. Entries should be\n in [0, 1].\n weights: Coefficients representing the weight of each label. Must be either\n a Tensor of shape [batch_size, num_labels] or `None`, in which case each\n weight is treated as 1.0.\n positive_pseudocount: Number of positive labels used to initialize the label\n priors.\n negative_pseudocount: Number of negative labels used to initialize the label\n priors.\n variables_collections: Optional list of collections for created variables.\n\n Returns:\n label_priors: An op to update the weighted label_priors. Gives the\n current value of the label priors when evaluated.\n \"\"\"\n dtype = labels.dtype.base_dtype\n num_labels = get_num_labels(labels)\n\n if weights is None:\n weights = tf.ones_like(labels)\n\n # We disable partitioning while constructing dual variables because they will\n # be updated with assign, which is not available for partitioned variables.\n partitioner = tf.get_variable_scope().partitioner\n try:\n tf.get_variable_scope().set_partitioner(None)\n # Create variable and update op for weighted label counts.\n weighted_label_counts = tf.contrib.framework.model_variable(\n name='weighted_label_counts',\n shape=[num_labels],\n dtype=dtype,\n initializer=tf.constant_initializer(\n [positive_pseudocount] * num_labels, dtype=dtype),\n collections=variables_collections,\n trainable=False)\n weighted_label_counts_update = weighted_label_counts.assign_add(\n tf.reduce_sum(weights * labels, 0))\n\n # Create variable and update op for the sum of the weights.\n weight_sum = tf.contrib.framework.model_variable(\n name='weight_sum',\n shape=[num_labels],\n dtype=dtype,\n initializer=tf.constant_initializer(\n [positive_pseudocount + negative_pseudocount] * num_labels,\n dtype=dtype),\n collections=variables_collections,\n trainable=False)\n weight_sum_update = weight_sum.assign_add(tf.reduce_sum(weights, 0))\n\n finally:\n tf.get_variable_scope().set_partitioner(partitioner)\n\n label_priors = tf.div(\n weighted_label_counts_update,\n weight_sum_update)\n return label_priors\n\n\ndef _prepare_labels_logits_weights(labels, logits, weights):\n \"\"\"Validates labels, logits, and weights.\n\n Converts inputs to tensors, checks shape compatibility, and casts dtype if\n necessary.\n\n Args:\n labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels].\n logits: A `Tensor` with the same shape as `labels`.\n weights: Either `None` or a `Tensor` with shape broadcastable to `logits`.\n\n Returns:\n labels: Same as `labels` arg after possible conversion to tensor, cast, and\n reshape.\n logits: Same as `logits` arg after possible conversion to tensor and\n reshape.\n weights: Same as `weights` arg after possible conversion, cast, and reshape.\n original_shape: Shape of `labels` and `logits` before reshape.\n\n Raises:\n ValueError: If `labels` and `logits` do not have the same shape.\n \"\"\"\n # Convert `labels` and `logits` to Tensors and standardize dtypes.\n logits = tf.convert_to_tensor(logits, name='logits')\n labels = convert_and_cast(labels, 'labels', logits.dtype.base_dtype)\n weights = convert_and_cast(weights, 'weights', logits.dtype.base_dtype)\n\n try:\n labels.get_shape().merge_with(logits.get_shape())\n except ValueError:\n raise ValueError('logits and labels must have the same shape (%s vs %s)' %\n (logits.get_shape(), labels.get_shape()))\n\n original_shape = labels.get_shape().as_list()\n if labels.get_shape().ndims > 0:\n original_shape[0] = -1\n if labels.get_shape().ndims <= 1:\n labels = tf.reshape(labels, [-1, 1])\n logits = tf.reshape(logits, [-1, 1])\n\n if weights.get_shape().ndims == 1:\n # Weights has shape [batch_size]. Reshape to [batch_size, 1].\n weights = tf.reshape(weights, [-1, 1])\n if weights.get_shape().ndims == 0:\n # Weights is a scalar. Change shape of weights to match logits.\n weights *= tf.ones_like(logits)\n\n return labels, logits, weights, original_shape\n\n\ndef _range_to_anchors_and_delta(precision_range, num_anchors, dtype):\n \"\"\"Calculates anchor points from precision range.\n\n Args:\n precision_range: As required in precision_recall_auc_loss.\n num_anchors: int, number of equally spaced anchor points.\n dtype: Data type of returned tensors.\n\n Returns:\n precision_values: A `Tensor` of data type dtype with equally spaced values\n in the interval precision_range.\n delta: The spacing between the values in precision_values.\n\n Raises:\n ValueError: If precision_range is invalid.\n \"\"\"\n # Validate precision_range.\n if not 0 <= precision_range[0] <= precision_range[-1] <= 1:\n raise ValueError('precision values must obey 0 <= %f <= %f <= 1' %\n (precision_range[0], precision_range[-1]))\n if not 0 < len(precision_range) < 3:\n raise ValueError('length of precision_range (%d) must be 1 or 2' %\n len(precision_range))\n\n # Sets precision_values uniformly between min_precision and max_precision.\n values = np.linspace(start=precision_range[0],\n stop=precision_range[1],\n num=num_anchors + 2)[1:-1]\n precision_values = convert_and_cast(\n values, 'precision_values', dtype)\n delta = convert_and_cast(\n values[0] - precision_range[0], 'delta', dtype)\n # Makes precision_values [1, 1, num_anchors].\n precision_values = expand_outer(precision_values, 3)\n return precision_values, delta\n","sub_path":"src/Nets/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":32769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"617200062","text":"from django.conf.urls import url\n\nfrom managers.api import views\n\nurlpatterns = [\n url(r'^$', views.ManagerListAPIView.as_view(), name='list'),\n url(r'^create/$', views.ManagerCreateAPIView.as_view(), name='create'),\n url(r'^(?P\\d+)/detail/$', views.ManagerRetrieveAPIView.as_view(), name='detail'),\n url(r'^(?P\\d+)/update/$', views.ManagerUpdateAPIView.as_view(), name='update'),\n url(r'^(?P\\d+)/delete/$', views.ManagerDeleteAPIView.as_view(), name='delete'),\n url(r'^staff/$', views.StaffManagerListAPIView.as_view(), name='staff_list'),\n url(r'^staff/create/$', views.StaffManagerCreateAPIView.as_view(), name='staff_create'),\n url(r'^staff/(?P\\d+)/detail/$', views.StaffManagerRetrieveAPIView.as_view(), name='staff_detail'),\n url(r'^staff/(?P\\d+)/update/$', views.StaffManagerUpdateAPIView.as_view(), name='staff_update'),\n url(r'^staff/(?P\\d+)/delete/$', views.StaffManagerDeleteAPIView.as_view(), name='staff_delete'),\n]\n","sub_path":"managers/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"183490373","text":"#! /usr/bin/python\n\n# centrifugeBuildTests.py seq.fna taxid.map\n\nimport sys\n\nfasta = open(sys.argv[1],\"r\")\ntaxIDmap = open(sys.argv[2],\"r\")\noutfile = open(\"centrifuge_build_tests.out\",\"w\")\n\ntaxIDlist = []\nseqNameList = []\ntestsFailed = 0\nfor line in taxIDmap:\n\ttaxIDlist.append(line.split(\"\\t\")[0])\n\tif len(line.split(\"\\t\")) > 2:\n\t\tprint (\"%s contains more than 2 fields\" % line)\n\t\toutfile.write(\"%s contains more than 2 fields\" % line)\n\t\ttestsFailed += 1\nfor seq in fasta:\n\tif seq.startswith(\">\"):\n\t\tif seq.strip(\">\\n\").split(\" \")[0] not in taxIDlist:\n\t\t\tprint(\"%s found in sequence file but missing from tax ID map\" % seq.strip(\">\\n\"))\n\t\t\toutfile.write(\"%s found in sequence file but missing from tax ID map\" % seq.strip(\">\\n\"))\n\t\t\ttestsFailed += 1\n\t\tseqNameList.append(seq.strip(\">\\n\").split(\" \")[0])\nfor item in taxIDlist:\n\tif item not in seqNameList:\n\t\tprint(\"%s found in tax ID map but missing from sequence file\" % item )\n\t\toutfile.write(\"%s found in tax ID map but missing from sequence file\" % item )\n\t\ttestsFailed += 1\nif len(taxIDlist) != len(seqNameList):\n\tprint(\"Tax ID map and sequence file have difference number of entries\")\n\tprint(\"Tax ID map: %d\" % len(taxIDlist))\n\tprint(\"Sequence file: %d\" % len(seqNameList))\n\toutfile.write(\"Tax ID map and sequence file have difference number of entries\")\n\toutfile.write(\"Tax ID map: %d\" % len(taxIDlist))\n\toutfile.write(\"Sequence file: %d\" % len(seqNameList))\n\ttestsFailed += 1\nif testsFailed == 0:\n\tprint(\"All tests passed!\")\n\toutfile.write(\"All tests passed!\")\nelse:\n\tprint(\"Failed %d tests\" % testsFailed)\n\toutfile.write(\"Failed %d tests\" % testsFailed)\n\nfasta.close()\ntaxIDmap.close()\noutfile.close()\n","sub_path":"scripts/centrifugeBuildTests.py","file_name":"centrifugeBuildTests.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"33876528","text":"import numpy as np\r\nfrom functools import partial\r\nimport os\r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\nimport h5py\r\n\r\nimport bokeh\r\n\r\nfrom small_lab_gui.helper import bokeh_gui_helper as bgh\r\nfrom small_lab_gui.helper import bokeh_plot_helper as bph\r\nfrom small_lab_gui.helper import measurement\r\n\r\ntesting = True\r\nif not testing:\r\n # for the lab\r\n from small_lab_gui.digitizers.digitizer_zi_hf2li import hf2li\r\n from small_lab_gui.axes.linear_axis_jena_eda4 import \\\r\n linear_axis_controller_jena_eda4\r\n from small_lab_gui.axes.linear_axis_jena_eda4 import \\\r\n linear_axis_piezojena_eda4\r\n from small_lab_gui.helper.postToELOG import elog\r\nelse:\r\n # for testing\r\n from small_lab_gui.digitizers.digitizer_zi_hf2li_dummy import hf2li_dummy \\\r\n as hf2li\r\n from small_lab_gui.axes.linear_axis_dummy import linear_axis_controller_dummy \\\r\n as linear_axis_controller_jena_eda4\r\n from small_lab_gui.axes.linear_axis_dummy import linear_axis_dummy \\\r\n as linear_axis_piezojena_eda4\r\n from small_lab_gui.helper.postToELOG_dummy import elog_dummy as elog\r\n\r\n\r\nclass lockin_alignment_gui():\r\n def __init__(self, doc, running, lockin_digitizer, delayer):\r\n self.title = 'Alignment'\r\n # measurement thread\r\n self.measurement = None\r\n # bokeh doc for callback\r\n self.doc = doc\r\n # digitizer card\r\n self.lockin_digitizer = lockin_digitizer\r\n # global measurement running indicator\r\n self.running = running\r\n # delay piezo\r\n self.delayer = delayer\r\n\r\n # set up inputs\r\n self.startBtn = bokeh.models.widgets.Button(\r\n label='Start', button_type='success')\r\n self.timeconstantInput = bokeh.models.widgets.TextInput(\r\n title='Time constant [sec]', value='0.05')\r\n self.orderInput = bokeh.models.widgets.TextInput(\r\n title='Filter Order', value='6')\r\n self.integrationInput = bokeh.models.widgets.TextInput(\r\n title='Integration time [sec]', value='1')\r\n self.piezoPos = bokeh.models.widgets.TextInput(\r\n title='Piezo Position [um]', value='1.0')\r\n\r\n # set up outputs\r\n self.signalIndicator = bokeh.models.widgets.Button(\r\n label='Rate', button_type='primary')\r\n self.angleIndicator = bokeh.models.widgets.Button(\r\n label='Angle', button_type='primary')\r\n\r\n # arrange layout\r\n self.inputs = bokeh.layouts.widgetbox(\r\n self.startBtn, self.timeconstantInput,\r\n self.integrationInput, self.piezoPos)\r\n self.indicators = bokeh.layouts.widgetbox(\r\n self.signalIndicator, self.angleIndicator)\r\n self.layout = bokeh.layouts.row(\r\n self.inputs, self.indicators, width=800)\r\n\r\n # start thread callback\r\n self.startBtn.on_click(self.start)\r\n\r\n def start(self):\r\n # in case this measurement is running, stop it\r\n if self.running.am_i_running(self):\r\n self.stop()\r\n # in case a different measurement is running, do nothing\r\n elif self.running.is_running():\r\n pass\r\n else:\r\n # set running indicator to block double readout\r\n self.running.now_running(self)\r\n # switch start to stop button\r\n self.startBtn.label = 'Stop'\r\n self.startBtn.button_type = 'danger'\r\n # set timeconstant and integration time\r\n self.timeconstant = float(self.timeconstantInput.value)\r\n self.integration = float(self.integrationInput.value)\r\n\r\n # create the measurement thread\r\n self.measurement = measurement.measurement(\r\n inputs=None,\r\n sequence=[\r\n self.lockin_digitizer.readout_continuous,\r\n measurement.sleep_function(0.1)],\r\n update=measurement.bokeh_update_function(\r\n self.update, self.doc),\r\n init=partial(\r\n self.lockin_digitizer.setup,\r\n integration=self.integration,\r\n timeconstant=self.timeconstant),\r\n finish=None,\r\n save_output=False)\r\n # start the measurement thread\r\n self.measurement.start()\r\n\r\n def stop(self):\r\n if self.measurement is not None:\r\n # measurement is inherited from Thread,\r\n # so one can wait for it using join\r\n self.measurement.stop()\r\n self.measurement.join()\r\n self.running.now_stopped()\r\n self.startBtn.label = 'Start'\r\n self.startBtn.button_type = 'success'\r\n\r\n def close(self):\r\n self.stop()\r\n\r\n def update(self, data):\r\n if not (data is None):\r\n r = data[0]['r']\r\n theta = data[0]['theta']\r\n x = np.real(r*np.exp(1j*theta))\r\n y = np.imag(r*np.exp(1j*theta))\r\n self.signalIndicator.label = str(x)\r\n self.angleIndicator.label = str(y)\r\n\r\n\r\nclass lockin_measurement_gui(lockin_alignment_gui):\r\n def __init__(self, doc, running, lockin_digitizer, delayer, logbook=None):\r\n super().__init__(doc, running, lockin_digitizer, delayer)\r\n self.title = 'Measurement'\r\n self.logbook = logbook\r\n\r\n # measurement source and line plot\r\n self.linePlot = bph.plot_2d()\r\n self.linePlot.line(legend='Current 2', line_color='red')\r\n self.linePlot.line(legend='Current 5', line_color='blue')\r\n\r\n self.linePlotMean = bph.plot_2d()\r\n self.linePlotMean.line(legend='Current 2', line_color='red')\r\n self.linePlotMean.line(legend='Current 5', line_color='blue')\r\n\r\n # save button\r\n self.saveBtn = bokeh.models.widgets.Button(\r\n label='Save Spectrum', button_type='success')\r\n self.saveBtn.on_click(self.save_spectrum)\r\n self.saveNameInput = bokeh.models.widgets.TextInput(\r\n title='Legend Name', value='Name')\r\n\r\n # scan table button\r\n self.scanTableBtn = bokeh.models.widgets.Toggle(label='Scan Table')\r\n\r\n # measurement inputs\r\n self.zeroDelInput = bokeh.models.widgets.TextInput(\r\n title='Zero Delay [um]', value='50.')\r\n self.startDelInput = bokeh.models.widgets.TextInput(\r\n title='Start Delay [fs]', value='-10.')\r\n self.stopDelInput = bokeh.models.widgets.TextInput(\r\n title='Stop Delay [fs]', value='10.')\r\n self.stepSizeInput = bokeh.models.widgets.TextInput(\r\n title='Step Size [fs]', value='0.5')\r\n self.comment = bokeh.models.widgets.TextAreaInput(\r\n title='Comment', value='', rows=10)\r\n\r\n # reclaim piezo button\r\n self.reclaimPiezoBtn = bokeh.models.widgets.Button(\r\n label='Reclaim Piezo', button_type='success')\r\n self.reclaimPiezoBtn.on_click(self.reclaimPiezo)\r\n\r\n # arrange items\r\n self.inputs = bokeh.layouts.widgetbox(\r\n self.startBtn, self.timeconstantInput, self.orderInput,\r\n self.integrationInput, self.zeroDelInput, self.startDelInput,\r\n self.stopDelInput, self.stepSizeInput, self.saveBtn,\r\n self.saveNameInput, self.scanTableBtn, self.comment,\r\n self.reclaimPiezoBtn)\r\n self.layout = bokeh.layouts.row(\r\n self.inputs,\r\n bokeh.layouts.column(\r\n self.linePlot.element, self.linePlotMean.element))\r\n\r\n def start(self):\r\n # in case this measurement is running, stop it\r\n if self.running.am_i_running(self):\r\n self.stop()\r\n # in case a different measurement is running, do nothing\r\n elif self.running.is_running():\r\n pass\r\n else:\r\n # set running indicator to block double readout\r\n self.running.now_running(self)\r\n self.startBtn.label = 'Stop'\r\n self.startBtn.button_type = 'danger'\r\n # integration time\r\n self.integration = float(self.integrationInput.value)\r\n self.order = int(self.orderInput.value)\r\n self.timeconstant = float(self.timeconstantInput.value)\r\n # delay vector setup\r\n if self.scanTableBtn.active:\r\n self.delays = np.loadtxt('scantable.txt')\r\n else:\r\n self.delays = np.arange(float(self.startDelInput.value),\r\n float(self.stopDelInput.value),\r\n float(self.stepSizeInput.value))\r\n self.piezo_values = (float(self.zeroDelInput.value) +\r\n 3.0e8 * self.delays*1.0e-15 / 2. * 1e6)\r\n\r\n # scan start time for save name\r\n self.now = datetime.datetime.now()\r\n\r\n # measurement thread\r\n self.measurement = measurement.measurement(\r\n inputs=[[pv, None] for pv in self.piezo_values],\r\n sequence=[\r\n measurement.single_input_sequence_function(\r\n self.delayer.abs_move),\r\n self.lockin_digitizer.frame],\r\n update=measurement.bokeh_update_function(\r\n self.update, self.doc),\r\n init=partial(\r\n self.lockin_digitizer.setup,\r\n integration=self.integration,\r\n timeconstant=self.timeconstant, order=self.order),\r\n finish=measurement.bokeh_no_input_finish_function(\r\n self.stop, self.doc),\r\n save_output=True)\r\n self.measurement.start()\r\n\r\n def save_spectrum(self):\r\n self.linePlot.save_current(name=self.saveNameInput.value, num=0)\r\n\r\n def reclaimPiezo(self):\r\n self.delayer.controller.reinit()\r\n self.delayer.reinit()\r\n\r\n def update(self, data):\r\n # check if data has contents\r\n if not (data is None):\r\n # loop sub steps\r\n curdelays = self.delays[0:len(data)]\r\n xs = np.real([d[1]['sig'] for d in data])\r\n ys = np.imag([d[1]['sig'] for d in data])\r\n rs = [d[1]['r'] for d in data]\r\n thetas = [d[1]['theta'] for d in data]\r\n xs2 = np.real([d[1]['sig2'] for d in data])\r\n ys2 = np.imag([d[1]['sig2'] for d in data])\r\n rs2 = [d[1]['r2'] for d in data]\r\n thetas2 = [d[1]['theta2'] for d in data]\r\n\r\n # update plots\r\n try:\r\n self.linePlot.update(num=0, x=curdelays, y=xs)\r\n self.linePlot.update(num=1, x=curdelays, y=xs2)\r\n self.linePlotMean.update(\r\n num=0, x=curdelays, y=xs-np.mean(xs))\r\n self.linePlotMean.update(\r\n num=1, x=curdelays, y=xs2-np.mean(xs2))\r\n except Exception as e:\r\n print('plot error')\r\n print(e)\r\n\r\n # save data\r\n try:\r\n os.makedirs(\r\n self.now.strftime('%Y-%m') + '/' +\r\n self.now.strftime('%Y-%m-%d'), exist_ok=True)\r\n fname = (self.now.strftime('%Y-%m') + '/'\r\n + self.now.strftime('%Y-%m-%d')\r\n + '/scan_lockin_'\r\n + self.now.strftime('%Y-%m-%d-%H-%M-%S'))\r\n\r\n # save data to hdf5 file\r\n with h5py.File(fname + '.hdf5', 'w') as f:\r\n f.create_dataset('delays', data=curdelays)\r\n f.create_dataset('rs', data=rs)\r\n f.create_dataset('thetas', data=thetas)\r\n f.create_dataset('xs', data=xs)\r\n f.create_dataset('ys', data=ys)\r\n f.create_dataset('rs2', data=rs2)\r\n f.create_dataset('thetas2', data=thetas2)\r\n f.create_dataset('xs2', data=xs2)\r\n f.create_dataset('ys2', data=ys2)\r\n f.create_dataset(\r\n 'comment', data=self.comment.value,\r\n dtype=h5py.special_dtype(vlen=str))\r\n f.flush()\r\n\r\n # save comment to separate txt file\r\n with open(fname + '.txt', 'w') as f:\r\n f.write(self.comment.value)\r\n\r\n # last step, save picture and scan to logbook\r\n if len(data) == len(self.delays):\r\n plt.clf()\r\n plt.plot(curdelays, xs)\r\n plt.plot(curdelays, xs2)\r\n plt.savefig(fname + '.pdf')\r\n plt.savefig(fname + '.png')\r\n if self.logbook:\r\n self.logbook.post(\r\n author='auto-save',\r\n subject='Current Scan: ' + fname + '.hdf5',\r\n text=self.comment.value, filename=fname + '.png')\r\n except Exception as e:\r\n print('save error')\r\n print(e)\r\n\r\n\r\nclass lockin_session_handler(bgh.bokeh_gui_session_handler):\r\n def open_session(self, doc):\r\n # create object to determine if some measurement is currently running\r\n running = bgh.running()\r\n\r\n # open hardware\r\n # zurich instruments lock-in digitzer\r\n digitizer = hf2li()\r\n\r\n # delay light pulse via piezo\r\n # pi piezo\r\n # movement_server = linear_axis.linear_axis_controller_remote()\r\n # piezo = linear_axis.linear_axis_remote(movement_server, 'piezo')\r\n # jena piezo\r\n jena_controller = linear_axis_controller_jena_eda4(\r\n port='COM9', baud=9600)\r\n piezo = linear_axis_piezojena_eda4(jena_controller, 0)\r\n\r\n # open logbook to auto-save scans\r\n logbook = elog(host='localhost', port=8080, logbook='demo')\r\n\r\n # alignment tab\r\n alignmentgui = lockin_alignment_gui(\r\n doc=doc,\r\n running=running,\r\n lockin_digitizer=digitizer,\r\n delayer=piezo)\r\n\r\n # measurement tab\r\n measurementgui = lockin_measurement_gui(\r\n doc=doc,\r\n running=running,\r\n lockin_digitizer=digitizer,\r\n delayer=piezo,\r\n logbook=logbook)\r\n\r\n self.title = 'Lockin Readout'\r\n self.tabs = [\r\n {'layout': alignmentgui.layout, 'title': alignmentgui.title},\r\n {'layout': measurementgui.layout, 'title': measurementgui.title}]\r\n\r\n # this list is auto-closed, all close functions of the\r\n # added objects are called at session destruction\r\n self.close_list.append(alignmentgui)\r\n self.close_list.append(measurementgui)\r\n self.close_list.append(piezo)\r\n self.close_list.append(digitizer)\r\n\r\n\r\nprint('start lockin')\r\n# start the server\r\nbgh.bokeh_gui_helper(lockin_session_handler(), 5025)\r\n","sub_path":"lockin.py","file_name":"lockin.py","file_ext":"py","file_size_in_byte":14932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"294448598","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom EABooleanController import *\nimport os\nfrom time import sleep\n\n##\n## @brief Clase para la gestion de 3 leds\n##\nclass EALedPrinter(object):\n\t\"\"\"docstring for EALedPrinter\"\"\"\n\tdef __init__(self, l1,l2,l3):\n\t\tself.led1 = EABooleanController(l1,'OUT')\n\t\tself.led2 = EABooleanController(l2,'OUT')\n\t\tself.led3 = EABooleanController(l3,'OUT')\n\t\tsuper(EALedPrinter, self).__init__()\n\t\t\n\t##\n\t## @brief Se encarga de iluminar los leds segun el array\n\t## @param arr Array de iluminación de 3 posiciones\n\t##\n\tdef printLedArray(self,arr):\n\t\tif(arr[0] == 1):\n\t\t\tself.led1.setOn()\n\t\telse:\n\t\t\tself.led1.setOff()\n\t\tif(arr[1] == 1):\n\t\t\tself.led2.setOn()\n\t\telse:\n\t\t\tself.led2.setOff()\n\t\tif(arr[2] == 1):\n\t\t\tself.led3.setOn()\n\t\telse:\n\t\t\tself.led3.setOff()\n\n\t##\n\t## @brief Realiza una animación de 3 leds\n\t## @param self The object\n\t## @param frameMatrix Matriz de frames [[1,0,0],[1,0,0]]\n\t## @param tim Tiempo de espera entre frames\n\t##\n\tdef playAnimation(self,frameMatrix,tim):\n\t\ti = 0\n\t\twhile(i < len(frameMatrix)):\n\t\t\tself.printLedArray(frameMatrix[i])\n\t\t\tsleep(tim)\n\t\t\ti+=1\n","sub_path":"EALedPrinter.py","file_name":"EALedPrinter.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"153507303","text":"#encoding:utf-8\nimport tkinter\nfrom socket import *\n\nimport threading\nimport time\nfrom datetime import datetime\n\ns = socket(AF_INET,SOCK_DGRAM) # 创建 socket 对象\n\n\n\ndef thredt_it():\n t = threading.Thread(target=func)\n t.setDaemon(True)\n # 启动\n t.start()\n\ndef SendMsg():\n t2 = threading.Thread(target=func2)\n t2.start()\n\ndef func2():\n global s\n t = input_text.get()\n host = ipplace_text4.get()\n port = port_text6.get()\n s.connect((host, int(port)))\n s.sendto(bytes(t, encoding='utf-8'),(host,int(port)))\n\ndef func():\n global s\n host = ipplace_text.get()\n port = port_text.get()\n s.bind((host, int(port)))\n text.insert(tkinter.INSERT, '本机进程启动成功...' + ' ')\n text.insert(tkinter.INSERT, 'host:'+host+'port:'+port)\n while True:\n data, address = s.recvfrom(1024)\n data = bytes.decode(data)\n text.insert(tkinter.INSERT,str(address) + ' :' + str(data))\n s.close()\n\n\nwin = tkinter.Tk()\nwin.geometry(\"500x700\")\nwin.title('UDPproce2')\n\n\nipplace_label = tkinter.Label(win,width=10,text='ip地址:')\nipplace_label.pack()\n\nipplace_text = tkinter.Entry(win)\nipplace_text.pack()\n\nport_label = tkinter.Label(win,width=10,text='端口号:')\nport_label.pack()\n\nport_text = tkinter.Entry(win)\nport_text.pack()\n\nbutton1 = tkinter.Button(win,text='启动',bg='pink',width=10,height=1,command=thredt_it)\nbutton1.pack(pady=10)\n\ninput_text_label = tkinter.Label(win,width=20,text='请输入内容:')\ninput_text_label.pack()\n\ninput_text = tkinter.Entry(win,width=100)\ninput_text.pack()\n\nbutton2 = tkinter.Button(win,text='发送',bg='pink',width=10,height=1,command=SendMsg)\nbutton2.pack(pady=10)\n\n\n\n\nipplace_labe3 = tkinter.Label(win,width=10,text='目标ip:')\nipplace_labe3.pack()\n\nipplace_text4 = tkinter.Entry(win)\nipplace_text4.pack()\n\nport_labe5 = tkinter.Label(win,width=10,text='目标端口号:')\nport_labe5.pack()\n\nport_text6 = tkinter.Entry(win)\nport_text6.pack()\n\n\n\ntext_label = tkinter.Label(win,width=10,text='聊天记录:')\ntext_label.pack()\n\ntext = tkinter.Text(win,width=100,height=20)\ntext.pack()\n\nbutton3 = tkinter.Button(win,text='清空聊天记录',bg='pink',width=10,height=1,command=SendMsg)\nbutton3.pack(pady=10)\n\nbutton5 = tkinter.Button(win,text='退出',bg='pink',width=10,height=1,command=lambda :win.quit())\nbutton5.pack(pady=10)\n\nwin.mainloop()\n","sub_path":"tkinter/tkinter网络编程/Udp进程通信/client1.py","file_name":"client1.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"634060969","text":"# -*- coding: utf-8 -*-\nimport manager_network\nfrom _user import User\nfrom _MODEL import MODEL\n\nsuper_user_groups = ['admin']\n\ndef lambda_handler(event, context):\n response = {\n 'statusCode': 200,\n 'headers': manager_network.get_response_header(),\n 'body': None,\n }\n\n session = manager_network.get_session(event)\n if session is None:\n manager_network.put_response_message(response, '1')\n return response\n\n item_id = manager_network.get_param(event, 'id')\n model = MODEL.get_item(item_id)\n\n if model['userId'] != session.userId:\n user = User.get_by_id(session.userId)\n if user.group not in super_user_groups:\n manager_network.put_response_message(response, '1')\n return response\n\n MODEL.delete_item(item_id)\n manager_network.put_response_message(response, '0')\n return response\n","sub_path":"serverless/template/lambda_delete_MODEL.py","file_name":"lambda_delete_MODEL.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"96446646","text":"#!/usr/bin/env python3\n# encoding: utf-8\ntry:\n f = open('./assert.py', 'r')\n # f = open('./test.py', 'r')\n print(f.read())\nfinally: \n if f:\n f.close()\n\n\nwith open('./test.txt', 'r') as f:\n print(f.read())\nwith open('./assert.py', 'r') as f:\n for line in f.readlines():\n print(line.strip()) # delete the end '\\n'\n\nfile = open('../images/haha.jpg', 'rb') # 默认都是读取文本文件,并且是UTF-8编码的文本文件。要读取二进制文件,比如图片、视频等等,用'rb'模式打开文件\nprint(file.read())\ntxt = open('./test.txt', encoding='gbk', errors='ignore')\nprint(txt.read())\n\nwith open('./test.txt', 'w') as txt:\n txt.write('print hello!')\n","sub_path":"test/open.py","file_name":"open.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"493054717","text":"\n\nfrom xai.brain.wordbase.nouns._cherub import _CHERUB\n\n#calss header\nclass _CHERUBIM(_CHERUB, ):\n\tdef __init__(self,): \n\t\t_CHERUB.__init__(self)\n\t\tself.name = \"CHERUBIM\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"cherub\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cherubim.py","file_name":"_cherubim.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"509091841","text":"#\n# Copyright (c) 2016 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom retry import retry\n\nfrom ..http_calls.platform import platform_operations\n\n\nclass Platform(object):\n \"\"\"\n this object should contain methods and fields that are general to whole platform.\n \"\"\"\n\n def retrieve_metrics(self, client=None, refresh=False):\n \"\"\"\n retrive basics metrics from platform using client api call.\n If refresh is True, this call can take time, depending on platform size\n :param refresh should data be refreshed? could take time\n :return:\n \"\"\"\n metrics_data = platform_operations.api_get_platform_operations(client)\n\n if refresh:\n self.refresh_data(client)\n # to consider in needed in future: parse metrics to platform fields\n metrics_data = self._check_for_refreshed_data(metrics_data[\"timestamp\"], client)\n\n self.metrics = PlatformMetrics(metrics_data)\n\n @staticmethod\n @retry(AssertionError, tries=30, delay=10)\n def _check_for_refreshed_data(timestamp, client=None):\n \"\"\"\n function check if data on platform are refreshed\n this should be call before creating any additional resources for example: orgs, spaces, users,...\n tries - number of check performed\n delay - time between tries, in seconds\n :param timestamp: timestamp of previous call\n :return: platform metrics\n \"\"\"\n metrics = platform_operations.api_get_platform_operations(client)\n if timestamp == metrics[\"timestamp\"]:\n txt = \"retrieved metrics from previous timestamp, previous {}, retrieved: {}\".format(timestamp,\n metrics[\"timestamp\"])\n raise AssertionError(txt)\n return metrics\n\n @staticmethod\n def refresh_data(client=None):\n \"\"\"\n trigger refresh operations.\n :param client: user used for refresh operations. Default\n :return:\n \"\"\"\n platform_operations.api_refresh_platform_operations(client)\n\n\nclass PlatformMetrics(object):\n\n def __init__(self, platform):\n self.apps = platform[\"controllerSummary\"][\"appCount\"]\n self.service_instances = platform[\"controllerSummary\"].get(\"serviceInstancesCount\", 0)\n self.services = platform[\"controllerSummary\"][\"serviceCount\"]\n self.buildpacks = platform[\"controllerSummary\"][\"buildpackCount\"]\n self.orgs = platform[\"controllerSummary\"][\"orgCount\"]\n self.spaces = platform[\"controllerSummary\"][\"spaceCount\"]\n self.users = platform[\"controllerSummary\"][\"userCount\"]\n self.buildpacks_data = platform[\"controllerSummary\"][\"buildpacks\"]\n","sub_path":"project/modules/tap_object_model/platform.py","file_name":"platform.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"416637689","text":"# All imports\nimport os\nimport boto3\nimport pandas as pd\nfrom botocore.config import Config\nfrom botocore import UNSIGNED\nimport toml\nimport shutil\nimport json\n\n\nclass OpenNeuroOverview(object):\n def __init__(self):\n self.archive_path = \"./\" # the path to archive\n\n def get_dataset_list(self):\n \"\"\"\n :return: a list of dataset available in OpenNeuro\n \"\"\"\n s3 = boto3.client(\"s3\", config=Config(signature_version=UNSIGNED))\n all_dataset = s3.list_objects(Bucket='openneuro.org', Delimiter=\"/\")\n dataset_list = []\n for dataset in all_dataset.get('CommonPrefixes'):\n dataset_list.append(dataset.get('Prefix'))\n return dataset_list\n\n def display_description(self, accession_number):\n \"\"\"\n read the dataset_description.json file\n :param accession_number: the dataset id\n :return: dataframe\n \"\"\"\n object = accession_number + \"/\"\n if object not in self.get_dataset_list():\n print(\"dataset cannot be found in the OpenNeuro dataset.\")\n return False\n else:\n path_to_file = accession_number + '/dataset_description.json'\n s3 = boto3.resource(\"s3\", config=Config(signature_version=UNSIGNED))\n data_description = s3.Object('openneuro.org', path_to_file).get()['Body']\n df = pd.read_json(data_description, orient='index')\n pd.set_option('display.max_rows', None)\n pd.set_option('display.max_columns', None)\n pd.set_option('display.width', None)\n pd.set_option('display.max_colwidth', -1)\n return df\n\n def display_readme(self, accession_number):\n \"\"\"\n read the README file\n :param accession_number: dataset id\n :return: everything in readme\n \"\"\"\n object = accession_number + \"/\"\n if object not in self.get_dataset_list():\n print(\"dataset cannot be found in the OpenNeuro dataset.\")\n return False\n else:\n try:\n path_to_file = accession_number + '/README'\n s3 = boto3.resource(\"s3\", config=Config(signature_version=UNSIGNED))\n readme = s3.Object('openneuro.org', path_to_file).get()['Body'].read()\n readme_print = str(readme, 'utf-8')\n # print(readme_print)\n return readme_print\n except:\n print(\"readme file does not exist.\")\n return False\n\n def check_archive(self, accession_number):\n \"\"\"\n :return: whether this dataset is in archive\n \"\"\"\n existed_dataset = [f.path.split(\"/\")[1] for f in os.scandir(self.archive_path) if f.is_dir()]\n print(existed_dataset)\n if accession_number in existed_dataset:\n return True\n else:\n return False\n\n def get_dataset(self, accession_number, download_all, subject_id=None):\n \"\"\"\n Open the dataset. If the dataset is not in the archive, download the dataset\n :param accession_number: the dataset id\n :param subject_id: the subject number, e.g. \"01\"\n :return: True if dataset exists. False otherwise.\n \"\"\"\n if self.check_archive(accession_number):\n path = self.archive_path + accession_number\n return path, os.path.join(path, 'open_neuro.toml'), 'dataset'\n else:\n object = accession_number + \"/\"\n if object in self.get_dataset_list():\n download = DownloadOpenNeuroDataset(accession_number)\n print(subject_id)\n if not download_all:\n download.download_subject(True, subject_id)\n path = self.archive_path + accession_number + \"_sub\" + subject_id\n return path, os.path.join(path, 'open_neuro.toml'), \"sub\"\n else:\n download.download_all()\n path = self.archive_path + accession_number\n return path, os.path.join(path, 'open_neuro.toml'), 'dataset'\n\n else:\n print(\"This dataset does not exist in the OpenNeuro database.\")\n return False\n\n\nclass DownloadOpenNeuroDataset(object):\n def __init__(self, accession_number):\n self.accession_number = accession_number\n self.subject = None\n self.default_destination = \"\" + self.accession_number # the default path. \"\" is saved for the path to BIDSArchive\n\n def get_subject_list(self, accession_number):\n \"\"\"\n read all files and subdirectory of this dataset\n :param accession_number: the dataset id\n :return: a list of file and subdirectory names of this dataset\n \"\"\"\n s3 = boto3.client(\"s3\", config=Config(signature_version=UNSIGNED))\n dataset_info = []\n prefix = accession_number + '/'\n dataset = s3.list_objects(Bucket='openneuro.org', Delimiter=\"/\", Prefix=prefix)\n for info in dataset.get('CommonPrefixes'):\n dataset_info.append(info.get('Prefix'))\n return dataset_info\n\n def check_subject(self, subject: str = \"01\"):\n \"\"\"\n check whether the subject folder exists\n :param subject: the subject id. e.g. \"01\" means \"sub-01\". The default subject id is 01\n :return: whether the subject directory exists\n \"\"\"\n paths = self.get_subject_list(self.accession_number)\n if not paths:\n return False\n path = \"\" + self.accession_number + \"/sub-\" + subject + \"/\"\n print(path)\n if path in paths:\n return True\n else:\n return False\n\n def download_all(self, destination=None):\n \"\"\"\n Download the whole dataset\n :param destination: String the path to download\n \"\"\"\n if destination is None:\n destination = self.default_destination\n try:\n request = 'aws s3 sync --no-sign-request s3://openneuro.org/' + self.accession_number + \" \" + destination\n os.system(request)\n print(\"Successfully downloaded\")\n self.write_conf()\n return True\n except:\n print(\"error occur\")\n return False\n\n def download_subject(self, root_included: bool, subject_id: str = \"01\", destination=None):\n \"\"\"\n Download every file in the root directory and the specified individual subject folder\n :param root_included: whether to include root files\n :param subject_id: the subject id. e.g. \"01\" means \"sub-01\"\n :param destination: the path to download\n \"\"\"\n self.subject = subject_id\n if not self.check_subject(subject_id):\n print(\"The dataset or subject folder does not exists.\")\n return False\n\n if destination is None:\n destination = self.default_destination + \"_sub\" + subject_id\n self.default_destination = destination\n try:\n if root_included:\n request = \"aws s3 cp --no-sign-request s3://openneuro.org/\" + self.accession_number + \" \" + destination \\\n + \" --recursive --exclude \\\"*/*\\\" --include \\\"sub-\" + subject_id + \"/*\\\"\"\n os.system(request)\n print(\"Successfully downloaded subject\" + subject_id + \" with all root files.\")\n else:\n request = \"aws s3 cp --no-sign-request s3://openneuro.org/\" + self.accession_number + \" \" + destination \\\n + \" --recursive --exclude \\\"*\\\" --include \\\"sub-\" + subject_id + \"/*\\\"\"\n os.system(request)\n print(\"Successfully downloaded subject\" + subject_id + \" with all root files.\")\n self.write_conf()\n return True\n except Exception as e:\n print(e)\n return False\n\n def reformat(self):\n \"\"\"\n Reformat it to the dataset that we can directly use for streaming\n :return:\n \"\"\"\n pass\n\n def write_conf(self):\n shutil.copy('open_neuro.toml', self.default_destination)\n conf = toml.load(self.default_destination + \"/open_neuro.toml\")\n # get title\n description_path = self.default_destination + \"/dataset_description.json\"\n with open(description_path) as f:\n dataset_description = json.load(f)\n conf['title'] = dataset_description['Name']\n\n # get subject Name and subjectNum\n if self.subject is None:\n list_subName = [f.path.split(\"/\")[1] for f in os.scandir(self.default_destination) if f.is_dir()]\n list_subNum = []\n for x in list_subName:\n if x.startswith('sub'):\n list_subNum.append(int(x.split(\"-\")[1]))\n conf['subjectName'] = list_subName\n conf['subjectNum'] = list_subNum\n # get session number does't change for now. Change based on subject. Default = None\n else:\n conf['subjectName'] = \"sub-\" + self.subject\n conf['subjectNum'] = int(self.subject)\n # save the edited toml file\n output_file_name = self.default_destination + \"/open_neuro.toml\"\n with open(output_file_name, \"w\") as toml_file:\n toml.dump(conf, toml_file)\n","sub_path":"OpenNeuroSample/OpenNeuroProto.py","file_name":"OpenNeuroProto.py","file_ext":"py","file_size_in_byte":9292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"239650328","text":"import os\nimport sys\nimport platform\nimport json\nimport logging\nimport time\n\nfrom cefpython3 import cefpython as cef\nfrom configuracao import Configuracao\nfrom mensagemApp import sucesso\nfrom mensagemApp import falha\n\nWINDOWS = (platform.system() == \"Windows\")\nLINUX = (platform.system() == \"Linux\")\nMAC = (platform.system() == \"Darwin\")\nWINDOWS_UTILS = cef.WindowUtils()\n\n\nclass Gui(object):\n def window(self):\n path= os.path.join(os.path.dirname(__file__), 'view'+ os.sep +'viewApp.html')\n browser = cef.CreateBrowserSync(url='file:///'+path, window_title=\"Cheques\",)\n set_javascript_bindings(browser)\n cef.MessageLoop()\n\n\ndef set_javascript_bindings(browser):\n bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False)\n bindings.SetFunction(\"buscarConfiguracao\", buscarConfiguracao)\n bindings.SetFunction(\"salvarConfiguracao\", salvarConfiguracao)\n bindings.SetFunction(\"sairApp\", sairApp)\n browser.SetJavascriptBindings(bindings)\n\n\ndef sairApp(callback=None):\n logging.info(\"Shutdown - \" + time.strftime('%c'))\n sys.exit()\n\n\ndef salvarConfiguracao(jsonConfiguracao, callback=None):\n try:\n\n configuracao = Configuracao()\n configuracao.parseFromJson(json.dumps(jsonConfiguracao, sort_keys=True, indent=4))\n print(json.dumps(jsonConfiguracao, sort_keys=True, indent=4))\n configuracao.salvar()\n\n if callback:\n callback.Call(sucesso(\"Configuracao atualizada.\"))\n else:\n return falha(\"Houve uma falha ao salvar a configuracao.\")\n\n except Exception as e:\n callback.Call(falha(\"Ocorreu uma falha ao salvar a configuracao.\"))\n\n\ndef buscarConfiguracao(callback=None):\n configuracao = Configuracao()\n configuracao.carregar()\n if callback:\n callback.Call(configuracao.__dict__)\n else:\n return configuracao.__dict__\n\n\ndef carregarTela():\n check_versions()\n\n sys.excepthook = cef.ExceptHook\n\n settings = {\n \"debug\": True,\n \"log_severity\": cef.LOGSEVERITY_ERROR,\n \"log_file\": \"debug.log\",\n \"product_version\": \"PyCheque/1.00\",\n \"user_agent\": \"PyCheque/1.00\",\n }\n\n if WINDOWS:\n settings[\"auto_zooming\"] = \"system_dpi\"\n cef.DpiAware.SetProcessDpiAware()\n\n cef.Initialize(settings=settings)\n\n app = Gui()\n app.window()\n\n print(\"Close\")\n sys.exit()\n\n\ndef check_versions():\n assert cef.__version__ >= \"55.3\", \"CEF Python v55.3+ required to run this\"\n","sub_path":"viewApp.py","file_name":"viewApp.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"136923162","text":"# coding: utf-8\n\n# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\n\"\"\"\nFILE: sample_build_classifier.py\n\nDESCRIPTION:\n This sample demonstrates how to build a classifier model. For this sample, you can use the training\n documents found in https://aka.ms/azsdk/formrecognizer/sampleclassifierfiles\n\n More details on building a classifier and labeling your data can be found here:\n https://aka.ms/azsdk/formrecognizer/buildclassifiermodel\n\nUSAGE:\n python sample_build_classifier.py\n\n Set the environment variables with your own values before running the sample:\n 1) AZURE_FORM_RECOGNIZER_ENDPOINT - the endpoint to your Form Recognizer resource.\n 2) AZURE_FORM_RECOGNIZER_KEY - your Form Recognizer API key\n 3) CLASSIFIER_CONTAINER_SAS_URL - The shared access signature (SAS) Url of your Azure Blob Storage container\n\"\"\"\n\n\ndef sample_build_classifier():\n # [START build_classifier]\n import os\n from azure.ai.formrecognizer import (\n DocumentModelAdministrationClient,\n ClassifierDocumentTypeDetails,\n BlobSource,\n BlobFileListSource,\n )\n from azure.core.credentials import AzureKeyCredential\n\n endpoint = os.environ[\"AZURE_FORM_RECOGNIZER_ENDPOINT\"]\n key = os.environ[\"AZURE_FORM_RECOGNIZER_KEY\"]\n container_sas_url = os.environ[\"CLASSIFIER_CONTAINER_SAS_URL\"]\n\n document_model_admin_client = DocumentModelAdministrationClient(\n endpoint=endpoint, credential=AzureKeyCredential(key)\n )\n\n poller = document_model_admin_client.begin_build_document_classifier(\n doc_types={\n \"IRS-1040-A\": ClassifierDocumentTypeDetails(\n source=BlobSource(\n container_url=container_sas_url, prefix=\"IRS-1040-A/train\"\n )\n ),\n \"IRS-1040-D\": ClassifierDocumentTypeDetails(\n source=BlobFileListSource(\n container_url=container_sas_url, file_list=\"IRS-1040-D.jsonl\"\n )\n ),\n },\n description=\"IRS document classifier\",\n )\n result = poller.result()\n print(f\"Classifier ID: {result.classifier_id}\")\n print(f\"API version used to build the classifier model: {result.api_version}\")\n print(f\"Classifier description: {result.description}\")\n print(f\"Document classes used for training the model:\")\n for doc_type, details in result.doc_types.items():\n print(f\"Document type: {doc_type}\")\n print(f\"Container source: {details.source.container_url}\\n\")\n # [END build_classifier]\n\n\nif __name__ == \"__main__\":\n sample_build_classifier()\n","sub_path":"sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2_and_later/sample_build_classifier.py","file_name":"sample_build_classifier.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"82313045","text":"from sandbox_environment_task import SandboxEnvironmentTask\n\nfrom project_layout import ProjectLayout\n\n\nclass FollowEnvironmentLogsTask(SandboxEnvironmentTask):\n def __init__(self, service_under_test_directory_path, whole_system):\n project_layout = ProjectLayout(service_under_test_directory_path)\n\n super(FollowEnvironmentLogsTask, self).__init__(\n project_layout.system_directory_path() if whole_system\n else service_under_test_directory_path,\n True,\n 'ssrn',\n whole_system,\n additional_docker_compose_file_paths=[\n project_layout.system_wide_log_aggregation_docker_compose_file_path()]\n if whole_system else []\n )\n\n def _run(self, environment, services):\n environment.follow_logs()\n\n\n","sub_path":"shared/infrastructure/automation/follow_environment_logs_task.py","file_name":"follow_environment_logs_task.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"60749160","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\nautocert.create\n'''\n\nimport os\n\nfrom pprint import pformat\nfrom attrdict import AttrDict\nfrom datetime import timedelta\n\nfrom utils import pki\nfrom utils.format import fmt\nfrom utils.exceptions import AutocertError\n\nfrom app import app\n\nfrom endpoint.base import EndpointBase\n\nclass UnknownCertificateAuthorityError(AutocertError):\n def __init__(self, authority):\n message = fmt('unknown certificate authority: {authority}')\n super(UnknownCertificateAuthorityError, self).__init__(message)\n\nclass CreateEndpoint(EndpointBase):\n def __init__(self, cfg, args):\n super(CreateEndpoint, self).__init__(cfg, args)\n\n def execute(self):\n status = 201\n modhash, key, csr = pki.create_modhash_key_and_csr(self.args.common_name, self.args.sans)\n crt, expiry, authority = self.authority.create_certificate(\n self.args.organization_name,\n self.args.common_name,\n self.args.validity_years,\n csr,\n self.args.bug,\n list(self.args.sans),\n self.args.repeat_delta,\n self.args.whois_check)\n cert = self.tardata.create_cert(\n self.args.common_name,\n modhash,\n key,\n csr,\n crt,\n self.args.bug,\n list(self.args.sans),\n expiry,\n authority)\n if self.args.destinations:\n note = 'bug {bug}'.format(**self.args)\n for name, dests in self.args.destinations.items():\n cert = self.destinations[name].install_certificates(note, [cert], *dests)[0]\n json = self.transform([cert])\n return json, status\n","sub_path":"api/endpoint/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"81742979","text":"from copy import deepcopy\nfrom ..base import Agent\n\n\nclass SillyAgent(Agent):\n agent_type = 'Silly Agent'\n\n def __init__(self, name='basic'):\n self.name = name\n\n def get_move(self, sna):\n if not sna:\n return None\n state = sna['state']\n actions = sna['actions']\n choice = self.make_choice(state, actions)\n return choice\n\n def end(self, score):\n pass\n\n def check_player_win(self, state, player):\n for j in range(3):\n win = True\n for i in range(3):\n win &= state[3*j+i] == player\n if win:\n return win\n for j in range(3):\n win = True\n for i in range(3):\n win &= state[j+i*3] == player\n if win:\n return win\n if state[0] == state[4] == state[8] == player:\n return True\n if state[2] == state[4] == state[6] == player:\n return True\n return False\n\n def make_choice(self, state, actions):\n temp = deepcopy(state[0])\n for action in actions:\n temp[action] = 1.0\n if self.check_player_win(temp, 1.0):\n return action\n else:\n temp = deepcopy(state[0])\n for action in actions:\n temp[action] = 0.0\n if self.check_player_win(temp, 0.0):\n return action\n else:\n temp = deepcopy(state[0])\n if 4 in actions:\n return 4\n else:\n return [x for x in actions if x <= sum(actions)/len(actions)][-1]\n\n def __repr__(self):\n return self.agent_type + \":\" + self.name\n","sub_path":"yomi/agents/silly_tic_tac_toe.py","file_name":"silly_tic_tac_toe.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"13914842","text":"# -*- coding: utf-8 -*-\n\"\"\"FAB Given step definitions.\"\"\"\nimport logging\nfrom statistics import median\n\nfrom behave.model import Table\nfrom behave.runner import Context\nfrom requests import Response\nfrom retrying import retry\nfrom scrapy import Selector\n\nfrom tests import get_absolute_url\nfrom tests.functional.pages import (\n fab_ui_build_profile_basic,\n fab_ui_confirm_identity,\n fab_ui_edit_online_profiles,\n fab_ui_profile,\n fab_ui_try_other_services,\n fab_ui_verify_company,\n fas_ui_contact,\n fas_ui_find_supplier,\n fas_ui_industries,\n fas_ui_profile,\n profile_ui_landing,\n sso_ui_invalid_password_reset_link,\n sso_ui_logout,\n sso_ui_password_reset,\n sso_ui_verify_your_email\n)\nfrom tests.functional.registry import get_fabs_page_object\nfrom tests.functional.utils.generic import (\n MailGunEvent,\n MailGunService,\n assertion_msg,\n check_hash_of_remote_file,\n detect_page_language,\n extract_csrf_middleware_token,\n extract_logo_url,\n find_mailgun_events,\n get_language_code,\n get_number_of_search_result_pages,\n get_password_reset_link,\n get_verification_link,\n surround\n)\nfrom tests.settings import (\n FAS_LOGO_PLACEHOLDER_IMAGE,\n FAS_MESSAGE_FROM_BUYER_SUBJECT,\n SEARCHABLE_CASE_STUDY_DETAILS\n)\n\n\ndef reg_sso_account_should_be_created(response: Response, supplier_alias: str):\n \"\"\"Will verify if SSO account was successfully created.\n\n Note:\n It's a very crude check, as it will only check if the response body\n contains selected phrases.\n\n :param response: response object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n sso_ui_verify_your_email.should_be_here(response)\n logging.debug(\"Successfully created new SSO account for %s\", supplier_alias)\n\n\ndef reg_should_get_verification_email(context: Context, alias: str):\n \"\"\"Will check if the Supplier received an email verification message.\n\n :param context: behave `context` object\n :param alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n logging.debug(\"Searching for an email verification message...\")\n actor = context.get_actor(alias)\n link = get_verification_link(context, actor.email)\n context.update_actor(alias, email_confirmation_link=link)\n\n\ndef bp_should_be_prompted_to_build_your_profile(\n context: Context, supplier_alias: str):\n fab_ui_build_profile_basic.should_be_here(context.response)\n logging.debug(\n \"%s is on the 'Build and improve your profile' page\", supplier_alias)\n token = extract_csrf_middleware_token(context.response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n\ndef prof_should_be_on_profile_page(response: Response, supplier_alias: str):\n fab_ui_profile.should_be_here(response)\n logging.debug(\"%s is on the company profile page\", supplier_alias)\n\n\ndef prof_should_be_told_about_missing_description(\n response: Response, supplier_alias: str):\n fab_ui_profile.should_see_missing_description(response)\n logging.debug(\"%s was told about missing description\", supplier_alias)\n\n\ndef fas_should_be_on_profile_page(context, supplier_alias, company_alias):\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n fas_ui_profile.should_be_here(context.response, number=company.number)\n logging.debug(\n \"%s is on the %s company's FAS page\", supplier_alias, company_alias)\n\n\ndef fas_check_profiles(context: Context, supplier_alias: str):\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n # Step 1 - go to company's profile page on FAS\n response = fas_ui_profile.go_to(actor.session, company.number)\n context.response = response\n # Step 2 - check if links to online profile are visible\n fas_ui_profile.should_see_online_profiles(company, response)\n logging.debug(\"%s can see all expected links to Online Profiles on \"\n \"FAS Company's Directory Profile Page\", supplier_alias)\n\n\ndef reg_supplier_is_not_appropriate_for_fab(\n context: Context, supplier_alias: str):\n fab_ui_try_other_services.should_be_here(context.response)\n logging.debug(\"%s was told that her/his business is not appropriate \"\n \"to feature in the Find a Buyer service\", supplier_alias)\n\n\ndef reg_supplier_has_to_verify_email_first(\n context: Context, supplier_alias: str):\n sso_ui_verify_your_email.should_be_here(context.response)\n logging.debug(\"%s was told that her/his email address has to be verified \"\n \"first before being able to Sign In\", supplier_alias)\n\n\ndef sso_should_be_signed_in_to_sso_account(\n context: Context, supplier_alias: str):\n response = context.response\n with assertion_msg(\"Expected sessionid cookie to be set. It looks like \"\n \"user is not logged in\"):\n assert response.cookies.get(\"sessionid\") is not None\n with assertion_msg(\"Response doesn't contain 'Sign out' button. It looks \"\n \"like user is not logged in\"):\n assert \"Sign out\" in response.content.decode(\"utf-8\")\n logging.debug(\"%s is logged in to the SSO account\", supplier_alias)\n\n\ndef sso_should_be_signed_out_from_sso_account(\n context: Context, supplier_alias: str):\n \"\"\"Sign out from SSO.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n\n # Step 1 - Get to the Sign Out confirmation page\n next_param = get_absolute_url(\"profile:about\")\n response = sso_ui_logout.go_to(session, next_param=next_param)\n context.response = response\n\n # Step 2 - check if Supplier is on Log Out page & extract CSRF token\n sso_ui_logout.should_be_here(response)\n token = extract_csrf_middleware_token(response)\n context.update_actor(supplier_alias, csrfmiddlewaretoken=token)\n\n # Step 3 - log out\n next_param = get_absolute_url(\"profile:landing\")\n response = sso_ui_logout.logout(session, token, next_param=next_param)\n context.response = response\n\n # Step 4 - check if Supplier is on SSO landing page\n profile_ui_landing.should_be_here(response)\n profile_ui_landing.should_be_logged_out(response)\n\n # Step 5 - reset requests Session object\n context.reset_actor_session(supplier_alias)\n\n\ndef prof_should_be_told_about_invalid_links(\n context: Context, supplier_alias: str):\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n\n facebook = True if company.facebook else False\n linkedin = True if company.linkedin else False\n twitter = True if company.twitter else False\n\n fab_ui_edit_online_profiles.should_see_errors(\n context.response, facebook=facebook, linkedin=linkedin,\n twitter=twitter)\n logging.debug(\n \"%s was not able to set Company's Online Profile links using invalid \"\n \"URLs to: %s %s %s\", supplier_alias, \"Facebook\" if facebook else \"\",\n \"LinkedIn\" if linkedin else \"\", \"Twitter\" if twitter else \"\")\n\n\ndef fab_should_see_all_case_studies(context: Context, supplier_alias: str):\n \"\"\"Check if Supplier can see all case studies on FAB profile page.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n case_studies = context.get_company(actor.company_alias).case_studies\n fab_ui_profile.should_see_case_studies(case_studies, context.response)\n\n\ndef fas_should_see_all_case_studies(context: Context, supplier_alias: str):\n \"\"\"Check if Supplier can see all case studies on FAS profile page.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n response = fas_ui_profile.go_to(actor.session, company.number)\n context.response = response\n case_studies = context.get_company(actor.company_alias).case_studies\n fas_ui_profile.should_see_case_studies(case_studies, response)\n logging.debug(\"%s can see all %d Case Studies on FAS Company's \"\n \"Directory Profile Page\", supplier_alias, len(case_studies))\n\n\ndef prof_should_see_logo_picture(context: Context, supplier_alias: str):\n \"\"\"Will check if Company's Logo visible on FAB profile page is the same as\n the uploaded one.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n logo_url = company.logo_url\n logo_hash = company.logo_hash\n logo_picture = company.logo_picture\n\n logging.debug(\"Fetching logo image visible on the %s's FAB profile page\",\n company.title)\n check_hash_of_remote_file(logo_hash, logo_url)\n logging.debug(\"The Logo visible on the %s's FAB profile page is the same \"\n \"as uploaded %s\", company.title, logo_picture)\n\n\ndef fas_should_see_png_logo_thumbnail(context: Context, supplier_alias: str):\n \"\"\"Will check if Company's PNG thumbnail logo visible on FAS profile.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n session = actor.session\n company = context.get_company(actor.company_alias)\n\n # Step 1 - Go to the FAS profile page & extract URL of visible logo image\n response = fas_ui_profile.go_to(session, company.number)\n context.response = response\n visible_logo_url = extract_logo_url(response, fas=True)\n placeholder = FAS_LOGO_PLACEHOLDER_IMAGE\n\n with assertion_msg(\n \"Expected company logo but got image placeholder '%s'\",\n visible_logo_url):\n assert visible_logo_url != placeholder\n with assertion_msg(\n \"Expected PNG logo thumbnail, but got: %s\", visible_logo_url):\n assert visible_logo_url.lower().endswith(\".png\")\n context.set_company_logo_detail(\n actor.company_alias, url=visible_logo_url)\n logging.debug(\"Set Company's logo URL to: %s\", visible_logo_url)\n\n\ndef fas_should_see_different_png_logo_thumbnail(context, actor_alias):\n \"\"\"Will check if Company's Logo visible on FAS profile page is the same as\n the one uploaded on FAB.\n\n :param context: behave `context` object\n :param actor_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(actor_alias)\n session = actor.session\n company = context.get_company(actor.company_alias)\n fas_logo_url = company.logo_url\n\n # Step 1 - Go to the FAS profile page & extract URL of visible logo image\n response = fas_ui_profile.go_to(session, company.number)\n context.response = response\n visible_logo_url = extract_logo_url(response, fas=True)\n placeholder = FAS_LOGO_PLACEHOLDER_IMAGE\n\n with assertion_msg(\n \"Expected company logo but got image placeholder\",\n visible_logo_url):\n assert visible_logo_url != placeholder\n with assertion_msg(\n \"Expected to see other logo thumbnail than the previous one '%s'.\",\n visible_logo_url):\n assert visible_logo_url != fas_logo_url\n with assertion_msg(\n \"Expected PNG logo thumbnail, but got: %s\", visible_logo_url):\n assert visible_logo_url.lower().endswith(\".png\")\n\n\ndef prof_all_unsupported_files_should_be_rejected(\n context: Context, supplier_alias: str):\n \"\"\"Check if all unsupported files were rejected upon upload as company logo.\n\n NOTE:\n This require `context.rejections` to be set.\n It should be a list of bool values.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n assert hasattr(context, \"rejections\")\n with assertion_msg(\n \"Some of the uploaded files that should be marked as unsupported \"\n \"were actually accepted. Please check the logs for more details\"):\n assert all(context.rejections)\n logging.debug(\"All files of unsupported types uploaded by %s were rejected\"\n .format(supplier_alias))\n\n\ndef fab_should_see_online_profiles(context: Context, supplier_alias: str):\n \"\"\"Check if Supplier can see all online Profiles on FAB Profile page.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n response = context.response\n fab_ui_profile.should_see_online_profiles(company, response)\n\n\ndef fab_no_links_to_online_profiles_are_visible(\n context: Context, supplier_alias: str):\n \"\"\"Supplier should't see any links to Online Profiles on FAB Profile page.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n response = context.response\n fab_ui_profile.should_not_see_online_profiles(response)\n logging.debug(\n \"%s cannot see links to Online Profiles on FAB Profile page\",\n supplier_alias)\n\n\ndef fas_no_links_to_online_profiles_are_visible(\n context: Context, supplier_alias: str):\n \"\"\"Supplier should't see any links to Online Profiles on FAS Profile page.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n response = context.response\n fas_ui_profile.should_not_see_online_profiles(response)\n logging.debug(\n \"%s cannot see links to Online Profiles on FAS Profile page\",\n supplier_alias)\n\n\ndef fab_profile_is_verified(context: Context, supplier_alias: str):\n \"\"\"Check if Supplier was told that Company's profile is verified.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n response = context.response\n fab_ui_profile.should_see_profile_is_verified(response)\n logging.debug(\"%s was told that the profile is verified.\", supplier_alias)\n\n\ndef fab_should_see_company_details(context: Context, supplier_alias: str):\n \"\"\"Supplier should see all expected Company details of FAB profile page.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n response = context.response\n fab_ui_profile.should_see_details(company, response, context.table)\n logging.debug(\"%s can see all expected details are visible of FAB \"\n \"Company's Directory Profile Page\", supplier_alias)\n\n\ndef profile_supplier_should_be_on_landing_page(\n context: Context, supplier_alias: str):\n \"\"\"Check if Supplier is on Profile Landing page.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n response = context.response\n profile_ui_landing.should_be_here(response)\n logging.debug(\"%s got to the SSO landing page.\", supplier_alias)\n\n\ndef fas_should_see_company_details(context: Context, supplier_alias: str):\n \"\"\"Supplier should see all expected Company details of FAS profile page.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n actor = context.get_actor(supplier_alias)\n company = context.get_company(actor.company_alias)\n session = actor.session\n\n # Step 1 - Go to the FAS profile page & extract URL of visible logo image\n response = fas_ui_profile.go_to(session, company.number)\n context.response = response\n\n # Step 2 - Check if all details are visible on FAS\n fas_ui_profile.should_see_details(company, response, context.table)\n logging.debug(\"%s can see all expected details are visible of FAS \"\n \"Company's Directory Profile Page\", supplier_alias)\n\n\n@retry(wait_fixed=5000, stop_max_attempt_number=3)\ndef fas_find_supplier_using_case_study_details(\n context: Context, buyer_alias: str, company_alias: str, case_alias: str,\n *, properties: Table = None):\n \"\"\"Find Supplier on FAS using parts of the Case Study added by Supplier.\n\n :param context: behave `context` object\n :param buyer_alias: alias of the Actor used in the scope of the scenario\n :param company_alias: alias of the sought Company\n :param case_alias: alias of the Case Study used in the search\n :param properties: (optional) table containing the names of Case Study parts\n that will be used search. If not provided, then all parts\n will be used except 'alias'.\n \"\"\"\n actor = context.get_actor(buyer_alias)\n session = actor.session\n company = context.get_company(company_alias)\n case_study = company.case_studies[case_alias]\n keys = SEARCHABLE_CASE_STUDY_DETAILS\n if properties:\n keys = [row['search using case study\\'s'] for row in properties]\n search_terms = {}\n for key in keys:\n if key == \"keywords\":\n for index, keyword in enumerate(case_study.keywords.split(\", \")):\n search_terms[\"keyword #{}\".format(index)] = keyword\n else:\n search_terms[key] = getattr(case_study, key.replace(\" \", \"_\"))\n logging.debug(\n \"Now %s will try to find '%s' using following search terms: %s\",\n buyer_alias, company.title, search_terms)\n for term_name in search_terms:\n term = search_terms[term_name]\n response = fas_ui_find_supplier.go_to(session, term=term)\n context.response = response\n found = fas_ui_find_supplier.should_see_company(response, company.title)\n if found:\n logging.debug(\n \"Found Supplier '%s' using '%s' : '%s' on 1st result page\",\n company.title, term_name, term)\n else:\n number_of_pages = get_number_of_search_result_pages(response)\n if number_of_pages > 1:\n for page_number in range(2, number_of_pages + 1):\n response = fas_ui_find_supplier.go_to(\n session, term=term, page=page_number)\n context.response = response\n found = fas_ui_find_supplier.should_see_company(\n response, company.title)\n if found:\n break\n else:\n with assertion_msg(\n \"Couldn't find '%s' using '%s': '%s' on the only \"\n \"available search result page\", company.title,\n term_name, term):\n assert False\n\n with assertion_msg(\n \"Buyer could not find Supplier '%s' on FAS using %s: %s\",\n company.title, term_name, term):\n assert found\n logging.debug(\n \"Buyer found Supplier '%s' on FAS using %s: %s\", company.title,\n term_name, term)\n\n\ndef fas_supplier_cannot_be_found_using_case_study_details(\n context: Context, buyer_alias: str, company_alias: str, case_alias: str):\n actor = context.get_actor(buyer_alias)\n session = actor.session\n company = context.get_company(company_alias)\n case_study = company.case_studies[case_alias]\n keys = SEARCHABLE_CASE_STUDY_DETAILS\n search_terms = {}\n for key in keys:\n if key == \"keywords\":\n for index, keyword in enumerate(case_study.keywords.split(\", \")):\n search_terms[\"keyword #{}\".format(index)] = keyword\n else:\n search_terms[key] = getattr(case_study, key)\n logging.debug(\n \"Now %s will try to find '%s' using following search terms: %s\",\n buyer_alias, company.title, search_terms)\n for term_name in search_terms:\n term = search_terms[term_name]\n logging.debug(\n \"Searching for '%s' using %s: %s\", buyer_alias, company.title,\n term_name, search_terms)\n response = fas_ui_find_supplier.go_to(session, term=term)\n context.response = response\n found = fas_ui_find_supplier.should_not_see_company(response, company.title)\n with assertion_msg(\n \"Buyer found Supplier '%s' on FAS using %s: %s\", company.title,\n term_name, term):\n assert found\n logging.debug(\n \"Buyer was not able to find unverified Supplier '%s' on FAS using \"\n \"%s: %s\", company.title, term_name, term)\n\n\ndef fas_should_find_with_company_details(\n context: Context, buyer_alias: str, company_alias: str):\n \"\"\"Check if Buyer was able to find Supplier using all selected search terms.\n\n NOTE:\n This step requires the search_results dict to be stored in context\n\n :param context: behave `context` object\n :param buyer_alias: alias of the Actor used in the scope of the scenario\n :param company_alias: alias of the Company used in the scope of the scenario\n \"\"\"\n assert hasattr(context, \"search_results\")\n company = context.get_company(company_alias)\n for result in context.search_results:\n # get response for specific search request. This helps to debug\n context.response = context.search_responses[result]\n with assertion_msg(\n \"%s wasn't able to find '%s' (alias: %s) using %s\", buyer_alias,\n company.title, company_alias, result):\n assert context.search_results[result]\n\n\ndef fas_pages_should_be_in_selected_language(\n context, pages_table: Table, language, *, page_part: str = None,\n probability: float = 0.9):\n \"\"\"Check if all viewed pages contain content in expected language\n\n NOTE:\n This requires all responses with page views to be stored in context.views\n\n :param context: behave `context` object\n :param pages_table: a table with viewed FAS pages\n :param language: expected language of the view FAS page content\n :param page_part: detect language of the whole page or just the main part\n :param probability: expected probability of expected language to be detected\n \"\"\"\n with assertion_msg(\"Required dictionary with page views is missing\"):\n assert hasattr(context, \"views\")\n pages = [row['page'] for row in pages_table]\n views = context.views\n\n if page_part:\n if page_part == \"main\":\n main = True\n elif page_part == \"whole\":\n main = False\n else:\n raise KeyError(\n \"Please select valid part of the page: main or whole\")\n\n for page_name in pages:\n response = views[page_name]\n # store currently processed response in context, so that it can be\n # printed out to the console in case of a failing assertion\n context.response = response\n content = response.content.decode(\"utf-8\")\n expected_language = get_language_code(language)\n logging.debug(\"Detecting the language of FAS %s page\", page_name)\n results = detect_page_language(content=content, main=main)\n detected = set(lang.lang for idx in results for lang in results[idx])\n logging.debug(\"`langdetect` detected FAS %s page to be in %s\", detected)\n\n error_msg = \"\"\n for lang_code in detected:\n probabilities = [lang.prob\n for idx in results\n for lang in results[idx]\n if lang.lang == lang_code]\n error_msg += (\"With median probability {} the text is in {}\\n\"\n .format(median(probabilities), lang_code))\n\n with assertion_msg(error_msg):\n assert all(lang.prob > probability\n for idx in results\n for lang in results[idx]\n if lang.lang == expected_language)\n\n\ndef fas_should_find_all_sought_companies(context: Context, buyer_alias: str):\n \"\"\"Check if all Buyer was able to find Supplier using all provided terms.\n\n :param context: behave `context` object\n :param buyer_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n with assertion_msg(\n \"Context has no required `search_details` dict. Please check if \"\n \"one of previous steps sets it correctly.\"):\n assert hasattr(context, \"search_results\")\n for company, results in context.search_results.items():\n for result in results:\n term = result[\"term\"]\n term_type = result[\"type\"]\n context.response = result[\"response\"]\n with assertion_msg(\n \"%s could not find Supplier '%s' using '%s' term '%s'\",\n buyer_alias, company, term_type, term):\n assert result[\"found\"]\n\n\ndef fas_should_be_told_that_message_has_been_sent(\n context: Context, buyer_alias: str, company_alias: str):\n response = context.response\n company = context.get_company(company_alias)\n fas_ui_contact.should_see_that_message_has_been_sent(company, response)\n logging.debug(\"%s was told that the message to '%s' (%s) has been sent\",\n buyer_alias, company.title, company_alias)\n\n\ndef fas_supplier_should_receive_message_from_buyer(\n context: Context, supplier_alias: str, buyer_alias: str):\n supplier = context.get_actor(supplier_alias)\n response = find_mailgun_events(\n context, service=MailGunService.DIRECTORY, recipient=supplier.email,\n event=MailGunEvent.ACCEPTED, subject=FAS_MESSAGE_FROM_BUYER_SUBJECT)\n context.response = response\n\n\ndef fab_should_see_expected_error_messages(context, supplier_alias):\n results = context.results\n logging.debug(results)\n for company, response, error in results:\n context.response = response\n with assertion_msg(\n \"Could not find expected error message: '%s' in the response, \"\n \"after submitting the form with following company details: \"\n \"title='%s' website='%s' keywords='%s' number of employees=\"\n \"'%s'\", error, company.title, company.website,\n company.keywords, company.no_employees):\n assert error in response.content.decode(\"utf-8\")\n logging.debug(\"%s has seen all expected form errors\", supplier_alias)\n\n\ndef fas_should_be_on_selected_page(context, actor_alias, page_name):\n response = context.response\n page_object = get_fabs_page_object(page_name)\n page_object.should_be_here(response)\n logging.debug(\n \"%s successfully got to the %s FAS page\", actor_alias, page_name)\n\n\ndef fas_should_see_promoted_industries(context, actor_alias, table):\n industries = [row['industry'].lower() for row in table]\n response = context.response\n for industry in industries:\n fas_ui_industries.should_see_industry_section(response, industry)\n logging.debug(\n \"%s can see all expected industry sections '%s'\", actor_alias,\n industries)\n\n\ndef fas_should_see_filtered_search_results(context, actor_alias):\n results = context.results\n sector_filters_selector = \"#id_sectors input\"\n for industry, result in results.items():\n context.response = result[\"response\"]\n content = result[\"response\"].content.decode(\"utf-8\")\n filters = Selector(text=content).css(sector_filters_selector).extract()\n for fil in filters:\n sector = Selector(text=fil).css(\"input::attr(value)\").extract()[0]\n checked = True if Selector(text=fil).css(\"input::attr(checked)\").extract() else False\n if sector in result[\"sectors\"]:\n with assertion_msg(\n \"Expected search results to be filtered by '%s' sector\"\n \" but this filter was not checked!\"):\n assert checked\n else:\n with assertion_msg(\n \"Expected search results to be filtered only by \"\n \"following sectors '%s', but they are also filtered \"\n \"by '%s'!\", \", \".join(result['sectors']), sector):\n assert not checked\n logging.debug(\n \"%s was presented with '%s' industry search results correctly \"\n \"filtered by following sectors: '%s'\", actor_alias, industry,\n \", \".join(result['sectors']))\n\n\ndef fas_should_see_unfiltered_search_results(context, actor_alias):\n response = context.response\n content = response.content.decode(\"utf-8\")\n sector_filters_selector = \"#id_sectors input\"\n filters = Selector(text=content).css(sector_filters_selector).extract()\n for fil in filters:\n sector = Selector(text=fil).css(\"input::attr(value)\").extract()[0]\n selector = \"input::attr(checked)\"\n checked = True if Selector(text=fil).css(selector).extract() else False\n with assertion_msg(\n \"Expected search results to be unfiltered but this \"\n \"filter was checked: '%s'\", sector):\n assert not checked\n logging.debug(\"%s was shown with unfiltered search results\", actor_alias)\n\n\ndef fas_should_see_company_once_in_search_results(\n context: Context, actor_alias: str, company_alias: str):\n company = context.get_company(company_alias)\n results = context.results\n founds = [(page, result['found'])\n for page, result in results.items()\n if result['found']]\n with assertion_msg(\n \"Expected to see company '%s' only once on first %d search result \"\n \"pages but found it %d times. On pages: %s\", company.title,\n len(results), len(founds), founds):\n assert len(founds) == 1\n logging.debug(\n \"As expected %s found company '%s' (%s) only once on first %d search \"\n \"result pages\", actor_alias, company.title, company_alias,\n len(results) + 1)\n\n\ndef fas_should_see_highlighted_search_term(context, actor_alias, search_term):\n response = context.response\n content = response.content.decode(\"utf-8\")\n search_summaries_selector = \".ed-company-search-summary\"\n summaries = Selector(text=content).css(search_summaries_selector).extract()\n tag = \"em\"\n keywords = [surround(keyword, tag) for keyword in search_term.split()]\n founds = []\n for summary in summaries:\n founds += [(keyword in summary) for keyword in keywords]\n\n with assertion_msg(\n \"Expected to see at least 1 search result with highlighted search \"\n \"term: '%s'\".format(\", \".join(keywords))):\n assert any(founds)\n\n logging.debug(\n \"{alias} found highlighted search {term}: '{keywords}' {founds} {times}\"\n \" in {results} search results\".format(\n alias=actor_alias, term=\"terms\" if len(keywords) > 1 else \"term\",\n keywords=\", \".join(keywords), founds=len([f for f in founds if f]),\n times=\"times\" if len([f for f in founds if f]) > 1 else \"time\",\n results=len(summaries)))\n\n\ndef fab_company_should_be_verified(context, supplier_alias):\n response = context.response\n fab_ui_verify_company.should_see_company_is_verified(response)\n\n\ndef fab_should_see_case_study_error_message(context, supplier_alias):\n results = context.results\n logging.debug(results)\n for field, value_type, case_study, response, error in results:\n context.response = response\n with assertion_msg(\n \"Could not find expected error message: '%s' in the response, \"\n \"after submitting the add case study form with '%s' value being\"\n \" '%s' following and other details: '%s'\", error, field,\n value_type, case_study):\n assert error in response.content.decode(\"utf-8\")\n logging.debug(\"%s has seen all expected case study errors\", supplier_alias)\n\n\ndef sso_should_be_told_about_password_reset(\n context: Context, supplier_alias: str):\n sso_ui_password_reset.should_see_that_password_was_reset(context.response)\n logging.debug(\"%s was told that the password was reset\", supplier_alias)\n\n\ndef sso_should_get_password_reset_email(context: Context, supplier_alias: str):\n \"\"\"Will check if the Supplier received an email verification message.\n\n :param context: behave `context` object\n :param supplier_alias: alias of the Actor used in the scope of the scenario\n \"\"\"\n logging.debug(\"Searching for a password reset email...\")\n actor = context.get_actor(supplier_alias)\n link = get_password_reset_link(context, actor.email)\n context.update_actor(supplier_alias, password_reset_link=link)\n\n\ndef sso_should_see_invalid_password_reset_link_error(\n context: Context, supplier_alias: str):\n sso_ui_invalid_password_reset_link.should_be_here(context.response)\n logging.debug(\n \"%s was told about invalid password reset link\", supplier_alias)\n\n\ndef should_be_at(context: Context, supplier_alias: str, page_name: str):\n response = context.response\n page = get_fabs_page_object(page_name.lower())\n page.should_be_here(response)\n logging.debug(\"%s is on '%s' page\", supplier_alias, page_name)\n\n\ndef should_see_selected_pages(context: Context, actor_alias: str):\n results = context.results\n for page_name, response in results.items():\n context.response = response\n page = get_fabs_page_object(page_name.lower())\n page.should_be_here(response)\n logging.debug(\"%s successfully got to '%s' page\", actor_alias, page_name)\n\n\ndef fab_should_be_asked_about_verification_form(\n context: Context, supplier_alias: str):\n fab_ui_confirm_identity.should_be_here(context.response)\n logging.debug(\n \"%s was asked about the form of identity verification\", supplier_alias)\n\n\ndef should_see_message(context: Context, actor_alias: str, message: str):\n content = context.response.content.decode(\"utf-8\")\n with assertion_msg(\n \"Response content doesn't contain expected message: '%s'\", message):\n assert message in content\n logging.debug(\"%s saw expected message: '%s'\", actor_alias, message)\n","sub_path":"tests/functional/steps/fab_then_impl.py","file_name":"fab_then_impl.py","file_ext":"py","file_size_in_byte":34500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"488278044","text":"# import urllib.request\n# request = urllib.request.Request('https://python.org')\n# response = urllib.request.urlopen(request)\n# print(response.read().decode('utf-8'))\n\nfrom urllib import request, parse\nurl = 'http://httpbin.org/post'\nheaders = {\n 'User-Agent': 'Mozilla/4.0 (compatible;MSIE 5.5;Windows NT)',\n 'Host': 'httbin.org'\n}\ndict={\n 'name': 'Germey'\n}\ndata = bytes(parse.urlencode(dict), encoding='utf-8')\nreq = request.Request(url=url, data=data, headers=headers, method='POST')\nresponse = request.urlopen(req)\nprint(response.read().decode('utf-8'))\n\n","sub_path":"04爬虫/基本库的使用/request构建请求.py","file_name":"request构建请求.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"173414234","text":"# Write your code here\nimport random\nimport sqlite3\n# potential issue in the code: it does not take care of when randomly two card generations\n# are the exact same. While the event is unlikely, it is still something that could happen\n# todo: fix this issue in the next commit\nconn = sqlite3.connect(\"card.s3db\")\ncur = conn.cursor()\ncur.execute(\"create table if not exists card(id integer, number text, pin text, balance integer default 0)\")\nconn.commit()\n\n\ndef create_string(size, value):\n str_val = str(value)\n while len(str_val) != size:\n str_val = \"0\" + str_val\n return str_val\n\n\ndef generate_checksum(first_15_acc_number):\n each_number = list(first_15_acc_number)\n luhn_sum = 0\n for i in range(len(each_number)):\n num = int(each_number[i])\n if (i + 1) % 2 == 1:\n num = 2 * num\n\n if num >= 10:\n num = num - 9\n luhn_sum = luhn_sum + num\n checksum = 10 - (luhn_sum % 10)\n if checksum == 10:\n checksum = 0\n return checksum\n\n\nclass Bank:\n IIN = 400000\n\n def __init__(self):\n self.pin = 0\n self.pin_string = \"\"\n self.account_identifier = 0\n self.identifier_string = \"\"\n self.balance = 0\n self.account_number = \"\"\n self.checksum = 0\n self.count = 0\n\n def create_account(self):\n self.pin = random.randint(0, 9999)\n self.account_identifier = random.randint(0, 999999999)\n self.pin_string = create_string(4, self.pin)\n self.identifier_string = create_string(9, self.account_identifier)\n self.account_number = str(self.IIN) + self.identifier_string\n self.checksum = generate_checksum(self.account_number)\n self.account_number = self.account_number + str(self.checksum)\n cur.execute(\n \"insert into card values({}, {}, {}, {})\".format(self.count + 1, self.account_number, self.pin_string, 0))\n conn.commit()\n\n # print the values\n print(\"\\nYour card has been created\")\n print(\"Your card number:\")\n print(self.account_number)\n print(\"Your card PIN:\")\n print(self.pin_string + \"\\n\")\n\n def login(self, number, pin):\n cur.execute(\"select number, pin from card where number = {}\".format(number))\n creds: list = cur.fetchone()\n\n if not creds:\n return False\n if creds[0] == number and create_string(4,creds[1]) == pin:\n\n self.account_number = number\n self.pin_string = pin\n cur.execute(\"select balance from card where number = {}\".format(number))\n balance_list: list = cur.fetchone()\n self.balance = balance_list[0]\n return True\n else:\n return False\n\n def bal(self):\n return self.balance\n\n def change_bal(self, amt):\n self.balance = amt\n cur.execute(\"update card set balance = {} where number = {}\".format(self.balance, self.account_number))\n conn.commit()\n\n def delete_account(self):\n cur.execute(\"delete from card where number = {}\".format(self.account_number))\n conn.commit()\n\n def transfer(self, other_card_number):\n cur.execute(\"select balance from card where number = {}\".format(other_card_number))\n bal_list = cur.fetchone()\n if not bal_list:\n print(\"Such a card does not exist.\\n\")\n else:\n print(\"Enter how much money you want to transfer:\")\n amt = int(input())\n if amt > self.balance or amt < 0:\n print(\"Not enough money!\\n\")\n else:\n\n bal = int(bal_list[0]) + amt\n self.balance = self.balance - amt\n cur.execute(\"update card set balance = {} where number = {}\".format(self.balance, self.account_number))\n cur.execute(\"update card set balance = {} where number = {}\".format(bal, other_card_number))\n print(\"Success!\\n\")\n conn.commit()\n\n\n# END OF CLASS DEFINITION\n\nbank = Bank()\n\nwhile True:\n print(\"1. Create an account\")\n print(\"2. Log into account\")\n print(\"0. Exit\")\n\n input_option = int(input())\n\n if input_option == 0:\n print(\"\\nBye!\")\n break\n\n elif input_option == 1:\n bank.create_account()\n\n elif input_option == 2:\n print(\"\\nEnter your card number:\")\n number = input()\n print(\"Enter your PIN:\")\n pin = input()\n\n if not bank.login(number, pin):\n print(\"\\nWrong card number or PIN!\\n\")\n\n else:\n print(\"\\nYou have successfully logged in!\\n\")\n while True:\n print(\"1. Balance\")\n print(\"2. Add income\")\n print(\"3. Do transfer\")\n print(\"4. Close account\")\n print(\"5. Log out\")\n print(\"0. Exit\")\n input_op = int(input())\n\n if input_op == 1:\n rem = bank.bal()\n print(f\"\\nBalance: {str(rem)}\\n\")\n\n elif input_op == 2:\n print(\"\\nEnter income:\")\n income = int(input())\n bank.change_bal(bank.balance + income)\n print(\"Income was added!\\n\")\n # fixme\n elif input_op == 3:\n print(\"\\nTransfer\")\n print(\"Enter card number:\")\n other_card = input()\n checksum = generate_checksum(other_card[0:15])\n if other_card == bank.account_number:\n print(\"You can't transfer money to the same account!\\n\")\n elif checksum != int(other_card[15]):\n print(\"Probably you made a mistake in the card number. Please try again!\\n\")\n else:\n bank.transfer(other_card)\n\n elif input_op == 4:\n bank.delete_account()\n print(\"\\nThe account has been closed!\\n\")\n break\n\n elif input_op == 5:\n print(\"\\nYou have successfully logged out\\n\")\n break\n\n elif input_op == 0:\n print(\"\\nBye!\")\n exit()\n #elif input_option == 5:\n # for row in cur.execute(\"select * from card\"):\n # print(row)\n\n","sub_path":"banking.py","file_name":"banking.py","file_ext":"py","file_size_in_byte":6361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"561329312","text":"import tornado.httpserver\nimport tornado.web\nimport tornado.websocket\nimport tornado.ioloop\nimport tornado.gen\nimport json\n\nimport database\n\nclass QueryHandler(tornado.web.RequestHandler):\n def get(self):\n query_geohash=self.get_argument(\"geohash\")\n location_info = database.get_location_info(query_geohash)\n to_send = json.dumps(location_info)\n self.write(to_send)\n\nclass Signup(tornado.web.RequestHandler):\n def post(self):\n user_name = self.get_argument(\"user_name\")\n new_user_id = database.create_new_user(user_name)\n\nclass LocationUpdater(tornado.web.RequestHandler):\n def post(self, map_id):\n user_id = self.get_argument(\"user_id\")\n lat = self.get_argument(\"lat\")\n lng = self.get_argument(\"lng\")\n if database.user_id_exists(user_id):\n database.update_location(user_id, lat, lng)\n\nclass HTMLHandler(tornado.web.RequestHandler):\n def get(self, filename):\n self.render(filename)\n\napplication = tornado.web.Application([\n (r'/signup',Signup ),\n (r'/maps/(.*)/update_location', LocationUpdater),\n (r'/query',QueryHandler),\n (r'^/(.*\\.html)$', HTMLHandler),\n (r'^/(.*)$', tornado.web.StaticFileHandler, {\"path\": \".\"})\n], debug=True)\n\nif __name__ == '__main__':\n http_server = tornado.httpserver.HTTPServer(application)\n import sys\n port = 8888\n if len(sys.argv) > 1:\n port = int(sys.argv[1])\n http_server.listen(port)\n print('Demo is runing at 0.0.0.0:8888\\nQuit the demo with CONTROL-C')\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"480742873","text":"''' Features that augment images\n\nAugmentations are features that can resolve more than one image without\ncalling `.resolve()` on the parent feature. Specifically, they create\n`updates_per_reload` images, while calling their parent feature\n`load_size` times.\n\nClasses\n-------\nAugmentation\n Base abstract augmentation class.\nPreLoad\n Simple storage with no augmentation.\nFlipLR\n Flips images left-right.\nFlipUD\n Flips images up-down.\nFlipDiagonal\n Flips images diagonally.\n'''\n\nfrom deeptrack.features import Feature\nfrom deeptrack.image import Image\nimport numpy as np\nfrom typing import Callable\n\n\n\nclass Augmentation(Feature):\n '''Base abstract augmentation class.\n\n Augmentations are features that can resolve more than one image without\n calling `.resolve()` on the parent feature. Specifically, they create\n `updates_per_reload` images, while calling their parent feature\n `load_size` times. They achieve this by resolving `load_size` results\n from the parent feature at once, and randomly drawing one of these \n results as input to the method `.get()`. A new input is chosen\n every time `.update()` is called. Once `.update()` has been called\n `updated_per_reload` times, a new batch of `load_size` results are\n resolved from the parent feature.\n\n The method `.get()` of implementations of this class may accept the\n property `number_of_updates` as an argument. This number represents\n the number of times the `.update()` method has been called since the\n last time the parent feature was resolved.\n\n Parameters\n ----------\n feature : Feature\n The parent feature.\n load_size : int\n Number of results to resolve from the parent feature.\n updates_per_reload : int\n Number of times `.update()` is called before resolving new results\n from the parent feature.\n update_properties : Callable or None\n Function called on the output of the method `.get()`. Overrides\n the default behaviour, allowing full control over how to update\n the properties of the output to account for the augmentation.\n '''\n\n __distributed__ = False\n def __init__(self, \n feature: Feature, \n load_size: int = 1, \n updates_per_reload: int = np.inf, \n update_properties: Callable or None = None, \n **kwargs):\n self.feature = feature \n\n def get_preloaded_results(load_size, number_of_updates):\n # Dummy property that loads results from the parent when\n # number of properties=0\n if number_of_updates == 0:\n self.preloaded_results = self._load(load_size)\n return None\n \n def get_number_of_updates(updates_per_reload=1):\n # Updates the number of updates. The very first update is not counted.\n if not hasattr(self.properties[\"number_of_updates\"], \"_current_value\"):\n return 0\n return (self.properties[\"number_of_updates\"].current_value + 1) % updates_per_reload\n\n if not update_properties:\n update_properties = self.update_properties\n \n super().__init__(\n load_size=load_size, \n updates_per_reload=updates_per_reload, \n index=lambda load_size: np.random.randint(load_size), \n number_of_updates=get_number_of_updates,\n preloaded_results=get_preloaded_results,\n update_properties=lambda: update_properties,\n **kwargs)\n\n\n def _process_and_get(self, *args, update_properties=None, index=0, **kwargs):\n # Loads a result from storage\n image_list = self.preloaded_results[index]\n if not isinstance(image_list, list):\n image_list = [image_list]\n \n # Calls get\n new_image_list = [self.get(Image(image).merge_properties_from(image), **kwargs) for image in image_list]\n\n # Updates properties\n if update_properties:\n for image in new_image_list:\n image.properties = [dict(prop) for prop in image.properties]\n update_properties(image, **kwargs)\n\n return new_image_list\n \n\n def _load(self, load_size):\n # Resolves parent and stores result\n preloaded_results = []\n for _ in range(load_size):\n self.feature.update()\n preloaded_results.append(self.feature.resolve())\n return preloaded_results\n\n\n\nclass PreLoad(Augmentation):\n '''Simple storage with no augmentation.\n\n '''\n\n def get(self, image, **kwargs):\n return image\n\n\nclass FlipLR(Augmentation):\n ''' Flips images left-right.\n\n Updates all properties called \"position\" to flip the second index.\n '''\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, load_size=1, updates_per_reload=2, **kwargs)\n\n\n def get(self, image, number_of_updates, **kwargs):\n if number_of_updates % 2:\n image = np.fliplr(image)\n return image\n\n\n def update_properties(self, image, number_of_updates, **kwargs):\n if number_of_updates % 2: \n for prop in image.properties:\n if \"position\" in prop:\n position = prop[\"position\"]\n new_position = (position[0], image.shape[1] - position[1], *position[2:])\n prop[\"position\"] = new_position\n\n\n\nclass FlipUD(Augmentation):\n ''' Flips images up-down.\n\n Updates all properties called \"position\" by flipping the first index.\n '''\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, load_size=1, updates_per_reload=2, **kwargs)\n\n\n def get(self, image, number_of_updates=0, **kwargs):\n if number_of_updates % 2:\n image = np.flipud(image)\n return image\n\n\n def update_properties(self, image, number_of_updates, **kwargs):\n if number_of_updates % 2: \n for prop in image.properties:\n if \"position\" in prop:\n position = prop[\"position\"]\n new_position = (image.shape[0] - position[0], *position[1:])\n prop[\"position\"] = new_position\n\n\nclass FlipDiagonal(Augmentation):\n ''' Flips images along the main diagonal.\n\n Updates all properties called \"position\" by swapping the first and second index.\n '''\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, load_size=1, updates_per_reload=2, **kwargs)\n\n\n def get(self, image, number_of_updates, axes=(1, 0, 2), **kwargs):\n if number_of_updates % 2:\n image = np.transpose(image, axes=axes)\n return image\n\n\n def update_properties(self, image, number_of_updates, **kwargs):\n if number_of_updates % 2: \n for prop in image.properties:\n if \"position\" in prop:\n position = prop[\"position\"]\n new_position = (position[1], position[0], *position[2:])\n prop[\"position\"] = new_position\n","sub_path":"deeptrack/augmentations.py","file_name":"augmentations.py","file_ext":"py","file_size_in_byte":7039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"444605703","text":"import torch\nimport torch.nn as nn\nfrom torch.utils import data\nimport numpy as np\nimport pandas as pd\n# timeorder=[]\n# speed,pressure,blood=[],[],[]\n# Right_atrial_pressure,Right_ventricular_pressure,Left_atrial_pressure,Left_ventricular_pressure=[],[],[],[]\n# Aortic_blood_flow,Aortic_pressure=[],[]\nfrom torch.utils.data import DataLoader\n\ndef standardization(data):\n mu = np.mean(data,axis=0)\n sigma = np.std(data,axis=0)\n return (data-mu)/sigma\ndef tensorToExcel(data):\n data = data.cpu().detach().numpy()\n data = pd.DataFrame(data)\n return data\ndef read_file(path):\n data_set=[]\n with open(path,'r',encoding='utf8') as f:\n lines = f.readlines()\n lines = [line.strip('\\n').split(' ') for line in lines]\n f.close()\n for i in range(len(lines)):\n dataline = [float(data) for data in lines[i][:-1]]\n data_set.append(dataline)\n train_data, valid_data, test_data = np.array(data_set[:15000]), np.array(data_set[15000:17500]), np.array(data_set[17500:])\n return train_data, valid_data, test_data\n\nclass TimeOderData(data.Dataset):\n def __init__(self,x,y=None):\n self.x=x\n self.y=y\n\n def __len__(self):\n return len(self.x)\n\n def __getitem__(self, item):\n X = torch.Tensor(self.x[item])\n if self.y is None:\n return X\n else:\n Y = torch.Tensor(self.y[item])\n return X,Y\n\nclass CNN_Function(nn.Module):\n def __init__(self):\n super(CNN_Function, self).__init__()\n self.seq = nn.Sequential(\n nn.Linear(3,256),\n nn.ReLU(),\n nn.Linear(256,64)\n )\n self.cov1 = nn.Conv2d(in_channels=1,out_channels=4,kernel_size=3,padding=1,stride=1)\n self.cov2 = nn.Conv2d(in_channels=4, out_channels=4, kernel_size=3, padding=1, stride=1)\n self.cov3 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3, padding=1, stride=1)\n self.cov4 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3, padding=1, stride=1)\n self.cov5 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3, padding=1, stride=1)\n self.cov6 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, padding=1, stride=1)\n self.cov7 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1, stride=1)\n self.cov8 = nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, padding=1, stride=1)\n self.cov9 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1, stride=1)\n self.cov10 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1, stride=1)\n self.cov11 = nn.Conv2d(in_channels=64, out_channels=126, kernel_size=3, padding=1, stride=1)\n self.cov12 = nn.Conv2d(in_channels=126, out_channels=126, kernel_size=3, padding=1, stride=1)\n self.cov13 = nn.Conv2d(in_channels=126, out_channels=250, kernel_size=3, padding=1, stride=1)\n self.cov14 = nn.Conv2d(in_channels=250, out_channels=250, kernel_size=3, padding=1, stride=1)\n self.net = nn.Sequential(self.cov1,self.cov2,self.cov3,self.cov4,self.cov5,self.cov6,self.cov7,self.cov8,self.cov9,self.cov10,self.cov11,self.cov12,self.cov13,self.cov14)\n self.fc = nn.Sequential(\n nn.Linear(250*64*1,1024),\n nn.ReLU(),\n nn.Linear(1024,6)\n )\n def forward(self, input):\n output = self.seq(input)\n output = output.unsqueeze(1)\n output = output.unsqueeze(3)\n output = self.net(output)\n output = output.view(output.size()[0],-1)\n output = self.fc(output)\n return output\n\ndef training(epochs):\n print(\"Starting training.....\")\n model.train()\n for epoch in range(epochs):\n total_loss = 0.0\n pred = torch.Tensor().to(device)\n y = torch.Tensor().to(device)\n for i,(input,output) in enumerate(train_loader):\n optimzer.zero_grad()\n input = input.to(device,dtype=torch.float)\n output = output.to(device,dtype=torch.float)\n output_model = model(input)\n pred = torch.cat((pred,output_model),0)\n y = torch.cat((y,output),0)\n loss = critic(output_model,output)\n loss.backward()\n optimzer.step()\n total_loss += loss.item()\n test_loss = testing()\n\n print(\"Train Epoch %d,train loss is %3.6f,test loss is %3.6f\"%(epoch+1,total_loss/batch_size,test_loss/batch_size))\n if (test_loss/batch_size)<0.15:\n print(\"Save model....\")\n save_models(epoch)\n tensorToExcel(output_model).to_csv(\"Epoch{}_pred.csv\".format(epoch))\n tensorToExcel(y).to_csv(\"Epoch{}_y.csv\".format(epoch))\n\ndef save_models(epoch):\n torch.save(model.state_dict(),\"Predmodel_{}.model\".format(epoch))\ndef testing():\n model.eval()\n with torch.no_grad():\n total_loss=0.0\n for i,(input,output) in enumerate(valid_loader):\n input = input.to(device,dtype=torch.float)\n output = output.to(device,dtype=torch.float)\n output_model = model(input)\n loss = critic(output_model,output)\n total_loss+=loss.item()\n model.train()\n return total_loss\n\n\nif __name__ == '__main__':\n print(\"Reading data ......\")\n device = torch.device(\"cuda\")\n batch_size = 128\n train_data,valid_data,test_data = read_file('data2.txt')\n train_x,train_y = train_data[:,1:4],train_data[:,4:]\n valid_x,valid_y = valid_data[:,1:4],valid_data[:,4:]\n test_x = test_data[:,1:4]\n model = CNN_Function()\n model = model.to(device)\n optimzer = torch.optim.Adam(model.parameters(),lr=0.01)\n critic = nn.L1Loss()\n train_set = TimeOderData(standardization(train_x),train_y)\n valid_set = TimeOderData(standardization(valid_x),valid_y)\n test_set = TimeOderData(test_x)\n train_loader = DataLoader(dataset=train_set,batch_size=batch_size,shuffle=True,num_workers=8)\n valid_loader = DataLoader(dataset=valid_set,batch_size=batch_size,num_workers=8,shuffle=True)\n test_loader = DataLoader(dataset=test_set,batch_size=batch_size,num_workers=8,shuffle=False)\n training(100)\n\n\n\n\n\n\n\n\n","sub_path":"CSVIM_Neural_Network/CNN_Function.py","file_name":"CNN_Function.py","file_ext":"py","file_size_in_byte":6170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"200703528","text":"from __future__ import print_function\n\nimport torch\nimport torchvision\nfrom torchvision import datasets, transforms\nimport numpy as np\n\nfrom rcnn import Occlusion\nfrom rcnn import DataContainer\nfrom rcnn import winit\n\nCIFAR10_TRAIN_MEAN = (0.4913997551666284, 0.48215855929893703, 0.4465309133731618)\nCIFAR10_TRAIN_STD = (0.24703225141799082, 0.24348516474564, 0.26158783926049628)\n\n\nclass CIFAR10(DataContainer):\n def __init__(self, batch_size: int, s: int = 4):\n self.batch_size = batch_size\n train_ds = datasets.CIFAR10(\n root=\".\",\n train=True,\n download=True,\n transform=transforms.Compose(\n [\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.RandomRotation(15),\n transforms.ToTensor(),\n Occlusion(mode=\"cutout\", size=s),\n transforms.Normalize(CIFAR10_TRAIN_MEAN, CIFAR10_TRAIN_STD),\n ]\n ),\n )\n\n self.train_loader = torch.utils.data.DataLoader(\n train_ds,\n batch_size=batch_size,\n shuffle=True,\n num_workers=0,\n worker_init_fn=winit,\n )\n\n self.test_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(\n root=\".\",\n train=False,\n transform=transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize(CIFAR10_TRAIN_MEAN, CIFAR10_TRAIN_STD),\n ]\n ),\n ),\n batch_size=batch_size,\n shuffle=True,\n num_workers=0,\n worker_init_fn=winit,\n )\n\n self.val_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(\n root=\".\",\n train=False,\n transform=transforms.Compose(\n [\n transforms.ToTensor(),\n Occlusion(mode=\"noise\", size=s),\n transforms.Normalize(CIFAR10_TRAIN_MEAN, CIFAR10_TRAIN_STD),\n ]\n ),\n ),\n batch_size=batch_size,\n shuffle=True,\n num_workers=0,\n worker_init_fn=winit,\n )\n\n self.loader_dict = {\n \"train\": self.train_loader,\n \"test\": self.test_loader,\n \"val\": self.val_loader,\n }\n\n self.sizes = {\n \"train\": len(self.train_loader) * batch_size,\n \"val\": len(self.val_loader) * batch_size,\n \"test\": len(self.test_loader) * batch_size,\n }\n\n def dl_dict(self):\n return self.loader_dict\n\n def update_val_loader(self, n: int, mode: str = \"cutout\"):\n self.val_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(\n root=\".\",\n train=False,\n transform=transforms.Compose(\n [\n transforms.ToTensor(),\n Occlusion(mode=mode, size=n),\n transforms.Normalize(CIFAR10_TRAIN_MEAN, CIFAR10_TRAIN_STD),\n ]\n ),\n ),\n batch_size=self.batch_size // 2,\n shuffle=True,\n num_workers=0,\n )\n","sub_path":"rcnn/dataloaders.py","file_name":"dataloaders.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"170589728","text":"from process_data import *\nfrom data_manager import *\n\nfrom random import randint, choice, random\nfrom operator import itemgetter\nfrom math import exp\nfrom optparse import OptionParser\n\n\ndef swap_simulated_annealing(dm, startRandom, Tmax=1000, Tmin=1,\n linear=False, exponential=True, sigmoidal=False):\n \"\"\" Simulated annealing using swap as in swap_hill_climber. Start with\n a max temp that changes based on the chosen cooling system. If the\n temp is high the acception_rate is also high thus scores that are\n lower than the previous score are also accepted. When the temp is\n low the acception_rate drops meaning that lower scores are rarely\n accepted\n \"\"\"\n\n print(\"Starting swap simulated annealing...\")\n\n temp = Tmax\n nIteration = 0\n\n while True:\n changed_lectures = []\n\n if dm.i == 0 and startRandom:\n for lecture in dm.lectures:\n changed_lectures.append(\n dm.randomLocation(lecture, no_overlap=True))\n\n changed_lectures.append(lecture)\n\n dm.addChanges(changed_lectures)\n dm.i += 1\n\n else:\n rLecture = choice(dm.lectures)\n rClassroom = choice(dm.classrooms)\n rDay = randint(0, 4)\n rTimeslot = randint(0, 3)\n\n new_location = rClassroom.timetable[rDay][rTimeslot]\n old_location = rLecture.classroom.\\\n timetable[rLecture.day][rLecture.timeslot]\n\n if new_location == []:\n new_location.append(rLecture)\n elif len(new_location) == 1 and len(old_location) == 1:\n swapLecture = new_location.pop()\n\n swapLecture.classroom = rLecture.classroom\n swapLecture.day = rLecture.day\n swapLecture.timeslot = rLecture.timeslot\n\n changed_lectures.append(swapLecture)\n else:\n continue\n\n rLecture.classroom = rClassroom\n rLecture.day= rDay\n rLecture.timeslot = rTimeslot\n\n changed_lectures.append(rLecture)\n\n dm.addChanges(changed_lectures)\n\n dm.plot.addScore(dm.iteration_dct[dm.i][\"score\"])\n\n # Simulated Annealing from here\n if linear:\n temp -= 0.1\n elif exponential:\n temp *= 0.9999\n elif sigmoidal:\n temp = Tmax / (1 + exp(0.05 * (dm.i-Tmax/10)))\n\n print(\"TEMP\", temp)\n\n\n acception_rate = exp((dm.iteration_dct[dm.i][\"score\"] - \\\n dm.iteration_dct[dm.i - 1][\"score\"]) / temp)\n\n if nIteration % 1000 == 0:\n dm.createBase()\n\n r = random()\n\n if dm.iteration_dct[dm.i][\"score\"] > \\\n dm.iteration_dct[dm.i - 1][\"score\"]:\n\n dm.i += 1\n nIteration += 1\n\n elif acception_rate >= r:\n dm.i += 1\n nIteration += 1\n\n else:\n # Reset to previous state\n dm.applyChanges(dm.compileChanges(dm.i - 1))\n nIteration += 1\n\n if temp <= Tmin or dm.iteration_dct[dm.i-1][\"score\"] >= 1400:\n break\n\n best_iteration, score = dm.compileBest()\n\n print(\"Best iteration: %s, Score: %s\" % (best_iteration, round(score)))\n\n dm.exportLectures(\"SSA%sTmax%sl%se%ss%s\" % (round(score), Tmax, linear, exponential, sigmoidal))\n\nif __name__ == \"__main__\":\n parser = OptionParser()\n parser.add_option(\"-o\", \"--loadFromOld\", dest=\"startRandom\", default=True,\n help=\"start from old timetable\", action=\"store_false\")\n\n parser.add_option(\"-t\", \"--startTemp\", dest=\"temp\", default=1000,\n help=\"define the default temp\")\n\n parser.add_option(\"-l\", \"--linear\", dest=\"linear\", default=False,\n help=\"Activate linear cooling function\", action=\"store_true\")\n\n parser.add_option(\"-e\", \"--exponential\", dest=\"exponential\", default=True,\n help=\"Activate exponential cooling function\", action=\"store_true\")\n\n parser.add_option(\"-s\", \"--sigmoidal\", dest=\"sigmoidal\", default=False,\n help=\"Activate sigmoidal cooling function\", action=\"store_true\")\n\n (options, args) = parser.parse_args()\n\n if options.linear or options.sigmoidal:\n options.exponential = False\n\n if sum([options.linear, options.exponential, options.sigmoidal]) > 1:\n print(\"Too many cooling schemes selected, try again\")\n\n else:\n if not options.startRandom:\n print(\"Algorithm will not start with random timetable\")\n data_manager.importLectures(input(\"Timetable name: \"))\n\n swap_simulated_annealing(data_manager, startRandom=options.startRandom,\n Tmax=int(options.temp), linear=options.linear,\n exponential=options.exponential, sigmoidal=options.sigmoidal)\n","sub_path":"simulated_annealing.py","file_name":"simulated_annealing.py","file_ext":"py","file_size_in_byte":4912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"472636410","text":"import random\nclass SlidingBoard(object):\n def __init__(self):\n a=0\n board1=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]\n self.board=[[],[],[],[]]\n random.shuffle(board1)\n for i in range(4):\t\n for j in range(4):\n self.board[i].append(board1[a])\n a+=1\n for i in range(4):\n for j in range(4):\n if self.board[i][j]==0:\n self.empty=(i,j)\n\n def move(self, num):\n self.pos=self.__find_position(num)\n if self.pos[0]==self.empty[0]:\n if self.pos[1]==self.empty[1]+1 or self.pos[1]==self.empty[1]-1:\n self.board[self.empty[0]][self.empty[1]], self.board[self.pos[0]][self.pos[1]]\\\n =self.board[self.pos[0]][self.pos[1]], self.board[self.empty[0]][self.empty[1]]\n self.empty=self.pos\n if self.pos[1]==self.empty[1]:\n if self.pos[0]==self.empty[0]+1 or self.pos[0]==self.empty[0]-1:\n board[self.empty[0]][self.empty[1]], board[self.pos[0]][self.pos[1]]\\\n =board[self.pos[0]][self.pos[1]], board[self.empty[0]][self.empty[1]]\n self.empty=self.pos\n print(\"Can't move! Try again.\")\n \n def __find_position(self, num):\n for i in range (4):\n for j in range(4):\n if self.board[i][j]==int(num):\n return (i, j)\n\n def print_board(self):\n print(\"S| 1 2 3 4\\n-+-----------\")\n for i in range (4):\n print(str(i+1)+\" |\",end=' ')\n for j in range(4):\n if self.board[i][j]!=0:\n if j!=3:\n print(str(self.board[i][j]).rjust(2),end=' ')\n else:\n print(str(self.board[i][j]).rjust(2))\n else:\n if j!=3:\n print(' '.rjust(2),end=' ')\n else:\n print(' '.rjust(2))\n\ndef get_number():\n num=input(\"Type the number you want to move (Type 0 to quit): \")\n while not (num.isdigit() and 0<=int(num)<=15):\n num=input(\"Type the number you want to move (Type 0 to quit): \")\n return int(num)\n\n#GOAL=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,0]]\n#slider=SlidingBoard()\n#while True:\n# slider.print_board()\n# if slider.board==GOAL:\n# print(\"Congratulations!\")\n# break\n# num=get_number()\n# if num==0:\n# break\n# slider.move(num)\n#print(\"Please come again\")\n","sub_path":"sliding_puzzle_class.py","file_name":"sliding_puzzle_class.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"277742199","text":"#!/usr/bin/env python3\n# import time\n# import cereal.messaging as messaging\n# from selfdrive.manager import start_managed_process, start_daemon_process, kill_managed_process\nfrom selfdrive.manager import start_managed_process\n\n# services = ['controlsState', 'thermal', 'radarState'] # the services needed to be spoofed to start ui offroad\nmanaged_processes = {\n# \"thermald\": \"selfdrive.thermald.thermald\",\n# \"uploader\": \"selfdrive.loggerd.uploader\",\n# \"deleter\": \"selfdrive.loggerd.deleter\",\n \"controlsd\": \"selfdrive.controls.controlsd\",\n \"plannerd\": \"selfdrive.controls.plannerd\",\n \"radard\": \"selfdrive.controls.radard\",\n \"ui\": (\"selfdrive/ui\", [\"./ui\"]),\n \"calibrationd\": \"selfdrive.locationd.calibrationd\",\n \"camerad\": (\"selfdrive/camerad\", [\"./camerad\"]),\n \"modeld\": (\"selfdrive/modeld\", [\"./modeld\"]),\n \"speedlimitd\": \"selfdrive.locationd.speedlimitd\",\n# \"locationd\": \"selfdrive.locationd.locationd\",\n# \"dmonitoringd\": \"selfdrive.monitoring.dmonitoringd\",\n# \"ubloxd\": (\"selfdrive/locationd\", [\"./ubloxd\"]),\n# \"loggerd\": (\"selfdrive/loggerd\", [\"./loggerd\"]),\n# \"logmessaged\": \"selfdrive.logmessaged\",\n# \"tombstoned\": \"selfdrive.tombstoned\",\n# \"logcatd\": (\"selfdrive/logcatd\", [\"./logcatd\"]),\n# \"proclogd\": (\"selfdrive/proclogd\", [\"./proclogd\"]),\n# \"pandad\": \"selfdrive.pandad\",\n# \"paramsd\": \"selfdrive.locationd.paramsd\",\n# \"sensord\": (\"selfdrive/sensord\", [\"./sensord\"]),\n# \"clocksd\": (\"selfdrive/clocksd\", [\"./clocksd\"]),\n# \"gpsd\": (\"selfdrive/sensord\", [\"./gpsd\"]),\n# \"updated\": \"selfdrive.updated\",\n# \"dmonitoringmodeld\": (\"selfdrive/modeld\", [\"./dmonitoringmodeld\"]),\n# \"rtshield\": \"selfdrive.rtshield\",\n}\n\n# start persistent processes\nfor p in managed_processes:\n start_managed_process(p)\n# procs = ['camerad', 'ui', 'modeld', 'calibrationd', 'plannerd', 'controlsd', 'radard', 'speedlimitd']\n# [start_managed_process(p) for p in procs] # start needed processes\n# pm = messaging.PubMaster(services)\n\n# dat_cs, dat_thermal, dat_radar = [messaging.new_message(s) for s in services]\n# dat_cs.controlsState.rearViewCam = False # ui checks for these two messages\n# dat_thermal.thermal.started = True\n\n# try:\n# while True:\n# pm.send('controlsState', dat_cs)\n# # pm.send('thermal', dat_thermal)\n# pm.send('radarState', dat_radar)\n# time.sleep(1 / 100) # continually send, rate doesn't matter for thermal\n# except KeyboardInterrupt:\n# [kill_managed_process(p) for p in procs]\n","sub_path":"selfdrive/debug/op_map.py","file_name":"op_map.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"223466203","text":"# Create a function that takes a list as a parameter,\n# and returns a new list with every second element from the orignal list\n# It should raise an error if the parameter is not a list\n# example: [1, 2, 3, 4, 5] should produce [2, 4]\n\ndef every_second_element(input):\n if type(input) != list:\n raise TypeError('Expected a list')\n new_list = []\n new_list += input[1::2]\n return new_list\n\nprint(every_second_element([1,2,3,4,5,7,8,9]))\n","sub_path":"first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"359304808","text":"\n\ndef permute(string, prefix):\n if len(string) == 0:\n print(prefix)\n else:\n for i in range(len(string)):\n sub_str = string[0:i] + string[i+1:]\n permute(sub_str, prefix + string[i])\n\nif __name__ == \"__main__\":\n permute(\"abcd\", \"\")\n","sub_path":"big_o/permute_str.py","file_name":"permute_str.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"317118935","text":"from __future__ import print_function\nimport os\nimport tensorflow as tf\nfrom functools import partial\nimport pickle\nimport numpy as np\nfrom machine.rbm.real import RBMReal\nfrom machine.rbm import RBMTransfer\nfrom hamiltonian import Ising, Heisenberg\nfrom graph import Hypercube\nfrom sampler import Gibbs, MetropolisExchange, MetropolisLocal\nfrom learner import Learner\nfrom logger import Logger\nfrom observable import * \n\n# System\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n#np.random.seed(123)\n#tf.set_random_seed(123)\n\n\nfor iteration in range(5):\n # Graph\n lattice_length = 8\n dimension = 1\n pbc = False\n if pbc:\n pbc_str = 'pbc'\n else:\n pbc_str = 'obc'\n\n # Hamiltonian\n #hamiltonian_type = \"ISING\"\n hamiltonian_type = \"HEISENBERG\"\n h = 1.0\n jx = 1.0\n jy = 1.0\n jz = -2.0\n\n # Sampler\n num_samples = 10000\n num_steps = 1000\n\n # Machine config\n # Rbm\n density = 2\n initializer = partial(np.random.normal, loc= 0.0, scale=0.01)\n\n # Learner\n sess = tf.Session()\n trainer = tf.train.RMSPropOptimizer\n learning_rate = 0.001\n num_epochs = 10000\n window_period = 200\n minibatch_size = 0 \n stopping_threshold = 0.005\n reference_energy = None\n use_dmrg_reference = True\n\n # transfer (k,p)-tiling, p is defined automatically\n k_val = 1 # (1,2)-tiling\n #k_val = 2 # (2,2)-tiling\n #k_val = lattice_length / 2 # (L,p)-tiling \n\n # Logger\n log = True\n result_path = './results/'\n subpath = '%d,p_tiling' % k_val\n visualize_weight = False\n visualize_visible = False\n visualize_freq = 10\n observables = [MagnetizationZ, MagnetizationZSquareFerro, MagnetizationZSquareAntiFerro, CorrelationZ]\n weight_diff = True\n\n # create instances\n graph = Hypercube(lattice_length, dimension, pbc)\n\n hamiltonian = None\n if hamiltonian_type == \"ISING\":\n hamiltonian = Ising(graph, jz, h)\n elif hamiltonian_type == \"HEISENBERG\":\n hamiltonian = Heisenberg(graph, jx, jy, jz)\n\n #sampler = Gibbs(num_samples, num_steps)\n sampler = MetropolisExchange(num_samples, num_steps)\n #sampler = MetropolisLocal(num_samples, num_steps)\n machine = RBMReal(graph.num_points, density, initializer, num_expe=iteration, use_bias=False)\n\n if hamiltonian_type == \"ISING\":\n if lattice_length == 8:\n transfer = RBMTransfer(machine, graph, '%sising_%dd_%d_%d_%.2f_1.00_%s/cold-start/' % (result_path, dimension, lattice_length / 2, density, jz, pbc_str), iteration)\n else:\n transfer = RBMTransfer(machine, graph, '%sising_%dd_%d_%d_%.2f_1.00_%s/%s/' % (result_path, dimension, lattice_length / 2, density, jz, pbc_str, subpath), iteration)\n elif hamiltonian_type == \"HEISENBERG\":\n if lattice_length == 8:\n transfer = RBMTransfer(machine, graph, '%sheisenberg_%dd_%d_%d_1.00_1.00_%.2f_%s/cold-start/' % (result_path, dimension, lattice_length / 2, density, jz, pbc_str), iteration)\n else:\n transfer = RBMTransfer(machine, graph, '%sheisenberg_%dd_%d_%d_1.00_1.00_%.2f_%s/%s/' % (result_path, dimension, lattice_length / 2, density, jz, pbc_str, subpath), iteration)\n\n transfer.tiling(k_val)\n\n machine.create_variable()\n\n\n if use_dmrg_reference:\n if hamiltonian_type == \"ISING\": \n refs = pickle.load(open('ising-energy-dmrg.p', 'r'))\n elif hamiltonian_type == \"HEISENBERG\":\n refs = pickle.load(open('heisenberg-energy-dmrg.p', 'r'))\n if lattice_length in refs:\n if jz in refs[lattice_length]:\n reference_energy = float(refs[lattice_length][jz])\n print('True energy:', reference_energy) \n\n learner = Learner(sess, graph, hamiltonian, machine, sampler, trainer, learning_rate, num_epochs, minibatch_size,\n window_period, reference_energy, stopping_threshold, visualize_weight, visualize_visible, visualize_freq)\n\n logger = Logger(log, result_path, subpath, visualize_weight, visualize_visible, visualize_freq, observables, weight_diff)\n\n learner.learn()\n logger.log(learner)\n\n logger.visualize_weights(transfer.W_base, logger.result_path, 0, 'before transfer', transfer.learner_base)\n logger.visualize_weights(transfer.W_transfer, logger.result_path, 1, 'after transfer', learner)\n\n # clear previous graph for multiple runs of learner\n tf.reset_default_graph()\n\n sess.close()\n","sub_path":"script-heisenberg-transfer.py","file_name":"script-heisenberg-transfer.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"475622655","text":"\nfrom simtk.openmm.app import *\nfrom simtk.openmm import *\nfrom simtk.unit import *\nimport sys\n\n\nclass DebugLogger:\n\n def __init__(self, filename, mode):\n self.filename = filename\n self.debugLog = open(filename, mode)\n\n def __del__(self):\n self.debugLog.close()\n\n def write_global_variables_headers(self, integrator):\n number_of_globals = integrator.getNumGlobalVariables()\n second_to_last = number_of_globals - 1\n for index in range(0, number_of_globals):\n name = integrator.getGlobalVariableName(index)\n self.debugLog.write(str(name))\n if index < second_to_last:\n self.debugLog.write(\",\")\n self.debugLog.write(\"\\n\")\n\n def write_global_variables_values(self, integrator):\n number_of_globals = integrator.getNumGlobalVariables()\n second_to_last = number_of_globals - 1\n for index in range(0, number_of_globals):\n name = integrator.getGlobalVariableName(index)\n value = integrator.getGlobalVariableByName(name)\n self.debugLog.write(str(value))\n if index < second_to_last:\n self.debugLog.write(\",\")\n self.debugLog.write(\"\\n\")\n\n @staticmethod\n def print_integration_algorithm_to_screen(integrator):\n for i in range(integrator.getNumComputations()):\n print(integrator.getComputationStep(i))\n sys.exit(-1)\n\n @staticmethod\n def print_global_variables_to_screen(integrator):\n for index in range(0, integrator.getNumGlobalVariables()):\n name = integrator.getGlobalVariableName(index)\n value = integrator.getGlobalVariableByName(name)\n print(name + \": \" + str(value))\n","sub_path":"gamd/DebugLogger.py","file_name":"DebugLogger.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"403827923","text":"# Copyright 2021 QHAna plugin runner contributors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Module containing extra marshmallow field classes to be used in plugin micro frontends.\"\"\"\n\nfrom collections import OrderedDict\nfrom enum import Enum\nfrom typing import Any, Iterable, List, Mapping, Optional, Set, Type\nfrom warnings import warn\n\nfrom marshmallow.exceptions import ValidationError\nfrom marshmallow.fields import Field\nfrom marshmallow.utils import resolve_field_instance\nfrom marshmallow.validate import OneOf\n\n\nclass OneOfEnum(OneOf):\n \"\"\"Validator for validating enum based choices.\n\n Succeeds if a ``value`` is a member of the enumeration.\n\n If choices contains the empty string ``\"\"`` then ``None`` will also validate.\n\n Args:\n enum (Type[Enum]): the enum type the choices are based on\n choices (Iterable[str]): the names of the enum items that are valid choices (can be a subset of the whole enum; can include ``\"\"``)\n labels (Optional[Iterable[str]]): the labels for the individual choices\n error (Optional[str]): Error message to raise in case of a validation error. Can be interpolated with ``{input}``, ``{choices}`` and ``{labels}``.\n\n Raises:\n ValueError: if the choices cannot be mapped to the given enum\n \"\"\"\n\n def __init__(\n self,\n enum: Type[Enum],\n choices: Iterable[str],\n labels: Optional[Iterable[str]],\n *,\n error: Optional[str],\n ):\n for choice in choices:\n if choice != \"\":\n try:\n enum[choice]\n except KeyError as err:\n raise ValueError(\n f\"Choice {choice} is not a valid enum value of Enum {enum}!\"\n ) from err\n super().__init__(choices=choices, labels=labels, error=error)\n self.enum_choices: Set[Optional[Enum]] = {c for c in enum if c.name in choices}\n if \"\" in self.choices:\n self.enum_choices.add(None)\n\n def __call__(self, value: Optional[Enum]) -> Optional[Enum]:\n if value not in self.enum_choices:\n raise ValidationError(self._format_error(value))\n\n return value\n\n\n# field is registered in qhana_plugin_runner.api module\nclass EnumField(Field):\n\n #: Default error messages.\n default_error_messages = {\"invalid\": \"Not a valid choice.\"}\n\n def __init__(self, enum_type: Type[Enum], **kwargs):\n metadata = kwargs.pop(\"metadata\", {})\n enum_meta = OrderedDict({e.name: e.value for e in enum_type})\n options = metadata.get(\"options\", {})\n for name, value in options.items():\n if isinstance(name, enum_type):\n name = name.name\n if name in enum_meta or name == \"\":\n # prefer manual override for values; allow to specify None (\"\") value and name\n enum_meta[name] = value\n else:\n # unknown enum member\n warn(\n f\"The enum field got an option {name} that is not present on the enum {enum_type}!\"\n )\n if \"\" in enum_meta:\n # None option should always be first\n enum_meta.move_to_end(\"\", last=False)\n metadata[\"options\"] = enum_meta\n\n super().__init__(metadata=metadata, **kwargs)\n\n self.enum_type: Type[Enum] = enum_type\n\n choices, labels = zip(*enum_meta.items())\n validator = OneOfEnum(\n enum=enum_type,\n choices=choices,\n labels=labels,\n error=self.error_messages[\"invalid\"],\n )\n self.validators.insert(0, validator)\n\n def _serialize(self, value: Enum, attr: str, obj, **kwargs):\n if value is None:\n return None\n\n return value.name\n\n def _deserialize(\n self, value: str, attr: Optional[str], data: Optional[Mapping[str, Any]], **kwargs\n ):\n if value == \"\":\n return None\n try:\n return self.enum_type[value]\n except KeyError as error:\n raise self.make_error(\"invalid\", input=value) from error\n\n\nclass CSVList(Field):\n \"\"\"Validator for validating comma separated lists.\n\n Args:\n element_type (Type[Field]): the field type of list elements\n\n Raises:\n ValueError: if fields are of an invalid type\n \"\"\"\n\n def __init__(self, element_type: Field, **kwargs):\n super().__init__(**kwargs)\n self.element_type = resolve_field_instance(element_type)\n\n def _serialize(self, value: List[Any], attr: str, obj: Any, **kwargs) -> str:\n return \",\".join(\n [self.element_type._serialize(v, attr, obj, **kwargs) for v in value]\n )\n\n def _deserialize(\n self, value: str, attr: Optional[str], data: Optional[Mapping[str, Any]], **kwargs\n ):\n if not value:\n return []\n return [self.element_type.deserialize(v) for v in value.split(\",\")]\n","sub_path":"qhana_plugin_runner/api/extra_fields.py","file_name":"extra_fields.py","file_ext":"py","file_size_in_byte":5442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"619274816","text":"#!/usr/bin/env python3\nimport os\nimport subprocess\n\n# Text styling class\nclass Text:\n HEADER = '\\033[1;34m'\n SUCCESS = '\\033[1;32m'\n FAIL = '\\033[1;21m'\n ENDC = '\\033[0m'\n\n# Commands class\nclass Command:\n CLONE_PIRBLASTER = 'git clone git@github.com:Electronya/PirBlaster.git'\n CREATE_PIRBLASTER_SVC = 'sudo cp ./scripts/services/pirblaster.service /etc/systemd/system'\n ENABLE_PIRBLASTER_SVC = 'sudo systemctl enable pirblaster.service'\n START_PIRBLASTER_SVC = 'sudo systemctl start pirblaster.service'\n CREATE_VRITUAL_ENV = 'python3 -m venv venv'\n ACTIVATE_VIRTUAL_ENV = 'source venv/bin/activate'\n DEACTIVATE_VIRTUAL_ENV = 'deactivate'\n INSTALL_DEPENDENCIES = 'pip install -r requirements.txt'\n DWNLD_PIGPIO = 'wget https://github.com/joan2937/pigpio/archive/master.zip'\n UNZIP_PIGPIO = 'unzip master.zip'\n BUILD_PIGPIO = 'make'\n INSTALL_PIGPIO = 'sudo make install'\n CREATE_PIGPIO_SVC = 'sudo cp ./scripts/services/pigpiod.service /etc/systemd/system'\n ENABLE_PIGPIO_SVC = 'sudo systemctl enable pigpiod.service'\n START_PIGPIO_SVC = 'sudo systemctl start pigpiod.service'\n\n# Execute shell command\ndef execCommand(command):\n process = subprocess.run(command.split(' '))\n return process.returncode\n\n# Install PIGPIO\ndef installPIGPIO():\n # TODO: Check if sevice is already installed & Split in multiple functions\n print(f\"{Text.HEADER}*** INSTALLING PIGPIO SERVICE ***{Text.ENDC}\")\n cmdResult = execCommand(Command.DWNLD_PIGPIO)\n if cmdResult != 0:\n print(f\"{Text.FAIL}PIGPIO DOWNLOAD FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}PIGPIO DOWNLOAD DONE{Text.ENDC}\")\n cmdResult = execCommand(Command.UNZIP_PIGPIO)\n if cmdResult != 0:\n print(f\"{Text.FAIL}PIGPIO UNZIP FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}PIGPIO UNZIP DONE{Text.ENDC}\")\n os.chdir('pigpio-master')\n cmdResult = execCommand(Command.BUILD_PIGPIO)\n if cmdResult != 0:\n print(f\"{Text.FAIL}PIGPIO BUILD FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}PIGPIO BUILD DONE{Text.ENDC}\")\n cmdResult = execCommand(Command.INSTALL_PIGPIO)\n if cmdResult !=0:\n print(f\"{Text.FAIL}PIGPIO INSTALL FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}PIGPIO INSTALL DONE{Text.ENDC}\")\n os.chdir('..')\n cmdResult = execCommand(Command.CREATE_PIGPIO_SVC)\n if cmdResult != 0:\n print(f\"{Text.FAIL}PIGPIOD SETUP FAILED!!!{Text.ENDC}\")\n return False\n cmdResult = execCommand(Command.ENABLE_PIGPIO_SVC)\n if cmdResult != 0:\n print(f\"{Text.FAIL}PIGPIOD SETUP FAILED!!!{Text.ENDC}\")\n return False\n cmdResult = execCommand(Command.START_PIGPIO_SVC)\n if cmdResult != 0:\n print(f\"{Text.FAIL}PIGPIOD SETUP FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}PIGPIOD SETUP DONE{Text.ENDC}\")\n return True\n\n# Clone PirBlaster repo\ndef clonePirBlaster():\n print(f\"{Text.HEADER}*** CLONING PIRBLASTER REPO ***{Text.ENDC}\")\n cmdResult = execCommand(Command.CLONE_PIRBLASTER)\n if cmdResult != 0:\n print(f\"{Text.FAIL}CLONING PIRBLASTER FAILED!!!{Text.ENDC}\")\n return False\n os.chdir('./PirBlaster')\n print(f\"{Text.SUCCESS}CLONING PIRBLASTER DONE{Text.ENDC}\")\n return True\n\n# Creating virtual environment\ndef createVirtualEnv():\n print(f\"{Text.HEADER}*** CREATING VIRTUAL ENVIRONMENT ***{Text.ENDC}\")\n cmdResult = execCommand(Command.CREATE_VRITUAL_ENV)\n if cmdResult != 0:\n print(f\"{Text.FAIL}CREATING VIRTUAL ENVIRONEMENT FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}CREATING VIRTUAL ENVIRONMENT DONE{Text.ENDC}\")\n return True\n\n# Activate virtual environment\ndef activateVirutalEnv():\n print(f\"{Text.HEADER}*** AVITVATING VIRTUAL ENVIRONMENT ***{Text.ENDC}\")\n cmdResult = execCommand(Command.ACTIVATE_VIRTUAL_ENV)\n if cmdResult != 0:\n print(f\"{Text.FAIL}ACTIVATING VIRTUAL ENVIRONMENT FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}ACTIVATING VIRTUAL ENVIRONMENT DONE{Text.ENDC}\")\n return True\n\n# Deactivate virtual environment\ndef deactivateVirtualEnv():\n print(f\"{Text.HEADER}*** DEACTIVATING VIRTUAL ENVIRONMENT ***{Text.ENDC}\")\n cmdResult = execCommand(Command.DEACTIVATE_VIRTUAL_ENV)\n if cmdResult != 0:\n print(f\"{Text.FAIL}DEACTIVATING VIRTUAL ENVIRONMENT FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}DEACTIVATING VIRTUAL ENVIRONMENT DONE{Text.ENDC}\")\n return True\n\n# Install dependencies\ndef installDependencies():\n print(f\"{Text.HEADER}*** INSTALLING PIRBLASTER DEPENDENCIES ***{Text.ENDC}\")\n cmdResult = execCommand(Command.INSTALL_DEPENDENCIES)\n if cmdResult != 0:\n print(f\"{Text.FAIL}INSTALLING PIRBLASTER DEPENDENCIES FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}INSTALLING PIRBLASTER DEPENDENCIES DONE{Text.ENDC}\")\n return True\n\n# Create PirBlaster service\ndef createPirBlasterSvc():\n print(f\"{Text.HEADER}*** CREATING PIRBLASTER SERVICE ***{Text.ENDC}\")\n cmdResult = execCommand(Command.CREATE_PIRBLASTER_SVC)\n if cmdResult != 0:\n print(f\"{Text.FAIL}CREATING PIRBLASTER SERVICE FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}CREATING PIRBLASTER SERVICE DONE{Text.ENDC}\")\n return True\n\n# Enabling PirBlaster Service\ndef enablePirBlasterSvc():\n print(f\"{Text.HEADER}*** ENABLING PIRBLASTER SERVICE ***{Text.ENDC}\")\n cmdResult = execCommand(Command.ENABLE_PIRBLASTER_SVC)\n if cmdResult != 0:\n print(f\"{Text.FAIL}ENALBING PIRBLASTER SERVICE FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}ENABLING PIRBLASTER SERVICE DONE{Text.ENDC}\")\n return True\n\n# Start PirBlaster Service\ndef startPirBlasterSvc():\n print(f\"{Text.HEADER}*** STARTING PIRBLASTER SERVICE ***{Text.ENDC}\")\n cmdResult = execCommand(Command.START_PIRBLASTER_SVC)\n if cmdResult != 0:\n print(f\"{Text.FAIL}STARTING PIRBLASTER SERVICE FAILED!!!{Text.ENDC}\")\n return False\n print(f\"{Text.SUCCESS}STARTING PIRBLASTER SERVICE DONE{Text.ENDC}\")\n return True\n\n# print(f\"{Text.HEADER}*** SERVICE CONFIGURATION ***{Text.ENDC}\")\n# Ask for the hostname the service will use for advertising\n# hostname = input(f\"Please enter the hostname that the service will use for advertising:\")\n\nif clonePirBlaster():\n if createVirtualEnv():\n if activateVirutalEnv():\n if installDependencies():\n if deactivateVirtualEnv():\n if createPirBlasterSvc():\n if enablePirBlasterSvc():\n if startPirBlasterSvc():\n print(f\"{Text.SUCCESS}INSATALLING PIRBLASTER SERVICE DONE{Text.ENDC}\")\n exit()\nprint(f\"{Text.FAIL}INTALLING PIRBLASTER SERVICE FAILED!!!{Text.ENDC}\")\n","sub_path":"scripts/install/PirBlaster_install.py","file_name":"PirBlaster_install.py","file_ext":"py","file_size_in_byte":6909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"379731737","text":"# 给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。\n\n# 注意:\n\n# 给定的整数保证在32位带符号整数的范围内。\n# 你可以假定二进制数不包含前导零位。\n# 示例 1:\n\n# 输入: 5\n# 输出: 2\n# 解释: 5的二进制表示为101(没有前导零位),其补数为010。所以你需要输出2。\n# 示例 2:\n\n# 输入: 1\n# 输出: 0\n# 解释: 1的二进制表示为1(没有前导零位),其补数为0。所以你需要输出0。\n\n# 来源:力扣(LeetCode)\n# 链接:https://leetcode-cn.com/problems/number-complement\n# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\nclass Solution:\n def findComplement(self, num: int) -> int:\n s = bin(num)[2:]\n res = \"\"\n for char in s:\n if char == '1':\n res+= '0'\n else:\n res+= '1'\n return int(res,2)","sub_path":"Python/476-数字的补数.py","file_name":"476-数字的补数.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"254043138","text":"from logging import currentframe\nfrom os import path as Path\nfrom typing import List\nimport custom_log as l\nimport os\nimport argument_handler as argh\n\ncurrent_mode = None\n\ndef get_mode():\n return current_mode\n\ndef walk(mode=None) -> List:\n \"\"\"\n walks through a path to return list of absolute path of images with png or jpg extensions\n :param mode: can be\n :param path: to the directory where images will be searched for\n :return: List of string path of images\n \"\"\"\n image_paths = []\n path: str = argh.get_path()\n if mode:\n path += mode\n global current_mode \n current_mode = mode\n l.log(path)\n ignore: str = argh.get_ignore_word()\n l.log(\"checking path integrity\")\n if Path.exists(path):\n l.log([path, \"exists\"])\n else:\n l.log(\"path does not exist\")\n exit()\n # l.disable()\n for folderName, subfolders, filenames in os.walk(path):\n for filename in filenames:\n if (filename.endswith('jpg') or\n filename.endswith('.png') or\n filename.endswith('.bmp') or\n filename.endswith('.jpeg')):\n file_path = os.path.join(folderName, filename)\n\n # l.log([file_path, filename])\n if ignore and is_exclude_image(file_path, ignore):\n continue\n image_paths.append(file_path)\n \n return image_paths\n\n\ndef is_exclude_image(image_path: str, ignore_word: str) -> str:\n import custom_log as l\n l.log(ignore_word)\n # exit()\n if ',' in ignore_word:\n list_ignores = ignore_word.split(',')\n\n for word in list_ignores:\n if image_path.lower().find(word) != -1:\n l.log([\"found entry in list_ignore: \", image_path, word])\n return True\n else:\n if image_path.lower().find(ignore_word) != -1:\n l.log([\"found entry in list_ignore: \", image_path, ignore_word])\n return True\n return False\n","sub_path":"image_in_window_screensaver/file_walker.py","file_name":"file_walker.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"556113646","text":"import matplotlib.pyplot as plt\nimport statsmodels.api as sm\nfrom pandas.stats.moments import rolling_mean\n\n\ndata_loader = sm.datasets.sunspots.load_pandas()\ndf = data_loader.data\nyear_range = df[\"YEAR\"].values\nsun_active = df[\"SUNACTIVITY\"].values\nSMA11 = rolling_mean(df, 11)[\"SUNACTIVITY\"].values\nSMA22 = rolling_mean(df, 22)[\"SUNACTIVITY\"].values\n\nplt.plot(year_range, sun_active, label=\"Original\")\nplt.plot(year_range, SMA11, label=\"SMA 11\")\nplt.plot(year_range, SMA22, label=\"SMA 22\")\n\nplt.legend()\nplt.savefig(r\"E:\\Desktop\\Python\\Maths\\SUNACTIVITY.png\")\nplt.show()","sub_path":"Data_Analysis/太阳黑子活动.py","file_name":"太阳黑子活动.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"581639391","text":"import random\n\n\ndef bladesroll(poolsize, showroll=1, difficulty=0):\n\troll1 = []\n\trollsnapshot = 0\n\tif (difficulty == 1 and poolsize <=1):\n\t\troll1.append(1)\n\telse:\n\t\tif poolsize > 0:\n\t\t\tfor x in range(0, poolsize):\n\t\t\t\tdieroll = random.randint(1, 6)\n\t\t\t\troll1.append(dieroll)\n\t\t\troll1 = sorted(roll1, reverse=True)\n\t\t\tif difficulty == 1:\n\t\t\t\troll1.pop(0)\n\n\n\n## Gotta Deal with zero pools\n\t\telse:\n\t\t\tfor x in range(0, 2):\n\t\t\t\tdieroll = random.randint(1, 6)\n\t\t\t\troll1.append(dieroll)\n\t\t\troll1 = sorted(myroll)\n\t\t\tif roll1[1]==6:\n\t\t\t\troll1[1] = 0\n\n\n\trollsnapshot = roll1\n\tbestroll = roll1.pop(0)\n\tif len(roll1) > 0:\n\t\tif roll1[0] == 6:\n\t\t\tbestroll += 1\n\tif showroll:\n\t\tprint(rollsnapshot, \" - \", bestroll)\n\n\n\n\t##\tprint (\"Best: \", bestroll)\n\t##\tprint (\"Rest: \", myroll)\n\n\n\treturn rollsnapshot, bestroll\n\n\n\ndef samplingroll(pool, samplesize=10):\n\trollcount = 1\n\tfail = 0\n\tmixed = 0\n\tsuccess = 0\n\tcrit = 0\n\twhile rollcount <= samplesize:\n\t\tdiceroll, bestresult = bladesroll(pool)\n\t\tif (bestresult == 1) or (bestresult == 2) or (bestresult == 3):\n\t\t\tfail += 1\n\t\telif (bestresult == 4) or (bestresult == 5):\n\t\t\tmixed += 1\n\t\telif bestresult == 6:\n\t\t\tsuccess += 1\n\t\telif bestresult > 6:\n\t\t\tcrit += 1\n\t\trollcount += 1\n\treturn fail, mixed, success, crit, pool, samplesize\n\n\ndef getbladesresults(poolsize, samplesize, output=1):\n\tfail, mixed, success, crit, poolsize, samplesize = samplingroll(poolsize, samplesize)\n\tfailpercent = round(fail / samplesize * 100, 2)\n\tmixedpercent = round(mixed / samplesize * 100, 2)\n\tsuccpercent = round(success / samplesize * 100, 2)\n\tcritpercent = round(crit / samplesize * 100, 2)\n\tif output == 1:\n\t\tprint(samplesize, \" rolls of \", poolsize, \" dice.\")\n\t\tprint(\"-----------------------------------------\")\n\t\tprint(\"Failure: \", f'{fail:10}', \" - \", failpercent, \"%\")\n\t\tprint(\"Mixed Results: \", f'{mixed:10}', \" - \", mixedpercent, \"%\")\n\t\tprint(\"Successes: \", f'{success:10}', \" - \", succpercent, \"%\")\n\t\tprint(\"Crits: \", f'{crit:10}', \" - \", critpercent, \"%\")\n\t\tprint()\n\telif output == 2:\n\t\tprint(\"%r,%r,%r,%r,%r,%r\" % (samplesize, poolsize, failpercent, mixedpercent, succpercent, critpercent))\n\treturn failpercent, mixedpercent, succpercent, critpercent\n\n\n## print(\"%r:%r\" % (len(diceroll), diceroll))\nhowbig = 10\nfor dicerolled in range(3,4):\n\tf, m, s, c = getbladesresults(dicerolled, howbig, 1)\n\n\n","sub_path":"brolltest.py","file_name":"brolltest.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"88626470","text":"from gluon.contrib.appconfig import AppConfig\nmyconf = AppConfig(reload=True)\n\nif not request.env.web2py_runtime_gae:\n db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all'])\nelse:\n db = DAL('google:datastore+ndb')\n session.connect(request, response, db=db)\n\nresponse.generic_patterns = ['*'] if request.is_local else []\nresponse.formstyle = myconf.take('forms.formstyle')\nresponse.form_label_separator = myconf.take('forms.separator')\n\nfrom gluon.tools import Auth, Service, PluginManager\n\nauth = Auth(db)\nservice = Service()\nplugins = PluginManager()\n\nauth.define_tables(username=False, signature=False)\n\nauth.settings.registration_requires_verification = True\nauth.settings.registration_requires_approval = True\nauth.settings.reset_password_requires_verification = True\n\nmail = auth.settings.mailer\n# mail.settings.server = 'logging' if request.is_local else myconf.take('smtp.server')\n# mail.settings.sender = myconf.take('smtp.sender')\n# mail.settings.login = myconf.take('smtp.login')\nmail.settings.server = 'gae'\nmail.settings.sender = 'dbauszus@gmail.com'\nmail.settings.login = 'dbauszus@gmail.com:***'","sub_path":"applications/auth_test/models/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"392875396","text":"import level1 as l\nimport json\n\ndef test1():\n print(\"Test for parse_f_j started...\")\n inp_file = ('fortest/data_test.json')\n result = l.parse_f_j(inp_file)\n requirement = {\"cars\": [{ \"id\": 1,\n \"price_per_day\": 2000,\n \"price_per_km\": 10 }],\n \"rentals\": [{ \"id\": 1,\n \"car_id\": 1,\n \"start_date\": \"2017-12-8\",\n \"end_date\": \"2017-12-10\", \"distance\": 100 }]}\n\n out(result,requirement)\n\ndef test2():\n print(\"Test for get_duration...\")\n result = l.get_duration('1970-1-1','2016-1-1')\n requirement = 16802\n\n out(result,requirement)\n\ndef test3():\n print(\"Test for to_json...\")\n req = {\"name\":123}\n l.to_json(req,'fortest/output_test.json')\n try:\n file = open('fortest/output_test.json','r')\n except FileNotFoundError:\n print (\"Fail! There is no file!\")\n file.close()\n return\n\n try:\n data = file.read()\n res = json.loads(data)\n file.close()\n out(res, req)\n except Exception:\n print (\"Fail! Something wrong with json\")\n file.close()\n\ndef test4():\n print(\"Test for to_json...\")\n req = {\"rentals\": [{\"id\": 1, \"price\": 7000}]}\n data = {\"cars\": [{ \"id\": 1,\n \"price_per_day\": 2000,\n \"price_per_km\": 10 }],\n \"rentals\": [{ \"id\": 1,\n \"car_id\": 1,\n \"start_date\": \"2017-12-8\",\n \"end_date\": \"2017-12-10\",\n \"distance\": 100 }]}\n res = l.calc(data)\n out(res,req)\n\n \ndef out(res,req):\n print(\"Result: \"+ str(res))\n print(\"Req: \" + str(req))\n\n if(res == req):\n print(\"Succesful!\\n\")\n else:\n print(\"Fail!\\n\")\n\n \nif __name__=='__main__':\n test1()\n test2()\n test3()\n test4()\n input(\"Press something to esc\")\n","sub_path":"level1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"650339405","text":"import numpy as np\nimport math\nfrom keras.initializations import normal, identity\nfrom keras.models import model_from_json\nfrom keras.models import Sequential, Model\nfrom keras.engine.training import collect_trainable_weights\nfrom keras.layers import Dense, Flatten, Input, merge, Lambda, GRU, Conv2D, MaxPooling2D, Flatten\nfrom keras.optimizers import Adam\nimport tensorflow as tf\nimport keras.backend as K\n\nHIDDEN1_UNITS = 300\nHIDDEN2_UNITS = 600\n\nclass ActorNetwork(object):\n def __init__(self, sess, state_size, num_states, action_size, BATCH_SIZE, TAU, LEARNING_RATE):\n self.sess = sess\n self.BATCH_SIZE = BATCH_SIZE\n self.TAU = TAU\n self.LEARNING_RATE = LEARNING_RATE\n\n K.set_session(sess)\n\n #Now create the model\n self.model , self.weights, self.state, self.states_images = self.create_actor_network(state_size, num_states, action_size) \n self.target_model, self.target_weights, self.target_state, self.target_state_images = self.create_actor_network(state_size, num_states, action_size) \n self.action_gradient = tf.placeholder(tf.float32,[None, action_size])\n self.params_grad = tf.gradients(self.model.output, self.weights, -self.action_gradient)\n grads = zip(self.params_grad, self.weights)\n self.optimize = tf.train.AdamOptimizer(LEARNING_RATE).apply_gradients(grads)\n self.sess.run(tf.initialize_all_variables())\n\n def train(self, states, action_grads, states_images):\n self.sess.run(self.optimize, feed_dict={\n self.state: states,\n self.action_gradient: action_grads,\n self.states_images: states_images\n })\n\n def target_train(self):\n actor_weights = self.model.get_weights()\n actor_target_weights = self.target_model.get_weights()\n for i in xrange(len(actor_weights)):\n actor_target_weights[i] = self.TAU * actor_weights[i] + (1 - self.TAU)* actor_target_weights[i]\n self.target_model.set_weights(actor_target_weights)\n\n def create_actor_network(self, state_size, num_states, action_dim):\n print(\"Now we build the model\")\n print(\"Changed model\")\n S = Input(shape=[num_states, state_size]) \n I = Input(shape = [15, 64,64])\n conv1 = Conv2D(32, 3,3,activation = 'relu',dim_ordering = 'th', input_shape = (3,64,64), border_mode = 'same')(I)\n mp1 = MaxPooling2D(pool_size = (2,2), dim_ordering = 'th')(conv1)\n conv2 = Conv2D( 16,3,3,activation = 'relu',dim_ordering = 'th', input_shape = (3,64,64), border_mode = 'same')(mp1)\n mp2 = MaxPooling2D(pool_size = (2,2), dim_ordering = 'th')(conv2)\n conv3 = Conv2D( 8,3,3,activation = 'relu',dim_ordering = 'th', input_shape = (3,64,64), border_mode = 'same')(mp2)\n mp3 = MaxPooling2D(pool_size = (2,2), dim_ordering = 'th')(conv3)\n mp3_flatten = Flatten()(mp3)\n im_h = Dense(16, activation = 'relu')(mp3_flatten)\n x = GRU(16, return_sequences=False, name='gru1')(S)\n x_merge = merge([im_h,x], mode = 'concat')\n h0 = Dense(HIDDEN1_UNITS, activation='relu')(x_merge)\n h1 = Dense(HIDDEN2_UNITS, activation='relu')(h0)\n Steering = Dense(1,activation='tanh',init=lambda shape, name: normal(shape, scale=1e-4, name=name))(h1) \n Acceleration = Dense(1,activation='sigmoid',init=lambda shape, name: normal(shape, scale=1e-4, name=name))(h1) \n Brake = Dense(1,activation='sigmoid',init=lambda shape, name: normal(shape, scale=1e-4, name=name))(h1) \n V = merge([Steering,Acceleration,Brake],mode='concat') \n model = Model(input=[S,I],output=V)\n return model, model.trainable_weights, S, I\n\n","sub_path":"ActorNetwork.py","file_name":"ActorNetwork.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"178642263","text":"from unittest import TestCase\r\nfrom ddt import*\r\nfrom bank import Bank\r\n\r\n# 数据源\r\nadd = [\r\n [1, 1, 111111, 1, 1, 1, 1, 1000],\r\n [2, 1, 111111, 1, 1, 1, 1, 1000]\r\n]\r\nsave = [\r\n [1, 100]\r\n]\r\nget = [\r\n [1, 111111, 100] # account, pwd, money\r\n]\r\nquery = [\r\n [1, 111111] # account, pwd\r\n]\r\n\r\ntransfer = [\r\n [1, 2, 111111, 100] # account, account1, pwd, transferMon\r\n]\r\n\r\n@ddt\r\nclass TestBank(TestCase):\r\n # 测试开户\r\n @data(*add)\r\n @unpack\r\n def testaddUser(self, account, username, password, country, province, street, gate, money):\r\n bank = Bank()\r\n bank.bank_addUser(account, username, password, country, province, street, gate, money,)\r\n\r\n # 测试存钱\r\n @data(*save)\r\n @unpack\r\n def testsaveMoney(self, account, money):\r\n bank = Bank()\r\n bank.bank_saveMoney(account, money)\r\n\r\n # 测试取钱\r\n @data(*get)\r\n @unpack\r\n def testgetMoney(self, account, pwd, money):\r\n bank = Bank()\r\n bank.bank_drawMoney(account, pwd, money)\r\n\r\n # 测试查询\r\n @data(*query)\r\n @unpack\r\n def testquery(self, account, pwd):\r\n bank = Bank()\r\n bank.bank_userQuery(account, pwd)\r\n\r\n @data(*transfer)\r\n @unpack\r\n def testtransferMoney(self, account, account1, pwd, transferMon):\r\n bank = Bank()\r\n bank.bank_transferMoney(account, account1, pwd, transferMon)\r\n","sub_path":"day14/参数化.py","file_name":"参数化.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"400732216","text":"import os\nimport sys\nimport shutil\nimport zipfile\n\n\nclass WordCounter:\n def __init__(self):\n self.result = []\n\n def find_in_dir(self, path):\n \"\"\"Searches given path for txt files including its subdirectories and zip archives\"\"\"\n\n for dirpath, directories, filenames in os.walk(path):\n\n for filename in filenames:\n\n name_and_extension = filename.split(\".\")\n extension = name_and_extension[-1]\n\n if extension == \"txt\":\n # print(os.path.join(dirpath, filename))\n with open(os.path.join(dirpath, filename)) as txt_file:\n words = txt_file.read().split()\n self.result.append({\"name\": filename,\n \"path\": os.path.join(dirpath, filename),\n \"wordcount\": len(words)})\n\n elif extension == \"zip\":\n folder_name = filename.split(\".\")[0]\n path_to_folder = os.path.join(dirpath, folder_name)\n\n try:\n # open zip file\n zfile = zipfile.ZipFile(os.path.join(dirpath, filename))\n\n # create new folder with contents from zip file\n zfile.extractall(path_to_folder)\n zfile.close()\n\n # Exit with error if zip file can't be extracted\n except Exception as e:\n sys.exit(str(e))\n\n # search inside extracted zip folder\n self.find_in_dir(path_to_folder)\n\n # remove the temp folder\n shutil.rmtree(path_to_folder)\n return self.result\n\n\n \n\ndef main():\n path = input(\"Please select path\\n\")\n # path = \"C:\\\\Users\\\\Akvelon\\\\Desktop\\\\wordcount\\\\tests\\\\test_folder\"\n # path = \"/home/user/PycharmProjects/txt_zip/tests/test_folder/\"\n\n try:\n os.chdir(path)\n\n # Exception if path does not exist or no read permissions\n except Exception as e:\n sys.exit(str(e))\n\n word_counter = WordCounter()\n result = word_counter.find_in_dir(path)\n\n for textfile in result:\n print(\"Name: {}\\n\\t Path: {}\\n\\t Word Count: {}\\n\\n\".\n format(textfile[\"name\"], textfile[\"path\"], textfile[\"wordcount\"]))\n\n \nif __name__ == \"__main__\":\n main()","sub_path":"wordcount.py","file_name":"wordcount.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"500877496","text":"import asyncio\nimport utils\nfrom bilibiliCilent import bilibiliClient\nfrom printer import Printer\nfrom bilibili import bilibili\n\n\nclass connect():\n instance = None\n def __new__(cls, *args, **kw):\n if not cls.instance:\n cls.instance = super(connect, cls).__new__(cls, *args, **kw)\n cls.instance.danmuji = None\n cls.instance.tag_reconnect = False\n return cls.instance\n\n async def connect(self):\n while True:\n await asyncio.sleep(0.01)\n Printer().printlist_append(['join_lottery', '', 'user', \"正在启动弹幕姬\"], True)\n time_start = int(utils.CurrentTime())\n self.danmuji = bilibiliClient()\n task_main = asyncio.ensure_future(self.danmuji.connectServer())\n task_heartbeat = asyncio.ensure_future(self.danmuji.HeartbeatLoop())\n finished, pending = await asyncio.wait([task_main, task_heartbeat], return_when=asyncio.FIRST_COMPLETED)\n print('弹幕姬异常或主动断开,处理完剩余信息后重连')\n self.danmuji.connected = False\n time_end = int(utils.CurrentTime())\n if task_heartbeat.done() == False:\n task_heartbeat.cancel()\n print('弹幕主程序退出,立即取消心跳模块')\n else:\n await asyncio.wait(pending)\n print('弹幕心跳模块退出,主程序剩余任务处理完毕')\n # 类似于lock功能,当reconnect模块使用时,禁止重启,直到reconnect模块修改完毕)\n while self.tag_reconnect:\n await asyncio.sleep(0.5)\n print('pending')\n if time_end - time_start < 5:\n print('当前网络不稳定,为避免频繁不必要尝试,将自动在5秒后重试')\n await asyncio.sleep(5)\n \n\n def reconnect(self, roomid):\n self.tag_reconnect = True\n if self.danmuji is not None:\n self.danmuji.close_connection()\n bilibili().dic_bilibili['roomid'] = roomid\n print('已经切换roomid')\n self.tag_reconnect = False\n","sub_path":"connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"209318907","text":"from .dal import solve_l1ls as dal_solver\nfrom .admm import solve_l1ls as admm_solver\nfrom .fista import solve_l1ls as fista_solver\n\nclass Lasso(object):\n def __init__(self, A, b, lmd, maxiter=100, verbose=False):\n self.A = A\n self.b = b\n self.lmd = lmd\n self.maxiter = maxiter\n self.verbose = verbose\n\n def solve(self, solver='admm'):\n if solver == 'fista':\n self.x = fista_solver(self.A, self.b, self.lmd, maxiter = self.maxiter, verbose = self.verbose)\n elif solver == 'admm':\n self.x = admm_solver(self.A, self.b, self.lmd, maxiter = self.maxiter, verbose = self.verbose)\n elif solver == 'dal':\n self.x = dal_solver(self.A, self.b, self.lmd, maxiter = self.maxiter, verbose = self.verbose)\n else:\n raise Exception('Unknown solver is specified')\n\n return self.x\n","sub_path":"tython/sparse/lasso.py","file_name":"lasso.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"29324785","text":"from sys import argv\n\nscript, filename = argv\n\nprint(\"We are going to erase %r.\" %filename)\nprint(\"If you don't want that, hit CTRL-C (^C).\")\nprint (\"if you DO want that, hit ENTER (RETURN on mac).\")\n\ninput(\"?\")\nprint(\"Opening the file\")\ntarget = open(filename, \"w\")\n\nprint(\"Truncating the file. Goodbye!!!\")\ntarget.truncate()\nprint(\"Enter Three different lines of text.\")\n\nline1 = input(\"line1: \")\nline2 = input(\"line2: \")\nline3 = input(\"line3: \")\n\nprint(\"These lines will now be added to the file\")\n\ntarget.write(line1)\ntarget.write(\"\\n\")\ntarget.write(line2)\ntarget.write(\"\\n\")\ntarget.write(line3)\n\nprint(\"Closing the file.\")\ntarget.close()\n\n\n# TEST\n# $python ex16_Reading&Writing.py test.txt","sub_path":"ex16_Reading&Writing.py","file_name":"ex16_Reading&Writing.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"604995601","text":"import os\nimport os.path\nfrom typing import Tuple, Union, List, Any, Dict, Type\nfrom os import listdir\nfrom os.path import isfile, join, splitext\nimport h5py\nimport numpy as np\nimport torch\nimport torch.utils.data as data\nfrom skimage.io import imread\nfrom skimage.transform import downscale_local_mean\nimport transforms\nimport torchvision\nfrom metrics import Result, AverageMeter\nfrom sys import stdout\nfrom numba import njit, float64, types, int64, float32, none\nimport cv2\n\nIMG_EXTENSIONS = [\n '.h5',\n]\n\nTNpData = Tuple[np.ndarray, np.ndarray, np.ndarray]\nSquareShape = Tuple[int, int, int, int]\nImageShape = Tuple[int, int]\n\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\n\ndefault_oheight, default_owidth = 228, 304 # image size after pre-processing\ncolor_jitter = transforms.ColorJitter(0.4, 0.4, 0.4)\n\n\ndef rgb2grayscale(rgb):\n return rgb[:, :, 0] * 0.2989 + rgb[:, :, 1] * 0.587 + rgb[:, :, 2] * 0.114\n\n\nto_tensor = transforms.ToTensor()\n\n\ndef center_square(image_shape: ImageShape, center_width_px: int,\n center_height_px: int) -> SquareShape:\n width, height = image_shape\n assert center_width_px <= width\n assert center_height_px <= height\n center_x, center_y = width // 2, height // 2\n xmin, xmax = (center_x - center_width_px // 2,\n center_x + center_width_px // 2)\n ymin, ymax = (center_y - center_height_px // 2,\n center_y + center_height_px // 2)\n return xmin, xmax, ymin, ymax\n\n\ndef apply_square(square: SquareShape,\n image: Union[np.ndarray, torch.Tensor]) -> np.ndarray:\n x_min, x_max, y_min, y_max = square\n # using try catches bellow as workaround\n # for pytorch not currently supporting zero sized tensors.\n try:\n image[:x_min, ...] = 0\n except ValueError:\n pass\n try:\n image[x_max:, ...] = 0\n except ValueError:\n pass\n try:\n image[x_min:x_max, :y_min, ...] = 0\n except ValueError:\n pass\n try:\n image[x_min:x_max:, y_max:, ...] = 0\n except ValueError:\n pass\n return image\n\n\n@njit(none(float32[:, :], int64, float64))\ndef downscale(depth_img, pixel_count, std_dev):\n x_max, y_max = depth_img.shape\n x_steps = list(range(0, x_max, pixel_count))\n if x_steps[-1] != x_max:\n x_steps.append(x_max)\n x_ranges = list(zip(x_steps, x_steps[1:]))\n y_steps = list(range(0, y_max, pixel_count))\n if y_steps[-1] != y_max:\n y_steps.append(y_max)\n y_ranges = list(zip(y_steps, y_steps[1:]))\n for xlow, xhigh in x_ranges:\n for ylow, yhigh in y_ranges:\n new_depth = depth_img[xlow:xhigh, ylow:yhigh].mean()\n new_depth = np.random.normal(new_depth, std_dev * new_depth)\n depth_img[xlow:xhigh, ylow:yhigh] = new_depth\n\n\ndepth_types = [\n \"full\", \"square\", \"low-quality-square\", \"single-pixel\",\n \"single-pixel-low-quality\"\n]\nmodalities = ['rgb', 'rgbd', 'd']\n\n\nclass RGBDDataset(data.Dataset):\n def __init__(self,\n root: str,\n phase: str,\n modality: str = modalities[0],\n num_samples: int = 0,\n square_width: int = 0,\n output_shape: Tuple[int, int] = (default_oheight,\n default_owidth),\n depth_type=depth_types[0]) -> None:\n self.depth_type = depth_type\n assert self.depth_type in depth_types\n self.oheight, self.owidth = output_shape\n self.phase = phase\n self.paths = self._get_data_paths(root)\n if len(self.paths) == 0:\n raise (RuntimeError(\n \"Found 0 images in subfolders of: \" + root + \"\\n\"\n \"Supported image extensions are: \" + \",\".join(IMG_EXTENSIONS)))\n if self.phase == 'train':\n self.transform = self.train_transform\n elif self.phase == 'val':\n self.transform = self.val_transform\n else:\n raise (RuntimeError(\"Invalid dataset phase: \" + self.phase + \"\\n\"\n \"Supported dataset phases are: train, val\"))\n\n if modality in modalities:\n self.modality = modality\n if modality in ['rgbd', 'd', 'gd']:\n self.num_samples = num_samples\n self.square_width = square_width\n else:\n self.num_samples = 0\n self.square_width = 0\n else:\n raise (RuntimeError(\n \"Invalid modality type: \" + modality + \"\\n\"\n \"Supported dataset types are: \" + ''.join(modalities)))\n\n @property\n def square_width(self) -> int:\n return self._square_width\n\n @square_width.setter\n def square_width(self, value: int) -> None:\n self._square_width = value\n self.square = center_square((self.oheight, self.owidth),\n self._square_width, self._square_width)\n\n @property\n def output_shape(self) -> Tuple[int, int]:\n return self.oheight, self.owidth\n\n @output_shape.setter\n def output_shape(self, value: Tuple[int, int]) -> None:\n self.oheight, self.owidth = value\n assert self.oheight >= 0\n assert self.owidth >= 0\n\n @property\n def mask_inside_square(self) -> Tuple[slice, slice, slice, slice]:\n x_min, x_max, y_min, y_max = self.square\n return (slice(None), slice(None), slice(x_min, x_max),\n slice(y_min, y_max))\n\n def train_transform(self, rgb: np.ndarray, depth_raw: np.ndarray,\n depth_fix: np.ndarray) -> TNpData:\n s = np.random.uniform(1.0, 1.5) # random scaling\n depth_raw = depth_raw / s\n depth_fix = depth_fix / s\n angle = np.random.uniform(-5.0, 5.0) # random rotation degrees\n do_flip = np.random.uniform(0.0, 1.0) < 0.5 # random horizontal flip\n # perform 1st part of data augmentation\n transform = transforms.Compose([\n transforms.Resize(\n 250.0 / self.iheight\n ), # this is for computational efficiency, since rotation is very slow\n transforms.Rotate(angle),\n transforms.Resize(s),\n transforms.CenterCrop((self.oheight, self.owidth)),\n transforms.HorizontalFlip(do_flip)\n ])\n rgb = transform(rgb)\n\n # random color jittering\n rgb = color_jitter(rgb)\n\n rgb = np.asfarray(rgb, dtype='float') / 255\n depth_raw = transform(depth_raw)\n depth_fix = transform(depth_fix)\n\n return rgb, depth_raw, depth_fix\n\n def val_transform(self, rgb: np.ndarray, depth_raw: np.ndarray,\n depth_fix: np.ndarray) -> TNpData:\n # perform 1st part of data augmentation\n transform = transforms.Compose([\n transforms.Resize(240.0 / self.iheight),\n transforms.CenterCrop((self.oheight, self.owidth)),\n ])\n rgb = transform(rgb)\n rgb = np.asfarray(rgb, dtype='float') / 255\n depth_raw = transform(depth_raw)\n depth_fix = transform(depth_fix)\n return rgb, depth_raw, depth_fix\n\n def create_subsampled_depth(self, depth: np.ndarray) -> np.ndarray:\n # remove depth values outside center square\n if self.depth_type == \"low-quality-square\" or self.depth_type == \"single-pixel-low-quality\":\n depth = depth.copy()\n downscale(depth, 10, 0.05)\n\n if \"square\" in self.depth_type:\n depth_subsampled = depth.copy()\n apply_square(self.square, depth_subsampled)\n elif \"full\" == self.depth_type:\n if self.num_samples > 0:\n depth_subsampled = self.dense_to_sparse(depth)\n kernel = np.ones((3, 3), np.uint8)\n depth_subsampled = cv2.dilate(\n depth_subsampled, kernel, iterations=1)\n else:\n depth_subsampled = depth\n elif \"single-pixel\" in self.depth_type:\n depth_subsampled = np.zeros_like(depth)\n x_size, y_size = depth_subsampled.shape[:2]\n center_x, center_y = x_size // 2, y_size // 2\n depth_subsampled[center_x, center_y] = depth[center_x, center_y]\n kernel = np.ones((3, 3), np.uint8)\n depth_subsampled = cv2.dilate(\n depth_subsampled, kernel, iterations=1)\n #depth_subsampled[center_x -50 : center_x + 50,center_y -50: center_y + 50] = depth[center_x,center_y]\n #depth_subsampled[center_x -50 : center_x ,center_y -50: center_y] = depth[center_x,center_y] / 2\n else:\n raise ValueError(\n f\"Invalid depth type self.depth_type = {self.depth_type}\")\n\n # provide random depth points\n return depth_subsampled\n\n def dense_to_sparse(self, depth):\n prob = float(self.num_samples) / depth.size\n mask_keep = np.random.uniform(0, 1, depth.shape) < prob\n new_depth = np.zeros_like(depth)\n new_depth[mask_keep] = depth[mask_keep]\n return new_depth\n\n def create_rgbd(self, rgb: np.ndarray, depth: np.ndarray) -> np.ndarray:\n sparse_depth = self.create_subsampled_depth(depth)\n # rgbd = np.dstack((rgb[:,:,0], rgb[:,:,1], rgb[:,:,2], sparse_depth))\n rgbd = np.append(rgb, np.expand_dims(sparse_depth, axis=2), axis=2)\n return rgbd\n\n def compute_depth_metrics(self, verbose=True) -> Result:\n \"\"\"Computes metrics on the difference between raw and fixed depth values\"\"\"\n avg = AverageMeter()\n for i, path in enumerate(self.paths):\n _, depth_raw, depth_fix = self.load_images(path)\n depth_raw = torch.tensor(depth_raw)\n depth_fix = torch.tensor(depth_fix)\n res = Result()\n res.evaluate(depth_raw, depth_fix)\n avg.update(res, 0, 0, 1)\n if verbose:\n stdout.write(f\"=> computing img {i}/{len(self)}\\r\")\n if verbose:\n stdout.write(\"\\n\")\n return avg.average()\n\n def load_images(self,\n path: Any) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n raise NotImplementedError(\n \"This method must be implemented in subclasses\")\n\n def _get_data_paths(self, base: str) -> List[Any]:\n raise NotImplementedError(\n \"This method must be implemented in subclasses\")\n\n def __getraw__(self, index: int) -> TNpData:\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (rgb, depth) the raw data.\n \"\"\"\n rgb, depth_raw, depth_fix = self.load_images(self.paths[index])\n return rgb, depth_raw, depth_fix\n\n def __get_all_item__(self, index: int\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor,\n np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Args:\n index (int): Index\n Returns:\n tuple: (input_tensor, depth_tensor, input_np, depth_np)\n \"\"\"\n\n rgb, depth_raw, depth_fix = self.__getraw__(index)\n if self.transform is not None:\n rgb_np, depth_raw_np, depth_fix_np = self.transform(\n rgb, depth_raw, depth_fix)\n else:\n raise (RuntimeError(\"transform not defined\"))\n\n # color normalization\n # rgb_tensor = normalize_rgb(rgb_tensor)\n # rgb_np = normalize_np(rgb_np)\n if self.modality == 'rgb':\n input_np = rgb_np\n elif self.modality == 'rgbd':\n input_np = self.create_rgbd(rgb_np, depth_raw_np)\n elif self.modality == 'd':\n input_np = self.create_subsampled_depth(depth_raw_np)\n input_tensor = to_tensor(input_np)\n while input_tensor.dim() < 3:\n input_tensor = input_tensor.unsqueeze(0)\n depth_raw_tensor = to_tensor(depth_raw_np)\n depth_raw_tensor = depth_raw_tensor.unsqueeze(0)\n\n depth_fix_tensor = to_tensor(depth_fix_np)\n depth_fix_tensor = depth_fix_tensor.unsqueeze(0)\n\n return input_tensor, depth_raw_tensor, depth_fix_tensor, input_np, depth_raw_np, depth_fix_np\n\n def __getitem__(self, index: int) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (input_tensor, depth_tensor) \n \"\"\"\n input_tensor, depth_raw_tensor, depth_fix_tensor, input_np, depth_raw_np, depth_fix_np = self.__get_all_item__(\n index)\n\n return input_tensor, depth_fix_tensor\n\n def __iter__(self):\n pass\n\n def __len__(self) -> int:\n return len(self.paths)\n\n\nclass NYUDataset(RGBDDataset):\n iheight = 480\n iwidth = 640\n\n def _get_data_paths(self, base: str) -> List[str]:\n classes, class_to_idx = self.find_classes(base)\n paths = [path for path, idx in self.make_dataset(base, class_to_idx)]\n return paths\n\n def load_images(self, path: str) -> TNpData:\n h5f = h5py.File(path, \"r\")\n rgb = np.array(h5f['rgb'])\n rgb = np.transpose(rgb, (1, 2, 0))\n depth = np.array(h5f['depth'])\n return rgb, depth, depth.copy()\n\n @staticmethod\n def make_dataset(dir,\n class_to_idx: Dict[str, int]) -> List[Tuple[str, int]]:\n images = []\n dir = os.path.expanduser(dir)\n for target in sorted(os.listdir(dir)):\n d = os.path.join(dir, target)\n if not os.path.isdir(d):\n continue\n\n for root, _, fnames in sorted(os.walk(d)):\n for fname in sorted(fnames):\n if is_image_file(fname):\n path = os.path.join(root, fname)\n item = (path, class_to_idx[target])\n images.append(item)\n\n return images\n\n @staticmethod\n def find_classes(dir):\n classes = [\n d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))\n ]\n classes.sort()\n class_to_idx = {classes[i]: i for i in range(len(classes))}\n return classes, class_to_idx\n\n\nclass SUNRGBDDataset(RGBDDataset):\n _im_folder_names = [\"image\", \"depth\", \"depth_bfx\"]\n _v2_im_folder_names = [\"image\", \"depth\", \"depthRaw\"]\n iheight = 427\n iwidth = 561\n\n def load_images(self, image_paths: Tuple[str, str, str]) -> TNpData:\n rgb_fn, depth_raw_fn, depth_fix_fn = image_paths\n rgb = imread(rgb_fn)\n depth_raw = self.scale_depth_image(imread(depth_raw_fn, as_grey=True))\n depth_fix = self.scale_depth_image(imread(depth_fix_fn, as_grey=True))\n return rgb, depth_raw, depth_fix\n\n @staticmethod\n def _get_im_filename(folder: str) -> str:\n im_paths = (join(folder, f) for f in listdir(folder)\n if isfile(join(folder, f)) and splitext(f)[1] in\n torchvision.datasets.folder.IMG_EXTENSIONS)\n return next(im_paths)\n\n def _get_data_paths(self, base: str) -> List[Tuple[str, str, str]]:\n data_paths = []\n for path, dirs, files in os.walk(base):\n for im_folder_names in [\n self._im_folder_names, self._v2_im_folder_names\n ]:\n if all(d in dirs for d in im_folder_names):\n rgb_dir, depth_raw_dir, depth_fix_dir = map(\n lambda dir: join(base, path, dir), im_folder_names)\n rgb_fn = self._get_im_filename(rgb_dir)\n depth_raw_fn = self._get_im_filename(depth_raw_dir)\n depth_fix_fn = self._get_im_filename(depth_fix_dir)\n data_paths.append((rgb_fn, depth_raw_fn, depth_fix_fn))\n break\n data_paths = sorted(data_paths)\n split_idx = len(data_paths) // 10\n if self.phase == \"val\":\n data_paths = data_paths[:split_idx]\n elif self.phase == \"train\":\n data_paths = data_paths[split_idx:]\n else:\n raise Exception(\"We should never be here\")\n\n return data_paths\n\n @staticmethod\n def scale_depth_image(image: np.ndarray) -> np.ndarray:\n \"\"\"Implements the same scaling of depht\n images as in the file read3dPoints.m \n in the SUNRGBDTooolbox\"\"\"\n\n # TODO Check that this yield resonable output values: DONE, looks like metric\n im_scale = np.bitwise_or(\n np.left_shift(image, 16 - 3), np.right_shift(image, 3)) / 1000\n im_scale[im_scale > 8] = 8\n return im_scale.astype(\"float32\")\n\n\ndata_names_2_type = {\n 'nyudepthv2': NYUDataset,\n 'SUNRGBD': SUNRGBDDataset\n} #type: Dict[str,Type[RGBDDataset]]\n\ndata_names = list(data_names_2_type.keys())\n\n\ndef choose_dataset_type(dataset_name: str) -> RGBDDataset:\n return data_names_2_type[dataset_name]\n","sub_path":"dataloaders.py","file_name":"dataloaders.py","file_ext":"py","file_size_in_byte":16851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"162023879","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def getIntersectionNode(self, headA, headB):\n \"\"\"\n :type head1, head1: ListNode\n :rtype: ListNode\n \"\"\"\n visted = set()\n run = headA\n \n while run:\n visted.add(run)\n run = run.next\n \n run = headB\n while run:\n if run in visted:\n return run\n run = run.next\n return None","sub_path":"Easy/160. Intersection of Two Linked Lists(set).py","file_name":"160. Intersection of Two Linked Lists(set).py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"251332511","text":"\"\"\"\nSection 2\nParallelism with MultiProcessing > multiprocessing(1) : Join, is_alive\nkeyword : multiprocessing, processing state\n\"\"\"\nfrom multiprocessing import Process, process\nimport time\nimport logging\n\n\ndef process_func(name):\n print(f'sub-process {name} : starting')\n time.sleep(3)\n print(f'sub-process {name} : finishing')\n\n\ndef main():\n # logging format\n format = '%(asctime)s : %(message)s'\n logging.basicConfig(format=format, level=logging.INFO, datefmt='%H:%M:%S')\n\n # 함수 인자 확인\n p = Process(target=process_func, args=('first',))\n \n logging.info('Main-Process : before creating Process')\n \n # 프로세스\n p.start()\n \n logging.info('Main-Process : During Process')\n \n # logging.info('Main-Process : Terminate Process')\n # p.terminate()\n \n logging.info('Main-Process : Joined Process')\n p.join()\n \n # 프로세스 상태 확인\n print(f'Process p is alive : {p.is_alive()}')\n\n\n# 메인 시작\nif __name__ == '__main__':\n main()\n","sub_path":"process/02_multiprocessing_join_is_alive.py","file_name":"02_multiprocessing_join_is_alive.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"342939115","text":"#!/usr/bin/env python3\r\n\r\nimport json\r\nimport tweepy\r\nimport datetime\r\nimport smtplib\r\nimport time\r\nimport utils\r\nimport schedule\r\nimport urllib.request\r\nimport urllib.error\r\n\r\nfrom yahoo_finance import Share\r\n\r\n\r\nconfig = utils.open_json(\"./Files/config.json\")\r\n\r\n# File names\r\nLOG = config[\"Files\"][\"Log\"]\r\nEMAILS = config[\"Files\"][\"Emails\"]\r\nTWITTER_NAMES = config[\"Files\"][\"Twitter\"]\r\nCOMPANIES = config[\"Files\"][\"Companies\"]\r\nGENERIC = config[\"Files\"][\"Generic\"]\r\nMONITOR = config[\"Files\"][\"CompaniesToMonitor\"]\r\n\r\n# Boolean value\r\nINITIAL_START = config[\"Files\"][\"InitialStart\"]\r\n\r\n# Email/Password info\r\nEMAIL = config[\"Email-Info\"][\"Email\"]\r\nPASSWORD = config[\"Email-Info\"][\"Password\"]\r\n\r\n# Twitter keys/names\r\nCONSUMER_KEY = config[\"Twitter-Auth\"][\"ConsumerKey\"]\r\nCONSUMER_KEY_SECRET = config[\"Twitter-Auth\"][\"ConsumerSecret\"]\r\nACCESS_TOKEN = config[\"Twitter-Auth\"][\"AccessToken\"]\r\nACCESS_TOKEN_SECRET = config[\"Twitter-Auth\"][\"AccessTokenSecret\"]\r\nTWITTER_HANDLES = config[\"Twitter-Auth\"][\"Handles\"]\r\n\r\n\r\nclass Twitter(object):\r\n def __init__(self, handle=''):\r\n self.handle = handle\r\n\r\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_KEY_SECRET)\r\n auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\r\n self.api = tweepy.API(auth)\r\n\r\n def check_tweets(self):\r\n \"\"\"Checks the twitter handle for new tweets.\r\n If there has been a new tweet, checks it in the Companies\r\n class to see if a company is contained in it\"\"\"\r\n\r\n try:\r\n new_tweet = self.api.user_timeline(screen_name=self.handle, count=1)\r\n\r\n for tweet in new_tweet: # Need to find a fix for this loop\r\n old_tweet = utils.open_file(f'{GENERIC}{self.handle}.txt').strip()\r\n\r\n if old_tweet != tweet.text.encode('utf8'):\r\n utils.write_to_file(f'{GENERIC}{self.handle}.txt', tweet.text)\r\n return tweet.text.encode('utf8')\r\n\r\n except tweepy.TweepError as error:\r\n utils.write_to_log(f'Error checking for new tweets: {error}')\r\n\r\n def check_mentions(self):\r\n \"\"\"Checks mentions for sign up's via email or twitter\r\n via \"Sign up / Sign up [email]\"\"\"\r\n\r\n try:\r\n mentions = self.api.mentions_timeline(count=3)\r\n\r\n for mention in mentions:\r\n if \"stop\" in mention.text.lower():\r\n # Unsubscribe for email\r\n if len(mention.text.split()) == 3:\r\n email = mention.text.split()[2]\r\n email_list = utils.open_file(EMAILS).split()\r\n\r\n if email in email_list:\r\n email_list.remove(email)\r\n utils.write_to_file(EMAILS, ' '.join(email_list))\r\n\r\n # Unsubscribe for Twitter handle\r\n else:\r\n twitter_name = mention.user.screen_name\r\n twitter_name_list = utils.open_file(TWITTER_NAMES).split()\r\n\r\n if twitter_name in twitter_name_list:\r\n twitter_name_list.remove(twitter_name)\r\n utils.write_to_file(TWITTER_NAMES, ' '.join(twitter_name_list))\r\n\r\n elif \"sign up\" in mention.text.lower():\r\n # Email sign up\r\n if len(mention.text.split()) > 3:\r\n email = mention.text.split()[3]\r\n email_list = utils.open_file(EMAILS).split()\r\n\r\n if email not in email_list:\r\n email_list.append(email)\r\n utils.append_to_file(EMAILS, email)\r\n\r\n # Twitter handle sign up\r\n else:\r\n twitter_name = mention.user.screen_name\r\n twitter_name_list = utils.open_file(TWITTER_NAMES).split()\r\n\r\n if twitter_name not in twitter_name_list:\r\n twitter_name_list.append(twitter_name)\r\n utils.append_to_file(TWITTER_NAMES, twitter_name)\r\n\r\n except tweepy.TweepError as error:\r\n utils.write_to_log(f'Error checking mentions: {error}')\r\n\r\n\r\nclass Companies(object):\r\n def __init__(self, tweet='', handle=None):\r\n if tweet != '':\r\n self.tweet = tweet.decode('utf8')\r\n self.original_tweet = self.tweet # Keeping a copy for later use, as self.tweet is edited\r\n else:\r\n self.tweet = tweet\r\n self.handle = handle\r\n\r\n def check_for_companies(self):\r\n \"\"\"Checks list of companies with Trump's tweet\r\n seeing if any companies are listed in his tweet.\r\n Inputs matches into monitor.json\"\"\"\r\n\r\n matches = []\r\n punc = (\"!\", \",\", \".\", \":\", \";\", \"@\", \"?\", \"(\", \")\")\r\n\r\n self.tweet = ''.join([letter for letter in self.tweet if letter not in punc]).lower()\r\n\r\n with open(COMPANIES) as f:\r\n companies = [line.strip() for line in f]\r\n\r\n for word in self.tweet.split():\r\n # Binary search for word\r\n if utils.find(companies, word):\r\n matches.append(word)\r\n\r\n company_dict = utils.open_json(MONITOR)\r\n comp_d = {}\r\n\r\n # Information that is needed by get_initial/current\r\n for company in matches:\r\n comp_d[company] = {}\r\n comp_d[company][\"Date-mentioned\"] = \"{:%d-%m-%Y %H:%M:%S}\".format(datetime.datetime.now())\r\n comp_d[company][\"Mentioned by\"] = self.handle\r\n comp_d[company][\"Tweet\"] = self.original_tweet\r\n comp_d[company][\"Days-left\"] = 7\r\n comp_d[company][\"Symbol\"] = \"unknown\"\r\n comp_d[company][\"Initial-share-price\"] = 1\r\n comp_d[company][\"Current-share-price\"] = 1\r\n comp_d[company][\"Share-price-list\"] = []\r\n\r\n company_dict.update(comp_d)\r\n utils.write_to_json(MONITOR, company_dict)\r\n\r\n return matches\r\n\r\n @staticmethod\r\n def get_initial_company_info():\r\n \"\"\"Gets the initial information for each company\"\"\"\r\n\r\n company_dict = utils.open_json(MONITOR)\r\n\r\n for company in company_dict:\r\n # Gets symbol for company\r\n if company_dict[company][\"Symbol\"] == \"unknown\":\r\n try:\r\n with urllib.request.urlopen(\r\n f'https://finance.yahoo.com/_finance_doubledown/'\r\n f'api/resource/searchassist;searchTerm={company}') as response:\r\n\r\n html = response.read().decode()\r\n d = json.loads(html)\r\n\r\n company_dict[company][\"Symbol\"] = d['items'][0]['symbol']\r\n\r\n except urllib.error.HTTPError as error:\r\n utils.write_to_log(f'Error opening URL: {error}')\r\n\r\n # Gets initial share price\r\n if company_dict[company][\"Initial-share-price\"] == 1:\r\n yahoo = Share(company_dict[company][\"Symbol\"])\r\n share = yahoo.get_price()\r\n company_dict[company][\"Initial-share-price\"] = float(share)\r\n company_dict[company][\"Current-share-price\"] = float(share)\r\n\r\n utils.write_to_json(MONITOR, company_dict)\r\n\r\n @staticmethod\r\n def get_current_shares():\r\n \"\"\"Gets current shares, compares it to initial, finds difference.\r\n Returns for output to handle\"\"\"\r\n\r\n company_dict = utils.open_json(MONITOR)\r\n\r\n for company in company_dict:\r\n try:\r\n yahoo = Share(company_dict[company][\"Symbol\"])\r\n yahoo.refresh()\r\n share = yahoo.get_price()\r\n\r\n company_dict[company][\"Current-share-price\"] = float(share)\r\n company_dict[company][\"Share-price-list\"].append(float(share))\r\n\r\n except ValueError:\r\n # yahoo.get_price() will return None if an error occurs\r\n print(\"Could not add to the Current share/Share price list\")\r\n\r\n utils.write_to_json(MONITOR, company_dict)\r\n\r\n @staticmethod\r\n def difference_in_shares():\r\n \"\"\"Finds the difference in shares.\r\n Creates a dict to be used by Output\"\"\"\r\n\r\n company_dict = utils.open_json(MONITOR)\r\n\r\n share_difference_dict = {}\r\n\r\n for company in company_dict:\r\n share_change = 1.0 - (company_dict[company][\"Initial-share-price\"] /\r\n company_dict[company][\"Current-share-price\"])\r\n\r\n maximum = 1 - (company_dict[company][\"Initial-share-price\"] /\r\n max(company_dict[company][\"Share-price-list\"]))\r\n\r\n share_difference_dict[company] = {}\r\n share_difference_dict[company][\"Change\"] = share_change\r\n share_difference_dict[company][\"Max\"] = max(company_dict[company][\"Share-price-list\"])\r\n share_difference_dict[company][\"Max-change\"] = maximum\r\n share_difference_dict[company][\"Initial\"] = company_dict[company][\"Initial-share-price\"]\r\n share_difference_dict[company][\"Current\"] = company_dict[company][\"Current-share-price\"]\r\n\r\n return share_difference_dict\r\n\r\n @staticmethod\r\n def minus_days():\r\n \"\"\"Takes away a day from the \"Days-Left\",\r\n removes from monitor.json if == 0\"\"\"\r\n\r\n company_dict = utils.open_json(MONITOR)\r\n remove = []\r\n\r\n for company in company_dict:\r\n if company_dict[company][\"Days-left\"] > 0:\r\n company_dict[company][\"Days-left\"] -= 1\r\n\r\n elif company_dict[company][\"Days-left\"] == 0:\r\n remove.append(company)\r\n\r\n for company in remove:\r\n # Do I want to keep a record of all the companies that have been mentioned and their prices???\r\n # Goes here\r\n del company_dict[company]\r\n\r\n utils.write_to_json(MONITOR, company_dict)\r\n\r\n\r\nclass Output(object):\r\n def __init__(self, matches=None, handle=None):\r\n self.handle = handle\r\n self.matches = matches\r\n self.twitter = Twitter()\r\n\r\n def tweet(self):\r\n \"\"\"Tweets and DMs the company that has been mentioned\"\"\"\r\n\r\n try:\r\n for company in self.matches:\r\n self.twitter.api.update_status(\r\n f'Yelp, looks like a good time to take a look at your shares in {company.upper()}! '\r\n f'{self.handle} just mentioned them!')\r\n\r\n twitter_users = utils.open_file(TWITTER_NAMES).split()\r\n\r\n for user in twitter_users:\r\n time.sleep(2)\r\n self.twitter.api.send_direct_message(screen_name=user,\r\n text=f'{self.handle} just tweeted about {company.upper()}! '\r\n f'Might be time to check your shares!')\r\n\r\n except tweepy.TweepError as error:\r\n utils.write_to_log(f'Error tweeting: {error}')\r\n\r\n def email(self):\r\n \"\"\"Emails a list of people\"\"\"\r\n\r\n company_output = ', '.join(self.matches)\r\n\r\n try:\r\n email_list = utils.open_file(EMAILS).split()\r\n\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.starttls()\r\n server.login(EMAIL, PASSWORD)\r\n server.sendmail(EMAIL, email_list,\r\n f'Trump just tweeted about {company_output}. '\r\n f'Might be time to check your shares...')\r\n server.quit()\r\n\r\n except smtplib.SMTPResponseException as error:\r\n utils.write_to_log(f'Email error: {error}')\r\n\r\n @staticmethod\r\n def share_output():\r\n \"\"\"Calls difference_in_shares from the Companies class,\r\n Outputs the data to twitter.\"\"\"\r\n\r\n share_difference_dict = Companies().difference_in_shares()\r\n\r\n for company in share_difference_dict:\r\n try:\r\n # If you're following one person, this can be changed to look better\r\n # Remove \"[Mentioned by: {company[\"Handle\"]}\" in the first line.\r\n Twitter().api.update_status(f'{company} [Mentioned by: {company[\"Handle\"]} - '\r\n f'Initial Share Price: {company[\"Initial\"]} '\r\n f'Current Share Price: {company[\"Current\"]}'\r\n f'Change: {company[\"Change\"]}'\r\n f'Max Change: {company[\"Max-change\"]} '\r\n )\r\n\r\n except tweepy.TweepError as error:\r\n utils.write_to_log(f'Twitter output Error: {error}')\r\n\r\n\r\ndef main():\r\n global TWITTER_HANDLES\r\n\r\n # Checks if this is the first time running the script\r\n # Allows the user to choose the Twitter Handles to follow\r\n # Sets the TWITTER_HANDLES which is an empty list, to the new updated list\r\n if INITIAL_START:\r\n handles = utils.initial_start()\r\n TWITTER_HANDLES = handles\r\n\r\n # Sets up jobs for schedule to handle\r\n companies = Companies()\r\n output = Output()\r\n\r\n schedule.every().day.at(\"16:00\").do(companies.minus_days)\r\n schedule.every().day.at(\"18:00\").do(output.share_output)\r\n\r\n while True:\r\n for handle in TWITTER_HANDLES:\r\n twitter = Twitter(handle)\r\n new_tweet = twitter.check_tweets()\r\n\r\n # Checks if a new tweet has been posted\r\n if new_tweet:\r\n companies = Companies(new_tweet, handle)\r\n matches = companies.check_for_companies()\r\n\r\n if matches:\r\n # Gets the initial company info\r\n companies.get_initial_company_info()\r\n\r\n # Outputs the matches via twitter/email\r\n output = Output(matches, handle)\r\n output.tweet()\r\n output.email()\r\n\r\n # Gets the current shares for each company, checks mentions for sign ups/removals\r\n Companies().get_current_shares()\r\n twitter.check_mentions()\r\n\r\n schedule.run_pending()\r\n time.sleep(30)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"stock_monitor.py","file_name":"stock_monitor.py","file_ext":"py","file_size_in_byte":14333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"322543363","text":"import discord\nimport os\nimport pymongo\nfrom discord.ext import commands\nfrom constants import BOT_TOKEN, PREFIX\n\ndef get_cogs():\n cogs = []\n for filename in os.listdir('./cogs'):\n if filename.endswith('.py'):\n cogs.append(filename[:-3])\n return cogs\n\nbot = commands.Bot(command_prefix=PREFIX, case_insensitive=True, help_command = None)\n\nbot.get_cogs = get_cogs\n\ncogs = get_cogs()\nfor cog in cogs:\n bot.load_extension(f'cogs.{cog}')\n print(f'{cog} is now loaded')\n\n@bot.event\nasync def on_ready():\n print(f'{bot.user} is ready')\n\nbot.run(BOT_TOKEN)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"94163004","text":"import matplotlib\nmatplotlib.use('Agg')\nimport numpy as np\nimport pandas as pd\nfrom util import get_data, plot_data\nimport datetime as dt\nimport matplotlib.pyplot as plt\n\n# 4 indicators\n\n#price : get_data(filename,pd.date_range(sd, ed))\ndef price_sma(price, lookback, symbol):\n\n\tsma = price.rolling(window = lookback, min_periods = lookback).mean()\n\tprice_sma_values = sma\n\t\n\n\tprice_sma_values = price / price_sma_values\n\t#normalize price JPM\n\tnormailize_price = price[symbol]/price[symbol][0]\n\n\tnormalize_sma = sma[symbol]/sma[symbol][lookback - 1]\n\t#plot normalize indicator\n\tif symbol == '!JPM~~~':\n\t\tax = price_sma_values[symbol].plot(legend = True, label = \" Price/SMA\", color = 'black')\n\t\tnormalize_sma.plot(ax = ax, legend = True, label = \"Normalized SMA\", color = 'blue')\n\t\tnormailize_price.plot(ax =ax, legend = True, label = \"Normalize Price\", color = 'red')\n\t\tplt.title(\"Indicator_SMA\")\n\t\tplt.savefig(symbol+ \"_Indicator_SMA\"+ \".png\")\n\t\tplt.close()\n\n\treturn sma, price_sma_values\n\n\n#bollinger bands\ndef bb(price,sma, lookback, symbol):\n\trolling_std = price.rolling(window=lookback, min_periods=lookback).std()\n\n\n\ttop_band = sma + (2 * rolling_std)\n\tbottom_band = sma - (2 * rolling_std)\n\n\ttband = top_band[symbol]\n\tbband = bottom_band[symbol]\n\tJPMprice = price[symbol]\n\n\tif symbol == '!JPM~~~~':\n\t\tax = tband.plot(legend = True, label = \" top_band\", color = 'black')\n\t\tbband.plot(ax = ax, legend = True, label = \"bottom_band\", color = 'blue')\n\t\tsma[symbol].plot(ax =ax, legend = True, label = symbol+ \" sma\", color = 'red')\n\t\tprice[symbol].plot(ax = ax, legend = True, label = symbol+\" price\", color = 'green')\n\t\tplt.title(\" Bollinger Bands\")\n\t\tplt.savefig(symbol+ \"_Bollinger_Bands\"+ \".png\")\n\t\tplt.close()\n\n\tbbp = (price - bottom_band)/(top_band - bottom_band)\n\n\treturn bbp\n\n#RSI\n\ndef RSI(price, lookback, symbol):\n\tdaily_rets = price.copy()\n\tdaily_rets.values[1:,:] = price.values[1:,:] - price.values[:-1,:]\n\tdaily_rets.values[0,:] = np.nan\n\tsymbols =list(daily_rets.columns)\n\trsi = price.copy()\n\t\n\tfor day in range(price.shape[0]):\n\n\t\tup_gain = daily_rets.ix[day-lookback+1 :day+1,:].where(daily_rets >= 0).sum()\n\t\tdown_loss = -1 * daily_rets.ix[day-lookback+1:day+1,:].where(daily_rets < 0).sum()\n\t\tfor sym in symbols:\n\t\t\tif down_loss[sym] == 0:\n\t\t\t\trsi.ix[day,sym] = 100\n\n\t\t\telse:\n\t\t\t\trs = (up_gain[sym]/lookback) / (down_loss[sym]/lookback)\n\t\t\t\trsi.ix[day,sym] = 100 - (100/(1+ rs))\n\trsi[symbol].ix[0:13] = np.nan\n\n\tif symbol == '!JPM~~~~~':\n\t\tax = rsi[symbol].plot(legend = True, label = \"RSI\", color = 'black')\n\t\tprice[symbol].plot(ax = ax, legend = True, label = symbol+\" price\", color = 'blue')\n\t\tplt.title(\" RSI\")\n\t\tplt.savefig(symbol +\"_RSI\"+ \".png\")\n\t\tplt.close()\n\n\treturn rsi\n\ndef stochastic_oscillator(price,lookback,symbol):\n\n\tL14 = price.rolling(window = lookback, min_periods = lookback).min()\n\tH14 = price.rolling(window = lookback, min_periods = lookback).max()\n\t\n\tK = 100 * (price - L14)/(H14 - L14)*1.0\n\tD = K.rolling(window = 3, min_periods = 3).mean()\n\n\tif symbol == '!JPM~~~~~':\n\t\tax = K[symbol].plot(legend = True, label = \"K value\", color = 'black')\n\t\tprice[symbol].plot(ax = ax, legend = True, label = symbol+\" price\", color = 'blue')\n\t\tD[symbol].plot(ax =ax, legend = True, label = \"D value\", color = 'red')\n\t\tplt.title(\"stochastic_oscillator\")\n\t\tplt.savefig(symbol+\"_stochastic_oscillator\"+ \".png\")\n\t\tplt.close()\n\n\treturn K,D\n\n","sub_path":"indicators.py","file_name":"indicators.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"101102121","text":"\nimport math\n\ndef lines():\n words = []\n with open(\"1.txt\") as fp:\n line = fp.readline()\n while line:\n words.append(line)\n line = fp.readline()\n return words\n\ndef process_lines():\n pre = lines()\n post = []\n for a in pre:\n post.append(int(a))\n return post\n\n\nlines = process_lines()\n\n\nfor x in lines:\n for y in lines:\n for z in lines:\n if x+y+z == 2020:\n print(x*y*z)","sub_path":"1_2.py","file_name":"1_2.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"296797984","text":"from PyQt4.QtWebKit import QWebPage, QWebSettings, QWebView\nfrom PyQt4.QtCore import Qt, QUrl, QBuffer, QSize\nfrom PyQt4.QtGui import QPainter, QImage\nfrom PyQt4.QtNetwork import QNetworkRequest\nfrom twisted.internet import defer\n\nqWebSettings = {\n QWebSettings.JavascriptEnabled : True,\n QWebSettings.PluginsEnabled : False,\n QWebSettings.PrivateBrowsingEnabled : True,\n QWebSettings.LocalStorageEnabled : True,\n #QWebSettings.JavascriptCanOpenWindows : True,\n #QWebSettings.FrameFlatteningEnabled : True,\n #QWebSettings.DeveloperExtrasEnabled : True,\n}\n\n\nfor key, value in qWebSettings.iteritems():\n QWebSettings.globalSettings().setAttribute(key, value)\n\nclass RenderError(Exception):\n pass\n\n\nclass HtmlRender(QWebPage):\n\n def __init__(self, url, baseurl=None):\n QWebPage.__init__(self) \n self.url = url\n self.webview = QWebView()\n self.webview.setPage(self)\n #self.webview.show()\n \n self.deferred = defer.Deferred(self.cancel)\n if baseurl:\n self._baseUrl = QUrl(baseurl)\n request = QNetworkRequest()\n request.setUrl(QUrl(url))\n\n self.networkAccessManager().finished.connect(self._urlFinished)\n self.networkAccessManager().get(request)\n else:\n self.loadFinished.connect(self._loadFinished)\n self.mainFrame().load(QUrl(url))\n\n def _loadFinished(self, ok):\n if ok:\n try:\n self.deferred.callback(self._render())\n except:\n self.deferred.errback()\n else:\n self.deferred.errback(RenderError())\n\n def _render(self):\n return str(self.mainFrame().toHtml().toUtf8())\n\n def _urlFinished(self, reply):\n self.networkAccessManager().finished.disconnect(self._urlFinished)\n self.loadFinished.connect(self._loadFinished)\n mimeType = reply.header(QNetworkRequest.ContentTypeHeader).toString()\n self.mainFrame().setContent(reply.readAll(), mimeType, self._baseUrl)\n\n def cancel(self, _):\n self.loadFinished.disconnect(self._loadFinished)\n self.webview.stop()\n\n def close(self):\n pass\n\n def javaScriptAlert(self, frame, msg):\n return\n\n def javaScriptConfirm(self, frame, msg):\n return False\n\n\nclass PngRender(HtmlRender):\n\n def __init__(self, url, baseurl=None, width=None, height=None, vwidth=1024, vheight=768):\n HtmlRender.__init__(self, url, baseurl)\n self.width = width\n self.height = height\n self.vwidth = vwidth\n self.vheight = vheight\n\n def _render(self):\n self.setViewportSize(QSize(self.vwidth, self.vheight))\n image = QImage(self.viewportSize(), QImage.Format_ARGB32)\n painter = QPainter(image)\n self.mainFrame().render(painter)\n painter.end()\n if self.width:\n image = image.scaledToWidth(self.width, Qt.SmoothTransformation)\n if self.height:\n image = image.copy(0, 0, self.width, self.height)\n b = QBuffer()\n image.save(b, \"png\")\n return str(b.data())\n","sub_path":"splash/qtrender.py","file_name":"qtrender.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"609228747","text":"from PIL import ImageTk, Image\n\n\"\"\"\nRecibe dos valores, mosX y mosY que definen el tamanio del mosaico\nRecorre la imagen de mosaico en mosaico\nPor cada mosaico se saca el promedio de los valores rojo,verde y azul de cada pixel\nYa que se obtiene cada promedio, se aplica ese valor a cada componente correspondiente de los pixeles del mosaico\n\"\"\"\ndef filtroMosaico(imagen,aplica,mosX,mosY):\n recorreX = 0\n recorreY = 0\n rprom = 0\n gprom = 0\n bprom = 0\n prom = 0\n ancho = imagen.size[0]\n alto = imagen.size[1]\n rgb = imagen.convert('RGB')\n pixels = aplica.load()\n for i in range(0,ancho,mosX):\n recorreX = i + mosX\n for j in range(0,alto,mosY):\n recorreY = j + mosY\n for k in range(i,recorreX):\n if (k >= ancho):\n break\n for l in range(j,recorreY):\n if (l >= alto):\n break\n r,g,b = rgb.getpixel((k,l))\n rprom += r\n gprom += g\n bprom += b\n prom += 1\n promRojo = (rprom/prom)\n promVerde = (gprom/prom)\n promAzul = (bprom/prom)\n rprom = 0\n gprom = 0\n bprom = 0\n prom = 0\n for k in range(i,recorreX):\n if (k >= ancho):\n break\n for l in range(j,recorreY):\n if (l >= alto):\n break\n pixels[k,l] = (promRojo,promVerde,promAzul)\n \n return aplica\n","sub_path":"Practica07-Procesamiento/src/FiltroMosaico.py","file_name":"FiltroMosaico.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"289324546","text":"from unittest.mock import patch\n\nfrom rubicon.sklearn import RubiconPipeline\nfrom rubicon.sklearn.estimator_logger import EstimatorLogger\nfrom rubicon.sklearn.filter_estimator_logger import FilterEstimatorLogger\nfrom rubicon.sklearn.pipeline import Pipeline\n\n\ndef test_get_default_estimator_logger(project_client, fake_estimator_cls):\n project = project_client\n estimator = fake_estimator_cls()\n steps = [(\"est\", estimator)]\n pipeline = RubiconPipeline(project, steps)\n\n logger = pipeline.get_estimator_logger()\n\n assert type(logger) == EstimatorLogger\n\n\ndef test_get_user_defined_estimator_logger(project_client, fake_estimator_cls):\n project = project_client\n estimator = fake_estimator_cls()\n steps = [(\"est\", estimator)]\n user_defined_logger = {\"est\": FilterEstimatorLogger(ignore_all=True)}\n pipeline = RubiconPipeline(project, steps, user_defined_logger)\n\n logger = pipeline.get_estimator_logger(\"est\")\n\n assert type(logger) == FilterEstimatorLogger\n\n\ndef test_fit_logs_parameters(project_client, fake_estimator_cls):\n project = project_client\n estimator = fake_estimator_cls()\n steps = [(\"est\", estimator)]\n user_defined_logger = {\"est\": FilterEstimatorLogger(ignore_all=True)}\n pipeline = RubiconPipeline(project, steps, user_defined_logger)\n\n with patch.object(Pipeline, \"fit\", return_value=None):\n with patch.object(\n FilterEstimatorLogger, \"log_parameters\", return_value=None\n ) as mock_log_parameters:\n pipeline.fit([\"fake data\"])\n\n mock_log_parameters.assert_called_once()\n\n\ndef test_score_logs_metric(project_client, fake_estimator_cls):\n project = project_client\n estimator = fake_estimator_cls()\n steps = [(\"est\", estimator)]\n pipeline = RubiconPipeline(project, steps)\n\n with patch.object(Pipeline, \"score\", return_value=None):\n with patch.object(EstimatorLogger, \"log_metric\", return_value=None) as mock_log_metric:\n pipeline.score([\"fake data\"])\n\n mock_log_metric.assert_called_once()\n","sub_path":"tests/unit/sklearn/test_pipeline.py","file_name":"test_pipeline.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"29447926","text":"from tkinter import *\nimport string\n\n\ndef select():\n\tuserMsg= str(msg.get(\"1.0\",END)).lower()[:-1]\n\tprint (\"user : \",userMsg)\n\tuserKey = str(key.get(\"1.0\",END)).lower()[:-1].replace(\"j\",\"i\")\n\tencryptedText = \"\"\n\tif var.get() ==1 :\n\t\tprint (\"Ceasar\")\n\t\tfor i in userMsg :\n\t\t\tencryptedText=encryptedText+chr((ord(i)-97+3)%97 + 97)\n\telse :\n\t\tprint (\"PlayFair\")\n\t\tuserMsg = userMsg.replace(\"j\",\"i\")\n\t\tuserMsg = \"\".join(userMsg.split())\n\t\tfor i in range(0,len(userMsg)+1,2):\n\t\t\tprint (\"i:\",i)\n\t\t\tif i+1 < len(userMsg) and userMsg[i] == userMsg[i+1] :\n\t\t\t\tuserMsg = userMsg[0:i+1]+\"x\"+userMsg[i+1:]\n\t\tprint (userMsg)\n\t\tallAlp = set(string.ascii_lowercase)\n\t\tallAlp.remove('j')\n\t\tkeyMat=[]\n\t\tfor i in userKey:\n\t\t\tkeyMat.append(i)\n\t\tremainingChars = sorted(set(allAlp).difference(set(keyMat)))\n\t\tfor i in remainingChars :\n\t\t\tkeyMat.append(i)\n\t\tprintKey(keyMat)\n\t\tfor i in range(0,len(userMsg)-1,2):\n\t\t\tx = keyMat.index(userMsg[i])\n\t\t\ty = keyMat.index(userMsg[i+1])\n\t\t\txrow = x/5\n\t\t\tyrow = y/5\n\t\t\txcol = x%5\n\t\t\tycol = y%5\n\t\t\tif xrow == yrow :\n\t\t\t\t#same row\n\t\t\t\tencryptedText=encryptedText + keyMat[xrow*5+((xcol+1)%5)] + keyMat[yrow*5+((ycol+1)%5)]\n\t\t\telif xcol == ycol :\n\t\t\t\t#same col\n\t\t\t\tencryptedText=encryptedText + keyMat[(((xrow+1)%5)*5)+xcol] + keyMat[(((yrow+1)%5)*5)+ycol]\n\t\t\telse:\n\t\t\t\tencryptedText=encryptedText + keyMat[xrow*5+ycol] + keyMat[yrow*5+xcol]\n\tresult.set(\"Encrypted Text : \"+encryptedText)\n\n\n\ndef printKey(keyMat) :\n\tfor i in range(0,5) :\n\t\tfor j in range(0,5) :\n\t\t\tprint (\"\\t\",keyMat[i*5+j],)\n\t\tprint (\"\\n\")\n\nroot=Tk();\nframe=Frame(root,width=300, height=300)\nframe.pack()\nvar=IntVar()\n\nstx = 10\nsty=10\ndistx=90\ndisty=50\nmsgLabel = Label(text=\"Enter msg :\")\nmsgLabel.place(x=stx,y=sty)\nmsg = Text()\nmsg.place(x=stx+distx,y=sty, height=20, width=180)\n\nkeyLabel = Label(text=\"Enter key :\")\nkeyLabel.place(x=stx,y=sty+disty)\nkey = Text()\nkey.place(x=stx+distx,y=sty+disty, height=20, width=180)\n\nradio1 = Radiobutton(root,text=\"ceaser\",variable=var, value=1, command=select)\nradio1.place(x=stx+30,y=sty+2*disty)\nradio2 = Radiobutton(root,text=\"playfair\",variable=var, value=2, command=select)\nradio2.place(x=stx+30,y=sty+3*disty)\n#radio1.pack()\n\nresult=StringVar()\nresLabel = Label(textvariable=result)\nresLabel.place(x=stx,y=sty+4*disty)\nroot.mainloop()","sub_path":"playfair.py","file_name":"playfair.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"638617841","text":"\nfrom .. import usbhid\n\nrival700 = {\n \"name\": \"SteelSeries Rival 700 (Experimental)\",\n\n \"vendor_id\": 0x1038,\n \"product_id\": 0x1700,\n \"interface_number\": 0,\n\n \"commands\": {\n\n \"set_sensitivity1\": {\n \"description\": \"Set sensitivity preset 1\",\n \"cli\": [\"-s\", \"--sensitivity1\"],\n \"command\": [0x03, 0x00, 0x01],\n \"suffix\": [0x00, 0x42],\n \"value_type\": \"range\",\n \"range_min\": 100,\n \"range_max\": 12000,\n \"range_increment\": 100,\n \"value_transform\": lambda x: int((x / 100) - 1),\n \"default\": 800,\n },\n\n \"set_sensitivity2\": {\n \"description\": \"Set sensitivity preset 2\",\n \"cli\": [\"-S\", \"--sensitivity2\"],\n \"command\": [0x03, 0x00, 0x02],\n \"suffix\": [0x00, 0x42],\n \"value_type\": \"range\",\n \"range_min\": 100,\n \"range_max\": 12000,\n \"range_increment\": 100,\n \"value_transform\": lambda x: int((x / 100) - 1),\n \"default\": 1600,\n },\n\n \"set_polling_rate\": {\n \"description\": \"Set polling rate in Hz\",\n \"cli\": [\"-p\", \"--polling-rate\"],\n \"command\": [0x04, 0x00],\n \"value_type\": \"choice\",\n \"choices\": {\n 125: 0x04,\n 250: 0x03,\n 500: 0x02,\n 1000: 0x01,\n },\n \"default\": 1000,\n },\n\n \"set_logo_color\": {\n \"description\": \"Set the logo backlight color\",\n \"cli\": [\"-c\", \"--logo-color\"],\n \"command\": [0x05, 0x00, 0x00],\n \"suffix\": [0xFF, 0x32, 0xC8, 0xC8, 0x00, 0x00, 0x01],\n \"report_type\": usbhid.HID_REPORT_TYPE_FEATURE, # wValue = 0x0300\n \"value_type\": \"rgbcolor\",\n \"default\": \"#FF1800\"\n },\n\n \"set_wheel_color\": {\n \"description\": \"Set the wheel backlight color\",\n \"cli\": [\"-C\", \"--wheel-color\"],\n \"command\": [0x05, 0x00, 0x01],\n \"suffix\": [0xFF, 0x32, 0xC8, 0xC8, 0x00, 0x01, 0x01],\n \"report_type\": usbhid.HID_REPORT_TYPE_FEATURE, # wValue = 0x0300\n \"value_type\": \"rgbcolor\",\n \"default\": \"#FF1800\"\n },\n\n \"save\": {\n \"description\": \"Save the configuration to the mouse memory\",\n \"cli\": None,\n \"command\": [0x09, 0x00],\n \"value_type\": None,\n },\n\n },\n\n}\n","sub_path":"rivalcfg/profiles/rival700.py","file_name":"rival700.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"72533965","text":"import http.client\nimport hashlib\nfrom urllib import parse\nimport random\n\nclass BaiduFanyi:\n def __init__(self, ToLanguage, FromLanguage):\n self.httpClient = None\n self.myurl = '/api/trans/vip/translate'\n self.appid = '20180619000178058'\n self.secretKey = '1b8f0UumffJWowWndmdy'\n self.ToLanguage = ToLanguage \n self.FromLanguage = FromLanguage \n self.supported_languages = { # as defined here: http://msdn.microsoft.com/en-us/library/hh456380.aspx\n 'zh' : '中文',\n 'en' : '英语',\n 'kor' : '韩语',\n 'jp' : '日语',\n 'spa' : '西班牙语',\n 'fra': '法语',\n 'th' : '泰语',\n 'ara' : '阿拉伯语',\n 'ru' : '俄语',\n 'pt' : '葡萄牙语',\n 'yue' : '粤语',\n 'wyw' : '文言文',\n 'auto' : '自动检测',\n }\n \n def print_supported_languages (self):\n \"\"\"Display the list of supported language codes and the descriptions as a single string\n (used when a call to translate requests an unsupported code)\"\"\"\n codes = []\n for k,v in self.supported_languages.items():\n codes.append('\\t'.join([k, '=', v]))\n return ('\\n'.join(codes))\n \n def judge_from_languages (self):\n if self.FromLanguage not in self.supported_languages.keys(): \n print ('Sorry, the API cannot translate from', self.FromLanguage)\n print ('Please use one of these instead:')\n return (0)\n else:\n return (1)\n \n def judge_to_languages (self):\n if self.ToLanguage not in self.supported_languages.keys(): # 检验译语是否支持\n print ('Sorry, the API cannot translate to', self.ToLanguage)\n print ('Please use one of these instead:')\n return (0)\n else:\n return (1)\n \n \n def translate (self, queryText):\n salt = random.randint(32768, 65536)\n sign = self.appid+queryText+str(salt)+self.secretKey\n m1 = hashlib.md5()\n m1.update(sign.encode(encoding='utf-8'))\n sign = m1.hexdigest()\n myurl = self.myurl+'?appid='+self.appid+'&q='+parse.quote(queryText)+'&from='+self.FromLanguage+'&to='+self.ToLanguage+'&salt='+str(salt)+'&sign='+sign \n file = open('result_baidu.txt','w')\n try:\n httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')\n httpClient.request('GET', myurl)\n response = httpClient.getresponse()\n string = response.read().decode('utf-8')\n string = eval(string) # eval() 函数用来执行一个字符串表达式,并返回表达式的值。\n for line in string['trans_result']: # str['trans_result']里有百度api返回的结果\n file.write(line['dst']+'\\n')\n except Exception as e:\n print(e)\n finally:\n if httpClient:\n httpClient.close()\n file.close()\n \n # Note: We convert result, which is JSON, to and from an object so we can pretty-print it.\n # We want to avoid escaping any Unicode characters that result contains. See:\n # https://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence\n \nif __name__ == \"__main__\":\n FromLanguage = input(\"请输入源语言: \").strip()\n ToLanguage = input(\"请输入目标语言: \").strip()\n fanyi = BaiduFanyi(ToLanguage, FromLanguage) \n source = fanyi.judge_from_languages()\n if (source==0):\n print (fanyi.print_supported_languages())\n target = fanyi.judge_to_languages()\n if (target==0):\n print (fanyi.print_supported_languages())\n \n if (source==1 and target==1):\n with open('fanyi.txt') as f: # 默认模式为‘r’,只读模式\n contents = f.read() # 读取文件全部内容\n fanyi.translate(contents)\n \n","sub_path":"translator_api_py/baidu_class.py","file_name":"baidu_class.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"377107725","text":"# [2017-06-27] Challenge #321 [Easy] Talking Clock\n\n# Description\n#\n# No more hiding from your alarm clock! You've decided you want your computer to keep you updated on the time so you're never late again. A talking clock takes a 24-hour time and translates it into words.\n#\n# Input Description\n#\n# An hour (0-23) followed by a colon followed by the minute (0-59).\n#\n# Output Description\n#\n# The time in words, using 12-hour format followed by am or pm.\n#\n# Sample Input data\n#\n# 00:00\n# 01:30\n# 12:05\n# 14:01\n# 20:29\n# 21:00\n# Sample Output data\n#\n# It's twelve am\n# It's one thirty am\n# It's twelve oh five pm\n# It's two oh one pm\n# It's eight twenty nine pm\n# It's nine pm\n\nzero_to_nineteen = [\"\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eightteen\", \"nineteen\"]\ntens = [\"\", \"\", \"twenty\", \"thirty\", \"fourty\", \"fifty\"]\n\nabrv = \"am\"\ntime = input(\"Enter a valid military time: \")\ntime = time.split(\":\")\nhours = int(time[0])\nmins = int(time[1])\n\n# check if it is the afternoon and covert out of military time\nif hours >= 12:\n abrv = \"pm\"\n hours = hours % 12\n\n# convert 00:xx to 12:xx\nif hours == 0:\n hours = 12\n\nhours_str = zero_to_nineteen[hours]\n\nif 0 < mins < 10:\n mins_str = \"oh \" + zero_to_nineteen[mins]\nelif mins < 20:\n mins_str = zero_to_nineteen[mins]\nelse:\n mins_arr = [int(d) for d in str(mins)]\n mins_str = tens[mins_arr[0]] + \" \" + zero_to_nineteen[mins_arr[1]]\n\nprint(\"It's \" + hours_str + \" \" + mins_str + \" \" + abrv)\n","sub_path":"Easy/TalkingClock.py","file_name":"TalkingClock.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"385082039","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic.edit import UpdateView\nfrom django.contrib import messages\n\nfrom core.models import Comment\n\n\ndef index(request):\n\tif request.method == 'POST':\n\t\t#Creating a comment\n\t\tnew_title = request.POST.get('title')\n\t\tnew_description = request.POST.get('description')\n\n\t\tif new_title and new_description:\n\t\t\tnew_comment = Comment(title=new_title, description=new_description, creation_user=request.user if request.user.is_authenticated else None)\n\t\t\tnew_comment.save()\n\n\tcomments = Comment.objects.all()\n\tcontext = {\n\t\t'all_comments': comments\n\t}\n\ttemplate = loader.get_template('index.html')\n\treturn HttpResponse(template.render(context, request))\n\n@login_required\ndef delete_comment(request, comment_id):\n\t\n\ttry:\n\t\tcomment = Comment.objects.get(pk=comment_id)\n\t\tif comment.creation_user != request.user:\n\t\t\ttemplate = loader.get_template('403.html')\n\t\t\treturn HttpResponse(template.render({}, request))\n\t\tcomment.delete()\n\t\tmessages.warning(request, 'Your post is delete!')\n\texcept Comment.DoesNotExist:\n\t\tpass\n\n\treturn redirect('index')\n\n@login_required\ndef edit_comment(request, comment_id):\n\n\ttry:\n\t\tcomment = Comment.objects.get(pk=comment_id)\n\texcept Comment.DoesNotExist:\n\t\ttemplate = loader.get_template('404.html')\n\t\treturn HttpResponse(template.render({}, request))\n\n\tif comment.creation_user != request.user:\n\t\ttemplate = loader.get_template('403.html')\n\t\treturn HttpResponse(template.render({}, request))\n\n\tif request.method == 'POST':\n\t\tnew_title = request.POST.get('title')\n\t\tnew_description = request.POST.get('description')\n\n\t\tif new_title and new_description:\n\t\t\tcomment.title = new_title\n\t\t\tcomment.description = new_description\n\t\t\tcomment.save()\n\t\t\tmessages.info(request, 'Your post is edit!')\n\t\t\treturn redirect('index')\n\n\n\n\tcontext = {\n\t\t'comment': comment\n\t}\n\ttemplate = loader.get_template('comment_detail.html')\n\treturn HttpResponse(template.render(context, request))\n\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"362348728","text":"from tkinter import *\r\nimport math\r\nimport random,os\r\nfrom tkinter import messagebox\r\n\r\n\r\n\r\n\r\nclass Bill_App:\r\n def __init__(self,root):\r\n self.root=root\r\n self.root.geometry(\"1520x820+0+0\")\r\n self.root.title(\"Daily Needs Store's Invioce Creator \")\r\n bg_color=\"maroon\" #maroon color\r\n title=Label(self.root,text=\"Daily Needs Store's Invoice Creator\",bd=12,relief=GROOVE,bg=bg_color,fg=\"gold\",font=(\"times new roman\",30,\"bold\"),pady=2).pack(fill=X)\r\n\r\n #---------------------Variable-----------------------------------------\r\n \r\n #------------------Cosmetics Variable-----------------------\r\n self.soap=IntVar()\r\n self.face_cream=IntVar()\r\n self.face_wash=IntVar()\r\n self.powder=IntVar()\r\n self.gel=IntVar()\r\n self.lotion=IntVar()\r\n \r\n #----------------------------------Grocery Variable---------------------------------\r\n self.rice=IntVar()\r\n self.wheat=IntVar()\r\n self.wheat_flour=IntVar()\r\n self.daal=IntVar()\r\n self.sugar=IntVar()\r\n self.tea=IntVar()\r\n\r\n #--------------------------Drinks Variables-----------------------\r\n self.maaza=IntVar()\r\n self.frooti=IntVar()\r\n self.coca_cola=IntVar()\r\n self.thumps_up=IntVar()\r\n self.limca=IntVar()\r\n self.sprite=IntVar()\r\n\r\n #-----------------------Total Products Variable---------------------------------------------\r\n self.cosmetic_price=StringVar()\r\n self.grocery_price=StringVar()\r\n self.drinks_price=StringVar()\r\n\r\n #-----------------Tax Variables----------------------------\r\n self.cosmetic_tax=StringVar()\r\n self.grocery_tax=StringVar()\r\n self.drinks_tax=StringVar() \r\n \r\n #------------------Total Prices Variable---------------------------------------\r\n self.total_product_price=StringVar()\r\n self.total_tax=StringVar()\r\n self.total_bill_price=IntVar()\r\n \r\n #---------------------------------------Customer Variable-------------------------\r\n self.c_name=StringVar()\r\n self.c_phone=StringVar()\r\n self.bill_no=StringVar()\r\n x=random.randint(1000,9999)\r\n self.bill_no.set(str(x))\r\n self.search_bill=StringVar() \r\n \r\n \r\n \r\n #-------------------Customer Details Frame---------------\r\n\r\n F1=LabelFrame(self.root,text=\"Customer Details\",bd=10,relief=GROOVE,font=(\"times new roman\",15,\"bold\"),fg=\"gold\",bg=bg_color) \r\n F1.place(x=0,y=80,relwidth=1)\r\n\r\n\r\n cname_label=Label(F1,text=\"Customer Name :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",18,\"bold\")).grid(row=0,column=0,padx=10,pady=10)\r\n cname_text=Entry(F1,width=18,textvariable=self.c_name,bd=7,relief=SUNKEN,font=(\"ariel\",15)).grid(row=0,column=1,padx=5,pady=10)\r\n\r\n cphone_label=Label(F1,text=\"Phone No. :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",18,\"bold\")).grid(row=0,column=2,padx=10,pady=10)\r\n cphone_text=Entry(F1,width=18,textvariable=self.c_phone,bd=7,relief=SUNKEN,font=(\"ariel\",15)).grid(row=0,column=3,padx=5,pady=10)\r\n\r\n cbill_label=Label(F1,text=\" Search Bill Number :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",18,\"bold\")).grid(row=0,column=4,padx=10,pady=10)\r\n cbill_text=Entry(F1,width=18,textvariable=self.search_bill,bd=7,relief=SUNKEN,font=(\"ariel\",15)).grid(row=0,column=5,padx=5,pady=10)\r\n\r\n bill_btn=Button(F1,text=\"Search\",command=self.find_bill,width=15,bd=7,font=(\"ariel\",12,\"bold\")).grid(row=0,column=6,padx=10,pady=10)\r\n\r\n #--------------------Cosmetics Frame---------------------------------\r\n F2=LabelFrame(self.root,text=\"Cosmetics Products\",bd=10,relief=GROOVE,font=(\"times new roman\",15,\"bold\"),fg=\"gold\",bg=bg_color) \r\n F2.place(x=5,y=180,width=350,height=380)\r\n\r\n\r\n bath_lbl=Label(F2,text=\"Bath Soap :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=0,column=0,padx=10,pady=10,sticky=\"w\")\r\n bath_txt=Entry(F2,width=10,textvariable=self.soap,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=0,column=1,padx=10,pady=10)\r\n\r\n face_w_lbl=Label(F2,text=\"Face Wash :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=1,column=0,padx=10,pady=10,sticky=\"w\")\r\n face_w_txt=Entry(F2,width=10,textvariable=self.face_wash,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=1,column=1,padx=10,pady=10)\r\n\r\n face_c_lbl=Label(F2,text=\"Face Cream :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=2,column=0,padx=10,pady=10,sticky=\"w\")\r\n face_c_txt=Entry(F2,width=10,textvariable=self.face_cream,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=2,column=1,padx=10,pady=10)\r\n\r\n hair_g_lbl=Label(F2,text=\"Hair Gel :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=3,column=0,padx=10,pady=10,sticky=\"w\")\r\n hair_g_txt=Entry(F2,width=10,textvariable=self.gel,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=3,column=1,padx=10,pady=10)\r\n\r\n body_lbl=Label(F2,text=\"Body Lotion :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=4,column=0,padx=10,pady=10,sticky=\"w\")\r\n body_txt=Entry(F2,width=10,textvariable=self.lotion,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=4,column=1,padx=10,pady=10)\r\n\r\n powder_lbl=Label(F2,text=\"Telcom Powder :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=5,column=0,padx=10,pady=10,sticky=\"w\")\r\n powder_txt=Entry(F2,width=10,textvariable=self.powder,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=5,column=1,padx=10,pady=10)\r\n\r\n\r\n #-----------------------Grocery Frame--------------------------\r\n F3=LabelFrame(self.root,text=\"Grocery Products\",bd=10,relief=GROOVE,font=(\"times new roman\",15,\"bold\"),fg=\"gold\",bg=bg_color) \r\n F3.place(x=360,y=180,width=335,height=380)\r\n\r\n g1_lbl=Label(F3,text=\"Rice :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=0,column=2,padx=10,pady=10,sticky=\"w\")\r\n g1_txt=Entry(F3,width=10,textvariable=self.rice,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=0,column=3,padx=10,pady=10)\r\n\r\n g2_lbl=Label(F3,text=\"Wheat :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=1,column=2,padx=10,pady=10,sticky=\"w\")\r\n g2_txt=Entry(F3,width=10,textvariable=self.wheat,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=1,column=3,padx=10,pady=10)\r\n\r\n g3_lbl=Label(F3,text=\"Wheat Flour :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=2,column=2,padx=10,pady=10,sticky=\"w\")\r\n g3_txt=Entry(F3,width=10,textvariable=self.wheat_flour,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=2,column=3,padx=10,pady=10)\r\n\r\n g4_lbl=Label(F3,text=\"Daal :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=3,column=2,padx=10,pady=10,sticky=\"w\")\r\n g4_txt=Entry(F3,width=10,textvariable=self.daal,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=3,column=3,padx=10,pady=10)\r\n\r\n g5_lbl=Label(F3,text=\"Sugar :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=4,column=2,padx=10,pady=10,sticky=\"w\")\r\n g5_txt=Entry(F3,width=10,textvariable=self.sugar,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=4,column=3,padx=10,pady=10)\r\n\r\n g6_lbl=Label(F3,text=\"Tea :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=5,column=2,padx=10,pady=10,sticky=\"w\")\r\n g6_txt=Entry(F3,width=10,textvariable=self.tea,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=5,column=3,padx=10,pady=10)\r\n\r\n\r\n\r\n\r\n #-----------------------------Drinks Frame-----------------------------\r\n F4=LabelFrame(self.root,text=\"Drinks Products\",bd=10,relief=GROOVE,font=(\"times new roman\",15,\"bold\"),fg=\"gold\",bg=bg_color) \r\n F4.place(x=700,y=180,width=335,height=380)\r\n\r\n d1_lbl=Label(F4,text=\"Maaza :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=0,column=4,padx=10,pady=10,sticky=\"w\")\r\n d1_txt=Entry(F4,width=10,textvariable=self.maaza,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=0,column=5,padx=10,pady=10)\r\n\r\n d2_lbl=Label(F4,text=\"Frooti :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=1,column=4,padx=10,pady=10,sticky=\"w\")\r\n d2_txt=Entry(F4,width=10,textvariable=self.frooti,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=1,column=5,padx=10,pady=10)\r\n\r\n d3_lbl=Label(F4,text=\"Coca-cola :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=2,column=4,padx=10,pady=10,sticky=\"w\")\r\n d3_txt=Entry(F4,width=10,textvariable=self.coca_cola,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=2,column=5,padx=10,pady=10)\r\n\r\n d4_lbl=Label(F4,text=\"Thumbs Up :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=3,column=4,padx=10,pady=10,sticky=\"w\")\r\n d4_txt=Entry(F4,width=10,textvariable=self.thumps_up,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=3,column=5,padx=10,pady=10)\r\n\r\n d5_lbl=Label(F4,text=\"Limca :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=4,column=4,padx=10,pady=10,sticky=\"w\")\r\n d5_txt=Entry(F4,width=10,textvariable=self.limca,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=4,column=5,padx=10,pady=10)\r\n\r\n d6_lbl=Label(F4,text=\"Sprite :\",font=(\"times new roman\",16,\"bold\"),bg=bg_color,fg=\"lightgreen\").grid(row=5,column=4,padx=10,pady=10,sticky=\"w\")\r\n d6_txt=Entry(F4,width=10,textvariable=self.sprite,font=(\"times new roman\",16,\"bold\"),bd=5,relief=SUNKEN).grid(row=5,column=5,padx=10,pady=10)\r\n\r\n\r\n #--------------------------------bill display----------------------------\r\n F5=Frame(self.root,bd=10,relief=GROOVE)\r\n F5.place(x=1050,y=180,width=455,height=380)\r\n bill_title=Label(F5,text=\"Bill Display\",font=\"arial 15 bold\",bd=7,relief=GROOVE).pack(fill=X)\r\n scrol_y=Scrollbar(F5,orient=VERTICAL)\r\n self.txtarea=Text(F5,yscrollcommand=scrol_y.set)\r\n scrol_y.pack(side=RIGHT,fill=Y)\r\n scrol_y.config(command=self.txtarea.yview)\r\n self.txtarea.pack(fill=BOTH,expand=1)\r\n\r\n #-------------------Button Frame----------------------------------------\r\n F6=LabelFrame(self.root,text=\"Bill Calculation Menu\",bd=10,relief=GROOVE,font=(\"times new roman\",15,\"bold\"),fg=\"gold\",bg=bg_color) \r\n F6.place(x=0,y=560,relwidth=1,height=260)\r\n \r\n m1=Label(F6,text=\"Total Cosmatic Price :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",20,\"bold\")).grid(row=0,column=0,padx=20,pady=1,sticky=\"w\")\r\n m1_txt=Entry(F6,width=18,textvariable=self.cosmetic_price,font=\"arial 10 bold\",bd=7,relief=SUNKEN).grid(row=0,column=1,padx=10,pady=10)\r\n\r\n m2=Label(F6,text=\"Total Grocery Price :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",20,\"bold\")).grid(row=1,column=0,padx=20,pady=1,sticky=\"w\")\r\n m2_txt=Entry(F6,width=18,textvariable=self.grocery_price,font=\"arial 10 bold\",bd=7,relief=SUNKEN).grid(row=1,column=1,padx=10,pady=10)\r\n\r\n m3=Label(F6,text=\"Total Drinks Price :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",20,\"bold\")).grid(row=2,column=0,padx=20,pady=1,sticky=\"w\")\r\n m3_txt=Entry(F6,width=18,textvariable=self.drinks_price,font=\"arial 10 bold\",bd=7,relief=SUNKEN).grid(row=2,column=1,padx=10,pady=10)\r\n\r\n m5=Label(F6,text=\"Total Product Price :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",22,\"bold\")).grid(row=3,column=0,padx=20,pady=1,sticky=\"w\")\r\n m5_txt=Entry(F6,width=18,textvariable=self.total_product_price,font=\"arial 10 bold\",bd=7,relief=SUNKEN).grid(row=3,column=1,padx=10,pady=10)\r\n\r\n m6=Label(F6,text=\"Total Taxes :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",24,\"bold\")).grid(row=3,column=2,padx=20,pady=1,sticky=\"w\")\r\n m6_txt=Entry(F6,width=18,textvariable=self.total_tax,font=\"arial 10 bold\",bd=7,relief=SUNKEN).grid(row=3,column=3,padx=10,pady=10)\r\n\r\n \r\n c1=Label(F6,text=\"Cosmatic Tax :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",20,\"bold\")).grid(row=0,column=2,padx=20,pady=1,sticky=\"w\")\r\n c1_txt=Entry(F6,width=18,textvariable=self.cosmetic_tax,font=\"arial 10 bold\",bd=7,relief=SUNKEN).grid(row=0,column=3,padx=10,pady=10)\r\n\r\n c2=Label(F6,text=\"Grocery Tax :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",20,\"bold\")).grid(row=1,column=2,padx=20,pady=1,sticky=\"w\")\r\n c2_txt=Entry(F6,width=18,textvariable=self.grocery_tax,font=\"arial 10 bold\",bd=7,relief=SUNKEN).grid(row=1,column=3,padx=10,pady=10)\r\n\r\n c3=Label(F6,text=\"Drinks Tax :\",bg=bg_color,fg=\"white\",font=(\"times new roman\",20,\"bold\")).grid(row=2,column=2,padx=20,pady=1,sticky=\"w\")\r\n c3_txt=Entry(F6,width=18,textvariable=self.drinks_tax,font=\"arial 10 bold\",bd=7,relief=SUNKEN).grid(row=2,column=3,padx=10,pady=10)\r\n\r\n\r\n btn_f=Frame(F6,bd=10,relief=GROOVE)\r\n btn_f.place(x=875,y=75,width=580,height=100)\r\n total_btn=Button(btn_f,text=\"Total\",command=self.total,bg=\"cadetblue\",fg=\"white\",pady=15,width=12,font=\"arial 12 bold\").grid(row=0,column=0,padx=5,pady=5)\r\n g_bill_btn=Button(btn_f,text=\"Generate Bill\",command=self.bill_area,bg=\"cadetblue\",fg=\"white\",pady=15,width=12,font=\"arial 12 bold\").grid(row=0,column=1,padx=5,pady=5)\r\n clear_btn=Button(btn_f,text=\"Clear\",command=self.clear_data,bg=\"cadetblue\",fg=\"white\",pady=15,width=12,font=\"arial 12 bold\").grid(row=0,column=2,padx=5,pady=5)\r\n exit_btn=Button(btn_f,text=\"Exit\",command=self.exit_app,bg=\"cadetblue\",fg=\"white\",pady=15,width=12,font=\"arial 12 bold\").grid(row=0,column=3,padx=5,pady=5)\r\n\r\n self.welcome_bill()\r\n\r\n\r\n def total(self):\r\n\r\n self.c_s_p=self.soap.get()*40\r\n self.c_fw_p=self.face_wash.get()*100\r\n self.c_fc_p=self.face_cream.get()*80\r\n self.c_g_p=self.gel.get()*60\r\n self.c_l_p=self.lotion.get()*200\r\n self.c_p_p=self.powder.get()*90\r\n\r\n self.total_cosmetic_price=float(\r\n (self.c_s_p)+\r\n (self.c_fw_p)+\r\n (self.c_fc_p)+\r\n (self.c_g_p)+\r\n (self.c_l_p)+\r\n (self.c_p_p)\r\n )\r\n self.cosmetic_price.set(\"Rs. \"+str(self.total_cosmetic_price))\r\n self.c_tax=round((self.total_cosmetic_price*0.18),2)\r\n self.cosmetic_tax.set(\"Rs. \"+str(self.c_tax))\r\n\r\n self.g_r_p=self.rice.get()*50\r\n self.g_w_p=self.wheat.get()*30\r\n self.g_wf_p=self.wheat_flour.get()*40\r\n self.g_d_p=self.daal.get()*100\r\n self.g_s_p=self.sugar.get()*50\r\n self.g_t_p=self.tea.get()*350\r\n\r\n self.total_grocery_price=float(\r\n (self.g_r_p)+\r\n (self.g_w_p)+\r\n (self.g_wf_p)+\r\n (self.g_d_p)+\r\n (self.g_s_p)+\r\n (self.g_t_p)\r\n )\r\n self.grocery_price.set(\"Rs. \"+str(self.total_grocery_price))\r\n self.g_tax=round((self.total_grocery_price*0.18),2)\r\n self.grocery_tax.set(\"Rs. \"+str(self.g_tax))\r\n\r\n self.d_m_p=self.maaza.get()*100\r\n self.d_f_p=self.frooti.get()*120\r\n self.d_c_p=self.coca_cola.get()*90\r\n self.d_t_p=self.thumps_up.get()*95\r\n self.d_l_p=self.limca.get()*85\r\n self.d_s_p=self.sprite.get()*105\r\n\r\n self.total_drinks_price=float(\r\n (self.d_m_p)+\r\n (self.d_f_p)+\r\n (self.d_c_p)+\r\n (self.d_t_p)+\r\n (self.d_l_p)+\r\n (self.d_s_p)\r\n )\r\n self.drinks_price.set(\"Rs. \"+str(self.total_drinks_price))\r\n self.d_tax=round((self.total_drinks_price*0.18),2)\r\n self.drinks_tax.set(\"Rs. \"+str(self.d_tax))\r\n\r\n\r\n self.product_price=float(\r\n (self.total_cosmetic_price)+\r\n (self.total_grocery_price)+\r\n (self.total_drinks_price)\r\n )\r\n self.total_product_price.set(\"Rs. \"+str(self.product_price))\r\n self.total_tax.set(\"Rs. \"+str(round((self.product_price*0.18),2)))\r\n\r\n \r\n\r\n self.total_bill_price=float(\r\n self.total_cosmetic_price+\r\n self.total_grocery_price+\r\n self.total_drinks_price+\r\n self.c_tax+\r\n self.g_tax+\r\n self.d_tax\r\n \r\n )\r\n\r\n self.total_bill_price=round((self.total_bill_price),2)\r\n\r\n\r\n def welcome_bill(self):\r\n self.txtarea.delete('1.0',END)\r\n self.txtarea.insert(END,\"\\t Welcome Daily Needs Retail Store \")\r\n self.txtarea.insert(END,f\"\\n\\n Bill Number : {self.bill_no.get()}\")\r\n self.txtarea.insert(END,f\"\\n Customer Name : {self.c_name.get()}\")\r\n self.txtarea.insert(END,f\"\\n Phone Number : {self.c_phone.get()} \")\r\n self.txtarea.insert(END,f\"\\n***************************************************\")\r\n self.txtarea.insert(END,f\"\\n Products\\t\\t\\tQTY\\t\\tPrice\")\r\n self.txtarea.insert(END,f\"\\n***************************************************\")\r\n\r\n\r\n\r\n\r\n def bill_area(self):\r\n if self.c_name.get()==\"\" or self.c_phone.get()==\"\":\r\n messagebox.showerror(\"Error\",\"Customer details are must\")\r\n \r\n elif self.cosmetic_price.get()==\"Rs. 0.0\" and self.grocery_price.get()==\"Rs. 0.0\" and self.drinks_price.get()==\"Rs. 0.0\":\r\n messagebox.showerror(\"Error\",\"No Product are Purchased\")\r\n\r\n else:\r\n\r\n self.welcome_bill()\r\n\r\n #-----------------Print Cosmetic Products in Bill--------------------------\r\n\r\n if self.soap.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Bath Soap\\t\\t\\t{self.soap.get()}\\t\\t{self.c_s_p}\")\r\n\r\n if self.face_wash.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Face Wash\\t\\t\\t{self.face_wash.get()}\\t\\t{self.c_fw_p}\")\r\n\r\n if self.face_cream.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Face Cream\\t\\t\\t{self.face_cream.get()}\\t\\t{self.c_fc_p}\")\r\n\r\n if self.gel.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Hair Gel\\t\\t\\t{self.gel.get()}\\t\\t{self.c_g_p}\")\r\n\r\n if self.lotion.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Body Lotion\\t\\t\\t{self.lotion.get()}\\t\\t{self.c_l_p}\")\r\n\r\n if self.powder.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Telcome Powder\\t\\t\\t{self.powder.get()}\\t\\t{self.c_p_p}\")\r\n\r\n #-----------------Print Grocery Products in Bill--------------------------\r\n\r\n if self.rice.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Rice\\t\\t\\t{self.rice.get()}\\t\\t{self.g_r_p}\")\r\n\r\n if self.wheat.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Wheat\\t\\t\\t{self.wheat.get()}\\t\\t{self.g_w_p}\")\r\n\r\n if self.wheat_flour.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Wheat Flour\\t\\t\\t{self.wheat_flour.get()}\\t\\t{self.g_wf_p}\")\r\n\r\n if self.daal.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Daal\\t\\t\\t{self.daal.get()}\\t\\t{self.g_d_p}\")\r\n\r\n if self.sugar.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Sugar\\t\\t\\t{self.sugar.get()}\\t\\t{self.g_s_p}\")\r\n\r\n if self.tea.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Tea\\t\\t\\t{self.tea.get()}\\t\\t{self.g_t_p}\")\r\n \r\n #-----------------Print Drinks Products in Bill--------------------------\r\n\r\n if self.maaza.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Maaza\\t\\t\\t{self.maaza.get()}\\t\\t{self.d_m_p}\")\r\n\r\n if self.frooti.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Frooti\\t\\t\\t{self.frooti.get()}\\t\\t{self.d_f_p}\")\r\n\r\n if self.coca_cola.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Coca Cola\\t\\t\\t{self.coca_cola.get()}\\t\\t{self.d_c_p}\")\r\n\r\n if self.thumps_up.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Thumbs Up\\t\\t\\t{self.thumps_up.get()}\\t\\t{self.d_t_p}\")\r\n\r\n if self.limca.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Limca\\t\\t\\t{self.limca.get()}\\t\\t{self.d_l_p}\")\r\n\r\n if self.sprite.get()!=0:\r\n self.txtarea.insert(END,f\"\\n Sprite\\t\\t\\t{self.sprite.get()}\\t\\t{self.d_s_p}\")\r\n\r\n self.txtarea.insert(END,f\"\\n---------------------------------------------------\")\r\n \r\n if self.cosmetic_tax.get()!=\"Rs. 0.0\":\r\n self.txtarea.insert(END,f\"\\n Costmetic Tax :\\t\\t\\t\\t\\t{self.cosmetic_tax.get()}\")\r\n\r\n if self.grocery_tax.get()!=\"Rs. 0.0\":\r\n self.txtarea.insert(END,f\"\\n Grocery Tax :\\t\\t\\t\\t\\t{self.grocery_tax.get()}\")\r\n \r\n if self.drinks_tax.get()!=\"Rs. 0.0\":\r\n self.txtarea.insert(END,f\"\\n Drinks Tax :\\t\\t\\t\\t\\t{self.drinks_tax.get()}\")\r\n\r\n self.txtarea.insert(END,f\"\\n Total Bill Price :\\t\\t\\t\\t\\tRs.{self.total_bill_price}\")\r\n\r\n\r\n self.txtarea.insert(END,f\"\\n---------------------------------------------------\")\r\n\r\n self.save_bill()\r\n\r\n def save_bill(self):\r\n op=messagebox.askyesno(\"Save Bill\",\"Do you want to save the Bill?\")\r\n \r\n if op>0:\r\n self.bill_data=self.txtarea.get('1.0',END)\r\n f1=open(\"bills/\"+str(self.bill_no.get())+\".txt\",\"w\")\r\n f1.write(self.bill_data)\r\n f1.close()\r\n messagebox.showinfo(\"Saved\",f\"Bill No. : {self.bill_no.get()} saved successfully\")\r\n\r\n else:\r\n return\r\n\r\n def find_bill(self):\r\n for i in os.listdir(\"bills/\"):\r\n if i.split(\".\")[0]==self.search_bill.get():\r\n f1=open(f\"bills/{i}\",\"r\")\r\n self.txtarea.delete('1.0',END)\r\n for d in f1:\r\n self.txtarea.insert(END,d)\r\n f1.close()\r\n if self.search_bill.get()==\"\" :\r\n messagebox.showerror(\"Error\",\"Enter Bill No.\")\r\n\r\n\r\n def clear_data(self):\r\n\r\n op=messagebox.askyesno(\"Clear\",\"Do you Really want to Clear all Details?\")\r\n if op>0:\r\n #------------------Cosmetics Variable-----------------------\r\n self.soap.set(0)\r\n self.face_cream.set(0)\r\n self.face_wash.set(0)\r\n self.powder.set(0)\r\n self.gel.set(0)\r\n self.lotion.set(0)\r\n \r\n #----------------------------------Grocery Variable---------------------------------\r\n self.rice.set(0)\r\n self.wheat.set(0)\r\n self.wheat_flour.set(0)\r\n self.daal.set(0)\r\n self.sugar.set(0)\r\n self.tea.set(0)\r\n\r\n #--------------------------Drinks Variables-----------------------\r\n self.maaza.set(0)\r\n self.frooti.set(0)\r\n self.coca_cola.set(0)\r\n self.thumps_up.set(0)\r\n self.limca.set(0)\r\n self.sprite.set(0)\r\n\r\n #-----------------------Total Products Variable---------------------------------------------\r\n self.cosmetic_price.set(\"\")\r\n self.grocery_price.set(\"\")\r\n self.drinks_price.set(\"\")\r\n\r\n #-----------------Tax Variables----------------------------\r\n self.cosmetic_tax.set(\"\")\r\n self.grocery_tax.set(\"\")\r\n self.drinks_tax.set(\"\") \r\n \r\n #------------------Total Prices Variable---------------------------------------\r\n self.total_product_price.set(\"\")\r\n self.total_tax.set(\"\")\r\n \r\n #---------------------------------------Customer Variable-------------------------\r\n self.c_name.set(\"\")\r\n self.c_phone.set(\"\")\r\n self.bill_no.set(\"\")\r\n x=random.randint(1000,9999)\r\n self.bill_no.set(str(x))\r\n self.search_bill=StringVar(\"\") \r\n self.welcome_bill()\r\n\r\n def exit_app(self):\r\n op=messagebox.askyesno(\"Exit\",\"Do you Really want to exit?\")\r\n if op>0:\r\n self.root.destroy() \r\n\r\nroot=Tk()\r\nobj = Bill_App(root)\r\nroot.mainloop()\r\n","sub_path":"bill.py","file_name":"bill.py","file_ext":"py","file_size_in_byte":25130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"208986656","text":"from django.shortcuts import render, redirect, reverse\nfrom django.core.mail import send_mail\nfrom main.models import UserProfile, Stock, Transaction, NewsPost, StockPurchased\n\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\n\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.conf import settings\nimport json\nimport re\nfrom django.db.models import F\nimport random\n\n\n@csrf_exempt\ndef get_stock_purchased(request):\n user_profile = UserProfile.objects.get(user=request.user)\n stocks_purchased = StockPurchased.objects.filter(owner=user_profile)\n list_stocks_purchased = []\n for stock_purchased in stocks_purchased:\n units = stock_purchased.units\n price = stock_purchased.stock.stock_price\n total = int(units) * int(price)\n stock_data = [stock_purchased.stock.stock_name, units, price, total]\n list_stocks_purchased.append(stock_data)\n response = {'stocks_purchased': list_stocks_purchased}\n return JsonResponse(response)\n\n\n@csrf_exempt\ndef get_news_post(request):\n news_list = []\n for news in NewsPost.objects.all():\n news_data = [news.headline, news.body, news.date_added]\n news_list.append(news_data)\n response = {'news_list': news_list}\n return JsonResponse(response)\n\n\ndef test(request):\n return render(request, 'main/useless.html')\n\n\ndef news(request):\n return render(request, 'main/news.html')\n \n@login_required\ndef game(request):\n return render(request, 'main/game.html')\n\n\n@login_required\ndef get_stocks_data(request, code):\n try:\n stocks = Stock.objects.filter(market_type=code)\n stocks_list = []\n for stock in stocks:\n stock_data = [stock.pk, stock.stock_name, stock.stock_price,\n stock.initial_price, stock.available_no_units, ]\n stocks_list.append(stock_data)\n data = {'stocks_list': stocks_list}\n return JsonResponse(data)\n except:\n return JsonResponse({'message': 'Error in Retrieving Stocks'})\n\n\n@login_required\ndef profile(request):\n return render(request, 'main/profile.html')\n\n\n@login_required\n@csrf_exempt\ndef buy_stock(request, pk):\n if request.method == 'POST':\n try:\n user_profile = request.user\n except:\n response_data = {'status': 'error',\n 'message': 'User Does not Exist'}\n return JsonResponse(response_data)\n try:\n pk = int(pk)\n stock_to_buy = Stock.objects.get(pk=pk)\n except:\n response_data = {'status': 'error',\n 'message': 'Invalid Stock PK'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n\n units = int(request.POST['units'])\n cost = stock_to_buy.stock_price * units\n if (user_profile.balance < cost and units < stock_to_buy.available_no_units):\n response_data = {'status': 'error',\n 'message': 'Insufficient Balance for Transaction or Insufficient No. of Stocks to Buy'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n\n try:\n user_profile.balance = F('balance') - cost\n user_profile.save()\n user_profile.refresh_from_db()\n stock_to_buy.available_no_units = F('available_no_units') - units\n stock_to_buy.save()\n stock_to_buy.refresh_from_db()\n transaction_uid = random.randint(1, 10000)\n transaction = Transaction.objects.create(\n uid=transaction_uid, owner=user_profile, stock=stock_to_buy)\n transaction.units = units\n transaction.cost = cost\n transaction.type = 'B'\n transaction.save()\n transaction.refresh_from_db()\n try:\n stock_purchased = StockPurchased.objects.create(\n owner=user_profile, stock=stock_to_buy)\n stock_purchased.units = F('units') + units\n stock_purchased.save()\n stock_purchased.refresh_from_db()\n except:\n stock_purchased = StockPurchased.objects.create(\n owner=user_profile, stock=stock_to_buy, units=units)\n stock_purchased.refresh_from_db()\n response_data = {'status': 'success',\n 'message': f'Transaction#{transaction.uid}: {user_profile.user.username} has successfully purchased {units} units of {stock_to_buy.stock_name} on {transaction.date_time}'}\n except:\n response_data = {'status': 'error',\n 'message': 'Error in Transaction'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n\n\n@csrf_exempt\n@login_required\ndef sell_stock(request, pk):\n if request.method == 'POST':\n try:\n user_profile = user=request.user\n except:\n response_data = {'status': 'error',\n 'message': 'User Does not Exist'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n try:\n pk = int(pk)\n stock = Stock.objects.get(pk=pk)\n stock_to_sell = StockPurchased.objects.get(\n stock=stock, owner=user_profile)\n except:\n response_data = {'status': 'error',\n 'message': 'Invalid Stock PK/User does not own any units of given Stock'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n\n units = int(request.POST['units'])\n cost = stock.stock_price * units\n\n if (units > stock_to_sell.units):\n response_data = {'status': 'error',\n 'message': 'Insufficient No. of Stocks to Sell'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n\n try:\n user_profile.balance = F('balance') + cost\n user_profile.save()\n user_profile.refresh_from_db()\n stock.available_no_stocks = F('available_no_stocks') + units\n stock.save()\n stock.refresh_from_db()\n if(stock_to_sell.units == 1):\n stock_to_sell.delete()\n else:\n stock_to_sell.units = F('units') - 1\n stock_to_sell.save()\n stock_to_sell.refresh_from_db()\n transaction_uid = random.randint(1, 10000)\n transaction = Transaction.objects.create(\n uid=transaction_uid, owner=user_profile, stock=stock)\n transaction.units = units\n transaction.cost = cost\n transaction.type = 'S'\n transaction.save()\n transaction.refresh_from_db()\n response_data = {'status': 'success',\n 'message': f'Transaction#{transaction.uid}: {user_profile.user.username} has successfully sold {units} units of {stock.stock_name} on {transaction.date_time}'}\n except:\n response_data = {'status': 'error',\n 'message': 'Error in Transaction'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n\n\n@login_required\ndef add_stock(request):\n if request.method == 'POST':\n stock_name = request.POST.get('stock_name')\n initial_price = request.POST.get('initial_price')\n market_type = request.POST.get('market_type')\n available_no_units = request.POST.get('available_no_units')\n try:\n stock = Stock.objects.create(stock_name=stock_name)\n stock.initial_price = initial_price\n stock.stock_price = initial_price\n stock.market_type = market_type\n stock.available_no_units = available_no_units\n stock.save()\n response_data = {'status': 'success',\n 'message': f'Added {stock.stock_name}, {stock.initial_price}, {stock.available_no_units}'}\n except:\n try:\n stock.delete()\n except:\n pass\n response_data = {'status': 'error',\n 'message': 'Error in adding Stock'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n try:\n last_five_added = Stock.objects.all().order_by('-date_added')[:5]\n except:\n last_five_added = ''\n return render(request, 'main/add_stock.html', {'last_five_added': last_five_added})\n\n\n@login_required\ndef delete_stock(request, pk):\n try:\n stock = Stock.objects.get(pk=pk)\n stock.delete()\n response_data = {'status': 'success',\n 'message': 'Deleted'}\n try:\n last_five_added = Stock.objects.all().order_by('-date_added')[:5]\n except:\n last_five_added = ''\n return render(request, 'main/add_stock.html', {'last_five_added': last_five_added})\n except:\n response_data = {'status': 'error',\n 'message': 'Error in Deleting Stock'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n\n\n@login_required\ndef add_newspost(request):\n if request.method == 'POST':\n headline = request.POST.get('headline')\n body = request.POST.get('body')\n try:\n newspost = NewsPost.objects.create(headline=headline)\n newspost.body = body\n newspost.save()\n response_data = {'status': 'success',\n 'message': f'Added {newspost.headline}'}\n except:\n try:\n newspost.delete()\n except:\n pass\n response_data = {'status': 'error',\n 'message': 'Error in adding NewsPost'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n try:\n last_five_added = NewsPost.objects.all().order_by('-date_added')[:5]\n except:\n last_five_added = ''\n return render(request, 'main/add_newspost.html', {'last_five_added': last_five_added})\n\n\n@login_required\ndef delete_newspost(request, pk):\n try:\n newspost = NewsPost.objects.get(pk=pk)\n newspost.delete()\n response_data = {'status': 'success',\n 'message': 'Deleted'}\n try:\n last_five_added = NewsPost.objects.all().order_by(\n '-date_added')[:5]\n except:\n last_five_added = ''\n return render(request, 'main/add_newspost.html', {'last_five_added': last_five_added})\n except:\n response_data = {'status': 'error',\n 'message': 'Error in Deleting NewsPost'}\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"488902957","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\n\ndef get_all_files(path, parent = '.'):\n fullpath = os.path.join(parent, path)\n if not os.path.exists(fullpath):\n raise Exception(\"path not exists: \" + path)\n entries = os.listdir(fullpath)\n files = []\n for f in entries:\n if os.path.isfile(os.path.join(fullpath, f)):\n files.append(os.path.join(fullpath,f))\n elif os.path.isdir(os.path.join(fullpath, f)):\n files.extend(get_all_files(f, fullpath))\n return files\n\ndef is_program(filename):\n return get_program_ext(filename) != None\n\ndef get_program_ext(filename):\n program_exts = [{\"ext\": \".py\", \"oneline_cmt\": \"#\", \"multiline_cmt\": [\"'''\", \"'''\"]}]\n for ext in program_exts:\n if filename.endswith(ext[\"ext\"]):\n return ext\n return None\n\ndef main():\n programs = filter(is_program, get_all_files(\"../\"))\n result = {}\n for program in programs:\n data = {\"newline\": 0, \"comments\": 0, \"line\": 0}\n with open(program) as f:\n ext = get_program_ext(program)\n incomments = False\n for line in f.readlines():\n line = line.strip()\n data[\"line\"] += 1\n data[\"ext\"] = ext[\"ext\"]\n if len(line) == 0 and not incomments:\n data[\"newline\"] += 1\n elif line.startswith(ext[\"oneline_cmt\"]) and not incomments:\n data[\"comments\"] += 1 \n elif line.startswith(ext[\"multiline_cmt\"][0]) and not incomments:\n incomments = True\n data[\"comments\"] += 1\n elif line.endswith(ext[\"multiline_cmt\"][1]) and incomments:\n data[\"comments\"] += 1\n incomments = False;\n elif incomments:\n data[\"comments\"] += 1\n result[program] = data\n\n n = c = l = 0\n for program, data in result.items():\n n += data[\"newline\"]\n c += data[\"comments\"]\n l += data[\"line\"]\n print(\"line: {}\\tnewline: {}\\tcomments: {}\".format(l, n, c))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"task0007/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"226942776","text":"\n\n#calss header\nclass _TOWNSHIP():\n\tdef __init__(self,): \n\t\tself.name = \"TOWNSHIP\"\n\t\tself.definitions = [u'a South African town where only black people lived during apartheid: ', u'in the US and Canada, a unit of local government consisting of a town and the area surrounding it: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_township.py","file_name":"_township.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"440632624","text":"import pathlib\nimport pandas as pd\nimport plotly\nimport plotly.express as px\nfrom operator import itemgetter\nfrom nfl_site.libraries import csv_to_dict, mean\n\n\n# create Dictionary to quickly look up player names\ndef create_id_name_lookup():\n pid_list = player_dict['playerId']\n\n lookup_dict = {}\n\n for i in range(len(pid_list)):\n lookup_dict[pid_list[i]] = player_dict['nameFull'][i]\n\n return lookup_dict\n\n\n# returns a list of ids associated with a name in the players.csv\ndef get_player_id(firstname, lastname):\n # get columns of values\n list1 = player_dict['nameFirst']\n list2 = player_dict['nameLast']\n\n id_list = [] # list to hold player ids\n\n fullname = firstname + ' ' + lastname\n\n # if column length is not the same there is a problem with data\n if len(list1) == len(list1):\n # iterate through first and last name columns\n for i in range(len(list2)):\n list_name = list1[i] + ' ' + list2[i]\n # if name is found add id to list\n if fullname == list_name:\n player_id = player_dict['playerId'][i]\n id_list.append(player_id)\n\n # return list of ids\n return id_list\n else:\n print('Error: Mismatched column length')\n return None\n\n\n# returns count of total receiving yards of a given player id in the receiver.csv\ndef get_receiving_yards(player_id):\n pid_list = receiver_dict['playerId']\n total_rec_yards = 0\n\n for i in range(len(pid_list)):\n if pid_list[i] == player_id:\n if receiver_dict['rec'][i] == '1' and receiver_dict['recPassInt'][i] == '0' \\\n and receiver_dict['recNull'][i] == '0':\n cell_val = receiver_dict['recYards'][i] # get value contained in cell of recYards column\n # check to make sure cell does not contain the None data type to prevent addition errors\n if cell_val:\n total_rec_yards += int(cell_val)\n\n return total_rec_yards\n\n\n# gets receiving yard for players of a given name\n# returns a dictionary of key(player id, player name)\n# and value (total rec yards, avg rec yards per play, total rec plays)\ndef get_rec_yards_dict(firstname, lastname):\n player_ids = get_player_id(firstname, lastname) # this is a list of player ids that match name\n full_name = firstname + ' ' + lastname\n if not player_ids:\n # if list returned by get_player_id is empty name does not exist in dataset\n # return empty dictionary\n return {}\n else:\n temp_dict = {}\n # if list returned by get_player_id is not empty get total rec yards for each id\n for pid in player_ids:\n total_yards = get_receiving_yards(pid)\n\n # create key to get rec plays from prp dictionary\n # tup_key = (pid, firstname + ' ' + lastname)\n\n if pid in rec_plays_count_dict.keys():\n\n temp_dict[pid] = [full_name, str(total_yards),\n str(float(total_yards) / float(rec_plays_count_dict[pid])),\n rec_plays_count_dict[pid]]\n else:\n temp_dict[pid] = [full_name, str(total_yards), '0.0', 0]\n\n return temp_dict\n\n\n# gets the top n players by receiving dictionary\n# returns a dictionary with key(player id, player name)\n# and value (total rec yards, avg rec yards per play, total rec plays)\ndef top_n_rec_yards(num):\n\n pid_list = receiver_dict['playerId']\n total_rec_dict = {}\n total_avg_rec_dict = {}\n\n for i in range(len(pid_list)):\n if receiver_dict['rec'][i] == '1' and receiver_dict['recPassInt'][i] == '0' \\\n and receiver_dict['recNull'][i] == '0':\n cell_val = receiver_dict['recYards'][i] # get value contained in cell of recYards column\n # check to make sure cell does not contain the None data type to prevent addition errors\n if cell_val:\n # create key for dictionary which is a tuple containing player id and full name\n tup_key = (pid_list[i], player_id_name_lookup[pid_list[i]])\n # if tuple key containing player id and full name does not exisis in dictionary create a new\n # entry else add to the total rec yards\n if tup_key not in total_rec_dict:\n total_rec_dict[tup_key] = int(cell_val)\n else:\n total_rec_dict[tup_key] += int(cell_val)\n\n # sort dictionary by total rec yards in descending order\n # Note: this returns a list not a dictionary\n rec_yards_desc = sorted(total_rec_dict.items(), key=itemgetter(1), reverse=True)\n # get the top n records from list and cast into a dictionary\n n_records = dict(rec_yards_desc[:num])\n\n # create dictionary containing keys (player id, player name)\n # and values (receiving yards, avg receiving yards per play, and total plays)\n for key, val in n_records.items():\n\n pid = key[0]\n\n if pid in rec_plays_count_dict.keys():\n total_avg_rec_dict[key] = (val, float(val) / float(rec_plays_count_dict[pid]), rec_plays_count_dict[pid])\n else:\n total_avg_rec_dict[key] = (val, 0.0, 0.0)\n\n return total_avg_rec_dict\n\n\n# get total receiving plays for players in receiver.csv\n# returns a dictionary of key(player id, player name) and value total receiving plays\ndef player_rec_plays():\n pid_list = receiver_dict['playerId']\n rec_plays_dict = {}\n\n for i in range(len(pid_list)):\n\n if pid_list[i] in player_id_name_lookup.keys():\n dict_key = pid_list[i]\n # if tuple key containing player id and full name does not exist in dictionary create a new\n # entry else add to the rec plays\n if dict_key not in rec_plays_dict:\n rec_plays_dict[dict_key] = 1\n else:\n rec_plays_dict[dict_key] += 1\n\n return rec_plays_dict\n\n\n# returns plotly div object given dictionary styled in same manner as out put of receiving functions\ndef avg_rec_yard_scatter(data_dict):\n df_dict = {'player_id': [], 'player_name': [], 'rec_plays': [], 'rec_yards_avg': []}\n\n # convert dictionary into a dictionary that is formatted for better conversion into pandas data frame\n for key, val in data_dict.items():\n df_dict['player_id'].append(key[0])\n df_dict['player_name'].append(key[1])\n df_dict['rec_plays'].append(val[2])\n df_dict['rec_yards_avg'].append(val[1])\n\n data_df = pd.DataFrame.from_dict(df_dict)\n\n # mean function is function created by Team member Ford.\n # DOES NOT USE PANDAS BUILT IN FUNCTION!!!\n df_mean = mean(data_df, 'rec_yards_avg')\n\n # Create and return plotly div object\n fig = px.scatter(data_df, x='rec_yards_avg', y='rec_plays', hover_name='player_name',\n labels={\n 'rec_yards_avg': 'Average Receiving Yards Per Play (ARYPP)',\n 'rec_plays': 'Total Receiving Plays'\n },\n title='Total Receiving Plays vs Average Receiving Yards Per Play (ARYPP)')\n fig.add_vline(df_mean, line_dash='dash', annotation_text=\"Overall ARYPP: \" + str(df_mean),\n annotation_position=\"top right\", line_color='green')\n graph_div = plotly.offline.plot(fig, output_type=\"div\")\n\n return graph_div\n\n\n# add a receiving play to the receiver_dict data store\ndef add_receiver_data(player_id, position, rec_yards):\n\n global rec_plays_count_dict\n\n data_dict = {'receiverId': '99999999', 'playId': '99999999', 'teamId': '99999999',\n 'playerId': player_id, 'recPosition': position, 'recYards': rec_yards,\n 'rec': '1', 'recYac': '0', 'rec1down': '0', 'recFumble': '0',\n 'recPassDef': '0', 'recPassInt': '0', 'recEnd': '0', 'recNull': '0'}\n\n # inserting data\n for key in receiver_dict.keys():\n receiver_dict[key].append(data_dict[key])\n\n # increment the receiving plays count of the player who had a receiving play record added\n # of player not in count dictionary add them\n if player_id in rec_plays_count_dict:\n rec_plays_count_dict[player_id] += 1\n else:\n rec_plays_count_dict[player_id] = 1\n\n\n# add a receiving play to the receiver_dict data store, checks for player existence\n# player exists returns true, if player dose not exist returns false\ndef add_existing_receiver_data(player_id, position, rec_yards):\n\n if player_id in player_dict['playerId']:\n\n add_receiver_data(player_id, position, rec_yards)\n\n return True\n\n return False\n\n\n# returns the max player id value in data set\ndef get_max_player_id():\n\n pid_list_string = player_dict['playerId']\n\n # convert player id's from strings to ints\n pid_list = [int(i) for i in pid_list_string]\n\n max_val = max(pid_list) # get max id value\n\n return max_val\n\n\n# add a new player and return their newly generated player id\ndef add_player(firstname, lastname, position):\n\n global player_id_name_lookup\n\n new_pid = str(get_max_player_id() + 1) # get a new player id for new player\n full_name = firstname + ' ' + lastname\n\n data_dict = {'playerId': new_pid, 'nameFirst': firstname, 'nameLast': lastname,\n 'nameFull': full_name, 'position': position, 'collegeId': '555555',\n 'nflId': '555555', 'combineId': '555555', 'college': 'UC', 'heightInches': '74',\n 'weight': '246', 'dob': '2020-14-11', 'ageAtDraft': '20', 'playerProfileUrl': 'https://www.nfl.com/',\n 'homeCity': 'Earth', 'homeState': 'Earth', 'homeCountry': 'Earth', 'highSchool': 'HS',\n 'hsCity': 'Earth', 'hsState': 'Earth', 'hsCountry': 'Earth'}\n\n # inserting new player data\n for key in player_dict.keys():\n player_dict[key].append(data_dict[key])\n\n # add new player to the id name look up dictionary\n player_id_name_lookup[new_pid] = full_name\n\n return new_pid\n\n\n# function returns list of all indices a value is found at in a list\ndef find_index(value, val_list):\n index_list = []\n\n for i, j in enumerate(val_list):\n if j == value:\n index_list.append(i)\n\n return index_list\n\n\n# remove player from players.csv data\ndef remove_from_player_csv(index_list):\n\n # delete all occurrences of player in players.csv data\n for i in index_list:\n for key in player_dict.keys():\n player_dict[key].pop(i)\n\n\n# remove player from receiver.csv data\ndef remove_from_receiver_csv(index_list):\n # sort the list to delete indices from largest to smallest\n index_list = sorted(index_list, reverse=True)\n\n # delete all occurrences of player in receiver.csv data\n for i in index_list:\n for key in receiver_dict.keys():\n receiver_dict[key].pop(i)\n\n\n# function deletes player form data store, returns tuple with success boolean and name of deleted player\ndef delete_player(player_id):\n global player_id_name_lookup\n global rec_plays_count_dict\n\n name_deleted = ''\n\n player_csv_pd_list = player_dict['playerId'] # list of player ids in player.csv\n receiver_csv_pid_list = receiver_dict['playerId'] # list of player ids in receiver.csv\n\n if player_id not in player_csv_pd_list:\n # if player does not exist there is nothing to delete\n return False, name_deleted\n else:\n\n # get indices of all player occurrences in the players.csv and receiver.csv data\n player_index_list = find_index(player_id, player_csv_pd_list)\n receiver_index_list = find_index(player_id, receiver_csv_pid_list)\n\n # remove player from players.csv and receiver.csv data\n remove_from_player_csv(player_index_list)\n remove_from_receiver_csv(receiver_index_list)\n\n # delete player from id name look up table and receiving plays count dictionary\n if player_id in player_id_name_lookup.keys():\n name_deleted = player_id_name_lookup.pop(player_id)\n\n if player_id in rec_plays_count_dict.keys():\n rec_plays_count_dict.pop(player_id)\n\n return True, name_deleted\n\n\n# dictionaries that need to be loaded prior to running above functions\n# these should remain at the end of the file\nif pathlib.Path('static/archive/').exists():\n\n player_dict = csv_to_dict(\"static/archive/players.csv\")\n receiver_dict = csv_to_dict(\"static/archive/receiver.csv\")\n player_id_name_lookup = create_id_name_lookup() # dictionary that can get player name given id\n rec_plays_count_dict = player_rec_plays() # get dictionary containing players and their total receiving plays\n","sub_path":"nfl_site/receiving/nfldata.py","file_name":"nfldata.py","file_ext":"py","file_size_in_byte":12638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"593871563","text":"from .. import config\n\n\nclass IDEncoder(object):\n\n def __init__(self):\n if not config.instance.security_encoding_alphabet:\n config.instance.load_configuration()\n self._alphabet = config.instance.security_encoding_alphabet\n self._block_size = config.instance.security_encoding_block_size\n self._min_length = config.instance.security_encoding_min_length\n if len(set(self._alphabet)) < 2:\n raise AttributeError('Alphabet must contain at least 2 chars.')\n self.alphabet = self._alphabet\n self.block_size = self._block_size\n self.mask = (1 << self._block_size) - 1\n self.mapping = list(range(self._block_size))\n\n def encode(self, n, min_length=None):\n n += 1 # handle `0` as input\n min_length = min_length if min_length else self._min_length\n return self.enbase(self.encode_num(n), min_length)\n\n def decode(self, n):\n decoded_id = self.decode_num(self.debase(n))\n return decoded_id - 1\n\n def encode_num(self, n):\n return (n & ~self.mask) | self._encode_num(n & self.mask)\n\n def _encode_num(self, n):\n result = 0\n for i, b in enumerate(reversed(self.mapping)):\n if n & (1 << i):\n result |= (1 << b)\n return result\n\n def decode_num(self, n):\n return (n & ~self.mask) | self._decode_num(n & self.mask)\n\n def _decode_num(self, n):\n result = 0\n for i, b in enumerate(reversed(self.mapping)):\n if n & (1 << b):\n result |= (1 << i)\n return result\n\n def enbase(self, x, min_length=None):\n min_length = min_length if min_length else self._min_length\n result = self._enbase(x)\n padding = self.alphabet[0] * (min_length - len(result))\n return '%s%s' % (padding, result)\n\n def _enbase(self, x):\n n = len(self.alphabet)\n if x < n:\n return self.alphabet[x]\n return self._enbase(int(x / n)) + self.alphabet[int(x % n)]\n\n def debase(self, x):\n n = len(self.alphabet)\n result = 0\n for i, c in enumerate(reversed(x)):\n result += self.alphabet.index(c) * (n ** i)\n return result\n\n\nid_encoder = None\n\n\ndef get_encoder():\n global id_encoder\n if not id_encoder:\n id_encoder = IDEncoder()\n return id_encoder\n","sub_path":"rest-service/manager_rest/storage/idencoder.py","file_name":"idencoder.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"548953062","text":"# coding=utf-8\n# Copyright 2018-2020 EVA\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Iterator, Dict\n\nimport pandas as pd\n\nfrom src.catalog.models.df_metadata import DataFrameMetadata\nfrom src.models.storage.batch import FrameBatch\n\n\nclass AbstractVideoLoader(metaclass=ABCMeta):\n \"\"\"\n Abstract class for defining video loader. All other video loaders use this\n abstract class. Video loader are expected fetch the videos from storage\n and return the frames in an iterative manner.\n\n Attributes:\n video_metadata (DataFrameMetadata): Object containing metadata of video\n batch_size (int, optional): No. of frames to fetch in batch from video\n skip_frames (int, optional): Number of frames to be skipped\n while fetching the video\n offset (int, optional): Start frame location in video\n limit (int, optional): Number of frames needed from the video\n curr_shard (int, optional): Shard number to load from if sharded\n total_shards (int, optional): Specify total number of shards if\n applicable\n \"\"\"\n\n def __init__(self, video_metadata: DataFrameMetadata, batch_size=1,\n skip_frames=0, offset=None, limit=None, curr_shard=0,\n total_shards=0):\n self.video_metadata = video_metadata\n self.batch_size = batch_size\n self.skip_frames = skip_frames\n self.offset = offset\n self.limit = limit\n self.curr_shard = curr_shard\n self.total_shards = total_shards\n self.identifier_column = video_metadata.identifier_column if video_metadata.identifier_column else 'id'\n\n def load(self) -> Iterator[FrameBatch]:\n \"\"\"\n This is a generator for loading the frames of a video.\n Uses the video metadata and other class arguments\n\n Yields:\n :obj: `eva.models.FrameBatch`: An object containing a batch of frames\n and record specific metadata\n \"\"\"\n\n frames = []\n for record in self._load_frames():\n if self.skip_frames > 0 and record.get(self.identifier_column, 0) % self.skip_frames != 0:\n continue\n if self.limit and record.get(self.identifier_column, 0) >= self.limit:\n return FrameBatch(pd.DataFrame(frames))\n frames.append(record)\n if len(frames) % self.batch_size == 0:\n yield FrameBatch(pd.DataFrame(frames))\n frames = []\n if frames:\n return FrameBatch(pd.DataFrame(frames))\n\n @abstractmethod\n def _load_frames(self) -> Iterator[Dict]:\n \"\"\"\n Loads video frames from storage and returns the Frame type.\n\n Yields:\n Frame: A frame object of the video, used for processing.\n \"\"\"\n pass\n","sub_path":"src/loaders/abstract_loader.py","file_name":"abstract_loader.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"61247113","text":"# Copyright 2017 SUSE Linux Gmbh\n# Copyright 2017 Huawei\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport copy\n\nfrom oslo_db import exception as db_exception\nimport sqlalchemy\n\nfrom keystone.common import driver_hints\nfrom keystone.common import sql\nfrom keystone import exception\nfrom keystone.i18n import _\nfrom keystone.limit.backends import base\n\n\nclass RegisteredLimitModel(sql.ModelBase, sql.ModelDictMixin):\n __tablename__ = 'registered_limit'\n attributes = [\n 'id',\n 'service_id',\n 'region_id',\n 'resource_name',\n 'default_limit',\n 'description'\n ]\n\n id = sql.Column(sql.String(length=64), primary_key=True)\n service_id = sql.Column(sql.String(255),\n sql.ForeignKey('service.id'))\n region_id = sql.Column(sql.String(64),\n sql.ForeignKey('region.id'), nullable=True)\n resource_name = sql.Column(sql.String(255))\n default_limit = sql.Column(sql.Integer, nullable=False)\n description = sql.Column(sql.Text())\n\n __table_args__ = (\n sqlalchemy.UniqueConstraint('service_id',\n 'region_id',\n 'resource_name'),)\n\n\nclass LimitModel(sql.ModelBase, sql.ModelDictMixin):\n __tablename__ = 'limit'\n attributes = [\n 'id',\n 'project_id',\n 'service_id',\n 'region_id',\n 'resource_name',\n 'resource_limit',\n 'description'\n ]\n\n id = sql.Column(sql.String(length=64), primary_key=True)\n project_id = sql.Column(sql.String(64),\n sql.ForeignKey('project.id'))\n service_id = sql.Column(sql.String(255))\n region_id = sql.Column(sql.String(64), nullable=True)\n resource_name = sql.Column(sql.String(255))\n resource_limit = sql.Column(sql.Integer, nullable=False)\n description = sql.Column(sql.Text())\n\n __table_args__ = (\n sqlalchemy.ForeignKeyConstraint(['service_id',\n 'region_id',\n 'resource_name'],\n ['registered_limit.service_id',\n 'registered_limit.region_id',\n 'registered_limit.resource_name']),\n sqlalchemy.UniqueConstraint('project_id',\n 'service_id',\n 'region_id',\n 'resource_name'),)\n\n\nclass UnifiedLimit(base.UnifiedLimitDriverBase):\n\n def _check_unified_limit_without_region(self, unified_limit,\n is_registered_limit=True):\n hints = driver_hints.Hints()\n hints.add_filter('service_id', unified_limit['service_id'])\n hints.add_filter('resource_name', unified_limit['resource_name'])\n hints.add_filter('region_id', None)\n if not is_registered_limit:\n # For limit, we should ensure:\n # 1. there is no duplicate entry.\n # 2. there is a registered limit reference.\n reference_hints = copy.deepcopy(hints)\n hints.add_filter('project_id', unified_limit['project_id'])\n with sql.session_for_read() as session:\n unified_limits = session.query(LimitModel)\n unified_limits = sql.filter_limit_query(LimitModel,\n unified_limits,\n hints)\n with sql.session_for_read() as session:\n registered_limits = session.query(RegisteredLimitModel)\n registered_limits = sql.filter_limit_query(\n RegisteredLimitModel, registered_limits, reference_hints)\n if not registered_limits.all():\n raise exception.NoLimitReference\n else:\n # For registered limit, we should just ensure that there is no\n # duplicate entry.\n with sql.session_for_read() as session:\n unified_limits = session.query(RegisteredLimitModel)\n unified_limits = sql.filter_limit_query(RegisteredLimitModel,\n unified_limits,\n hints)\n if unified_limits.all():\n msg = _('Duplicate entry')\n limit_type = 'registered_limit' if is_registered_limit else 'limit'\n raise exception.Conflict(type=limit_type, details=msg)\n\n def _check_referenced_limit_without_region(self, registered_limit):\n hints = driver_hints.Hints()\n hints.add_filter('service_id', registered_limit.service_id)\n hints.add_filter('resource_name', registered_limit.resource_name)\n hints.add_filter('region_id', None)\n with sql.session_for_read() as session:\n limits = session.query(LimitModel)\n limits = sql.filter_limit_query(LimitModel,\n limits,\n hints)\n if limits.all():\n raise exception.RegisteredLimitError(id=registered_limit.id)\n\n @sql.handle_conflicts(conflict_type='registered_limit')\n def create_registered_limits(self, registered_limits):\n with sql.session_for_write() as session:\n new_registered_limits = []\n for registered_limit in registered_limits:\n if registered_limit.get('region_id') is None:\n self._check_unified_limit_without_region(registered_limit)\n ref = RegisteredLimitModel.from_dict(registered_limit)\n session.add(ref)\n new_registered_limits.append(ref.to_dict())\n return new_registered_limits\n\n @sql.handle_conflicts(conflict_type='registered_limit')\n def update_registered_limit(self, registered_limit_id, registered_limit):\n try:\n with sql.session_for_write() as session:\n ref = self._get_registered_limit(session, registered_limit_id)\n if not ref.region_id:\n self._check_referenced_limit_without_region(ref)\n old_dict = ref.to_dict()\n old_dict.update(registered_limit)\n new_registered_limit = RegisteredLimitModel.from_dict(\n old_dict)\n for attr in registered_limit:\n if attr != 'id':\n setattr(ref, attr, getattr(new_registered_limit,\n attr))\n return ref.to_dict()\n except db_exception.DBReferenceError:\n raise exception.RegisteredLimitError(id=registered_limit_id)\n\n @driver_hints.truncated\n def list_registered_limits(self, hints):\n with sql.session_for_read() as session:\n registered_limits = session.query(RegisteredLimitModel)\n registered_limits = sql.filter_limit_query(RegisteredLimitModel,\n registered_limits,\n hints)\n return [s.to_dict() for s in registered_limits]\n\n def _get_registered_limit(self, session, registered_limit_id):\n ref = session.query(RegisteredLimitModel).get(registered_limit_id)\n if ref is None:\n raise exception.RegisteredLimitNotFound(id=registered_limit_id)\n return ref\n\n def get_registered_limit(self, registered_limit_id):\n with sql.session_for_read() as session:\n return self._get_registered_limit(\n session, registered_limit_id).to_dict()\n\n def delete_registered_limit(self, registered_limit_id):\n try:\n with sql.session_for_write() as session:\n ref = self._get_registered_limit(session,\n registered_limit_id)\n if not ref.region_id:\n self._check_referenced_limit_without_region(ref)\n session.delete(ref)\n except db_exception.DBReferenceError:\n raise exception.RegisteredLimitError(id=registered_limit_id)\n\n @sql.handle_conflicts(conflict_type='limit')\n def create_limits(self, limits):\n try:\n with sql.session_for_write() as session:\n new_limits = []\n for limit in limits:\n if limit.get('region_id') is None:\n self._check_unified_limit_without_region(\n limit, is_registered_limit=False)\n ref = LimitModel.from_dict(limit)\n session.add(ref)\n new_limits.append(ref.to_dict())\n return new_limits\n except db_exception.DBReferenceError:\n raise exception.NoLimitReference()\n\n @sql.handle_conflicts(conflict_type='limit')\n def update_limit(self, limit_id, limit):\n with sql.session_for_write() as session:\n ref = self._get_limit(session, limit_id)\n old_dict = ref.to_dict()\n old_dict.update(limit)\n new_limit = LimitModel.from_dict(old_dict)\n ref.resource_limit = new_limit.resource_limit\n ref.description = new_limit.description\n return ref.to_dict()\n\n @driver_hints.truncated\n def list_limits(self, hints):\n with sql.session_for_read() as session:\n limits = session.query(LimitModel)\n limits = sql.filter_limit_query(LimitModel,\n limits,\n hints)\n return [s.to_dict() for s in limits]\n\n def _get_limit(self, session, limit_id):\n ref = session.query(LimitModel).get(limit_id)\n if ref is None:\n raise exception.LimitNotFound(id=limit_id)\n return ref\n\n def get_limit(self, limit_id):\n with sql.session_for_read() as session:\n return self._get_limit(session,\n limit_id).to_dict()\n\n def delete_limit(self, limit_id):\n with sql.session_for_write() as session:\n ref = self._get_limit(session,\n limit_id)\n session.delete(ref)\n","sub_path":"keystone/limit/backends/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":10828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"224608724","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\" \n\tSocial-Distancing: Code for estimating the distance between people and show warning if they are standing too close to each other.\n \n\tIIT : Istituto italiano di tecnologia\n\t\n Pattern Analysis and Computer Vision (PAVIS) research line\n\t\n Description: Social-Distancing is an open-source project for automatically estimating interpersonal distance from uncalibrated RGB\n\tcameras. The software can be freely used for any non-commercial applications to assess compliance with safe distances. Given a frame\n\tcaptured from a scene, the algorithm first detects visible people in the scene using an off-the-shelf body pose detector and \n\testimates the height of the people through measuring the distance from their body joints. In the second step, the algorithm estimates\n\tan area of one meter around all the detected people. This distance is roughly estimated proportional to a typical human body height\n\tof 160 cm and can be used to draw a circle centered in human position in the scene. In the third step, the Homography of the scene\n\tis estimated given two parameters which essentially map the rectangular bird’s view model for the scene to the trapezoidal perspective\n\tview of the scene. These two parameters need to be manually tuned to estimate best the scene perspective. According to the Homography\n\tmatrix, the safe circular distance for each person is converted to ellipsoids in perspective view. The people are considered to be\n\tstaying in safe distance from each other if their ellipsoids do not collide. Conversely, if ellipsoids of two people collide, those\n\tpeople are considered as being in risk and their ellipsoids will be shown in red.\n\t\n Usage Example: \n\t\t$ python3 social-distancing.py --image_in [path to the input image] --image_out [path to the result image] --horizontal_ratio 0.7 --vertical_ratio 0.7\n $ python3 social-distancing.py --stream_in [path to the input sequence] --stream_out [path to the result sequence] --horizontal_ratio 0.7 --vertical_ratio 0.7\n\t\n $ python3 social-distancing.py -h to get others parameters infos \n \n Tested on ShanghaiTech [1] dataset.\n\t[1] Zhang, Yingying, et al. \"Single-image crowd counting via multi-column convolutional neural network.\" Proceedings of the IEEE conference on computer vision and pattern recognition. 2016.\n\t\n Disclaimer:\n\tThe information and content provided by this application is for information purposes only. \n\tYou hereby agree that you shall not make any health or medical related decision based in whole \n\tor in part on anything contained within the application without consulting your personal doctor.\n\tThe software is provided \"as is\", without warranty of any kind, express or implied, \n\tincluding but not limited to the warranties of merchantability, \n\tfitness for a particular purpose and noninfringement. In no event shall the authors, \n\tPAVIS or IIT be liable for any claim, damages or other liability, whether in an action of contract, \n\ttort or otherwise, arising from, out of or in connection with the software \n\tor the use or other dealings in the software.\n\t\n LICENSE:\n\tThis project is licensed under the terms of the MIT license.\n\tThis project incorporates material from the projects listed below (collectively, \"Third Party Code\"). \n\tThis Third Party Code is licensed to you under their original license terms. \n\tWe reserves all other rights not expressly granted, whether by implication, estoppel or otherwise.\n\tThe software can be freely used for any non-commercial applications and it is useful\n\tfor maintaining the safe social distance among people in pandemics. The code is open and can be \n\timproved with your support, please contact us at socialdistancig@iit.it if you will to help us.\n\"\"\"\n\nimport numpy as np\nimport cv2\nimport math\nimport itertools\nimport sys\nimport os\nimport argparse\nimport time\nimport json\nimport queue\n\nfrom turbojpeg import TurboJPEG, TJPF_GRAY, TJSAMP_GRAY, TJFLAG_PROGRESSIVE\n\nfrom social_distance_monitor.src.stream_server import StreamServer\nfrom social_distance_monitor.src.response_server import ResponseServer\n\nclass SocialDistancing:\n colors = [(0, 255, 0), (0, 0, 255)]\n\n nd_color = [(153, 0, 51), (153, 0, 0),\n (153, 51, 0), (153, 102, 0),\n (153, 153, 0), (102, 153, 0),\n (51, 153, 0), (0, 153, 0),\n (0, 102, 153), (0, 153, 51),\n (0, 153, 102), (0, 153, 153),\n (0, 102, 153), (0, 51, 153),\n (0, 0, 153), (153, 0, 102),\n (102, 0, 153), (153, 0, 153),\n (102, 0, 153), (0, 0, 153),\n (0, 0, 153), (0, 0, 153),\n (0, 153, 153), (0, 153, 153),\n (0, 153, 153)\n ]\n\n connections = [(0, 16), (0, 15), (16, 18), (15, 17),\n (0, 1), (1, 2), (2, 3), (3, 4),\n (1, 5), (5, 6), (6, 7), (1, 8),\n (8, 9), (9, 10), (10, 11),\n (8, 12), (12, 13), (13, 14),\n (11, 24), (11, 22), (22, 23),\n (14, 21), (14, 19), (19, 20)]\n\n '''\n Initialize Object\n '''\n\n def __init__(self, args, op):\n # Ratio params\n horizontal_ratio = float(args.horizontal_ratio)\n vertical_ratio = float(args.vertical_ratio)\n\n # Open video capture\n self.cap = cv2.VideoCapture(args.stream_in)\n\n if not self.cap.isOpened():\n print(\"Error: Opening video stream or file {0}\".format(\n args.stream_in))\n sys.exit(-1)\n\n # Get input size\n width = int(self.cap.get(3))\n height = int(self.cap.get(4))\n\n # Get image size\n im_size = (width, height)\n\n # Compute Homograpy\n self.homography_matrix = self.compute_homography(\n horizontal_ratio, vertical_ratio, im_size)\n\n self.background_masked = False\n # Open image backgrouns, if it is necessary\n if args.masked == \"enabled\":\n # Set masked flag\n self.background_masked = True\n\n # Load static background\n self.background_image = cv2.imread(args.background_in)\n\n # Close, if no background, but required\n if self.background_image is None:\n print(\"Error: Unable to load background image (flag enabled)\")\n sys.exit(-1)\n\n # Custom Params (refer to include/openpose/flags.hpp for more parameters)\n params = dict()\n\n # Openpose params\n\n # Model path\n params[\"model_folder\"] = args.openpose_folder\n\n # Face disabled\n params[\"face\"] = False\n\n # Hand disabled\n params[\"hand\"] = False\n\n # Net Resolution\n params[\"net_resolution\"] = args.net_size\n\n # Gpu number\n params[\"num_gpu\"] = 1 # Set GPU number\n\n # Gpu Id\n # Set GPU start id (not considering previous)\n params[\"num_gpu_start\"] = 0\n\n # Starting OpenPose\n self.opWrapper = op.WrapperPython()\n self.opWrapper.configure(params)\n self.opWrapper.start()\n\n # Process Image\n self.datum = op.Datum()\n\n # Json server\n self.dt_vector = {}\n\n # Client list\n self.stream_list = []\n\n # Initialize video server\n self.video_server = StreamServer(\n int(args.video_port), self.stream_list, \"image/jpeg\")\n self.video_server.activate()\n\n # Initialize json server\n self.js_server = ResponseServer(\n int(args.js_port), \"application/json\")\n self.js_server.activate()\n\n # turbo jpeg initialization\n self.jpeg = TurboJPEG()\n\n # Calibrate heigh value\n self.calibrate = float(args.calibration)\n\n # Actually unused\n self.ellipse_angle = 0\n\n # Body confidence threshold\n self.body_th = float(args.body_threshold)\n\n # Show confidence \n self.show_confidence = True\n\n '''\n Draw Skelethon\n '''\n\n def draw_skeleton(self, frame, keypoints, colour):\n\n for keypoint_id1, keypoint_id2 in self.connections:\n x1, y1 = keypoints[keypoint_id1]\n x2, y2 = keypoints[keypoint_id2]\n\n if 0 in (x1, y1, x2, y2):\n continue\n\n pt1 = int(round(x1)), int(round(y1))\n pt2 = int(round(x2)), int(round(y2))\n\n cv2.circle(frame, center=pt1, radius=4,\n color=self.nd_color[keypoint_id2], thickness=-1)\n cv2.line(frame, pt1=pt1, pt2=pt2,\n color=self.nd_color[keypoint_id2], thickness=2)\n\n '''\n Compute skelethon bounding box\n '''\n\n def compute_simple_bounding_box(self, skeleton):\n x = skeleton[::2]\n x = np.where(x == 0.0, np.nan, x)\n left, right = int(round(np.nanmin(x))), int(round(np.nanmax(x)))\n y = skeleton[1::2]\n y = np.where(y == 0.0, np.nan, y)\n top, bottom = int(round(np.nanmin(y))), int(round(np.nanmax(y)))\n return left, right, top, bottom\n\n '''\n Compute Homograpy\n '''\n\n def compute_homography(self, H_ratio, V_ratio, im_size):\n rationed_hight = im_size[1] * V_ratio\n rationed_width = im_size[0] * H_ratio\n src = np.array([[0, 0], [0, im_size[1]], [\n im_size[0], im_size[1]], [im_size[0], 0]])\n dst = np.array([[0+rationed_width/2, 0+rationed_hight], [0, im_size[1]], [im_size[0],\n im_size[1]], [im_size[0]-rationed_width/2, 0+rationed_hight]], np.int32)\n h, status = cv2.findHomography(src, dst)\n return h\n\n '''\n Compute overlap\n '''\n\n def compute_overlap(self, rect_1, rect_2):\n x_overlap = max(\n 0, min(rect_1[1], rect_2[1]) - max(rect_1[0], rect_2[0]))\n y_overlap = max(\n 0, min(rect_1[3], rect_2[3]) - max(rect_1[2], rect_2[2]))\n overlapArea = x_overlap * y_overlap\n if overlapArea:\n overlaps = True\n else:\n overlaps = False\n return overlaps\n\n '''\n Trace results\n '''\n\n def trace(self, image, skeletal_coordinates, draw_ellipse_requirements, is_skeletal_overlapped):\n bodys = []\n\n # Trace ellipses and body on target image\n i = 0\n\n for skeletal_coordinate in skeletal_coordinates[0]:\n if float(skeletal_coordinates[1][i]) slacker007@cybersyndicates.com\n\nimport argparse\nfrom getpass import getpass\nfrom string import Formatter\nfrom subprocess import call\nfrom subprocess import Popen\nfrom subprocess import PIPE\n\ndef main():\n '''\n Main function definition; Controls Execution & Flow\n '''\n # Use nargs to specify how many args an option should take\n ap = argparse.ArgumentParser()\n ap.add_argument('-a', nargs=1)\n ap.add_argument('-l', nargs=1)\n ap.add_argument('-u', nargs=1)\n ap.add_argument('-p', nargs=1)\n\n # How to access arguments\n opts = ap.parse_args('-a A1 -l L1 -u U1 -p P1'.split())\n\n print(opts)\n print(opts.a)\n print(opts.l)\n print(opts.u)\n '''\n # To require at least 1 option supplied (-a, -l, -u, -p)\n opts = ap.parse_args([])\n if not any([opts.a, opts.l, opts.u, opts.p]):\n ap.print_usage()\n quit()\n '''\n p = Popen([r'wmic -U cpt91 //10.10.80.100 \"select * from win32_groups\"'], stdin=PIPE, stdout=PIPE)\n output = p.communicate(input=\"HappyTrailRedFish137!!\")[0] \n print(output)\n\n\n return 0\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"GetMacs.py","file_name":"GetMacs.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"241160572","text":"def add_matrix(matrix1, matrix2):\n return_matrix = []\n for row in range(len(matrix1)):\n return_matrix.append([])\n for col in range(len(matrix2[row])):\n element = 0\n for cross in range(len(matrix2)):\n element += matrix1[row][cross] * matrix2[cross][col]\n return_matrix[row].append(element)\n return return_matrix\n\n\ndef input_matrix():\n create_matrix = []\n for row in range(3): # set col size to 3\n create_matrix.append([])\n buf = str(input()).strip().split(' ')\n for col in range(len(buf)):\n create_matrix[row].append(eval(buf[col]))\n return create_matrix\n\n\nA = input_matrix()\nB = input_matrix()\nC = add_matrix(A, B)\nprint('%-5d%-5d%-5d' % (C[0][0], C[0][1], C[0][2]))\nprint('%-5d%-5d%-5d' % (C[1][0], C[1][1], C[1][2]))\nprint('%-5d%-5d%-5d' % (C[2][0], C[2][1], C[2][2]))\n","sub_path":"p_matrix_method.py","file_name":"p_matrix_method.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"342317578","text":"from src.utils.db import connect_to_db, run_query\nimport scipy.stats\n\n\n# Creates the poisson probabilities for goals_for and goals_against for each team, up to 3 goals.\ndef create_team_poisson_probabilities():\n\n # Connect to database\n conn, cursor = connect_to_db()\n\n # Extract data\n query = 'select fixture_id, team_name, date, season, is_home, goals_for, goals_against from team_fixtures'\n df = run_query(cursor, query)\n\n # Sort the data by season, team_name and date\n df = df.sort_values(['season', 'team_name', 'date'])\n\n # Calculate the moving average\n # NOTE: The moving average value uses the previous games data, not the goals_for and goals_against on that row.\n df['goals_for_mavg'] = df.groupby(['team_name', 'season'])['goals_for'].\\\n transform(lambda x: x.rolling(8, 8).mean()).shift(1)\n df['goals_against_mavg'] = df.groupby(['team_name', 'season'])['goals_against'].\\\n transform(lambda x: x.rolling(8, 8).mean()).shift(1)\n\n # Calculate the moving standard deviation\n #df['goals_for_sdavg'] = df.groupby(['team_name', 'season'])['goals_for'].\\\n # transform(lambda x: x.rolling(8, 8).std()).shift(1)\n #df['goals_against_sdavg'] = df.groupby(['team_name', 'season'])['goals_against'].\\\n # transform(lambda x: x.rolling(8, 8).std()).shift(1)\n\n # Get goals_for probabilities\n df['gf_prob_0'] = df['goals_for_mavg'].apply(lambda x: scipy.stats.distributions.poisson.pmf(0, x))\n df['gf_prob_1'] = df['goals_for_mavg'].apply(lambda x: scipy.stats.distributions.poisson.pmf(1, x))\n df['gf_prob_2'] = df['goals_for_mavg'].apply(lambda x: scipy.stats.distributions.poisson.pmf(2, x))\n df['gf_prob_3'] = df['goals_for_mavg'].apply(lambda x: scipy.stats.distributions.poisson.pmf(3, x))\n df['gf_prob_other'] = df.apply(lambda x: 1-(x['gf_prob_0'] + x['gf_prob_1'] +\n x['gf_prob_2'] + x['gf_prob_3']), axis=1)\n\n # Get goals_against probabilities\n df['ga_prob_0'] = df['goals_against_mavg'].apply(lambda x: scipy.stats.distributions.poisson.pmf(0, x))\n df['ga_prob_1'] = df['goals_against_mavg'].apply(lambda x: scipy.stats.distributions.poisson.pmf(1, x))\n df['ga_prob_2'] = df['goals_against_mavg'].apply(lambda x: scipy.stats.distributions.poisson.pmf(2, x))\n df['ga_prob_3'] = df['goals_against_mavg'].apply(lambda x: scipy.stats.distributions.poisson.pmf(3, x))\n df['ga_prob_other'] = df.apply(lambda x: 1 - (x['ga_prob_0'] + x['ga_prob_1'] +\n x['ga_prob_2'] + x['ga_prob_3']), axis=1)\n\n # ToDo: Get the data also in key-value pair, e.g type: goals_for/goals_against, amount:, value: for easier plotting\n \n # Create the DB table to store data\n cursor.execute(\"DROP TABLE IF EXISTS poisson_team_odds\")\n cursor.execute(\"\"\"CREATE TABLE poisson_team_odds (fixture_id INT, team_name TEXT, date DATE, season TEXT, \n is_home INT, goals_for FLOAT, goals_against FLOAT, goals_for_mavg FLOAT, goals_against_mavg FLOAT, gf_prob_0 FLOAT, \n gf_prob_1 FLOAT, gf_prob_2 FLOAT, gf_prob_3 FLOAT, ga_prob_0 FLOAT, ga_prob_1 FLOAT, ga_prob_2 FLOAT, \n ga_prob_3 FLOAT)\"\"\")\n\n # Remove Nans (the first 8 games for each team)\n df = df.dropna()\n\n # Round floats to 2 decimal places\n float_columns = df.select_dtypes(include='float64').columns\n df[float_columns] = round(df.select_dtypes(include='float64'), 4)\n\n # Load data into the DB\n for row in df.iterrows():\n params = [row[1][0], str(row[1][1]), str(row[1][2]), str(row[1][3]), row[1][4], row[1][5], row[1][6],\n row[1][7], row[1][8], row[1][9], row[1][10], row[1][11], row[1][12], row[1][13], row[1][14],\n row[1][15], row[1][16]]\n cursor.execute('''insert into poisson_team_odds VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', params)\n\n conn.commit()\n\n\n# Combines the poisson team_odds table so we can get the odds for different score combinations.\ndef combine_team_poisson_probabilities():\n\n # Connect to database\n conn, cursor = connect_to_db()\n\n # Extract data, join the poisson_team_odds table on itself to combine the home and away teams.\n query = '''\n select\n -- IDENTIFIERS\n fixture_id, date, season, home_team, away_team,\n -- SCORE PROBABILITIES\n 0.5 * (gf_0_h + ga_0_a) * 0.5 * (gf_0_a + ga_0_h) p0_0,\n 0.5 * (gf_1_h + ga_1_a) * 0.5 * (gf_0_a + ga_0_h) p1_0,\n 0.5 * (gf_2_h + ga_2_a) * 0.5 * (gf_0_a + ga_0_h) p2_0,\n 0.5 * (gf_3_h + ga_3_a) * 0.5 * (gf_0_a + ga_0_h) p3_0,\n 0.5 * (gf_0_h + ga_0_a) * 0.5 * (gf_1_a + ga_1_h) p0_1,\n 0.5 * (gf_1_h + ga_1_a) * 0.5 * (gf_1_a + ga_1_h) p1_1,\n 0.5 * (gf_2_h + ga_2_a) * 0.5 * (gf_1_a + ga_1_h) p2_1,\n 0.5 * (gf_3_h + ga_3_a) * 0.5 * (gf_1_a + ga_1_h) p3_1,\n 0.5 * (gf_0_h + ga_0_a) * 0.5 * (gf_2_a + ga_2_h) p0_2,\n 0.5 * (gf_1_h + ga_1_a) * 0.5 * (gf_2_a + ga_2_h) p1_2,\n 0.5 * (gf_2_h + ga_2_a) * 0.5 * (gf_2_a + ga_2_h) p2_2,\n 0.5 * (gf_3_h + ga_3_a) * 0.5 * (gf_2_a + ga_2_h) p3_2,\n 0.5 * (gf_0_h + ga_0_a) * 0.5 * (gf_3_a + ga_3_h) p0_3,\n 0.5 * (gf_1_h + ga_1_a) * 0.5 * (gf_3_a + ga_3_h) p1_3,\n 0.5 * (gf_2_h + ga_2_a) * 0.5 * (gf_3_a + ga_3_h) p2_3,\n 0.5 * (gf_3_h + ga_3_a) * 0.5 * (gf_3_a + ga_3_h) p3_3\n from\n (\n select \n -- IDENTIFIERS\n t1.fixture_id, t1.date, t1.season, t1.team_name home_team, t2.team_name away_team,\n -- HOME TEAM PROBABILITIES\n t1.gf_prob_0 gf_0_h, t1.gf_prob_1 gf_1_h, t1.gf_prob_2 gf_2_h, t1.gf_prob_3 gf_3_h, \n t1.ga_prob_0 ga_0_h, t1.ga_prob_1 ga_1_h, t1.ga_prob_2 ga_2_h, t1.ga_prob_3 ga_3_h, \n -- AWAY TEAM PROBABILITIES\n t2.gf_prob_0 gf_0_a, t2.gf_prob_1 gf_1_a, t2.gf_prob_2 gf_2_a, t2.gf_prob_3 gf_3_a, \n t2.ga_prob_0 ga_0_a, t2.ga_prob_1 ga_1_a, t2.ga_prob_2 ga_2_a, t2.ga_prob_3 ga_3_a\n from \n (select * from poisson_team_odds where is_home = 1) t1 -- home_teams\n left join \n (select * from poisson_team_odds where is_home = 0) t2 -- away_teams\n on t1.fixture_id = t2.fixture_id \n and t1.season = t2.season \n and t1.team_name is not t2.team_name\n )'''\n\n df = run_query(cursor, query)\n\n df['prob_sum'] = df.select_dtypes('float64').apply(lambda x: sum(x), axis=1)\n\n # Round floats to 2 decimal places\n float_columns = df.select_dtypes(include='float64').columns\n df[float_columns] = round(df.select_dtypes(include='float64'), 4)\n\n # Create the DB table to store data\n cursor.execute(\"DROP TABLE IF EXISTS poisson_match_probabilities\")\n cursor.execute(\"\"\"CREATE TABLE poisson_match_probabilities (fixture_id INT, date DATE, season TEXT, \n home_team TEXT, away_team TEXT, p0_0 FLOAT, p1_0 FLOAT, p2_0 FLOAT, p3_0 FLOAT, p0_1 FLOAT, p1_1 FLOAT, \n p2_1 FLOAT, p3_1 FLOAT, p0_2 FLOAT, p1_2 FLOAT, p2_2 FLOAT, p3_2 FLOAT, p0_3 FLOAT, p1_3 FLOAT, p2_3 FLOAT, \n p3_3 FLOAT, prob_sum FLOAT)\"\"\")\n\n # Load data into the DB\n for row in df.iterrows():\n params = [row[1][0], str(row[1][1]), str(row[1][2]), str(row[1][3]), row[1][4], row[1][5], row[1][6],\n row[1][7], row[1][8], row[1][9], row[1][10], row[1][11], row[1][12], row[1][13], row[1][14],\n row[1][15], row[1][16], row[1][17], row[1][18], row[1][19], row[1][20], row[1][21]]\n cursor.execute('insert into poisson_match_probabilities VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', params)\n\n conn.commit()\n\n\n# Run functions\ncreate_team_poisson_probabilities()\ncombine_team_poisson_probabilities()\n\n\n\n","sub_path":"src/old/calculate_poisson_params.py","file_name":"calculate_poisson_params.py","file_ext":"py","file_size_in_byte":7680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"539610178","text":"discs = [(1, 13), (10, 19), (2, 3), (1, 7), (3, 5), (5, 17)]\r\n#discs = [(4, 5), (1, 2)]\r\ntime = 0\r\n\r\nwhile True:\r\n win = True\r\n for i in range(1, len(discs) + 1):\r\n total_time = time + i\r\n pos = discs[i-1][0]\r\n num_of_slots = discs[i-1][1]\r\n if (pos + total_time) % num_of_slots != 0:\r\n win = False\r\n break\r\n if win:\r\n break\r\n else:\r\n time += 1\r\nprint(time)","sub_path":"Advent of Code 2016/Day 15/15_1.py","file_name":"15_1.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"601841148","text":"# Copyright 2019 GreenWaves Technologies, SAS\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\n\nfrom graph.types.others import ReshapeParameters\nfrom graph.types.base import SensitiveToOrder, Transposable\n\nLOG = logging.getLogger(\"nntool.\" + __name__)\n\ndef add_sequence(trans_seqs, trans_nodes):\n if trans_nodes and len(trans_nodes) > 1:\n trans_seq = trans_seqs.get(trans_nodes[-1])\n if not trans_seq:\n trans_seq = []\n trans_seqs[trans_nodes[-1]] = trans_seq\n trans_seq.append(trans_nodes)\n\ndef find_last_transpose(G, node, trans_seqs, trans_nodes=None):\n if isinstance(node, str):\n node = G.node(node)\n\n if isinstance(node, SensitiveToOrder):\n add_sequence(trans_seqs, trans_nodes)\n trans_nodes = None\n elif isinstance(node, Transposable):\n if trans_nodes is None:\n # new sequence\n trans_nodes = []\n trans_nodes.append(node)\n\n out_edges = G.out_edges(node.name)\n\n if len(out_edges) == 0:\n add_sequence(trans_seqs, trans_nodes)\n return\n\n # Edges are visited in a repeatable order\n out_edges.sort(key=lambda x: str(x.from_idx) + x.to_node.name + str(x.to_idx))\n\n for edge in out_edges:\n if trans_nodes:\n if len(out_edges) > 1:\n trans_nodes_copy = trans_nodes.copy()\n else:\n trans_nodes_copy = trans_nodes\n find_last_transpose(G, edge.to_node, trans_seqs, trans_nodes_copy)\n else:\n find_last_transpose(G, edge.to_node, trans_seqs)\n\ndef find_last_transposes(G):\n \"\"\"Does a depth first search in the graph to discover transposable\n nodes with no SensitiveToOrder nodes between them\"\"\"\n LOG.info(\"finding transpose sequences\")\n trans_seqs = {}\n for node in G.inputs():\n find_last_transpose(G, node, trans_seqs)\n return trans_seqs\n\ndef reverses_transpose(trans1, trans2):\n \"\"\"Checks if one transpose reverses another\"\"\"\n if trans1 is None or trans2 is None:\n return False\n for idx, val in enumerate(trans1):\n if trans2[val] != idx:\n return False\n return True\n\ndef get_first_transposable(rseq, idx):\n \"\"\"Looks back in the string of transposables for a vlid transposable. Reshapes that are\n not transposing are skipped but returned in an array\"\"\"\n reshapes = []\n while idx < len(rseq):\n node = rseq[idx]\n if isinstance(node, ReshapeParameters) and not node.has_transpose:\n reshapes.append(rseq[idx])\n elif isinstance(node, Transposable):\n return node, reshapes, idx\n idx += 1\n return None, reshapes, idx\n\ndef apply_reshape(trans, reshape):\n \"\"\"Create a new transpose if there are 1 sized dimensions in the reshape\"\"\"\n if not reshape.does_nothing():\n return trans\n\n old_shape = reshape.old_shape.shape.copy()\n trans = trans.copy()\n while True:\n change = False\n idx = 0\n while idx < len(trans):\n dim_idx = trans[idx]\n if old_shape[dim_idx] == 1:\n change = True\n del old_shape[dim_idx]\n del trans[idx]\n for jdx, dim_jdx in enumerate(trans):\n if dim_jdx > dim_idx:\n trans[jdx] -= 1\n change = True\n break\n idx += 1\n if not change:\n break\n\n return trans\n\ndef apply_reshapes(trans, reshapes):\n for reshape in reversed(reshapes):\n trans = apply_reshape(trans, reshape)\n return trans\n\ndef process(seq, switchable):\n rseq = seq[::-1]\n idx = 0\n while idx < len(rseq) - 1:\n node = rseq[idx]\n pnode, reshapes, idx = get_first_transposable(rseq, idx + 1)\n sw_node = switchable.get(node)\n if reverses_transpose(node.transpose_in, apply_reshapes(pnode.transpose_out, reshapes)):\n if not sw_node:\n switchable[node] = {\n 'can_switch': True,\n 'segments': {pnode: reshapes}\n }\n elif sw_node['can_switch']:\n sw_node['segments'][pnode] = reshapes\n else:\n if not sw_node:\n # This node cannot be switched so all the nodes that could\n # switched cannot be\n switchable[node] = {'can_switch': False, 'segments': {}}\n elif sw_node['can_switch']:\n sw_node['can_switch'] = False\n sw_node['segments'].clear()\n\ndef process_sequences(trans_seqs):\n \"\"\"Extracts nodes that are valid for transpose elimination\"\"\"\n LOG.info(\"processing transpose sequences\")\n switchable = {}\n for seqs in trans_seqs.values():\n for seq in seqs:\n process(seq, switchable)\n return switchable\n\ndef update_switchable(switchable):\n \"\"\"Updates the node transposes\"\"\"\n LOG.info(\"updating nodes\")\n updated_reshapes = set()\n for node, switch in switchable.items():\n if not switch['can_switch']:\n continue\n for pnode, reshapes in switch['segments'].items():\n for reshape in reshapes:\n if reshape not in updated_reshapes:\n updated_reshapes.add(reshape)\n reshape.old_shape.transpose(pnode.transpose_out)\n reshape.shape.transpose(node.transpose_in)\n LOG.info(\"reshape %s modified\", reshape.name)\n pnode.transpose_out = None\n LOG.info(\"transpose eliminated %s => %s\", pnode.name, node.name)\n\n node.transpose_in = None\n\ndef eliminate_transposes(G):\n \"\"\"Eliminates unnecessary transposes from the graph. Valid transposes are those that have no\n nodes that are sensitive to order between them and where one reverses the other\"\"\"\n LOG.info(\"eliminating unnecessary transposes\")\n trans_seqs = find_last_transposes(G)\n if not trans_seqs:\n LOG.info(\"no transpose sequences found\")\n return\n switchable = process_sequences(trans_seqs)\n update_switchable(switchable)\n","sub_path":"tools/nntool/graph/manipulations/eliminate_transposes.py","file_name":"eliminate_transposes.py","file_ext":"py","file_size_in_byte":6567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"149530684","text":"from tkinter import Tk\nfrom tkinter import filedialog as fd\n\nimport pygame\n\nimport ai\nimport chess\nimport gui\nfrom chess import RMB, LMB\n\nBOARD_IMG = 'data/images/board.jpg'\nFRAME_COLOR = pygame.Color('#ead7c6')\nLETTER_COLOR = pygame.Color('#663a0d')\nFONT_TYPEWRITER_PATH = 'data/fonts/linowrite.ttf'\nBUTTON_IMG_PATH = 'data/images/buttons/'\n\nPLAY_IMG = pygame.image.load(BUTTON_IMG_PATH + 'play.png')\nPAUSE_IMG = pygame.image.load(BUTTON_IMG_PATH + 'pause.png')\nREDO_IMG = pygame.image.load(BUTTON_IMG_PATH + 'redo.png')\nUNDO_IMG = pygame.image.load(BUTTON_IMG_PATH + 'undo.png')\nFLIP_IMG = pygame.image.load(BUTTON_IMG_PATH + 'flip.png')\nRESET_IMG = pygame.image.load(BUTTON_IMG_PATH + 'reset.png')\nSAVE_IMG = pygame.image.load(BUTTON_IMG_PATH + 'save.png')\nOPEN_IMG = pygame.image.load(BUTTON_IMG_PATH + 'open.png')\nBOT_ON_IMG = pygame.image.load(BUTTON_IMG_PATH + 'bot_on.png')\nBOT_OFF_IMG = pygame.image.load(BUTTON_IMG_PATH + 'bot_off.png')\n\nAI_DEPTH = 2\n\n\nclass PromoteDialog:\n def __init__(self, rect, target, btn_space=10, title_h=20, color=chess.WHITE):\n self.x, self.y, self.w, self.h = self.rect = rect\n self.btn_space = btn_space\n self.title_h = title_h\n\n self.target = target\n\n figures = list(chess.PIECES_CHARS.keys())\n figures.remove('K')\n self.figures = figures\n self.output = 'Q'\n\n self.btn_w = (self.w - self.btn_space * (len(self.figures) + 1)) // len(self.figures)\n\n self.gui_group = gui.UIGroup(rect)\n\n self.title_lbl = gui.UILabel((0, 0, self.w, self.title_h), 'Выберите фигуру:')\n\n for i, fig in enumerate(self.figures):\n x = self.btn_space + (self.btn_w + self.btn_space) * i\n y = self.btn_space + self.title_h\n\n piece = chess.PIECES_CHARS[fig](color)\n img = chess.get_piece_img(piece)\n del piece\n\n pygame.draw.rect(img, pygame.Color('black'), (3, 3, img.get_width() - 6, img.get_height() - 6), 9)\n\n btn = gui.UIButton((x, y, self.btn_w, self.btn_w), None, img=img, text=fig,\n font_size=1, text_align=(gui.ALIGN_LEFT, gui.ALIGN_TOP))\n self.gui_group.add_element(btn)\n\n self.gui_group.add_element(self.title_lbl)\n\n def __call__(self):\n clock = pygame.time.Clock()\n\n mpos = pygame.mouse.get_pos()\n\n running = True\n\n while running:\n has_interacted = False\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.MOUSEBUTTONDOWN:\n btn = self.gui_group.get_click(event.pos)\n if isinstance(btn, gui.UIButton):\n self.output = btn.text[0].upper()\n running = False\n has_interacted = True\n if event.type == pygame.MOUSEMOTION:\n mpos = pygame.mouse.get_pos()\n self.gui_group.get_mouse_over(mpos)\n has_interacted = True\n if event.type == pygame.MOUSEBUTTONUP:\n self.gui_group.get_mouse_up(mpos)\n has_interacted = True\n\n if has_interacted:\n self.render()\n pygame.display.update(self.rect)\n\n clock.tick(10)\n\n del clock\n return self.output\n\n def get_img(self):\n return self.gui_group.get_img()\n\n def render(self):\n x, y, w, h = self.rect\n self.target.blit(self.get_img(), (x, y))\n\n\nclass Chess:\n def __init__(self, size, frame_size, pos=(0, 0), frame_image=None, frame_color=FRAME_COLOR, promote=input):\n self.size = self.w, self.h = size\n self.pos = self.x, self.y = pos\n self.offset = self.x_offset, self.y_offset = frame_size\n\n chess_side = min(self.size)\n self.chess_size = self.chess_w, self.chess_h = chess_side - 2 * self.x_offset, chess_side - 2 * self.y_offset\n self.chess_pos = self.chess_x, self.chess_y = self.w - (self.x_offset + self.chess_w), self.y_offset\n\n self.frame_color = frame_color\n\n self.chess_board = chess.ChessBoard(self.chess_size, promote)\n ui_x, ui_y = 20, 20\n ui_w, ui_h = self.w - chess_side - 40, self.h - 40\n\n self.lbl_status = gui.UILabel((10, 10, ui_w - 20, 50), bg_color=pygame.Color('white'), text='Ход белых')\n self.stopwatch = gui.UILcdDisplay((10, 10 + (self.lbl_status.y + self.lbl_status.h) + 10,\n ui_w - 20, 50))\n\n btn_w, btn_h = 50, 50\n self.play_btn = gui.UIButton((10, 10 + (self.stopwatch.y + self.stopwatch.h) + 10, btn_w, btn_h),\n self.unpause_stopwatch, img=PLAY_IMG)\n self.pause_btn = gui.UIButton((self.play_btn.x + self.play_btn.w + 20,\n 10 + (self.stopwatch.y + self.stopwatch.h) + 10, btn_w, btn_h),\n self.pause_stopwatch, img=PAUSE_IMG)\n\n self.undo_btn = gui.UIButton((10, 10 + (self.play_btn.y + self.play_btn.h) + 30,\n btn_w, btn_h), self.undo, img=UNDO_IMG)\n\n self.redo_btn = gui.UIButton((self.undo_btn.x + self.undo_btn.w + 20,\n 10 + (self.play_btn.y + self.play_btn.h) + 30,\n btn_w, btn_h), self.redo, img=REDO_IMG)\n\n self.flip_btn = gui.UIButton((self.redo_btn.x + self.redo_btn.w + 20,\n 10 + (self.play_btn.y + self.play_btn.h) + 30,\n btn_w, btn_h), self.chess_board.flip, img=FLIP_IMG)\n\n self.reset_btn = gui.UIButton((10, 10 + (self.undo_btn.y + self.undo_btn.h) + 10,\n btn_w, btn_h), self.reset, img=RESET_IMG)\n\n self.save_btn = gui.UIButton((self.reset_btn.x + self.reset_btn.w + 20,\n 10 + (self.undo_btn.y + self.undo_btn.h) + 10,\n btn_w, btn_h), self.write_to_file, img=SAVE_IMG)\n\n self.load_btn = gui.UIButton((self.save_btn.x + self.save_btn.w + 20,\n 10 + (self.undo_btn.y + self.undo_btn.h) + 10,\n btn_w, btn_h), self.read_from_file, img=OPEN_IMG)\n\n self.ai_enabled_switch = gui.UISwitch((10, 10 + (self.reset_btn.y + self.reset_btn.h) + 30,\n btn_w, btn_h), action=self.switch_ai,\n on_img=BOT_ON_IMG, off_img=BOT_OFF_IMG)\n\n self.ai_enabled_lbl = gui.UILabel((self.ai_enabled_switch.x + self.ai_enabled_switch.w + 20,\n self.ai_enabled_switch.y,\n ui_w - self.ai_enabled_switch.w - 40,\n btn_h), 'ИИ выключен')\n\n self.turn_history_box = gui.UIListVertical((10,\n 10 + (self.ai_enabled_switch.y + self.ai_enabled_switch.h) + 30,\n ui_w - 20,\n ui_h - (self.ai_enabled_switch.y + self.ai_enabled_switch.h + 50)))\n\n self.gui_group = gui.UIGroup((ui_x, ui_y, ui_w, ui_h))\n\n self.gui_group.add_element(self.stopwatch)\n self.gui_group.add_element(self.lbl_status)\n self.gui_group.add_element(self.turn_history_box)\n self.gui_group.add_element(self.pause_btn)\n self.gui_group.add_element(self.play_btn)\n self.gui_group.add_element(self.undo_btn)\n self.gui_group.add_element(self.redo_btn)\n self.gui_group.add_element(self.flip_btn)\n self.gui_group.add_element(self.reset_btn)\n self.gui_group.add_element(self.save_btn)\n self.gui_group.add_element(self.load_btn)\n self.gui_group.add_element(self.ai_enabled_switch)\n self.gui_group.add_element(self.ai_enabled_lbl)\n\n if isinstance(frame_image, pygame.Surface):\n self.img = pygame.transform.smoothscale(frame_image, self.size)\n else:\n self.img = self.get_frame_img()\n\n self.is_ai_enabled = False\n\n self.turn_len = 120\n self.stopwatch_secs = self.turn_len\n self.is_stopwatch_running = True\n\n self.update_stopwatch_text()\n\n def switch_ai(self):\n self.is_ai_enabled = self.ai_enabled_switch.get_state()\n if self.is_ai_enabled:\n self.ai_enabled_lbl.set_text('ИИ включен')\n else:\n self.ai_enabled_lbl.set_text('ИИ выключен')\n\n def write_to_file(self):\n file_name = fd.asksaveasfilename(filetypes=[(\"Txt files\", \"*.txt\")])\n\n if file_name:\n self.chess_board.write_to_file(file_name)\n\n def read_from_file(self):\n file_name = fd.askopenfilename(filetypes=[(\"Txt files\", \"*.txt\")])\n\n if file_name:\n try:\n self.chess_board.read_from_file(file_name)\n except Exception as error:\n print('Error reading file:', error)\n self.reset()\n\n self.turn_history_box.clear()\n\n def undo(self):\n self.chess_board.undo()\n self.stopwatch_secs = self.turn_len\n self.update_stopwatch_text()\n\n def redo(self):\n self.chess_board.redo()\n self.stopwatch_secs = self.turn_len\n self.update_stopwatch_text()\n\n def reset(self):\n self.chess_board.reset()\n\n self.turn_history_box.clear()\n\n self.stopwatch_secs = self.turn_len\n self.is_stopwatch_running = True\n self.update_stopwatch_text()\n\n def pause_stopwatch(self):\n self.is_stopwatch_running = False\n\n def unpause_stopwatch(self):\n self.is_stopwatch_running = True\n\n def update_stopwatch_text(self):\n mins = self.stopwatch_secs // 60\n secs = self.stopwatch_secs % 60\n\n s_mins = ('0' if mins < 10 else '') + str(mins)\n s_secs = ('0' if secs < 10 else '') + str(secs)\n\n self.stopwatch.set_text(s_mins + ':' + s_secs)\n\n def tick_stopwatch(self):\n if self.is_stopwatch_running and not self.chess_board.is_checkmate():\n self.stopwatch_secs -= 1\n self.update_stopwatch_text()\n\n if self.stopwatch_secs == 0:\n self.stopwatch_secs = self.turn_len\n self.change_turn()\n\n def get_frame_img(self):\n img = pygame.Surface(self.size)\n\n img.fill(self.frame_color)\n\n size = min(self.chess_board.col_size // 2, self.chess_board.row_size // 2, self.y_offset - 4)\n font = pygame.font.Font(FONT_TYPEWRITER_PATH, size)\n\n flipped = self.chess_board.get_flipped()\n\n for i in range(8):\n row_letter_img = font.render(chess.get_row_letter(i, is_flipped=flipped), True, LETTER_COLOR)\n col_letter_img = font.render(chess.get_col_letter(i, is_flipped=flipped), True, LETTER_COLOR)\n\n x_off = (self.x_offset - row_letter_img.get_width()) // 2\n y_off = (self.y_offset - col_letter_img.get_height()) // 2\n\n col_offset = (self.chess_board.col_size - col_letter_img.get_width()) // 2\n row_offset = (self.chess_board.row_size - row_letter_img.get_height()) // 2\n\n x = self.chess_x + col_offset + (self.chess_board.col_size * i)\n y = self.chess_y + row_offset + (self.chess_board.row_size * i)\n\n img.blit(row_letter_img, (self.chess_x - self.x_offset + x_off, y))\n img.blit(row_letter_img, (self.w - self.x_offset + x_off, y))\n img.blit(col_letter_img, (x, y_off))\n img.blit(col_letter_img, (x, self.h - self.y_offset + y_off))\n\n chess_side = min(self.size)\n cx, cy = self.w - chess_side, self.h - chess_side\n offset = 4\n pygame.draw.rect(img, LETTER_COLOR, (cx + offset, cy + offset,\n chess_side - 2 * offset, chess_side - 2 * offset), 5)\n pygame.draw.rect(img, chess.BLACK_CELL_COLOR, (self.chess_x - 2, self.chess_y - 2,\n self.chess_w, self.chess_h), 3)\n\n return img\n\n def get_surface(self):\n board_img = self.chess_board.get_surface(chess.draw_chess)\n\n frame = self.get_frame_img()\n\n frame.blit(board_img, self.chess_pos)\n self.gui_group.render(frame)\n\n return frame\n\n def render(self, target):\n img = self.get_surface()\n target.blit(img, self.pos)\n\n def get_mouse_over(self, mouse_pos):\n self.gui_group.get_mouse_over(mouse_pos)\n\n def get_mouse_up(self, mouse_pos):\n self.gui_group.get_mouse_up(mouse_pos)\n\n def make_ai_move(self):\n is_maximising = self.chess_board.color == chess.WHITE\n\n best_move = ai.minimax_root(AI_DEPTH, self.chess_board, is_maximising)\n\n history_obj = self.chess_board.make_move(*best_move, True)\n\n self.update_game(history_obj)\n\n self.stopwatch_secs = self.turn_len\n self.update_stopwatch_text()\n\n def change_turn(self):\n self.chess_board.color = chess.opponent(self.chess_board.color)\n if self.chess_board.color == chess.WHITE:\n self.lbl_status.set_text('Ход белых')\n else:\n self.lbl_status.set_text('Ход чёрных')\n\n def update_game(self, history_obj):\n if isinstance(history_obj, chess.HistoryObject):\n self.stopwatch_secs = self.turn_len\n self.update_stopwatch_text()\n\n c1, c2, *_ = history_obj.old.keys()\n f1, f2 = history_obj.old[c1], history_obj.old[c2]\n\n if isinstance(f1, (chess.King, chess.Queen, chess.Rook, chess.Pawn, chess.Knight, chess.Bishop)):\n char = f1.char()[0]\n\n s_pos1 = chess.to_chess_notation(c1).lower()\n s_pos2 = chess.to_chess_notation(c2).lower()\n\n s_color = 'Белые' if history_obj.color == chess.WHITE else 'Чёрные'\n\n text = s_color + ': ' + char + ' ' + s_pos1 + ' - ' + s_pos2\n\n new_lbl = gui.UILabel((0, 0, 100, 30))\n self.turn_history_box.add_element(new_lbl, True)\n new_lbl.set_text(text)\n\n if self.chess_board.color == chess.WHITE:\n self.lbl_status.set_text('Ход белых')\n else:\n self.lbl_status.set_text('Ход чёрных')\n\n def get_click(self, mouse_pos, button=LMB):\n self.gui_group.get_click(mouse_pos)\n\n mx, my = mouse_pos\n mpos = mx - self.chess_x, my - self.y - self.chess_y\n\n move = self.chess_board.get_click(mpos, button)\n\n self.update_game(move)\n return move\n\n\ndef main():\n size = screen_w, screen_h = 1000, 700\n\n pygame.init()\n\n screen = pygame.display.set_mode(size)\n screen.fill(pygame.Color('white'))\n\n dialog_w, dialog_h = screen_w // 2, screen_h // 4\n dialog_x, dialog_y = (screen_w - dialog_w) // 2, (screen_h - dialog_h) // 2\n\n dia = PromoteDialog((dialog_x, dialog_y, dialog_w, dialog_h), screen, 10, 40)\n\n chessb = Chess(size, (60, 60), (0, 0), promote=dia)\n\n game_over_lbl = gui.UILabel((0, 0, dialog_w, dialog_h // 2 - 10), text='Игра закончена',\n bg_color=pygame.Color('white'))\n play_again_btn = gui.UIButton((20, dialog_h // 2, dialog_w - 40, dialog_h // 2 - 10), chessb.reset,\n text='Начать заново')\n game_over = gui.UIGroup((dialog_x, dialog_y, dialog_w, dialog_h), bg_color=pygame.Color('white'))\n game_over.add_element(game_over_lbl)\n game_over.add_element(play_again_btn)\n game_over.hide()\n\n chessb.render(screen)\n pygame.display.flip()\n\n clock = pygame.time.Clock()\n\n STOPWATCH_TICK = pygame.USEREVENT + 1\n pygame.time.set_timer(STOPWATCH_TICK, 1000)\n\n mpos = pygame.mouse.get_pos()\n\n running = True\n\n while running:\n has_interacted = False\n is_checkmate = chessb.chess_board.is_checkmate()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.MOUSEBUTTONDOWN:\n left, _, right = pygame.mouse.get_pressed(3)\n\n btn = LMB if left else RMB\n\n if is_checkmate:\n game_over.get_click(mpos)\n else:\n if chessb.get_click(event.pos, btn) and chessb.is_ai_enabled:\n chessb.render(screen)\n pygame.display.update((chessb.x, chessb.y, chessb.w, chessb.h))\n\n if not chessb.chess_board.is_checkmate():\n chessb.make_ai_move()\n\n has_interacted = True\n if event.type == pygame.MOUSEMOTION:\n mpos = pygame.mouse.get_pos()\n\n chessb.get_mouse_over(mpos)\n game_over.get_mouse_over(mpos)\n\n has_interacted = True\n if event.type == pygame.MOUSEBUTTONUP:\n chessb.get_mouse_up(mpos)\n game_over.get_mouse_up(mpos)\n\n has_interacted = True\n if event.type == STOPWATCH_TICK:\n chessb.tick_stopwatch()\n has_interacted = True\n\n if has_interacted or is_checkmate:\n screen.fill(pygame.Color('white'))\n chessb.render(screen)\n\n if is_checkmate:\n game_over.show()\n\n text = 'Игра закончена! '\n if chessb.chess_board.color == chess.WHITE:\n text += 'Победили чёрные'\n else:\n text += 'Победили белые'\n\n game_over_lbl.set_text(text)\n game_over.render(screen)\n\n pygame.display.flip()\n\n if not is_checkmate:\n game_over.hide()\n\n clock.tick(10)\n\n\npygame.quit()\n\nif __name__ == '__main__':\n Tk().withdraw()\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"114535114","text":"#!/usr/bin/env python3\n\nfrom collections import defaultdict\n\ndef part_one():\n speeds = [line.strip() for line in open(r\"2015\\2015_14_reindeer.txt\")]\n print(max(distance_flown(deer, 2503) for deer in speeds))\n\ndef part_two():\n speeds = [line.strip() for line in open(r\"2015\\2015_14_reindeer.txt\")]\n print(race(speeds, 2503))\n\ndef race(speeds, seconds):\n \"\"\"\n >>> speeds = [\"Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.\", \"Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds.\"]\n >>> race(speeds, 1000)\n 689\n \"\"\"\n scoreboard = defaultdict(int)\n for s in range(1, seconds + 1):\n rank = [[deer, distance_flown(deer, s)] for deer in speeds]\n winner = max(rank, key = lambda i: i[1])\n scoreboard[winner[0]] += 1\n scoreboard[winner[0]] += 1\n return max(scoreboard.values())\n\ndef distance_flown(reindeer, seconds):\n \"\"\"\n >>> distance_flown(\"Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.\", 1000)\n 1120\n >>> distance_flown(\"Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds.\", 1000)\n 1056\n \"\"\"\n reindeer = reindeer.split(\" \")\n speed = int(reindeer[3])\n fly_time = int(reindeer[6])\n rest_time = int(reindeer[13])\n\n seconds_flown = (seconds // (fly_time + rest_time)) * fly_time\n seconds_left = seconds % (fly_time + rest_time)\n return speed * (seconds_flown + min(seconds_left, fly_time))\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n part_one()\n part_two()","sub_path":"2015/2015_14.py","file_name":"2015_14.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"387305404","text":"\n'''\n'''\n\n# TODO fill in doc string\n\n###########\n# Imports #\n###########\n\nimport typing\nimport typing_extensions\nimport weakref\nimport operator\nimport pyparsing\n\nfrom .misc_utilities import *\n\n# TODO make sure imports are used\n# TODO make sure these imports are ordered in some way\n\n###################\n# Exception Types #\n###################\n\nclass ParseError(Exception):\n\n def __init__(self, original_text: str, problematic_text: str, problem_column_number: int) -> None:\n self.original_text = original_text\n self.problematic_text = problematic_text\n self.problem_column_number = problem_column_number\n super().__init__(f'''Could not parse the following:\n\n {self.problematic_text}\n {(' '*(self.problem_column_number - 1))}^\n''')\n return\n\nclass SemanticError(Exception):\n pass\n\n#######################################\n# Base Type Sanity Checking Utilities #\n#######################################\n\nBASE_TYPES = ('Boolean', 'Integer', 'Float', 'String', 'NothingType')\n\nBaseTypeName = operator.getitem(typing_extensions.Literal, BASE_TYPES)\n\nclass BaseTypeTrackerType(type):\n \n instantiated_base_type_tracker_classes: typing.List[weakref.ref] = []\n \n def __new__(meta, class_name: str, bases: typing.Tuple[type, ...], attributes: dict) -> type:\n \n updated_attributes = dict(attributes)\n assert 'tracked_type' in updated_attributes\n updated_attributes['base_type_to_value'] = {}\n result_class = type.__new__(meta, class_name, bases, updated_attributes)\n \n result_class_weakref = weakref.ref(result_class)\n meta.instantiated_base_type_tracker_classes.append(result_class_weakref)\n \n return result_class\n \n def __getitem__(cls, base_type_name: BaseTypeName) -> typing.Callable[[typing.Any], typing.Any]:\n def note_value(value: typing.Any) -> typing.Any:\n assert base_type_name not in cls.base_type_to_value\n assert isinstance(value, cls.tracked_type), f'{value} is not an instance of the tracked type {cls.tracked_type}'\n cls.base_type_to_value[base_type_name] = value\n return value\n return note_value\n \n def __getattr__(cls, base_type_name: BaseTypeName) -> typing.Callable[[typing.Any], typing.Any]:\n return cls[base_type_name]\n \n @classmethod\n def vaildate_base_types(meta) -> None:\n for instantiated_base_type_tracker_class_weakref in meta.instantiated_base_type_tracker_classes:\n instantiated_base_type_tracker_class = instantiated_base_type_tracker_class_weakref()\n instantiated_base_type_tracker_class_is_alive = instantiated_base_type_tracker_class is not None\n assert instantiated_base_type_tracker_class_is_alive\n assert len(BASE_TYPES) == len(instantiated_base_type_tracker_class.base_type_to_value.keys())\n assert all(key in BASE_TYPES for key in instantiated_base_type_tracker_class.base_type_to_value.keys())\n assert all(base_type in instantiated_base_type_tracker_class.base_type_to_value.keys() for base_type in BASE_TYPES)\n return\n\ndef sanity_check_base_types() -> None:\n BaseTypeTrackerType.vaildate_base_types()\n return \n\nclass TensorTypeParserElementBaseTypeTracker(metaclass=BaseTypeTrackerType):\n tracked_type: type = pyparsing.ParserElement\n\nclass AtomicLiteralParserElementBaseTypeTracker(metaclass=BaseTypeTrackerType):\n tracked_type: type = pyparsing.ParserElement\n\nclass LiteralASTNodeClassBaseTypeTracker(metaclass=BaseTypeTrackerType):\n tracked_type: type = type\n\n##########\n# Driver #\n##########\n\nif __name__ == '__main__':\n print(\"TODO add something here\")\n\n","sub_path":"static_autodiff/tibs/parser_utilities.py","file_name":"parser_utilities.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"8783138","text":"import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nimport pandas_datareader.data as web\nimport fix_yahoo_finance as yf\nyf.pdr_override()\nimport pandas as pd\npd.core.common.is_list_like = pd.api.types.is_list_like\nimport datetime\n\nfrom pandas import Series, DataFrame\n\n\n\n\nclass MyWindow(QWidget):\n def __init__(self):\n super().__init__()\n self.setupUI()\n\n def setupUI(self):\n self.setGeometry(600, 200, 1200, 600)\n self.setWindowTitle(\"PyChart Viewer v0.1\")\n self.setWindowIcon(QIcon('stock.png'))\n # 변수 정의\n # 결과 확인 \n self.statusLabel = QLabel(self)\n self.statusLabel.setText(\"종목코드 입력\")\n # 차트 그림 버튼\n self.pushButton = QPushButton(\"차트그리기\")\n self.pushButton.clicked.connect(self.pushButtonClicked) \n # 종목코드입력\n self.lineEdit1 = QLineEdit(\"\", self)\n #self.pushButton.clicked.connect(self.pushButtonClicked)\n # 시장 선택\n groupBox1 = QGroupBox(\"시장구분\", self)\n self.radio1 = QRadioButton(\"KOSPI\", self)\n self.radio1.setChecked(True)\n self.radio1.clicked.connect(self.radioButtonClicked)\n self.radio2 = QRadioButton(\"KOSDAQ\", self)\n self.radio2.clicked.connect(self.radioButtonClicked)\n \n # 기간 선택\n self.startDate = QLineEdit(\"\", self)\n self.endDate = QLineEdit(str(datetime.date.today()), self)\n groupBox2 = QGroupBox(\"조회기간\", self)\n\n # Left Layout\n self.fig = plt.Figure()\n self.canvas = FigureCanvas(self.fig)\n\n leftLayout = QVBoxLayout()\n leftLayout.addWidget(self.canvas)\n\n # Right Layout\n # 시장 선택 \n rightInner1 = QVBoxLayout()\n rightInner1.addWidget(self.radio1)\n rightInner1.addWidget(self.radio2)\n groupBox1.setLayout(rightInner1)\n # 기간 입력\n rightInner2 = QVBoxLayout()\n rightInner2.addWidget(self.startDate)\n rightInner2.addWidget(self.endDate)\n groupBox2.setLayout(rightInner2)\n # 우측 박스 구성\n rightLayout = QVBoxLayout()\n rightLayout.addWidget(self.pushButton)\n rightLayout.addWidget(self.lineEdit1)\n rightLayout.addWidget(groupBox1)\n rightLayout.addWidget(groupBox2)\n rightLayout.addWidget(self.statusLabel)\n rightLayout.addStretch(1)\n #전체구성\n layout = QHBoxLayout()\n layout.addLayout(leftLayout)\n layout.addLayout(rightLayout)\n layout.setStretchFactor(leftLayout, 1)\n layout.setStretchFactor(rightLayout, 0)\n\n self.setLayout(layout)\n\n def pushButtonClicked(self):\n # code = self.lineEdit1.text()\n if self.radio1.isChecked():\n ticker = self.lineEdit1.text() + '.KS'\n else:\n ticker = self.lineEdit1.text() + '.KQ'\n \n sDate = datetime.datetime.strptime(self.startDate.text(), \"%Y-%m-%d\").date()\n eDate = datetime.datetime.strptime(self.endDate.text(), \"%Y-%m-%d\").date()\n \n df = web.get_data_yahoo(ticker, sDate, eDate)\n df['MA20'] = df['Adj Close'].rolling(window=20).mean()\n df['MA60'] = df['Adj Close'].rolling(window=60).mean()\n\n ax = self.fig.add_subplot(111)\n ax.plot(df.index, df['Adj Close'], label='Adj Close')\n ax.plot(df.index, df['MA20'], label='MA20')\n ax.plot(df.index, df['MA60'], label='MA60')\n ax.legend(loc='upper right')\n ax.grid()\n\n self.canvas.draw()\n\n def radioButtonClicked(self):\n msg = \"\"\n if self.radio1.isChecked():\n msg = \"KS\"\n else:\n msg = \"KQ\"\n self.statusLabel.setText(msg)\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n window = MyWindow()\n window.show()\n app.exec_()","sub_path":"study_2nd/stock_query1.py","file_name":"stock_query1.py","file_ext":"py","file_size_in_byte":3997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"5822941","text":"# Variable <--> Tensor <--> numpy in pytorch\n\n# Torch 自称为神经网络界的 Numpy, 因为他能将 torch 产生的 tensor 放在 GPU 中加速运算\n# (前提是你有合适的 GPU), 就像 Numpy 会把 array 放在 CPU 中加速运算.\n\n# PyTorch 使用的技术为自动微分(automatic differentiation)。\n# 在这种机制下,系统会有一个 Recorder 来记录我们执行的运算,然后再反向计算对应的梯度。\n# 这种技术在构建神经网络的过程中十分强大,因为我们可以通过计算前向传播过程中参数的微分来节省时间。\n\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\n\n# fake data\nx = torch.linspace(-5, 5, 200) # data (tensor), shape=(100, 1)\nx = Variable(x) # transform to Variable\nx_np = x.data.numpy() # to plot the data format in torch can't be recognized by matplotlib. In order to plot, transforming to numpy data necessary\n\n# activation function\ny_relu = F.relu(x).data.numpy()\ny_sigmoid = torch.sigmoid(x).data.numpy()\ny_tanh = F.tanh(x).data.numpy()\ny_softplus = F.softplus(x).data.numpy()\n\n# y_softmax = F.softmax(x)\n# softmax is a special kind of activation function, it is about probability\n# and will make the sum as 1.\n\nplt.figure(1, figsize=(8, 6))\nplt.subplot(221)\nplt.plot(x_np, y_relu, c='red', label='relu')\nplt.ylim((-1, 5))\nplt.legend(loc='best')\n\nplt.subplot(222)\nplt.plot(x_np, y_sigmoid, c='red', label='sigmoid')\nplt.ylim((-0.2, 1.2))\nplt.legend(loc='best')\n\nplt.subplot(223)\nplt.plot(x_np, y_tanh, c='red', label='tanh')\nplt.ylim((-1.2, 1.2))\nplt.legend(loc='best')\n\nplt.subplot(224)\nplt.plot(x_np, y_softplus, c='red', label='softplus')\nplt.ylim((-0.2, 6))\nplt.legend(loc='best')\n\nplt.show()\n\n\n\nnp_data = np.arange(6).reshape((2, 3))\ntorch_data = torch.from_numpy(np_data) # transform np data to torch data, give numpy data (np_data) in form of ndarray (n-dimension array)\ntensor2array = torch_data.numpy() # transform tensor to numpy\n\nprint(\n '\\nnumpy array:', np_data,\n '\\ntorch tensor:', torch_data,\n '\\ntensor to array:', tensor2array,\n)\n\n\n\n'''math calculation in torch'''\ndata = [-1, -2, 1, 2]\ntensor = torch.FloatTensor(data) # 转换成32位浮点 tensor\n\n\n# abs 绝对值计算\ndata = [-1, -2, 1, 2]\ntensor = torch.FloatTensor(data) # 转换成32位浮点 tensor\nprint(\n '\\nabs',\n '\\nnumpy: ', np.abs(data), # [1 2 1 2]\n '\\ntorch: ', torch.abs(tensor) # [1 2 1 2]\n)\n\n# sin 三角函数 sin\nprint(\n '\\nsin',\n '\\nnumpy: ', np.sin(data), # [-0.84147098 -0.90929743 0.84147098 0.90929743]\n '\\ntorch: ', torch.sin(tensor) # [-0.8415 -0.9093 0.8415 0.9093]\n)\n\n# mean 均值\nprint(\n '\\nmean',\n '\\nnumpy: ', np.mean(data), # 0.0\n '\\ntorch: ', torch.mean(tensor) # 0.0\n)\n\n\n#除了简单的计算, 矩阵运算才是神经网络中最重要的部分. 所以我们展示下矩阵的乘法. 注意一下包含了一个 numpy 中可行, 但是 torch 中不可行的方式.\n# matrix multiplication 矩阵点乘\ndata = [[1, 2], [3, 4]]\ntensor = torch.FloatTensor(data) # 转换成32位浮点 tensor\n\n\n# matrix-dot-multiplication\nprint(\n '\\nmatrix multiplication (matmul)',\n '\\nnumpy: ', np.matmul(data, data), # [[7, 10], [15, 22]]\n '\\ntorch: ', torch.mm(tensor, tensor) # [[7, 10], [15, 22]]\n)\n\n# multiplication. multiply the corresponding positions\nprint(\n '\\ntorch: ', torch.mul(tensor, tensor) # torch 会转换成 [1,2,3,4].dot([1,2,3,4) = 30.0\n)\n\n\n\n\n# Variable can back-propagation, Tensor can't BP\ntensor = torch.FloatTensor([[1, 2], [3, 4]]) # define FloatTensor by using torch.FloatTensor()\nvariable = Variable(tensor, requires_grad=True) # 把鸡蛋放到篮子里. requires_grad: build grad graph\n\nt_out = torch.mean(tensor*tensor)\nv_out = torch.mean(variable*variable)\n\nprint(t_out)\nprint(v_out)\n\n# back-propagation means deviation back propagate\nv_out.backward()\nprint(variable.grad) # after v_out.backward(), check the grad of variable\nprint(variable.creator)\n\n\n\nprint(variable)\nprint(variable.data) # data in Variable is in form of Tensor. variable is in form of Variable\nprint(variable.data.numpy()) # transform variable.data (in form of tensor) to the form of numpy\n\n\n\n\n\n\n","sub_path":"morvan_pytorch/morvan_Varibale.py","file_name":"morvan_Varibale.py","file_ext":"py","file_size_in_byte":4279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"174622507","text":"from PIL import Image\nimport os\nimport numpy as np\n\nfrom warnings import filterwarnings\nfilterwarnings(\"error\",category=Warning)\n\nsiz=128\nhq=True\n\nanvil=Image.open('Anvil4096.png')\nanvil=anvil.resize((siz,siz))\n\nfor i in os.walk('.\\\\ba\\\\'):\n fl=i[2]#fl是文件名的列表\n\ndef divide(arr,nam):\n im=Image.new('RGBA', (arr.shape[1], arr.shape[0]), (255,255,255,255))\n for y in range(0,arr.shape[1],siz):\n for x in range(0,arr.shape[0],siz):\n darr=arr[x-siz:x,y-siz:y]\n try:\n n=np.mean(darr)/255\n except:\n continue\n if hq==False:\n im2=anvil.resize((int(anvil.width*n)+1,int(anvil.height*n)+1))\n else:\n im2=anvil.resize((int(anvil.width*n)+1,int(anvil.height*n)+1),Image.ANTIALIAS)\n im.paste(im2,(int(y-n*siz/2),int(x-n*siz/2)))\n im.save('.\\\\r\\\\'+nam.replace('.jpg','.png'))\n\ndef pic(fl=fl):\n frl=[]#帧列表(PIL对象)\n for num in range(int(input(\"断点>>>\")),len(fl)):\n i=fl[num]\n print(i)\n frl.append(Image.open('.\\\\ba\\\\'+i))\n arr=np.array(frl[-1])\n divide(arr,i)\n \npic()\n","sub_path":"main_final.py","file_name":"main_final.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"511252083","text":"\"\"\"Example app to login to GitHub\"\"\"\nimport http.cookiejar\n\nimport mechanicalsoup\n\nfrom settings import URL\n\nbrowser = mechanicalsoup.Browser()\n\n\n# def case_id_form(case):\n\n# for form in browser.forms():\n# if form.attrs['name'] == 'inquiryFormByCaseNum':\n# browser.form = form\n# break\n\n# browser.form['caseId'] = case\n# browser.submit()\n# response = browser.response().read()\n# browser.back()\n\n# return response\n\nbrowser = mechanicalsoup.Browser()\nlogin_page = browser.get(URL)\nlogin_form = mechanicalsoup.Form(login_page.soup.form)\nlogin_form.check({\"disclaimer\": ['Y']})\n\nresponse = browser.submit(login_form, URL)\nprint(response.soup)\n","sub_path":"tests/python3/mechanicalsoup_test.py","file_name":"mechanicalsoup_test.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"240701228","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as mlines\nimport pandas as pd\nimport seaborn as sns\nimport nibabel as nib\nimport cv2\nfrom scipy.ndimage import gaussian_filter\nfrom skimage.filters.rank import entropy\nfrom skimage.filters.rank import gradient\nfrom skimage.morphology import disk\nfrom skimage import feature\nimport scipy.ndimage as ndi\nimport scipy\nfrom skimage.feature import greycomatrix, greycoprops\nfrom skimage.measure import shannon_entropy\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef varpercent(valstart_, valend_):\n\treturn ((valend_ -valstart_)/valstart_)*100\n\n\ndef AES(img):\n\t\"\"\" \n\tAES(k)=sqrt{sum[E(Iij)(Gx^2(Iij)+Gy^2(Iij))]}/sum[E(Iij)]\n\t\t\n\t\tE(Iij)--> binary mask of the edges extracted using Canny edge detector \n\t\tGx -----> [-1 -1 -1; 0 0 0; 1 1 1]\n\t\tGy -----> [-1 0 1; -1 0 1; -1 0 1]\n\t\tG x , and G y represent the centered gradient kernels along x and y, respectively\n\t\tThe mean value across all the slices was considered for the analysis. When blurring increases,\n\t\tAES values decrease.\n\t\"\"\"\n\tGx = np.array([[-1,-1,-1],[0,0,0],[1,1,1]])\n\tGy = np.array([[-1,0,1],[-1,0,1],[-1,0,1]])\n\t## \n\tx = np.zeros((img.shape[2]))\n\t## \n\tfor kk in range(0, img.shape[2]):\n\t\ts = img[:,:,kk]\n\t\tE = feature.canny(s, sigma=0.6)\n\t\tE = E.astype(np.float64)\n\t\tfiltx = cv2.filter2D(s, -1, Gx)\n\t\tfilty = cv2.filter2D(s, -1, Gy)\n\t\taes_ = np.sqrt((E*((filtx**2)+(filty**2))).sum()) / E.sum()\n\t\tx[kk]=aes_\n\t\t\n\tx = x[~np.isnan(x)]\n\n\treturn x\n\ndef GradEntr_eval(img):\n\tx = np.zeros((img.shape[2]))\n\t## \n\tfor kk in range(0, img.shape[2]):\n\t\ts = img[:,:,kk]\n\t\t# s = s/s.max()\n\t\t# s =(np.uint8(s*255))\n\t\tentr_ = gradient(s, disk(3))\n\t\tentr_ = entr_/entr_.max()\n\t\tout = entropy(entr_, disk(3))\n\t\tx[kk]= out.sum()/(out.shape[0]*out.shape[1])\n\t\t\n\tx = x[~np.isnan(x)]\n\n\treturn x\n\ndef Haralick_eval(img):\n\tx = np.zeros((img.shape[2]))\n\tdistances = [3, 5, 7, 9, 11, 21]\n\tangles = [0, np.pi/4, np.pi/2, 3*np.pi/4]\n\t## \n\tfor kk in range(0, img.shape[2]):\n\t\ts = img[:,:,kk]\n\t\ts = s/s.max()\n\t\ttmp_ =(np.uint8(s*255))\n\t\tglcm = greycomatrix(tmp_, \n distances=distances, \n angles=angles,\n symmetric=False,\n normed=True)\n\n\t\ttmp= glcm.sum(axis=2).sum(axis=2)\n\t\tx[kk]= shannon_entropy(tmp)\n\t\t\n\tx = x[~np.isnan(x)]\n\n\treturn x\n# --------------------------------------------------------------------------------------------\n# load nii files\n\"\"\"\nclass_1_ = nib.load('./ref_vols_for_metrics_testing/xi27_class-1_T1.nii.gz').get_fdata()\nclass_2_ = nib.load('./ref_vols_for_metrics_testing/xi27_class-2_T1.nii.gz').get_fdata()\nclass_3_ = nib.load('./ref_vols_for_metrics_testing/xi27_class-3_T1.nii.gz').get_fdata()\n\n## normalize\nclass_1_ = class_1_/class_1_.max()\nclass_2_ = class_2_/class_2_.max()\nclass_3_ = class_3_/class_3_.max()\n## calculation metrics\naes_1_, aes_2_, aes_3_ = AES(class_1_), AES(class_2_), AES(class_3_)\ncge_1_, cge_2_, cge_3_ = GradEntr_eval(class_1_), GradEntr_eval(class_2_), GradEntr_eval(class_3_)\nhta_1_, hta_2_, hta_3_ = Haralick_eval(class_1_), Haralick_eval(class_2_), Haralick_eval(class_3_)\n\nnp.savetxt('AES_class_1_.txt', aes_1_, delimiter=' ')\nnp.savetxt('AES_class_2_.txt', aes_2_, delimiter=' ')\nnp.savetxt('AES_class_3_.txt', aes_3_, delimiter=' ')\n\nnp.savetxt('CGE_class_1_.txt', cge_1_, delimiter=' ')\nnp.savetxt('CGE_class_2_.txt', cge_2_, delimiter=' ')\nnp.savetxt('CGE_class_3_.txt', cge_3_, delimiter=' ')\n\nnp.savetxt('HTA_class_1_.txt', hta_1_, delimiter=' ')\nnp.savetxt('HTA_class_2_.txt', hta_2_, delimiter=' ')\nnp.savetxt('HTA_class_3_.txt', hta_3_, delimiter=' ')\n\"\"\"\n## --------------------------------------------------------------------------------------------\n\nsubj =['dl43','vq83','xi27']\nn_ =2 \n\naes_1_ = 100*np.loadtxt('./ref_vols_for_metrics_testing/'+str(subj[n_])+'/AES_class_1_.txt')\naes_2_ = 100*np.loadtxt('./ref_vols_for_metrics_testing/'+str(subj[n_])+'/AES_class_2_.txt')\naes_3_ = 100*np.loadtxt('./ref_vols_for_metrics_testing/'+str(subj[n_])+'/AES_class_3_.txt')\n\n\ncge_1_ = np.loadtxt('./ref_vols_for_metrics_testing/'+str(subj[n_])+'/CGE_class_1_.txt')\ncge_2_ = np.loadtxt('./ref_vols_for_metrics_testing/'+str(subj[n_])+'/CGE_class_2_.txt')\ncge_3_ = np.loadtxt('./ref_vols_for_metrics_testing/'+str(subj[n_])+'/CGE_class_3_.txt')\n\n# labels = ['OMTS ON\\nNo intentional\\nMotion', 'Sample 2', 'Sample 3']\nlabels = ['1', '2', '3']\nind = np.arange(len(labels))\nwidth = 0.5\nplt.figure(figsize = (6,3))\n# plt.subplot(331)\n# plt.imshow(sample_n_, cmap='gray', vmin=0, vmax=0.25)\n# plt.text(150,-10, 'Sample 1')\n# plt.text(650,-10, 'Sample 2')\n# plt.text(1150,-10, 'Sample 3')\n# plt.axis('off')\nfs_=10\nplt.subplot(121)\nplt.boxplot([aes_1_, aes_2_, aes_3_], notch=True, showfliers=False)\nplt.xticks([1, 2, 3],labels, fontsize=fs_, fontweight='bold')\n# plt.xticks([1, 2, 3],['','',''], fontsize=fs_, fontweight='bold')\nplt.yticks(fontsize=fs_, fontweight='bold')\nplt.ylim(0,0.7)\nplt.grid(True)\n# plt.title('Average Edge Strength', fontsize=fs_, fontweight='bold')\nplt.subplot(122)\nplt.boxplot([cge_1_, cge_2_, cge_3_], notch=True,showfliers=False)\nplt.xticks([1, 2, 3],labels, fontsize=fs_, fontweight='bold')\n#plt.xticks([1, 2, 3],['','',''], fontsize=fs_, fontweight='bold')\nplt.ylim(0,2.5)\nplt.yticks(fontsize=fs_, fontweight='bold')\nplt.grid(True)\n#plt.title('Gradient Entropy', fontsize=fs_, fontweight='bold')\nplt.tight_layout()\nplt.show()\n\n\"\"\"\nsubj =['dl43','vq83','xi27']\n\nclass1_aes, class2_aes, class3_aes = [],[],[]\nclass1_cge, class2_cge, class3_cge = [],[],[]\n\nfor ii in subj:\n\taes_1_ = 100*np.loadtxt('./ref_vols_for_metrics_testing/'+str(ii)+'/AES_class_1_.txt')\n\taes_2_ = 100*np.loadtxt('./ref_vols_for_metrics_testing/'+str(ii)+'/AES_class_2_.txt')\n\taes_3_ = 100*np.loadtxt('./ref_vols_for_metrics_testing/'+str(ii)+'/AES_class_3_.txt')\n\n\tclass1_aes.append(aes_1_)\n\tclass2_aes.append(aes_2_)\n\tclass3_aes.append(aes_3_)\n\n\tcge_1_ = np.loadtxt('./ref_vols_for_metrics_testing/'+str(ii)+'/CGE_class_1_.txt')\n\tcge_2_ = np.loadtxt('./ref_vols_for_metrics_testing/'+str(ii)+'/CGE_class_2_.txt')\n\tcge_3_ = np.loadtxt('./ref_vols_for_metrics_testing/'+str(ii)+'/CGE_class_3_.txt')\n\n\tclass1_cge.append(cge_1_)\n\tclass2_cge.append(cge_2_)\n\tclass3_cge.append(cge_3_)\n\nclass1_aes, class2_aes, class3_aes = np.asarray(class1_aes), np.asarray(class2_aes), np.asarray(class3_aes)\nclass1_cge, class2_cge, class3_cge = np.asarray(class1_cge), np.asarray(class2_cge), np.asarray(class3_cge)\n\"\"\"\n\n# plt.figure(1)\n# ax1 = plt.subplot(211)\n# ax1.boxplot(class1_aes, notch=True, showfliers=False, positions=[0.5,1.,1.5])\n# ax1.boxplot(class2_aes, notch=True, showfliers=False, positions=[2,2.5,3])\n# ax1.boxplot(class3_aes, notch=True, showfliers=False, positions=[3.5,4.0,4.5])\n# ax1.set_xlim(0, 5)\n# ax1.set_xticklabels([])\n# ax1.set_xticks([])\n# ax1.grid(True)\n\n## ----\n\n#ax2 = plt.subplot(212)\n#ax2.boxplot(class1_cge[0,:], notch=True, showfliers=False, positions=[0.5,1.,1.5])\n#ax2.boxplot(class2_cge[0,:], notch=True, showfliers=False, positions=[2,2.5,3])\n#ax2.boxplot(class3_cge[0,:], notch=True, showfliers=False, positions=[3.5,4.0,4.5])\n#ax2.set_xlim(0, 5)\n#ax2.set_xticklabels([])\n#ax2.set_xticks([])\n#ax2.grid(True)\n# plt.show()\n\n#bplot_aes_ = [np.mean(aes_1_), np.mean(aes_2_), np.mean(aes_3_)]\n#bplot_cge_ = [np.mean(cge_1_), np.mean(cge_2_), np.mean(cge_3_)]\n#bplot_hta_ = [np.mean(hta_1_), np.mean(hta_2_), np.mean(hta_3_)]\n\n#bplot_aessd_ = [np.std(aes_1_), np.std(aes_2_), np.std(aes_3_)]\n#bplot_cgesd_ = [np.std(cge_1_), np.std(cge_2_), np.std(cge_3_)]\n#bplot_htasd_ = [np.std(hta_1_), np.std(hta_2_), np.std(hta_3_)]\n\n\n\n\n\"\"\"\n\n\"\"\"\n\n# plt.bar(ind, menMeans, width, yerr=menStd)\n\"\"\"\nbb_aes_ = [varpercent(np.mean(aes_1_), np.mean(np.mean(aes_1_))), \n\t\t varpercent(np.mean(aes_1_), np.mean(np.mean(aes_2_))), \n\t\t varpercent(np.mean(aes_1_), np.mean(np.mean(aes_3_)))]\n\nbb_cge_ = [varpercent(np.mean(cge_1_), np.mean(np.mean(cge_1_))), \n\t\t varpercent(np.mean(cge_1_), np.mean(np.mean(cge_2_))), \n\t\t varpercent(np.mean(cge_1_), np.mean(np.mean(cge_3_)))]\n\nbb_hta_ = [varpercent(np.mean(hta_1_), np.mean(np.mean(hta_1_))), \n\t\t varpercent(np.mean(hta_1_), np.mean(np.mean(hta_2_))), \n\t\t varpercent(np.mean(hta_1_), np.mean(np.mean(hta_3_)))]\n\nplt.figure()\nplt.subplot(231)\nplt.boxplot([aes_1_, aes_2_, aes_3_], notch=True, showfliers=False)\n# plt.xticks_label(labels)\nplt.grid(True)\nplt.title('Average Edge Strength')\n# plt.bar(ind, bplot_aes_)#, width, yerr=bplot_aessd_)\nplt.subplot(232)\nplt.boxplot([cge_1_, cge_2_, cge_3_], notch=True,showfliers=False)\nplt.grid(True)\nplt.title('Gradient Entropy')\n# plt.bar(ind, bplot_cge_)#, width, yerr=bplot_cgesd_)\nplt.subplot(233)\nplt.boxplot([hta_1_, hta_2_, hta_3_],notch=True, showfliers=False)\nplt.grid(True)\nplt.title('Haralick''s Entropy')\n# plt.bar(ind, bplot_hta_)#, width, yerr=bplot_htasd_)\n\nplt.subplot(234)\nplt.bar(ind, bb_aes_)\nplt.subplot(235)\nplt.bar(ind, bb_cge_)\nplt.subplot(236)\nplt.bar(ind, bb_hta_)\n\n#plt.tight_layout()\nplt.show()\n\"\"\"\n# ------------------------\n\"\"\" calculation metrics\naes_1_, aes_2_, aes_3_ = AES(class_1_), AES(class_2_), AES(class_3_)\ncge_1_, cge_2_, cge_3_ = GradEntr_eval(class_1_), GradEntr_eval(class_2_), GradEntr_eval(class_3_)\nhta_1_, hta_2_, hta_3_ = Haralick_eval(class_1_), Haralick_eval(class_2_), Haralick_eval(class_3_)\n\nnp.savetxt('AES_class_1_.txt', aes_1_, delimiter=' ')\nnp.savetxt('AES_class_2_.txt', aes_2_, delimiter=' ')\nnp.savetxt('AES_class_3_.txt', aes_3_, delimiter=' ')\n\nnp.savetxt('CGE_class_1_.txt', cge_1_, delimiter=' ')\nnp.savetxt('CGE_class_2_.txt', cge_2_, delimiter=' ')\nnp.savetxt('CGE_class_3_.txt', cge_3_, delimiter=' ')\n\nnp.savetxt('HTA_class_1_.txt', hta_1_, delimiter=' ')\nnp.savetxt('HTA_class_2_.txt', hta_2_, delimiter=' ')\nnp.savetxt('HTA_class_3_.txt', hta_3_, delimiter=' ')\n\n\"\"\"","sub_path":"testing_metrics_classic.py","file_name":"testing_metrics_classic.py","file_ext":"py","file_size_in_byte":9777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"394699027","text":"from turtle import *\r\nspeed(10)\r\npensize(5)\r\nfor r in range(51):\r\n penup()\r\n goto(-400,300-r*5)\r\n pendown()\r\n for g in range(51):\r\n color(r/50, g/50, 0)\r\n forward(5)\r\nmainloop()\r\n","sub_path":"Quellen/python/8 Allerlei Q-Gruppenmitgliedern/farbverlauf_2param.py","file_name":"farbverlauf_2param.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"167881128","text":"import pandas as pd\npd.set_option('max_rows', 5)\nfrom learntools.core import binder; binder.bind(globals())\nfrom learntools.pandas.creating_reading_and_writing import *\nprint(\"Setup complete.\")\n\n#create dataframes \n\nfruits = pd.DataFrame({'Apples':[30],'Bananas':[21]})\nfruit_sales = pd.DataFrame({'Apples':[35,41], 'Bananas':[21,34]},index=['2017 Sales','2018 Sales'])\n\n\ningredients = pd.Series(['4 cups','1 cup','2 large','1 can'],index=['Flour','Milk','Eggs','Spam'],name='Dinner')\ningredients #just to check answer\n\nreviews = pd.read_csv(\"../input/wine-reviews/winemag-data_first150k.csv\",index_col=0)\nreviews\n\nanimals = pd.DataFrame({'Cows': [12, 20], 'Goats': [22, 19]}, index=['Year 1', 'Year 2'])\nanimals\nanimals.to_csv(\"cows_and_goats.csv\")\n","sub_path":"Data Manipulation/CSW.py","file_name":"CSW.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"431128427","text":"import pygame\nimport random\n\nfrom const import *\n\nclass bomb(pygame.sprite.Sprite):\n def __init__(self,game):\n super().__init__()\n\n #창의 넓이,높이\n self.game=game\n self.width=WIDTH\n self.height=HEIGHT\n\n #fire image 불러옴\n self.image=pygame.image.load(\"tile/flame_frames.png\").convert_alpha()\n self.image=pygame.transform.scale(self.image,(60,60))\n\n #위에서 떨어지는 폭탄\n def bomb_draw(self,screen,fire):\n\n self.mask=pygame.mask.from_surface(self.image)\n\n self.rect = self.image.get_rect()\n\n #좌표 = (fire[0],fire[1])\n self.rect.x=fire[0]\n self.rect.y=fire[1]\n\n #y로 1.5만큼 떨어짐\n fire[1]+=1.5\n\n #self와 배경의 땅과의 충돌 검사\n hits=pygame.sprite.spritecollide(self,self.game.platforms,False)\n #self와 캐릭터의 충돌 검사\n hits_character=pygame.sprite.spritecollide(self,self.game.player_group,False,pygame.sprite.collide_mask)\n\n if hits_character:\n pygame.quit()\n\n #충돌했다면\n if hits:\n fire[0]=random.randrange(0,900)\n fire[1]=40\n screen.blit(self.image,(fire[0],fire[1]))\n\n else:\n if fire[1]>600:\n fire[0]=random.randrange(0,900)\n fire[1]=random.randrange(0,600)\n screen.blit(self.image,(fire[0],fire[1]))\n\n else:\n screen.blit(self.image,(fire[0],fire[1]))\n\n\n\n #screen.blit(self.saw_tooth,(700,260))\n\nclass arrow(pygame.sprite.Sprite):\n def __init__(self,game,x,y):\n super().__init__()\n\n self.game=game\n \n #arrow image 불러옴\n self.arrow=pygame.image.load(\"tile/platform_tile_064.png\").convert_alpha()\n self.arrow=pygame.transform.scale(self.arrow,(60,20))\n\n #충돌 검사 위해 초기화\n self.rect = self.arrow.get_rect()\n self.mask=pygame.mask.from_surface(self.arrow)\n\n self.rect.x=x\n self.rect.y=y\n\n def arrow_player_detect(self):\n hits=pygame.sprite.spritecollide(self.game.player1,self.game.arrow_sprites,False,pygame.sprite.collide_mask)\n\n if hits:\n pygame.quit()","sub_path":"temp/trap.py","file_name":"trap.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"645934688","text":"import setuptools\n\n\nrequires = [\n 'eventlet>=0.9.17',\n 'kombu==1.0.4',\n 'django==1.4.5',\n 'pympler',\n 'iso8601',\n 'pyyaml',\n 'south',\n]\n\n\nsetuptools.setup(\n name='stacktash',\n version='1.0.0',\n url='https://github.com/gtt116/stacktash/',\n license='Apache 2.0',\n description=\"Stacktash\",\n author='gtt116',\n author_email='gtt116@gmali.com',\n packages=setuptools.find_packages(),\n install_requires=requires,\n include_package_data=True,\n py_modules=[],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"512948868","text":"from consts import *\n\ndef calc_combinations(current, i, all_combinations, D):\n if i + 1 > D:\n all_combinations.append(current)\n else:\n current[i] = 1\n calc_combinations(current[:], i + 1, all_combinations, D)\n current[i] = -1\n calc_combinations(current[:], i + 1, all_combinations, D) \n\ndef get_all_combinations(D=D):\n all_combinations = []\n init_state = [0] * D\n calc_combinations(init_state, 0, all_combinations, D)\n return all_combinations\n\ndef generate_samples(amount, D=D):\n return 2 * (np.random.randn(amount, D) > 0).astype(TYPE) - 1\n\ndef get_random_init_uniform_samples(set_size, D=D):\n x = (np.random.randn(set_size, D) > 0.0).astype(TYPE)\n x = 2 * (x-0.5)\n return x\n\nclass ReadOnceDNF():\n\n def __init__(self, partition=[], specifiec_DNF=None):\n if specifiec_DNF is not None:\n self.DNF = specifiec_DNF\n else:\n self.DNF = []\n for i in range(len(partition)):\n term = []\n for j in range(len(partition)):\n if i == j:\n term += [1] * partition[j]\n else:\n term += [0] * partition[j]\n self.DNF.append(np.array(term, dtype=TYPE))\n\n def get_label(self, x):\n for term in self.DNF:\n flag = True\n for i, literal in enumerate(term):\n if literal * x[i] == NEGATIVE:\n flag = False\n if flag:\n return POSITIVE\n return NEGATIVE\n\n def evaluate(self, X, Y):\n res = 0\n for (x, y) in zip(X, Y):\n if self.get_label(x) == y:\n res += 1\n return res / X.shape[0]","sub_path":"submission/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"191986785","text":"#!/usr/bin/python\n# coding=gbk\nimport sys\nimport os\nimport mConfig\nimport mCsv\nimport mCase\nimport mFile\nimport mUtils\nimport logging\n\ndef getInfo ():\n keyMap = {\"素材编号\":\"caseID\",\n \"主体长\":\"bodyHeight\",\n \"主体宽\":\"bodyWidth\",\n \"左右留边\":\"LRInterval\",\n \"上下留边\":\"TBInterval\",\n \"度数\":\"degree\",\n \"角半径\":\"cornerDegree\"\n };\n p = mConfig.GetCaseInfoPath ();\n\n if True != mFile.checkExist (p):\n logging.error (\"Get CaseID Info Error, Because Of Path Not Exist:\" + p);\n return {};\n return mCsv.ReadAFile (p, \"caseID\", keyMap);\n\n\ndef getCaseInfo (caseID):\n try:\n return getInfo ()[caseID];\n except:\n return None;\n\ndef getModul (caseID):\n if -1 == caseID.find (\"_\"):\n return caseID;\n else:\n return caseID.split(\"_\")[0];\n\ndef getModulPicSize (caseID):\n pixPerMM = mConfig.GetPixPerMM ();\n infos = getInfo ()\n if False == mUtils.dectHaveKey (infos, caseID):\n logging.error (\"can't find caseID:\" + caseID);\n return None;\n info = infos[caseID];\n\n size = {};\n size[\"bodyWidth_mm\"] = float(info[\"bodyWidth\"])*1.0;\n size[\"bodyHeight_mm\"] = float(info[\"bodyHeight\"])*1.0;\n size[\"bodyWidth_pix\"] = int(float(info[\"bodyWidth\"])*pixPerMM);\n size[\"bodyHeight_pix\"] = int(float(info[\"bodyHeight\"])*pixPerMM);\n size[\"body_pix\"] = (size[\"bodyWidth_pix\"], size[\"bodyHeight_pix\"]);\n\n size[\"width_mm\"] = float(info[\"bodyWidth\"])*1.0 - float(info[\"LRInterval\"]) * 2;\n size[\"height_mm\"] = float(info[\"bodyHeight\"])*1.0 - float(info[\"TBInterval\"]) * 2;\n size[\"width_pix\"] = int(size[\"width_mm\"]*pixPerMM);\n size[\"height_pix\"] = int(size[\"height_mm\"]*pixPerMM);\n size[\"wh_pix\"] = (size[\"width_pix\"], size[\"height_pix\"]);\n\n size[\"degree\"] = int(info[\"degree\"]);\n size[\"cornerDegree\"] = int(info[\"cornerDegree\"]);\n size[\"TBInterval_mm\"] = float(info[\"TBInterval\"]);\n size[\"LRInterval_mm\"] = float(info[\"LRInterval\"]);\n size[\"TBInterval_pix\"] = int(size[\"TBInterval_mm\"]*pixPerMM);\n size[\"LRInterval_pix\"] = int(size[\"LRInterval_mm\"]*pixPerMM);\n size[\"caseWidth_mm\"] = float(info[\"bodyWidth\"])*1.0;\n size[\"caseHeight_mm\"] = float(info[\"bodyHeight\"])*1.0;\n size[\"caseWidth_Pix\"] = int(size[\"caseWidth_mm\"]*pixPerMM);\n size[\"caseHeight_Pix\"] = int(size[\"caseHeight_mm\"]*pixPerMM);\n \n return size;\n\n\nif __name__ == \"__main__\":\n getInfo();\n print (getModulPicSize(\"i5s_tpu\"));\n","sub_path":"mCase.py","file_name":"mCase.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"420760415","text":"##############################################################################################################\n# GAUSSIAN DISTRIBUTION PROGRAM #\n##############################################################################################################\n\n##############################################################################################################\n# To plot the Gaussian curves of different sampling rate CSV file taken from Oscilloscope #\n##############################################################################################################\n\n# To call the different related libraries required for the program//\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n##############################################################################################################\n# To locate and read the files//\n\ncsvfile_location_1 = (r'D:/Python/VacuumData_Analysis/ForAcquired_Date[18.Dec.2019]viaAPD/1MSas/NoiseFree '\n r'RawData(1MSas)Set1.csv')\ncsvfile_location_2 = (r'D:/Python/VacuumData_Analysis/ForAcquired_Date[18.Dec.2019]viaAPD/2.5MSas/NoiseFree'\n r' RawData(2.5MSas)Set1.csv')\ncsvfile_location_3 = (r'D:/Python/VacuumData_Analysis/ForAcquired_Date[18.Dec.2019]viaAPD/3.15MSas/NoiseFree'\n r' RawData(3.15MSas)Set1.csv')\ncsvfile_location_4 = (r'D:/Python/VacuumData_Analysis/ForAcquired_Date[18.Dec.2019]viaAPD/6.25MSas/NoiseFree'\n r' RawData(6.25MSas)Set1.csv')\ncsvfile_location_5 = (r'D:/Python/VacuumData_Analysis/ForAcquired_Date[18.Dec.2019]viaAPD/10MSas/NoiseFree'\n r' RawData(10MSas)Set1.csv')\n\ncsvfile_read_1 = pd.read_csv(csvfile_location_1)\ncsvfile_read_2 = pd.read_csv(csvfile_location_2)\ncsvfile_read_3 = pd.read_csv(csvfile_location_3)\ncsvfile_read_4 = pd.read_csv(csvfile_location_4)\ncsvfile_read_5 = pd.read_csv(csvfile_location_5)\n\n# To print the first ten elements of all the columns of CSV files//\nprint(\"First 10 elements of all the columns of data file =\", csvfile_read_1.head(10))\nprint(\"First 10 elements of all the columns of data file =\", csvfile_read_2.head(10))\nprint(\"First 10 elements of all the columns of data file =\", csvfile_read_3.head(10))\nprint(\"First 10 elements of all the columns of data file =\", csvfile_read_4.head(10))\nprint(\"First 10 elements of all the columns of data file =\", csvfile_read_5.head(10))\n\n#############################################################################################################\nprint ('########################################################################################')\nprint ('######### To determine the statistical Values of the Different Sampled File #########')\nprint ('########################################################################################')\n\n# To determine the minimum values of the CSV data files//\ncsvfile_min_1 = csvfile_read_1.min()\nprint ('Min. value of the CSV data file1: '+ str(csvfile_min_1[0]))\ncsvfile_min_2 = csvfile_read_2.min()\nprint ('Min. value of the CSV data file2: '+ str(csvfile_min_2[0]))\ncsvfile_min_3 = csvfile_read_3.min()\nprint ('Min. value of the CSV data file3: '+ str(csvfile_min_3[0]))\ncsvfile_min_4 = csvfile_read_4.min()\nprint ('Min. value of the CSV data file4: '+ str(csvfile_min_4[0]))\ncsvfile_min_5 = csvfile_read_5.min()\nprint ('Min. value of the CSV data file5: '+ str(csvfile_min_5[0]))\n\n# To determine the maximum values of the CSV data files//\ncsvfile_max_1 = csvfile_read_1.max()\nprint ('Max value of the CSV data file1: '+ str(csvfile_max_1[0]))\ncsvfile_max_2 = csvfile_read_2.max()\nprint ('Max value of the CSV data file2: '+ str(csvfile_max_2[0]))\ncsvfile_max_3 = csvfile_read_3.max()\nprint ('Max value of the CSV data file3: '+ str(csvfile_max_3[0]))\ncsvfile_max_4 = csvfile_read_4.max()\nprint ('Max value of the CSV data file4: '+ str(csvfile_max_4[0]))\ncsvfile_max_5 = csvfile_read_5.max()\nprint ('Max value of the CSV data file5: '+ str(csvfile_max_5[0]))\n\n# To determine the mean values of the CSV data file//\ncsvfile_mean_1 = csvfile_read_1.mean()\nprint ('Mean value of the CSV data file1: '+ str(csvfile_mean_1[0]))\ncsvfile_mean_2 = csvfile_read_2.mean()\nprint ('Mean value of the CSV data file2: '+ str(csvfile_mean_2[0]))\ncsvfile_mean_3 = csvfile_read_3.mean()\nprint ('Mean value of the CSV data file3: '+ str(csvfile_mean_3[0]))\ncsvfile_mean_4 = csvfile_read_4.mean()\nprint ('Mean value of the CSV data file4: '+ str(csvfile_mean_4[0]))\ncsvfile_mean_5 = csvfile_read_5.mean()\nprint ('Mean value of the CSV data file5: '+ str(csvfile_mean_5[0]))\n\n# To determine the standard deviation values of the CSV data files//\ncsvfile_std_1 = csvfile_read_1.std()\nprint ('Standard deviation of the CSV data file1: '+ str(csvfile_std_1[0]))\ncsvfile_std_2 = csvfile_read_2.std()\nprint ('Standard deviation of the CSV data file2: '+ str(csvfile_std_2[0]))\ncsvfile_std_3 = csvfile_read_3.std()\nprint ('Standard deviation of the CSV data file3: '+ str(csvfile_std_3[0]))\ncsvfile_std_4 = csvfile_read_4.std()\nprint ('Standard deviation of the CSV data file4: '+ str(csvfile_std_4[0]))\ncsvfile_std_5 = csvfile_read_5.std()\nprint ('Standard deviation of the CSV data file5: '+ str(csvfile_std_5[0]))\n\n'''\n For reference related to this program check the mentioned URL's attached herein below:\n https://www.science-emergence.com/Articles/How-to-plot-a-normal-distribution-with-matplotlib-in-python-/\n https://machinelearningmastery.com/quick-and-dirty-data-analysis-with-pandas/\n https://realpython.com/python-histograms/\n https://codefellows.github.io/sea-python-401d2/lectures/stats_day2.html\n\n'''\n#############################################################################################################\nprint ('########################################################################################')\nprint ('########### To Plot the Gaussian Distribtuion on the CSV Data based Files ##########')\nprint ('########################################################################################')\n\n# To define the function over different variables//\ndef gaussian(x, mean, std):\n return (1/ np.sqrt(2 * np.pi * std**2)* np.exp(-0.5 *((x - mean)/ std)**2)) # The same defined function\n # will work for each of the different CSV files//\n\n# To define the range between which the gaussian curve will plot, i.e. from -0.25 to +0.25, with total count\n# same as of the data file counts//\nx1 = np.linspace(-0.25, 0.25, int(csvfile_read_1.count()))\nx2 = np.linspace(-0.25, 0.25, int(csvfile_read_2.count()))\nx3 = np.linspace(-0.25, 0.25, int(csvfile_read_3.count()))\nx4 = np.linspace(-0.25, 0.25, int(csvfile_read_4.count()))\nx5 = np.linspace(-0.25, 0.25, int(csvfile_read_5.count()))\n\nw = 5.0 \nh = 4.0\nd = 70 \nplt.figure(figsize=(w, h), dpi=d) # To plot the figure//\nplt.subplots_adjust(left=0.155)\nplt.subplots_adjust(bottom=0.15)\nplt.plot(x1, gaussian(x1, csvfile_mean_1[0], csvfile_std_1[0]), color='blue', label=\"1MSa/s\")\nplt.plot(x2, gaussian(x2, csvfile_mean_2[0], csvfile_std_2[0]), color='coral', label=\"2.5MSa/s\")\nplt.plot(x3, gaussian(x3, csvfile_mean_3[0], csvfile_std_3[0]), color='red', label=\"3.15MSa/s\")\nplt.plot(x4, gaussian(x4, csvfile_mean_4[0], csvfile_std_4[0]), color='cyan', label=\"6.25MSa/s\")\nplt.plot(x5, gaussian(x5, csvfile_mean_5[0], csvfile_std_5[0]), color='magenta', label=\"10MSa/s\")\nplt.xlabel(\"$x$\", fontsize=16)\nplt.ylabel(\"$p(x)$\", fontsize=16)\nplt.legend()\nplt.grid('on')\nplt.show()\n","sub_path":"GAUSSIAN,Distribtuion.py","file_name":"GAUSSIAN,Distribtuion.py","file_ext":"py","file_size_in_byte":7542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"15997209","text":"#!/usr/bin/env python\nimport zmq, json, time, random, socket, struct\n\ncontext = zmq.Context()\nzsock = context.socket(zmq.PUB)\nzsock.bind(\"tcp://0.0.0.0:9898\")\n\nharvester = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )\nharvester.bind( (\"0.0.0.0\", 9899) )\nwhile True:\n data, _ = harvester.recvfrom(1024)\n header = data[:struct.calcsize(\"LL\")]\n (version, message) = struct.unpack(\"LL\", header)\n data = data[ struct.calcsize(\"LL\"):]\n if version == 1 and message == 1: # bfsSend message\n (fromId, toId, sequence, nbytes) = struct.unpack(\"LLLL\", data)\n zsock.send(json.dumps( {'type' : 'bfsSend',\n 'from' : fromId,\n 'to' : toId,\n 'size' : nbytes } ) )\n elif version == 1 and message == 100: # gridftp notification\n (fromId, toId, bytes, duration) = struct.unpack(\"LLLL\", data)\n zsock.send(json.dumps({'type' : 'gridftpDone',\n 'from' : fromId,\n 'to' : toId,\n 'size' : nbytes,\n 'duration' : duration } ) )\n\n ","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"509736582","text":"def read_tokens():\n return input().strip().split(' ')\n\n\ndef read_ints():\n return [int(s) for s in read_tokens()]\n\n\ndef process_subset(arr, sofar):\n sum_so_far = 0\n for idx, el in enumerate(sofar):\n if el == 1:\n sum_so_far += arr[idx]\n\n return sum_so_far\n\n\ndef compute_subset(n, arr, sofar, ans):\n if not ans: # without this check it doesnt work\n if not n:\n curr_sum = process_subset(arr, sofar)\n if curr_sum != 0 and curr_sum % 2 == 0:\n ans.append(sofar)\n else:\n compute_subset(n-1, arr, sofar + [0], ans)\n compute_subset(n-1, arr, sofar + [1], ans)\n\n\nT, = read_ints()\nfor test in range(T):\n n, = read_ints()\n arr = read_ints()\n ans = []\n compute_subset(len(arr), arr, [], ans)\n if not ans:\n print(-1)\n else:\n first = ans[0]\n c = sum(1 for el in first if el == 1)\n print(c)\n for idx, el in enumerate(first):\n if el == 1:\n print(f\"{idx+1} \", end='')\n print()\n","sub_path":"recursion/28-1323A.py","file_name":"28-1323A.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"144011609","text":"#!/usr/bin/python3\n\nimport subprocess\nimport sys\n\n# This will likely get replaced with optparse someday\nif len(sys.argv) < 2:\n print(\"Please specify interface.\")\n sys.exit(1)\n\niface = sys.argv[1]\n\n# This is the command line for tshark to do the heavy lifting\n# The key bit for us is the \"-l\" flag to ensure the buffer gets\n# flushed on every line.\n\ntshark_cmd = [\"tshark\",\n \"-i\", iface,\n \"-p\", \"-n\", \"-Q\", \"-l\",\n \"-Y\", \"dhcpv6.msgtype==7 && dhcpv6.iaprefix.pref_addr\",\n \"-T\", \"fields\",\n \"-e\", \"ipv6.dst\",\n \"-e\", \"dhcpv6.iaprefix.pref_addr\",\n \"-e\", \"dhcpv6.iaprefix.pref_len\",\n \"--\", \"ip6 and udp and dst port 546\"]\n\n# Fire up tshark, making sure we are in text mode and line buffered\ntshark_p = subprocess.Popen(tshark_cmd, stdout=subprocess.PIPE,\n bufsize=1, universal_newlines=True)\n\n# The main loop\nwhile tshark_p.poll() is None:\n tshark_line = tshark_p.stdout.readline().rstrip(\"\\n\")\n try:\n (lease_dest, lease_prefix, lease_len) = tshark_line.split('\\t')\n except ValueError:\n print(\"Got a bad line from tshark\")\n\n # Format our lease for easier comparison later\n lease_f = \"{}/{}\".format(lease_prefix, lease_len)\n\n # Add or update route\n add_route_cmd = [\"ip\", \"-6\", \"route\", \"replace\",\n lease_f, \"via\", lease_dest, \"dev\", iface]\n\n print(\"Adding route {} via {}\".format(lease_f, lease_dest))\n\n # This should be subprocess.run in Python 3.5\n subprocess.call(add_route_cmd)\n\n# end while\n","sub_path":"d6rm.py","file_name":"d6rm.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"445331743","text":"from miller_rabin import Miller_Rabin_test\nfrom random import getrandbits\n\n\n# Функция для генерации простого числа\n# По умолчанию, размер числа равен 170 бит\ndef search_prime_number(bit_length = 170):\n # Флаг простоты числа\n is_prime = False\n # Простое случайное число размером bit_length бит\n random_prime_number = None\n # Пока не получим простое число\n while not is_prime:\n # Создаём случайное число размером bit_length бит\n random_prime_number = getrandbits(bit_length)\n # Проверяем его на простоту\n is_prime = Miller_Rabin_test(random_prime_number)\n # Возвращаем случайное простое число\n return random_prime_number\n","sub_path":"prime_numbers.py","file_name":"prime_numbers.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"164489727","text":"from backend.src.playsSeperator import playsSeperator\nfrom backend.src.dataCollector import dataCollector\n\ndata_collector = dataCollector()\ndata = data_collector.readfile(\"https://github.com/jayeshjakkani/American-Football-Analytics-Application/blob/master/backend/src/NCSU.csv?raw=true\")\nplay_separator = playsSeperator()\nplays = play_separator.getDataframesByPlays(\"NCST\", data,'Season','2019')\n\ndef test02():\n for k, v in plays.items():\n assert v is not None\n","sub_path":"tests/test_playsSeperator.py","file_name":"test_playsSeperator.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"602673080","text":"import quopri\nfrom framework.core import Application, DebugApplication, MockApplication\nfrom framework.templater import render\nfrom framework.saver import save_to_file\nfrom models import WebInterface\nfrom framework.log import Logger, debug\n\n\ndef secret_front(request):\n request['secret'] = 'some secret'\n\n\ndef about_front(request):\n request['key'] = 'key'\n\n\ndef contacts_front(request):\n request['phone'] = '+7-999-123-45-67'\n request['address'] = 'Москва, Лениградское ш. 16А'\n\n\nfronts = {'secret_front': secret_front, 'other_front': about_front, 'contacts': contacts_front}\n\n# app = Application(fronts)\napp = DebugApplication(fronts)\n# app = MockApplication(fronts)\nweb = WebInterface()\nlogger = Logger('main')\n\n\ndef decode_value(val):\n val_b = bytes(val.replace('%', '=').replace(\"+\", \" \"), 'UTF-8')\n val_decode_str = quopri.decodestring(val_b)\n return val_decode_str.decode('UTF-8')\n\n\n@app.add_route('/')\ndef view_index(request):\n logger.log('view_index')\n request['title'] = 'Главная'\n return '200 OK', render('templates/index.html', object_list=request)\n\n\n@app.add_route('/about')\ndef view_about(request):\n logger.log('view_about')\n request['title'] = 'О нас'\n return '200 OK', render('templates/about.html', object_list=request)\n\n\n@app.add_route('/contacts')\ndef view_contacts(request):\n logger.log('view_contacts')\n request['title'] = 'Контакты'\n if request['method'] == 'POST':\n data = request['data']\n title = ''.join(data['title'])\n text = ''.join(data['text'])\n email = ''.join(data['email'])\n print(f'{title}, {text}, {email}')\n if title or text or email:\n save_to_file(f'{title}, {text}, {email}')\n return '200 OK', render('templates/contacts.html', object_list=request)\n\n\n@app.add_route('/categories')\ndef view_create_category(request):\n logger.log('view_create_category')\n request['title'] = 'Категории'\n request['categories'] = web.categories\n if request['method'] == 'POST':\n data = request['data']\n try:\n name = data['name']\n except:\n return '400 BAD_REQUEST', render('templates/categories.html', object_list=request)\n new_category = web.create_category(name)\n web.categories.append(new_category)\n request['categories'] = web.categories\n return '201 CREATED', render('templates/categories.html', object_list=request)\n return '200 OK', render('templates/categories.html', object_list=request)\n\n\n@app.add_route('/create_course')\ndef view_create_course(request):\n logger.log('view_create_course')\n request['title'] = 'Создать курс'\n request['categories'] = web.categories\n if request['method'] == 'POST':\n data = request['data']\n try:\n name = data['name']\n except:\n return '400 BAD_REQUEST', render('templates/categories.html', object_list=request)\n category_id = data.get('category_id')\n if category_id:\n category = web.find_category_by_id(int(category_id[0]))\n course = web.create_course('record', name, category)\n web.courses.append(course)\n request['categories'] = web.categories\n return '200 OK', render('templates/create_course.html', object_list=request)\n\n\n@app.add_route('/courses')\ndef view_list_courses(request):\n logger.log('view_list_courses')\n request['title'] = 'Курсы'\n request['courses'] = web.courses\n return '200 OK', render('templates/list_course.html', object_list=request)\n\n\n@app.add_route('/student_add')\ndef view_student_add(request):\n request['title'] = 'Запись на курс'\n request['courses'] = web.courses\n request['students'] = web.students\n if request['method'] == 'POST':\n data = request['data']\n print(request)\n course_name = data['course_name']\n print(course_name)\n course = web.get_course(course_name)\n print(course)\n student_name = data['student_name']\n student = web.get_student(student_name)\n course.add_student(student)\n return '200 OK', render('templates/add_student.html', object_list=request)\n\n\n@app.add_route('/student_create')\ndef view_student_add(request):\n request['title'] = 'Создать студента'\n if request['method'] == 'POST':\n data = request['data']\n name = data['name']\n new_obj = web.create_user('student', name)\n web.students.append(new_obj)\n return '200 OK', render('templates/create_student.html', object_list=request)\n\n\n@app.add_route('/student_list')\ndef view_student_add(request):\n request['title'] = 'Список студентов'\n request['students'] = web.students\n return '200 OK', render('templates/list_student.html', object_list=request)\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"120402491","text":"#!/usr/bin/python\n\"\"\"\nProposals data model\n\"\"\"\nfrom peewee import TextField, CharField, Expression, OP\nfrom metadata.rest.orm import CherryPyAPI\nfrom metadata.orm.utils import ExtendDateTimeField, ExtendDateField\nfrom metadata.orm.utils import datetime_converts, date_converts, datetime_now_nomicrosecond\n\n# pylint: disable=too-many-instance-attributes\nclass Proposals(CherryPyAPI):\n \"\"\"\n Proposals data model\n\n Attributes:\n +-------------------+-------------------------------------+\n | Name | Description |\n +===================+=====================================+\n | title | Title of the proposal |\n +-------------------+-------------------------------------+\n | abstract | Long abstract of the proposal |\n +-------------------+-------------------------------------+\n | science_theme | science group or theme assigned to |\n +-------------------+-------------------------------------+\n | proposal_type | kind or type of proposal |\n +-------------------+-------------------------------------+\n | submitted_date | date proposal entered the system |\n +-------------------+-------------------------------------+\n | accepted_date | date proposal was accepted |\n +-------------------+-------------------------------------+\n | actual_start_date | date the proposal was started |\n +-------------------+-------------------------------------+\n | actual_end_date | date the proposal was ended |\n +-------------------+-------------------------------------+\n | closed_date | date the proposal was terminated |\n +-------------------+-------------------------------------+\n | encoding | encoding of the other text attrs |\n +-------------------+-------------------------------------+\n \"\"\"\n id = CharField(primary_key=True)\n title = TextField(default=\"\")\n abstract = TextField(default=\"\")\n science_theme = CharField(null=True)\n proposal_type = CharField(default=\"\")\n submitted_date = ExtendDateTimeField(default=datetime_now_nomicrosecond)\n accepted_date = ExtendDateField(null=True)\n actual_start_date = ExtendDateField(null=True)\n actual_end_date = ExtendDateField(null=True)\n closed_date = ExtendDateField(null=True)\n encoding = CharField(default=\"UTF8\")\n\n @staticmethod\n def elastic_mapping_builder(obj):\n \"\"\"\n Build the elasticsearch mapping bits\n \"\"\"\n super(Proposals, Proposals).elastic_mapping_builder(obj)\n obj['title'] = obj['abstract'] = obj['science_theme'] = obj['proposal_type'] = \\\n obj['encoding'] = {'type': 'string'}\n\n obj['submitted_date'] = \\\n {'type': 'date', 'format': \"yyyy-mm-dd'T'HH:mm:ss\"}\n\n obj['actual_start_date'] = obj['accepted_date'] = \\\n obj['actual_end_date'] = obj['closed_date'] = \\\n {'type': 'date', 'format': \"yyyy-mm-dd\"}\n\n def to_hash(self):\n \"\"\"\n Converts the object to a hash\n \"\"\"\n obj = super(Proposals, self).to_hash()\n obj['_id'] = unicode(self.id)\n obj['title'] = unicode(self.title)\n obj['abstract'] = unicode(self.abstract)\n obj['science_theme'] = unicode(self.science_theme)\n obj['proposal_type'] = unicode(self.proposal_type)\n obj['submitted_date'] = self.submitted_date.isoformat()\n obj['actual_start_date'] = self.actual_start_date.isoformat() \\\n if self.actual_start_date is not None else None\n obj['accepted_date'] = self.accepted_date.isoformat() \\\n if self.accepted_date is not None else None\n obj['actual_end_date'] = self.actual_end_date.isoformat() \\\n if self.actual_end_date is not None else None\n obj['closed_date'] = self.closed_date.isoformat() \\\n if self.closed_date is not None else None\n obj['encoding'] = str(self.encoding)\n return obj\n\n def from_hash(self, obj):\n \"\"\"\n Converts the hash to the object\n \"\"\"\n super(Proposals, self).from_hash(obj)\n # pylint: disable=invalid-name\n if '_id' in obj:\n self.id = unicode(obj['_id'])\n # pylint: enable=invalid-name\n if 'title' in obj:\n self.title = unicode(obj['title'])\n if 'abstract' in obj:\n self.abstract = unicode(obj['abstract'])\n if 'science_theme' in obj:\n self.science_theme = unicode(obj['science_theme'])\n if 'proposal_type' in obj:\n self.proposal_type = unicode(obj['proposal_type'])\n if 'encoding' in obj:\n self.encoding = str(obj['encoding'])\n self._set_datetime_part('submitted_date', obj)\n self._set_date_part('accepted_date', obj)\n self._set_date_part('actual_start_date', obj)\n self._set_date_part('actual_end_date', obj)\n self._set_date_part('closed_date', obj)\n\n def where_clause(self, kwargs):\n \"\"\"\n PeeWee specific where clause used for search.\n \"\"\"\n where_clause = super(Proposals, self).where_clause(kwargs)\n for date_key in ['accepted_date',\n 'actual_start_date', 'actual_end_date']:\n if date_key in kwargs:\n date_obj = date_converts(kwargs[date_key])\n where_clause &= Expression(getattr(Proposals, date_key), OP.EQ, date_obj)\n for date_key in ['submitted_date']:\n if date_key in kwargs:\n date_obj = datetime_converts(kwargs[date_key])\n where_clause &= Expression(getattr(Proposals, date_key), OP.EQ, date_obj)\n if '_id' in kwargs:\n where_clause &= Expression(Proposals.id, OP.EQ, kwargs['_id'])\n for key in ['title', 'abstract', 'science_theme', 'proposal_type', 'encoding']:\n if key in kwargs:\n where_clause &= Expression(getattr(Proposals, key), OP.EQ, kwargs[key])\n return where_clause\n","sub_path":"metadata/orm/proposals.py","file_name":"proposals.py","file_ext":"py","file_size_in_byte":6096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"330239926","text":"#! /usr/bin/python3\nimport os, logging, time, websocket, json, hmac\nfrom parameters import *\nos.chdir('') # Put your working directory\nfrom telegram import Bot # pip install python-telegram-bot --upgrade\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nbot=Bot(botToken)\n\ndef on_open(ws):\n ts = int(time.time() * 1000)\n login={'op': 'login', 'args': {\n 'key': api,\n 'sign': hmac.new(\n secret.encode(), f'{ts}websocket_login'.encode(), 'sha256').hexdigest(),\n 'time': ts,\n }}\n\n ws.send(json.dumps(login))\n channel_data = {'op': 'subscribe', 'channel': 'fills'}\n ws.send(json.dumps(channel_data))\n\n\ndef on_message(ws,message):\n json_message=json.loads(message)\n try:\n data=json_message['data']\n price=data['price']\n size=data['size']\n side=data['side']\n market=data['market']\n fee=data['fee']\n liquidity=data['liquidity']\n \n bot.sendMessage(chatId, f\"A {market} order got filled\")\n bot.sendMessage(chatId,f\"Market = {market} | Price = {price} | Size = {size} | Side = {side} | Liquidity = {liquidity} | Fee = {fee}\")\n\n except:\n pass\n","sub_path":"tgFills.py","file_name":"tgFills.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"531834816","text":"import sys\nimport pickle\nfrom signal import SIGINT\nimport signal\nimport os\nfrom pathlib import Path\n\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nimport rehash\nfrom tqdm import tqdm\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n# Head request to get file-length and check whether it supports ranges.\ndef get_file_info_from_server(url):\n try:\n headers={\"Accept-Encoding\": \"identity\"} # Avoid dealing with gzip\n response = requests.head(url, headers=headers) \n response.raise_for_status()\n content_length = None\n # tqdm.write(f\"{response.headers}\")\n if \"Content-Length\" in response.headers:\n content_length = int(response.headers['Content-Length'])\n accept_ranges = (response.headers.get(\"Accept-Ranges\") == \"bytes\")\n return accept_ranges, content_length\n except Exception as ex:\n tqdm.write(f\"HEAD Request Error: {ex}\")\n return False, None\n\n# Support 3 retries and backoff\nretry_strategy = Retry(\n total=3,\n backoff_factor=1,\n status_forcelist=[429, 500, 502, 503, 504],\n method_whitelist=[\"HEAD\", \"GET\", \"OPTIONS\"]\n)\nadapter = HTTPAdapter(max_retries=retry_strategy)\nsession = requests.Session()\nsession.mount(\"https://\", adapter)\nsession.mount(\"http://\", adapter)\n\nterminate = False\ndef handler(signal_received, frame):\n global terminate\n terminate = True\n\nchunk_size = 1024*1024\n\ndef download_file_full(url, local_file, content_length):\n try:\n checksum = rehash.sha256()\n headers = {\"Accept-Encoding\": \"identity\"} # Avoid dealing with gzip\n with tqdm(total=content_length, unit=\"byte\", unit_scale=1) as progress, \\\n session.get(url, headers=headers, stream=True, timeout=5) as response, \\\n open(local_file, 'b') as file_out:\n\n response.raise_for_status()\n\n for chunk in response.iter_content(chunk_size):\n if terminate:\n sys.exit(0)\n\n file_out.write(chunk)\n checksum.update(chunk)\n progress.update(len(chunk))\n\n except Exception as ex:\n tqdm.write(f\"Download error: {ex}\")\n return None\n\n return checksum.hexdigest()\n\ndef download_file_resumable(url, local_file, content_length):\n # Always go off the checkpoint as the file was flushed before writing.\n download_checkpoint = local_file + \".ckpnt\"\n try:\n resume_point, checksum = pickle.load(open(download_checkpoint, \"rb\"))\n tqdm.write(\"File already exists, resuming download.\")\n except:\n resume_point = 0\n checksum = rehash.sha256()\n if os.path.exists(local_file):\n os.remove(local_file)\n Path(local_file).touch()\n\n assert (resume_point < content_length)\n\n # Support resuming\n headers = {}\n headers[\"Range\"] = f\"bytes={resume_point}-\"\n headers[\"Accept-Encoding\"] = \"identity\" # Avoid dealing with gzip\n\n try:\n with tqdm(total=content_length, unit=\"byte\", unit_scale=1) as progress, \\\n session.get(url, headers=headers, stream=True, timeout=5) as response, \\\n open(local_file, 'r+b') as file_out:\n\n response.raise_for_status()\n progress.update(resume_point)\n file_out.seek(resume_point)\n\n for chunk in response.iter_content(chunk_size):\n if terminate:\n sys.exit(0)\n\n file_out.write(chunk)\n file_out.flush()\n resume_point += len(chunk)\n checksum.update(chunk) \n pickle.dump((resume_point, checksum), open(download_checkpoint,\"wb\"))\n progress.update(len(chunk))\n\n os.remove(download_checkpoint)\n\n except Exception as ex:\n tqdm.write(f\"Download error: {ex}\")\n return False\n\n return checksum.hexdigest()\n\n# In order to avoid leaving extra garbage meta files behind this will \n# will overwrite any existing files found at local_file. If you don't want this\n# behaviour you can handle this externally.\ndef download_file(url, local_file, expected_checksum=None):\n # Handle SIGINT nicely\n previous_signal_int = signal.signal(SIGINT, handler)\n\n success = False\n try:\n max_retries = 3\n accept_ranges, content_length = get_file_info_from_server(url)\n if accept_ranges and content_length:\n download_method = download_file_resumable\n tqdm.write(\"Server supports resume\")\n else:\n download_method = download_file_full\n tqdm.write(\"Server doesn't support resume\")\n \n for i in range(max_retries):\n checksum = download_method(url, local_file, content_length)\n if checksum:\n tqdm.write(f\"File downloaded. Checksum: {checksum}\")\n if expected_checksum and expected_checksum != checksum:\n tqdm.write(f\"Checksum doesn't match. Expecting: {expected_checksum}\")\n continue\n\n success = True\n break\n\n except Exception as ex:\n tqdm.write(f\"Unexpected Error: {ex}\")\n finally:\n if terminate:\n tqdm.write('SIGINT or CTRL-C detected, stopping.')\n\n signal.signal(SIGINT, previous_signal_int)\n return success","sub_path":"best_download/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"15893257","text":"#!/usr/bin/python2 \n# -*- coding: utf-8 -*-\n\nfrom pyspark import SparkContext \nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import to_date, to_timestamp,months_between,current_timestamp,date_format,month,lit\nfrom pyspark.sql import functions as F\n#获得数据\nspark = SparkSession.builder.master(\"local[4]\").appName(\"pssql04\").getOrCreate()\ndf = spark.read.csv(\"file:///home/hadoop/Desktop/pyspark/1.txt\",header=None,encoding=\"utf-8\",inferSchema=True,sep=\"\\t\")#.drop_duplicates()\n\n\n#执行sql查询1\nsc=df.select(df[4].alias(\"gender\"))\nsc1=sc[sc.gender.isNotNull()].groupBy(\"gender\").count()\nsc2=sc1.select(sc1.gender,sc1[1].alias(\"num\"))\nsc2.createOrReplaceTempView(\"Tur_db\")\nq=\"\"\"select gender,num,num/CAST(SUM(num) over() as float) as pc\nfrom Tur_db\ngroup by gender,num\n\"\"\"\nspark.sql(q).show()\n\n","sub_path":"N&E local/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"145404567","text":"\"\"\" tahua.api.lib.api_helper\n\n This module defines various helper functions to make it easier to process\n API requests.\n\"\"\"\nimport base64\nfrom hashlib import sha256\nfrom zlib import crc32\n\nimport simplejson as json\n\nfrom django.http import HttpResponseBadRequest,HttpResponse\nfrom django.db import transaction\n\n#from tahua.lib import aesWrapper\n\nfrom tahua.models import Session, Client\n\n#############################################################################\n\ndef process_request(request):\n \"\"\" Process an API request.\n\n The parameters are as follows:\n\n 'request'\n\n The HttpRequest object passed to the API view function.\n\n We attempt to extract and validate the supplied payload, and then check\n that all the required fields are present in the payload.\n\n Upon completion, we return a dictionary representing the processed\n request payload. This dictionary will have the following entries:\n\n 'error'\n\n If this is present, an error occurred while validating the\n request. This will be an HttpResponseBadRequest object\n suitable for return back to the caller.\n\n 'callback'\n\n The value of the request's \"callback\" parameter, if supplied.\n\n 'client'\n\n The Client object associated with this request.\n\n 'session'\n\n The Session object associated with this request, or None if no\n session is associated with this request.\n\n 'request_key'\n\n The current request key.\n\n 'fields'\n\n A dictionary containing the supplied payload fields.\n \"\"\"\n if request.method == \"GET\":\n params = request.GET\n else:\n params = request.POST\n\n # The following helper function makes it easier to return an API request\n # error back to the caller.\n\n def request_error(request_payload, err_msg):\n request_payload['error'] = HttpResponseBadRequest(err_msg)\n return request_payload\n\n # Prepare our request payload dictionary.\n\n request_payload = {}\n if \"callback\" in params:\n request_payload['callback'] = params['callback']\n request_payload['fields'] = {} # initially.\n\n # Check that we've been given the expected parameters.\n\n for param in params.keys():\n if param not in [\"callback\", \"request_key\", \"client_id\", \"payload\"]:\n return request_error(request_payload,\n \"Unknown parameter '%s'\" % param)\n\n for param in [\"request_key\", \"client_id\", \"payload\"]:\n if param not in params:\n return request_error(request_payload,\n \"Missing required '%s' parameter\" % param)\n\n # Extract the supplied CGI parameters.\n\n request_key = params['request_key']\n client_id = params['client_id']\n encrypted_payload = params['payload']\n\n # Get the Client app making this request.\n\n try:\n client = Client.objects.get(client_id=client_id)\n except Client.DoesNotExist:\n return request_error(request_payload, \"Invalid client ID\")\n\n # Attempt to decrypt the payload.\n\n# key = str(client.client_key) + aesWrapper.hexToBytes(request_key)\n# bytes = aesWrapper.hexToBytes(encrypted_payload)\n# payload_string = aesWrapper.decrypt(bytes, key)\n\n payload_string = base64.b64decode(encrypted_payload)\n\n try:\n payload = json.loads(payload_string, use_decimal=True)\n except ValueError:\n return request_error(request_payload, \"Invalid payload\")\n\n # Load the Session associated with this request, if any.\n\n if \"session_key\" in payload:\n session_key = payload['session_key']\n try:\n session = Session.objects.get(session_key=session_key)\n except Session.DoesNotExist:\n return request_error(request_payload, \"Invalid session key\")\n client = session.client\n request_num = session.request_num\n else:\n session_key = \"\"\n session = None\n request_num = \"\"\n\n # Calculate what the request key should have been, based upon the supplied\n # payload and the client ID, and ensure that it matches what we were\n # expecting.\n\n stripped = ''.join(payload_string.split())\n checksum = crc32(stripped)\n combined = str(session_key) + str(request_num) \\\n + str(client.client_key) + str(checksum)\n calc_request_key = sha256(combined).hexdigest()\n\n if request_key != calc_request_key:\n return request_error(request_payload, \"Invalid request key\")\n\n # Ensure that this client is authorized to access the API.\n\n if not client.authorized:\n return request_error(request_payload, \"Client not authorized\")\n\n # Finally, assemble the request payload and return it to the caller.\n\n if client != None: request_payload['client'] = client\n if session != None: request_payload['session'] = session\n\n request_payload['request_key'] = request_key\n\n for field,value in payload.items():\n request_payload['fields'][field] = value\n\n return request_payload\n\n#############################################################################\n\ndef check_fields(request_payload, required_fields=[], optional_fields=[]):\n \"\"\" Ensure that the given fields are present in the given request payload.\n\n The parameters are as follows:\n\n 'request_payload'\n\n A processed request payload, as returned by a previous call to\n process_request(), above.\n\n 'required_fields'\n\n A list of fields which must be present in the payload.\n\n 'optional_fields'\n\n A list of fields which can optionally be included in the\n payload.\n\n The payload is accepted if all the required fields are present, zero\n or more of the optional fields are present, and no other fields are\n present.\n\n If the payload is accepted, we return None. Otherwise, we return an\n HttpResponseBadRequest object suitable for returning back to\n the caller to indicate what was wrong with the payload.\n \"\"\"\n for field in required_fields:\n if field not in request_payload['fields']:\n return HttpResponseBadRequest(\"Missing required payload field '%s'\"\n % field)\n\n all_fields = set()\n for field in required_fields:\n all_fields.add(field)\n for field in optional_fields:\n all_fields.add(field)\n\n for field in request_payload['fields']:\n if field not in all_fields:\n return HttpResponseBadRequest(\"Unknown payload field '%s'\" % field)\n\n return None # All okay.\n\n#############################################################################\n\ndef response(request_payload, response_payload, update_session=True):\n \"\"\" Prepare to return a response back to the caller of the API.\n\n The parameters are as follows:\n\n 'request_payload'\n\n The request payload, as returned by a previous call to\n process_request().\n\n 'response_payload'\n\n A dictionary containing the response payload to send back to\n the client.\n\n 'update_session'\n\n If True, the current session's request number will be updated.\n Note that this should only be set to False if the caller is\n deleting the current session.\n\n We calculate an appropriate response to send back to the API client.\n Upon completion, we return an HttpResponse object containing the\n response to send back to the client.\n \"\"\"\n # Prepare our response.\n\n if request_payload.get(\"session\") != None:\n session_key = request_payload['session'].session_key\n request_num = request_payload['session'].request_num\n else:\n session_key = \"\"\n request_num = \"\"\n\n if request_payload.get(\"client\") != None:\n client_key = request_payload['client'].client_key\n else:\n client_key = \"\"\n\n payload_string = json.dumps(response_payload, use_decimal=True)\n stripped = ''.join(payload_string.split())\n checksum = crc32(stripped)\n combined = str(session_key) + str(request_num) \\\n + str(client_key) + str(checksum)\n response_key = sha256(combined).hexdigest()\n\n# key = str(client_key) \\\n# + aesWrapper.hexToBytes(request_payload['request_key'])\n# bytes = aesWrapper.encrypt(payload_string, key)\n# encrypted_payload = aesWrapper.bytesToHex(bytes)\n\n encrypted_payload = base64.b64encode(payload_string)\n\n response = json.dumps({'response_key' : response_key,\n 'payload' : encrypted_payload})\n\n # If we've been asked to update the session, increment the session's\n # request number so this request can only be used once.\n\n if update_session and request_payload.get(\"session\") != None:\n request_payload['session'].request_num += 1\n request_payload['session'].save()\n\n # Add a JSON-P callback, if necessary.\n\n if \"callback\" in request_payload:\n response = request_payload['callback'] + \"(\" + response + \")\"\n\n # Finally, return the response back to the caller.\n\n return HttpResponse(response, mimetype=\"application/json\")\n\n#############################################################################\n\ndef error(request_payload, error_tuple):\n \"\"\" Prepare to return the given error response back to the caller.\n\n The parameters are as follows:\n\n 'request_payload'\n\n The request payload, as returned by a previous call to\n process_request().\n\n 'error_tuple'\n\n An (err_code, err_msg) tuple, containing the error code and\n error message to return back to the caller. Note that you\n would normally supply one of the predefined constants listed in\n the 'api_errors' module to return a known error back to the\n caller.\n\n We calculate an appropriate error response to send back to the API\n client. Upon completion, we return an HttpResponse object containing\n the response to send back to the client.\n \"\"\"\n response_payload = {'error' : {'code' : error_tuple[0],\n 'message' : error_tuple[1]}}\n\n return response(request_payload, response_payload)\n\n","sub_path":"tahua/lib/api_helper.py","file_name":"api_helper.py","file_ext":"py","file_size_in_byte":10622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"90459861","text":"import sys\r\n\r\ndef partIsOp(x):\r\n return x == '+' or x == '/' or x == '*'\r\n\r\ndef evaluate(op, a, b):\r\n if op == '+':\r\n return a + b\r\n if op == '*':\r\n return a * b\r\n if op == '/':\r\n return a / b\r\n\r\nlines = open(sys.argv[1], 'r')\r\nfor line in lines:\r\n line = line.replace('\\n', '').replace('\\r', '')\r\n if len(line) > 0:\r\n parts = [x if partIsOp(x) else float(x) for x in line.split(' ')]\r\n while len(parts) > 1:\r\n for i in range(len(parts) - 1, -1, -1):\r\n if partIsOp(parts[i]):\r\n result = evaluate(parts[i], parts[i + 1], parts[i + 2])\r\n parts = parts[0:i] + [result] + parts[i + 3::]\r\n break\r\n print(int(parts[0]))\r\n\r\nlines.close()\r\n","sub_path":"Hard/Prefix Expressions/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"446178388","text":"# 6. count the number of subset with given difference\n\ndef countSubset(arr, subset1Sum, n):\n for j in range(subset1Sum+1):\n t[0][j] = 0\n\n for i in range(n+1):\n t[i][0] = 1\n\n for i in range(1, n+1):\n for j in range(1, subset1Sum+1):\n if arr[i-1] > j:\n t[i][j] = t[i-1][j]\n\n else:\n # t[i][j] = countSubset(arr, j - arr[i-1], i-1) + countSubset(arr, j, i-1)\n t[i][j] = t[i-1][j-arr[i-1]] + t[i-1][j]\n\n return t[n][subset1Sum]\n\narr = [1,1,2,3]\ndiff = 1\narrSum = sum(arr)\nsubset1Sum = int((diff+arrSum)/2)\nt = [[0 for j in range(subset1Sum+1)] for i in range(len(arr)+1)]\n\nprint(countSubset(arr,subset1Sum,len(arr)))","sub_path":"01Knapsack/Problem6.py","file_name":"Problem6.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"564382963","text":"import pyxel\nimport sys\nimport copy\nfrom mousecollide import MouseCollied\nimport random\nimport math\nfrom enum import Enum\n\n\"\"\"\n現状の課題。\n1、キャラを選択して云々の処理がまだ入ってない。\n2、クラスを分割できない。(正直見通しが悪くなってしまった。)\n\"\"\"\nCHIPSIZE = 16\n\nMAPSIZE_X = 18\nMAPSIZE_Y = 16\n\nVIEW_WIDTH = 256\nVIEW_HEIGHT = 256 \n\nclass Phase(Enum):\n pause = -1\n not_selected= 0 # 選ばれていない。\n moving = 1 # 移動中\n attack = 2 # 攻撃\n wait = 3 # 待機\n end_faze = 5 # 行動終了\n\n enemy_end_faze = 6 # 行動終了\n\nclass Turn(Enum):\n player = 0\n enemy = 1\n\nclass UnitPhase(Enum):\n not_selected = 0\n selected = 1\n\nclass Board():\n def __init__(self):\n self.map = []\n for y in range(MAPSIZE_Y):\n self.map.append([-1] * MAPSIZE_X)\n\n for x in range(MAPSIZE_X):\n self.map[0][x] = -10\n self.map[MAPSIZE_Y - 1][x] = -10\n\n for y in range(MAPSIZE_Y):\n self.map[y][0] = -10\n self.map[y][MAPSIZE_X - 1] = -10\n\n self.fcamera_x = 0\n self.fcamera_y = 0\n # チップの数に問題あり\n\n self.fcamera_x_chip = 0\n self.fcamera_y_chip = 0\n\n self.enemy_type = {\n 'A':10,\n 'B':9,\n 'C':8,\n 'D':7,\n 'E':6,\n }\n self.ob_list = []\n self.open_list = []\n self.close_list = []\n self.route_list = []\n\n def init(self):\n self.phase = Phase.not_selected\n self.turn = Turn.player\n \n def anime_init(self):\n self.move_timer = 0\n self.move_speed = 10\n\n def create_map(self):\n for y in range(1, len(self.map) - 1):\n for x in range(1, len(self.map[0]) - 1):\n if self.rand_parsen(5): # 5%の確率で岩山を出す。 \n self.map[y][x] = -2\n self.copy_map = copy.deepcopy(self.map)\n self.unit_map = copy.deepcopy(self.map)\n self.unit_map[MAPSIZE_Y - 3][MAPSIZE_X // 2 - 1] = 5\n self.unit_map[MAPSIZE_Y - 3][MAPSIZE_X // 2] = 5\n self.unit_map[MAPSIZE_Y - 3][MAPSIZE_X // 2 + 1] = 5\n # ついでにここで敵生成\n self.unit_map[MAPSIZE_Y // 4][MAPSIZE_X // 2 - 2] = 10\n self.unit_map[MAPSIZE_Y // 4][MAPSIZE_X // 2 - 1] = 9\n self.unit_map[MAPSIZE_Y // 4][MAPSIZE_X // 2 ] = 8\n self.unit_map[MAPSIZE_Y // 4][MAPSIZE_X // 2 + 1] = 7\n self.unit_map[MAPSIZE_Y // 4][MAPSIZE_X // 2 + 2] = 6\n self.init()\n self.anime_init()\n self.ob_search()\n\n class Unit:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.life = 50\n self.at_point = 10\n\n def life_draw(self):\n pyxel.rect(0, 0, self.life, CHIPSIZE, 5)\n\n def update(self):\n self.check_click_unit()\n self.move_unit()\n self.unit_search()\n self.scroll_map()\n self.turn_judge()\n self.enemy_turn()\n\n def draw(self):\n for y in range(len(self.map)):\n for x in range(len(self.map[0])):\n self.map_draw(y,x)\n self.unit_draw(y,x)\n self.map_searched_draw(y,x)\n\n def ob_search(self):\n for y in range(len(self.map)):\n for x in range(len(self.map[0])):\n if self.map[y][x] <= -5:\n self.ob_list.append((x, y))\n\n def unit_search(self):\n self.unit_list = []\n self.enemy_list = []\n for y in range(len(self.unit_map)):\n for x in range(len(self.unit_map[0])):\n if self.unit_map[y][x] == 5:\n self.unit_list.append((x,y))\n if self.unit_map[y][x] >= 6:\n # x,y,enemy_type\n self.enemy_list.append((x,y,self.unit_map[y][x]))\n # import pdb;pdb.set_trace()\n\n def unit_generage(self):\n for i in self.unit_list:\n unit = self.Unit(i[1], i[0])\n for j in self.enemy_list:\n enemy = self.Unit(j[1],j[0])\n \n def co_search(self, p_tuple):\n return p_tuple[0] * CHIPSIZE, p_tuple[1] * CHIPSIZE\n\n def rand_parsen(self, n):\n if random.randint(0, 99) < n:\n return True\n\n # むしろカメラが動いてマップの見える位置が変わる\n\n def scroll_map(self):\n if pyxel.btnp(pyxel.KEY_D, 1, 3):\n self.fcamera_x += CHIPSIZE\n self.fcamera_x_chip += 1\n if self.fcamera_x > CHIPSIZE * (MAPSIZE_X - CHIPSIZE):\n self.fcamera_x = CHIPSIZE * (MAPSIZE_X - CHIPSIZE)\n self.fcamera_x_chip = MAPSIZE_X - CHIPSIZE\n \n if pyxel.btnp(pyxel.KEY_A, 1, 3):\n self.fcamera_x -= CHIPSIZE\n self.fcamera_x_chip -= 1\n if self.fcamera_x < 0:\n self.fcamera_x = 0 \n self.fcamera_x_chip = 0\n\n if pyxel.btnp(pyxel.KEY_W, 1, 3):\n self.fcamera_y -= CHIPSIZE\n self.fcamera_y_chip -= 1\n if self.fcamera_y < 0:\n self.fcamera_y = 0 \n self.fcamera_y_chip = 0\n \n if pyxel.btnp(pyxel.KEY_S, 1, 3):\n self.fcamera_y += CHIPSIZE\n self.fcamera_y_chip += 1\n if self.fcamera_y > CHIPSIZE * (MAPSIZE_Y - CHIPSIZE):\n self.fcamera_y = CHIPSIZE * (MAPSIZE_Y - CHIPSIZE) \n self.fcamera_y_chip = MAPSIZE_Y - CHIPSIZE\n \n return\n \n # ここから移動範囲のupdateメソッド、そしてユニットのメソッド\n \n def check_click_unit(self):\n self.mx = pyxel.mouse_x // 16 + self.fcamera_x_chip\n self.my = pyxel.mouse_y // 16 + self.fcamera_y_chip\n if self.phase == Phase.not_selected and self.turn == Turn.player:\n if pyxel.btn(pyxel.MOUSE_LEFT_BUTTON):\n if self.unit_map[self.my][self.mx] == 5:\n self.sx = self.mx\n self.sy = self.my\n self.phase = Phase.moving\n self.movepoint = self.unit_map[self.my][self.mx]\n self.search_4_vec(self.mx, self.my, self.movepoint)\n #分身を防ぐための苦肉の策\n self.unit_map[self.my][self.mx] = self.copy_map[self.my][self.mx]\n\n def move_unit(self):\n if self.phase == Phase.moving:\n if pyxel.btnr(pyxel.MOUSE_RIGHT_BUTTON):\n if self.copy_map[self.my][self.mx] >= 0:\n pyxel.play(0, 0, loop=False)\n self.gx = self.mx\n self.gy = self.my\n # ここにmove関数\n self.unit_map[self.my][self.mx] = 5\n self.copy_map = copy.deepcopy(self.map)\n self.phase = Phase.end_faze \n # self.phase = Phase.not_selected\n \n def search_4_vec(self, x, y, movepoint):\n \"\"\"\n 4方向をsearchする。\n 移動範囲を調べる\n \"\"\"\n if 0 < x and x < len(self.map[0]) and 0 < y and y < len(self.map):\n self.search_map(x, y-1, movepoint)\n self.search_map(x, y+1, movepoint)\n self.search_map(x-1, y, movepoint)\n self.search_map(x+1, y, movepoint)\n\n def search_map(self, x, y, movepoint):\n if x < 0 or len(self.copy_map[0]) <= x:\n return\n\n if y < 0 or len(self.copy_map) <= y:\n return\n \n if (movepoint - 1) <= self.copy_map[y][x]:\n return\n\n # 今サーチしてるマスのunit_map上に何かいたら。\n if self.unit_map[y][x] >= 5:\n return\n \n movepoint += self.map[y][x]\n \n if movepoint > 0:\n self.copy_map[y][x] = movepoint\n self.search_4_vec(x, y, movepoint)\n else:\n movepoint = 0\n\n # ここからdraw関数\n\n def map_draw(self,y,x):\n pyxel.blt(x * CHIPSIZE, y * 16, 0, 0, 16, 16, 16)\n if self.map[y][x] == -1:\n pyxel.blt(x * CHIPSIZE - self.fcamera_x, y * 16 - self.fcamera_y, 0, 0, 16, 16, 16)\n elif self.map[y][x] == -10:\n pyxel.blt(x * CHIPSIZE - self.fcamera_x, y * 16 - self.fcamera_y, 0, 0, 32, 16, 16)\n elif self.map[y][x] == -2:\n pyxel.blt(x * CHIPSIZE - self.fcamera_x, y * 16 - self.fcamera_y, 0, 0, 48, 16, 16, colkey=1)\n\n def unit_draw(self,y,x):\n # いちいちcopy_mapを初期化するため、そこにユニットを置いたら、ほかのユニットが消える恐れがある。\n if self.unit_map[y][x] == 5:\n pyxel.blt(x * CHIPSIZE - self.fcamera_x, y * CHIPSIZE - self.fcamera_y, 0, 16, 0, 16, 16,colkey=0)\n if self.unit_map[y][x] == self.enemy_type['A']:\n pyxel.blt(x * CHIPSIZE - self.fcamera_x, y * CHIPSIZE - self.fcamera_y, 0, 16, 16, 16, 16,colkey=1)\n if self.unit_map[y][x] == self.enemy_type['B']:\n pyxel.blt(x * CHIPSIZE - self.fcamera_x, y * CHIPSIZE - self.fcamera_y, 0, 16, 32, 16, 16,colkey=1)\n if self.unit_map[y][x] == self.enemy_type['C']:\n pyxel.blt(x * CHIPSIZE - self.fcamera_x, y * CHIPSIZE - self.fcamera_y, 0, 16, 48, 16, 16,colkey=1)\n if self.unit_map[y][x] == self.enemy_type['D']:\n pyxel.blt(x * CHIPSIZE - self.fcamera_x, y * CHIPSIZE - self.fcamera_y, 0, 16, 64, 16, 16,colkey=1)\n if self.unit_map[y][x] == self.enemy_type['E']:\n pyxel.blt(x * CHIPSIZE - self.fcamera_x, y * CHIPSIZE - self.fcamera_y, 0, 16, 80, 16, 16,colkey=1)\n\n def map_searched_draw(self, y, x):\n self.msc = MouseCollied(y, x, y * CHIPSIZE, x * 16)\n if self.msc.point_check_hit():\n pyxel.blt(pyxel.mouse_x // 16 * CHIPSIZE, pyxel.mouse_y // 16 * 16, 0, 0, 0, 16, 16, colkey=0)\n if self.copy_map[y][x] >= 0 and self.copy_map[y][x] <= 4:\n pyxel.rectb(x*CHIPSIZE - self.fcamera_x, y*CHIPSIZE - self.fcamera_y, CHIPSIZE, CHIPSIZE, 12)\n if self.copy_map[y][x] == 5:\n pyxel.blt(x * CHIPSIZE - self.fcamera_x, y * CHIPSIZE - self.fcamera_y, 0, 16, 0, 16, 16,colkey=0)\n if self.phase == Phase.moving:\n pyxel.blt(pyxel.mouse_x // 16 * CHIPSIZE, pyxel.mouse_y // 16 * 16, 0, 32, 0, 16, 16, colkey=0)\n \n \"\"\"\n ちなみにここから敵AIのルーチン\n 敵A:猪突猛進型(ひたすらプレイヤーを追いかけてくる)\n 敵B:通常型(PCとの単純距離差55以内なら近づいてくる)\n 敵��:守備型(PCとの単純距離差が3以内になった所で近づき、以後は距離に関係なく常にプレイヤーを追いかけるA型になる)\n 敵D:ピボット型(ある地点から単純距離半径6以上の地点へは何があっても進めない。その範囲の中でプレイヤーに近づこうとする)\n 敵E:アーチャー(単純距離差が5以内で近づくのだが、主人公からの単純距離差が3になる地点を確保しようとする) \n \"\"\"\n class Node:\n def __init__(self, x, y, cost = 0, pare_id = None):\n self.x = x\n self.y = y\n self.cost = cost\n # 親ノード\n self.pare_id = pare_id\n \n def return_cost(self):\n return self.cost\n\n def enemy_turn(self):\n if self.turn == Turn.enemy and self.phase == Phase.not_selected:\n if self.enemy_list == None:\n print(\"Enemy Not Found\")\n return\n self.phase = Phase.moving\n self.enemy_move(self.enemy_list[random.randint(0, len(self.enemy_list)-1)], \\\n self.unit_list[random.randint(0, len(self.unit_list)-1)])\n self.enemy_attack()\n self.enemy_end()\n\n def enemy_move(self, enemy_ad, unit_ad):\n if self.phase == Phase.moving:\n self.search_4_vec(enemy_ad[0], enemy_ad[1], 6)\n self.calc_move(enemy_ad, unit_ad)\n # import pdb;pdb.set_trace()\n self.copy_map = copy.deepcopy(self.map)\n self.phase = Phase.attack\n\n def calc_move(self, enemy_ad, unit_ad, t_cost = 0):\n move_id = self.Node(enemy_ad[0], enemy_ad[1])\n self.open_list.append(move_id)\n try:\n # まず自分の周りをオープンして、そこに移動したらターゲットの地点に近づくか遠のくか計算し、それをNodeのコストに換算する。\n # Nodeクラスで作ったその時点でのコストをよそと比較し、一番コストが小さいNodeの地点へ移動する。\n # open_nodeを行う範囲を拡張すれば、移動範囲が広がるのだが・・・\n for i in range(-1, 1):\n for j in range(-1, 1):\n self.open_node(enemy_ad[0] + i, enemy_ad[1] + j, unit_ad[0], unit_ad[1], t_cost)\n\n if not self.open_list:\n return\n\n move_id = self.cost_search()\n\n if move_id.x == enemy_ad[1] and move_id.y == enemy_ad[0]:\n return\n \n if move_id.x == unit_ad[1] and move_id.y == unit_ad[0]:\n print(\"Find Goal\")\n return\n \n \"\"\"\n self.route_list.append(move_id)\n \n if self.copy_map[move_id.y][move_id.x] > 0 and self.unit_map[move_id.y][move_id.y] < 5:\n self.calc_move(enemy_ad, (move_id.x, move_id.y), t_cost=t_cost + 1)\n \"\"\"\n\n self.unit_map[enemy_ad[1]][enemy_ad[0]] = self.map[enemy_ad[1]][enemy_ad[0]]\n self.unit_map[move_id.y][move_id.x] = enemy_ad[2]\n\n except IndexError as inde:\n print(\"Unexpected error in calc_move: {}\".format(inde))\n print(\"self.open_list\", self.open_list)\n\n def open_node(self, x, y, tx, ty, t_cost):\n heu_cost = abs(max(tx - x, ty - y))\n\n if self.unit_map[y][x] >= 5:\n return\n\n if self.copy_map[y][x] <= 0:\n return\n\n for i in self.ob_list:\n if i[0] == x and i[1] == y:\n return\n\n aNode = self.Node(x, y, cost=heu_cost + t_cost)\n\n for _, bNode in enumerate(self.open_list):\n if aNode.x == bNode.x and aNode.y == bNode.y:\n if aNode.cost < bNode.cost:\n bNode.cost = aNode.cost\n\n self.open_list.append(aNode)\n # self.unit_map[y][x] = self.enemy_type[\"B\"]\n\n return self.open_list\n \n def cost_search(self):\n if not self.open_list:\n print(\"Not Node\")\n return\n # close_listに計算済みのノードを格納したい。\n # import pdb;pdb.set_trace()\n try:\n most_min_cost = sorted(self.open_list, key=lambda c:c.return_cost())[1]\n return most_min_cost\n except:\n print(\"Unexpected error in cost_search:\", sys.exc_info()[0])\n \n def enemy_attack(self):\n if self.phase == Phase.attack:\n # print(\"Enemy Attacks\")\n self.phase = Phase.wait\n\n def enemy_end(self):\n if self.phase == Phase.wait:\n # print(\"Enemy End\")\n self.phase = Phase.enemy_end_faze\n\n def turn_judge(self):\n if self.phase == Phase.end_faze:\n self.turn = Turn.enemy\n self.phase = Phase.not_selected\n if self.phase == Phase.enemy_end_faze:\n # import pdb; pdb.set_trace()\n self.init()\n\nclass App():\n def __init__(self):\n pyxel.init(VIEW_WIDTH, VIEW_HEIGHT, caption=\"mouse\")\n pyxel.load(\"Tile.pyxres\")\n self.board = Board()\n self.board.create_map()\n pyxel.run(self.update, self.draw)\n\n def update(self):\n self.board.update()\n\n def draw(self):\n self.board.draw()\n\nApp()","sub_path":"saBakuDeWars/_app.py","file_name":"_app.py","file_ext":"py","file_size_in_byte":15969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"187930595","text":"# -*- coding: utf-8 -*-\n\"\"\"Clasess that adapt JIRA for use as a zazu IssueTracker.\"\"\"\nimport zazu.credential_helper\nimport zazu.issue_tracker\nimport zazu.util\nzazu.util.lazy_import(locals(), [\n 'jira',\n 're'\n])\n\n__author__ = \"Nicholas Wiles\"\n__copyright__ = \"Copyright 2016\"\n\nZAZU_IMAGE_URL = 'http://vignette1.wikia.nocookie.net/disney/images/c/ca/Zazu01cf.png'\nZAZU_REPO_URL = 'https://github.com/stopthatcow/zazu'\nJIRA_CREATED_BY_ZAZU = '----\\n!{}|width=20! Created by [Zazu|{}]'.format(ZAZU_IMAGE_URL, ZAZU_REPO_URL)\n\n\nclass JiraIssueTracker(zazu.issue_tracker.IssueTracker):\n \"\"\"Implements zazu issue tracker interface for JIRA.\"\"\"\n\n def __init__(self, base_url, default_project, components):\n \"\"\"Create a JiraIssueTracker.\n\n Args:\n base_url (str): base URL for the JIRA instance.\n default_project (str): project that new issues will be created in by default.\n components (list of str): list of components that new issues can be associated with.\n \"\"\"\n self._base_url = base_url\n self._default_project = default_project\n self._components = components\n self._jira_handle = None\n\n def connect(self):\n \"\"\"Get handle to ensure that JIRA credentials are in place.\"\"\"\n self._jira()\n\n def _jira(self):\n if self._jira_handle is None:\n username, password = zazu.credential_helper.get_user_pass_credentials('Jira')\n self._jira_handle = jira.JIRA(self._base_url,\n basic_auth=(username, password),\n options={'check_update': False}, max_retries=0)\n return self._jira_handle\n\n def browse_url(self, id):\n \"\"\"Get the url to open to display the issue.\"\"\"\n self.validate_id_format(id)\n return '{}/browse/{}'.format(self._base_url, id)\n\n def issue(self, id):\n \"\"\"Get an issue by id.\"\"\"\n self.validate_id_format(id)\n try:\n ret = self._jira().issue(id)\n # Only show description up to the separator\n if ret.fields.description is None:\n ret.fields.description = ''\n ret.fields.description = ret.fields.description.split('\\n\\n----', 1)[0]\n except jira.exceptions.JIRAError as e:\n raise zazu.issue_tracker.IssueTrackerError(str(e))\n return JiraIssueAdaptor(ret, self)\n\n def create_issue(self, project, issue_type, summary, description, component):\n \"\"\"Create a new issue on JIRA.\n\n Args:\n project (str): the JIRA project short string to create the issue in.\n issue_type (str): the JIRA issue type to create.\n summary (str): a summary of the issue.\n description (str): a detailed description of the issue.\n component (str): the JIRA component to associate with the issue.\n \"\"\"\n try:\n issue_dict = {\n 'project': {'key': project},\n 'issuetype': {'name': issue_type},\n 'summary': summary,\n 'description': '{}\\n\\n{}'.format(description, JIRA_CREATED_BY_ZAZU)\n }\n if component is not None:\n issue_dict['components'] = [{'name': component}]\n issue = self._jira().create_issue(issue_dict)\n self._jira().assign_issue(issue, issue.fields.reporter.name)\n return JiraIssueAdaptor(issue, self)\n except jira.exceptions.JIRAError as e:\n raise zazu.issue_tracker.IssueTrackerError(str(e))\n\n def default_project(self):\n \"\"\"JIRA project associated with this tracker.\"\"\"\n return self._default_project\n\n def issue_types(self):\n \"\"\"Issue types that can be created by this tracker.\"\"\"\n return ['Task', 'Bug', 'Story']\n\n def issue_components(self):\n \"\"\"Components that are associated with this tracker.\"\"\"\n return self._components\n\n @staticmethod\n def validate_id_format(id):\n \"\"\"Validate that an id is the proper format for Jira.\n\n Args:\n id (str): the id to check.\n\n Raises:\n zazu.issue_tracker.IssueTrackerError: if the id is not valid.\n\n \"\"\"\n if not re.match('[A-Z]+-[0-9]+$', id):\n raise zazu.issue_tracker.IssueTrackerError('issue id \"{}\" is not of the form PROJ-#'.format(id))\n\n @staticmethod\n def from_config(config):\n \"\"\"Make a JiraIssueTracker from a config.\"\"\"\n try:\n url = config['url']\n except KeyError:\n raise zazu.ZazuException('Jira config requires a \"url\" field')\n try:\n project = config['project']\n except KeyError:\n raise zazu.ZazuException('Jira config requires a \"project\" field')\n components = config.get('component', None)\n if not isinstance(components, list):\n components = [components]\n return JiraIssueTracker(url, project, components)\n\n @staticmethod\n def type():\n \"\"\"Return the name of this IssueTracker type.\"\"\"\n return 'Jira'\n\n\nclass JiraIssueAdaptor(zazu.issue_tracker.Issue):\n \"\"\"Wraps a issue returned from the jiri api and adapts it to the zazu.issue_tracker.Issue interface.\"\"\"\n\n def __init__(self, jira_issue, tracker_handle):\n \"\"\"Create a JiraIssueAdaptor by wrapping a jira Issue object.\n\n Args:\n jira_issue: Jira issue handle.\n tracker_handle: The tracker associated with this issue.\n \"\"\"\n self._jira_issue = jira_issue\n self._tracker = tracker_handle\n\n @property\n def name(self):\n \"\"\"Get the name of the issue.\"\"\"\n return self._jira_issue.fields.summary\n\n @property\n def status(self):\n \"\"\"Get the status string of the issue.\"\"\"\n return self._jira_issue.fields.status.name\n\n @property\n def description(self):\n \"\"\"Get the description of the issue.\"\"\"\n return self._jira_issue.fields.description\n\n @property\n def type(self):\n \"\"\"Get the string type of the issue.\"\"\"\n return self._jira_issue.fields.issuetype.name\n\n @property\n def assignee(self):\n \"\"\"Get the string assignee of the issue.\"\"\"\n return self._jira_issue.fields.assignee.name\n\n @property\n def closed(self):\n \"\"\"Return True if the issue is closed.\"\"\"\n return self._jira_issue.fields.resolution.name != 'Unresolved'\n\n @property\n def browse_url(self):\n \"\"\"Get the url to open to display the issue.\"\"\"\n return self._tracker.browse_url(self.id)\n\n @property\n def id(self):\n \"\"\"Get the string id of the issue.\"\"\"\n return self._jira_issue.key\n\n def __str__(self):\n \"\"\"Return the id as the string representation.\"\"\"\n return self.id\n","sub_path":"zazu/plugins/jira_issue_tracker.py","file_name":"jira_issue_tracker.py","file_ext":"py","file_size_in_byte":6788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"323706145","text":"from transitions.extensions import GraphMachine\nfrom monsterHunterCrawler import MHCrawler\nfrom utils import send_text_message, send_image_message, send_video_message, send_button_message\n\nclass TocMachine(GraphMachine):\n mhc = MHCrawler()\n\n def __init__(self):\n #----------------------------------------------------------------------------------\n #dfa all state\n dfa = {\n 'states': [\n 'allMission',\n 'searchMission',\n 'printMission',\n 'user',\n 'help',\n 'command',\n 'allMonster',\n 'monster',\n 'attackEffect',\n 'video',\n 'trap',\n 'effect',\n 'character'\n \n ],\n 'transitions': [\n {\n 'trigger': 'back',\n 'source':[\n 'video',\n 'help',\n 'allMission',\n 'printMission',\n 'command'\n ],\n 'dest': 'user'\n },\n {\n 'trigger': 'advance',\n 'source':[\n 'allMonster',\n 'searchMission'\n ],\n 'dest': 'user',\n 'conditions': 'isBack'\n },\n {\n 'trigger': 'back',\n 'source':[\n 'attackEffect',\n 'trap',\n 'effect',\n 'character'\n ],\n 'dest': 'monster',\n }\n ],\n 'initial': 'user',\n 'auto_transitions': False,\n 'show_conditions': True,\n }\n #----------------------------------------------------------------------------------\n self.machine = GraphMachine(\n model=self,\n **dfa\n )\n #\n self.machine.add_transition('advance', 'user', 'allMission', conditions = 'isAllMission')\n self.machine.add_transition('advance', 'user', 'searchMission', conditions = 'isSearchMission')\n #self.machine.add_transition('advance', 'searchMission', 'searchMission', conditions = 'isSearchMission')\n self.machine.add_transition('advance', 'searchMission', 'printMission')\n self.machine.add_transition('back2Search', 'printMission', 'searchMission')\n self.machine.add_transition('advance', 'user', 'help', conditions = 'isHelp')\n self.machine.add_transition('advance', 'user', 'command', conditions = 'isCommand')\n self.machine.add_transition('advance', 'user', 'allMonster', conditions = 'isAllMonster')\n self.machine.add_transition('advance', 'allMonster', 'monster', conditions = 'isMonster')\n self.machine.add_transition('advance', 'monster', 'monster', conditions = 'isMonster2')\n self.machine.add_transition('advance', 'monster', 'allMonster', conditions = 'isBack')\n self.machine.add_transition('back', 'monster', 'allMonster')\n self.machine.add_transition('advance', 'monster', 'attackEffect', conditions = 'isAttackEffect')\n self.machine.add_transition('advance', 'user', 'video', conditions = 'isVideo')\n self.machine.add_transition('advance', 'monster', 'effect', conditions = 'isEffect')\n self.machine.add_transition('advance', 'monster', 'trap', conditions = 'isTrap')\n self.machine.add_transition('advance', 'monster', 'character', conditions = 'isCharacter')\n #\n \n def on_enter_character(self, event):\n sender_id = event['sender']['id']\n self.mhc.dropItem()\n responese = send_text_message(sender_id, self.mhc.monEff['character']);\n self.back(event)\n\n def isCharacter(self, event):\n sender_id = event['sender']['id']\n text = event['message']['text']\n if text == \"特徵\":\n return True\n else:\n return False\n\n def on_enter_trap(self, event):\n sender_id = event['sender']['id']\n self.mhc.dropItem()\n responese = send_text_message(sender_id, self.mhc.monEff['trap']);\n self.back(event)\n \n def isTrap(self, event):\n sender_id = event['sender']['id']\n text = event['message']['text']\n if text == \"陷阱\":\n return True\n else:\n return False\n\n def on_enter_effect(self, event):\n sender_id = event['sender']['id']\n self.mhc.dropItem()\n responese = send_text_message(sender_id, self.mhc.monEff['seffect']);\n self.back(event)\n \n def isEffect(self, event):\n sender_id = event['sender']['id']\n text = event['message']['text']\n if text == \"效果\":\n return True\n else:\n return False\n\n def isVideo(self, event):\n sender_id = event['sender']['id']\n text = event['message']['text']\n if text == \"video\":\n return True\n else:\n return False\n\n def on_enter_video(self, event):\n sender_id = event['sender']['id']\n responese = send_video_message(sender_id, \"https://www.youtube.com/watch?v=pp_wSIhdd2s\");\n self.back(event)\n\n def isAttackEffect(self, event):\n sender_id = event['sender']['id']\n text = event['message']['text']\n if text == \"弱點\":\n return True\n else:\n return False\n\n def on_enter_attackEffect(self, event):\n sender_id = event['sender']['id']\n self.mhc.dropItem()\n responese = send_text_message(sender_id, self.mhc.monEff['weak']);\n self.back(event)\n\n def isMonster2(self, event):\n sender_id = event['sender']['id']\n text = event['message']['text']\n if self.mhc.searchMonster(text): \n print(self.mhc.monImg)\n responese = send_image_message(sender_id, self.mhc.monImg)\n responese = send_text_message(sender_id, self.mhc.monster.get(1))\n #print(self.mhc.monster.get(1))\n return True\n else:\n return False\n\n def isMonster(self, event):\n sender_id = event['sender']['id']\n text = event['message']['text']\n if self.mhc.searchMonster(text): \n print(self.mhc.monImg)\n responese = send_image_message(sender_id, self.mhc.monImg)\n responese = send_text_message(sender_id, self.mhc.monster.get(1))\n #print(self.mhc.monster.get(1))\n return True\n else:\n responese = send_text_message(sender_id, \"請輸入正確魔物名子\")\n return False\n\n\n def on_enter_monster(self, event):\n sender_id = event['sender']['id']\n \n def isAllMonster(self, event):\n if event.get(\"message\"):\n text = event['message']['text']\n if text.lower() == '魔物':\n return True\n if text.lower() == 'monster':\n return True\n return False\n return False\n\n def on_enter_allMonster(self, event):\n sender_id = event['sender']['id']\n self.mhc.listAllMonster()\n responese = send_text_message(sender_id, self.mhc.mbuffer);\n\n def on_enter_monster(self, event):\n pass\n\n def isAllMission(self, event): \n if event.get(\"message\"):\n text = event['message']['text']\n return text.lower() == '本周任務'\n return False\n \n\n def on_enter_allMission(self, event):\n sender_id = event['sender']['id']\n self.mhc.listAllQuest()\n responese = send_text_message(sender_id, self.mhc.mbuffer);\n self.back()\n \n def isBack(self, event):\n if event.get(\"message\"):\n text = event['message']['text']\n return text.lower() == 'back'\n return False\n\n def isSearchMission(self, event):\n if event.get(\"message\"):\n text = event['message']['text']\n return text.lower() == '任務'\n return False\n\n def on_enter_searchMission(self, event):\n sender_id = event['sender']['id']\n responese = send_text_message(sender_id, '輸入任務');\n\n def on_enter_printMission(self, event):\n sender_id = event['sender']['id']\n text = ''\n if event.get('message'):\n text = event['message']['text']\n else:\n responese = send_text_message(sender_id, '請輸入文字'); \n self.back2Search(event)\n return\n\n if(self.mhc.searchQuest(text)):\n responese = send_image_message(sender_id, self.mhc.murl)\n responese = send_text_message(sender_id, self.mhc.mbuffer)\n self.back()\n else:\n responese = send_text_message(sender_id, '請輸入正確任務名'); \n self.back2Search(event)\n\n\n def isHelp(self, event):\n if event.get(\"message\"):\n text = event['message']['text']\n return text.lower() == 'help'\n return False\n \n def on_enter_help(self, event):\n sender_id = event['sender']['id']\n self.mhc.listAllQuest()\n text = \"*Monster Hunter Chatbot*\\n你可以搜尋最近活動和魔物的功略,輸入command可以的知道所有指令\"\n responese = send_image_message(sender_id, 'https://img.gq.com.tw/_rs/645/userfiles/sm/sm1024_images_A1/35545/2018031643207121.jpg')\n responese = send_text_message(sender_id, text);\n self.back()\n\n def isCommand(self, event):\n if event.get(\"message\"):\n text = event['message']['text']\n return text.lower() == 'command'\n return False\n\n def on_enter_command(self, event):\n \"\"\"\n self.mhc.listAllMonster()\n self.mhc.searchMonster('滅盡龍')\n self.mhc.dropItem()\n responese = send_text_message(sender_id, self.mhc.drop.get(1))\n \"\"\"\n sender_id = event['sender']['id']\n responese = send_button_message(sender_id)\n self.back()\n","sub_path":"fsm.py","file_name":"fsm.py","file_ext":"py","file_size_in_byte":10160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"649808488","text":"'''\n this app is the camera interface\n'''\n\n\n\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.image import Image\nfrom kivy.clock import Clock\nfrom kivy.graphics.texture import Texture\n\nimport cv2\n\nclass CamApp(App):\n\n def build(self):\n self.img1=Image()\n layout = BoxLayout()\n layout.add_widget(self.img1)\n #opencv2 stuffs\n self.capture = cv2.VideoCapture(0)\n cv2.namedWindow(\"CV2 Image\")\n Clock.schedule_interval(self.update, 1.0/33.0)\n return layout\n\n def update(self, dt):\n # display image from cam in opencv window\n ret, frame = self.capture.read()\n faceCascade = cv2.CascadeClassifier('C:/Users/Rajneesh/Desktop/Project/frontalface.xml')\n faces=faceCascade.detectMultiScale(frame,scaleFactor=1.1,minSize=(40,40),minNeighbors=5,flags=cv2.CASCADE_SCALE_IMAGE)\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x,y), (x+w, y+h),(0,255,0), 2)\n cv2.putText(frame,\"Face\", (x, y-4), cv2.FONT_HERSHEY_SIMPLEX, 0.8,(0,255,0), 1, cv2.LINE_AA)\n \n #cv2.imshow(\"CV2 Image\", frame)\n # convert it to texture\n buf1 = cv2.flip(frame, 0)\n buf = buf1.tostring()\n texture1 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')\n texture1.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')\n # display image from the texture\n self.img1.texture = texture1\n\nif __name__ == '__main__':\n CamApp().run()\n cv2.destroyAllWindows()\n\n","sub_path":"cam2.py","file_name":"cam2.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"308654034","text":"# skeleton borrowed from Apache Beam's wordcount_minimal.py example\n\nfrom __future__ import absolute_import\n\nimport argparse\nimport logging\nimport re\n\nfrom past.builtins import unicode\n\nimport apache_beam as beam\nfrom apache_beam.io import ReadFromText\nfrom apache_beam.io import WriteToText\nfrom apache_beam.options.pipeline_options import PipelineOptions\nfrom apache_beam.options.pipeline_options import SetupOptions\n\ndef run(argv=None):\n \"\"\"Main entry point; defines and runs the wordcount pipeline.\"\"\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--input',\n dest='input',\n default='gs://lswa-scalica/input/df_input.txt',\n help='Input file to process.')\n parser.add_argument('--output',\n dest='output',\n default='gs://lswa-scalica/output/df_output.txt',\n help='Output file to write results to.')\n known_args, pipeline_args = parser.parse_known_args(argv)\n pipeline_args.extend([\n '--runner=DataflowRunner',\n '--project=scalica-224416',\n '--staging_location=gs://lswa-scalica/staging',\n '--temp_location=gs://lswa-scalica/tmp',\n '--job_name=scalica-job',\n ])\n\n # We use the save_main_session option because one or more DoFn's in this\n # workflow rely on global context (e.g., a module imported at module level).\n pipeline_options = PipelineOptions(pipeline_args)\n pipeline_options.view_as(SetupOptions).save_main_session = True\n with beam.Pipeline(options=pipeline_options) as p:\n # format input into a dictionary\n def format_input(line):\n split_line = line.split(',')\n user_id = split_line[0]\n followees = split_line[1].split('-') \n followees = [int(followee) for followee in followees if followee]\n followers = split_line[2].split('-')\n followers = [int(follower) for follower in followers if follower]\n\n return {\n 'user_id': user_id, \n 'followees': followees, \n 'followers': followers\n }\n\n # split followees and followers into list of pairs\n def split(user_data):\n follower_pairs = []\n\n for followee in user_data['followees']:\n for follower in user_data['followers']:\n if followee != follower:\n follower_pair = str(followee) + ',' + str(follower)\n follower_pairs.append(follower_pair)\n \n return follower_pairs\n\n # emit a count for each follower_pair\n def map_count(follower_pair):\n return (follower_pair, 1)\n\n # format each follower pair + counter\n def format_result(map_pair):\n (follower_pair, count) = map_pair\n return '%s: %s' % (follower_pair, count)\n\n logging.info('reading from input')\n\n # Read the input file\n lines = p | ReadFromText(known_args.input)\n print(lines)\n\n suggestions = (\n lines\n | 'FormatInput' >> beam.Map(format_input)\n | 'Split' >> beam.FlatMap(split)\n | 'MapCount' >> beam.Map(map_count)\n | 'GroupAndSum' >> beam.CombinePerKey(sum))\n\n logging.info('generated suggestions')\n\n output = suggestions | 'Format' >> beam.Map(format_result)\n\n # for convenience, only write to one shard\n # for scalability, don't define this parameter so Dataflow scales numshards appropriately\n output | WriteToText(known_args.output, num_shards=1)\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.INFO)\n run()\n","sub_path":"dataflow/follower_suggestion_job.py","file_name":"follower_suggestion_job.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"487908302","text":"'''\n\nIntegration test for testing max allowed vblk data volume to be attached on mini.\n\n@author: zhaohao.chen\n'''\n\nimport apibinding.inventory as inventory\nimport zstackwoodpecker.test_util as test_util\nimport zstackwoodpecker.test_state as test_state\nimport zstackwoodpecker.test_lib as test_lib\nimport zstackwoodpecker.operations.resource_operations as res_ops\nimport zstackwoodpecker.zstack_test.zstack_test_volume as test_volume_header\nimport zstackwoodpecker.zstack_test.zstack_test_vm as test_vm_header\nimport zstackwoodpecker.operations.volume_operations as vol_ops\nimport time\nimport os\nimport random\n\nPROVISION = [\"volumeProvisioningStrategy::ThinProvisioning\",\"volumeProvisioningStrategy::ThickProvisioning\"]\nround_num = 21\nvolume = None\nvm = None\ntest_obj_dict = test_state.TestStateDict()\ndef test():\n global test_obj_dict\n global round_num\n global volume\n global vm\n VM_CPU = 2\n VM_MEM = 2147483648\n volume_creation_option = test_util.VolumeOption()\n ps_uuid = res_ops.query_resource(res_ops.PRIMARY_STORAGE)[0].uuid\n volume_creation_option.set_primary_storage_uuid(ps_uuid)\n \n #1.create vm\n vm_creation_option = test_util.VmOption()\n image_name = os.environ.get('imageName_s')\n image_uuid = test_lib.lib_get_image_by_name(image_name).uuid\n l3_name = os.environ.get('l3VlanNetworkName1')\n l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid\n vm_creation_option.set_l3_uuids([l3_net_uuid])\n vm_creation_option.set_image_uuid(image_uuid)\n vm_creation_option.set_name('Mini_vm_datavolume_test')\n vm_creation_option.set_cpu_num(VM_CPU)\n vm_creation_option.set_memory_size(VM_MEM)\n vm = test_vm_header.ZstackTestVm()\n vm.set_creation_option(vm_creation_option)\n vm.create()\n vm.check()\n test_obj_dict.add_vm(vm)\n vm_uuid = vm.get_vm().uuid\n #create thin/thick data volume with random disksize and random provision type\n #and attach to vm\n for i in range(round_num):\n volume_name = \"volume_%s\" % i\n volume_creation_option.set_name(volume_name)\n max_size = (res_ops.query_resource(res_ops.PRIMARY_STORAGE)[0].availableCapacity - 1048576)/(20 * 512) \n disk_size = random.randint(2048, max_size) * 512\n volume_creation_option.set_diskSize(disk_size)\n volume_creation_option.set_system_tags([random.choice(PROVISION)])\n volume = test_volume_header.ZstackTestVolume()\n volume.set_volume(vol_ops.create_volume_from_diskSize(volume_creation_option))\n volume.check() \n test_obj_dict.add_volume(volume)\n try:\n volume.attach(vm)\n except Exception as e:\n test_util.test_logger(e)\n test_util.test_pass('Allowed max num of attached vblk is %s' % i)\n test_util.test_fail(\"Allowed max num of attached vblk may is not %s\" % round_num )\n\ndef error_cleanup():\n global test_obj_dict\n test_lib.lib_error_cleanup(test_obj_dict)\n\ndef env_recover():\n global test_obj_dict\n test_lib.lib_error_cleanup(test_obj_dict)\n \n","sub_path":"integrationtest/vm/mini/volume/test_max_allowed_attached_vblk_volume.py","file_name":"test_max_allowed_attached_vblk_volume.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"146239530","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.conf import settings\n\nfrom manager_topic.models import Topic\n\nclass Comment(models.Model):\n\n author = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n related_name='autor_comments',\n verbose_name='Author name'\n )\n\n topic = models.ForeignKey(\n Topic,\n related_name='topic_comments',\n verbose_name='Topic'\n )\n\n text = models.TextField(\n max_length=2047,\n verbose_name='Comment text'\n )\n\n comment = models.ForeignKey(\n 'self', blank=True, null=True,\n related_name='child_comments',\n verbose_name='Parent comment'\n )\n\n is_archive = models.BooleanField(\n default=False,\n verbose_name='Comment is archived'\n )\n\n created = models.DateTimeField(\n auto_now_add=True,\n verbose_name='Creation date'\n )\n\n updated = models.DateTimeField(\n auto_now=True,\n verbose_name='Updation date'\n )\n\n class Meta:\n verbose_name = 'Comment'\n verbose_name_plural = 'Comments'\n ordering = 'topic', 'author', 'id'\n\n def __unicode__(self):\n return str(self.id)\n\n","sub_path":"mipt_overflow/src/comments/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"506998565","text":"import collections\n\nimport serializable\n\nENTITY_TYPE_TO_ICON_URL = {\n 'Sightseeing': 'sight-2.png',\n 'Food': 'restaurant.png',\n 'Hotel': 'lodging_0star.png',\n 'Shopping': 'departmentstore.png',\n 'Nightlife': 'bar_coktail.png',\n}\n\nclass Entity(serializable.Serializable):\n PUBLIC_FIELDS = serializable.fields('name', 'entity_type', 'address',\n 'lat', 'lng', serializable.listf('urls'), serializable.listf('related_urls'),\n serializable.listf('image_urls'), 'tripadvisor_rating',\n 'yelp_rating', 'foursquare_rating', 'price', 'icon_url')\n\n def __init__(self, name=None, entity_type=None, address=None,\n lat=None, lng=None, urls=(), related_urls=(), image_urls=(),\n tripadvisor_rating=None, yelp_rating=None,\n foursquare_rating=None, price=None, phone=None):\n self.name = name\n self.entity_type = entity_type\n self.address = address\n self.lat = lat\n self.lng = lng\n self.urls = urls\n self.related_urls = related_urls\n self.image_urls = image_urls\n self.tripadvisor_rating = tripadvisor_rating\n self.yelp_rating = yelp_rating\n self.foursquare_rating = foursquare_rating\n self.price = price\n self.phone = phone\n\n self.icon_url = ENTITY_TYPE_TO_ICON_URL.get(self.entity_type, '')\n\n def initialize(self):\n self.icon_url = ENTITY_TYPE_TO_ICON_URL.get(self.entity_type, '')\n\nclass TripPlan(serializable.Serializable):\n PUBLIC_FIELDS = serializable.fields('title', serializable.objlistf('entities', Entity),\n 'entities_by_type')\n\n TYPES_IN_ORDER = ('Hotel', 'Food', 'Sightseeing', 'Shopping', 'Nightlife')\n\n def __init__(self, title=None, entities=()):\n self.title = title\n self.entities = entities\n\n self.entities_by_type = collections.defaultdict(list)\n for entity in entities:\n self.entities_by_type[entity.entity_type].append(entity)\n\n def entities_for_type(self, entity_type):\n return self.entities_by_type.get(entity_type, ())\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"358286207","text":"# -*- encoding:utf-8 -*-\nfrom locust import User, task, events, constant,HttpUser\nimport time\nimport websocketnew\nimport ssl\nimport json\nimport jsonpath\nimport pytest\nimport pymysql\nfrom threading import Thread\nfrom gevent._semaphore import Semaphore\n\n\nhost='rm-bp1ghcqu341s7aqoj.mysql.rds.aliyuncs.com'\nport=3306\nuser='kongzhibing'\npasswd='Kongzhibingqwer123456'\n\n\ndef selectSql(sql):\n db = pymysql.connect(\n host=host,\n port=port,\n user=user,\n passwd=passwd,\n charset='utf8')\n cursor = db.cursor()\n cursor.execute(sql)\n data = list(cursor.fetchall())\n return data\n\n\n\n#TODO:设置集合点\n# all_locusts_spawned = Semaphore()\n# all_locusts_spawned.acquire()\n\n\ndef on_message(ws, message):\n print(message)\n\n\n# 重新实现对应事件\ndef on_error(ws, error):\n print(\"occur error \" + error)\n\n\ndef on_close(ws):\n print(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^con is closed^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\n\n\ndef on_open(ws):\n # data = '{\"optionType\":\"2\",\"deptType\":\"1\",\"activityGoodsId\":4907,\"fieldName\":\"minPrice\",\"value\":\"66\",\"action\":\"EDIT_FIELD\"}'\n # ws.send(data)\n # 查询组货详情字段\n def run(*args):\n \"\"\"\n 修改各个商品各个字段的信息\n :param args:\n :return:\n \"\"\"\n activity_id = 885\n # 查询组货详情中的商品id\n sql = \"select a.`id` from `live_assistant_temp`.`tb_activity_goods` a where a.`activity_id`={activity_id} and a.`related_status`=1;\".format(\n activity_id=activity_id)\n activityGoodsIds = selectSql(sql)\n for activityGoodsId in activityGoodsIds:\n # 查询商品的默认字段名\n activityGoodsId = activityGoodsId[0]\n sql = \"select a.`field_name` from `live_assistant_temp`.`tb_activity_goods_field` a where a.`activity_goods_id`={activityGoodsId} and a.`field_type`=1 and a.`deleted_at` is null\".format(\n activityGoodsId=activityGoodsId)\n defaultFieldNames = selectSql(sql)\n for defaultFieldName in defaultFieldNames:\n defaultFieldName = defaultFieldName[0]\n values = ['2222']\n for value in values:\n standard = {\"optionType\": \"2\", \"deptType\": \"2\", \"activityGoodsId\": activityGoodsId,\n \"fieldName\": defaultFieldName, \"value\": value,\n \"action\": \"EDIT_FIELD\".format(defaultFieldName=defaultFieldName)}\n print(standard)\n ws.send(json.dumps(standard))\n time.sleep(2)\n time.sleep(1)\n ws.close()\n\n\ndef eventType_success(eventType, recvText, total_time):\n events.request_success.fire(request_type=\"[RECV]\",\n name=eventType,\n response_time=total_time,\n response_length=len(recvText))\n\n\nclass WebSocketClient(object):\n _locust_environment = None\n\n def __init__(self, host):\n self.host = host\n # 针对 WSS 关闭 SSL 校验警报\n self.ws = websocketnew.WebSocket(sslopt={\"cert_reqs\": ssl.CERT_NONE})\n\n def connect(self):\n start_time = time.time()\n try:\n self.ws = websocketnew.WebSocketApp(self.host,\n on_message = on_message,\n on_error = on_error,\n on_open = on_open,\n on_close=on_close,)\n self.ws.run_forever()\n except websocketnew.WebSocketConnectionClosedException as e:\n total_time = int((time.time() - start_time) * 1000)\n events.request_failure.fire(\n request_type=\"[Connect]\", name='Connection is already closed', response_time=total_time, exception=e)\n except websocketnew.WebSocketTimeoutException as e:\n total_time = int((time.time() - start_time) * 1000)\n events.request_failure.fire(\n request_type=\"[Connect]\", name='TimeOut', response_time=total_time, exception=e)\n else:\n total_time = int((time.time() - start_time) * 1000)\n events.request_success.fire(\n request_type=\"[Connect]\", name='WebSocket', response_time=total_time, response_length=0)\n\n\n\n def execut(self):\n self.ws.run_forever()\n\n\nclass WebsocketUser(User):\n abstract = True\n\n def __init__(self, *args, **kwargs):\n super(WebsocketUser, self).__init__(*args, **kwargs)\n self.client = WebSocketClient(self.host)\n self.client._locust_environment = self.environment\n\n\nclass ApiUser(WebsocketUser):\n host = 'ws://116.62.106.122:5111/?sid=860missionGoodsDetail&token=2777af36-d4f0-48a1-910c-0bb1a9711730'\n wait_time = constant(0)\n\n # def on_start(self):\n # self.client.connect()\n # all_locuts_spwned.wait()\n\n @task\n def executLONG(self):\n self.client.connect()\n\n\n\n","sub_path":"xingNeng/longWebsocketLocust.py","file_name":"longWebsocketLocust.py","file_ext":"py","file_size_in_byte":5033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"559194159","text":"#!/usr/bin/env python\n# coding=utf8\n\nimport sys\nimport asyncio\nimport logging\n\nimport time\n\nimport kaztron\nfrom kaztron import runner\nfrom kaztron.config import get_kaztron_config\nfrom kaztron.utils.logging import setup_logging\n\n# In the loving memory of my time as a moderator of r/worldbuilding network\n# To the future dev, this whole thing is a mess that somehow works. Sorry for the inconvenience.\n# (Assuming this is from Kazandaki -- Laogeodritt)\n\n\n# load configuration\ntry:\n config = get_kaztron_config(kaztron.cfg_defaults)\nexcept OSError as e:\n print(str(e), file=sys.stderr)\n sys.exit(runner.ErrorCodes.CFG_FILE)\n\n# setup logging\nsetup_logging(logging.getLogger(), config) # setup the root logger\nlogger = logging.getLogger(\"kaztron.bootstrap\")\n\n\ndef reset_backoff(backoff: runner.Backoff, sequence):\n if sequence == backoff.n: # don't do it if we had a retry in the meantime\n backoff.reset()\n\n\nif __name__ == '__main__':\n logger.info(\"Welcome to KazTron v{}, booting up...\".format(kaztron.__version__))\n\n loop = asyncio.get_event_loop()\n try:\n bo_timer = runner.Backoff(initial_time=3.0, base=1.58, max_attempts=12)\n wait_time = 0\n while True:\n reset_task = loop.call_later(wait_time, reset_backoff, bo_timer, bo_timer.n)\n runner.run(loop)\n logger.error(\"Bot halted unexpectedly.\")\n reset_task.cancel()\n wait_time = bo_timer.next()\n logger.info(\"Restarting bot in {:.1f} seconds...\".format(wait_time))\n time.sleep(wait_time)\n logger.info(\"Restarting bot...\")\n except StopIteration:\n logger.error(\"Too many failed attempts. Exiting.\")\n sys.exit(runner.ErrorCodes.RETRY_MAX_ATTEMPTS)\n except KeyboardInterrupt: # outside of runner.run\n logger.info(\"Interrupted by user. Exiting.\")\n finally:\n logger.info(\"Exiting.\")\n loop.close()\n","sub_path":"KazTron.py","file_name":"KazTron.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"133709434","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import, division, print_function\n\nimport logging\n\nimport numpy as np\n\n__all__ = ['Data']\nlog = logging.getLogger(__name__)\n\n\nclass Data(object):\n \"\"\"Data set.\n\n Args:\n x (tensor): Inputs with rows corresponding to data points and columns to\n features.\n y (tensor): Multiple outputs with rows corresponding to data points and\n columns to outputs.\n \"\"\"\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n # Set some handy properties.\n self.n = x.shape[0] # Number of data points\n self.m = x.shape[1] # Number of features\n self.p = y.shape[1] # Number of outputs\n\n def per_output(self):\n \"\"\"Return observations per output, respecting that the data must be\n closed downwards.\n\n Returns:\n generator: Generator that generates tuples containing the\n observations per layer and a mask which observations are not\n missing relative to the previous layer.\n \"\"\"\n mask = np.ones(self.n).astype(np.bool)\n y = self.y\n\n for i in range(self.p):\n # Update mask and outputs.\n mask = ~np.isnan(y[mask, i])\n y = y[mask]\n\n # Give them.\n yield y, mask\n","sub_path":"gpar/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"29517453","text":"import numpy as np\nfrom agents.model import Actor, Critic\nfrom agents.noise import Noise\nfrom agents.replay import Replay\n\nclass Agent(object):\n def __init__(self, task):\n self.task = task\n self.state_size = task.state_size\n self.action_size = task.action_size\n self.action_low = task.action_low\n self.action_high = task.action_high\n \n #Parames\n self.MU = 0\n self.THETA = 0.15\n self.SIGMA = 0.10\n self.GAMMA = 0.99\n self.TAU = 0.001\n self.BATCHS = 256\n self.MAX_REWARD = -999999999\n\n #Actor Model\n self.actor_local = Actor(self.state_size, self.action_size, self.action_low, self.action_high)\n self.actor_target = Actor(self.state_size, self.action_size, self.action_low, self.action_high)\n #init\n self.actor_target.model.set_weights(self.actor_local.model.get_weights())\n\n #Critic Model\n self.critic_local = Critic(self.state_size, self.action_size)\n self.critic_target = Critic(self.state_size, self.action_size)\n #init\n self.critic_target.model.set_weights(self.critic_local.model.get_weights())\n\n #Noise process\n self.noiseObj = Noise(self.action_size, self.MU, self.THETA, self.SIGMA)\n \n #Replay memory\n self.replayObj = Replay(self.BATCHS)\n \n\n def reset_episode(self):\n self.count = 0\n self.total_reward = 0\n self.noiseObj.reset()\n state = self.task.reset()\n self.last_state = state\n return(state)\n\n def step(self, action, reward, next_state, done):\n self.replayObj.add(self.last_state, action, reward, next_state, done)\n self.total_reward += reward\n self.count += 1\n if self.total_reward > self.MAX_REWARD:\n self.MAX_REWARD = self.total_reward\n\n if len(self.replayObj) > self.BATCHS:\n experiences = self.replayObj.sample()\n self.learn(experiences)\n\n self.last_state = next_state\n\n def act(self, states):\n action = self.actor_local.model.predict(np.reshape(states, [-1, self.state_size]))[0]\n return(list(action + self.noiseObj.sample()))\n\n def learn(self, experiences):\n states = np.array([e.state for e in experiences if e is not None])\n actions = np.array([e.action for e in experiences if e is not None]).reshape(-1, self.action_size)\n rewards = np.array([e.reward for e in experiences if e is not None]).reshape(-1, 1)\n dones = np.array([e.done for e in experiences if e is not None]).reshape(-1, 1)\n\n next_state = np.array([e.next_state for e in experiences if e is not None])\n #获取预测next_state的actions 和目标模型的Q值\n next_actions = self.actor_target.model.predict_on_batch(next_state)\n \n next_Q_targets= self.critic_target.model.predict_on_batch([next_state, next_actions])\n Q_targets = rewards + self.GAMMA * next_Q_targets * (1 - dones)\n\n self.critic_local.model.train_on_batch(x=[states, actions], y=Q_targets)\n #训练actor 模型\n action_gradients = np.reshape(self.critic_local.get_action_gradients([states, actions, 0]), (-1, self.action_size))\n self.actor_local.train_fn([states, action_gradients, 1])\n \n self.update(self.critic_local.model, self.critic_target.model)\n self.update(self.actor_local.model, self.actor_target.model)\n\n def update(self, local_model, target_model):\n local_weights = np.array(local_model.get_weights())\n target_weights = np.array(target_model.get_weights())\n\n new_weights = self.TAU * local_weights + (1 - self.TAU) * target_weights\n target_model.set_weights(new_weights)\n","sub_path":"agents/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"610508155","text":"# -*- coding: UTF-8 -*-\nfrom django.views.generic import TemplateView\nfrom ch7 import views\n\n__author__ = 'ielkin'\n\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns('',\n url(r'^$', TemplateView.as_view(template_name='base.html'), name='index'),\n url(r'^meta/$', views.meta, name='meta'),\n url(r'^date/(?P\\w{3})/(?P\\d\\d)/$', views.date),\n (r'^date/birthday/$', views.date, {'month': 'Dec', 'day': '22'}),\n)","sub_path":"DjangoTwoScoops/icecream/ch7/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"73224756","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport json\nimport requests\nimport tempfile\nimport requests_cache\n\nclass Market(object):\n\n\t_session = None\n\t__DEFAULT_BASE_URL = 'https://api.coinmarketcap.com/v1/'\n\t__DEFAULT_TIMEOUT = 30\n\t__TEMPDIR_CACHE = True\n\n\tdef __init__(self, base_url = __DEFAULT_BASE_URL, request_timeout = __DEFAULT_TIMEOUT, tempdir_cache = __TEMPDIR_CACHE):\n\t\tself.base_url = base_url\n\t\tself.request_timeout = request_timeout\n\t\tself.cache_filename = 'coinmarketcap_cache'\n\t\tself.cache_name = os.path.join(tempfile.gettempdir(), self.cache_filename) if tempdir_cache else self.cache_filename\n\n\t@property\n\tdef session(self):\n\t\tif not self._session:\n\t\t\tself._session = requests_cache.core.CachedSession(cache_name=self.cache_name, backend='sqlite', expire_after=120)\n\t\t\tself._session.headers.update({'Content-Type': 'application/json'})\n\t\t\tself._session.headers.update({'User-agent': 'coinmarketcap - python wrapper around \\\n\t\t\t coinmarketcap.com (github.com/mrsmn/coinmarketcap-api)'})\n\t\treturn self._session\n\n\tdef __request(self, endpoint, params):\n\t\tresponse_object = self.session.get(self.base_url + endpoint, params = params, timeout = self.request_timeout)\n\n\t\ttry:\n\t\t\tresponse = json.loads(response_object.text)\n\n\t\t\tif isinstance(response, list) and response_object.status_code == 200:\n\t\t\t\tresponse = [dict(item, **{u'cached':response_object.from_cache}) for item in response]\n\t\t\tif isinstance(response, dict) and response_object.status_code == 200:\n\t\t\t\tresponse[u'cached'] = response_object.from_cache\n\n\t\texcept Exception as e:\n\t\t\treturn e\n\n\t\treturn response\n\n\tdef ticker(self, currency=\"\", **kwargs):\n\t\t\"\"\"\n\t\tReturns a list of dicts containing one/all the currencies\n\n\t\tOptional parameters:\n\n\t\tGET /ticker/\n\n\t\t(int) start - return results from rank [start] and above\n\t\t(int) limit - return a maximum of [limit] results (default is 100, use 0 to return all results)\n\t\t(string) convert - return price, 24h volume, and market cap in terms of another currency. Valid values are:\n\t\t\t\t \"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\",\n\t\t\t\t \"INR\", \"JPY\",\"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\",\n\t\t\t\t \"TRY\", \"TWD\", \"ZAR\"\n\n\t\tGET /ticker/{id}\n\n\t\t(string) convert - return price, 24h volume, and market cap in terms of another currency. Valid values are:\n\t\t\t\t \"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\",\n\t\t\t\t \"INR\", \"JPY\",\"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\",\n\t\t\t\t \"TRY\", \"TWD\", \"ZAR\"\n\n\t\tMisc:\n\n\t\tAll 'last_updated' fields are unix timestamps.\n\t\t\"\"\"\n\n\t\tparams = {}\n\t\tparams.update(kwargs)\n\n\t\t# see https://github.com/mrsmn/coinmarketcap/pull/28\n\t\tif currency:\n\t\t\tcurrency = currency + '/'\n\n\t\tresponse = self.__request('ticker/' + currency, params)\n\t\treturn response\n\n\tdef stats(self, **kwargs):\n\t\t\"\"\"\n\t\tReturns a dict containing cryptocurrency statistics.\n\n\t\tOptional parameters:\n\n\t\t(string) convert - return 24h volume, and market cap in terms of another currency. Valid values are:\n\t\t\t\t \"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\",\n\t\t\t\t \"INR\", \"JPY\", \"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\",\n\t\t\t\t \"TRY\", \"TWD\", \"ZAR\"\n\n\t\tMisc:\n\n\t\tAll 'last_updated' fields are unix timestamps.\n\t\t\"\"\"\n\n\t\tparams = {}\n\t\tparams.update(kwargs)\n\t\tresponse = self.__request('global/', params)\n\t\treturn response\n","sub_path":"coinmarketcap/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"593909430","text":"#!/usr/bin/env python\n\n# -*- coding: utf-8 -*-\n\nimport threading\n\nfrom datetime import datetime\n\nfrom time import sleep\n\nloops = [4,2]\n\nclass ThreadFunc(object):\n\tdef __init__(self, func, args, name=''):\n\t\tself.func = func\n\t\tself.name = name\n\t\tself.args = args\n\n\tdef __call__(self):\n\t\t#只要定义类型的时候,实现__call__函数,这个类型就成为可调用的\n\t\tself.func(*self.args)\n\ndef loop(nloop, nsec):\n\tprint ('start loop {} at: {}'.format(nloop, datetime.now().strftime('%Y-%m-%d:%H:%M:%S')))\n\tsleep(nsec)\n\tprint ('end loop {} at: {}\\r'.format(nloop, datetime.now().strftime('%Y-%m-%d:%H:%M:%S')))\n\ndef main():\n\tprint ('starting at: {}'.format(datetime.now().strftime('%Y-%m-%d:%H:%M:%S')))\n\tthreads = []\n\tnloops = range(len(loops))\n\t# 创建一个thread实例, 传给它一个可调用类对象\n\tfor i in nloops:\n\t\tt = threading.Thread(target=ThreadFunc(func=loop, args=(i, loops[i]), name=loop.__name__))\n\t\tthreads.append(t)\n\n\tfor i in nloops:\n\t\tthreads[i].start()\n\n\tfor i in nloops:\n\t\tthreads[i].join()\n\n\tprint('All Done at:{}'.format(datetime.now().strftime('%Y-%m-%d:%H:%M:%S')))\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"threads/threading_sync2.py","file_name":"threading_sync2.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"527116481","text":"# На вход подаются две строки целых чисел.\n# Напечатайте количество чисел из первой строки, которые встречаются во второй строке.\n# Напечатайте числа, которые встречаются и в первой строке, и во второй.\n# Пример ввода\n# 1 3 2\n# 4 3 2\n# Пример вывода\n# 2\n# 2 3\n\nl0 = [1,2,3,4,5,6]\nl1 = [4,5,7,8,9]\ns = set(l0).intersection(set(l1))\nprint (len(s))\nprint (s)\n\n","sub_path":"specialist/level1/ex46.py","file_name":"ex46.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"25280567","text":"import pandas as pd\nfrom scipy.interpolate import interp1d\nfrom scipy.integrate import quad\nimport numpy as np\n\nfilename = \"data/wave_statistics/not_north_sea.xlsx\"\nxls = pd.ExcelFile(filename)\nframes = [pd.read_excel(xls, sheet_name=sheet_name) for sheet_name in xls.sheet_names]\n\nwp = np.empty(0)\n\nfor tp, row in frames[0].iteritems():\n # y = tp_row # the row of tp values\n x = frames[0].index.values\n # print(y)\n # print(frames[0][tp].values)\n # hs = getHs(tp)\n hs = 1.5\n f = interp1d(x, frames[0][tp].values, fill_value=0, bounds_error=False)\n wp = np.append(wp, quad(f, 0, hs)[0])\n\nx = frames[0].index.values\n\n\ndef getWorkability(tp):\n return (3)\n\n\nd = {}\nfor tp, rows in frames[0].iteritems():\n d[tp] = getWorkability(tp)\n\ntotal = np.empty([xls.book.nsheets])\n\nhs_prev = 0\n\nfor i in range(xls.book.nsheets):\n hs_prev = 0\n total[i] = 0\n for tp, occ_rate in frames[i].iteritems():\n for hs, item in frames[i].iterrows():\n if d[tp] >= hs:\n total[i] += occ_rate[hs]\n else:\n total[i] += (d[tp] - hs_prev) / (hs - hs_prev) * occ_rate[hs]\n break\n hs_prev = hs\n\n# print(\"%1.0f percent \" % total)\nprint(total[0])\nprint(total[1])\n\nimport matplotlib.pyplot as plt\n\nfrom barplot import stacked_bar\n\ndata = np.transpose([(frames[i].sum(axis=1)).values for i in range(xls.book.nsheets)])\n\n# category_labels = ['Cat A', 'Cat B', 'Cat C', 'Cat D']\ncategory_labels = [sheet_name for sheet_name in xls.sheet_names]\nseries_labels = ['Hs = {:.2f} m'.format(hs) for hs in x]\n\nstacked_bar(data, series_labels, category_labels=category_labels, y_label=\"Occurance (%)\")\nplt.show()\n","sub_path":"lib/read_wave_statistics.py","file_name":"read_wave_statistics.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"371905894","text":"__author__ = 'kim'\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# from superclass model\n#features = np.array(['$H_1$', '$A_{HL}$', '$\\gamma_2$', 'Period', 'Period SNR',\nfeatures = np.array(['$H_1$', '$A$', '$\\gamma_2$', 'Period',\n '$\\psi^{CS}$', '$\\psi^{\\eta}$', '$\\phi_{21}$', '$\\phi_{31}$', '$Q_{3-1}$',\n '$R_{21}$', '$R_{31}$', '$W$', '$\\gamma_1$', '$m_{p10}$',\n '$m_{p90}$ ', '$K$'])\n#importance = np.log10(1000*np.array(\nimportance = np.array(\n [ 0.0838103, 0.04731345, 0.05649128, 0.22203722 , 0.03425052, 0.0597012,\n 0.01237353, 0.01205099, 0.06908623, 0.08775943, 0.04070028, 0.03292771,\n 0.06845165, 0.07809138, 0.06159055, 0.03336428])\n\n\nwidth = 1.0\nsorted_index = np.argsort(importance)[::-1]\nx = np.arange(len(features))\nplt.bar(x, importance[sorted_index], width=width, color='w')\nplt.xlabel('Variability feature', fontsize=15)\nplt.ylabel('Feature importance', fontsize=15)\nplt.xticks([])\nplt.xticks([])\n\n# label\nsorted_feature = features[sorted_index]\nfor i in range(len(sorted_feature)):\n fontsize = 18\n if sorted_feature[i] == 'Period' or sorted_feature[i] == 'Period SNR':\n fontsize = 15\n plt.text(i + width / 2., importance[sorted_index][i], sorted_feature[i],\n rotation=45, va='bottom', fontsize=fontsize)\nplt.axis([-1, 17, 0, 0.27])\nplt.savefig('feature_importance.eps')\n#plt.show()\n\n\n","sub_path":"plot_figures/feature_importance.py","file_name":"feature_importance.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"593234467","text":"# -*- coding: utf-8 -*-\nimport time\nimport logging\nfrom datetime import datetime\nfrom flask import request\n\nlog = logging.getLogger(__name__)\n\n\ndef before_request():\n request.start_time = time.time()\n request.time_ns = time.time_ns()\n\n\ndef log_after_request(response, request_latency):\n duration = request_latency / 1000000\n dt = datetime.fromtimestamp(request.start_time)\n timestamp = dt.isoformat('T')\n\n ip = request.headers.get('X-Forwarded-For', request.remote_addr)\n host = request.host.split(':', 1)[0]\n args = dict(request.args)\n request_id = request.headers.get('X-Request-ID') or ''\n\n log_params = {\n 'method': request.method,\n 'path': request.path,\n 'status': response.status_code,\n 'duration': int(duration),\n 'time': timestamp,\n 'ip': ip,\n 'request_host': host,\n 'params': args\n }\n\n if request_id:\n log_params['request_id'] = request_id\n\n log.info(f'{request.method} {request.path} : {response.status_code} : {duration} ms', extra=log_params)\n\n\ndef after_request(response):\n request_latency = time.time_ns() - request.time_ns\n log_after_request(response, request_latency)\n\n return response\n\n\ndef monitor(app):\n app.before_request(before_request)\n app.after_request(after_request)\n","sub_path":"family_tree/middleware/request_logging.py","file_name":"request_logging.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"354181608","text":"# -*- coding: utf-8 -*-\n\"\"\"Tests the xonsh lexer.\"\"\"\nfrom __future__ import unicode_literals, print_function\nimport sys\nimport glob\nimport builtins\nimport platform\nimport subprocess\nfrom collections import defaultdict\nfrom contextlib import contextmanager\n\nfrom nose.plugins.skip import SkipTest\n\nfrom xonsh.built_ins import ensure_list_of_strs\nbuiltins.__xonsh_env__ = {}\nfrom xonsh.base_shell import BaseShell\nfrom xonsh.execer import Execer\nfrom xonsh.tools import XonshBlockError\n\n\nVER_3_4 = (3, 4)\nVER_3_5 = (3, 5)\nVER_MAJOR_MINOR = sys.version_info[:2]\nVER_FULL = sys.version_info[:3]\nON_MAC = (platform.system() == 'Darwin')\n\ndef sp(cmd):\n return subprocess.check_output(cmd, universal_newlines=True)\n\nclass DummyStyler():\n styles = defaultdict(None.__class__)\n\nclass DummyBaseShell(BaseShell):\n\n def __init__(self):\n self.styler = DummyStyler()\n\n\nclass DummyShell:\n def settitle(self):\n pass\n\n _shell = None\n\n @property\n def shell(self):\n if self._shell is None:\n self._shell = DummyBaseShell()\n return self._shell\n\n\n@contextmanager\ndef mock_xonsh_env(xenv):\n builtins.__xonsh_env__ = xenv\n builtins.__xonsh_ctx__ = {}\n builtins.__xonsh_shell__ = DummyShell()\n builtins.__xonsh_help__ = lambda x: x\n builtins.__xonsh_glob__ = glob.glob\n builtins.__xonsh_exit__ = False\n builtins.__xonsh_superhelp__ = lambda x: x\n builtins.__xonsh_regexpath__ = lambda x: []\n builtins.__xonsh_expand_path__ = lambda x: x\n builtins.__xonsh_subproc_captured__ = sp\n builtins.__xonsh_subproc_uncaptured__ = sp\n builtins.__xonsh_ensure_list_of_strs__ = ensure_list_of_strs\n builtins.XonshBlockError = XonshBlockError\n builtins.evalx = eval\n builtins.execx = None\n builtins.compilex = None\n builtins.aliases = {}\n yield\n del builtins.__xonsh_env__\n del builtins.__xonsh_ctx__\n del builtins.__xonsh_shell__\n del builtins.__xonsh_help__\n del builtins.__xonsh_glob__\n del builtins.__xonsh_exit__\n del builtins.__xonsh_superhelp__\n del builtins.__xonsh_regexpath__\n del builtins.__xonsh_expand_path__\n del builtins.__xonsh_subproc_captured__\n del builtins.__xonsh_subproc_uncaptured__\n del builtins.__xonsh_ensure_list_of_strs__\n del builtins.XonshBlockError\n del builtins.evalx\n del builtins.execx\n del builtins.compilex\n del builtins.aliases\n\n\ndef skipper():\n \"\"\"Raises SkipTest\"\"\"\n raise SkipTest\n\ndef skip_if(cond):\n \"\"\"Skips a test under a given condition.\"\"\"\n def dec(f):\n if cond:\n return skipper\n else:\n return f\n return dec\n\n#\n# Execer tools\n#\n\nDEBUG_LEVEL = 0\nEXECER = None\n\ndef execer_setup():\n # only setup one parser\n global EXECER\n if EXECER is None:\n EXECER = Execer(debug_level=DEBUG_LEVEL, login=False)\n\ndef check_exec(input, **kwargs):\n with mock_xonsh_env(None):\n if not input.endswith('\\n'):\n input += '\\n'\n EXECER.debug_level = DEBUG_LEVEL\n EXECER.exec(input, **kwargs)\n\ndef check_eval(input):\n with mock_xonsh_env({'AUTO_CD': False, 'XONSH_ENCODING' :'utf-8',\n 'XONSH_ENCODING_ERRORS': 'strict', 'PATH': []}):\n EXECER.debug_level = DEBUG_LEVEL\n EXECER.eval(input)\n\ndef check_parse(input):\n with mock_xonsh_env(None):\n EXECER.debug_level = DEBUG_LEVEL\n tree = EXECER.parse(input, ctx=None)\n return tree\n\n","sub_path":"tests/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"202415567","text":"import glob\nimport optparse\nimport os\nimport subprocess\nimport sys\n\nfrom .__version__ import __version__\n\n# must have shell = True on Windows\nshellout = sys.platform == 'win32'\n\n\nclass EnvOptionParser(optparse.OptionParser):\n\n def error(self, msg, no=2):\n \"\"\"error(msg : string, [no : int])\n\n Print a usage message incorporating 'msg' to stderr and exit.\n Takes an optional error number.\n \"\"\"\n self.print_usage(sys.stderr)\n self.exit(no, \"%s: error: %s\\n\" % (self.get_prog_name(), msg))\n\n\nclass Runner(object):\n envdir_usage = \"usage: %prog [--help] [--version] dir child\"\n envshell_usage = \"usage: %prog [--help] [--version] dir\"\n\n def __init__(self):\n self.parser = EnvOptionParser(version=__version__)\n self.parser.disable_interspersed_args()\n\n @staticmethod\n def is_envvar(name):\n root, name = os.path.split(name)\n return (name == name.upper() and\n not name.startswith('_') and\n not '=' in name)\n\n def environ(self, path):\n env_paths = filter(self.is_envvar, glob.glob(os.path.join(path, '*')))\n for env_path in env_paths:\n with open(env_path, 'r') as env_file:\n root, name = os.path.split(env_path)\n value = env_file.read().strip().replace('\\x00', '\\n')\n yield name, value\n\n def path(self, path):\n real_path = os.path.realpath(os.path.expanduser(path))\n if not os.path.exists(real_path):\n # use 111 error code to adher to envdir's standard\n self.parser.error(\"envdir %r does not exist\" % path, no=111)\n if not os.path.isdir(real_path):\n # use 111 error code to adher to envdir's standard\n self.parser.error(\"envdir %r not a directory\" % path, no=111)\n return real_path\n\n def _default_envdir_path(self, frame):\n # frame here (inside *this* method) is not the same as in the\n # place where the method is invoked\n callerdir = os.path.dirname(frame.f_back.f_code.co_filename)\n return os.path.join(callerdir, 'envdir')\n\n def read(self, path=None):\n if path is None:\n path = self._default_envdir_path(sys._getframe())\n\n for name, value in self.environ(self.path(path)):\n if value:\n os.environ[name] = value\n elif name in os.environ:\n del os.environ[name]\n\n def write(self, path_or_envvars, envvars=None):\n if envvars is None:\n path = self._default_envdir_path(sys._getframe())\n envvars = path_or_envvars\n else:\n path = path_or_envvars\n # envvars already defined\n\n # trying to write to existing directory will cause OSError (or\n # FileExistsError on python 3)\n os.makedirs(path)\n for name, value in envvars.items():\n env_file_path = os.path.join(path, name)\n with open(env_file_path, 'w') as env_file:\n env_file.write('%s' % value)\n\n def shell(self, args):\n self.parser.set_usage(self.envshell_usage)\n self.parser.prog = 'envshell'\n\n if len(args) == 0:\n self.parser.error(\"incorrect number of arguments\")\n self.parser.print_usage()\n\n sys.stdout.write(\"Launching envshell for %s. \"\n \"Type 'exit' or 'Ctrl+D' to return.\\n\" %\n self.path(args[0]))\n sys.stdout.flush()\n self.read(args[0])\n\n try:\n subprocess.check_call([os.environ['SHELL']],\n universal_newlines=True,\n shell=shellout,\n bufsize=0,\n close_fds=True)\n except OSError as err:\n if err.errno == 2:\n self.parser.error(err.errno,\n \"Unable to find shell %s\" %\n os.environ['SHELL'])\n else:\n self.parser.exit(err.errno, '')\n\n def call(self, args):\n self.parser.set_usage(self.envdir_usage)\n self.parser.prog = 'envdir'\n\n if len(args) < 2:\n self.parser.error(\"incorrect number of arguments\")\n self.parser.print_usage()\n\n self.read(args[0])\n\n # the args to call later\n child_args = args[1:]\n\n # in case someone passes in -- for any reason to separate the commands\n if child_args[0] == '--':\n child_args = child_args[1:]\n\n try:\n subprocess.check_call(child_args,\n universal_newlines=True,\n shell=shellout,\n bufsize=0,\n close_fds=True)\n except OSError as err:\n if err.errno == 2:\n self.parser.error(err.errno,\n \"Unable to find command %s\" %\n child_args[0])\n else:\n self.parser.exit(err.errno, '')\n except subprocess.CalledProcessError as err:\n self.parser.exit(err.returncode, '')\n except KeyboardInterrupt:\n self.parser.exit()\n\n def main(self, name, args):\n options, args = self.parser.parse_args(args)\n if name.endswith('envdir') or name.endswith('__main__.py'):\n self.call(args)\n elif name.endswith('envshell'):\n self.shell(args)\n else:\n self.parser.print_usage(sys.stderr)\n\nenvdir = Runner()\n\n\ndef main():\n envdir.main(sys.argv[0], sys.argv[1:])\n\nif __name__ == '__main__':\n main()\n","sub_path":"envdir/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":5696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"279064714","text":"'''\n\tVarious helper functions used by Flask API implementation (app.py)\n'''\nfrom flask import json\n\nnutrient_id_map = {'protein': '203', 'fat': '204', 'carbs': '205', 'sugar': '269'}\n\ndef get_nutrient_id( nutrient ):\n return nutrient_id_map[nutrient]\n\ndef filter(parameters):\n\t# Filters food_data.json's foods based off a min/max nutrient values given in parameters\n\n\twith open('food_data.json') as food_json:\n\t\tdata = json.load(food_json)['report']['foods']\n\n\t\tfor param, val in parameters.items():\n\t\t\tdata = _filter_once(data, param, val)\n\t\t\n\t\treturn data\n\n\ndef _filter_once(data, parameter, value):\n\t# Filters out all invalid data from data and returns the filtered list once using given parameter and limit value\n\tif value != \"\":\n\t\tnutrient_id, is_min = _get_id_and_if_min(parameter)\n\t\tlimit = float(value)\n\t\tresult = []\n\n\t\tfor f in data:\n\t\t\tfor n in f['nutrients']:\n\t\t\t\tif n['nutrient_id'] == nutrient_id:\n\t\t\t\t\tval = 0.0 if n['value'] == '--' else float(n['value'])\n\t\t\t\t\tif is_min and val >= limit:\n\t\t\t\t\t\tresult.append(f)\n\t\t\t\t\telif not is_min and val <= limit:\n\t\t\t\t\t\tresult.append(f)\n\n\t\treturn result\n\n\ndef _get_id_and_if_min(parameter):\n\t# Splits the parameter into nutrient id and whether if it's a min filter\n\t nutrient, min_or_max = parameter.split('_')\n\t nutrient_id = get_nutrient_id(nutrient)\n\t is_min = True if min_or_max == \"min\" else False\n\n\t return (nutrient_id, is_min)","sub_path":"backend/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"374333870","text":"# Autor: Andrés Reyes Rangel.\n# Reproduce el juego de space invaders.\n\nimport pygame\n\n# Dimensiones de la pantalla\nANCHO = 800\nALTO = 600\n# Colores\nBLANCO = (255, 255, 255) # R,G,B en el rango [0,255]\nVERDE_BANDERA = (0, 122, 0)\nROJO = (255, 0, 0)\nAZUL = (0, 0, 255)\nNEGRO = (0, 0, 0)\n\n\n# Movimiento enemigos\nDerecha = True\nBajar = False\nayudita = 0\nnlineas = 0\n\n# Crea 60 enemigos en la lista\ndef crearEnemigos(listaEnemigos, imgEnemigo):\n for columna in range(1,13): # 1...12\n for renglon in range(1,8): # 1..5\n enemigo = pygame.sprite.Sprite()\n enemigo.image = imgEnemigo\n enemigo.rect = imgEnemigo.get_rect()\n enemigo.rect.left = columna*58\n enemigo.rect.top = renglon*60\n listaEnemigos.append(enemigo)\n\n\n\ndef dibujarEnemigos(ventana, listaEnemigos):\n global Bajar, Derecha, estadoJuego, PIERDE\n PIERDE = 5\n for enemigo in listaEnemigos:\n if Bajar:\n enemigo.rect.top += 20\n if Derecha:\n enemigo.rect.left += 2\n else:\n enemigo.rect.left -= 2\n Bajar = False\n for enemigo in listaEnemigos:\n ventana.blit(enemigo.image, enemigo.rect)\n xe, ye, ae, ale = enemigo.rect\n if xe == 0:\n Derecha = True\n Bajar = True\n if xe == ANCHO - ae:\n Derecha = False\n Bajar = True\n if ye >= ALTO - ale:\n estadoJuego = PIERDE\n\n\ndef dibujarBalas(ventana, listaBala):\n for bala in listaBala:\n ventana.blit(bala.image, bala.rect)\n\n\ndef actualizarBalas(listaBala):\n # MOVER BALAS\n for bala in listaBala:\n bala.rect.top -= 5\n # NO USAR ITERADOR CUANDO BORRO DATOS DE UNA LISTA\n # BORRAR\n for k in range(len(listaBala)-1, -1,-1):\n bala = listaBala[k]\n if bala.rect.top <= - bala.rect.height:\n listaBala.remove(bala)\n\n\ndef checarColisiones(listaBala, listaEnemigos):\n destruidos = 0\n for iB in range(len(listaBala)-1, -1, -1):\n bala = listaBala[iB]\n for iE in range(len(listaEnemigos)-1,-1,-1):\n enemigo = listaEnemigos[iE]\n xb, yb, ab, alb = bala.rect\n xe, ye, ae, ale = enemigo.rect\n if xb >= xe and xb <= xe + ae and yb >= ye and yb <= ye + ale:\n listaBala.remove(bala)\n listaEnemigos.remove(enemigo)\n # CONTAR ENEMIGOS DESTRUIDOS\n destruidos += 1\n break\n return destruidos\n\n\ndef checarColisionNave(listaEnemigos, nave):\n destruidos = 0\n for iE in range(len(listaEnemigos) - 1, -1, -1):\n enemigo = listaEnemigos[iE]\n xn, yn, an, aln = nave.rect\n xe, ye, ae, ale = enemigo.rect\n if xn <= xe + ae <= xn + an:\n if yn <= ye <= yn + aln:\n listaEnemigos.remove(enemigo)\n # CONTAR ENEMIGOS DESTRUIDOS\n destruidos += 1\n return destruidos\n\n\n# Estructura básica de un programa que usa pygame para dibujar\ndef dibujar():\n # Inicializa el motor de pygame\n pygame.init()\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana de dibujo\n reloj = pygame.time.Clock() # Para limitar los fps\n termina = False # Bandera para saber si termina la ejecución\n\n imgFondo = pygame.image.load(\"fondoMenu.png\")\n imgFondoJuego = pygame.image.load(\"fondoEspacio.png\")\n imgFondoPerdiste = pygame.image.load(\"fondoPerdiste.jpg\")\n imgBtnJugar = pygame.image.load(\"Boton_jugar.png\")\n imgBtnAyuda = pygame.image.load(\"Boton_Ayuda.png\")\n imgBtnVolver = pygame.image.load(\"Boton_Volver.png\")\n imgBtnMenu = pygame.image.load(\"Boton_Menu.png\")\n imgBtnSalir = pygame.image.load(\"Boton_Salir.png\")\n\n\n spriteBtnSalir = pygame.sprite.Sprite()\n spriteBtnSalir.image = imgBtnSalir\n spriteBtnSalir.rect = imgBtnSalir.get_rect()\n spriteBtnSalir.rect.left = 680\n spriteBtnSalir.rect.top = 550\n\n spriteBtnJugar = pygame.sprite.Sprite()\n spriteBtnJugar.image = imgBtnJugar\n spriteBtnJugar.rect = imgBtnJugar.get_rect()\n spriteBtnJugar.rect.left = 50\n spriteBtnJugar.rect.top = 500\n\n spriteBtnAyuda = pygame.sprite.Sprite()\n spriteBtnAyuda.image = imgBtnAyuda\n spriteBtnAyuda.rect = imgBtnAyuda.get_rect()\n spriteBtnAyuda.rect.left = 370\n spriteBtnAyuda.rect.top = 500\n\n spriteBtnVolver = pygame.sprite.Sprite()\n spriteBtnVolver.image = imgBtnVolver\n spriteBtnVolver.rect = imgBtnVolver.get_rect()\n spriteBtnVolver.rect.left = 570\n spriteBtnVolver.rect.top = 550\n\n spriteBtnMenu = pygame.sprite.Sprite()\n spriteBtnMenu.image = imgBtnMenu\n spriteBtnMenu.rect = imgBtnMenu.get_rect()\n spriteBtnMenu.rect.left = 550\n spriteBtnMenu.rect.top = 1\n\n # Estados\n MENU = 1\n JUEGO = 2\n AYUDA = 3\n GANA = 4\n PIERDE = 5\n estadoJuego = MENU\n\n # ENEMIGOS\n imgEnemigo = pygame.image.load(\"enemigoAbajo.png\")\n listaEnemigos = []\n crearEnemigos(listaEnemigos, imgEnemigo)\n\n # PERSONAJE.NAVE\n imgNave = pygame.image.load(\"nave.png\")\n nave = pygame.sprite.Sprite()\n nave.image = imgNave\n nave.rect = imgNave.get_rect()\n nave.rect.left = ANCHO // 2 - nave.rect.width // 2\n nave.rect.top = ALTO - nave.rect.height\n\n # PROYECTILES\n imgBala = pygame.image.load(\"bala.png\")\n listaBala = [] # Al inicio no hay balas\n\n # SONIDO AL DESTRUIR UN ENEMIGO\n pygame.mixer.init()\n efectoDestruye = pygame.mixer.Sound(\"shoot.wav\")\n pygame.mixer.music.load(\"musicaFondo.mp3\")\n pygame.mixer.music.play()\n\n # PANTALLA FIN (GANA)\n # PANTALLA BLANCA, LETRERO GANAS...\n puntos = 0 # Naves destruidas\n fuente = pygame.font.SysFont(\"monospaced\", 70)\n\n # TEXTO AYUDA\n ayudita = 0\n nlineas = 0\n\n while not termina: # Ciclo principal\n # Procesa los eventos que recibe el programa\n for evento in pygame.event.get():\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\n termina = True\n if evento.type == pygame.MOUSEBUTTONUP:\n xm, ym = pygame.mouse.get_pos()\n if estadoJuego == MENU:\n xbj, ybj, abj, albj = spriteBtnJugar.rect\n xba, yba, aba, alba = spriteBtnAyuda.rect\n if xbj <= xm <= xbj + abj:\n if ybj <= ym <= ybj+albj:\n estadoJuego = JUEGO # Cambia de estado\n elif xba <= xm <= xba + aba:\n if yba <= ym <= yba + alba:\n estadoJuego = AYUDA\n if evento.type == pygame.MOUSEBUTTONUP:\n xm, ym = pygame.mouse.get_pos()\n if estadoJuego == PIERDE or estadoJuego == GANA:\n xbv, ybv, abv, albv = spriteBtnSalir.rect\n if xbv <= xm <= xbv + abv:\n if ybv <= ym <= ybv + albv:\n termina = True\n if evento.type == pygame.KEYDOWN and estadoJuego == JUEGO:\n xn, yn, an, aln = nave.rect\n if evento.key == pygame.K_LEFT or evento.key == pygame.K_a:\n if xn > 0:\n nave.rect.left -= 20\n elif evento.key == pygame.K_RIGHT or evento.key == pygame.K_d:\n if xn + an < ANCHO:\n nave.rect.left += 20\n elif evento.key == pygame.K_UP or evento.key == pygame.K_SPACE or evento.key == pygame.K_w: # DISPARA\n efectoDestruye.play()\n bala = pygame.sprite.Sprite()\n bala.image = imgBala\n bala.rect = imgBala.get_rect()\n bala.rect.left = nave.rect.left + nave.rect.width//2\n bala.rect.top = nave.rect.top + bala.rect.height//4\n listaBala.append(bala)\n if evento.type == pygame.KEYDOWN and estadoJuego == AYUDA:\n if evento.key == pygame.K_UP and ayudita > 0:\n ayudita -= 1\n if evento.key == pygame.K_DOWN and ayudita < nlineas - 1:\n ayudita += 1\n if evento.type == pygame.MOUSEBUTTONUP:\n xm, ym = pygame.mouse.get_pos()\n if estadoJuego == AYUDA:\n xbm, ybm, abm, albm = spriteBtnMenu.rect\n if xbm <= xm <= xbm + abm:\n if ybm <= ym <= ybm + albm:\n estadoJuego = MENU\n\n # Borrar pantalla\n ventana.fill(NEGRO)\n\n # Dibujar, aquí haces todos los trazos que requieras\n # Normalmente llamas a otra función y le pasas -ventana- como parámetro, por ejemplo, dibujarLineas(ventana)\n\n if estadoJuego == MENU:\n ventana.blit(imgFondo, (0,0))\n ventana.blit(spriteBtnJugar.image, spriteBtnJugar.rect)\n ventana.blit(spriteBtnAyuda.image, spriteBtnAyuda.rect)\n elif estadoJuego == JUEGO:\n ventana.blit(imgFondoJuego, (0,0))\n dibujarEnemigos(ventana, listaEnemigos)\n dibujarBalas(ventana, listaBala)\n ventana.blit(nave.image, nave.rect)\n # ACTUALIZACIÓN\n actualizarBalas(listaBala)\n # VERIFICAR COLISIONES\n destruidos = checarColisiones(listaBala, listaEnemigos)\n naveDestruida = checarColisionNave(listaEnemigos, nave)\n puntos += destruidos\n if puntos >= 84:\n estadoJuego = GANA # TERMINA EL JUEGO, GANA\n elif naveDestruida == 1:\n estadoJuego = PIERDE\n texto = fuente.render(\"Puntuación: \" + str(puntos), 1, BLANCO) # MUESTRA EN LA PANTALLA LA PUNTUACIÓN DEL USUARIO.\n ventana.blit(texto, (0,0))\n elif estadoJuego == GANA:\n ventana.blit(imgFondoPerdiste, (0, 0))\n ventana.blit(spriteBtnSalir.image, spriteBtnSalir.rect)\n # TEXTO GANA\n texto = fuente.render(\"¡FELICIDADES HAS GANADO!\", 1, BLANCO)\n ventana.blit(texto, (55,270))\n elif estadoJuego == PIERDE:\n ventana.blit(imgFondoPerdiste, (0, 0))\n ventana.blit(spriteBtnSalir.image, spriteBtnSalir.rect)\n texto = fuente.render(\"¡GAME OVER!\", 1, ROJO)\n texto2 = fuente.render(\"PUNTUACION: \" + str(puntos), 1, ROJO)\n ventana.blit(texto2, (220,350))\n ventana.blit(texto, (240, 270))\n elif estadoJuego == AYUDA:\n ventana.blit(spriteBtnMenu.image, spriteBtnMenu.rect)\n # Archivo para poner las instrucciones\n nlineas = len(open('ayuda.txt').readlines())\n ayuda = open(\"ayuda.txt\", \"r\", encoding=\"UTF-8\")\n ayuda.seek(0)\n for i in range(0,ayudita):\n ayuda.readline()\n linea = ayuda.readline()\n cadena = linea.split(\",\")\n y = 70\n for i in range(0,len(cadena)):\n texto = fuente.render(cadena[i], 1, BLANCO)\n ventana.blit(texto, (10, y))\n y += 40\n texto = fuente.render(str(ayudita + 1) + \" / \" + str(nlineas), 1, BLANCO)\n ventana.blit(texto, (ANCHO - 100, ALTO - 40))\n ayuda.close()\n\n\n pygame.display.flip() # Actualiza trazos\n reloj.tick(40) # 40 fps\n\n # Después del ciclo principal\n pygame.quit() # termina pygame\n\n\ndef main():\n dibujar()\n\n\nmain()","sub_path":"SpaceInvaders.py","file_name":"SpaceInvaders.py","file_ext":"py","file_size_in_byte":11432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"28267240","text":"from django.contrib import admin\n\nfrom decimal import Decimal\n\nfrom models import Wallet, Address, Transaction, OutgoingTransaction\n\n\nclass WalletAdmin(admin.ModelAdmin):\n readonly_fields = [\n 'path',\n 'internal_wallet',\n 'getBalanceInfo',\n 'listTransactions',\n ]\n\n def listTransactions(self, instance):\n txs = Transaction.objects.filter(wallet=instance).order_by('created_at')\n result = ''\n for tx in txs:\n result += str(tx.created_at) + ' ' + unicode(tx) + '\\n'\n return result\n listTransactions.short_description = 'Transactions'\n\n def getBalanceInfo(self, instance):\n return u'Received: {}\\nSent: {}\\nTotal: {}'.format(\n instance.getReceived(0),\n instance.getSent(),\n instance.getBalance(0)\n )\n\n getBalanceInfo.short_description = 'Balance'\n\n\nclass AddressAdmin(admin.ModelAdmin):\n readonly_fields = [\n 'wallet',\n 'subpath_number',\n 'address',\n ]\n\n\nclass OutgoingTransactionAdmin(admin.ModelAdmin):\n readonly_fields = [\n 'created_at',\n 'inputs_selected_at',\n 'sent_at',\n 'listInputs',\n 'listOutputs',\n 'getFee',\n ]\n\n def listInputs(self, instance):\n if instance.inputs.count() == 0:\n return 'No inputs'\n result = ''\n total = Decimal(0)\n for inpt in instance.inputs.all():\n result += unicode(inpt) + '\\n'\n total += inpt.amount\n result += 'Total: ' + str(total) + ' BTC\\n'\n return result\n listInputs.short_description = 'Inputs'\n\n def listOutputs(self, instance):\n if instance.outputs.count() == 0:\n return 'No outputs'\n result = ''\n total = Decimal(0)\n for output in instance.outputs.all():\n result += unicode(output) + '\\n'\n total += output.amount\n result += 'Total: ' + str(total) + ' BTC\\n'\n return result\n listOutputs.short_description = 'Outputs'\n\n def getFee(self, instance):\n return instance.calculateFee()\n getFee.short_description = 'Fee'\n\n\nclass TransactionAdmin(admin.ModelAdmin):\n readonly_fields = [\n 'wallet',\n 'created_at',\n 'amount',\n 'description',\n 'receiving_address',\n 'sending_addresses',\n 'incoming_txid',\n 'block_height',\n 'outgoing_tx',\n ]\n\n list_display = ['__unicode__', 'created_at', 'amount', 'description']\n\nadmin.site.register(Wallet, WalletAdmin)\nadmin.site.register(Address, AddressAdmin)\nadmin.site.register(OutgoingTransaction, OutgoingTransactionAdmin)\nadmin.site.register(Transaction, TransactionAdmin)\n","sub_path":"bitcoin_webwallet/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"547127492","text":"\"\"\"Support for first generation Bosch smart home thermostats: Nefit Easy, Junkers CT100 etc.\"\"\"\n\nimport asyncio\nimport logging\n\nfrom aionefit import NefitCore\nimport voluptuous as vol\n\nfrom homeassistant import config_entries\n\n# from homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import EVENT_HOMEASSISTANT_STOP\nfrom homeassistant.exceptions import ConfigEntryNotReady\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.helpers.dispatcher import async_dispatcher_send\n\nfrom .const import (\n CONF_ACCESSKEY,\n CONF_DEVICES,\n CONF_MAX_TEMP,\n CONF_MIN_TEMP,\n CONF_NAME,\n CONF_PASSWORD,\n CONF_SENSORS,\n CONF_SERIAL,\n CONF_SWITCHES,\n CONF_TEMP_STEP,\n DISPATCHER_ON_DEVICE_UPDATE,\n DOMAIN,\n SENSOR_TYPES,\n STATE_CONNECTED,\n STATE_CONNECTION_VERIFIED,\n STATE_ERROR_AUTH,\n STATE_INIT,\n SWITCH_TYPES,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\nCONNECTION_SCHEMA = vol.Schema(\n {\n vol.Required(CONF_SERIAL): cv.string,\n vol.Required(CONF_ACCESSKEY): cv.string,\n vol.Required(CONF_PASSWORD): cv.string,\n vol.Optional(CONF_NAME, default=\"Nefit\"): cv.string,\n vol.Optional(CONF_SENSORS, default=list(SENSOR_TYPES)): vol.All(\n cv.ensure_list, [vol.In(SENSOR_TYPES)]\n ),\n vol.Optional(CONF_SWITCHES, default=list(SWITCH_TYPES)): vol.All(\n cv.ensure_list, [vol.In(SWITCH_TYPES)]\n ),\n vol.Optional(CONF_MIN_TEMP, default=10): cv.positive_int,\n vol.Optional(CONF_MAX_TEMP, default=28): cv.positive_int,\n vol.Optional(CONF_TEMP_STEP, default=0.5): cv.small_float,\n }\n)\n\nCONFIG_SCHEMA = vol.Schema(\n {\n DOMAIN: vol.Schema(\n {\n vol.Required(CONF_DEVICES): vol.All(\n cv.ensure_list, [CONNECTION_SCHEMA]\n ), # array of serial, accesskey, password\n }\n )\n },\n extra=vol.ALLOW_EXTRA,\n)\n\nDOMAINS = [\"climate\", \"sensor\", \"switch\"]\n\n\nasync def async_setup(hass, config):\n \"\"\"Set up the nefiteasy component.\"\"\"\n if DOMAIN not in config:\n return True\n\n conf = config[DOMAIN]\n\n if CONF_DEVICES not in conf:\n return True\n\n for device_conf in conf[CONF_DEVICES]:\n hass.async_create_task(\n hass.config_entries.flow.async_init(\n DOMAIN,\n context={\"source\": config_entries.SOURCE_IMPORT},\n data=device_conf,\n )\n )\n\n return True\n\n\nasync def async_setup_entry(hass, entry: config_entries.ConfigEntry):\n \"\"\"Set up the nefiteasy component.\"\"\"\n hass.data.setdefault(DOMAIN, {})\n\n hass.data[DOMAIN][entry.entry_id] = {}\n\n credentials = dict(entry.data)\n client = NefitEasy(hass, credentials)\n\n await client.connect()\n _LOGGER.debug(\"Is connected state? %s\", client.connected_state)\n\n if client.connected_state == STATE_CONNECTION_VERIFIED:\n hass.data[DOMAIN][entry.entry_id][\"client\"] = client\n _LOGGER.info(\n \"Successfully connected %s to Nefit device!\",\n credentials.get(CONF_SERIAL),\n )\n else:\n raise ConfigEntryNotReady\n\n for domain in DOMAINS:\n hass.async_create_task(\n hass.config_entries.async_forward_entry_setup(entry, domain)\n )\n\n return True\n\n\nasync def async_unload_entry(hass, entry: config_entries.ConfigEntry):\n \"\"\"Unload nefit easy component.\"\"\"\n if not all(\n await asyncio.gather(\n *[\n hass.config_entries.async_forward_entry_unload(entry, component)\n for component in DOMAINS\n ]\n )\n ):\n return False\n\n client = hass.data[DOMAIN][entry.entry_id][\"client\"]\n\n await client.shutdown()\n\n hass.data[DOMAIN].pop(entry.entry_id)\n\n return True\n\n\nclass NefitEasy:\n \"\"\"Supporting class for nefit easy.\"\"\"\n\n def __init__(self, hass, credentials):\n \"\"\"Initialize nefit easy component.\"\"\"\n _LOGGER.debug(\"Initialize Nefit class\")\n\n self.data = {} # stores device states and values\n self.keys = {} # unique name for entity\n self.events = {}\n self.ui_status_vars = {} # variables to monitor for sensors\n self.hass = hass\n self.connected_state = STATE_INIT\n self.expected_end = False\n self.is_connecting = False\n self.serial = credentials.get(CONF_SERIAL)\n\n self.nefit = NefitCore(\n serial_number=credentials.get(CONF_SERIAL),\n access_key=credentials.get(CONF_ACCESSKEY),\n password=credentials.get(CONF_PASSWORD),\n message_callback=self.parse_message,\n )\n\n self.nefit.failed_auth_handler = self.failed_auth_handler\n self.nefit.no_content_callback = self.no_content_callback\n self.nefit.session_end_callback = self.session_end_callback\n\n async def connect(self):\n \"\"\"Connect to nefit easy.\"\"\"\n _LOGGER.debug(\"Starting connecting..\")\n if not self.is_connecting:\n self.is_connecting = True\n retries_connection = 0\n\n while self.connected_state != STATE_CONNECTED and retries_connection < 3:\n await self.nefit.connect()\n _LOGGER.debug(\"Waiting for connected event\")\n try:\n await asyncio.wait_for(\n self.nefit.xmppclient.connected_event.wait(), timeout=29.0\n )\n self.connected_state = STATE_CONNECTED\n _LOGGER.debug(\"adding stop listener\")\n self.hass.bus.async_listen_once(\n EVENT_HOMEASSISTANT_STOP, self.shutdown\n )\n except asyncio.TimeoutError:\n _LOGGER.debug(\n \"TimeoutError on waiting for connected event (connection retries=%d)\",\n retries_connection,\n )\n retries_connection = retries_connection + 1\n except: # noqa: E722 pylint: disable=bare-except\n _LOGGER.debug(\"Unknown error\")\n\n # test password for decrypting messages if connected\n if self.connected_state == STATE_CONNECTED:\n _LOGGER.info(\n \"Testing connection (connect retries=%d)\", retries_connection\n )\n retries_validation = 0\n while (\n self.connected_state != STATE_CONNECTION_VERIFIED\n and retries_validation < 3\n ):\n try:\n self.nefit.get(\"/gateway/brandID\")\n await asyncio.wait_for(\n self.nefit.xmppclient.message_event.wait(), timeout=29.0\n )\n self.nefit.xmppclient.message_event.clear()\n\n if self.connected_state == STATE_ERROR_AUTH:\n self.is_connecting = False\n return\n\n self.connected_state = STATE_CONNECTION_VERIFIED\n _LOGGER.info(\n \"Connected %s with %d retries and %d test retries.\",\n self.serial,\n retries_connection,\n retries_validation,\n )\n except asyncio.TimeoutError:\n _LOGGER.error(\n \"Did not get a response in time for testing connection (validation retries=%d).\",\n retries_validation,\n )\n retries_validation = retries_validation + 1\n except: # noqa: E722 pylint: disable=bare-except\n _LOGGER.error(\"No connection while testing connection.\")\n break\n\n if self.connected_state != STATE_CONNECTION_VERIFIED:\n self.hass.components.persistent_notification.create(\n f\"Did not succeed in connecting {self.serial} to Bosch cloud after retrying 3 times. Retry in 30 seconds.\",\n title=\"Nefit connect error\",\n notification_id=\"nefit_connect_error\",\n )\n self.is_connecting = False\n\n # wait 30 seconds to retry\n await asyncio.sleep(30)\n await self.connect()\n\n self.is_connecting = False\n else:\n _LOGGER.debug(\"Connection procedure was already running..\")\n\n async def shutdown(self, event):\n \"\"\"Shutdown.\"\"\"\n _LOGGER.debug(\"Shutdown connection to Bosch cloud\")\n self.expected_end = True\n await self.nefit.disconnect()\n\n async def no_content_callback(self, data):\n \"\"\"Log no content.\"\"\"\n _LOGGER.debug(\"no_content_callback: %s\", data)\n\n async def failed_auth_handler(self, event):\n \"\"\"Handle failed auth.\"\"\"\n self.connected_state = STATE_ERROR_AUTH\n self.nefit.xmppclient.connected_event.set()\n\n # disconnect, since nothing will work from now.\n await self.shutdown(\"auth_failed\")\n\n if event == \"auth_error_password\":\n self.hass.components.persistent_notification.create(\n f\"Invalid password for connecting {self.serial} to Bosch cloud.\",\n title=\"Nefit password error\",\n notification_id=\"nefit_password_error\",\n )\n else:\n self.hass.components.persistent_notification.create(\n f\"Invalid credentials (serial or accesskey) for connecting {self.serial} to Bosch cloud.\",\n title=\"Nefit authentication error\",\n notification_id=\"nefit_logon_error\",\n )\n\n async def session_end_callback(self):\n \"\"\"If connection is closed unexpectedly, try to reconnect.\"\"\"\n if not self.expected_end:\n self.hass.components.persistent_notification.create(\n f\"Unexpected disconnect of {self.serial} with Bosch server. Try to reconnect..\",\n title=\"Nefit disconnect\",\n notification_id=\"nefit_disconnect\",\n )\n\n _LOGGER.info(\"Starting reconnect procedure.\")\n # Reset values\n self.connected_state = STATE_INIT\n self.expected_end = False\n\n # Retry connection\n await self.connect()\n\n async def parse_message(self, data):\n \"\"\"Message received callback function for the XMPP client.\"\"\"\n _LOGGER.debug(\"parse_message data %s\", data)\n if \"id\" not in data:\n _LOGGER.error(\"Unknown response received: %s\", data)\n return\n\n if data[\"id\"] in self.keys:\n key = self.keys[data[\"id\"]]\n _LOGGER.debug(\"Got update for %s.\", key)\n\n if (\n data[\"id\"] == \"/ecus/rrc/uiStatus\"\n and self.connected_state == STATE_CONNECTION_VERIFIED\n ):\n self.data[\"temp_setpoint\"] = float(data[\"value\"][\"TSP\"]) # for climate\n self.data[\"inhouse_temperature\"] = float(\n data[\"value\"][\"IHT\"]\n ) # for climate\n self.data[\"user_mode\"] = data[\"value\"][\"UMD\"] # for climate\n self.data[\"boiler_indicator\"] = data[\"value\"][\"BAI\"] # for climate\n self.data[\"last_update\"] = data[\"value\"][\"CTD\"]\n\n # Update all sensors/switches when there is new data form uiStatus\n for uikey in self.ui_status_vars:\n self.update_device_value(\n uikey, data[\"value\"].get(self.ui_status_vars[uikey])\n )\n\n self.update_device_value(key, data[\"value\"])\n\n # Mark event as finished if it was part of an update action\n if key in self.events:\n self.events[key].set()\n\n def update_device_value(self, key, value):\n \"\"\"Store new device value and send to dispatcher to be picked up by device.\"\"\"\n self.data[key] = value\n\n # send update signal to dispatcher to pick up new state\n signal = DISPATCHER_ON_DEVICE_UPDATE.format(key=key)\n async_dispatcher_send(self.hass, signal)\n\n async def get_value(self, key, url):\n \"\"\"Get value.\"\"\"\n is_new_key = url not in self.keys\n if is_new_key:\n self.events[key] = asyncio.Event()\n self.keys[url] = key\n event = self.events[key]\n event.clear() # clear old event\n self.nefit.get(url)\n await asyncio.wait_for(event.wait(), timeout=9)\n if is_new_key:\n del self.events[key]\n del self.keys[url]\n return self.data[key]\n","sub_path":"custom_components/nefiteasy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"411326086","text":"import http.client\nimport time\nimport yaml\nimport json\nfrom astropy.time import Time\nimport sys\nimport sender\n\nclass TelescopeController(object):\n \n def __init__(self, address, port, parameter_file_name, band):\n \n self.ip = address\n self.port = port\n self.band = band\n with open(parameter_file_name, 'r') as param_file:\n param_dict = yaml.safe_load(param_file)\n self.v_max_az = param_dict['telescope']['v_max_az'] \n self.v_max_alt = param_dict['telescope']['v_max_alt'] \n self.backend_host = param_dict['connection']['backend_host']\n self.sender_port = param_dict['connection']['sender_port']\n self.on_source_threshold = param_dict['data_logging']['on_source_threshold']\n self.on_source_rms = param_dict['data_logging']['on_source_rms']\n self.data_log_config_name = param_dict['data_logging']['data_log_config_name']\n self.data_log_config_file_name = param_dict['data_logging']['data_log_config_file_name']\n\n def connection(self):\n return http.client.HTTPConnection(self.ip, self.port)\n \n def get_response(self,conn):\n response = conn.getresponse()\n print(response.status, response.reason)\n time.sleep(1.)\n return response.read()\n \n def stow(self,stow_position):\n conn = self.connection()\n stow_Command = \"{\\\"path\\\":\\\"acu.dish_management_controller.stow\\\",\\\"params\\\":{\\\"action\\\":\\\"\" + stow_position + \"\\\"}}\" \n conn.request(\"PUT\", \"/devices/command\", stow_Command)\n self.get_response(conn)\n \n def initiate(self):\n conn = self.connection()\n \n print(\"getting command authority...\")\n get_cmd_authority = \"{\\\"path\\\":\\\"acu.command_arbiter.authority\\\",\\\"params\\\":{\\\"action\\\":\\\"1\\\"}}\"\n conn.request(\"PUT\", \"/devices/command\", get_cmd_authority)\n self.get_response(conn)\n \n print(\"unstowing telescope...\")\n self.stow(\"0\")\n \n \n print(\"activating axes...\")\n conn.request(\"PUT\", \"/devices/command\", \"{\\\"path\\\":\\\"acu.azimuth.activate\\\"}\")\n self.get_response(conn)\n conn.request(\"PUT\", \"/devices/command\", \"{\\\"path\\\":\\\"acu.elevation.activate\\\"}\")\n self.get_response(conn) \n time.sleep(10)\n \n print(\"set threshhold and averaging time for on_source...\")\n on_source_str_1 = \"{\\\"path\\\":\\\"acu.dish_management_controller.set_on_source_threshold\\\",\\\"params\\\":{\\\"threshold\\\":\\\"\"\n on_source_str_2 = \"\\\", \\\"time_period_for_rms_calculation\\\":\\\"\"\n on_source_command = on_source_str_1 + str(self.on_source_threshold) + on_source_str_2 + str(self.on_source_rms) + \"\\\"}}\"\n conn.request(\"PUT\", \"/devices/command\", on_source_command)\n self.get_response(conn)\n \n print(\"creating datalogging config...\")\n with open(self.data_log_config_file_name, 'r') as file:\n datalog_path = file.read()\n conn.request(\"PUT\", \"/datalogging/config\", body='{\"name\": \"' + self.data_log_config_name + '\",\"paths\": '+ datalog_path +'}')\n self.get_response(conn)\n \n #function for moving to certain position\n def move_pos(self, az_pos, alt_pos, rel_abs):\n conn = self.connection()\n az_posString_1 = \"{\\\"path\\\":\\\"acu.azimuth.slew_to_\"+rel_abs[0:3]+\"_pos\\\",\\\"params\\\":{\\\"new_axis_\"+rel_abs+\"_position_set_point\\\":\\\"\"\n az_posString_2 = \"\\\", \\\"new_axis_speed_set_point_for_this_move\\\":\\\"\"\n az_posCommand = az_posString_1 + str(az_pos) + az_posString_2 + str(self.v_max_az) + \"\\\"}}\"\n conn.request(\"PUT\", \"/devices/command\", az_posCommand)\n self.get_response(conn)\n time.sleep(1.)\n\n alt_posString_1 = \"{\\\"path\\\":\\\"acu.elevation.slew_to_\"+rel_abs[0:3]+\"_pos\\\",\\\"params\\\":{\\\"new_axis_\"+rel_abs+\"_position_set_point\\\":\\\"\"\n alt_posString_2 = \"\\\", \\\"new_axis_speed_set_point_for_this_move\\\":\\\"\"\n alt_posCommand = alt_posString_1 + str(alt_pos) + alt_posString_2 + str(self.v_max_alt) + \"\\\"}}\"\n conn.request(\"PUT\", \"/devices/command\", alt_posCommand)\n self.get_response(conn)\n time.sleep(1.)\n \n def move_band(self):\n print(\"moving indexer to band...\")\n conn = self.connection()\n indexer_str = \"{\\\"path\\\":\\\"acu.dish_management_controller.move_to_band\\\",\\\"params\\\":{\\\"action\\\":\\\"\"\n indexer_command = indexer_str + band + \"\\\"}}\"\n conn.request(\"PUT\", \"/devices/command\", indexer_command)\n self.get_response(conn)\n time.sleep(1.)\n \n def wait_for_pos_reached(self):\n conn = self.connection()\n curr_az = 9999.\n curr_az_set = 0.\n curr_alt = 9999.\n curr_alt_set = 0.\n curr_indexer = 9999.\n curr_indexer_set = 0.\n while(abs(curr_az-curr_az_set) > 0.001 and abs(curr_alt-curr_alt_set) > 0.001 and abs(curr_indexer-curr_indexer_set) > 0.001):\n conn.request(\"GET\", \"/devices/statusValue?path=acu.azimuth.p_act\")\n response = self.get_response(conn).decode('utf-8')\n result = json.loads(response)\n curr_az = float(result['value'])\n conn.request(\"GET\", \"/devices/statusValue?path=acu.azimuth.p_set\")\n response = self.get_response(conn).decode('utf-8')\n result = json.loads(response)\n curr_az_set = float(result['value'])\n \n conn.request(\"GET\", \"/devices/statusValue?path=acu.elevation.p_act\")\n response = self.get_response(conn).decode('utf-8')\n result = json.loads(response)\n curr_alt = float(result['value'])\n conn.request(\"GET\", \"/devices/statusValue?path=acu.elevation.p_set\")\n response = self.get_response(conn).decode('utf-8')\n result = json.loads(response)\n curr_alt_set = float(result['value'])\n \n conn.request(\"GET\", \"/devices/statusValue?path=acu.indexer.p_act\")\n response = self.get_response(conn).decode('utf-8')\n result = json.loads(response)\n curr_indexer = float(result['value'])\n conn.request(\"GET\", \"/devices/statusValue?path=acu.indexer.p_set\")\n response = self.get_response(conn).decode('utf-8')\n result = json.loads(response)\n curr_indexer_set = float(result['value'])\n \n print(\"alt difference: \" + str(abs(curr_alt - curr_alt_set))) \n print(\"az difference: \" + str(abs(curr_az-curr_az_set)))\n print(\"indexer difference: \" + str(abs(curr_indexer-curr_indexer_set)))\n time.sleep(1)\n \n def run_table(self, table, stop_time):\n print(\"running observation...\")\n conn = self.connection()\n conn.request(\"PUT\", \"/acuska/programTrack\", table)\n self.get_response(conn)\n time.sleep(10.)\n while Time.now() < stop_time:\n sys.stdout.write(\"\\rRemaining seconds:\" + str((stop_time.mjd - Time.now().mjd) * 24. * 3600.))\n sys.stdout.flush()\n time.sleep(1.)\n print(\"\\n\")\n \n def start_data_logging(self):\n \n print(\"starting datalogging...\")\n conn = self.connection()\n conn.request(\"PUT\", \"/datalogging/start?configName=test_configuration\")\n self.get_response(conn)\n \n def stop_data_logging(self):\n\n print(\"stopping datalogging...\")\n conn = self.connection()\n conn.request(\"PUT\", \"/datalogging/stop\")\n self.get_response(conn)\n \n def export(self, source_name, flux, ra, dec): \n #here with try and except, because we had problems with the server not responding\n #get uuid of datalogging session\n print(\"getting id of datalogging session\")\n conn.request(\"GET\", \"/datalogging/sessions\")\n response = getResponse(conn).decode('utf-8')\n time_start_i = [i.start()+13 for i in re.finditer('\"startTime\"', response)]\n time_end_i = [i.start()-3 for i in re.finditer(\"stopTime\", response)]\n times_array = [response[time_start_i[i]:time_end_i[i]] for i in range(len(time_start_i))]\n latest_time = max(times_array)\n uuid_end = response.find(str(latest_time)) - 14\n uuid_start = response.find('\"uuid\":',uuid_end-30, uuid_end) + 7\n uuid = response[uuid_start:uuid_end]\n\n\n #export session\n print(\"exporting session...\")\n header = \"#\" + \"Source name: \" + source_name + \", Source flux: \" + str(flux) + \", RA: \" + str(ra) + \", Dec: \" + str(dec) + \", Input Parameter: \" + str(sys.argv[1:]) + \"\\n\\n\"\n sender.send_log_file_info(uuid, header, self.backend_host, self.sender_port)\n \n conn.request(\"GET\", \"/datalogging/exportSession?interval_ms=100&id=\"+uuid)\n response = getResponse(conn).decode('utf-8')\n\n time_str=time.strftime(\"_%Y_%m_%d_%H_%M_%S\")\n log_file = open(log_file_name+time_str+\".txt\", \"w\")\n log_file.write(\"#\" + \"Source name: \" + source_name + \", Source flux: \" + str(flux) + \", RA: \" + str(ra) + \", Dec: \" + str(dec) + \", Input Parameter: \" + str(sys.argv[1:]) + \"\\n\\n\" + response)\n log_file.close()\n \n","sub_path":"telescope_controller.py","file_name":"telescope_controller.py","file_ext":"py","file_size_in_byte":9152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"499907971","text":"import itertools\n\n\ndef dict_product(d: dict):\n k = d.keys()\n v = d.values()\n v_product = itertools.product(*v)\n d_product = list()\n for v_p in v_product:\n d_one = dict(zip(k, v_p))\n d_product.append(d_one)\n return d_product\n","sub_path":"src/GEAR/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"203266072","text":"##############################################################\n# #\n# Mark Hoogendoorn and Burkhardt Funk (2017) #\n# Machine Learning for the Quantified Self #\n# Springer #\n# Chapter 3 #\n# #\n##############################################################\n\nimport numpy as np\nfrom pykalman import KalmanFilter\nimport warnings\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\",category=DeprecationWarning)\n warnings.filterwarnings(\"ignore\",category=FutureWarning)\n\n# Implements the Kalman filter for single columns.\nclass KalmanFilters:\n\n # Very simple Kalman filter: fill missing values and remove outliers for single attribute.\n # We assume a very simple transition matrix, namely simply a [[1]]. It\n # is however still useful as it is able to dampen outliers and impute missing values. The new\n # values are appended in a new column.\n def apply_kalman_filter(self, data_table, col):\n\n # Initialize the Kalman filter with the trivial transition and observation matrices.\n kf = KalmanFilter(transition_matrices = [[1]], observation_matrices = [[1]])\n\n numpy_array_state = data_table.as_matrix(columns=[col])\n numpy_array_state = numpy_array_state.astype(np.float32)\n numpy_matrix_state_with_mask = np.ma.masked_invalid(numpy_array_state)\n\n # Find the best other parameters based on the data (e.g. Q)\n kf = kf.em(numpy_matrix_state_with_mask, n_iter=5)\n\n # And apply the filter.\n (new_data, filtered_state_covariances) = kf.filter(numpy_matrix_state_with_mask)\n\n data_table[col + '_kalman'] = new_data\n return data_table\n","sub_path":"assignment3/Chapter3/KalmanFilters.py","file_name":"KalmanFilters.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"403944277","text":"#!/usr/bin/python3\n\nimport os\n\ncolabName=input('What is the name of this CoLab? (e.g. \"Climate\"):')\nuserName=input('What is the username of the user who will run the CoLab?:')\nrootPath=input('What is the absolute path of the root directory of the project? (usually the \"home\" of the dedicated user):')\n\nfileNameList=[]\nfor fileName in os.listdir('exec_pre'):\n\tfileNameList.append('exec_pre/'+fileName)\n\nfor fileName in os.listdir('systemd_unit_files'):\n\tfileNameList.append('systemd_unit_files/'+fileName)\n\nfileNameList.append('colab-permissions')\n\nfor fileName in fileNameList:\n\twith open(fileName, 'r') as file:\n\t\tfileData = file.read()\n\tfileData=fileData.replace('__X__',colabName)\n\tprint('Replaced __X__ with '+colabName)\t\n\tfileData=fileData.replace('__x__',colabName.lower())\n\tprint('Replaced __x__ with '+colabName.lower())\n\tfileData=fileData.replace('__user__',userName)\n\tprint('Replaced __user__ with '+userName)\n\tfileData=fileData.replace('__rootPath__',rootPath)\n\tprint('Replaced __rootPath__ with '+rootPath)\n\twith open(fileName,'w') as file:\n\t\tfile.write(fileData)\n\ncolabUnitFileName='systemd_unit_files/__x__-colab.service'\ncolabUnitNewName=colabUnitFileName.replace('__x__',colabName.lower())\nprint('Renamed '+colabUnitFileName+' to '+colabUnitNewName)\nos.replace(colabUnitFileName,colabUnitNewName)","sub_path":"systemd-config/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"413778156","text":"# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nmatplotlib.rcParams['font.sans-serif'] = ['SimHei']\nmatplotlib.rcParams['axes.unicode_minus'] = False\n\nname_list = ['Monday','Tuesday','Friday','Sunday']\nnum_list = [1.5,0.6,7.8,6]\nnum_list1 = [1,2,3,1]\nx =list(range(len(num_list)))\ntotal_width, n = 0.8, 2\nwidth = total_width / n\n\n\nplt.bar(x, num_list, width=width, label='部首',fc = 'b',tick_label = name_list)\n\nplt.legend()\n\nplt.grid(linestyle='-.')\nplt.show()\n","sub_path":"8matplotlibStudy/3barStudy.py","file_name":"3barStudy.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"98615169","text":"from __future__ import print_function, division\nimport sys\nimport os\nsys.path.append(os.path.abspath(\".\"))\nsys.dont_write_bytecode = True\nfrom utils.lib import O\nfrom utils.sk import rdivDemo\nfrom prettytable import PrettyTable\n\n__author__ = \"bigfatnoob\"\n\n\ndef median_iqr(lst, ordered=False):\n if not ordered:\n lst = sorted(lst)\n n = len(lst)\n q = n // 4\n iqr = lst[q * 3] - lst[q]\n if n % 2:\n return lst[q * 2], iqr\n else:\n p = max(0, q - 1)\n return (lst[p] + lst[q]) * 0.5, iqr\n\n\nclass Statistics(O):\n @staticmethod\n def default_settings():\n return O(\n gen_step=20\n )\n\n def __init__(self, settings=None):\n O.__init__(self)\n self.generations = []\n self.runtime = 0\n if not settings:\n settings = Statistics.default_settings()\n self.settings = settings\n\n def insert(self, pop):\n self.generations.append(pop)\n return self\n\n def tiles(self):\n num_obs = len(self.generations[0][0].objectives)\n for i in range(num_obs):\n obj_gens = []\n for gen, pop in enumerate(self.generations):\n if gen % self.settings.gen_step != 0:\n continue\n objs = [\"gen%d_f%d\" % (gen, i + 1)]\n for point in pop:\n objs.append(point.objectives[i])\n obj_gens.append(objs)\n rdivDemo(obj_gens)\n\n def median_spread(self):\n num_obs = len(self.generations[0][0].objectives)\n data = []\n for i in range(num_obs):\n data_map = {}\n meds = []\n iqrs = []\n for gen, pop in enumerate(self.generations):\n objs = [pt.objectives[i] for pt in pop]\n med, iqr = median_iqr(objs)\n meds.append(med)\n iqrs.append(iqr)\n data_map[\"meds\"] = meds\n data_map[\"iqrs\"] = iqrs\n data.append(data_map)\n return data\n\n def spit_objectives(self):\n objectives = []\n for point in self.generations[-1]:\n objectives.append(point.objectives)\n return objectives\n\n @staticmethod\n def tabulate(columns, pt):\n tab = PrettyTable(columns)\n tab.align[\"name\"] = \"l\"\n nodes = pt.get_nodes()\n for node in nodes:\n row = []\n for key in columns:\n row.append(node.has()[key])\n tab.add_row(row)\n print(tab)\n\n def get_objectives(self, index, obj_ids):\n return [[point.objectives[obj_id]\n if isinstance(point.objectives[obj_id], int) else point.objectives[obj_id].value\n for obj_id in obj_ids] for point in self.generations[index]]\n\n def get_objectives_samples(self, index, obj_ids):\n return [[[point.objectives[obj_id]]\n if isinstance(point.objectives[obj_id], int) else point.objectives[obj_id].has()['_samples'].tolist()\n for obj_id in obj_ids] for point in self.generations[index]]\n\n def get_objective_samples(self, index, obj_id):\n return [[point.objectives[obj_id]]\n if isinstance(point.objectives[obj_id], int) else point.objectives[obj_id].has()['_samples'].tolist()\n for point in self.generations[index]]\n","sub_path":"utils/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":2962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"245153898","text":"#Crie um programa que leia dois valores e mostre um menu na tela:\n#[1] Somar: [2] Multiplicar: [3] Maior: [4] Novos números {5] Sair do programa:\n#Seu programa deverá realizar a operação solicitada em cada caso.\nfrom time import sleep\nop = 0\ns = 0\nm = 0\nma = 0\nn1 = 0\nn2 = 0\nv1 = float(input('Digite um valor: '))\nv2 = float(input('Digite outro: '))\nwhile op != 5:\n print(\"\"\"Escolha o que fazer com esses valores:\n [ 1 ] Somar \n [ 2 ] Multiplicar \n [ 3 ] Maior \n [ 4 ] Novos números\n [ 5 ] Sair do programa\"\"\")\n op = int(input('Qual a sua opção ?'))\n if op == 1:\n s = v1 + v1\n print('A soma dos números é de {}'.format(s))\n elif op == 2:\n m = v1 * v2\n print('A multiplicação dos números é de {}'.format(m))\n elif op == 3:\n if v1 > v2:\n ma = v1\n else:\n ma = v2\n print('O maior número é o {}'.format(ma))\n elif op == 4:\n print('Informe os novos valores')\n v1 = int(input('Digite um novo valor: '))\n v2 = int(input('Digite outro: '))\n\n elif op == 5:\n print('Finalizando...')\n sleep(2)\n else:\n print('Você digitou um valor de uma opção inexistênte!')\nprint('Fim do programa, obrigado por utiliza-lo')\n","sub_path":"ex59.py","file_name":"ex59.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"48857124","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass BrspiderSpider(scrapy.Spider):\n name = 'BRSpider'\n allowed_domains = ['https://www.baseball-reference.com/boxes/?month=10&day=9&year=2011']\n start_urls = ['https://www.baseball-reference.com/boxes/?month=10&day=9&year=2011']\n\n def parse(self, response):\n parser = scrapy.Selector(response)\n\n #Create array with selectors for each league\n XPATH_ALGAMES = \"//*[@id='standings-upto-AL-overall']/tbody\"\n XPATH_NLGAMES = \"//*[@id='standings-upto-NL-overall']/tbody\"\n ALgames = response.xpath(XPATH_ALGAMES)\n NLgames = response.xpath(XPATH_NLGAMES)\n\n #Extraction from html for AL teams\n XPATH_CITY_AL = XPATH_ALGAMES + \"//th/a\"\n XPATH_GB_AL = XPATH_ALGAMES + \"//td[4]\"\n XPATH_RS_AL = XPATH_ALGAMES + \"//td[5]\"\n XPATH_RA_AL = XPATH_ALGAMES + \"//td[6]\"\n XPATH_WINS_AL = XPATH_ALGAMES + \"//td[1]\"\n XPATH_LOSSES_AL = XPATH_ALGAMES + \"//td[2]\"\n XPATH_WINPER_AL = XPATH_ALGAMES + \"//td[3]\"\n\n raw_cities_AL = response.xpath(XPATH_CITY_AL).extract()\n raw_GBs_AL = response.xpath(XPATH_GB_AL).extract()\n raw_RSs_AL = response.xpath(XPATH_RS_AL).extract()\n raw_RAs_AL = response.xpath(XPATH_RA_AL).extract()\n raw_wins_AL = response.xpath(XPATH_WINS_AL).extract()\n raw_losses_AL = response.xpath(XPATH_LOSSES_AL).extract()\n raw_winPer_AL = response.xpath(XPATH_WINPER_AL).extract()\n\n clean_cities_AL = [0] * len(raw_cities_AL)\n clean_RSs_AL = [0] * len(raw_cities_AL)\n clean_RAs_AL = [0] * len(raw_cities_AL)\n clean_GBs_AL = [0] * len(raw_cities_AL)\n clean_wins_AL = [0] * len(raw_cities_AL)\n clean_losses_AL = [0] * len(raw_cities_AL)\n clean_winPer_AL = [0] * len(raw_cities_AL)\n\n\n #parsing/cleaning strings for AL\n for i in range(len(raw_cities_AL)):\n clean_cities_AL[i] = raw_cities_AL[i][32:35]\n clean_RSs_AL[i] = raw_RSs_AL[i][34:38]\n clean_RSs_AL[i] = ''.join(c for c in clean_RSs_AL[i] if c.isdigit())\n clean_RAs_AL[i] = raw_RAs_AL[i][34:38]\n clean_RAs_AL[i] = ''.join(c for c in clean_RAs_AL[i] if c.isdigit())\n clean_wins_AL[i] = raw_wins_AL[i][33:36]\n clean_wins_AL[i] = ''.join(c for c in clean_wins_AL[i] if c.isdigit())\n clean_losses_AL[i] = raw_losses_AL[i][33:36]\n clean_losses_AL[i] = ''.join(c for c in clean_losses_AL[i] if c.isdigit())\n clean_winPer_AL[i] = raw_winPer_AL[i][45:49]\n\n clean_GBs_AL[0] = 0.0\n for i in range(1,len(raw_GBs_AL)):\n clean_GBs_AL[i] = raw_GBs_AL[i][43:46]\n\n #Extraction from html for NL teams\n XPATH_CITY_NL = XPATH_NLGAMES + \"//th/a\"\n XPATH_GB_NL = XPATH_NLGAMES + \"//td[4]\"\n XPATH_RS_NL = XPATH_NLGAMES + \"//td[5]\"\n XPATH_RA_NL = XPATH_NLGAMES + \"//td[6]\"\n XPATH_WINS_NL = XPATH_NLGAMES + \"//td[1]\"\n XPATH_LOSSES_NL = XPATH_NLGAMES + \"//td[2]\"\n XPATH_WINPER_NL = XPATH_NLGAMES + \"//td[3]\"\n\n raw_cities_NL = response.xpath(XPATH_CITY_NL).extract()\n raw_GBs_NL = response.xpath(XPATH_GB_NL).extract()\n raw_RSs_NL = response.xpath(XPATH_RS_NL).extract()\n raw_RAs_NL = response.xpath(XPATH_RA_NL).extract()\n raw_wins_NL = response.xpath(XPATH_WINS_NL).extract()\n raw_losses_NL = response.xpath(XPATH_LOSSES_NL).extract()\n raw_winPer_NL = response.xpath(XPATH_WINPER_NL).extract()\n\n clean_cities_NL = [0] * len(raw_cities_NL)\n clean_RSs_NL = [0] * len(raw_cities_NL)\n clean_RAs_NL = [0] * len(raw_cities_NL)\n clean_GBs_NL = [0] * len(raw_cities_NL)\n clean_wins_NL = [0] * len(raw_cities_NL)\n clean_losses_NL = [0] * len(raw_cities_NL)\n clean_winPer_NL = [0] * len(raw_cities_NL)\n\n #parsing/cleaning strings for NL\n for i in range(len(raw_cities_NL)):\n clean_cities_NL[i] = raw_cities_NL[i][32:35]\n clean_RSs_NL[i] = raw_RSs_NL[i][34:38]\n clean_RSs_NL[i] = ''.join(c for c in clean_RSs_NL[i] if c.isdigit())\n clean_RAs_NL[i] = raw_RAs_NL[i][34:38]\n clean_RAs_NL[i] = ''.join(c for c in clean_RAs_NL[i] if c.isdigit())\n clean_wins_NL[i] = raw_wins_NL[i][33:36]\n clean_wins_NL[i] = ''.join(c for c in clean_wins_NL[i] if c.isdigit())\n clean_losses_NL[i] = raw_losses_NL[i][33:36]\n clean_losses_NL[i] = ''.join(c for c in clean_losses_NL[i] if c.isdigit())\n clean_winPer_NL[i] = raw_winPer_NL[i][45:49]\n\n clean_GBs_NL[0] = 0.0\n for i in range(1,len(raw_GBs_NL)):\n clean_GBs_NL[i] = raw_GBs_NL[i][43:46]\n\n clean_cities = clean_cities_AL + clean_cities_NL\n clean_RSs = clean_RSs_AL + clean_RSs_NL\n clean_RAs = clean_RAs_AL + clean_RAs_NL\n clean_wins = clean_wins_AL + clean_wins_NL\n clean_losses = clean_losses_AL + clean_losses_NL\n clean_winPer = clean_winPer_AL + clean_winPer_NL\n clean_GBs = clean_GBs_AL + clean_GBs_NL\n\n print(\"CITIES TEST##########:\")\n print(clean_cities)\n\n for i in range(len(clean_cities)):\n yield{\n 'city': clean_cities[i],\n 'GB': clean_GBs[i],\n 'RS': clean_RSs[i],\n 'RA': clean_RAs[i],\n 'wins': clean_wins[i],\n 'losses': clean_losses[i],\n 'winper': clean_winPer[i]\n }\n\n \n","sub_path":"test3/test3/spiders/__pycache__/BRSpider.py","file_name":"BRSpider.py","file_ext":"py","file_size_in_byte":5526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"637874100","text":"import os\nimport pypact as pp\n\nfluxes = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'fluxes')\n\nff1 = pp.FluxesFile()\npp.from_file(ff1, fluxes)\n\n# normalise values\nsum1 = sum(ff1.values)\nff1.values = [v/sum1 for v in ff1.values]\n\nimport matplotlib.pyplot as plt\n\nplt.loglog(ff1.midPointEnergies, ff1.values, 'k', alpha=0.7, label='80 MeV proton beam')\nplt.xlabel(\"Energy (eV)\", fontsize=18)\nplt.ylabel(\"Normalised units\", fontsize=18)\nplt.grid()\nplt.legend()\nplt.show()\n","sub_path":"2020/exercises/files/advanced/tocsv/scripts/plotflux.py","file_name":"plotflux.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"332781925","text":"import os\nimport requests\ndirlist = os.listdir('.')\nif 'images' not in dirlist:\n os.mkdir('images')\npath = './images/'\nfor i in range(863, 941):\n for j in range(1, 51):\n url = f'http://img.mmjpg.com/2017/{i}/{j}.jpg'\n filename = path + f'{i}-{j}.jpg'\n percent = ((i - 863) * 50 + j) / ((941 - 863) * 50) * 100\n print(f'下载中,请稍候…… 已完成{percent:.2f}%', end='\\r')\n try:\n r = requests.get(url)\n r.raise_for_status()\n with open(filename, 'wb') as f:\n f.write(r.content)\n \n except:\n continue\n","sub_path":"getimages.py","file_name":"getimages.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"402324372","text":"from optparse import OptionParser, OptionGroup\nimport contest_master\nimport pandas as pd\nimport numpy as np\nimport Utils\n\nif __name__==\"__main__\":\n\n usage = \"usage: %prog [options]\"\n parser = OptionParser(usage=usage)\n\n parser.add_option(\"-v\",\"--verbose\", action=\"store_true\", dest=\"doVerbose\", default=False, help=\"Set the program in verbose mode\")\n parser.add_option(\"-f\",\"--forceCSV\", action=\"store_true\", dest=\"forceCSV\", default=False, help=\"Force CSV formatted file even thouth it existed\")\n parser.add_option(\"--contest\", action=\"store\", type=\"string\", default=\"cqww\", help=\"Contest type\")\n parser.add_option(\"--callsign\", action=\"store\", type=\"string\", default=\"p33w\", help=\"Callsign to analyze\")\n parser.add_option(\"--year\", action=\"store\", type=\"string\", default=\"2014\", help=\"Year of the CQ WW contest\")\n parser.add_option(\"--mode\", action=\"store\", type=\"string\", default=\"cw\", help=\"Mode of the CQ WW contest: cw or ph\")\n parser.add_option(\"--save\", action=\"store_true\", default=False, help=\"Save contest analysis in folder\")\n\n (options, args) = parser.parse_args()\n\n doVerbose = options.doVerbose\n forceCSV = options.forceCSV\n contestType = options.contest\n callsign = options.callsign\n year = options.year\n mode = options.mode\n save = options.save\n\n contest = contest_master.contest()\n\n contest.logName = \"logfiles/log_%s_%s_%s_%s.log\" % (contestType, year, mode, callsign)\n doLoop = Utils.importLog(contest=contest, contestType=contestType, year=year, mode=mode, callsign=callsign, forceCSV=forceCSV)\n\n # Get toolDictionary, with the tools to be applied.\n # To add a new tool:\n # - Define the class in a separate file\n # - Add it in toolDictionary\n import toolDictionary\n toolDict = toolDictionary.toolDictionary\n\n # If it's a new log, or forceCSV=True, loop on tools.\n # Two functions:\n # - applyToAll if computed using built-in functions in data frame.\n # - applyToRow if complex function that needs to be computed qso by qso.\n if doLoop:\n for tool in toolDict.names():\n contest.log = contest.log.apply(lambda row : toolDict.tools()[tool].applyToRow(row), axis=1)\n toolDict.tools()[tool].applyToAll(contest)\n\n # Save everything into formatted csv file\n contest.log.to_csv(\"%s_formatted.csv\" % (contest.logName.replace(\".log\", \"\")))\n\n # Common: read formatted csv and do studies\n contest.log = pd.read_csv(\"%s_formatted.csv\" % contest.logName.replace(\".log\", \"\"), dtype=Utils.dict_types)\n\n # Common: format fix for datetime\n contest.log[\"datetime\"] = pd.to_datetime(contest.log[\"datetime\"])\n\n # Plots\n import plotDictionary\n plotDict = plotDictionary.plotDictionary\n for plot in plotDict.names():\n plotDict.plots()[plot].doPlot(contest, False)\n","sub_path":"contestAnalyzer.py","file_name":"contestAnalyzer.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"315236322","text":"#!/usr/bin/env python\nimport env\n\nimport common.external_deps.dependency as dependency\ndependency.install('lxml')\n\nimport os\n\nfrom config_descr import NAME\nfrom common.description import Description\nfrom common.shared_logger import g_logger\nfrom common.config import get_global_property\nfrom common import descr_argument_parser\nfrom lxml import etree\n\n\ndef get_context_description():\n return Description({\n 'android_manifest_xml': {\n 'default': os.path.join(get_global_property(NAME.project_dir), \"android/AndroidManifest.xml\"),\n 'help': 'path to AndroidManifest.xml'\n },\n 'package': {\n 'default': \"\",\n 'help': 'package name',\n }\n })\n\n\ndef get_input_context(*argv, **kwargs):\n parser = descr_argument_parser.DescrArgumentParser()\n parser.add_descr(get_context_description())\n return parser.get_context(*argv, **kwargs)\n\n\ndef save_xml_tree(tree, path):\n dst_file = open(path, 'w')\n tree.getroot().tail = ''\n dst_file.write(etree.tostring(tree, pretty_print=True, encoding='utf8'))\n dst_file.close()\n\n\ndef do(context):\n g_logger.info(context)\n\n tree = etree.parse(context['android_manifest_xml'])\n root = tree.getroot()\n g_logger.info(root.attrib)\n if \"package\" in root.attrib and context[\"package\"]:\n g_logger.info(\"changing package from \\\"%s\\\" to \\\"%s\\\"\" % (root.attrib[\"package\"], context[\"package\"]))\n root.attrib[\"package\"] = context[\"package\"]\n save_xml_tree(tree, context['android_manifest_xml'])\n g_logger.info(\"done\")\n\n\nif __name__ == '__main__':\n do(get_input_context())\n","sub_path":"Scripts/helpers/edit_android_manifest.py","file_name":"edit_android_manifest.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"444629494","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 27 10:19:38 2021\n\n@author: vaziris\n\"\"\"\n'''\n\n'''\nfrom pprint import pprint\nimport pandas as pd\nimport geopandas as gpd \nimport numpy as np \nimport pickle\nimport json\nimport pygeoj\nimport pyproj\nimport shapely.geometry as sg\nfrom shapely.geometry import Polygon\nfrom shapely.geometry import Point\nimport swifter\nfrom shapely import ops \nimport matplotlib.pyplot as plt\nimport seaborn as sns\npd.set_option('display.max_columns', None)\npd.set_option('display.width', 100)\n\n\n#%%\n\n\n\n\n\ndef MyGrouping_Grid(df_inrix,df_incident ,width = 0.1,height = 0.1, Source_crs='EPSG:4326', Intended_crs='EPSG:4326' ):\n \n '''\n This function grids the state TN and returns the number of segments/groups and highway accidents per grid as well as the boundary and center of each grid\n \n Parameters\n ----------\n df_inrix : DF\n includes the inrix segment for all over TN\n df_incident : DF\n inlcudes the accident records for all over TN\n Source_crs,Intended_crs: Str\n you can choose between 'EPSG:4326' and 'EPSG:4326'.\n\n Returns\n -------\n Grid: GDF\n The Dataframe that incudes the the boundary and center of the grid as well as the the number of segments/groups and highway accidents per grid. The geometry feature is the boundary.\n Grid_center: GDF\n The Dataframe that incudes the the boundary and center of the grid as well as the the number of segments/groups and highway accidents per grid. The geometry feature is the center.\n \n ''' \n #%%Preparation\n if df_inrix is None: \n #Reading the Inrix Data\n df_inrix=pd.read_pickle('D:/inrix_new/inrix_pipeline/data_main/data/cleaned/Line/inrix_grouped.pkl')\n\n if df_incident is None: \n #Reading the Incident Data\n df_incident =pd.read_pickle('D:/inrix_new/inrix_pipeline/data_main/data/cleaned/Line/incident_XDSegID.pkl')\n df_incident=df_incident[df_incident['XDSegID'].notna()]\n \n\n #Convert to GDF and put the center as the geometry\n df_inrix['line']=df_inrix['geometry']\n df_inrix = gpd.GeoDataFrame(df_inrix, geometry=df_inrix['line'], crs={'init': Source_crs}).to_crs(Intended_crs)\n df_inrix['center']=df_inrix.centroid\n df_inrix = gpd.GeoDataFrame(df_inrix, geometry=df_inrix['center'], crs={'init': Intended_crs})\n \n #Convert to GDF\n df_incident = (gpd.GeoDataFrame(df_incident, geometry=df_incident['geometry'], crs={'init': Source_crs} )).to_crs(Intended_crs)\n #%%Defining Grid\n xmin,ymin,xmax,ymax = df_inrix['geometry'].total_bounds\n #xmin,ymin,xmax,ymax =[-90.15445012, 34.97582988, -81.72287999, 36.67620991]\n print('The bounding box is considered to be: ',xmin,ymin,xmax,ymax )\n \n rows = int(np.ceil((ymax-ymin) / height))\n cols = int(np.ceil((xmax-xmin) / width))\n XleftOrigin = xmin\n XrightOrigin = xmin + width\n YtopOrigin = ymax\n YbottomOrigin = ymax- height\n polygons = []\n X_id=[]\n Y_id=[]\n for i in range(cols):\n Ytop = YtopOrigin\n Ybottom =YbottomOrigin\n for j in range(rows):\n polygons.append(Polygon([(XleftOrigin, Ytop), (XrightOrigin, Ytop), (XrightOrigin, Ybottom), (XleftOrigin, Ybottom)])) \n X_id.append(i)\n Y_id.append(j)\n Ytop = Ytop - height\n Ybottom = Ybottom - height\n XleftOrigin = XleftOrigin + width\n XrightOrigin = XrightOrigin + width \n Grid = pd.DataFrame({'geometry':polygons,'X_id':X_id,'Y_id':Y_id }).reset_index().rename(columns={'index':'Grid_ID'})\n Grid['Boundary']=Grid['geometry']\n Grid = (gpd.GeoDataFrame(Grid, geometry=Grid['geometry'], crs={'init': Intended_crs} ))\n Grid['center']=Grid.centroid\n Grid\n #%%Adding Segment\n Grid_Inrix = gpd.sjoin(Grid[['Grid_ID','geometry']], df_inrix[['XDSegID','Miles','geometry']],how=\"left\", op='contains').drop('index_right',axis=1)\n DF_grouped=Grid_Inrix[['Grid_ID','XDSegID','Miles']].groupby('Grid_ID').agg({'XDSegID': ['count'],'Miles': ['sum']}) \n DF_grouped.columns=['Num_of_Seg','Miles_Seg']\n DF_grouped=DF_grouped.reset_index()\n Grid=pd.merge(Grid,DF_grouped, left_on='Grid_ID', right_on='Grid_ID', how='left' )\n #%%Adding Accident\n Grid_Incident = gpd.sjoin(Grid[['Grid_ID','geometry']], df_incident[['Incident_ID','geometry']],how=\"left\", op='contains').drop('index_right',axis=1)\n DF_grouped=Grid_Incident[['Grid_ID','Incident_ID']].groupby('Grid_ID').agg({'Incident_ID': ['count']}) \n DF_grouped.columns=['Num_of_Inc']\n DF_grouped=DF_grouped.reset_index()\n Grid=pd.merge(Grid,DF_grouped, left_on='Grid_ID', right_on='Grid_ID', how='left' )\n Grid_center=Grid.copy()\n Grid_center=(gpd.GeoDataFrame(pd.DataFrame(Grid_center), geometry=pd.DataFrame(Grid_center)['center'], crs={'init': Intended_crs} ))\n #%%Graphing\n sns.set()\n Fig,ax=plt.subplots(2,1,figsize=[20,10])\n Fig1=Grid.plot(column=(np.log(1+Grid['Num_of_Seg'])),ax=ax[0], legend = True); ax[0].set_title('log of segments per gird')\n Fig2=Grid.plot(column=(np.log(1+Grid['Num_of_Inc'])),ax=ax[1], legend = True); ax[1].set_title('log of accidents per gird') \n \n Fig,ax=plt.subplots(2,1,figsize=[20,10])\n Fig1=Grid.plot(ax=ax[0], legend = True); ax[0].set_title('Boundary of each grid');#ax[0].set_xlim(-91, -81);ax[0].set_ylim(34.5, 37) \n Fig2=Grid_center.plot(ax=ax[1], legend = True); ax[1].set_title('Center of each grid');#ax[1].set_xlim(-91, -81);ax[1].set_ylim(34.5, 37) \n \n return Grid,Grid_center\n\n\n\n\n\ndef Distance_Dict_Builder(All_seg_incident,Grid_center):\n '''\n This function builds a dictionary that contains the the distance between the intented segments/groups and Grids\n\n Parameters\n ----------\n All_seg_incident : DF\n This includes the segments/groups and their geometries, that we want to find their distances to the center of grids .\n Grid_center : GDF\n This is a GDF that for the grids and the geometry is the center of the grid .\n\n Returns\n -------\n Distant_Dic: Dictionary \n DESCRIPTION.\n All_seg_incident: GDF\n DESCRIPTION.\n\n '''\n\n #%%\n\n if All_seg_incident is None: \n df_grouped =pd.read_pickle('D:/inrix_new/data_main/data/cleaned/Line/grouped/grouped_3.pkl')\n df_=pd.read_pickle('D:/inrix_new/data_main/data/cleaned/Line/Regression_4h_History_G_top20_NoNA.pkl')\n All_seg_incident=df_grouped[df_grouped['Grouping'].isin(df_['XDSegID'])].reset_index().drop('index',axis=1) #just selecting the groups/segment with at least one accident\n \n #%% \n All_seg_incident['line']=All_seg_incident['geometry']\n All_seg_incident_4326=gpd.GeoDataFrame(All_seg_incident, geometry=All_seg_incident['line'], crs={'init': 'epsg:4326'} )\n All_seg_incident_4326['center']=All_seg_incident_4326.centroid\n All_seg_incident_4326=gpd.GeoDataFrame(All_seg_incident_4326, geometry=All_seg_incident_4326['center'], crs={'init': 'epsg:4326'} )\n \n \n '''\n def Center_Finder(row):\n #This function finds the the center of the line which connects the beggining and the end\n try:\n Beg=row['geometry'].coords[0]\n End=row['geometry'].coords[-1]\n except: \n Beg=row['geometry'][0].coords[0]\n End=row['geometry'][-1].coords[-1] \n \n return Point((Beg[0]+End[0])/2, (Beg[1]+End[1])/2) \n \n All_seg_incident['line']=All_seg_incident['geometry']\n All_seg_incident['center']=All_seg_incident.apply(lambda row: Center_Finder(row),axis=1)\n All_seg_incident_4326=gpd.GeoDataFrame(All_seg_incident, geometry=All_seg_incident['center'], crs={'init': 'epsg:4326'} )\n '''\n \n All_seg_incident_3310=All_seg_incident_4326.to_crs('EPSG:3310')\n Grid_center_3310=Grid_center.to_crs('EPSG:3310')\n \n #%%\n Distant_Dic={}\n for i,row_i in All_seg_incident_3310.iterrows():\n Distant_Dic[row_i.Grouping]={}\n for j,row_j in Grid_center_3310.iterrows(): \n Distant_Dic[row_i.Grouping][row_j.Grid_ID]=row_i['geometry'].distance(row_j['geometry'])/1000\n \n \n return Distant_Dic,All_seg_incident\n\n\n\n\n","sub_path":"allocation/Griding_TN.py","file_name":"Griding_TN.py","file_ext":"py","file_size_in_byte":8166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"292213","text":"from django.core.mail import send_mail\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.contrib.auth.models import User,auth,Group\nfrom django.conf import settings\nfrom moneymanagement.models import *\n\n# Create your views here.\n\ndef home(request):\n return render(request,'index.html')\n\n\ndef register(request):\n if request.method == 'POST':\n firstname= request.POST['firstname']\n lastname= request.POST['lastname']\n country= request.POST['country']\n dateofbirth= request.POST['dateofbirth']\n addressline1= request.POST['addressline1']\n countryname = Countries.objects.get(country_id=country).countryname\n if countryname == 'USA':\n addressline2= request.POST['addressline2']\n else:\n addressline2= request.POST.get('addressline2input', False); \n city= request.POST['city']\n postalcode= request.POST['postalcode']\n email= request.POST['email']\n mobileno= int(request.POST['mobileno'])\n ssnno= request.POST['ssnno']\n phoneno= request.POST['phoneno']\n print(len(phoneno))\n if len(phoneno) < 1:\n phoneno = 0 \n password = 12345\n to_email = [email]\n #student = Student.objects.last()\n if User.objects.filter(username=email).exists():\n \n return render(request,'home.html',{'module':'register','messages' : 'User already exists'})\n else:\n \n User.objects.create_user(username=email,password=password,\n email=email,first_name=firstname,last_name=lastname)\n UserID= User.objects.last().id\n UserDetail = UserDetails(userID_id=UserID,dateofbirth=dateofbirth,mobilenumber=mobileno,\n phonenumber=phoneno)\n \n UserAddress = Address(userID_id=UserID,addressLine1=addressline1,\n addressLine2=addressline2,city=city,postelCode=postalcode,\n ssnnNmber=ssnno,country=country)\n UserAddress.save()\n UserDetail.save()\n \n user = auth.authenticate(username=email,password=password)\n auth.login(request,user)\n request.session['userid'] = user.id\n request.session['useremail'] = user.email\n return render(request,'groups.html',{'module':'groups'})\n else:\n countries = Countries.objects.all()\n states = States.objects.all()\n return render(request,'home.html',{'module':'register','countries':countries,'states':states})\n \ndef login(request):\n if request.method == 'POST':\n email= request.POST['email']\n password= request.POST['password']\n user =auth.authenticate(username=email,password=password) \n \n \n if user is not None: \n auth.login(request,user)\n request.session['userid'] = user.id\n request.session['useremail'] = user.email\n return render(request,'groups.html',{'module':'groups'})\n else: \n return render(request,'home.html',{'module':'login','messages':'Invalid Username or Password'})\n \n \n # send_mail('Subject here', 'Here is the message.', settings.EMAIL_HOST_USER,\n # ['to@example.com'], fail_silently=False)\n return render(request,'home.html',{'module':'login'})\n\ndef logout(request):\n auth.logout(request)\n return render(request,'home.html',{'module':'login'})\n \ndef contact(request):\n return render(request,'home.html',{'module':'contact'})\n\ndef groups(request):\n return render(request,'groups.html',{'module':'groups'})\n\ndef creategroup(request):\n if request.method == 'POST':\n userid = request.session['userid']\n if GroupDescription.objects.filter(createBy=userid,isActive=1).exists():\n groups = GroupDescription.objects.filter(createBy=userid,isActive=1)\n return render(request,'useractivity.html',{'module':'invitegroup','groups':groups,'message':'You have already active group'})\n else: \n GroupName = request.POST['GroupName']\n payments = request.POST['payments']\n payfrequency = request.POST['payfrequency']\n startdate = request.POST['startdate']\n noofperiod = request.POST['noofperiod'] \n GroupDesc = GroupDescription(groupName=GroupName,payments=payments,\n paymentsFrequency=payfrequency,startDate=startdate\n ,noofperiod=noofperiod,createBy=userid,isActive=1)\n GroupDesc.save()\n userid = request.session['userid']\n groups = GroupDescription.objects.filter(createBy=userid,isActive=1)\n return render(request,'useractivity.html',{'module':'invitegroup','groups':groups})\n \n else:\n periodtypes = Periodtype.objects.all()\n return render(request,'useractivity.html',{'module':'creategroup','periodtypes':periodtypes})\n\ndef editprofile(request):\n userid = request.session['userid']\n if request.method == 'POST':\n firstname= request.POST['firstname']\n lastname= request.POST['lastname']\n addressline1= request.POST['addressline1']\n addressline2= request.POST['addressline2']\n city= request.POST['city']\n postalcode= request.POST['postalcode']\n \n mobileno= int(request.POST['mobileno'])\n message =''\n phoneno= request.POST['phoneno']\n print(len(phoneno))\n if len(phoneno) < 1:\n phoneno = 0 \n \n User.objects.filter(id=userid).update(first_name=firstname,last_name=lastname)\n UserDetails.objects.filter(userID__pk=userid).update(mobilenumber=mobileno,\n phonenumber=phoneno) \n Address.objects.filter(userID__pk=userid).update(addressLine1=addressline1,addressLine2=addressline2\n ,city=city,postelCode=postalcode) \n message='Profile Updated successfully'\n \n UserDetail = UserDetails.objects.get(userID__pk=userid)\n UserAddress = Address.objects.get(userID__pk=userid)\n countryname = Countries.objects.get(country_id=UserAddress.country).countryname\n if request.method == 'POST':\n return render(request,'useractivity.html',{'message':message,'module':'editprofile','UserDetail':UserDetail,'Address':UserAddress})\n else:\n return render(request,'useractivity.html',{'module':'editprofile','UserDetail':UserDetail,'Address':UserAddress,'countryname':countryname})\n \ndef payoutorder(request): \n userid = request.session['userid']\n \n if request.method == 'POST':\n count=0\n payoutlists = GroupDetails.objects.filter(isActive =1 )\n for payoutlist in payoutlists: \n payoutorder = request.POST[payoutlist.Username]\n GroupDetails.objects.filter(isActive =1,Username=payoutlist.Username).update(payoutOrder=payoutorder)\n count +=1 \n \n return render(request,'groups.html',{'module':'groups'}) \n else:\n payoutlists = GroupDetails.objects.filter(isActive =1 ) \n return render(request,'useractivity.html',{'module':'payoutorder','payoutlists':payoutlists})\n\ndef myinvitation(request,invitestatus=0,groupID=0):\n email = request.session['useremail']\n userid = request.session['userid'] \n if request.method == 'GET' and invitestatus != 0 and groupID != 0:\n if Settings.objects.filter(id =1).exists(): \n maxgroupcount = Settings.objects.get(id=1).maximumgroup\n else:\n maxgroupcount =10 \n \n groupcount =GroupDetails.objects.filter(id=groupID).count() \n if invitestatus == 1 and maxgroupcount <= groupcount :\n groupdetails = GroupDescription.objects.filter(id=groupID).get()\n GroupDetail = GroupDetails(userID =userid,payStatus=0,payoutOrder=0,\n Username= email,Createby=groupdetails.createBy,isActive=groupdetails.isActive,groupdescpID=groupID)\n GroupDetail.save()\n InvitationDetails.objects.filter(emailID=email,isInvite=1,groupID=groupID).update(isInvite=0)\n else:\n InvitationDetails.objects.filter(emailID=email,isInvite=1,groupID=groupID).update(isInvite=0)\n invitations=InvitationDetails.objects.filter(emailID=email,isInvite=1)\n return render(request,'useractivity.html',{'module':'myinvitation','invitations':invitations,'message':'You are late to accept this inviation'})\n \n invitations=InvitationDetails.objects.filter(emailID=email,isInvite=1)\n return render(request,'useractivity.html',{'module':'myinvitation','invitations':invitations,'message':'hi'})\n\ndef invitegroup(request): \n userid = request.session['userid']\n groups=GroupDescription.objects.filter(createBy=userid,isActive=1)\n if GroupDescription.objects.filter(createBy=userid,isActive=1).exists(): \n if request.method == 'POST': \n groupdesc= GroupDescription.objects.get(createBy=userid,isActive=1) \n email = request.POST['invitemail']\n groupID = groupdesc.pk \n if InvitationDetails.objects.filter(groupID=groupID,emailID=email,isInvite=1).exists():\n return render(request,'useractivity.html',{'module':'invitegroup','groups':groups,'message':'Invitation already send'})\n else: \n invitation =InvitationDetails(groupID=groupID,emailID=email,isInvite=1)\n invitation.save()\n return render(request,'useractivity.html',{'module':'invitegroup','groups':groups,'message':'Invitaion send Successfully'})\n else:\n return render(request,'useractivity.html',{'module':'invitegroup','groups':groups})\n else:\n return render(request,'useractivity.html',{'module':'invitegroup','groups':groups,'message':'You have not active group'})\n \n \ndef following(request):\n userid = request.session['userid']\n usergroups = GroupDescription.objects.filter(createBy=userid,isActive=1)\n return render(request,'useractivity.html',{'module':'following','groups':usergroups})\n\n\ndef follower(request):\n return render(request,'useractivity.html',{'module':'follower'})\n\ndef newcardregistor(request):\n return render(request,'usercard.html',{'module':'newcardregistor'})\n\ndef activegroups(request):\n groupdetails = GroupDescription.objects.filter(isActive=1)\n return render(request,'admin.html',{'module':'activegroup','groupdetails':groupdetails})\n\ndef setting(request):\n if request.method == 'POST':\n mingroup= request.POST['mingroup']\n maxgroup= request.POST['maxgroup']\n periodtype= request.POST['periodtype']\n if Settings.objects.filter(id =1).exists():\n Settings.objects.filter(id =1).update(minimumgroup=mingroup,maximumgroup=maxgroup)\n periodtype =Periodtype(periodtypename=periodtype)\n periodtype.save()\n else:\n groupsetting =Settings(minimumgroup=mingroup,maximumgroup=maxgroup)\n periodtype =Periodtype(periodtypename=periodtype)\n periodtype.save()\n groupsetting.save() \n return render(request,'admin.html',{'module':'setting','message':'setting insert successfully'})\n \n else:\n return render(request,'admin.html',{'module':'setting'})\n\ndef userlist(request):\n users = User.objects.all()\n return render(request,'admin.html',{'module':'userlist','Users':users})","sub_path":"Moneylending/moneymanagement/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"286785611","text":"my_var = False\nguess = 10\nprint(my_var)\nmy_num = 89.1010\nprint(type(my_num))\nmy_name = \"Mohamad\"\nmy_name2 = \"Mohamad\"\n\nif my_name == my_name2:\n print(\"Sama aja boskuh\")\nelse:\n print(\"Beda\")\n\nstr_one = \"Your\"\nstr_two = \"face\"\nprint(str_one + str_two)\nname = \"Mohamad\"\nname += \" Handy Nugraha\"\nprint(name)\n\n\nprint(f\"nilai kamu sebanyak {guess}\")\n","sub_path":"section7/section7.py","file_name":"section7.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"569172652","text":"from flask import Flask, jsonify, request\nfrom flask_restful import reqparse, abort, Api, Resource\nfrom datetime import datetime\n\napp = Flask(__name__)\napi = Api(app)\n\nTODOS = {\n 'todo1': {'task': 'build an api'},\n 'todo2': {'task': '?????'},\n 'todo3': {'task': 'profit'},\n}\n\ndef abort_todo_if_doesnt_exist(todo_id):\n if todo_id not in TODOS:\n abort(404, message=\"Todo {} doesn't exist\".format(todo_id))\nparser = reqparse.RequestParser()\nparser.add_argument('task')\n\nclass Todo(Resource):\n def get(self, todo_id):\n abort_todo_if_doesnt_exist(todo_id)\n return TODOS[todo_id]\n\n def delete(self, todo_id):\n abort_todo_if_doesnt_exist(todo_id)\n del TODOS[todo_id]\n return '', 204\n\n def put(self, todo_id):\n args = parser.parse_args()\n task = {'task':args['task']}\n TODOS[todo_id] = task\n return task, 201\n\nclass TodoList(Resource):\n def get(self):\n return TODOS\n\n def post(self):\n args = parser.parse_args()\n todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1\n todo_id = 'todo%i' % todo_id\n TODOS[todo_id] = {'task': args['task']}\n return TODOS[todo_id], 200\n\nclass Time(Resource):\n def get(self):\n return jsonify({\"message\":datetime.now()}), 200\n\nclass IP(Resource):\n def get(self):\n return request.environ.get('HTTP_X_REAL_IP',request.remote_addr), 200\n\n\napi.add_resource(TodoList,'/todos')\napi.add_resource(Todo, '/todos/')\napi.add_resource(Time,'/time')\napi.add_resource(IP,'/ip')\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n\n\n\n\n","sub_path":"to_do_app.py","file_name":"to_do_app.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316888974","text":"import string\nimport numpy as np\nimport math\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression, ElasticNet\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split, RandomizedSearchCV, GridSearchCV\nfrom scipy.stats import pearsonr\nfrom scipy.stats import randint as sp_randint\nfrom sklearn.metrics import r2_score\nimport pdb\n\ndef new_char():\n \n all_possible_chars = string.printable[:-10] + \" \"\n idx = np.random.randint(len(all_possible_chars))\n \n return all_possible_chars[idx]\n\ndef mse(arr1, arr2):\n return ((arr1 - arr2)**2)/arr1.shape[0]\n\n\n\nclass DNA:\n def __init__(self, data, preproc_algos, models, mutant = False, verbose = False):\n self.genes = {}\n self.genes[\"data\"] = []\n self.genes[\"preproc\"] = []\n self.genes[\"models\"] = []\n self.fitness = 0\n self.verbose = verbose\n \n if not mutant:\n # Allocating genes --> data, preproc and models are lists of strings\n print(f\"data: {data}\")\n for idx in data: \n if np.random.random() > 0.01: self.genes[\"data\"].append(idx)\n else: self.genes[\"data\"].append(None)\n \n # Ensuring each DNA instance has at least one dataset\n if len(self.genes[\"data\"]) == 0:\n idx = np.random.randint(0, len(data))\n self.genes[\"data\"].append(data[idx])\n \n print(f\"self.genes['data']: {self.genes['data']}\")\n\n for p in preproc_algos: \n if np.random.random() > 0.01: self.genes[\"preproc\"].append(p)\n else: self.genes[\"preproc\"].append(None)\n\n \n for m in models: \n if np.random.random() > 0.01: self.genes[\"models\"].append(m)\n else: self.genes[\"models\"].append(None)\n \n # Ensuring each DNA instance has at least one model\n if len(self.genes[\"models\"]) == 0:\n idx = np.random.randint(0, len(models))\n self.genes[\"models\"].append(models[idx])\n \n\n def crossover(self, partner, midpt_bool):\n\n child = DNA( None, None, None, mutant=True)\n \n if not midpt_bool:\n \n total_fitness = self.fitness + partner.fitness\n \n # THIS WAS NEW\n # self_prob = prob of taking one of own genes in crossover\n # Weighting self_prob based on fitness, capping at max_self_prob\n max_self_prob = 0.8\n if total_fitness == 0: self_prob = 0.5 \n else: self_prob = min( max_self_prob, max( (1-max_self_prob) , self.fitness / max(total_fitness, 1e-4) ) )\n \n if self.verbose:\n print(f\"self.fitness: {self.fitness}\")\n print(f\"partner.fitness: {partner.fitness}\") \n print(f\"self_prob: {self_prob}\")\n \n for i in range(len(self.genes['data'])):\n val = np.random.random()\n if self.verbose: print(f\"val: {val}\")\n if val < self_prob: \n if self.verbose: print(\"self gene\")\n child.genes['data'].append(self.genes['data'][i])\n else: child.genes['data'].append(partner.genes['data'][i])\n \n for i in range(len(self.genes['models'])):\n val = np.random.random()\n if self.verbose: print(f\"val: {val}\")\n if val < self_prob: \n if self.verbose: print(\"self gene\")\n child.genes['models'].append(self.genes['models'][i])\n else: child.genes['models'].append(partner.genes['models'][i])\n \n else:\n\n midpt = min(max(2, np.random.randint(len(self.genes))), len(self.genes)-2) \n\n for i in range(len(self.genes)): \n if (i > midpt): child.genes[i] = self.genes[i]\n else: child.genes[i] = partner.genes[i]\n\n return child\n\n # NEED TO UPDATE !!!!\n def mutate(self, mut_rate):\n \n '''Based on a mutation probability, picks a new random character'''\n \n for i in range(len(self.genes['data'])): \n pass\n# if (np.random.random() < mut_rate):\n# self.genes['data'] = new_char()\n \n \n def calc_fitness(self, df_dict, tgt):\n \n self.genes['preds'] = []\n \n # Perform preprocessing if desired\n# for df in self.genes['data']:\n# if 'preproc_algos' in self.genes.keys(): pass\n# else: continue\n \n # Concatenating subsets into full df\n df_keys = [df_idx for df_idx in self.genes['data'] if df_idx is not None]\n df_tuple = tuple([df_dict[key] for key in df_keys])\n \n df = np.concatenate( df_tuple , axis=1)\n# full_df = pd.concat([df_dict[key] for key in df_keys], axis=1)\n \n X_tr, X_te, y_tr, y_te = self.split_train_test(df,tgt)\n del df\n \n for model in self.genes['models']:\n if model is not None:\n test_preds = self.train_mod_and_predict(model, X_tr, y_tr, X_te) \n self.genes['preds'].append(test_preds)\n try: print(f\"\\nR2 for test_preds: {r2_score(y_te, test_preds)}\")\n except: pdb.set_trace()\n print(f\"\\n test_preds head: {test_preds[:5]}\")\n \n # Ensembling and final fitness calculation\n if len(self.genes['preds']) == 0: self.fitness = 0\n else: self.fitness = self.ensemble_and_score(self.genes['preds'], y_te)\n \n \n def split_train_test(self, df, tgt, rand_state = 2, test_float = 0.2):\n X_tr, X_te, y_tr, y_te = train_test_split(df, tgt, test_size=test_float, random_state=rand_state)\n return X_tr, X_te, y_tr, y_te\n \n \n def train_mod_and_predict(self, mod, X_tr, y_tr, X_te, num_folds = 5, n_iter = 10):\n \n if mod == 'rf':\n est = RandomForestRegressor(criterion='mse') \n\n params = {'max_depth': sp_randint(1,12),\n 'min_samples_leaf': sp_randint(1,50),\n 'n_estimators': sp_randint(1,30),\n 'max_features': sp_randint(X_tr.shape[1]*0.3, X_tr.shape[1])}\n\n rs = RandomizedSearchCV(est, param_distributions=params, \n n_jobs=24, n_iter=n_iter, cv=num_folds)\n\n print(\"\\nPerforming randomized search\")\n rs.fit(X_tr, y_tr)\n print(\"Best score: %0.3f\" % rs.best_score_)\n print(\"Best parameters set:\")\n best_parameters = rs.best_estimator_.get_params()\n for param_name in sorted(params.keys()):\n print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))\n\n preds = rs.predict(X_te)\n return preds\n\n elif mod == 'lr':\n print(\"Linear regression\")\n lr = LinearRegression()\n lr.fit(X_tr, y_tr)\n preds = lr.predict(X_te)\n return preds \n \n def ensemble_and_score(self, pred_list, y_te, ens_perc = 0.7):\n \n '''NEED TO SPLIT PREDS TO LEARN WEIGHTS ON TOP HALF AND EVAL ON BOTTOM HALF of test set'''\n \n ### Processing pred_list ###\n pred_array = np.array(pred_list)\n \n print(f\"\\npred_array.shape: {pred_array.shape}\")\n# print(f\"pred_array: {pred_array}\")\n \n# print(f\"\\nScore on og_preds: {r2_score(eval_labels, eval_preds[:,0])}\")\n \n # Ensuring pred_array has column dimension if only one set of preds\n if pred_array.ndim == 1: pred_array.reshape(-1,1)\n \n # Transposing so pred_array will have samples as rows and predictions by each model as different col\n else: pred_array = pred_array.T\n \n print(f\"\\npred_array head: {pred_array[:5,:]}\")\n \n if pred_array.shape[0] != y_te.shape[0]: raise Exception(\"Different number of predictions and ground truths.\")\n \n ############################### \n print(f\"pred_array.shape post-processing: {pred_array.shape}\")\n \n print(f\"\\ny_te[:5]: {y_te[:5]}\")\n \n ens_preds, eval_preds, ens_labels, eval_labels = self.split_train_test(pred_array, y_te, test_float = 1-ens_perc)\n \n# num_ens_samples = int(pred_array.shape[0] * ens_perc)\n \n# # Model predictions and labels used to learn ensemble weights\n# ens_preds = pred_array[ : num_ens_samples, :]\n# ens_labels = y_te[ : num_ens_samples].reshape(-1,1)\n \n# # Model predictions and labels used for evaluation\n# eval_preds = pred_array[ num_ens_samples : , :]\n# eval_labels = y_te[ num_ens_samples : ].reshape(-1,1)\n \n# print(f\"\\n ens_preds first col: {ens_preds[:,0]}\")\n# print(f\"\\n eval_preds first col: {eval_preds[:,0]}\") \n# print(f\"\\nens_labels: {ens_labels}\")\n# print(f\"\\neval_labels: {eval_labels}\")\n\n print(f\"ens_preds.shape: {ens_preds.shape}\")\n print(f\"eval_preds.shape: {eval_preds.shape}\")\n print(f\"ens_labels.shape: {ens_labels.shape}\")\n print(f\"eval_labels.shape: {eval_labels.shape}\") \n \n# ### Ensembling ###\n# score = -10000\n# for wt in [0.1, 0.3, 0.5, 0.7, 0.9]:\n# wt_score = r2_score(eval_labels, (eval_preds[:,0]*wt + eval_preds[:,1]*(1-wt)))\n# if wt_score > score:\n# final_wt = wt\n# score = wt_score\n \n# final_wt_score = r2_score(eval_labels, (eval_preds[:,0]*final_wt + eval_preds[:,1]*(1-final_wt)))\n# print(f\"\\nScore from simple weighting: {final_wt_score}\\n\")\n# print(f\"final_wt: {final_wt}\")\n \n lr = LinearRegression() \n lr.fit(ens_preds, ens_labels)\n ens_eval_preds = lr.predict(eval_preds)\n \n el_net = self.elastic_net_ensemble(ens_preds, ens_labels)\n print(f\"\\nel_net coefficients: {el_net.coef_}\")\n el_net_ens_eval_preds = el_net.predict(eval_preds)\n \n ###################\n if self.verbose:\n print(f\"\\nScore on el_net eval: {r2_score(eval_labels, el_net_ens_eval_preds)}\")\n\n print(f\"\\nScore on training/ensemble samples: {lr.score(ens_preds, ens_labels)}\")\n print(f\"\\nScore on lr.score(eval_preds, eval_labels): {lr.score(eval_preds, eval_labels)}\")\n print(f\"\\nScore on averaging eval samples: {r2_score(eval_labels,np.mean(eval_preds, axis=1))}\")\n print(f\"\\nScore on first col eval_preds: {r2_score(eval_labels, eval_preds[:,0])}\")\n print(f\"\\nScore on full og_preds first col: {r2_score(y_te, pred_array[:,0])}\")\n print(f\"\\nScore on avg og_preds: {r2_score(y_te, np.mean(pred_array, axis=1))}\")\n\n print(f\"\\nLR coefficients: {lr.coef_}\")\n print(f\"LR intercept: {lr.intercept_}\")\n\n print(f\"ens eval preds shape: {ens_eval_preds.shape}\")\n\n print(f\"\\neval_preds[:5, :]: {eval_preds[:5, :]}\")\n print(f\"\\nens_eval_preds[:5]: {ens_eval_preds[:5]}\")\n print(f\"eval_labels[:5]: {eval_labels[:5]}\")\n \n # Ensuring ens_eval_preds has column dimension if only one set of preds\n if ens_eval_preds.ndim == 1: ens_eval_preds.reshape(-1,1)\n \n if ens_eval_preds.shape != eval_labels.shape:\n raise Exception(\"Shape of preds is not the same as the shape of labels\")\n \n print(f\"ens_eval_preds.shape: {ens_eval_preds.shape}\")\n print(f\"eval_labels.shape: {eval_labels.shape}\")\n \n score = r2_score(eval_labels, ens_eval_preds)\n print(f\"\\nScore: {score}\\n\")\n \n return score\n \n def elastic_net_ensemble(self, X_train, y_train):\n \n el = ElasticNet(normalize=True, max_iter=10000)\n parameters = {\n 'alpha': (0.2, 0.5, 1, 5),\n 'l1_ratio': (0.5, 0.7, 0.9, 1)\n }\n\n # find the best parameters for both the feature extraction and classifier\n gs = GridSearchCV(el, parameters, scoring = 'r2', n_jobs=16, cv = 10)\n\n print(\"\\nPerforming grid search\")\n gs.fit(X_train, y_train)\n print(\"Best score: %0.3f\" % gs.best_score_)\n best_parameters = gs.best_estimator_.get_params()\n for param_name in sorted(parameters.keys()):\n print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))\n return gs.best_estimator_\n \n \n def get_genes(self):\n return {'Data':self.genes['data'], 'Preprocessing':self.genes['preproc'], 'Models':self.genes['models']}\n \n \n \n \n### Needed for importation of DNA class ###\nif __name__ == \"__main__\":\n pass\n","sub_path":"genAlgo/arxiv/dna_data_v1.py","file_name":"dna_data_v1.py","file_ext":"py","file_size_in_byte":13015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"278783323","text":"str1 = input()\r\nstr2 = input()\r\n\r\nsort_str1 = sorted(str1)\r\nsort_str2 = sorted(str2)\r\n\r\nif (sort_str1 == sort_str2):\r\n print(\"The given strins are Anagram\")\r\nelse:\r\n print(\"The given string are not Anagram\")\r\n \r\n","sub_path":"To find srtings are anagram.py","file_name":"To find srtings are anagram.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"467643184","text":"# pylint: disable=unused-argument\n\nfrom dagster import InputDefinition, Int, Nothing, Output, OutputDefinition, SolidDefinition, solid\n\n\n@solid\ndef my_solid(context):\n return 1\n\n\ndef _return_one(context):\n return 1\n\n\nsolid_def = SolidDefinition(\n name=\"my_solid\",\n input_defs=[],\n output_defs=[OutputDefinition(Int)],\n compute_fn=_return_one,\n)\n\n# my_logging_solid_start\n@solid\ndef my_logging_solid(context):\n context.log.info(\"Hello world\")\n\n\n# my_logging_solid_end\n\n# input_example_solid_start\n@solid(\n input_defs=[\n InputDefinition(name=\"a\", dagster_type=str),\n InputDefinition(name=\"b\", dagster_type=int),\n ]\n)\ndef my_input_example_solid(context, a, b):\n pass\n\n\n# input_example_solid_end\n\n# my_input_output_example_solid_start\n@solid(\n input_defs=[\n InputDefinition(name=\"a\", dagster_type=int),\n InputDefinition(name=\"b\", dagster_type=int),\n ],\n output_defs=[\n OutputDefinition(name=\"sum\", dagster_type=int),\n OutputDefinition(name=\"difference\", dagster_type=int),\n ],\n)\ndef my_input_output_example_solid(context, a, b):\n yield Output(a + b, output_name=\"sum\")\n yield Output(a - b, output_name=\"difference\")\n\n\n# my_input_output_example_solid_end\n\n\n@solid(\n input_defs=[\n InputDefinition(name=\"a\", dagster_type=int),\n InputDefinition(name=\"b\", dagster_type=int),\n ],\n output_defs=[OutputDefinition(name=\"result\", dagster_type=int)],\n)\ndef my_explicit_def_solid(context, a, b):\n yield Output(a + b, output_name=\"result\")\n\n\n@solid\ndef my_typehint_output_solid(context, a: int, b: int) -> int:\n yield Output(a + b)\n\n\n# my_yield_solid_start\n@solid\ndef my_yield_solid(context):\n yield Output(1)\n\n\n# my_yield_solid_end\n\n# return_and_yield_start\n@solid\ndef return_solid(context):\n return 1\n\n\n# Is equivalent to\n@solid\ndef yield_solid(context):\n yield Output(1, \"result\")\n\n\n# return_and_yield_end\n\n\n# incorrect_solid_start\n# This is invalid\n@solid\ndef incorrect_solid(context):\n yield 1\n\n\n# incorrect_solid_end\n\n# multi_output_solid_start\n@solid(output_defs=[OutputDefinition(name=\"output_1\"), OutputDefinition(name=\"output_2\")])\ndef multiple_output_solid(context):\n yield Output(1, output_name=\"output_1\")\n yield Output(2, output_name=\"output_2\")\n\n\n# multi_output_solid_end\n\n\n# x_solid_start\ndef x_solid(\n arg,\n name=\"default_name\",\n input_defs=None,\n **kwargs,\n):\n \"\"\"\n Args:\n args (any): One or more arguments used to generate the nwe solid\n name (str): The name of the new solid.\n input_defs (list[InputDefinition]): Any input definitions for the new solid. Default: None.\n\n Returns:\n function: The new solid.\n \"\"\"\n\n @solid(name=name, input_defs=input_defs or [InputDefinition(\"start\", Nothing)], **kwargs)\n def _x_solid(context):\n # Solid logic here\n pass\n\n return _x_solid\n\n\n# x_solid_end\n","sub_path":"examples/docs_snippets/docs_snippets/legacy/how_tos/solids.py","file_name":"solids.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"137844870","text":"# coding=utf-8\nimport os\n\nimport obj_data\nimport obj_file\nimport obj_log_split\nfrom func_log_process import LogProcess\nfrom obj_mobatch import OsMobatch\nfrom obj_read_config import Config\n\n\ndef grep_log_files_put_to_log_output(path):\n \"\"\"\n grep the log files, put the result to new file\n :return: grep_file_list as type list\n \"\"\"\n log_process = LogProcess()\n log_process.log_path = path\n log_process.output_path = os.path.join(path, \"temp\")\n obj_file.cleanup_dir(log_process.output_path)\n\n csv_sleeping_cell = log_process.sleeping_cell()\n return csv_sleeping_cell\n\n\ndef get_suspect_and_ensure(site, suspect, ensure, sleeping_file=\"\"):\n if suspect:\n suspect = 1\n else:\n suspect = 0\n if ensure:\n ensure = 1\n else:\n ensure = 0\n\n if os.path.exists(sleeping_file):\n d_suspect = obj_data.make_data_to_dict(obj_data.read_csv_to_data(sleeping_file), [0], [3])\n d_ensure = obj_data.make_data_to_dict(obj_data.read_csv_to_data(sleeping_file), [0], [4])\n if suspect:\n if site in d_suspect:\n suspect = eval(d_suspect[site][0]) + suspect\n if ensure:\n if site in d_ensure:\n ensure = eval(d_ensure[site][0]) + ensure\n\n if suspect > 2:\n if site in d_ensure:\n ensure = eval(d_ensure[site][0]) + 1\n else:\n ensure = 1\n if ensure and (not suspect):\n suspect = 1\n\n return suspect, ensure\n\n\ndef judging_and_output_sleeping_file(csv_file=\"\"):\n sleeping_file = os.path.join(config.output_path, \"quick_view.csv\")\n ratio_pdcp = ratio_rrc = ratio_ucast = value_pdcp = None\n data = obj_data.read_csv_to_data(csv_file)\n quick_list = []\n for row in data:\n if row[1] == \"ifHCInUcastPkts\":\n ratio_ucast = float(row[-1])\n elif row[1] == \"pmPdcpPktReceivedDl\":\n ratio_pdcp = float(row[-1])\n value_pdcp = eval(row[-2])\n elif row[1] == \"pmRrcConnLevSum\":\n ratio_rrc = float(row[-1])\n\n if ratio_pdcp is not None and ratio_rrc is not None and ratio_ucast is not None:\n quick_row = [row[0], ratio_pdcp, ratio_rrc, ratio_pdcp < 0.6 and ratio_rrc > 1, value_pdcp < 1]\n quick_list.append(quick_row)\n ratio_pdcp = ratio_rrc = ratio_ucast = value_pdcp = None\n if quick_list:\n this_list = [[\"Site Name\", \"ratio_pdcp\", \"ratio_rrc\", \"Suspect\", \"Ensure\"]]\n this_list.extend([[x[0], x[1], x[2], get_suspect_and_ensure(x[0], x[3], x[4], sleeping_file)[0],\n get_suspect_and_ensure(x[0], x[3], x[4], sleeping_file)[1]] for x in quick_list])\n obj_data.write_data_to_csv(this_list, sleeping_file)\n\n return sleeping_file\n\n\ndef get_log_for_sleeping_cell(sleeping_file=\"\", csv_file=\"\"):\n site_list = []\n suspect_list = []\n ensure_list = []\n if os.path.exists(sleeping_file):\n site_list = obj_data.read_csv_to_data(sleeping_file)\n i = 0\n for row in site_list:\n if i:\n # suspect\n if eval(row[-2]) > 0:\n suspect_list.append(row[0])\n # ensure\n if eval(row[-1]) == 1:\n ensure_list.append(row[0])\n i = i + 1\n if suspect_list:\n output_path = os.path.join(config.output_path, \"log_\" + config.date_time)\n obj_file.copy_file(sleeping_file, output_path)\n obj_file.copy_file(csv_file, output_path)\n\n report_path = os.path.join(config.report_path, config.date_time)\n obj_file.copy_file(sleeping_file, report_path)\n obj_file.copy_file(csv_file, report_path)\n\n mobatch.site_info = \"'%s'\" % (\",\".join(suspect_list))\n mobatch.commands = os.path.join(os.path.join(config.tool_path, \"MOS\"), \"get_log_for_sleeping_cell.mos\")\n mobatch.log_path = output_path\n mobatch.execute_mobatch()\n\n if ensure_list:\n report_path = os.path.join(config.report_path, \"manual_crash_\" + config.date_time)\n if os.path.exists(sleeping_file):\n obj_file.copy_file(sleeping_file, report_path)\n if os.path.exists(csv_file):\n obj_file.copy_file(csv_file, report_path)\n\n mobatch.site_info = \"'%s'\" % (\",\".join(ensure_list))\n # mobatch.commands = os.path.join(\"'dcgm -k 1 %s'\" % report_path)\n mobatch.commands = os.path.join(os.path.join(config.tool_path, \"MOS\"), \"manual_crash_for_sleeping_cell.mos\")\n mobatch.log_path = report_path\n # mobatch.execute_mobatch()\n\n\nif __name__ == '__main__':\n config = Config()\n\n # run mobatch\n mobatch = OsMobatch()\n mobatch.commands = os.path.join(os.path.join(config.tool_path, \"MOS\"), \"SleepingCellMonitor.mos\")\n mobatch.site_info = os.path.join(os.path.join(config.tool_path, \"config\"), \"sitelist_sleeping_cell.txt\")\n log_path = mobatch.execute_mobatch()\n # log_path = os.path.join(os.path.join(config.tool_path, \"log.sample\"), \"flow_SleepingCell\")\n\n # split the logs\n log_path = obj_log_split.log_split(log_path)\n\n # grep the log, return csvfile\n kpi_file = grep_log_files_put_to_log_output(log_path)\n obj_file.copy_file(kpi_file, config.report_path)\n\n # output the kpi file\n file_sleeping_cell = judging_and_output_sleeping_file(kpi_file)\n obj_file.copy_file(file_sleeping_cell, config.report_path)\n\n # get the log for sleeping cell\n get_log_for_sleeping_cell(file_sleeping_cell, kpi_file)\n","sub_path":"CodeLibrary/PYTH/flow/flow_SleepingCell.py","file_name":"flow_SleepingCell.py","file_ext":"py","file_size_in_byte":5449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"81034044","text":"def r_fib(n):\n\tif n == 1:\n\t\treturn 1\n\tif n == 0:\n\t\treturn 0\n\treturn r_fib(n-1)+r_fib(n-2)\n\ndef i_fib(n):\n\ta, b, count = 0, 1, 0\n\twhile count < n:\n\t\ta, b = b, a+b\n\t\tcount += 1\n\treturn a\n\nvar = int(input(\"Geben Sie eine Fibonacci Zahl ein : \"))\n\nwhile True:\n\tif var < 0:\n\t\tvar = int(input(\"Geben Sie eine Fibonacci Zahl ein : \"))\n\t\tcontinue\n\telse:\n\t\tprint(\"Die \", var, \"te Fibonacci Zahl ist : \", r_fib(var), \"(Rekursiv)\")\n\t\tprint(\"Die \", var, \"te Fibonacci Zahl ist : \", i_fib(var), \"(Iterativ)\")\n\t\tbreak\n\n\t\n","sub_path":"Aufgabe2.py","file_name":"Aufgabe2.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"95948753","text":"# -*- coding: utf-8 -*-\nimport sys\nsys.path.insert(0, '../../')\nimport pandas as pd\nimport numpy as np\nimport scipy.stats\nimport matplotlib.pyplot as plt\nimport mut.thermo\nimport mut.viz\ncolors = mut.viz.color_selector('pboc')\nconstants = mut.thermo.load_constants()\nmut.viz.plotting_style()\n \n# Load the sampling statistics\ndata = pd.read_csv('../../data/csv/epRA_sbc.csv')\n\n# Compute the prior distribution functions\nepRA_range = np.linspace(-40, 10, 500)\nsigma_range = np.linspace(0, 0.5, 500)\nepRA_pdf = scipy.stats.norm(-12, 6).pdf(epRA_range)\nepRA_cdf = scipy.stats.norm(-12, 6).cdf(epRA_range)\nsigma_pdf = scipy.stats.halfnorm(0, 0.1).pdf(sigma_range)\nsigma_cdf = scipy.stats.halfnorm(0, 0.1).cdf(sigma_range)\n\n# Define the bounds of the 95\\% of the uniform distribution. \nn_bins = 20\nn_sims = 10000\nperc_low = scipy.stats.binom.ppf(0.005, 800, n_bins/ 400)\nperc_high = scipy.stats.binom.ppf(0.095, 800, n_bins / 400)\n\n\n# Instantiate the figure canvas\nfig, ax = plt.subplots(2, 3, figsize=(7, 5))\n\n# Apply special formatting. \nfor a in ax.ravel():\n a.xaxis.set_tick_params(labelsize=6.5)\n a.yaxis.set_tick_params(labelsize=6.5)\n\n# Add labels. \nax[0, 0].set_xlabel('DNA binding energy [$k_BT$]', fontsize=6.5)\n\nax[0, 1].set_xlabel('DNA binding energy [$k_BT$]', fontsize=6.5)\nfor i in range(2):\n ax[i, 0].set_ylabel(r'true $\\Delta\\varepsilon_{RA}$ [$k_BT$]', fontsize=6.5)\n ax[i, 0].set_xlabel(r'inferred $\\Delta\\varepsilon_{RA}$ [$k_BT$]', fontsize=6.5)\n ax[i, 1].set_ylabel('cumulative distribution', fontsize=6.5)\n\n# # Plot the analytical prior distributions. \nax[0, 0].plot(epRA_range, epRA_pdf, 'k-', lw=1.5, label=r'$\\mathcal{N}(-12, 6)$')\nax[1, 0].plot(sigma_range, sigma_pdf, 'k-', lw=1.5, label=r'$\\mathcal{N}(-12, 6)$')\n# ax[0, 1].plot(epRA_range, epRA_cdf, 'k-', lw=1.5, label=r'$\\mathcal{N}(-12, 6)$')\n# ax[1, 0].plot(sigma_range, sigma_pdf, 'k-', lw=1.5, label=r'$\\mathcal{HN}(0, 0.1)$')\n# ax[1, 1].plot(sigma_range, sigma_cdf, 'k-', lw=1.5, label=r'$\\mathcal{HN}(0, 0.1)$')\n\n# Plot the simulated prior distributions. \nax_ind = {'ep_RA': 0, 'sigma': 1}\nn_bins = np.linspace(-40, 10, 80)\nfor g, d in data.groupby('param'):\n # Compute the histograms \n ax[ax_ind[g], 1].plot(d['post_mean'], d['ground_truth'], '.', color=colors['red'], markersize=1)\n ax[ax_ind[g], 1].plot(d['post_mean'], d['ground_truth'], '.', color=colors['red'], markersize=1)\n \n \nplt.tight_layout()\nplt.savefig('./test.pdf')\n","sub_path":"code/figures/FigS3_sbc.py","file_name":"FigS3_sbc.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"518113795","text":"import json\nimport ssd1306\nimport urequests\nfrom machine import Pin, I2C\nfrom time import localtime, mktime, sleep\n\nCONTENTS = ['confirmed', 'cases', 'recovered', 'deaths']\nlast_values = []\n\ni2c = I2C(-1, scl=Pin(22), sda=Pin(21))\n\noled_width = 128\noled_height = 64\noled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)\n\noled.text('github.com/', 20, 20)\noled.text('nilson-santos', 13, 35) \noled.show()\n\n\ndef get_api():\n return eval(urequests.get('https://covid19-brazil-api.now.sh/api/report/v1/brazil/').text)\n\n\ndef counters_sanitizer(content):\n content = str(\"{:,}\".format(int(api['data'][content]))).replace(',', '.')\n return content\n\n\ndef change_to_string(valor):\n if valor < 10:\n valor = '0' + str(valor)\n else:\n valor = str(valor)\n return valor\n\n\ndef datatime_sanitizer():\n update_at = api['data']['updated_at']\n Y = int(update_at[:4])\n m = int(update_at[5:7])\n d = int(update_at[8:10])\n H = int(update_at[11:13])\n M = int(update_at[14:16])\n S = int(update_at[17:19])\n\n t = mktime((Y, m, d, H, M, S, 0, 0, 0))\n t -= 3*3600 # convert to local time UTC -3\n t = localtime(t)\n \n t_list = [change_to_string(valor) for valor in t]\n\n data = t_list[2] + '-' + t_list[1] + '-' + t_list[0]\n time = t_list[3] + ':' + t_list[4] + ':' + t_list[5]\n\n return [data, time]\n\n\ndef oled_show(title, title_h_start, title_v_start, value,\n value_h_start, value_v_start,\n value2='', value2_h_start=0, value2_v_start=0\n ):\n oled.fill(0)\n oled.text('CORONAVIRUS', 20, 0)\n oled.text(title, title_h_start, title_v_start)\n oled.text(value, value_h_start, value_v_start)\n oled.text(value2, value2_h_start, value2_v_start)\n oled.show()\n sleep(5)\n\n\nwhile True:\n api = get_api()\n values = [counters_sanitizer(value) for value in CONTENTS]\n date, time = datatime_sanitizer()\n\n for _ in range(10):\n\n oled_show('Confirmados', 20, 22, values[0], 27, 40)\n \n oled_show('Ativos', 40, 22, values[1], 36, 40)\n \n oled_show('Recuperados', 20, 22, values[2], 27, 40)\n \n oled_show('Mortos', 40, 22, values[3], 39, 40)\n \n oled_show('Atualizado', 24, 22, date, 24, 40, time, 32, 50)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"434348433","text":"#!/usr/bin/env python\n# coding=utf-8\n\"\"\"Canvas routes.\n\nCanvas routes\n\"\"\"\nfrom __future__ import unicode_literals\n\nfrom flask import session\nfrom flask import request\nfrom flask import jsonify\nfrom flask import Blueprint\n\nfrom jiagouyun.controllers import canvas as canvas_controller\nfrom jiagouyun.utils import getLogger\nfrom jiagouyun.utils import exceptions\nfrom jiagouyun.utils.auth import need_login\n\nlogger = getLogger(__name__)\ncanvas_bp = Blueprint(\"canvas\", __name__)\n\n\n@canvas_bp.route(\"\", methods=[\"GET\"])\n@need_login\ndef list_canvases():\n \"\"\"List canvases.\n\n @api {get} /canvas 获取画布列表\n @apiName ListCanvas\n @apiGroup Canvas\n\n @apiParam {Number} page 页码。\n @apiParam {Number} results_per_page 每页显示的数量\n \"\"\"\n page = 1\n results_per_page = 10\n try:\n page = int(request.args[\"page\"])\n except:\n pass\n try:\n results_per_page = int(request.args[\"results_per_page\"])\n except:\n pass\n count, data = canvas_controller.list_canvases(\n page, results_per_page, user_id=session['user']['id'])\n total_pages = count / \\\n results_per_page if count % results_per_page == 0 else count / results_per_page + 1\n\n return jsonify({\n \"code\": 0,\n \"data\": {\n \"objects\": data,\n \"total_pages\": total_pages,\n \"current_page\": page,\n \"num_results\": count\n }\n })\n\n\n@canvas_bp.route(\"//share\", methods=[\"GET\"])\n@need_login\ndef list_share_canvases(canvas_id):\n \"\"\"List Share History.\n\n @api {get} /canvas/:canvas_id/share 获取当前版本分享历史数据\n @apiName ListShareCanvas\n @apiGroup Canvas\n\n @apiParam {Number} page 页码。\n @apiParam {Number} results_per_page 每页显示的数量\n \"\"\"\n page = 1\n results_per_page = 10\n try:\n page = int(request.args[\"page\"])\n except:\n pass\n try:\n results_per_page = int(request.args[\"results_per_page\"])\n except:\n pass\n count, data = canvas_controller.list_share_canvases(canvas_id, page, results_per_page, user_id=session['user']['id'])\n total_pages = count / \\\n results_per_page if count % results_per_page == 0 else count / results_per_page + 1\n\n return jsonify({\n \"code\": 0,\n \"data\": {\n \"objects\": data,\n \"total_pages\": total_pages,\n \"current_page\": page,\n \"num_results\": count\n }\n })\n\n\n@canvas_bp.route(\"\", methods=[\"POST\"])\n@need_login\ndef create_canvas():\n \"\"\"Create canvas.\n\n @api {post} /canvas 创建画布\n @apiName CreateCanvas\n @apiGroup Canvas\n\n @apiParam {String} name 画布名称。\n @apiParam {String} description 画布简介。\n @apiParam {String} draft 画布内容(引入版本后改为当前草稿)。\n \"\"\"\n data = request.json\n data['user_id'] = session['user']['id']\n canvas = canvas_controller.create_canvas(data)\n if canvas is None:\n raise exceptions.CanvasCreateFailed()\n\n return jsonify({\n \"code\": \"0\",\n \"data\": canvas\n })\n\n\n@canvas_bp.route(\"//copy\", methods=[\"POST\"])\n@need_login\ndef copy_canvas(canvas_id):\n \"\"\"Copy canvas.\n\n @api {post} /canvas 拷贝画布\n @apiName CopyCanvas\n @apiGroup Canvas\n\n @apiParam {String} name 画布名称。\n \"\"\"\n data = request.json\n data['user_id'] = session['user']['id']\n canvas = canvas_controller.copy_canvas(data, canvas_id)\n if canvas is None:\n raise exceptions.CopyCanvasFailed()\n\n return jsonify({\n \"code\": \"0\",\n \"data\": canvas\n })\n\n\n@canvas_bp.route(\"//share\", methods=[\"POST\"])\n@need_login\ndef share_canvas(canvas_id):\n \"\"\"Share Canvas.\n\n @api {post} /canvas/:canvas_id/share 分享画布\n @apiName ShareCanvas\n @apiGroup Canvas\n\n @apiParam {String} to_email 被分享者邮箱。\n @apiParam {String} canvas_version_id 架构版本ID,作判断用处。\n \"\"\"\n data = request.json\n data['user_id'] = session['user']['id']\n user_email = canvas_controller.verify_email(data)\n if user_email is None:\n raise exceptions.UserNotFound()\n data[\"owner_id\"] = user_email[\"id\"]\n canvas_verify = canvas_controller.verify(canvas_id, data)\n canvas = canvas_controller.share_canvas(data, data[\"canvas_version_id\"], user_email)\n if canvas is None:\n raise exceptions.ShareCanvasFailed()\n\n return jsonify({\n \"code\": \"0\",\n \"data\": canvas\n })\n\n\n@canvas_bp.route(\"/\", methods=[\"GET\"])\n@need_login\ndef get_canvas(canvas_id):\n \"\"\"Get canvas.\n\n @api {get} /canvas/:id 获取画布\n @apiName GetCanvas\n @apiGroup Canvas\n\n @apiParam {Number} id 画布ID。\n \"\"\"\n\n canvas = canvas_controller.get_canvas(canvas_id)\n if canvas is None or canvas['user_id'] != session['user']['id']:\n raise exceptions.CanvasNotFound()\n return jsonify({\n \"code\": \"0\",\n \"data\": canvas\n })\n\n\n@canvas_bp.route(\"/\", methods=[\"DELETE\"])\n@need_login\ndef delete_canvas(canvas_id):\n \"\"\"Delete canvas.\n\n @api {delete} /canvas/:id 删除画布\n @apiName DeleteCanvas\n @apiGroup Canvas\n\n @apiParam {Number} id 画布ID。\n \"\"\"\n canvas = canvas_controller.get_canvas(canvas_id)\n if canvas is None or canvas['user_id'] != session['user']['id']:\n raise exceptions.CanvasNotFound()\n canvas_controller.delete_canvas(canvas_id)\n return jsonify({\n \"code\": \"0\",\n \"data\": {}\n })\n\n\n@canvas_bp.route(\"/\", methods=[\"PATCH\"])\n@need_login\ndef update_canvas(canvas_id):\n \"\"\"Update canvas.\n\n @api {patch} /canvas/:id 更新画布\n @apiName UpdateCanvas\n @apiGroup Canvas\n\n @apiParam {Number} id 画布ID。\n @apiParam {String} name 画布名称。\n @apiParam {String} description 画布简介。\n @apiParam {String} draft 画布内容(引入版本后改为当前草稿)。\n \"\"\"\n data = request.json\n canvas = canvas_controller.get_canvas(canvas_id)\n if canvas is None or canvas['user_id'] != session['user']['id']:\n raise exceptions.CanvasNotFound()\n canvas = canvas_controller.update_canvas(canvas_id, data)\n\n if canvas is None:\n raise exceptions.CanvasUpdateFailed()\n\n return jsonify({\n \"code\": \"0\",\n \"data\": canvas\n })\n\n\n@canvas_bp.route(\"//versions\", methods=[\"GET\"])\n@need_login\ndef get_canvas_versions(canvas_id):\n \"\"\"Get All Canvas versions.\n\n @api {get} /canvas/:canvas_id/versions 获取画布版本列表\n @apiName GetCanvasVersions\n @apiGroup CanvasVersion\n\n @apiParams {Number} canvas_id 画布ID\n \"\"\"\n canvas = canvas_controller.get_canvas(canvas_id)\n if canvas is None:\n raise exceptions.CanvasNotFound()\n\n versions = canvas_controller.get_canvas_versions(canvas_id)\n\n return jsonify({\n \"code\": \"0\",\n \"data\": versions\n })\n\n\n@canvas_bp.route(\"//versions/\", methods=[\"GET\"])\n@need_login\ndef get_canvas_version(canvas_id, version_id):\n \"\"\"Get a Canvas version.\n\n @api {get} /canvas/:canvas_id/versions/:version_id 获取单个画布版本\n @apiName GetCanvasVersion\n @apiGroup CanvasVersion\n\n @apiParams {Number} canvas_id 画布ID\n @apiParams {Number} version_id 版本ID\n \"\"\"\n version = canvas_controller.get_canvas_version(canvas_id, version_id)\n if version is None:\n raise exceptions.CanvasVersionNotFound()\n\n return jsonify({\n \"code\": \"0\",\n \"data\": version\n })\n\n\n@canvas_bp.route(\"//versions/\", methods=[\"DELETE\"])\n@need_login\ndef delete_canvas_version(canvas_id, version_id):\n \"\"\"Delete a Canvas version.\n\n @api {delete} /canvas/:canvas_id/versions/:version_id 删除画布版本\n @apiName DeleteCanvasVersion\n @apiGroup CanvasVersion\n\n @apiParams {Number} canvas_id 画布ID\n @apiParams {Number} version_id 版本ID\n \"\"\"\n canvas_controller.delete_canvas_version(canvas_id, version_id)\n return jsonify({\n \"code\": \"0\",\n \"data\": {}\n })\n\n\n@canvas_bp.route(\"//versions\", methods=[\"POST\"])\n@need_login\ndef create_canvas_version(canvas_id):\n \"\"\"Create a Canvas version.\n\n @api {post} /cavnas/:canvas_id/version 创建画布版本\n @apiName CreateCavansVersion\n @apiGroup CanvasVersion\n\n @apiParams {Number} canvas_id 画布ID\n @apiParams {String} title 版本标题\n @apiParams {String} description 版本描述\n \"\"\"\n title = request.json['title']\n description = request.json.get(\"description\", \"\")\n canvas_version = canvas_controller.create_canvas_version(canvas_id, title, description)\n if canvas_version is None:\n raise exceptions.CanvasVersionCreateFailed()\n return jsonify({\n \"code\": \"0\",\n \"data\": canvas_version\n })\n","sub_path":"jiagouyun/routes/canvas.py","file_name":"canvas.py","file_ext":"py","file_size_in_byte":8836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"310471738","text":"\"\"\"\nExample showing how to create particle explosions via the GPU.\n\"\"\"\nimport random\nimport time\nimport math\nfrom array import array\nfrom dataclasses import dataclass\n\nimport arcade\nimport arcade.gl\n\nSCREEN_WIDTH = 1024\nSCREEN_HEIGHT = 768\nSCREEN_TITLE = \"GPU Particle Explosion\"\n\nPARTICLE_COUNT = 300\n\n\n@dataclass\nclass Burst:\n \"\"\" Track for each burst. \"\"\"\n buffer: arcade.gl.Buffer\n vao: arcade.gl.Geometry\n start_time: float\n\n\nclass MyWindow(arcade.Window):\n \"\"\" Main window\"\"\"\n def __init__(self):\n super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n self.burst_list = []\n\n # Program to visualize the points\n self.program = self.ctx.load_program(\n vertex_shader=\"vertex_shader_v3.glsl\",\n fragment_shader=\"fragment_shader.glsl\",\n )\n\n self.ctx.enable_only()\n\n def on_draw(self):\n \"\"\" Draw everything \"\"\"\n self.clear()\n\n # Set the particle size\n self.ctx.point_size = 2 * self.get_pixel_ratio()\n\n # Loop through each burst\n for burst in self.burst_list:\n\n # Set the uniform data\n self.program['time'] = time.time() - burst.start_time\n\n # Render the burst\n burst.vao.render(self.program, mode=self.ctx.POINTS)\n\n def on_update(self, dt):\n \"\"\" Update everything \"\"\"\n pass\n\n def on_mouse_press(self, x: float, y: float, button: int, modifiers: int):\n \"\"\" User clicks mouse \"\"\"\n\n def _gen_initial_data(initial_x, initial_y):\n \"\"\" Generate data for each particle \"\"\"\n for i in range(PARTICLE_COUNT):\n angle = random.uniform(0, 2 * math.pi)\n speed = abs(random.gauss(0, 1)) * .5\n dx = math.sin(angle) * speed\n dy = math.cos(angle) * speed\n red = random.uniform(0.5, 1.0)\n green = random.uniform(0, red)\n blue = 0\n yield initial_x\n yield initial_y\n yield dx\n yield dy\n yield red\n yield green\n yield blue\n\n # Recalculate the coordinates from pixels to the OpenGL system with\n # 0, 0 at the center.\n x2 = x / self.width * 2. - 1.\n y2 = y / self.height * 2. - 1.\n\n # Get initial particle data\n initial_data = _gen_initial_data(x2, y2)\n\n # Create a buffer with that data\n buffer = self.ctx.buffer(data=array('f', initial_data))\n\n # Create a buffer description specifying the buffer's data format\n buffer_description = arcade.gl.BufferDescription(\n buffer,\n '2f 2f 3f',\n ['in_pos', 'in_vel', 'in_color'])\n\n # Create our Vertex Attribute Object\n vao = self.ctx.geometry([buffer_description])\n\n # Create the Burst object and add it to the list of bursts\n burst = Burst(buffer=buffer, vao=vao, start_time=time.time())\n self.burst_list.append(burst)\n\n\nif __name__ == \"__main__\":\n window = MyWindow()\n window.center_window()\n arcade.run()\n","sub_path":"doc/tutorials/gpu_particle_burst/gpu_particle_burst_06.py","file_name":"gpu_particle_burst_06.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"155054949","text":"#!/usr/bin/env python3\nimport message\nimport ply.lex\nimport ply.yacc\nimport re\n\n\nclass SourceLocation:\n def __init__(self, token, **kwargs):\n self.lineno = token.lexer.lineno\n if 'lexerror' in kwargs:\n # In t_error(), the first character is not recognized by the lexer.\n # We should show the error indicator at the beginning.\n #\n # The default behavior is treating the whole string as error, which\n # results in showing the error indiacator at the end.\n self.length = 1\n self.begin = 0\n self.data = token.value\n else:\n self.length = len(token.value)\n self.begin = token.lexer.lexpos - self.length\n self.data = token.lexer.lexdata\n\n def get_line(self):\n line_begin = self.data.rfind('\\n', 0, self.begin)\n if (line_begin == -1):\n line_begin = 0\n else:\n line_begin += 1\n\n line_end = self.data.find('\\n',\n self.begin + self.length - 1,\n len(self.data))\n if (line_end == -1):\n line_end = len(self.data)\n\n # Strip spaces\n # To prevent shell's expanding of tabs, replace them with space\n line_text = self.data[line_begin: line_end].rstrip()\n line_text_stripped = line_text.lstrip()\n line_text_stripped.replace('\\t', ' ')\n\n space_length = len(line_text) - len(line_text_stripped)\n loc_begin = self.begin - line_begin - space_length\n return line_text_stripped, loc_begin\n\n\nclass ParseTree:\n def __init__(self, node_type, loc_obj):\n self.node_type = node_type\n if type(loc_obj) is ply.lex.LexToken:\n loc_obj.type = node_type\n self.loc = SourceLocation(loc_obj)\n if type(loc_obj) is ParseTree:\n self.loc = loc_obj.loc\n\n\ndef Parser():\n\n ####################################\n # Definitions for lexer and parser #\n ####################################\n\n operator_group = [\n # logic\n {'type': 'left', '||': 'lor'},\n {'type': 'left', '&&': 'land'},\n {'type': 'left', '!': 'lnot'},\n\n # comparison\n {'type': 'nonassoc',\n '>': 'gt', '<': 'lt', '<=': 'le', '>=': 'ge',\n '==': 'eq', '!=': 'ne'},\n\n # bitwise operation\n {'type': 'left', '|': 'bor'},\n {'type': 'left', '^': 'bxor'},\n {'type': 'left', '&': 'band'},\n {'type': 'left', '>>': 'brs', '<<': 'bls'},\n\n # arithmetic operation\n {'type': 'left', '+': 'plus', '-': 'minus'},\n {'type': 'left', '*': 'times', '/': 'div', '%': 'mod'},\n ]\n\n reserved = ('pack', 'var',\n 'if', 'else',\n 'while', 'break', 'continue')\n\n # Some values aren't used directly, but by PLY using Python's inspection\n # mechanism. Use \"NOQA\" to supress checkers' warnings.\n\n literals = r',:;\\.()[]{}=' # NOQA\n t_ignore = ' \\t' # NOQA\n tokens = ['ident', 'integer'] + list(reserved)\n\n operator_map = {}\n precedence = []\n for i in operator_group:\n precedence_group = []\n for op, name in i.items():\n if op == 'type':\n precedence_group.insert(0, name) # associativity at first\n else:\n precedence_group.append(name) # operator name at last\n operator_map[op] = name\n tokens.append(name)\n precedence.append(tuple(precedence_group))\n\n #####################\n # Lexer code begins #\n #####################\n\n def t_error(t):\n loc = SourceLocation(t, lexerror=True)\n message.error(\"Illegal character '{}'\".format(t.value[0]), loc)\n\n def t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n\n def get_operator_regex():\n desc_in_length = sorted(operator_map.keys(), key=len, reverse=True)\n return '|'.join([re.escape(i) for i in desc_in_length])\n\n @ply.lex.TOKEN(get_operator_regex())\n def t_operator(t):\n node = ParseTree('operator', t)\n node.value = t.value\n t.type = operator_map[t.value]\n t.value = node\n return t\n\n def get_ident_regex():\n range = ''\n char_set = set(literals + t_ignore + ''.join(operator_map.keys()))\n for char in char_set:\n if char in '[]-^\\\\':\n range += '\\\\'\n range += char\n return r'[^0-9{0}][^{0}]*'.format(range)\n\n # to support unicode identifiers, accept everything except symbols\n @ply.lex.TOKEN(get_ident_regex())\n def t_ident(t):\n if t.value in reserved:\n node = ParseTree('reserved', t)\n t.type = t.value\n else:\n node = ParseTree('ident', t)\n node.value = t.value\n t.value = node\n return t\n\n def t_integer(t):\n r'[0-9]+|0x[0-9a-fA-F]+|0b[01]+'\n node = ParseTree('integer', t)\n node.value = int(t.value, base=0)\n t.value = node\n return t\n\n ######################\n # Parser code begins #\n ######################\n\n def make_stmt_list(node):\n # If p is not statement list:\n # Make a statement list whose only statement is p\n if node.node_type == 'stmt_list':\n return node\n new_node = ParseTree('stmt_list', None)\n new_node.body = [node]\n return new_node\n\n def p_error(p):\n if type(p.value) is ParseTree:\n loc = p.value.loc\n else:\n loc = None\n message.error('Syntax error: unexpected token type \"{}\"'\n .format(p.type), loc)\n\n def p_start(p):\n '''\n start : top_stmt_list\n '''\n p[0] = p[1]\n\n def p_pack_decl(p):\n \"pack_decl : pack ident '{' stmt_list '}' \"\n p[0] = ParseTree('pack', p[2])\n p[0].name = p[2].value\n p[0].body = p[4]\n\n def p_stmt_list(p):\n '''\n top_stmt_list : top_stmt_list pack_decl\n |\n stmt_list : stmt_list stmt\n |\n '''\n if len(p) == 1:\n p[0] = ParseTree('stmt_list', None)\n p[0].body = []\n else:\n p[0] = p[1]\n p[0].body.append(p[2])\n\n def p_stmt(p):\n '''\n stmt : stmt_matched\n | stmt_unmatched\n '''\n p[0] = p[1]\n\n def p_stmt_var(p):\n '''\n stmt_matched : var ident ':' ident '=' expr ';'\n stmt_matched : var ident ':' ident ';'\n '''\n p[0] = ParseTree('var', p[1])\n p[0].name = p[2].value\n p[0].type = p[4]\n p[0].expr = None if len(p) < 7 else p[6]\n\n def p_stmt_expr(p):\n \"stmt_matched : expr ';'\"\n p[0] = p[1]\n\n def p_stmt_stmt_list(p):\n \"stmt_matched : '{' stmt_list '}'\"\n p[0] = p[2]\n\n def p_stmt_if_else(p):\n '''\n stmt_matched : if '(' expr ')' stmt_matched else stmt_matched\n stmt_unmatched : if '(' expr ')' stmt\n '''\n p[0] = ParseTree('if', p[1])\n p[0].cond = p[3]\n p[0].succ = make_stmt_list(p[5])\n p[0].fail = None if len(p) == 6 else make_stmt_list(p[7])\n\n def p_stmt_while_matched(p):\n '''\n stmt_matched : while '(' expr ')' stmt_matched\n stmt_unmatched : while '(' expr ')' stmt_unmatched\n '''\n p[0] = ParseTree('while', p[1])\n p[0].cond = p[3]\n p[0].body = make_stmt_list(p[5])\n\n def p_stmt_loop_control(p):\n '''\n stmt_matched : break ';'\n | continue ';'\n '''\n p[0] = p[1]\n\n def p_call(p):\n '''\n call : ident '(' arg_list ')'\n | ident '(' ')'\n '''\n p[0] = ParseTree('call', p[1])\n p[0].name = p[1].value\n if len(p) == 5:\n p[0].args = p[3]\n else:\n p[0].args = []\n\n def p_arg_list_new(p):\n \"arg_list : arg\"\n p[0] = [p[1]]\n\n def p_arg_list_append(p):\n \"arg_list : arg_list ',' arg\"\n p[0] = p[1]\n p[0].append(p[3])\n\n def p_arg_required(p):\n \"arg : expr\"\n p[0] = p[1]\n\n def p_arg_optional(p):\n \"arg : ident '=' expr\"\n p[0] = {'key': p[1], 'value': p[3]}\n\n def p_expr_single(p):\n '''\n expr : ident\n | integer\n | call\n '''\n p[0] = p[1]\n\n def p_expr_paren(p):\n \"expr : '(' expr ')'\"\n p[0] = p[2]\n\n def get_expr_op2_docstring():\n exclude = ['lnot']\n\n tab = ' '\n header = tab + tab + 'expr : expr '\n tail = ' expr'\n join = ' expr\\n' + tab * 3 + ' | expr '\n names = sorted([x for x in operator_map.values() if x not in exclude])\n names = sorted(names, key=len)\n print(header + join.join(names) + tail)\n\n def p_expr_op1(p):\n '''\n expr : lnot expr\n '''\n p[0] = ParseTree('expr_op1', p[1])\n p[0].op = p[1]\n p[0].rhs = p[2]\n\n def p_expr_op2(p):\n # PLY doesn't support using decorators in parser function.\n # Use get_expr_op2_docstring() as a workaround.\n\n '''\n expr : expr eq expr\n | expr ge expr\n | expr gt expr\n | expr le expr\n | expr lt expr\n | expr ne expr\n | expr bls expr\n | expr bor expr\n | expr brs expr\n | expr div expr\n | expr lor expr\n | expr mod expr\n | expr band expr\n | expr bxor expr\n | expr land expr\n | expr plus expr\n | expr minus expr\n | expr times expr\n '''\n\n p[0] = ParseTree('expr_op2', p[2])\n p[0].lhs = p[1]\n p[0].op = p[2]\n p[0].rhs = p[3]\n\n return ply.lex.lex(), ply.yacc.yacc()\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":9954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"283751083","text":"# PuLP : Python LP Modeler\n# Version 1.4.2\n\n# Copyright (c) 2002-2005, Jean-Sebastien Roy (js@jeannot.org)\n# Modifications Copyright (c) 2007- Stuart Anthony Mitchell (s.mitchell@auckland.ac.nz)\n# $Id:solvers.py 1791 2008-04-23 22:54:34Z smit023 $\n\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\"\"\"\n\nfrom .core import LpSolver_CMD, subprocess, PulpSolverError, clock\nfrom .core import scip_path\nimport os\nfrom .. import constants\nimport sys\n\n\nclass SCIP_CMD(LpSolver_CMD):\n \"\"\"The SCIP optimization solver\"\"\"\n\n SCIP_STATUSES = {\n 'unknown': constants.LpStatusUndefined,\n 'user interrupt': constants.LpStatusNotSolved,\n 'node limit reached': constants.LpStatusNotSolved,\n 'total node limit reached': constants.LpStatusNotSolved,\n 'stall node limit reached': constants.LpStatusNotSolved,\n 'time limit reached': constants.LpStatusNotSolved,\n 'memory limit reached': constants.LpStatusNotSolved,\n 'gap limit reached': constants.LpStatusNotSolved,\n 'solution limit reached': constants.LpStatusNotSolved,\n 'solution improvement limit reached': constants.LpStatusNotSolved,\n 'restart limit reached': constants.LpStatusNotSolved,\n 'optimal solution found': constants.LpStatusOptimal,\n 'infeasible': constants.LpStatusInfeasible,\n 'unbounded': constants.LpStatusUnbounded,\n 'infeasible or unbounded': constants.LpStatusNotSolved,\n }\n\n def defaultPath(self):\n return self.executableExtension(scip_path)\n\n def available(self):\n \"\"\"True if the solver is available\"\"\"\n return self.executable(self.path)\n\n def actualSolve(self, lp):\n \"\"\"Solve a well formulated lp problem\"\"\"\n if not self.executable(self.path):\n raise PulpSolverError(\"PuLP: cannot execute \"+self.path)\n\n tmpLp, tmpSol = self.create_tmp_files(lp.name, 'lp', 'sol')\n lp.writeLP(tmpLp)\n proc = [\n '%s' % self.path, '-c', 'read \"%s\"' % tmpLp, '-c', 'optimize',\n '-c', 'write solution \"%s\"' % tmpSol, '-c', 'quit'\n ]\n proc.extend(self.options)\n if not self.msg:\n proc.append('-q')\n\n self.solution_time = clock()\n subprocess.check_call(proc, stdout=sys.stdout, stderr=sys.stderr)\n self.solution_time += clock()\n\n if not os.path.exists(tmpSol):\n raise PulpSolverError(\"PuLP: Error while executing \"+self.path)\n\n status, values = self.readsol(tmpSol)\n\n # Make sure to add back in any 0-valued variables SCIP leaves out.\n finalVals = {}\n for v in lp.variables():\n finalVals[v.name] = values.get(v.name, 0.0)\n\n lp.assignVarsVals(finalVals)\n lp.assignStatus(status)\n self.delete_tmp_files(tmpLp, tmpSol)\n return status\n\n @staticmethod\n def readsol(filename):\n \"\"\"Read a SCIP solution file\"\"\"\n with open(filename) as f:\n # First line must containt 'solution status: '\n try:\n line = f.readline()\n comps = line.split(': ')\n assert comps[0] == 'solution status'\n assert len(comps) == 2\n except:\n raise PulpSolverError(\"Can't read SCIP solver output: %r\" % line)\n\n status = SCIP_CMD.SCIP_STATUSES.get(comps[1].strip(), constants.LpStatusUndefined)\n\n # Look for an objective value. If we can't find one, stop.\n try:\n line = f.readline()\n comps = line.split(': ')\n assert comps[0] == 'objective value'\n assert len(comps) == 2\n float(comps[1].strip())\n except:\n raise PulpSolverError(\"Can't read SCIP solver output: %r\" % line)\n\n # Parse the variable values.\n values = {}\n for line in f:\n try:\n comps = line.split()\n values[comps[0]] = float(comps[1])\n except:\n raise PulpSolverError(\"Can't read SCIP solver output: %r\" % line)\n\n return status, values\n\n\nSCIP = SCIP_CMD\n","sub_path":"pulp/apis/scip_api.py","file_name":"scip_api.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"644293168","text":"######################\n# (c) 2012 Andreas Mueller \n# ALL RIGHTS RESERVED.\n#\n# DON'T USE WITHOUT AUTHOR CONSENT!\n#\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom joblib import Parallel, delayed\n\nfrom structured_svm import StructuredSVM, inference, find_constraint\n\nfrom IPython.core.debugger import Tracer\n\ntracer = Tracer()\n\n\nclass LatentSSVM(StructuredSVM):\n def fit(self, X, Y):\n w = np.ones(self.problem.size_psi) * 1e-5\n subsvm = StructuredSVM(self.problem, self.max_iter, self.C,\n self.check_constraints, verbose=self.verbose -\n 1, n_jobs=self.n_jobs,\n break_on_bad=self.break_on_bad)\n #objectives = []\n constraints = None\n ws = []\n #Y = Y / self.problem.n_states_per_label\n H = self.problem.init_latent(X, Y)\n #kmeans_init(X, Y, edges, self.problem.n_states_per_label)\n self.H_init_ = H\n inds = np.arange(len(H))\n for i, h in zip(inds, H):\n plt.matshow(h, vmin=0, vmax=self.problem.n_states - 1)\n plt.colorbar()\n plt.savefig(\"figures/h_init_%03d.png\" % i)\n plt.close()\n\n for iteration in xrange(10):\n print(\"LATENT SVM ITERATION %d\" % iteration)\n # find latent variables for ground truth:\n if iteration == 0:\n pass\n else:\n H_new = np.array([self.problem.latent(x, y, w)\n for x, y in zip(X, Y)])\n if np.all(H_new == H):\n print(\"no changes in latent variables of ground truth.\"\n \" stopping.\")\n break\n print(\"changes in H: %d\" % np.sum(H_new != H))\n\n # update constraints:\n constraints = [[] for i in xrange(len(X))]\n for sample, h, i in zip(subsvm.constraints_, H_new,\n np.arange(len(X))):\n for constraint in sample:\n const = find_constraint(self.problem, X[i], h, w,\n constraint[0])\n y_hat, dpsi, _, loss = const\n constraints[i].append([y_hat, dpsi, loss])\n H = H_new\n #if initialization weak?\n #if iteration == 0:\n #subsvm.max_iter = 10\n\n #subsvm.fit(X, H, constraints=new_constraints)\n #constraints = subsvm.constraints_\n subsvm.fit(X, H, constraints=constraints)\n #if iteration == 0:\n #subsvm.max_iter = self.max_iter\n H_hat = Parallel(n_jobs=self.n_jobs)(delayed(inference)\n (self.problem, x, subsvm.w)\n for x in X)\n inds = np.arange(len(H))\n for i, h, h_hat in zip(inds, H, H_hat):\n plt.matshow(h, vmin=0, vmax=self.problem.n_states - 1)\n plt.colorbar()\n plt.savefig(\"figures/h_%03d_%03d.png\" % (iteration, i))\n plt.close()\n plt.matshow(h_hat, vmin=0, vmax=self.problem.n_states - 1)\n plt.colorbar()\n plt.savefig(\"figures/h_hat_%03d_%03d.png\" % (iteration, i))\n plt.close()\n w = subsvm.w\n ws.append(w)\n #objectives.append(subsvm.primal_objective_)\n self.w = w\n #plt.figure()\n #plt.plot(objectives)\n #plt.show()\n","sub_path":"latent_structured_svm.py","file_name":"latent_structured_svm.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"447751716","text":"from .types import IntrinsicFunction, UserDefSymbol\nimport cmd_ir.instructions as i\n\nclass NativeExec(IntrinsicFunction):\n\n def __init__(self, compiler, params, code):\n self.compiler = compiler\n self.param_map = [p.name for p in params]\n self.code = code\n\n def invoke(self, instance, args):\n arg_dict = dict(zip(self.param_map, args))\n scope = dict(args=arg_dict,\n i=i,\n compiler=self.compiler,\n _instance=instance,\n __name__=__name__)\n # \"this\" not present in static functions\n if isinstance(instance, UserDefSymbol):\n scope['this'] = instance.this\n local_res = {}\n exec(self.code, scope, local_res)\n return local_res['__result__']\n\nclass IntrinsicSupport:\n\n def __init__(self, compiler):\n self.compiler = compiler\n\n def traverse(self, children):\n with self.compiler.scope:\n for decl in children:\n self.compiler.transform(decl)\n\n def native_definition(self, func_decl, py_code):\n assert func_decl.typespace is not None\n assert py_code\n py_code = 'def run():\\n' + py_code + '\\n__result__ = run()'\n code = compile(py_code, 'native.py', 'exec')\n intrinsic = NativeExec(self.compiler, func_decl.params, code)\n if func_decl.is_operator:\n func_decl.typespace._set_intrinsic_op(func_decl.name,\n func_decl.params, intrinsic)\n else:\n func_decl.typespace._make_intrinsic(func_decl.name, intrinsic)\n\n def type_configure(self, type_name, py_code):\n exec('if True:\\n' + py_code, {\n 'the_type': type_name,\n 'i': i,\n 'compiler': self.compiler,\n '__name__': __name__\n })\n","sub_path":"cbl/intrinsic_support.py","file_name":"intrinsic_support.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"9115559","text":"import datetime\nimport logging\nimport arrow\n\nfrom django.db.models import Sum\nfrom django.utils import timezone\n\nfrom .models import *\nfrom . import units\n\n\ndef workouts_time_bounds(user):\n workouts = Workout.objects.filter(user=user, started__isnull=False)\n\n try:\n latest_workout = workouts.latest(\"started\")\n earliest_workout = workouts.earliest(\"started\")\n\n return latest_workout.started, earliest_workout.started\n\n except Exception as e:\n logging.warn(str(e))\n return None, None\n\n\ndef week_range(number:int=None, end=None, start=timezone.now()):\n if number is None and end is None:\n raise AttributeError(\"number or end parameter must be provided\")\n\n week_start = arrow.get(start).floor('week').datetime\n week = datetime.timedelta(weeks=1)\n second = datetime.timedelta(seconds=1)\n\n while True:\n yield (week_start, week_start + week - second)\n week_start -= week\n\n if end is not None and week_start < end:\n break\n\n if number is not None:\n number -= 1\n if number <= 0:\n break\n\n\nclass Day:\n def __init__(self, start_time):\n self.start_time = start_time\n self.workouts = []\n\n def __repr__(self):\n return str(self.workouts)\n\n\nclass Week:\n def __init__(self, statistics, start_time, end_time):\n self.statistics = statistics\n self.start_time = start_time\n self.end_time = end_time\n\n @property\n def workouts(self):\n return self.statistics.previous_workouts(self.start_time, self.end_time)\n\n @property\n def days(self):\n\n def make_day(number):\n start_time = self.start_time + datetime.timedelta(days=number)\n return Day(start_time)\n\n result = list(map(make_day, range(7)))\n\n for workout in self.workouts:\n day = workout.started.weekday()\n result[day].workouts.append(workout)\n\n logging.debug(str(result))\n\n return reversed(result)\n\n\nclass Statistics:\n def __init__(self, user):\n self.user = user\n\n def total_reps(self):\n return Reps.objects.filter(excercise__workout__user=self.user).aggregate(Sum('reps'))['reps__sum']\n\n def total_km(self):\n meters = Gpx.objects.filter(workout__user=self.user).aggregate(Sum('length_2d'))['length_2d__sum']\n return units.km_from_m(meters)\n\n def _volume(self, workout_type):\n return 0\n\n def most_popular_workouts(self):\n workouts = Workout.objects \\\n .filter(user=self.user) \\\n .values_list('workout_type') \\\n .annotate(count=Count('workout_type')) \\\n .order_by('-count')\n\n def decorate_with_volume(workout):\n workout_type, count = workout\n return workout_type, count, self._volume(workout_type)\n\n return map(decorate_with_volume, workouts)\n\n def weeks(self, start=datetime.datetime.utcnow()):\n\n def make_week(week_bounds):\n return Week(self, *week_bounds)\n\n _, end_time = workouts_time_bounds(self.user)\n\n logging.debug(\"building weeks up to {}\".format(end_time))\n\n if end_time is None:\n return []\n\n result = list(map(make_week, week_range(start=start, end=end_time)))\n\n return result\n\n def reps_per_week(self):\n def reps_in_range(time_range):\n begin, end = time_range\n reps = Reps.objects.filter(excercise__workout__user=self.user,\n excercise__time_started__gt=begin,\n excercise__time_started__lt=end).aggregate(Sum('reps'))['reps__sum']\n\n return {'time': '{:%d.%m}'.format(end),\n 'value': 0 if reps is None else reps}\n\n return list(map(reps_in_range, week_range(5)))\n\n def previous_workouts(self, begin=None, end=None):\n if begin is not None and end is not None:\n return Workout.objects.filter(user=self.user,\n started__gt=begin,\n started__lt=end).order_by('-started')\n else:\n return Workout.objects.filter(user=self.user).order_by('-started')\n\n def not_started_workouts(self):\n return Workout.objects.filter(user=self.user, started__isnull=True)\n\n def most_common_excercises(self):\n return Excercise.objects.filter(workout__user=self.user).values_list('name').annotate(count=Count('name')).order_by('-count')\n","sub_path":"training/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"220564366","text":"from urllib.request import urlopen\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\nfrom bs4 import BeautifulSoup\ndef getcontent(url):\n try:\n html=urlopen(url)\n except HTTPError as e:\n return None\n try:\n bsObj=BeautifulSoup(html,'html.parser')\n content=bsObj.body\n except AttributeError as e:\n return None\n return content\ndef getdate(url):\n try:\n html=urlopen(url)\n except HTTPError as e:\n return None\n try:\n bsObj=BeautifulSoup(html,'html.parser')\n date=bsObj.findAll(\"span\",{\"class\":\"posted-date\"})\n except AttributeError as e:\n return None\n return date\ndef gettitle(url):\n try:\n html=urlopen(url)\n except HTTPError as e:\n return None\n try:\n bsObj=BeautifulSoup(html,'html.parser')\n title=bsObj.findAll(\"h2\",{\"class\":\"entry-title\"})\n except AttributeError as e:\n return None\n return title\ndef getsummary(url):\n try:\n html=urlopen(url)\n except HTTPError as e:\n return None\n try:\n bsObj=BeautifulSoup(html,'html.parser')\n summary=bsObj.findAll(\"div\",{\"class\":\"entry-summary\"})\n except AttributeError as e:\n return None\n return summary\ndef getauthor(url):\n try:\n html=urlopen(url)\n except HTTPError as e:\n return None\n try:\n bsObj=BeautifulSoup(html,'html.parser')\n author=bsObj.findAll(\"span\",{\"class\":\"entry-author\"})\n except AttributeError as e:\n return None\n return author\ncontent = getcontent(\"https://blog.snowstar.org/\")\nauthor=getauthor(\"https://blog.snowstar.org/\")\ndate=getdate(\"https://blog.snowstar.org/\")\ntitle=gettitle(\"https://blog.snowstar.org/\")\nsummary=getsummary(\"https://blog.snowstar.org/\")\nif title == None:\n print(\"title could not be found\")\nelse:\n print(title)\n '''with open('C:/work/data.txt','a') as f:\n f.write(title)'''\nif author == None:\n print(\"author could not be found\")\nelse:\n print(author)\n '''with open('C:/work/data.txt','a') as f:\n f.write(author)'''\nif date == None:\n print(\"date could not be found\")\nelse:\n print(date)\n '''with open('C:/work/data.txt','a') as f:\n f.write(date)'''\nif summary == None:\n print(\"summary could not be found\")\nelse:\n print(summary)\n '''with open('C:/work/data.txt','a') as f:\n f.write(summary)'''","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"321482953","text":"import json\r\nfrom flask import Blueprint, request\r\n\r\nimport Models, Errors, Utils\r\nimport ObjectiveResponses as R\r\nfrom Database import DBSession\r\n\r\nthis = Blueprint('session', __name__)\r\n\r\n@this.route('/session/minecraft/join', methods=['POST'])\r\ndef joinGame():\r\n req = json.loads(request.data)\r\n \r\n # 检查 AccessToken\r\n session = Models.Session.query.filter(Models.Session.access_token == req['accessToken']).first()\r\n if session == None:\r\n return json.dumps(Errors.InvalidToken), 403, {'Content-Type': 'application/json'}\r\n \r\n # 验证令牌与角色对应关系\r\n if session.profile_uuid != req['selectedProfile']:\r\n return json.dumps(Errors.InvalidToken), 403, {'Content-Type': 'application/json'}\r\n \r\n # 保存 ServerID\r\n DBSession.add(Models.ServerID(req['serverId'], session.profile_uuid))\r\n DBSession.commit()\r\n return '', 204\r\n\r\n@this.route('/session/minecraft/hasJoined', methods=['GET'])\r\ndef hasJoined():\r\n r_username = request.args.get('username')\r\n r_serverId = request.args.get('serverId')\r\n # r_ip = request.args.get('ip')\r\n \r\n # 查找 ServerID\r\n server_id = Models.ServerID.query.filter(Models.ServerID.server_id == r_serverId).first()\r\n if server_id == None:\r\n return '', 204\r\n \r\n # 验证 ServerID 对应的 Username(实际上是 Profile 名称)\r\n profile = Models.Profile.query.filter(Models.Profile.uuid == server_id.profile_uuid).first()\r\n if profile == None:\r\n return '', 204\r\n print(server_id.profile_uuid, profile.uuid, profile.name, r_username)\r\n if profile.name != r_username:\r\n return '', 204\r\n DBSession.delete(server_id)\r\n DBSession.commit()\r\n \r\n # 查询角色和皮肤信息\r\n skin = Models.Skin.query.filter(Models.Skin.profile_uuid == profile.uuid).first()\r\n cape = Models.Cape.query.filter(Models.Cape.profile_uuid == profile.uuid).first()\r\n if skin == None: skin = Utils.NullSkin\r\n if cape == None: cape = Utils.NullCape\r\n r_profile = R.Profile(profile.name, R.Texture(profile.name, skin.hash, skin.model, cape.hash).base64json(), True, True)\r\n return r_profile.json(), {'Content-Type': 'application/json'}\r\n\r\n@this.route('/session/minecraft/profile/', methods=['GET'])\r\ndef get_role(uuid):\r\n r_unsigned = request.args.get('unsigned')\r\n if r_unsigned == 'false':\r\n signture = True\r\n else:\r\n signture = False\r\n profile = Models.Profile.query.filter(Models.Profile.uuid == uuid).first()\r\n if profile == None:\r\n return '', 204\r\n skin = Models.Skin.query.filter(Models.Skin.profile_uuid == uuid).first()\r\n cape = Models.Cape.query.filter(Models.Cape.profile_uuid == uuid).first()\r\n if skin == None: skin = Utils.NullSkin\r\n if cape == None: cape = Utils.NullCape\r\n r_profile = R.Profile(profile.name, R.Texture(profile.name, skin.hash, skin.model, cape.hash).base64json(), True, signture)\r\n return r_profile.json(), {'Content-Type': 'application/json'}\r\n \r\n","sub_path":"Blueprints/Session.py","file_name":"Session.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"442755666","text":"from __future__ import division, print_function\r\nimport sys\r\nimport io\r\nimport os\r\nimport glob\r\nimport re\r\nimport numpy as np\r\nimport cv2\r\n\r\n# Keras\r\nfrom keras.applications.imagenet_utils import preprocess_input, decode_predictions\r\nfrom keras.models import load_model\r\nfrom keras.preprocessing import image\r\n\r\n# Flask utils\r\nfrom flask import Flask, redirect, url_for, request, render_template, jsonify, send_from_directory\r\nfrom werkzeug.utils import secure_filename\r\nfrom gevent.pywsgi import WSGIServer\r\n\r\nUPLOAD_FOLDER = 'uploads'\r\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\r\n\r\n# Define a flask app\r\napp = Flask(__name__)\r\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\r\n\r\n# Model saved with Keras model.save()\r\nMODEL_PATH = 'models/grape_disease_classifier.h5'\r\nFILE_PATH_FINAL = None\r\n\r\n# Load your trained model\r\nmodel = load_model(MODEL_PATH)\r\nmodel._make_predict_function() \r\nprint('Model loaded. Start serving...')\r\n\r\ndef model_predict(img_path, model):\r\n\timg = cv2.imread(img_path)\r\n\timg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n\timg = cv2.resize(img,(256,256))\r\n\timg = np.reshape(img,[1,256,256,3])\r\n\tdisease = model.predict_classes(img)\r\n\tpreds = disease[0]\r\n\treturn preds\r\n\r\ndef assign_filepath(file_path):\r\n global FILE_PATH_FINAL\r\n FILE_PATH_FINAL = file_path\r\n \r\n\r\n@app.route('/', methods=['GET'])\r\ndef index():\r\n # Main page\r\n return render_template('index.html')\r\n\r\n@app.route('/uploads/')\r\ndef uploaded_file(filename):\r\n return send_from_directory(app.config['UPLOAD_FOLDER'],\r\n filename)\r\n\t\r\n@app.route('/predict', methods=['GET', 'POST'])\r\ndef upload():\r\n if request.method == 'POST':\r\n # Get the file from post request\r\n f = request.files['file']\r\n print(type(f))\r\n in_memory_file = io.BytesIO()\r\n f.save(in_memory_file)\r\n data = np.fromstring(in_memory_file.getvalue(), dtype=np.uint8)\r\n color_image_flag = 1\r\n img = cv2.imdecode(data, color_image_flag)\r\n img = cv2.resize(img,(256,256))\r\n\r\n # Save the file to ./uploads\r\n basepath = os.path.dirname(__file__)\r\n file_path = os.path.join(\r\n basepath, 'uploads', secure_filename(f.filename))\r\n cv2.imwrite(file_path, img)\r\n '''f.save(file_path)'''\r\n assign_filepath(file_path)\r\n \r\n\r\n # Make prediction\r\n preds = model_predict(file_path, model)\r\n if preds == 0:\r\n return jsonify(dict(redirect='black_measles'))\r\n elif preds == 1:\r\n return jsonify(dict(redirect='black_rot'))\r\n elif preds == 2:\r\n return jsonify(dict(redirect='healthy'))\r\n elif preds == 3:\r\n return jsonify(dict(redirect='leaf_blight'))\r\n else:\r\n result = \"none\"\r\n return result\r\n return None\r\n\t\r\n@app.route('/black_measles', methods=['GET', 'POST'])\r\ndef black_measles():\r\n\treturn render_template('black_measles.html')\r\n\r\n@app.route('/black_rot', methods=['GET', 'POST'])\r\ndef black_rot():\r\n\treturn render_template('black_rot.html')\r\n\r\n@app.route('/healthy', methods=['GET', 'POST'])\r\ndef healthy():\r\n\treturn render_template('healthy.html')\r\n\t\r\n@app.route('/leaf_blight', methods=['GET', 'POST'])\r\ndef leaf_blight():\r\n\treturn render_template('leaf_blight.html')\r\n\r\n@app.route('/file_path', methods=['GET','POST'])\r\ndef file_path():\r\n return FILE_PATH_FINAL\r\n\t\r\nif __name__ == '__main__':\r\n '''app.run(port=5002, debug=True)'''\r\n # Serve the app with gevent\r\n http_server = WSGIServer(('', 5000), app)\r\n http_server.serve_forever()\r\n","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"85915122","text":"#!/usr/bin/python3\nfrom pathlib import Path\nfrom rofi import rofi\nimport sys\n\n\ndef fancy(label, number):\n return f\"{label} ({number})\"\n\n\ndef remove_duplicates(ls):\n new_list = []\n [new_list.append(elem) for elem in ls if not elem in new_list]\n return new_list\n\n\ndef get_labels(path):\n file = open(path, mode='r', encoding='utf-8-sig')\n lines = file.readlines()\n file.close()\n lines = [line for line in lines if\n '\\\\newlabel' in line and '{' in line and not '@' in line and not 'gdef' in line and not 'LastPage' in line]\n\n labels = [line.split('{')[1].split('}')[0] for line in lines]\n numbers = [line.split('{')[3].split('}')[0] for line in lines]\n options = [fancy(label, number) for (label, number) in zip(labels, numbers)]\n return labels, options\n\n\ndef get_all_labels(pathlist):\n labels = []\n options = []\n for path in pathlist:\n try:\n nlabels, noptions = get_labels(path)\n except:\n continue\n\n labels += nlabels\n options += noptions\n unique = remove_duplicates(zip(labels, options))\n return [a for (a, b) in unique], [b for (a, b) in unique]\n\n\ndef main(args):\n arglist = []\n if len(args) > 1:\n path = Path(args[1])\n arglist = list(path.glob('*.aux'))\n else:\n arglist = ['/home/maximilian/current_course/full.aux']\n\n labels, options = get_all_labels(arglist)\n\n key, index, selected = rofi('Select label', options, [\n '-lines', min(40, max(len(options), 5)), '-width', '1700'\n ])\n\n if index >= 0:\n command = labels[index]\n else:\n command = selected\n return command.strip()\n\n\nif __name__ == '__main__':\n selected_label = main(sys.argv)\n print(selected_label)\n","sub_path":"scripts/labels.py","file_name":"labels.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"510818399","text":"#!/usr/bin/python3\ndef mergesort(a_list):\n print('splitting list...',a_list)\n if len(a_list) > 1:\n mid = len(a_list)//2\n lefthalf = a_list[:mid]\n righthalf = a_list[mid:]\n #recursive call to split list further\n mergesort(lefthalf)\n mergesort(righthalf)\n \n i = 0\n j = 0\n k = 0\n while i < len(lefthalf) and j < len(righthalf):\n if lefthalf[i] < righthalf[j]:\n a_list[k] = lefthalf[i]\n i = i+1\n else:\n a_list[k] = righthalf[j]\n j = j+1\n k = k+1\n while i < len(lefthalf):\n a_list[k] = lefthalf[i]\n i = i+1\n k = k+1\n while j < len(righthalf):\n a_list[k] = righthalf[j]\n j = j+1\n k = k+1\n print('Merging',a_list)\n\nmylist = [21,1,26,45,29,28,2,9,16,49,39,27,43,34,46,40]\nprint('Before',mylist)\nmergesort(mylist)\nprint('After',mylist)\n\n\n","sub_path":"GooglePython/andela-tests/msort2.py","file_name":"msort2.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"59369388","text":"import pymongo\n\nconnection = pymongo.MongoClient(\"mongodb://localhost\")\ndb = connection.students\n\ndocs = db.grades.find({\"type\": \"homework\"}).sort([(\"student_id\", pymongo.ASCENDING), (\"score\", pymongo.ASCENDING)])\n\nstd_id = \"PLACE_HOLDER\"\ndeleted = 0\nfor doc in docs:\n if doc['student_id'] != std_id:\n std_id = doc['student_id']\n d = db.grades.delete_one({'_id': doc['_id']})\n deleted += d.deleted_count\nprint('{} docs deleted'.format(deleted))\n","sub_path":"mongodb/m101p/chapter_2_crud/hw22.py","file_name":"hw22.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"188363983","text":"import re\r\nimport html2text\r\n\r\nfile = open(\"index.html\", \"r\").read()\r\n\r\nentry_matches = re.finditer(\"((.|\\s)*?)\", file)\r\n\r\n\r\ndef clear_html(text):\r\n text = re.sub('(.*?)', '**\\g<1>**', text)\r\n text = re.sub('(.*?)', '_\\g<1>_', text)\r\n text = html2text.html2text(text).replace(\"\\n\", \" \")\r\n return text.strip()\r\n\r\n\r\ncsv = []\r\nfor match in entry_matches:\r\n dic = {}\r\n kanji = re.search('

((.|\\s)*?)

', match.group())\r\n kanji_explanation = re.search('

((.|\\s)*?)

', match.group())\r\n if kanji:\r\n dic['kanji'] = clear_html(kanji.group(1))\r\n if kanji_explanation:\r\n dic['kanji_explanation'] = clear_html(kanji_explanation.group(1))\r\n primitive_explanation = re.search('

((.|\\s)*?)

', match.group())\r\n if primitive_explanation:\r\n dic['primitive_explanation'] = clear_html(primitive_explanation.group(1))\r\n primitive_meanings = []\r\n meaning_matches = re.finditer('(.*?)', primitive_explanation.group())\r\n for match in meaning_matches:\r\n primitive_meanings.append(re.sub(\"[^A-Za-z ]\", \"\",match.group(1).lower().strip()))\r\n dic['primitive_meanings'] = list(set(primitive_meanings))\r\n csv.append(dic)\r\n\r\ntext = list(csv)\r\nordered_meanings = []\r\nprim_only = []\r\norder = ['kanji', 'kanji_explanation', 'primitive_meanings', 'primitive_explanation']\r\nfor i in range(len(text)):\r\n if 'primitive_meanings' in text[i].keys():\r\n text[i] = [text[i][x] if x in text[i].keys() else \"\" for x in order]\r\n if text[i][2] != \"\":\r\n text[i][2] = \",\".join(text[i][2])\r\n ordered_meanings.append(text[i][2])\r\n text[i] = \";\".join(text[i])\r\n\r\nto_write = \"\"\r\nfor line in ordered_meanings:\r\n if line.strip() != \"\":\r\n to_write += line + \"\\n\"\r\nopen(\"order.txt\", \"w+\").write(to_write.strip())\r\n\r\n# with open(\"kanji_and_primitive_exps.csv\", \"w+\") as file:\r\n# to_write = \"\"\r\n# for line in real_text:\r\n# to_write += line + \"\\n\"\r\n# file.write(to_write.strip())\r\n","sub_path":"Japanese-concept-recognizer/real_primitives/primitive_story_extractor.py","file_name":"primitive_story_extractor.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"585737441","text":"\n'''Copyright (c) 2017, Marek Cieplucha, https://github.com/mciepluc\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, \nare permitted provided that the following conditions are met (The BSD 2-Clause \nLicense):\n\n1. Redistributions of source code must retain the above copyright notice, \nthis list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, \nthis list of conditions and the following disclaimer in the documentation and/or \nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL POTENTIAL VENTURES LTD BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. '''\n\n\"\"\"\nConstrained-random verification features.\n\nClasses:\nRandomized - base class for objects intended to contain random variables\n\"\"\"\n\nimport random\nimport constraint\nimport inspect\nimport itertools\n\nclass Randomized(object):\n \"\"\"\n Base class for randomized types. Final class should contain defined random \n variables using addRand() method. Constraints may be added/deleted using \n add/delConstraint() methods. \n Constraint is an arbitrary function and may either return a true/false value\n (hard constraints) or a numeric value, which may be interpreted as soft \n constraints or distribution functions. Constraint function arguments must \n match final class attributes (random or not). Constraints may have multiple \n random arguments which corresponds to multi-dimensional distributions.\n Function randomize() performs a randomization for all random variables \n meeting all defined constraints. \n Function randomize_with() performs a randomization using additional \n constraint functions given in an argument.\n Functions pre/post_randomize() are called before/after randomize and should \n be overloaded in a final class if necessary. \n If a hard constraint cannot be resolved, an exception is thrown. If a soft\n constraint cannot be resolved (all acceptable solutions have 0 probability)\n a variable value is not being randomized. \n\n Example:\n class FinalRandomized(Randomized)\n def __init__(self, x):\n Randomized.__init__(self)\n self.x = x\n self.y = 0\n self.z = 0\n #define y as a random variable taking values from 0 to 9\n addRand(y, list(range(10)))\n #define z as a random variable taking values from 0 to 4\n addRand(z, list(range(5))) \n addConstraint(lambda x, y: x !=y ) #hard constraint\n addConstraint(lambda y, z: y + z ) #multi-dimensional distribution\n\n object = FinalRandomized(5)\n object.randomize_with(lambda z : z > 3) #additional constraint to be applied\n\n As generating constrained random objects may involve a lot of computations, \n it is recommended to limit random variables domains and use \n pre/post_randomize() methods where possible. \n \"\"\"\n def __init__(self):\n # all random variables, map NAME -> DOMAIN\n self._randVariables = {}\n \n # all simple constraints: functions of single random variable and\n # optional non-random variables\n # map VARIABLE NAME -> FUNCTION\n self._simpleConstraints = {}\n \n # all implicit constraints: functions that requires to be resolved by a\n # Solver\n # map TUPLE OF VARIABLE NAMES -> FUNCTION\n self._implConstraints = {}\n \n # all implicit distributions: functions that involve implicit random\n # variables and single unconstrained variable\n # map TUPLE OF VARIABLE NAMES -> FUNCTION\n self._implDistributions = {}\n \n # all simple distributions: functions of unconstrained random variables\n # and non-random variables\n # map VARIABLE NAME -> FUNCTION\n self._simpleDistributions = {}\n \n # list of lists containing random variables solving order\n self._solveOrder = []\n\n def addRand(self, var, domain=None):\n \"\"\"\n Adds a random variable to the solver. All random variables must be \n defined before adding any constraint. Therefore it is highly \n recommended to do this in an __init__ method. \n Syntax:\n addRand(var, domain)\n Where:\n var - a variable name (str) corresponding to the class member variable\n domain - a list of all allowed values of the variable var\n\n Examples:\n addRand(\"data\", list(range(1024)))\n addRand(\"delay\", [\"small\", \"medium\", \"high\"])\n \"\"\"\n assert (not (self._simpleConstraints or\n self._implConstraints or\n self._implDistributions or\n self._simpleDistributions)\n ), \\\n \"All random variable must be defined before adding a constraint\"\n\n if not domain:\n domain = range(65535) # 16 bit unsigned int\n\n self._randVariables[var] = domain # add a variable to the map\n\n def addConstraint(self, cstr):\n \"\"\"\n Adds a constraint function to the solver. A constraint may return a \n true/false or a numeric value. Constraint function arguments must be \n valid class member names (random or not). Arguments must be listed in \n alphabetical order. Due to calculation complexity, it is recommended to \n create as few constraints as possible and implement pre/post \n randomization methods or use solveOrder() function.\n Each constraint is associated with its arguments being random variables, \n which means for each random variable combination only one constraint of \n the true/false type and one numeric may be defined. The latter will \n overwrite the existing one. For example, when class has two random \n variables (x,y), 6 constraint functions may be defined: boolean and \n numeric constraints of x, y and a pair (x,y). \n Syntax:\n (ovewritting = )addConstraint(cstr)\n Where:\n cstr - a constraint function\n overwritting - returns an overwritten constraint or None if no overwrite\n happened (optional)\n\n Examples:\n def highdelay_cstr(delay):\n delay == \"high\"\n addConstraint(highdelay_cstr) #hard constraint\n addConstraint(lambda data : data < 128) #hard constraint\n #distribution (highest probability density at the boundaries):\n addConstraint(lambda data : abs(64 - data)) \n #hard constraint of multiple variables (some of them may be non-random):\n addConstraint(lambda x,y,z : x + y + z == 0) \n #soft constraint created by applying low probability density for some \n #solutions:\n addConstraint(\n lambda delay, size : 0.01 if (size < 5 & delay == \"medium\") else 1\n ) \n #this constraint will overwrite the previously defined (data < 128)\n addConstraint(lambda data : data < 256)\n \"\"\"\n \n #just add constraint considering all random variables \n return self._addConstraint(cstr, self._randVariables)\n \n def solveOrder(self, *orderedVars):\n \"\"\"\n Defines an order of the constraints resolving. May contain variable\n names or lists with variable names. Constraints are resolved in a given\n order, which means for implicit constraint and distribution functions,\n they may be treated as simple ones, as one some variables could be \n already resolved.\n solveOrder(*orderedVars)\n Where:\n orderedVars - variables that are requested to be resolved in an specific\n order\n Example:\n addRand (x, list(range(0,10)))\n addRand (y, list(range(0,10)))\n addRand (z, list(range(0,10)))\n addRand (w, list(range(0,10)))\n addConstraint(lambda x, y : x + y = 9)\n addConstraint(lambda z : z < 5) \n addConstraint(lambda w : w > 5)\n \n solveOrder([\"x\", \"z\"], \"y\"] \n #In first step, \"z\", \"x\" and \"w\" will be resolved, which means only \n #second and third constraint will be applied. In second step, first \n #constraint will be resolved as it was requested to solve \"y\" after \"x\"\n #and \"z\". \"x\" will be treated as a constant in this case. \n \"\"\"\n self._solveOrder = []\n for selRVars in orderedVars:\n if type(selRVars) is not list:\n self._solveOrder.append([selRVars])\n else:\n self._solveOrder.append(selRVars)\n\n def delConstraint(self, cstr):\n \"\"\"\n Deletes a constraint function.\n Syntax:\n delConstraint(cstr)\n Where:\n cstr - a constraint function\n\n Example:\n delConstraint(highdelay_cstr) \n \"\"\"\n return self._delConstraint(cstr, self._randVariables)\n\n def pre_randomize(self):\n \"\"\"\n A function called before randomize(_with)(). To be overridden in a final \n class if used. \n \"\"\"\n pass\n\n def post_randomize(self):\n \"\"\"\n A function called after randomize(_with)(). To be overridden in a final \n class if used. \n \"\"\"\n pass\n\n def randomize(self):\n \"\"\"\n Randomizes a final class using only predefined constraints.\n \"\"\"\n self._randomize()\n\n def randomize_with(self, *constraints):\n \"\"\"\n Randomizes a final class using additional constraints given in an \n argument. Additional constraints may override existing ones.\n \"\"\"\n overwritten_constrains = []\n\n # add new constraints\n for cstr in constraints:\n overwritten = self.addConstraint(cstr)\n if overwritten:\n overwritten_constrains.append(overwritten)\n \n raise_exception = False\n try:\n self._randomize()\n except:\n raise_exception = True\n\n # remove new constraints\n for cstr in constraints:\n self.delConstraint(cstr)\n\n # add back overwritten constraints\n for cstr in overwritten_constrains:\n self.addConstraint(cstr)\n \n if raise_exception:\n raise Exception(\"Could nor resolve implicit constraints!\")\n \n def _addConstraint(self, cstr, rvars):\n \"\"\"\n Adds a constraint for a specific random variables list (which determines\n a type of a constraint - simple or implicit).\n \"\"\" \n if isinstance(cstr, constraint.Constraint):\n # could be a Constraint object...\n pass\n else:\n variables = inspect.getargspec(cstr).args\n assert (variables == sorted(variables)), \\\n \"Variables of a constraint function must be defined in \\\n alphabetical order\"\n\n # determine the function type... rather unpythonic but necessary for\n # distinction between a constraint and a distribution\n callargs = []\n rand_variables = []\n for var in variables:\n if var in rvars:\n rand_variables.append(var)\n callargs.append(random.choice(rvars[var]))\n else:\n callargs.append(getattr(self, var))\n\n ret = cstr(*callargs)\n\n def _addToMap(_key, _map):\n overwriting = None\n if _key in _map:\n overwriting = _map[_key]\n _map[_key] = cstr\n return overwriting\n\n if type(ret) is bool:\n # this is a constraint\n if (len(rand_variables) == 1):\n overwriting = _addToMap(\n rand_variables[0], self._simpleConstraints)\n else:\n overwriting = _addToMap(\n tuple(rand_variables), self._implConstraints)\n else:\n # this is a distribution\n if (len(rand_variables) == 1):\n overwriting = _addToMap(\n rand_variables[0], self._simpleDistributions)\n else:\n overwriting = _addToMap(\n tuple(rand_variables), self._implDistributions)\n\n return overwriting\n \n def _delConstraint(self, cstr, rvars):\n \"\"\"\n Deletes a constraint for a specific random variables list (which \n determines a type of a constraint - simple or implicit).\n \"\"\" \n if isinstance(cstr, constraint.Constraint):\n # could be a Constraint object...\n pass\n else:\n variables = inspect.getargspec(cstr).args\n\n rand_variables = [\n var for var in variables if var in rvars]\n\n if (len(rand_variables) == 1):\n if rand_variables[0] in self._simpleConstraints:\n del self._simpleConstraints[rand_variables[0]]\n elif rand_variables[0] in self._simpleDistributions:\n del self._simpleDistributions[rand_variables[0]]\n else:\n assert(0), \"Could not delete a constraint!\"\n else:\n if tuple(rand_variables) in self._implConstraints:\n del self._implConstraints[tuple(rand_variables)]\n elif tuple(rand_variables) in self._implDistributions:\n del self._implDistributions[tuple(rand_variables)]\n else:\n assert(0), \"Could not delete a constraint!\"\n \n \n def _randomize(self):\n \"\"\"\n Calls _resolve and pre/post_randomize functions with respect to defined \n variables resolving order.\n \"\"\"\n self.pre_randomize()\n if not self._solveOrder:\n #call _resolve for all random variables \n solution = self._resolve(self._randVariables)\n self._update_variables(solution)\n else:\n \n #list of random variables names\n remainingRVars = list(self._randVariables.keys())\n \n #list of resolved random variables names \n resolvedRVars = []\n \n #list of random variables with defined solve order\n remainingOrderedRVars = [item for sublist in self._solveOrder \n for item in sublist]\n \n allConstraints = [] # list of functions (all constraints and dstr)\n allConstraints.extend([self._implConstraints[_] \n for _ in self._implConstraints])\n allConstraints.extend([self._implDistributions[_] \n for _ in self._implDistributions])\n allConstraints.extend([self._simpleConstraints[_] \n for _ in self._simpleConstraints])\n allConstraints.extend([self._simpleDistributions[_] \n for _ in self._simpleDistributions])\n \n for selRVars in self._solveOrder:\n \n #step 1: determine all variables to be solved at this stage\n actualRVars = list(selRVars) #add selected\n for rvar in actualRVars:\n remainingOrderedRVars.remove(rvar) #remove selected\n remainingRVars.remove(rvar) #remove selected\n \n #if implicit constraint requires a variable which is not given\n #at this stage, it will be resolved later\n for rvar in remainingRVars:\n rvar_unused = True\n for c_vars in self._implConstraints:\n if rvar in c_vars:\n rvar_unused = False\n for d_vars in self._implDistributions:\n if rvar in d_vars:\n rvar_unused = False\n if rvar_unused and not rvar in remainingOrderedRVars:\n actualRVars.append(rvar)\n remainingRVars.remove(rvar)\n \n # a new map of random variables\n newRandVariables = {}\n for var in self._randVariables:\n if var in actualRVars:\n newRandVariables[var] = self._randVariables[var]\n \n #step 2: select only valid constraints at this stage\n \n #delete all constraints and add back but considering only \n #limited list of random vars\n actualCstr = []\n for f_cstr in allConstraints:\n self.delConstraint(f_cstr)\n f_cstr_args = inspect.getargspec(f_cstr).args\n #add only constraints containing actualRVars but not\n #remainingRVars\n add_cstr = True\n for var in f_cstr_args:\n if (var in self._randVariables and \n not var in resolvedRVars and\n (not var in actualRVars or var in remainingRVars)\n ):\n add_cstr = False\n if add_cstr: \n self._addConstraint(f_cstr, newRandVariables)\n actualCstr.append(f_cstr)\n \n #call _resolve for all random variables \n solution = self._resolve(newRandVariables)\n self._update_variables(solution) \n \n resolvedRVars.extend(actualRVars)\n \n #add back everything as it was before this stage\n for f_cstr in actualCstr:\n self._delConstraint(f_cstr, newRandVariables)\n \n for f_cstr in allConstraints: \n self._addConstraint(f_cstr, self._randVariables)\n \n self.post_randomize()\n\n def _resolve(self, randomVariables):\n \"\"\"\n Resolves constraints for given random variables.\n \"\"\"\n \n # we need a copy, as we will be updating domains\n randVariables = dict(randomVariables)\n \n # step 1: determine search space by applying simple constraints to the\n # random variables\n\n for rvar in randVariables:\n domain = randVariables[rvar]\n new_domain = []\n if rvar in self._simpleConstraints:\n # a simple constraint function to be applied\n f_cstr = self._simpleConstraints[rvar]\n # check if we have non-random vars in cstr...\n # arguments of the constraint function\n f_c_args = inspect.getargspec(f_cstr).args\n for ii in domain:\n f_cstr_callvals = []\n for f_c_arg in f_c_args:\n if (f_c_arg == rvar):\n f_cstr_callvals.append(ii)\n else:\n f_cstr_callvals.append(getattr(self, f_c_arg))\n # call simple constraint for each domain element\n if f_cstr(*f_cstr_callvals):\n new_domain.append(ii)\n # update the domain with the constrained one\n randVariables[rvar] = new_domain\n\n # step 2: resolve implicit constraints using external solver\n\n # we use external hard constraint solver here - file constraint.py\n problem = constraint.Problem()\n\n constrainedVars = [] # all random variables for the solver\n\n for rvars in self._implConstraints:\n # add all random variables\n for rvar in rvars:\n if not rvar in constrainedVars:\n problem.addVariable(rvar, randVariables[rvar])\n constrainedVars.append(rvar)\n # add constraint\n problem.addConstraint(self._implConstraints[rvars], rvars)\n\n # solve problem\n solutions = problem.getSolutions()\n \n if (len(solutions) == 0) & (len(constrainedVars) > 0):\n raise Exception(\"Could nor resolve implicit constraints!\")\n\n # step 3: calculate implicit distributions for all random variables\n # except simple distributions\n\n # all variables that have defined distribution functions\n distrVars = []\n # solutions with applied distribution weights - list of maps VARIABLE\n # -> VALUE\n dsolutions = []\n\n # add all variables that have defined distribution functions\n for dvars in self._implDistributions:\n # add all variables that have defined distribution functions\n for dvar in dvars:\n if dvar not in distrVars:\n distrVars.append(dvar)\n\n # all variables that have defined distributions but unconstrained\n ducVars = [var for var in distrVars if var not in constrainedVars]\n\n # list of domains of random unconstrained variables\n ducDomains = [randVariables[var] for var in ducVars]\n\n # Cartesian product of above\n ducSolutions = list(itertools.product(*ducDomains))\n\n # merge solutions: constrained ones and all possible distribution values\n for sol in solutions:\n for ducsol in ducSolutions:\n dsol = dict(sol)\n jj = 0\n for var in ducVars:\n dsol[var] = ducsol[jj]\n jj += 1\n dsolutions.append(dsol)\n\n dsolution_weights = []\n dsolutions_reduced = []\n\n for dsol in dsolutions: # take each solution\n weight = 1.0\n # for all defined implicit distributions\n for dstr in self._implDistributions:\n f_idstr = self._implDistributions[dstr]\n f_id_args = inspect.getargspec(f_idstr).args\n # all variables in solution we need to calculate weight\n f_id_callvals = []\n for f_id_arg in f_id_args: # for each variable name\n if f_id_arg in dsol: # if exists in solution\n f_id_callvals.append(dsol[f_id_arg])\n else: # get as non-random variable\n f_id_callvals.append(getattr(self, f_id_arg))\n # update weight of the solution - call distribution function\n weight = weight * f_idstr(*f_id_callvals)\n # do the same for simple distributions\n for dstr in self._simpleDistributions:\n # but only if variable is already in the solution\n # if it is not, it will be calculated in step 4\n if dstr in sol:\n f_sdstr = self._simpleDistributions[dstr]\n f_sd_args = inspect.getargspec(f_sdstr).args\n # all variables in solution we need to calculate weight\n f_sd_callvals = []\n for f_sd_arg in f_sd_args: # for each variable name\n if f_sd_arg in dsol: # if exists in solution\n f_sd_callvals.append(dsol[f_sd_arg])\n else: # get as non-random variable\n f_sd_callvals.append(getattr(self, f_sd_arg))\n # update weight of the solution - call distribution function\n weight = weight * f_sdstr(*f_sd_callvals)\n if (weight > 0.0):\n dsolution_weights.append(weight)\n # remove solutions with weight = 0\n dsolutions_reduced.append(dsol)\n\n solution_choice = self._weighted_choice(\n dsolutions_reduced, dsolution_weights)\n solution = solution_choice if solution_choice is not None else {}\n\n # step 4: calculate simple distributions for remaining random variables\n for dvar in randVariables:\n if not dvar in solution: # must be already unresolved variable\n domain = randVariables[dvar]\n weights = []\n if dvar in self._simpleDistributions:\n # a simple distribution to be applied\n f_dstr = self._simpleDistributions[dvar]\n # check if we have non-random vars in dstr...\n f_d_args = inspect.getargspec(f_dstr).args\n # list of lists of values for function call\n f_d_callvals = []\n for i in domain:\n f_d_callval = []\n for f_d_arg in f_d_args:\n if (f_d_arg == dvar):\n f_d_callval.append(i)\n else:\n f_d_callval.append(getattr(self, f_d_arg))\n f_d_callvals.append(f_d_callval)\n # call distribution function for each domain element to get\n # the weight\n weights = [f_dstr(*f_d_callvals_i)\n for f_d_callvals_i in f_d_callvals]\n new_solution = self._weighted_choice(domain, weights)\n if new_solution is not None:\n # append chosen value to the solution\n solution[dvar] = new_solution\n else:\n # random variable has no defined distribution function -\n # call simple random.choice\n solution[dvar] = random.choice(domain)\n\n return solution\n\n def _weighted_choice(self, solutions, weights):\n \"\"\"\n Gets a solution from the list with defined weights.\n \"\"\"\n try:\n import numpy\n # pick weighted random\n return numpy.random.choice(solutions, size=1, p=weights)\n except:\n # if numpy not available\n non_zero_weights = [x for x in weights if x > 0]\n\n if not non_zero_weights:\n return None\n\n min_weight = min(non_zero_weights)\n\n weighted_solutions = []\n\n for x in range(len(solutions)):\n # insert each solution to the list multiple times\n weighted_solutions.extend(\n [solutions[x] for _ in range(\n int(weights[x] * (1.0 / min_weight)))\n ])\n\n return random.choice(weighted_solutions)\n\n def _update_variables(self, solution):\n \"\"\"\n Updates members of the final class after randomization.\n \"\"\"\n # update class members\n for var in self._randVariables:\n if var in solution:\n setattr(self, var, solution[var])\n","sub_path":"cocotb/crv.py","file_name":"crv.py","file_ext":"py","file_size_in_byte":27543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"239363442","text":"import random\n\nclass Dojo():\n def __init__(self):\n self.offices = []\n self.livingspaces = []\n self.all_rooms = self.offices + self.livingspaces\n self.staff = []\n self.fellow = []\n self.all_people = self.staff + self.fellow\n\n def create_room(self, room_name, room_type):\n if len(room_name) == 0 or len(room_type) == 0:\n if room_type.isalpha() and room_type == \"office\":\n for i in room_name:\n if i not in self.offices:\n if i.isalpha():\n self.offices.append(room_name)\n return self.offices\n elif room_type == \"livingspace\":\n for i in room_name:\n if i not in self.livingspaces:\n self.offices.append(room_name)\n return self.livingspaces\n\n def add_person(self, person_name, person_type, wants_accomodation=\"N\"):\n if len(person_name) == 0 or len(person_type) == 0:\n if person_type.isalpha() and person_type == \"fellow\":\n #if wants_accomodation ==\"Y\":\n #allocated_room = allocation(person_name)\n for i in person_name:\n if i not in self.all_people: \n if i.isalpha(): \n self.fellow.append(person_name)\n return self.fellow\n elif person_type == \"staff\":\n for i in person_name: \n if i not in self.all_people: \n self.staff.append(person_name)\n return self.staff\n \"\"\"\n def allocation(self, person_name, person_type):\n if person_type == \"staff\" or person_type == \"fellow\":\n office_check = random.choice(self.offices)\n if len(office_check) < 7:\n self\n \"\"\" \n \n\n","sub_path":"room_allocator/app/dojo.py","file_name":"dojo.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"472127529","text":"import pymongo\n# database vars\ncon = pymongo.Connection()\nbRoomsCol = con.DatabaseZMKM.bRooms\nmRoomsCol = con.DatabaseZMKM.mRooms\nsRoomsCol = con.DatabaseZMKM.sRooms\n\nbRoomsCol.remove()\nmRoomsCol.remove()\nsRoomsCol.remove()\nfrom BlockSettings import BlockSettings\nfor i in BlockSettings:\n for j in BlockSettings[i]['bRoomNumbersArray']:\n bRoomsCol.insert({\"state\": \"empty\", \"roomSize\": \"big\", \"roomNum\": str(j), \"id\": str(i)})\n for j in BlockSettings[i]['mRoomNumbersArray']:\n mRoomsCol.insert({\"state\": \"empty\", \"roomSize\": \"middle\", \"roomNum\": str(j), \"id\": str(i)})\n for j in BlockSettings[i]['sRoomNumbersArray']:\n sRoomsCol.insert({\"state\": \"empty\", \"roomSize\": \"small\", \"roomNum\": str(j), \"id\": str(i)})\n","sub_path":"resetLockers.py","file_name":"resetLockers.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"338583851","text":"from hypergraphs.semirings.lazysort import post_process, post_process2\n\n\ndef test_kbest():\n # XXX: add an automated test.\n\n if 1:\n from hypergraphs.apps.parse import papa\n H = papa.hypergraph\n else:\n from hypergraphs.apps.parse import abc\n H = abc.hypergraph\n\n Z = H.Z()\n for x in H.sorted():\n t = post_process(lambda e: e.head[2], x.data)\n print()\n print(float(x.score/Z))\n print(t)\n\n return\n\n\n# EXPERIMENTAL: trying to find the k-best derivations that include a specific\n# node or edge. Backpointers are messy in the outside pass because of the lack\n# of associativity.\ndef test_kbest_marginal():\n if 1:\n from hypergraphs.apps.parse import papa\n H = papa.hypergraph\n else:\n from hypergraphs.apps.parse import abc\n H = abc.hypergraph\n\n S = H._sorted()\n B = S.inside()\n A = S.outside(B)\n\n# item = (1,7,'VP',1)\n# item = (0,1,'Papa',0)\n\n for item in [*H.nodes\n# (0, 1, 'a', 0),\n# (1, 2, 'b', 0),\n# (2, 3, 'c', 0),\n ]:\n# H.show()\n print('\\nitem:', item)\n\n # XXX: the usual multiplication operation is AC, but ours is not. To get\n # around this we have to use a function to punch a hole in the product.\n # for x in B[item] * A[item]:\n for x in A[item]:\n# for x in B[item]:\n t = post_process2(lambda e: e.head[2], x.data)\n print(t)\n\n\n\nif __name__ == '__main__':\n test_kbest()\n# test_kbest_marginal()\n","sub_path":"test/kbest.py","file_name":"kbest.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"436002705","text":"import json\n\nfrom django.http import HttpResponseNotFound\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom .models import Product, Comment\n\n\ndef index(request, *args, **kwargs):\n try:\n sentiments = Comment.objects.values()\n sentiments = list(sentiments)\n # print(json.dumps(sentiments, ensure_ascii=False))\n keys = {\n 'id': '序列',\n 'c_id': '评论ID',\n 'p_id': '商品id',\n 'p_name': '商品',\n 'c_time': '评论时间',\n 'short': '评论内容',\n 'sentiment': '情感倾向',\n 'add_time': '爬取时间'\n }\n context = {\n 'results': json.dumps(sentiments, ensure_ascii=False),\n 'keys': json.dumps(keys, ensure_ascii=False),\n }\n return render(request, 'index.html', context)\n except Exception as e:\n return HttpResponseNotFound(f\"

{e}

\")\n","sub_path":"week10/MyDjango/smzd/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"519302298","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nBUFFER_SIZE = int(1e6) # replay buffer size\nBATCH_SIZE = 64 # minibatch size\nGAMMA = 0.99 # discount factor\nGRACE_PERIOD = int(1e3) # withold learning up to this\nTAU = 1e-3 # for soft update of target parameters\nLR_ACTOR = 1e-3 # learning rate of the actor\nLR_CRITIC = 1e-3 # learning rate of the critic\nUPDATE_FREQ = 10 # update frequency\nWEIGHT_DECAY = 1e-2 # L2 weight decay\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef final_layer_init(layer):\n nn.init.uniform_(layer.weight.data, -3e-3, 3e-3)\n return layer\n\n\ndef hidden_init(layer):\n fan_in = layer.weight.data.size()[0]\n lim = 1.0 / np.sqrt(fan_in)\n nn.init.uniform_(layer.weight.data, -lim, lim)\n return layer\n\n\nclass Actor(nn.Module):\n \"\"\"Actor (Policy) Model.\"\"\"\n\n def __init__(self, state_size, action_size, max_action, fc_units=(400, 300)):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n fc1_units (int): Number of nodes in first hidden layer\n fc2_units (int): Number of nodes in second hidden layer\n \"\"\"\n super(Actor, self).__init__()\n self.layers = nn.ModuleList()\n # self.layers.append(nn.BatchNorm1d(state_size))\n for i, (inp, outp) in enumerate(zip((state_size,) + fc_units, fc_units + (action_size,))):\n if i < len(fc_units):\n self.layers.append(hidden_init(nn.Linear(inp, outp)))\n self.layers.append(nn.ReLU())\n else:\n self.layers.append(final_layer_init(nn.Linear(inp, outp)))\n\n def forward(self, state):\n \"\"\"Build an actor (policy) network that maps states -> actions.\"\"\"\n for layer in self.layers:\n state = layer(state)\n return torch.tanh(state)\n\n\nclass Critic(nn.Module):\n \"\"\"Critic (Value) Model.\"\"\"\n\n def __init__(self, state_size, action_size, max_action, fcs1_units=256, fc2_units=256, fc3_units=128):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n fcs1_units (int): Number of nodes in the first hidden layer\n fc2_units (int): Number of nodes in the second hidden layer\n \"\"\"\n super(Critic, self).__init__()\n self.norm = nn.BatchNorm1d(state_size)\n self.fcs1 = hidden_init(nn.Linear(state_size, fcs1_units))\n self.fc2 = hidden_init(nn.Linear(fcs1_units + action_size, fc2_units))\n self.fc3 = hidden_init(nn.Linear(fc2_units, fc3_units))\n self.fc4 = final_layer_init(nn.Linear(fc3_units, 1))\n\n def forward(self, state, action):\n \"\"\"Build a critic (value) network that maps (state, action) pairs -> Q-values.\"\"\"\n state = self.norm(state)\n xs = F.leaky_relu(self.fcs1(state))\n x = torch.cat((xs, action), dim=1)\n x = F.leaky_relu(self.fc2(x))\n x = F.leaky_relu(self.fc3(x))\n return self.fc4(x)\n\n\nclass DDPG:\n def __init__(self, state_dim, action_dim, max_action):\n self.actor = Actor(state_dim, action_dim, max_action).to(device)\n self.actor_target = Actor(state_dim, action_dim, max_action).to(device)\n self.actor_target.load_state_dict(self.actor.state_dict())\n self.actor_optimizer = torch.optim.Adam(self.actor.parameters())\n\n self.critic = Critic(state_dim, action_dim, max_action).to(device)\n self.critic_target = Critic(state_dim, action_dim, max_action).to(device)\n self.critic_target.load_state_dict(self.critic.state_dict())\n self.critic_optimizer = torch.optim.Adam(self.critic.parameters())\n\n self.noise = OrnsteinUhlenbeckProcess(action_dim)\n\n def select_action(self, state):\n state = torch.FloatTensor(state.reshape(1, -1)).to(device)\n action = self.actor(state).cpu().data.numpy().flatten()\n action += self.noise.sample()\n return np.clip(action, -1, 1)\n\n def train(self, replay_buffer, iterations, batch_size=100, discount=0.99, tau=0.005):\n\n for _ in range(iterations):\n\n # Sample replay buffer\n x, y, u, r, d = replay_buffer.sample(batch_size)\n state = torch.FloatTensor(x).to(device)\n action = torch.FloatTensor(u).to(device)\n next_state = torch.FloatTensor(y).to(device)\n done = torch.FloatTensor(1 - d).to(device)\n reward = torch.FloatTensor(r).to(device)\n\n # Compute the target Q value\n target_Q = self.critic_target(next_state, self.actor_target(next_state))\n target_Q = reward + (done * discount * target_Q).detach()\n\n # Get current Q estimate\n current_Q = self.critic(state, action)\n\n # Compute critic loss\n critic_loss = F.mse_loss(current_Q, target_Q)\n\n # Optimize the critic\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n self.critic_optimizer.step()\n\n # Compute actor loss\n actor_loss = -self.critic(state, self.actor(state)).mean()\n\n # Optimize the actor\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n\n # Update the frozen target models\n for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\n target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)\n\n for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\n target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)\n\n def save(self, filename, directory):\n torch.save(self.actor.state_dict(), \"%s/%s_actor.pth\" % (directory, filename))\n torch.save(self.critic.state_dict(), \"%s/%s_critic.pth\" % (directory, filename))\n\n def load(self, filename, directory):\n self.actor.load_state_dict(torch.load(\"%s/%s_actor.pth\" % (directory, filename), map_location=device))\n self.critic.load_state_dict(torch.load(\"%s/%s_critic.pth\" % (directory, filename), map_location=device))\n\n\nclass Agent:\n \"\"\"Interacts with and learns from the environment.\"\"\"\n\n def __init__(self, state_size, action_size, random_seed, memory=None):\n \"\"\"Initialize an Agent object.\n\n Params\n ======\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n random_seed (int): random seed\n \"\"\"\n self.num_agents = num_agents\n self.state_size = state_size\n self.action_size = action_size\n self.updated = 0\n\n # Actor Network (w/ Target Network)\n self.actor_local = Actor(state_size, action_size, random_seed, fc_units=(state_size * 10, action_size * 40)).to(device)\n self.actor_target = Actor(state_size, action_size, random_seed, fc_units=(state_size * 10, action_size * 40)).to(device)\n self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=LR_ACTOR)\n\n # Critic Network (w/ Target Network)\n self.critic_local = Critic(state_size, action_size, random_seed).to(device)\n self.critic_target = Critic(state_size, action_size, random_seed).to(device)\n self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=LR_CRITIC, weight_decay=WEIGHT_DECAY)\n\n # Noise process\n self.noise = OrnsteinUhlenbeckProcess(action_size)\n\n # Replay memory\n self.memory = memory or ReplayBuffer(random_seed)\n\n if random_seed is not None:\n random.seed(random_seed)\n\n def step(self, n, state, action, reward, next_state, done):\n \"\"\"Save experience in replay memory, and use random sample from buffer to learn.\"\"\"\n # Save experience / reward\n self.memory.add(state, action, reward, next_state, done)\n\n # Learn, if enough samples are available in memory\n if len(self.memory) > max(GRACE_PERIOD, BATCH_SIZE):\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA, n % UPDATE_FREQ == 0 and n > 0)\n\n def select_action(self, state, add_noise=True):\n \"\"\"Returns actions for given state as per current policy.\"\"\"\n if len(self.memory) > GRACE_PERIOD:\n self.updated += 1\n state = torch.from_numpy(state).float().to(device)\n self.actor_local.eval()\n with torch.no_grad():\n action = self.actor_local(state).cpu().data.numpy()\n self.actor_local.train()\n if add_noise:\n action += self.noise.sample()\n else:\n action = [[random.uniform(-1, 1) for _ in range(self.action_size)] for _ in range(self.num_agents)]\n return np.clip(action, -1, 1)\n\n def learn(self, experiences, gamma, update):\n \"\"\"Update policy and value parameters using given batch of experience tuples.\n Q_targets = r + γ * critic_target(next_state, actor_target(next_state))\n where:\n actor_target(state) -> action\n critic_target(state, action) -> Q-value\n\n Params\n ======\n experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples\n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n\n # ---------------------------- update critic ---------------------------- #\n # Get predicted next-state actions and Q values from target models\n actions_next = self.actor_target(next_states)\n Q_targets_next = self.critic_target(next_states, actions_next)\n # Compute Q targets for current states (y_i)\n Q_targets = rewards + (gamma * Q_targets_next * (1 - dones)).detach()\n\n # Compute critic loss\n Q_expected = self.critic_local(states, actions)\n critic_loss = F.mse_loss(Q_expected, Q_targets)\n\n # Minimize the loss\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n self.critic_optimizer.step()\n\n # ---------------------------- update actor ---------------------------- #\n # Compute actor loss\n actions_pred = self.actor_local(states)\n actor_loss = -self.critic_local(states, actions_pred).mean()\n\n # Minimize the loss\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n\n # ----------------------- update target networks ----------------------- #\n if update:\n self.soft_update(self.critic_local, self.critic_target, TAU)\n self.soft_update(self.actor_local, self.actor_target, TAU)\n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model: PyTorch model (weights will be copied from)\n target_model: PyTorch model (weights will be copied to)\n tau (float): interpolation parameter\n \"\"\"\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau * local_param.data + (1.0 - tau) * target_param.data)\n\n\nclass OrnsteinUhlenbeckProcess:\n def __init__(self, size, mu=0.0, theta=0.15, sigma=0.1, dt=1e-2, x0=None):\n self.theta = theta # time constant, 1 / tau\n self.sigma = sigma # standard deviation\n self.mu = mu # mean\n self.dt = dt # time step\n self.x0 = x0 # initial values\n self.size = size # number of samples\n self.a = theta * dt\n self.b = sigma * np.sqrt(2.0 * theta * dt)\n self.reset()\n\n def reset(self):\n self.x_prev = copy.copy(self.x0) if self.x0 is not None else np.ones(self.size) * self.mu\n\n def sample(self):\n dx = self.a * (self.mu - self.x_prev) + self.b * np.random.randn(self.size)\n self.x_prev += dx\n return self.x_prev\n","sub_path":"p2_continuous-control/mDDPG.py","file_name":"mDDPG.py","file_ext":"py","file_size_in_byte":12293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"31054163","text":"import socket\nsock = socket.socket()\n\nsock.bind((\"127.0.0.1\", 12346))\n\nsock.listen(5)\n\n#will accept only one connection at a time\nclient_sock, client_addr = sock.accept()\n\nfile=open(\"SIX.mp3\",\"rb\")\npacket=file.read(1024)\nwhile packet:\n\tclient_sock.send(packet)\n\tpacket=file.read(1024)\n\n\n\nclient_sock.close()\nsock.close()\n","sub_path":"reference_codes/normal_file_transfer/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"164723128","text":"#!/usr/bin/env python3\r\n\r\nfrom reporter.core import SqlReport, Schedule\r\nfrom reporter.emailing import RECIPIENT_GENVASC_ADMIN\r\n\r\n\r\nclass GenvascInvalidPracticeCode(SqlReport):\r\n def __init__(self):\r\n super().__init__(\r\n introduction=(\"The following practice codes are invalid \"\r\n \"in the GENVASC practice details REDCap:\"),\r\n recipients=[RECIPIENT_GENVASC_ADMIN],\r\n schedule=Schedule.daily,\r\n sql='''\r\n\r\nSELECT\r\n p.app_title AS project_name,\r\n rd.value AS practice_code\r\nFROM STG_redcap_briccsext.dbo.redcap_data rd\r\nJOIN STG_redcap_briccsext.dbo.redcap_metadata md\r\n ON md.project_id = rd.project_id\r\n AND md.field_name = rd.field_name\r\nJOIN STG_redcap_briccsext.dbo.redcap_projects p\r\n ON p.project_id = rd.project_id\r\nWHERE rd.project_id IN (29, 53)\r\n AND rd.field_name IN (\r\n 'practice_code'\r\n )\r\n AND i2b2ClinDataIntegration.dbo.isInvalidPracticeCode(rd.value) = 1\r\n\r\n '''\r\n )\r\n\r\n def get_report_line(self, row):\r\n return '- {} - {}\\r\\n'.format(\r\n row['project_name'],\r\n row['practice_code']\r\n )\r\n","sub_path":"reporter/uhl_reports/genvasc/data_quality/invalid_practice_code.py","file_name":"invalid_practice_code.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"66815708","text":"from network import SRNDeblurNet\nfrom log import TensorBoardX\nfrom utils import *\nimport train_config as config\nfrom data import *\nfrom tqdm import tqdm\nfrom time import time\nimport sys\nimport os\nfrom pytorch_ssim import ssim as ssim\nfrom VGG19 import *\n\nlog10 = np.log(10)\nMAX_DIFF = 2\n\ndef perceptualLoss(fakeIm, realIm):\n '''\n use vgg19 conv1_2, conv2_2, conv3_3 feature, before relu layer\n '''\n\n weights = [1, 0.2, 0.04]\n features_fake = vgg19(fakeIm)\n features_real = vgg19(realIm)\n features_real_no_grad = [f_real.detach() for f_real in features_real]\n\n loss = 0\n for i in range(len(features_real)):\n loss_i = mse(features_fake[i], features_real_no_grad[i])\n loss = loss + loss_i * weights[i]\n\n return loss\n\ndef compute_loss( db256 , db128 , db64 , batch ):\n assert db256.shape[0] == batch['label256'].shape[0]\n\n loss = 0\n\n # 256\n # ssim_loss1 = ssim(db256, batch['label256'] )\n mse1 = mse(db256, batch['label256'])\n perceptualLoss1=perceptualLoss(db256, batch['label256'])\n loss += mse1+0.01*perceptualLoss1\n\n # 128\n mse2 = mse(db128, batch['label128'])\n perceptualLoss2 = perceptualLoss(db128, batch['label128'])\n loss += mse2+0.01*perceptualLoss2\n\n # 64\n mse3 = mse(db64, batch['label64'])\n perceptualLoss3 = perceptualLoss(db64, batch['label64'])\n loss += mse3+0.01*perceptualLoss3\n\n #psnr\n psnr = 10*torch.log( MAX_DIFF**2 / mse1 ) / log10\n\n return {'loss':loss , 'psnr':psnr}\n\ndef backward(loss , optimizer):\n optimizer.zero_grad()\n loss['loss'].backward()\n optimizer.step()\n return\n\ndef set_learning_rate(optimizer , epoch ):\n optimizer.param_groups[0]['lr'] = config.train['learning_rate']*0.3**(epoch//500)\n\nif __name__ == \"__main__\":\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n tb = TensorBoardX(config_filename = 'train_config.py' , sub_dir = config.train['sub_dir'] )\n log_file = open('{}/{}'.format(tb.path,'train.log'),'w')\n\n train_img_list = open(config.train['train_img_list'],'r').read().strip().split('\\n')\n val_img_list = open(config.train['val_img_list'],'r').read().strip().split('\\n')\n train_dataset = Dataset( train_img_list ) \n val_dataset = TestDataset( val_img_list )\n train_dataloader = torch.utils.data.DataLoader( train_dataset , batch_size = config.train['batch_size'] , shuffle = True , drop_last = True , num_workers = 8 , pin_memory = True)\n val_dataloader = torch.utils.data.DataLoader( val_dataset , batch_size = config.train['val_batch_size'] , shuffle = True , drop_last = True , num_workers = 2 , pin_memory = True)\n\n mse = torch.nn.MSELoss().cuda()\n net = torch.nn.DataParallel( SRNDeblurNet(xavier_init_all = config.net['xavier_init_all']) ).cuda()\n vggnet = VGG19()\n vgg19 = torch.nn.DataParallel(vggnet).cuda()\n\n assert config.train['optimizer'] in ['Adam' , 'SGD']\n if config.train['optimizer'] == 'Adam':\n optimizer = torch.optim.Adam( net.parameters() , lr = config.train['learning_rate'] , weight_decay = config.loss['weight_l2_reg']) \n if config.train['optimizer'] == 'SGD':\n optimizer = torch.optim.SGD( net.parameters() , lr = config.train['learning_rate'] , weight_decay = config.loss['weight_l2_reg'] , momentum = config.train['momentum'] , nesterov = config.train['nesterov'] )\n\n last_epoch = -1 \n\n if config.train['resume'] is not None:\n last_epoch = load_model( net , config.train['resume'] , epoch = config.train['resume_epoch'] ) \n\n if config.train['resume_optimizer'] is not None:\n _ = load_optimizer( optimizer , net , config.train['resume_optimizer'] , epoch = config.train['resume_epoch'])\n assert last_epoch == _\n\n train_loss_log_list = []\n val_loss_log_list = []\n first_val = True\n\n t = time()\n\n best_val_psnr = 0\n best_net = None\n best_optimizer = None\n for epoch in tqdm(range( last_epoch + 1 , config.train['num_epochs'] ) , file = sys.stdout):\n set_learning_rate(optimizer,epoch)\n tb.add_scalar( 'lr' , optimizer.param_groups[0]['lr'] , epoch*len(train_dataloader) , 'train')\n for step , batch in tqdm(enumerate( train_dataloader ) , total= len(train_dataloader) , file=sys.stdout , desc = 'training'):\n t_list = []\n for k in batch:\n batch[k] = batch[k].cuda( non_blocking=True)\n batch[k].requires_grad = False\n db256 , db128 , db64 = net( batch['img256'] , batch['img128'] , batch['img64'] )\n loss = compute_loss( db256 , db128 , db64 , batch )\n\n\n backward(loss,optimizer)\n\n for k in loss:\n loss[k] = float(loss[k].cpu().detach().numpy())\n train_loss_log_list.append( { k:loss[k] for k in loss} )\n\n for k,v in loss.items():\n tb.add_scalar( k , v , epoch*len(train_dataloader) + step , 'train' )\n\n #validate and log\n if first_val or epoch % config.train['log_epoch'] == config.train['log_epoch'] - 1 :\n with torch.no_grad():\n first_val = False\n for step,batch in tqdm(enumerate(val_dataloader), total = len(val_dataloader) , file = sys.stdout ,desc = 'validating' ):\n for k in batch:\n batch[k] = batch[k].cuda(non_blocking = True)\n batch[k].requires_grad = False\n db256 , db128 , db64 = net( batch['img256'] , batch['img128'] , batch['img64'] )\n loss = compute_loss( db256 , db128 , db64 , batch )\n\n\n for k in loss:\n loss[k] = float(loss[k].cpu().detach().numpy())\n val_loss_log_list.append( { k:loss[k] for k in loss} )\n\n train_loss_log_dict = { k: float( np.mean( [ dic[k] for dic in train_loss_log_list] )) for k in train_loss_log_list[0] }\n val_loss_log_dict = { k: float( np.mean( [ dic[k] for dic in val_loss_log_list] )) for k in val_loss_log_list[0] }\n for k,v in val_loss_log_dict.items():\n tb.add_scalar( k , v , (epoch+1)*len(train_dataloader) , 'val' )\n\n if best_val_psnr < train_loss_log_dict['psnr']:\n best_val_psnr = train_loss_log_dict['psnr']\n save_model( net , tb.path , epoch )\n save_optimizer( optimizer , net , tb.path , epoch )\n\n train_loss_log_list.clear() \n val_loss_log_list.clear()\n\n tt = time()\n log_msg = \"\"\n log_msg += \"epoch {} , {:.2f} imgs/s\".format( epoch , ( config.train['log_epoch'] * len(train_dataloader) * config.train['batch_size'] + len( val_dataloader ) * config.train['val_batch_size'] ) / (tt - t) )\n\n log_msg += \" | train : \"\n for idx,k_v in enumerate(train_loss_log_dict.items()):\n k,v = k_v\n if k == 'acc':\n log_msg += \"{} {:.3%} {}\".format(k,v,',')\n else:\n log_msg += \"{} {:.5f} {}\".format(k,v,',')\n log_msg += \" | val : \"\n for idx,k_v in enumerate(val_loss_log_dict.items()):\n k,v = k_v\n if k == 'acc':\n log_msg += \"{} {:.3%} {}\".format(k,v,',')\n else:\n log_msg += \"{} {:.5f} {}\".format(k,v,',' if idx < len(val_loss_log_list) - 1 else '')\n tqdm.write( log_msg , file = sys.stdout )\n sys.stdout.flush()\n log_file.write(log_msg+'\\n')\n log_file.flush()\n t = time()\n\n # plt.plot(train_loss, color='b')\n # plt.plot(val_loss, color='r')\n # plt.savefig('loss.jpg')","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"383761844","text":"from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\n\nfrom ..util import (\n number_to_hex,\n hex_to_number,\n b32_encode,\n b32_decode,\n pack,\n unpack,\n InvalidChecksum,\n)\n\nUser = settings.AUTH_USER_MODEL\n\n\nclass CommandCode(object):\n START_CLERK = 1\n END_CLERK = 3\n\n @classmethod\n def encode_code(cls, command, payload):\n \"\"\"\n Encode a 72-bit command code.\n\n Format of the code:\n command: 4 bits\n payload: 46 bits\n zeros: 18 bits\n checksum: 4 bits\n -------------------\n total: 40 bits\n\n :param command: Command to encode\n :type command: int\n\n :param payload: Payload data\n :type payload: int\n\n :return: Encoded command code\n :rtype: str\n\n :raise OverflowError: If the command or payload is too large.\n\n >>> CommandCode.encode_code(\n ... CommandCode.END_CLERK,\n ... 123456789,\n ... )\n 'AAAEARPT2YAQAMA'\n\n \"\"\"\n return b32_encode(\n pack([\n ( 4, command),\n (46, payload),\n (18, 0),\n ], checksum_bits=4),\n length=9\n )\n\n @classmethod\n def parse_code(cls, data):\n \"\"\"\n Parse a 72-bit command code.\n\n :param data: Command string\n :type data: str\n :return: Command and payload\n :rtype: (int, int)\n\n :raise ValueError: If the data is not valid.\n :raise InvalidChecksum: If the checksum does not match.\n\n >>> CommandCode.parse_code('AAAEARPT2YAQAMA') == (3, 123456789)\n True\n >>> CommandCode.parse_code('7QBUARPT2YAQAMA')\n Traceback (most recent call last):\n ...\n ValueError: not a CommandCode\n >>> CommandCode.parse_code('0')\n Traceback (most recent call last):\n ...\n ValueError: not a CommandCode\n >>> CommandCode.parse_code('AAAEARPT2YARAMA')\n Traceback (most recent call last):\n ...\n InvalidChecksum\n\n \"\"\"\n try:\n command, payload, zeros = unpack(\n b32_decode(data, length=9),\n [4, 46, 18],\n checksum_bits=4,\n )\n except TypeError:\n raise ValueError('not a CommandCode')\n\n if zeros != 0:\n raise ValueError('not a CommandCode')\n\n return int(command), payload\n\n\nclass Clerk(models.Model):\n user = models.ForeignKey(User)\n\n def __unicode__(self):\n return u''.format(unicode(self.user))\n\n def get_code(self):\n return number_to_hex(self.id, 36)\n\n @classmethod\n def by_hex_code(cls, hex_code):\n \"\"\"\n Return the Clerk instance with the given hex code.\n\n :param code: Hex code to look for\n :type code: str\n :return: The corresponding Clerk\n :rtype: Clerk | None\n \"\"\"\n return cls.objects.get(id=hex_to_number(hex_code))\n\n\nclass Vendor(models.Model):\n user = models.ForeignKey(User)\n\n def __unicode__(self):\n return u''.format(unicode(self.user))\n\n\nclass Item(models.Model):\n ADVERTISED = \"AD\"\n BROUGHT = \"BR\"\n STAGED = \"ST\"\n SOLD = \"SO\"\n MISSING = \"MI\"\n RETURNED = \"RE\"\n COMPENSATED = \"CO\"\n\n STATE = (\n (ADVERTISED, _(u\"Advertised\")),\n (BROUGHT, _(u\"Brought to event\")),\n (STAGED, _(u\"Staged for selling\")),\n (SOLD, _(u\"Sold\")),\n (MISSING, _(u\"Missing\")),\n (RETURNED, _(u\"Returned to vendor\")),\n (COMPENSATED, _(u\"Compensated to vendor\")),\n )\n\n code = models.CharField(\n max_length=16,\n blank=True,\n null=False,\n db_index=True,\n help_text=_(u\"Barcode content of the product\"),\n )\n name = models.CharField(max_length=256)\n # FIXME: prevent negative prices\n price = models.DecimalField(max_digits=8, decimal_places=2)\n vendor = models.ForeignKey(Vendor)\n state = models.CharField(\n choices=STATE,\n max_length=8,\n default=ADVERTISED\n )\n\n def __unicode__(self):\n return self.name\n\n @classmethod\n def new(cls, *args, **kwargs):\n \"\"\"\n Construct new Item and generate its barcode.\n\n :param args: Item Constructor arguments\n :param kwargs: Item Constructor arguments\n :return: New stored Item object with calculated code.\n :rtype: Item\n \"\"\"\n obj = cls(*args, **kwargs)\n obj.save()\n\n obj.code = obj.gen_barcode()\n obj.save(update_fields=[\"code\"])\n return obj\n\n def gen_barcode(self):\n \"\"\"\n Generate and return barcode data for the Item.\n\n Format of the code:\n vendor id: 12 bits\n item id: 24 bits\n checksum: 4 bits\n -------------------\n total: 40 bits\n\n :return: Barcode data.\n :rtype str\n \"\"\"\n return b32_encode(\n pack([\n (12, self.vendor.id),\n (24, self.pk),\n ], checksum_bits=4)\n )\n\n @staticmethod\n def parse_barcode(data):\n \"\"\"\n Parse barcode data into vendor id and item id.\n\n :param data: Barcode data scanned from product\n :type data: str\n :return: Vendor id and item id\n :rtype: (int, int)\n :raise InvalidChecksum: If the checksum does not match the data.\n \"\"\"\n return unpack(\n b32_decode(data),\n [12, 24],\n checksum_bits=4,\n )\n\n @staticmethod\n def get_item_by_barcode(data):\n \"\"\"\n Get Item by barcode. If code check fails, returns None.\n\n :param data: Barcode data scanned from product\n :type data: str\n\n :rtype: Item | None\n :raise Item.DoesNotExist: If no Item matches the code.\n \"\"\"\n try:\n vendor_id, _ = Item.parse_barcode(data)\n except InvalidChecksum:\n return None\n return Item.objects.get(code=data, vendor__id=vendor_id)\n\n\nclass ReceiptItem(models.Model):\n ADD = \"ADD\"\n REMOVE = \"DEL\"\n\n ACTION = (\n (ADD, _(u\"Added to receipt\")),\n (REMOVE, _(u\"Removed from receipt\")),\n )\n\n item = models.ForeignKey(Item)\n receipt = models.ForeignKey(\"Receipt\")\n action = models.CharField(choices=ACTION, max_length=16, default=ADD)\n\n\nclass Receipt(models.Model):\n PENDING = \"PEND\"\n FINISHED = \"FINI\"\n\n STATUS = (\n (PENDING, _(u\"Not finished\")),\n (FINISHED, _(u\"Finished\")),\n )\n\n items = models.ManyToManyField(Item, through=ReceiptItem)\n status = models.CharField(choices=STATUS, max_length=16)\n total = models.DecimalField(max_digits=8, decimal_places=2)\n clerk = models.ForeignKey(Clerk)\n sell_time = models.DateTimeField(null=True)\n","sub_path":"kirppu/app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"637862975","text":"\"\"\"\n1.变量 = 值(声明变量)\n\nname = \"李毅\"\nnum1 = num2 = num3\nnum11 , num12 = 10,30\n\n\"\"\"\n# summation = 0\n# num = 1\n# while num <= 100:\n# if (num % 3 == 0 or num % 7 == 0) and num % 21 != 0:\n# summation += 1\n# num += 1\n# print(summation)\n# num = int(input(\"斐波那契数列中第n个数的值:\"))\n# n1 = 1\n# n2 = 1\n# index = 2\n# num1 = 0\n# if not (not (num == 1) and not (num == 2)):\n# print(1)\n# while index < num:\n# num1= n1 + n2\n# n1 = n2\n# n2 = num1\n# index += 1\n# print(num1)\n# sum = 0\n# # for num in range(101,201):\n# # for i in range(2,num):\n# # if num % i == 0:\n# # break\n# # else:\n# # sum+=1\n# # print(num)\n# # print(sum)\n\nnum = 100\nwhile num<999:\n a = num // 100\n b = num // 10 % 10\n c = num % 10\n if num == a**3+b**3+c**3:\n print(num)\n num+=1\n","sub_path":"Python1808/第一阶段/day6-列表/01-recode.py","file_name":"01-recode.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"635863802","text":"# coding=utf-8\n\"\"\"Sphinx documentation generator configuration file.\n\nThe full set of configuration options is listed on the Sphinx website:\nhttp://sphinx-doc.org/config.html\n\"\"\"\nimport os\nimport sys\n\n\n# Add the Movie Recommender root directory to the system path. This allows\n# references such as :mod:`movie_recommender.…` to be processed correctly.\nROOT_DIR = os.path.abspath(os.path.join(\n os.path.dirname(__file__),\n os.path.pardir\n))\nsys.path.insert(0, ROOT_DIR)\n\n\ndef _get_version():\n \"\"\"Return the stripped contents of the version file.\n\n We could parse this version string with packaging.version.Version if we\n wished to verify that the version string in the VERSION file was valid.\n (The act of generating documentation would serve as a unit test for the\n contents of the version file.)\n \"\"\"\n with open(os.path.join(ROOT_DIR, 'VERSION')) as handle:\n return handle.read().strip()\n\n\n# Project Information ---------------------------------------------------------\n# pylint:disable=invalid-name\nauthor = 'Jeremy Audet'\ncopyright = '2018, Jeremy Audet' # pylint:disable=redefined-builtin\nproject = 'Movie Recommender'\nversion = release = _get_version()\n\n\n# General Configuration -------------------------------------------------------\nextensions = ['sphinx.ext.autodoc']\nsource_suffix = '.rst'\nmaster_doc = 'index'\nexclude_patterns = ['_build']\nnitpicky = True\nautodoc_default_flags = ['members']\n# Format-Specific Options -----------------------------------------------------\nhtmlhelp_basename = 'MovieRecommenderdoc'\nlatex_documents = [(\n master_doc,\n project + '.tex',\n project + ' Documentation',\n author,\n 'manual',\n)]\nman_pages = [(\n master_doc,\n 'movie-recommender',\n project + ' Documentation',\n [author],\n 1, # man pages section\n)]\ntexinfo_documents = [(\n master_doc,\n 'MovieRecommender',\n project + ' Documentation',\n author,\n 'MovieRecommender',\n ('Movie Recommender is an application for generating movie '\n 'recommendations.'),\n 'Miscellaneous'\n)]\n","sub_path":"python/movie-recommender/docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"125539981","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCalculate the cross section for Sigma+ (anti-Sigma+).\nAlso plot the xp dependence.\n\"\"\"\n\nimport numpy as np\nimport ROOT\nfrom array import array \n\nROOT.gROOT.Macro(\"~/.rootmac/rootlogon.C\")\n\ndata_b = np.loadtxt('../massfit/fitResultsSigmaPlus.txt')\n\nxp_min_b = data_b[:,0]\nxp_max_b = data_b[:,1]\ny_b = data_b[:,2]\ndy_b = data_b[:,3]\n\nxp_c_b = 0.5*(xp_max_b+xp_min_b)\ndxp_b = 0.5*(xp_max_b-xp_min_b)\n\nx = array(\"d\",xp_c_b)\ny = array(\"d\",y_b)\ndx = array(\"d\",dxp_b)\ndy = array(\"d\",dy_b)\n\n\nh = ROOT.TH2D(\"h200\",\"\",100,0,1,100,0,15000)\ng = ROOT.TGraphErrors(len(x),x,y,dx,dy)\ng.SetMarkerStyle(2)\ng.SetMarkerColor(2)\n\n\ndata_ab = np.loadtxt('../massfit/fitResultsAntiSigmaPlus.txt')\n\nxp_min_ab = data_ab[:,0]\nxp_max_ab = data_ab[:,1]\ny_ab = data_ab[:,2]\ndy_ab = data_ab[:,3]\n\nxp_c_ab = 0.5*(xp_max_ab+xp_min_ab)\ndxp_ab = 0.5*(xp_max_ab-xp_min_ab)\n\nx1 = array(\"d\",xp_c_ab)\ny1 = array(\"d\",y_ab)\ndx1 = array(\"d\",dxp_ab)\ndy1 = array(\"d\",dy_ab)\n\ng1 = ROOT.TGraphErrors(len(x1),x1,y1,dx1,dy1)\ng1.SetMarkerStyle(4)\ng1.SetMarkerColor(4)\n\nh.Draw()\ng.Draw(\"*\")\ng1.Draw(\"*\")\n\n\n\n","sub_path":"analysis/cross_section/raw_yield.py","file_name":"raw_yield.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"249540219","text":"# -*- codeing = utf-8 -*-\n# @Time : 2021/10/11 21:16\n# @Author :\n# @File : word.py\n# @Software : PyCharm\nfrom pyecharts import options as opts\nfrom pyecharts.charts import WordCloud\n\n\nwords = [\n (\"知乎\", \"46\"),\n (\"B站\", \"94\"),\n (\"CSDN\", \"78\"),\n (\"博客园\", \"12\"),\n (\"百度\", \"150\"),\n (\"GitHub\", \"53\"),\n (\"菜鸟\", \"13\"),\n (\"中国大学MOOC\", \"22\"),\n (\"焦糖\", \"27\"),\n (\"模板之家\", \"16\"),\n (\"豆瓣\", \"33\"),\n (\"天猫\", \"5\"),\n (\"微博\", \"7\"),\n]\n\nc = (\n WordCloud()\n .add(\n \"\",\n words,\n word_size_range=[20, 100],\n textstyle_opts=opts.TextStyleOpts(font_family=\"cursive\"),\n )\n .set_global_opts(title_opts=opts.TitleOpts(title=\"WordCloud-My_Web\"))\n .render(\"wordcloud2.html\")\n)","sub_path":"word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"29901152","text":"import unittest\nfrom teste_1016 import calcular_tempo\nimport os\n\n\n\nclass TesteDistanciaCarros(unittest.TestCase):\n def setUp(self):\n self.entradas = {\n 'entrada1': 30,\n 'entrada2': 110,\n 'entrada3': 7\n }\n self.respostas = {\n 'entrada1': f'{60} minutos',\n 'entrada2': f'{220} minutos',\n 'entrada3': f'{14} minutos' \n }\n\n def test_calcular_tempo(self):\n for entrada in self.entradas.keys():\n with self.subTest(entrada=entrada):\n self.assertEqual(calcular_tempo(self.entradas[entrada]), self.respostas[entrada])\n\n @unittest.skip('')\n def test_input_output(self):\n for entrada in self.entradas.keys():\n with self.subTest(entrada=entrada):\n with open('input1016', 'w') as input1016:\n input1016.write(f'{self.entradas[entrada]}')\n os.system('python3 teste_1016.py < input1016 > output1016')\n with open('output1016', 'r') as output1016:\n output = output1016.read()\n self.assertEqual(output, f'{self.respostas[entrada]}\\n')\n \n\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/teste1016_test.py","file_name":"teste1016_test.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"552719871","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom datetime import datetime, date\nfrom django.contrib.auth.decorators import login_required\nimport re\nfrom urllib.request import urlopen\nfrom .forms import HandleForm\nfrom django.views.generic import TemplateView\nimport requests\nfrom bs4 import BeautifulSoup\nfrom . import fusioncharts\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom .models import *\nfrom collections import OrderedDict\nimport mpld3\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\ndef home(request):\n return render(request, 'home.html', {})\n\ndef contact(request):\n return render(request, 'contact.html', {})\n\ndef cfhandle(request):\n if request.method == 'POST':\n form = HandleForm(request.POST)\n if form.is_valid():\n handle = form.cleaned_data.get('handle')\n return redirect('/cfhandle/' + handle)\n else:\n form = HandleForm()\n\n return render(request, 'searchhandle.html', {'form': form})\n\ndef time_table(request):\n \n return render(request, 'time_table.html', {})\n\ndef code_forces(request):\n url=\"https://codeforces.com/contests\"\n page=requests.get(url)\n bs=BeautifulSoup(page.content, 'html.parser')\n\n tables=bs.find_all('table', class_=\"\")\n dic=[]\n\n sec=tables[0].find_all('tr')\n for item in sec:\n secx=item.find_all('td')\n secx=[x.text.strip() for x in secx]\n\n if len(secx)>0:\n if secx[1] == '':\n secx[1] = \"Not Mentioned\"\n dic.append(secx)\n\n\n return render(request, 'cf.html', {'dic':dic})\n\ndef code_chef(request):\n url=\"https://www.codechef.com/contests\"\n page=requests.get(url)\n bs=BeautifulSoup(page.content, 'html.parser')\n tables=bs.find_all('table', class_=\"dataTable\")\n \n dic1=[]\n dic2=[]\n \n sec=tables[0].find_all('tr')\n for item in sec:\n secx=item.find_all('td')\n secx=[x.text.strip() for x in secx]\n\n if len(secx)>0:\n dic1.append(secx)\n\n sec=tables[1].find_all('tr')\n for item in sec:\n secx=item.find_all('td')\n secx=[x.text.strip() for x in secx]\n\n if len(secx)>0:\n dic2.append(secx)\n \n return render(request, 'cchef.html', {'dic1':dic1,'dic2':dic2})\n\ndef who(request, handle):\n context = {\n 'handle': handle,\n }\n start_url = \"https://www.codeforces.com/\"\n print(handle)\n cf_handle = handle\n contests_url = start_url + 'profile/' + cf_handle\n print(contests_url)\n page = requests.get(contests_url)\n soup = BeautifulSoup(page.content, 'lxml')\n\n title = soup.find('title').text\n print(title)\n if title == 'Codeforces':\n form = HandleForm()\n return render(request, 'searchhandle.html', {'form': form, 'error': 'invalid handle case sensitive'})\n\n\n\n return render(request, 'options.html', context)\n\n\n# def submission(request, handle):\n# friend = handle\n# p_link = \"https://codeforces.com/api/user.status?handle=\"\n# r = requests.get(p_link + friend)\n# data = r.json()\n# accepted = 0\n# wrong_answer = 0\n# time_exceed = 0\n# runtime_error = 0\n# hacked = 0\n# compilation_error = 0\n# submissions = {}\n# today = date.today()\n# for rows in data['result']:\n# time = rows['creationTimeSeconds']\n# s_day = datetime.fromtimestamp(time).date()\n# days = (today - s_day).days\n# week = days // 7\n# day = days % 7 + 1\n# if week <= 3:\n# if submissions.get(week) is None:\n# submissions[week] = {day: 1}\n# else:\n# dic = submissions[week]\n# if dic.get(day) is None:\n# dic[day] = 1\n# else:\n# dic[day] += 1\n# if rows.get('verdict') is not None:\n# verdict = rows['verdict']\n# if verdict == \"OK\":\n# accepted += 1\n# elif verdict == \"HACKED\":\n# hacked += 1\n# elif verdict == \"WRONG_ANSWER\":\n# wrong_answer += 1\n# elif verdict == \"TIME_LIMIT_EXCEEDED\":\n# time_exceed += 1\n# elif verdict == \"RUNTIME_ERROR\":\n# runtime_error += 1\n# else:\n# compilation_error += 1\n#\n# for key in submissions:\n# dic = submissions[key]\n# for i in range(1, 8):\n# if dic.get(i) is None:\n# dic[i] = 0\n#\n# context = {\n# 'handle': handle,\n# 'accepted': accepted,\n# 'hacked': hacked,\n# 'runtime_error': runtime_error,\n# 'wrong_answer': wrong_answer,\n# 'time_exceed': time_exceed,\n# 'compilation_error': compilation_error,\n# }\n# for key in submissions:\n# dic = submissions[key]\n# for i in range(1, 8):\n# context['day' + str(key) + str(i)] = dic[i]\n# print(context)\n# return render(request, \"sub_stats.html\", context)\n\n\n# def contest(request, handle):\n# page_url = \"https://codeforces.com/api/user.rating?handle=\" + handle\n# r = requests.get(page_url)\n# data = r.json()\n# contests = []\n# ranks = []\n# for i in data['result']\n# contests.append(i['contestId'])\n# ranks.append(i['rank'])\n# context = {\n# 'handle': handle,\n# 'contests': contests,\n# 'ranks': ranks,\n# }\n#\n# return render(request, \"contest_stats.html\", context)\n#\n\n\ndef contest(request,handle):\n\n fcs = fetch_contest_stats(handle)\n chart = {\"output_languages\" : display_stats_languages(handle).render(),\n \"output_verdicts\" : display_stats_verdicts(handle).render(),\n \"output_levels\" : display_stats_levels(handle).render(),\n }\n fcs.update(chart)\n\n return render(request, 'contest_stats.html', fcs)\n\n fcs = fetch_contest_stats(handle)\n submissionsFigure(request)\n\n return render(request, 'figure_html.html', fcs)\n\ndef fetch_contest_stats(handle):\n start_url = \"https://www.codeforces.com/\"\n\n cf_handle = handle\n contests_url = start_url+'contests/with/'+cf_handle\n\n page = requests.get(contests_url)\n soup = BeautifulSoup(page.content, 'lxml')\n\n\n table = soup.find('table', class_='tablesorter user-contests-table')\n tbody = table.find('tbody')\n\n ROWS = tbody.find_all('tr')\n\n delta_rating = []\n rank_list = []\n\n for item in ROWS:\n elements = item.find_all('td')\n rank = int(elements[2].find('a').text)\n rating_change = int(elements[4].text)\n\n delta_rating.append(rating_change)\n rank_list.append(rank)\n\n delta_rating.sort()\n rank_list.sort()\n\n mydict = {\n 'Handle' : cf_handle,\n 'No_of_Contests' : ROWS[0].find('td').text,\n 'Best_Rank' : rank_list[0],\n 'Worst_Rank' : rank_list[len(rank_list)-1],\n 'Max_Up' : delta_rating[len(delta_rating)-1],\n 'Max_Down' : delta_rating[0],\n }\n\n return mydict\n\ndef search_handle(request):\n if request.method == \"POST\":\n form = HandleForm(request.POST)\n\n\n if form.is_valid():\n handle = form.cleaned_data[\"cf_handle\"]\n # print(handle)\n\n fcs = fetch_contest_stats(handle)\n chart = {\"output_languages\" : display_stats_languages(handle).render(),\n \"output_verdicts\" : display_stats_verdicts(handle).render(),\n \"output_levels\" : display_stats_levels(handle).render(),\n }\n\n fcs.update(chart)\n\n return render(request, 'login/contest_stats.html', fcs)\n\n else :\n form = HandleForm()\n\n form = HandleForm()\n\n return render(request, 'login/search.html', {\"form\":form})\n\ndef get_submission_stats(handle):\n languages.objects.all().delete()\n verdicts.objects.all().delete()\n levels.objects.all().delete()\n\n page = requests.get(\"https://codeforces.com/submissions/\" + handle)\n\n soup = BeautifulSoup(page.content, 'lxml')\n div = soup.find_all('div', class_='pagination')\n\n if len(div) == 1:\n t=1\n\n else:\n ul = div[1].find('ul')\n li = ul.find_all('li')\n\n t = int(li[-2].text)\n\n\n val = pd.Series()\n verd = pd.Series()\n lev = pd.Series()\n\n for i in range(t):\n p = pd.read_html(\"https://codeforces.com/submissions/\" + handle + \"/page/\" + str(i+1))\n table = p[5]\n\n val = val.combine(table['Lang'].value_counts(),(lambda x1, x2 : x1+x2), fill_value=0)\n verd = verd.combine(table['Verdict'].value_counts(),(lambda x1, x2 : x1+x2), fill_value=0)\n lev = lev.combine(table['Problem'].value_counts(),(lambda x1, x2 : x1+x2), fill_value=0)\n\n labels_lang = val._index\n labels_verd = verd._index\n labels_lev = lev._index\n\n\n for l in labels_lang:\n a = languages.objects.update_or_create(name = l, val = val[l])[0]\n a.save()\n\n for l in labels_verd:\n a = verdicts.objects.update_or_create(name = l, val = verd[l])[0]\n a.save()\n\n for l in labels_lev:\n a = levels.objects.update_or_create(name = l, val = lev[l])[0]\n a.save()\n\n\ndef display_stats_languages(handle):\n get_submission_stats(handle)\n\n chartConfig = OrderedDict()\n chartConfig[\"caption\"] = \"Languages of \" + handle\n chartConfig[\"xAxisName\"] = \"Languages\"\n chartConfig[\"xAxisName\"] = \"Submissions\"\n chartConfig[\"theme\"] = \"fusion\"\n chartConfig[\"animation\"] = \"\"\n\n datasource = OrderedDict()\n datasource[\"Chart\"] = chartConfig\n datasource[\"data\"] = []\n # print(languages.objects.all())\n for l in languages.objects.all():\n datasource[\"data\"].append({\"label\": l.name, \"value\": str(l.val)})\n\n graph2D = fusioncharts.FusionCharts(\"pie2d\", \"Languages Chart\", \"600\", \"400\", \"languages_chart\", \"json\", datasource)\n\n return graph2D\n\ndef display_stats_verdicts(handle):\n\n chartConfig = OrderedDict()\n chartConfig[\"caption\"] = \"Verdicts of \" + handle\n chartConfig[\"xAxisName\"] = \"Verdicts\"\n chartConfig[\"xAxisName\"] = \"Submissions\"\n chartConfig[\"theme\"] = \"fusion\"\n chartConfig[\"animation\"] = \"\"\n\n datasource = OrderedDict()\n datasource[\"Chart\"] = chartConfig\n datasource[\"data\"] = []\n\n WA = 0\n AC = 0\n RTE = 0\n MLE = 0\n CE = 0\n TLE = 0\n\n for l in verdicts.objects.all():\n item = l.name\n if item[:5] == \"Wrong\":\n WA += l.val\n\n elif item[:5] == \"Time\":\n TLE += l.val\n\n elif item == \"Accepted\":\n AC += l.val\n\n elif item[:6] == \"Memory\":\n MLE += l.val\n\n elif item[:11] == \"Compilation\":\n CE += l.val\n\n elif item[:7] == \"Runtime\":\n RTE += l.val\n\n datasource[\"data\"].append({\"label\": \"Accepted\", \"value\": AC})\n datasource[\"data\"].append({\"label\": \"Wrong Answer\", \"value\": WA})\n datasource[\"data\"].append({\"label\": \"Runtime Error\", \"value\": RTE})\n datasource[\"data\"].append({\"label\": \"Memory Limit Exceeded\", \"value\": MLE})\n datasource[\"data\"].append({\"label\": \"Compilation Error\", \"value\": CE})\n datasource[\"data\"].append({\"label\": \"Time Limit Exceeded\", \"value\": TLE})\n\n graph2D = fusioncharts.FusionCharts(\"pie2d\", \"Verdicts Chart\", \"700\", \"500\", \"verdicts_chart\", \"json\", datasource)\n\n return graph2D\n\ndef display_stats_levels(handle):\n\n chartConfig = OrderedDict()\n chartConfig[\"caption\"] = \"Levels of \" + handle\n chartConfig[\"xAxisName\"] = \"Levels\"\n chartConfig[\"xAxisName\"] = \"Submissions\"\n chartConfig[\"theme\"] = \"fusion\"\n chartConfig[\"animation\"] = \"\"\n\n datasource = OrderedDict()\n datasource[\"Chart\"] = chartConfig\n datasource[\"data\"] = []\n\n A = 0\n B = 0\n C = 0\n D = 0\n E = 0\n R = 0\n\n for l in levels.objects.all():\n item = l.name\n if item[0] == \"A\":\n A += l.val\n\n elif item[0] == \"B\":\n B += l.val\n\n elif item[0] == \"C\":\n C += l.val\n\n elif item[0] == \"D\":\n D += l.val\n\n elif item[0] == \"E\":\n E += l.val\n\n else:\n R += l.val\n\n datasource[\"data\"].append({\"label\": \"A\", \"value\": A})\n datasource[\"data\"].append({\"label\": \"B\", \"value\": B})\n datasource[\"data\"].append({\"label\": \"C\", \"value\": C})\n datasource[\"data\"].append({\"label\": \"D\", \"value\": D})\n datasource[\"data\"].append({\"label\": \"E\", \"value\": E})\n datasource[\"data\"].append({\"label\": \"R\", \"value\": R})\n\n\n graph2D = fusioncharts.FusionCharts(\"column2d\", \"Levels Chart\", \"700\", \"500\", \"levels_chart\", \"json\", datasource)\n\n return graph2D\n\ndef iitg(request):\n url1 = \"https://codeforces.com/ratings/organization/297\"\n page1 = requests.get(url1)\n soup1 = BeautifulSoup(page1.content, 'lxml')\n div1 = soup1.find_all('div', class_='pagination')\n\n if len(div1) == 1:\n t = 1\n else:\n ul = div1[1].find('ul')\n li = ul.find_all('li')\n\n t = int(li[-2].text)\n\n dic = []\n for i in range(t + 1):\n url = \"https://codeforces.com/ratings/organization/297/page/\" + str(i+1)\n # print(url)\n page = requests.get(url)\n bs = BeautifulSoup(page.content, 'lxml')\n div = bs.find_all('div',class_='datatable ratingsDatatable')\n # print(div)\n tables = div[0].find_all('table')\n\n sec=tables[0].find_all('tr')\n for item in sec:\n secx = item.find_all('td')\n\n if len(secx) == 0:\n continue\n list = []\n stri = secx[0].text.strip()\n r = 0\n for e in stri:\n if e =='(':\n break\n if e>='0' and e<='9':\n r = r*10 + int(e)\n if r==0:\n continue\n list.append(r)\n list.append(secx[1].text.strip())\n list.append(sec[1].find_all('a')[0]['class'][1])\n list.append(secx[2].text.strip())\n list.append(secx[3].text.strip())\n dic.append(list)\n print(dic)\n return render(request, 'iitg.html', {'dic':dic})\n\ndef allchat(request):\n alluser = User.objects.all()\n return render(request, 'allchat.html', {'alluser': alluser})\n\ndef chatroom(request, userid1, userid2):\n userid1 = int(userid1)\n userid2 = int(userid2)\n\n if userid1 > userid2:\n userid1,userid2 = userid2,userid1\n print(userid1,userid2)\n\n user1_ = User.objects.get(pk=userid1)\n user2_ = User.objects.get(pk=userid2)\n\n print(user1_, user2_)\n\n try:\n chatroom = Chatroom.objects.get(user1=user1_, user2=user2_)\n except Chatroom.DoesNotExist:\n chatroom = Chatroom.objects.create(user1=user1_, user2=user2_)\n chatroom.save()\n\n\n messages = Chatmessage.objects.filter(chatroom=chatroom)\n print(chatroom)\n print(messages)\n # return render(request, 'home.html', {})\n return render(request, 'chat.html', {'chatroom':chatroom, 'messages':messages})\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"356780119","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 24 16:39:10 2018\n\n@author: Tanay Dwivedi\n\"\"\"\nimport cv2\nimport time\n\n# global constants\npartition_x = 3\npartition_y = 3\nimage_size = 448\n\n# Video Stream\ncap = cv2.VideoCapture('dataset/video5.mp4')\n\n# Image folder\nimage_folder = 'images'\n\n# Time interval\nt_interval = 0.3\n\n# Computer Local Time\nstart_time = time.localtime();\nstart_time = time.mktime(start_time)\n\n# Setting a temprorary variable as current time\nstart_time_2 = start_time\nstart_time = start_time + t_interval\n\n# Index of images\ni = 1\n\n# Function to crop image\nprint(start_time)\n\ndef crop_image(image):\n width, height, col = image.shape\n w_x = (width - image_size) / partition_x\n h_y = (height - image_size) / partition_y\n x_begin = 0\n y_begin = 0\n for j in range(1,partition_x+1):\n for k in range(1,partition_y+1):\n img_crop = image[x_begin:x_begin+image_size , y_begin:y_begin+image_size]\n cv2.imwrite(image_folder + '/' + str(i) + '_' + str(j) + '_' + str(k) + '.jpg',img_crop)\n y_begin = y_begin + h_y\n x_begin = x_begin + w_x\n y_begin = 0\n\nwhile True:\n ret, frame = cap.read()\n cv2.imshow('frame',frame)\n \n start_time = time.localtime();\n start_time = time.mktime(start_time)\n \n if start_time > start_time_2:\n # cv2.imwrite('images/'+ str(i) +'.jpg',frame)\n crop_image(frame)\n start_time_2 = start_time_2 + t_interval\n i = i + 1\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"src/obj_detect/scripts/click_per_second.py","file_name":"click_per_second.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"379078723","text":"from sklearn.linear_model import LinearRegression, LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom xgboost import XGBClassifier\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport xgboost as xgb\n\nfrom santander_classifier.utils import binarize\n\n\nclass PredictionModel(object):\n def __init__(self, x_train, x_test, y_train, y_test=None):\n self.x_train = x_train\n self.x_test = x_test\n self.y_train = y_train\n self.y_test = y_test\n self.random_state = 1\n\n def baseline(self):\n return np.zeros_like(self.y_train), np.zeros_like(self.y_test)\n\n def ord_least_squares(self):\n model = LinearRegression(fit_intercept=True, normalize=True)\n model = model.fit(self.x_train, self.y_train)\n\n return (model.predict(self.x_train), model.predict(self.x_test))\n\n def log_regr(self):\n model = LogisticRegression(\n penalty='l2',\n tol=0.0001,\n C=0.2,\n random_state=self.random_state,\n multi_class='multinomial',\n solver='newton-cg'\n )\n model = model.fit(self.x_train, self.y_train)\n\n return map(lambda x: model.predict_proba(x)[:, 1],\n (self.x_train, self.x_test))\n\n def decision_tree(self):\n model = DecisionTreeClassifier(\n criterion='entropy',\n max_depth=25, min_samples_split=50,\n random_state=self.random_state\n )\n\n model = model.fit(self.x_train, self.y_train)\n\n return map(lambda x: model.predict_proba(x)[:, 1],\n (self.x_train, self.x_test))\n\n def random_forest(self):\n model = RandomForestClassifier(\n n_estimators=25, criterion='entropy', max_depth=20,\n min_samples_split=100, max_features='auto',\n bootstrap=True, random_state=self.random_state\n )\n\n model = model.fit(self.x_train, self.y_train)\n\n return map(lambda x: model.predict_proba(x)[:, 1],\n (self.x_train, self.x_test))\n\n def xgboost(self):\n gen_params = {'booster': 'gbtree', 'verbosity': 2, 'thread': 8}\n tree_params = {'eta': 0.2, 'gamma': 0, 'max_depth': 6, 'min_child_weight': 300}\n learn_params = {'objective': 'binary:logistic', 'base_score': 0.5,\n 'eval_metric': 'auc', 'seed': self.random_state,\n 'lambda': 1, 'alpha': 0, # weight regulirazation\n 'scale_pos_weight': 0.9 / 0.1, 'max_delta_step': 0 # imbalanced\n }\n params = {}\n params.update(gen_params)\n params.update(tree_params)\n params.update(learn_params)\n num_round = 150\n\n dtrain = xgb.DMatrix(self.x_train, label=self.y_train)\n dtest = xgb.DMatrix(self.x_test, label=self.y_test)\n watchlist = [(dtest, 'eval'), (dtrain, 'train')]\n xgb_model = xgb.train(params, dtrain, num_round,\n evals=watchlist, verbose_eval=10)\n xgb_model.save_model('../models/xgb_classifier.model')\n\n return map(lambda x: xgb_model.predict(x),\n (dtrain, dtest))\n\n def xgboost_classifier(self):\n # fit model no training data\n model = XGBClassifier()\n eval_set = [(self.x_test, self.y_test)]\n model.fit(self.x_train, self.y_train, eval_metric=\"auc\",\n eval_set=eval_set, verbose=True)\n return map(lambda x: model.predict_proba(x)[:, 1],\n (self.x_train, self.x_test))\n\n def linear_svm(self):\n model = SVC(C=1.0, kernel='linear', probability=False, tol=0.001,\n random_state=self.random_state)\n model = model.fit(self.x_train, self.y_train)\n\n return map(lambda x: model.predict(x),\n (self.x_train, self.x_test))\n\n def rbf_svm(self):\n model = SVC(C=1.0, kernel='rbf', probability=True, tol=0.001,\n random_state=self.random_state)\n model = model.fit(self.x_train, self.y_train)\n\n return map(lambda x: model.predict(x),\n (self.x_train, self.x_test))\n\n def mlp(self):\n pass\n\n\ndef find_cutoff(y_prob, y, vis=True):\n '''Finds decision boundary that maximizes f1 score.'''\n cutoffs = np.arange(0.1, 0.9, 0.05)\n scores = np.zeros_like(cutoffs)\n\n for i in range(len(scores)):\n scores[i] = roc_auc_score(y, binarize(y_prob, cutoffs[i]))\n\n cutoff = cutoffs[np.argmax(scores)]\n\n if vis:\n fig, ax = plt.subplots()\n ax.plot(cutoffs, scores, '-o', ms=20, lw=2, alpha=0.7, mfc='orange')\n ax.grid()\n ax.set_title(\"ROC AUC vs cutoff value\")\n plt.show()\n print (\"Best cutoff value is \" + str(cutoff))\n\n return cutoff\n\n\ndef train_predict(model_name, data, cutoff=None, prob=True, verbose=True):\n '''Fits model on train data and returns predictions.\n\n Args:\n model_name: string name of model\n data: tuple of 2d numpy arrays x_train, x_test, y_train, y_test\n verbose: if True prints cutoff value\n\n Returns:\n y_pred_test: 1D numpy array, binary prediction on test set\n y_pred_prob_test: 1D numpy array, probability prediction on test set\n y_pred_prob_train: 1D numpy array, probability prediction on train set\n '''\n model_obj = PredictionModel(data[0], data[1], data[2], data[3])\n y_pred_prob_train, y_pred_prob_test = getattr(model_obj, model_name)()\n\n if not prob:\n return y_pred_prob_test, y_pred_prob_test, y_pred_prob_train\n\n if not cutoff:\n cutoff = find_cutoff(y_pred_prob_train, data[2])\n\n y_pred_test = binarize(y_pred_prob_test, cutoff)\n\n y_pred_test, y_pred_prob_test, y_pred_prob_train = list(map(\n lambda x: x.flatten(),\n (y_pred_test, y_pred_prob_test, y_pred_prob_train)\n ))\n\n return y_pred_test, y_pred_prob_test, y_pred_prob_train\n\n\ndef predict(model_name, data, cutoff, prob=True):\n '''Fits model on train data and returns predictions.\n\n Args:\n model_name: string name of model\n data: tuple of 2d numpy arrays x_train, x_test, y_train\n cutoff: float, decision boundary for classification\n\n Returns:\n y_pred: 1D numpy array, binary prediction on test set\n '''\n model_obj = PredictionModel(data[0], data[1], data[2])\n _, y_pred_prob_test = getattr(model_obj, model_name)()\n\n if not prob:\n return y_pred_prob_test\n\n y_pred_test = binarize(y_pred_prob_test, cutoff)\n y_pred_test = y_pred_test.flatten()\n\n return y_pred_test\n","sub_path":"santander_classifier/classifiers.py","file_name":"classifiers.py","file_ext":"py","file_size_in_byte":6772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"194087179","text":"\"\"\"\n Utils related with Json Web Token\n\"\"\"\n\nfrom .serializers.user import UserSerializer\n\ndef jwt_response_payload_handler(token, user=None, request=None):\n '''\n Function to handler the login response with JWTokens\n '''\n return {\n 'token' : token,\n 'user' : UserSerializer(user, context={'request':request}).data\n }","sub_path":"api/jwt.py","file_name":"jwt.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"66239606","text":"import numpy as np \nfrom matplotlib.pyplot import *\nimport matplotlib.cm as cm\nfrom matplotlib.colors import LinearSegmentedColormap\nimport netCDF4\nimport sys\nimport glob\nimport os\n##### import lib from the parent folder #####\nsys.path.insert(1, '../') # move 2 parent folder (figures/)\nfrom function import progressbar\nfrom nclcmaps import nclcmap\n# ===========================================\n\n\ndef draw_thprof(init, end):\n for n in range(init, end):\n ##### retrieve variables #####\n xx, zz = np.meshgrid(x, z)\n td = netCDF4.Dataset(td_files[n])\n #print(td_files[n])\n progressbar(now=n, length=end-init, text='draw theta')\n t = int(np.array(td['Time']))\n th = td['th'][0, :len(z), y_prof, xslice]\n thbar = np.mean(td['th'][0, :len(z), :, :], axis=(1, 2))\n thbar = np.tile(thbar, (len(x), 1)).transpose()\n\n ##### dw / dt #####\n prevw = np.array(netCDF4.Dataset(dy_files[n-1 + (n == init)])['w'])\n nexw = np.array(netCDF4.Dataset(dy_files[n+1 - (n == end-1)])['w'])\n dwdt = (nexw - prevw) / 60\n dwdt = dwdt[0, :len(z), y_prof, xslice]\n ##### draw th-thbar #####\n contourf(x, z, th-thbar, levels=50, vmin=-5, vmax=5, cmap='coolwarm')\n colorbar(extend='both')\n wt = contour(x, z, dwdt, colors='black', linewidths=.5)\n #clabel(wt, inline=True, fontsize=5)\n ##### draw wind #####\n u = np.array(netCDF4.Dataset(dy_files[n])['u'])[0, :len(z), y_prof, xslice]\n w = np.array(netCDF4.Dataset(dy_files[n])['w'])[0, :len(z), y_prof, xslice]\n ws = np.sqrt(u ** 2 + w ** 2)\n interval = 2\n quiver(xx[::interval, ::interval], zz[::interval, ::interval],\n (u/ws)[::interval, ::interval], (w/ws)[::interval, ::interval],\n ws[::interval, ::interval], cmap='rainbow')\n \n title(' t = '+ str(t) + r\" min [Shade: $\\theta '$, Contour: $\\frac{\\partial w}{\\partial t}$]\")\n xlabel('X (m)')\n ylabel('Z (m)')\n savefig('th_dwdt'+td_files[n][-9:-3]+'.jpg', dpi=300)\n clf()\n\nif __name__ == '__main__':\n\n exp_name = str(input())\n td_loc = '/media/wk2/atmenu10246/VVM/DATA/' + exp_name + '/archive/'\n td_files, dy_files = [], []\n for td, dy in zip(glob.glob(td_loc +exp_name + '.L.Thermodynamic-??????.nc'), glob.glob(td_loc + exp_name + '.L.Dynamic-??????.nc')):\n td_files.append(td)\n dy_files.append(dy)\n print('Appended nc files: '+ str(len(td_files)))\n # ========================================\n\n ##### universal variables #####\n dt = netCDF4.Dataset(td_files[0]) # take initial state\n z, y, x = np.array(dt['zc']), np.array(dt['yc']), np.array(dt['xc'])\n x = x - max(x)/2\n xslice = slice(int(len(x)/2)-2, len(x)-35)\n x = x[xslice]\n z = z[z<=12000]\n thbar = np.mean(dt['th'][0, :len(z), :, :], axis=(1, 2))\n thbar = np.tile(thbar, (len(x), 1)).transpose()\n y_prof = 63# max thbar index\n # =============================\n\n init, end = 0, 30#len(td_files)\n draw_thprof(init, end)\n\n","sub_path":"hi_reso24/th_prof.py","file_name":"th_prof.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"478836075","text":"# -*- coding: utf-8 -*-\n\nfrom sklearn import datasets\niris = datasets.load_iris()\nfrom sklearn.tree import DecisionTreeClassifier\n\nX = iris.data\nY = iris.target\n\n\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.5)\n\nfrom tensorflow.contrib import learn\nimport tensorflow as tf\nfeature_name = \"flow_features\"\nfeature_columns = [tf.feature_column.numeric_column(feature_name,\n shape=[4])]\n\nclf = tf.estimator.DNNClassifier(\n feature_columns=feature_columns,\n n_classes=3,\n model_dir=\"/tmp/iris_model\",\n hidden_units=[100, 70, 50, 25])\n\n\ndef input_fn(dataset):\n def _fn():\n features = {feature_name: tf.constant(dataset.data)}\n label = tf.constant(dataset.target)\n return features, label\n return _fn\n\n# Fit model.\nclf.train(input_fn=input_fn(X_train),\n steps=1000)\nprint(\"fit done\")\n","sub_path":"ai/ml/tf.py","file_name":"tf.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"305519651","text":"\nimport base.setting\n\n\nclass GetUrl:\n\n def proto_api_url(self, grpc_data=None, proto_method=None):\n format_url = base.setting.grpc_format_url\n if not format_url:\n raise RuntimeError(\"no url been set\")\n url = format_url % (grpc_data, proto_method)\n return url\n\n def http_api_url(self, url_params=None):\n base_url = base.setting.http_base_url\n if not base_url:\n raise RuntimeError(\"no url been set\")\n url = \"{0}{1}?debug=1\".format(base_url, url_params)\n return url\n\n def get_url(\n self,\n method,\n grpc_data=None,\n proto_method=None,\n url_params=None):\n url = None\n if method == \"GRPC\":\n url = self.proto_api_url(\n grpc_data=grpc_data,\n proto_method=proto_method)\n elif method in (\"HTTP\", \"HTTPS\"):\n url = self.http_api_url(url_params=url_params)\n return url\n\n\nif __name__ == \"__main__\":\n get_url =GetUrl()\n api = \"v1/course/hour\"\n url = get_url.http_api_url(api)\n print(url)","sub_path":"base/get_url.py","file_name":"get_url.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"528536038","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'liuzhijun'\n\nfrom handlers.base import BaseHandler\nimport logging\nfrom models import Blog\nfrom cache import cache\n\n\nlogger = logging.getLogger('foofish.' + __name__)\n\n\nclass IndexHandler(BaseHandler):\n @cache\n def get(self):\n latest_blog_id = self.redis.zrange('blog.list', -1, -1)[0]\n post = self.redis.hgetall(latest_blog_id)\n blog = Blog(id=latest_blog_id, **post)\n self.render(\"blog-post.html\", blog=blog)\n\n\nclass ArchivesHandler(BaseHandler):\n def get(self):\n blog_ids = self.redis.zrevrange('blog.list', 0, -1)\n blogs = [Blog(id=b_id, **self.redis.hgetall(b_id)) for b_id in blog_ids]\n self.render(\"archives.html\", blogs=blogs)\n\n\nclass ArticleHandler(BaseHandler):\n\n @cache\n def get(self, blog_id):\n post = self.redis.hgetall(blog_id)\n blog = Blog(id=blog_id, **post)\n self.render(\"blog-post.html\", blog=blog)\n\n\nclass CategoryHandler(BaseHandler):\n def get(self, tag):\n key = 'blog.tag.%s' % tag\n blog_ids = self.redis.zrevrange(key, 0, -1)\n blogs = [Blog(id=b_id, **self.redis.hgetall(b_id)) for b_id in blog_ids if self.redis.hgetall(b_id)]\n self.render(\"archives.html\", blogs=blogs)\n\n\nclass AboutHandler(BaseHandler):\n def get(self):\n self.render(\"about.html\")\n","sub_path":"handlers/blog_service.py","file_name":"blog_service.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"21859790","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom __future__ import annotations\n\nfrom typing import MutableMapping, MutableSequence\n\nfrom google.protobuf import field_mask_pb2 # type: ignore\nimport proto # type: ignore\n\nfrom google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation\nfrom google.cloud.discoveryengine_v1beta.types import search_service\n\n__protobuf__ = proto.module(\n package=\"google.cloud.discoveryengine.v1beta\",\n manifest={\n \"ConverseConversationRequest\",\n \"ConverseConversationResponse\",\n \"CreateConversationRequest\",\n \"UpdateConversationRequest\",\n \"DeleteConversationRequest\",\n \"GetConversationRequest\",\n \"ListConversationsRequest\",\n \"ListConversationsResponse\",\n },\n)\n\n\nclass ConverseConversationRequest(proto.Message):\n r\"\"\"Request message for\n [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation]\n method.\n\n Attributes:\n name (str):\n Required. The resource name of the Conversation to get.\n Format:\n ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``.\n Use\n ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-``\n to activate auto session mode, which automatically creates a\n new conversation inside a ConverseConversation session.\n query (google.cloud.discoveryengine_v1beta.types.TextInput):\n Required. Current user input.\n serving_config (str):\n The resource name of the Serving Config to use. Format:\n ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/servingConfigs/{serving_config_id}``\n If this is not set, the default serving config will be used.\n conversation (google.cloud.discoveryengine_v1beta.types.Conversation):\n The conversation to be used by auto session\n only. The name field will be ignored as we\n automatically assign new name for the\n conversation in auto session.\n safe_search (bool):\n Whether to turn on safe search.\n user_labels (MutableMapping[str, str]):\n The user labels applied to a resource must meet the\n following requirements:\n\n - Each resource can have multiple labels, up to a maximum\n of 64.\n - Each label must be a key-value pair.\n - Keys have a minimum length of 1 character and a maximum\n length of 63 characters and cannot be empty. Values can\n be empty and have a maximum length of 63 characters.\n - Keys and values can contain only lowercase letters,\n numeric characters, underscores, and dashes. All\n characters must use UTF-8 encoding, and international\n characters are allowed.\n - The key portion of a label must be unique. However, you\n can use the same key with multiple resources.\n - Keys must start with a lowercase letter or international\n character.\n\n See `Google Cloud\n Document `__\n for more details.\n summary_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SummarySpec):\n A specification for configuring the summary\n returned in the response.\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n query: gcd_conversation.TextInput = proto.Field(\n proto.MESSAGE,\n number=2,\n message=gcd_conversation.TextInput,\n )\n serving_config: str = proto.Field(\n proto.STRING,\n number=3,\n )\n conversation: gcd_conversation.Conversation = proto.Field(\n proto.MESSAGE,\n number=5,\n message=gcd_conversation.Conversation,\n )\n safe_search: bool = proto.Field(\n proto.BOOL,\n number=6,\n )\n user_labels: MutableMapping[str, str] = proto.MapField(\n proto.STRING,\n proto.STRING,\n number=7,\n )\n summary_spec: search_service.SearchRequest.ContentSearchSpec.SummarySpec = (\n proto.Field(\n proto.MESSAGE,\n number=8,\n message=search_service.SearchRequest.ContentSearchSpec.SummarySpec,\n )\n )\n\n\nclass ConverseConversationResponse(proto.Message):\n r\"\"\"Response message for\n [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation]\n method.\n\n Attributes:\n reply (google.cloud.discoveryengine_v1beta.types.Reply):\n Answer to the current query.\n conversation (google.cloud.discoveryengine_v1beta.types.Conversation):\n Updated conversation including the answer.\n related_questions (MutableSequence[str]):\n Suggested related questions.\n search_results (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.SearchResult]):\n Search Results.\n \"\"\"\n\n reply: gcd_conversation.Reply = proto.Field(\n proto.MESSAGE,\n number=1,\n message=gcd_conversation.Reply,\n )\n conversation: gcd_conversation.Conversation = proto.Field(\n proto.MESSAGE,\n number=2,\n message=gcd_conversation.Conversation,\n )\n related_questions: MutableSequence[str] = proto.RepeatedField(\n proto.STRING,\n number=6,\n )\n search_results: MutableSequence[\n search_service.SearchResponse.SearchResult\n ] = proto.RepeatedField(\n proto.MESSAGE,\n number=3,\n message=search_service.SearchResponse.SearchResult,\n )\n\n\nclass CreateConversationRequest(proto.Message):\n r\"\"\"Request for CreateConversation method.\n\n Attributes:\n parent (str):\n Required. Full resource name of parent data store. Format:\n ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}``\n conversation (google.cloud.discoveryengine_v1beta.types.Conversation):\n Required. The conversation to create.\n \"\"\"\n\n parent: str = proto.Field(\n proto.STRING,\n number=1,\n )\n conversation: gcd_conversation.Conversation = proto.Field(\n proto.MESSAGE,\n number=2,\n message=gcd_conversation.Conversation,\n )\n\n\nclass UpdateConversationRequest(proto.Message):\n r\"\"\"Request for UpdateConversation method.\n\n Attributes:\n conversation (google.cloud.discoveryengine_v1beta.types.Conversation):\n Required. The Conversation to update.\n update_mask (google.protobuf.field_mask_pb2.FieldMask):\n Indicates which fields in the provided\n [Conversation][google.cloud.discoveryengine.v1beta.Conversation]\n to update. The following are NOT supported:\n\n - [conversation.name][]\n\n If not set or empty, all supported fields are updated.\n \"\"\"\n\n conversation: gcd_conversation.Conversation = proto.Field(\n proto.MESSAGE,\n number=1,\n message=gcd_conversation.Conversation,\n )\n update_mask: field_mask_pb2.FieldMask = proto.Field(\n proto.MESSAGE,\n number=2,\n message=field_mask_pb2.FieldMask,\n )\n\n\nclass DeleteConversationRequest(proto.Message):\n r\"\"\"Request for DeleteConversation method.\n\n Attributes:\n name (str):\n Required. The resource name of the Conversation to delete.\n Format:\n ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass GetConversationRequest(proto.Message):\n r\"\"\"Request for GetConversation method.\n\n Attributes:\n name (str):\n Required. The resource name of the Conversation to get.\n Format:\n ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass ListConversationsRequest(proto.Message):\n r\"\"\"Request for ListConversations method.\n\n Attributes:\n parent (str):\n Required. The data store resource name. Format:\n ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}``\n page_size (int):\n Maximum number of results to return. If\n unspecified, defaults to 50. Max allowed value\n is 1000.\n page_token (str):\n A page token, received from a previous ``ListConversations``\n call. Provide this to retrieve the subsequent page.\n filter (str):\n A filter to apply on the list results. The supported\n features are: user_pseudo_id, state.\n\n Example: \"user_pseudo_id = some_id\".\n order_by (str):\n A comma-separated list of fields to order by, sorted in\n ascending order. Use \"desc\" after a field name for\n descending. Supported fields:\n\n - ``update_time``\n - ``create_time``\n - ``conversation_name``\n\n Example: \"update_time desc\" \"create_time\".\n \"\"\"\n\n parent: str = proto.Field(\n proto.STRING,\n number=1,\n )\n page_size: int = proto.Field(\n proto.INT32,\n number=2,\n )\n page_token: str = proto.Field(\n proto.STRING,\n number=3,\n )\n filter: str = proto.Field(\n proto.STRING,\n number=4,\n )\n order_by: str = proto.Field(\n proto.STRING,\n number=5,\n )\n\n\nclass ListConversationsResponse(proto.Message):\n r\"\"\"Response for ListConversations method.\n\n Attributes:\n conversations (MutableSequence[google.cloud.discoveryengine_v1beta.types.Conversation]):\n All the Conversations for a given data store.\n next_page_token (str):\n Pagination token, if not returned indicates\n the last page.\n \"\"\"\n\n @property\n def raw_page(self):\n return self\n\n conversations: MutableSequence[gcd_conversation.Conversation] = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=gcd_conversation.Conversation,\n )\n next_page_token: str = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py","file_name":"conversational_search_service.py","file_ext":"py","file_size_in_byte":11419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"115691634","text":"import daanlycs.dbconfig as dbconf\r\nimport sqlalchemy as sqla\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport akutils.normalize as nmize\r\nfrom django.contrib.admin.utils import quote\r\n\r\nengine = sqla.create_engine(\"mysql+mysqlconnector://\"+dbconf.report_username+\":\"+dbconf.report_password+\"@\"+dbconf.report_host+\"/\"+dbconf.report_database,echo=True)\r\nconnection = engine.connect()\r\nqry = \"SELECT i.`QUICKBOOKS_ID` AS customer, i.`DATE` as date, SUM(i.`TOTAL`) AS total FROM invoice i WHERE i.`DATE` = '2017-05-31' GROUP BY i.`QUICKBOOKS_ID`, i.`DATE`\";\r\n\r\ndf = pd.read_sql(qry, connection, index_col='customer', parse_dates=['date'], coerce_float=True)\r\n\r\n# print(df)\r\nx_data=df.index.values\r\nx_data_tick_pos = np.arange(1,len(x_data)+1,1)\r\ny_data = df['total'].values\r\n\r\n\r\nfig, ax = plt.subplots()\r\n\r\nax.scatter(x_data_tick_pos,y_data,s=nmize.normalize(y_data, 1, 500))\r\n\r\nplt.xlabel(\"Customers\")\r\nplt.ylabel(\"Total revenue\")\r\nplt.title(\"Revenue collected for each customer in the month of May 2017\")\r\nplt.margins(0.1)\r\n\r\nfor i, txt in enumerate(x_data):\r\n if y_data[i]>25000:\r\n ax.annotate(txt + \"\\n\" + str(y_data[i]), (x_data_tick_pos[i],y_data[i]),xytext=(-5,20), \r\n textcoords='offset points', ha='center', va='bottom',\r\n bbox=dict(boxstyle='round,pad=0.2', fc='yellow'),\r\n arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.2', \r\n color='red'),fontsize=6)\r\ndf.to_csv(\"SDS-Invoice.csv\",sep=',')\r\nprint(df.dtypes)\r\n# plt.show()","sub_path":"daanlycs/invoice.py","file_name":"invoice.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"350480670","text":"import re\n\n\nclass Tokenizer:\n '''\n Removes all comments and white space from the input\n and breaks it into Jack-language tokens,\n as specified by the Jack grammar\n\n\n keywords = ['class', 'constructor', 'function', 'method', 'field','static',\n 'var', 'int', 'char', 'boolean', 'void', 'true','false',\n 'null', 'this', 'let', 'do', 'if', 'else', 'while', 'return']\n\n symbols = ['{', '}', '(', ')', '[', ']', '.', ',', ';','+',\n '-', '*', '/', '&', '|', '<', '>', '=', '~']\n '''\n\n types = ['int', 'boolean', 'char']\n\n\n def __init__(self, input_file):\n '''\n Constructor: takes the input file as argument,\n opens it and gets ready to tokenize it\n '''\n self.lines = input_file.readlines()\n self.clean_file = \"\"\n self.current_token = None\n self.next_token = None\n self.i = 0\n self.str_list = []\n self.n_str = 0\n\n\n def remove_comments(self):\n '''\n Ignore every type of comment in the file\n and paste the clean code in clean_file\n '''\n n = 0\n while n < len(self.lines):\n # Ignore '//' comments\n if '//' in self.lines[n]:\n self.clean_file += self.lines[n][:self.lines[n].index('//')]\n n += 1\n # Ignore '/*...*/' and '/**...*/' comments\n elif '/*' in self.lines[n] or '/**' in self.lines[n]:\n while '*/' not in self.lines[n]:\n n += 1\n n += 1\n # Append normal line of code to clean file\n else:\n self.clean_file += self.lines[n]\n n += 1\n\n\n def split_tokens(self):\n '''\n Create a list with all the tokens of the input file\n and an iterator for the tokens\n '''\n self.tokens = re.findall(\"\\w+|[{}()\\[\\].;\\\",+\\-*/&|<>=~]\", self.clean_file)\n self.iterator = self.__iter__()\n\n\n def create_strconst_list(self):\n ''' Create a list of all the string constants of the input file '''\n s = self.clean_file\n while '\"' in s:\n i1 = s.find('\"')\n i2 = s.find('\"', i1+1)\n text = s[i1:i2+1]\n self.str_list.append(text)\n s = s[i2+1:]\n\n\n def __iter__(self):\n ''' Iterate over tokens and yields them '''\n while self.i < len(self.tokens):\n # Yield a string constant\n if self.tokens[self.i] == '\"':\n token = self.str_list[self.n_str]\n self.n_str += 1\n self.i += 2\n while self.tokens[self.i-1] != '\"':\n self.i += 1\n yield token\n # Yield every other token\n else:\n yield self.tokens[self.i]\n self.i += 1\n\n\n def advance(self):\n '''\n Get the next token from the tokens's iterator\n and makes it the current token\n '''\n self.current_token = self.next_token\n try:\n self.next_token = next(self.iterator)\n except StopIteration:\n pass\n\n\n def is_identifier(self, token):\n return token.isidentifier()\n\n\n def is_type(self, token):\n ''' Returns true if the token is primitive type or className '''\n return self.is_identifier(token) or token in self.types\n\n\n def key_word(self):\n ''' Returns the keyword wich is the current token '''\n return self.current_token\n\n\n def symbol(self):\n ''' Returns the symbol wich is the current token '''\n return self.current_token.replace('&', '&').replace('<', '<').replace('>', '>')\n\n\n def identifier(self):\n ''' Returns the identifier wich is the current token '''\n return self.current_token\n\n\n def int_val(self):\n ''' Returns the integer value of the current token '''\n return int(self.current_token)\n\n\n def string_val(self):\n ''' Returns the string value of the current token, without the double quotes '''\n return self.current_token.strip('\"')\n","sub_path":"projects/11/JackTokenizer.py","file_name":"JackTokenizer.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"285435232","text":"from matplotlib import pyplot as plt \nimport numpy as np\nfrom scipy import stats\n\ndef prob_function(sample):\n values=[]\n for i in [0,1,2,3,4,5]:\n value=np.where(np.array(sample)==i)\n values.append(len(value[0])/len(sample))\n return lambda i : values[i]\n\ndef expectation(func,var=lambda x:x):\n return sum([var(x)*func(x) for x in [0,1,2,3,4,5]])\n\ndef variance(func,var=lambda x:x):\n return expectation(func,lambda x:(x-expectation(func))**2)\n\ndef std_deviation(func,var=lambda x:x):\n return (variance(func,var))**0.5\n\n\n\n\ndef main():\n sample1=2*[0]+4*[1]+12*[2]+24*[3]+24*[4]+10*[5]\n sample2=6*[0]+14*[1]+18*[2]+18*[3]+14*[4]+6*[5]\n sample3=2*[5]+4*[4]+12*[3]+24*[2]+24*[1]+10*[0]\n\n fig=plt.figure(figsize=(12,6))\n\n ax1=fig.add_subplot(131)\n ax2=fig.add_subplot(132)\n ax3=fig.add_subplot(133)\n \n for i in [1,2,3]:\n eval(\"ax{0}.set_title(\\\n 'skew=%f'%stats.skew(sample{0}))\".format(i))\n #eval(\"ax{0}.hist(sample{0})\".format(i))\n sample=eval(\"sample{}\".format(i))\n func=prob_function(sample)\n func=np.vectorize(func)\n print(expectation(func))\n print(variance(func))\n print(np.var(sample))\n print(std_deviation(func))\n print(np.std(sample))\n xs=np.array([0,1,2,3,4,5])\n ys=func(xs)\n print(ys)\n eval(\"ax{0}.plot(xs,ys)\".format(i))\n\n plt.show()\n\nif __name__ == '__main__':\n main()","sub_path":"statistics/forML/skewness.py","file_name":"skewness.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"62578202","text":"import os\nimport json\nimport collections\n\n\"\"\"\n==============\nThis script is going to fill config.json file with addresses and abi's from last build. \nThis means whenever you do \"truffle migrate\", you need to run this script and update config file.\n==============\n\n==============\nTo run: $ python update_config.py\n==============\n\n\"\"\"\ndirectory = \"../build/contracts\"\ndict = {}\nabi = {}\nnetwork_id = 42\n\nfor contract in os.listdir(directory):\n if contract.endswith(\".json\"):\n with open(os.path.join(directory,contract)) as json_contract:\n dictdump = json.loads(json_contract.read())\n if(dictdump.get(\"networks\") == {}):\n continue\n\n if(dictdump[\"abi\"] != None):\n abi[contract] = dictdump[\"abi\"]\n if(dictdump[\"networks\"].get(str(network_id)) != None ):\n dict[contract] = dictdump[\"networks\"][str(network_id)][\"address\"]\n else:\n print(\"{} doesn't have address on network id: {}\".format(contract, network_id))\n\nwith open(\"./data.json\",\"r+\") as jsonFile:\n data = {}\n\n for contract in dict:\n c = contract[:-5]\n data[c] = {}\n data[c]['abi'] = abi[contract]\n data[c]['address'] = dict[contract]\n print(\"Added {} with address: {}\".format(c, dict[contract]))\n\n jsonFile.seek(0)\n json.dump(data, jsonFile)\n jsonFile.truncate()\n","sub_path":"solidity/scripts/get_config.py","file_name":"get_config.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"144628125","text":"import math\nimport numpy as np\ndef f(t,y):\n return y-2*t/y\ndef Runge_Kutta_4order(xspan,y0,h):\n t = xspan[0]\n y=y0\n while( 1 ):\n k1 = h*f(t,y)\n k2 = h*f(t+h/2,y+k1/2)\n k3 = h*f(t+h/2,y+k2/2)\n k4 = h*f(t+h,y+k3)\n y = y + (k1+2*k2+2*k3+k4)/6\n y=np.around(y,4)\n print(y)\n t = t + h\n if(t>xspan[1]):break\n return y\nif __name__=='__main__':\n y1=0\n Runge_Kutta_4order([0,1],1,0.2)\n h=0.2\n","sub_path":"Numerical_Analysis/Q2_5_3Runge_Kutta_4order.py","file_name":"Q2_5_3Runge_Kutta_4order.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"280444371","text":"# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"ResNet.\"\"\"\nimport numpy as np\nimport mindspore.nn as nn\nfrom mindspore.ops import operations as P\nfrom mindspore.common.tensor import Tensor\n\n\ndef _weight_variable(shape, factor=0.01):\n init_value = np.random.randn(*shape).astype(np.float32) * factor\n return Tensor(init_value)\n\n\ndef _conv3x3(in_channel, out_channel, stride=1):\n weight_shape = (out_channel, in_channel, 3, 3)\n weight = _weight_variable(weight_shape)\n return nn.Conv2d(in_channel, out_channel,\n kernel_size=3, stride=stride, padding=0, pad_mode='same', weight_init=weight)\n\n\ndef _conv1x1(in_channel, out_channel, stride=1):\n weight_shape = (out_channel, in_channel, 1, 1)\n weight = _weight_variable(weight_shape)\n return nn.Conv2d(in_channel, out_channel,\n kernel_size=1, stride=stride, padding=0, pad_mode='same', weight_init=weight)\n\n\ndef _conv7x7(in_channel, out_channel, stride=1):\n weight_shape = (out_channel, in_channel, 7, 7)\n weight = _weight_variable(weight_shape)\n return nn.Conv2d(in_channel, out_channel,\n kernel_size=7, stride=stride, padding=0, pad_mode='same', weight_init=weight)\n\n\ndef _bn(channel):\n return nn.BatchNorm2d(channel, eps=1e-4, momentum=0.9,\n gamma_init=1, beta_init=0, moving_mean_init=0, moving_var_init=1)\n\n\ndef _bn_last(channel):\n return nn.BatchNorm2d(channel, eps=1e-4, momentum=0.9,\n gamma_init=0, beta_init=0, moving_mean_init=0, moving_var_init=1)\n\n\ndef _fc(in_channel, out_channel):\n weight_shape = (out_channel, in_channel)\n weight = _weight_variable(weight_shape)\n return nn.Dense(in_channel, out_channel, has_bias=True, weight_init=weight, bias_init=0)\n\n\nclass ResidualBlock(nn.Cell):\n \"\"\"\n ResNet V1 residual block definition.\n\n Args:\n in_channel (int): Input channel.\n out_channel (int): Output channel.\n stride (int): Stride size for the first convolutional layer. Default: 1.\n\n Returns:\n Tensor, output tensor.\n\n Examples:\n >>> ResidualBlock(3, 256, stride=2)\n \"\"\"\n expansion = 4\n\n def __init__(self,\n in_channel,\n out_channel,\n stride=1):\n super(ResidualBlock, self).__init__()\n\n channel = out_channel // self.expansion\n self.conv1 = _conv1x1(in_channel, channel, stride=1)\n self.bn1 = _bn(channel)\n\n self.conv2 = _conv3x3(channel, channel, stride=stride)\n self.bn2 = _bn(channel)\n\n self.conv3 = _conv1x1(channel, out_channel, stride=1)\n self.bn3 = _bn_last(out_channel)\n\n self.relu = nn.ReLU()\n\n self.down_sample = False\n\n if stride != 1 or in_channel != out_channel:\n self.down_sample = True\n self.down_sample_layer = None\n\n if self.down_sample:\n self.down_sample_layer = nn.SequentialCell([_conv1x1(in_channel, out_channel, stride),\n _bn(out_channel)])\n self.add = P.Add()\n\n def construct(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.down_sample:\n identity = self.down_sample_layer(identity)\n\n out = self.add(out, identity)\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Cell):\n \"\"\"\n ResNet architecture.\n\n Args:\n block (Cell): Block for network.\n layer_nums (list): Numbers of block in different layers.\n in_channels (list): Input channel in each layer.\n out_channels (list): Output channel in each layer.\n strides (list): Stride size in each layer.\n num_classes (int): The number of classes that the training images are belonging to.\n Returns:\n Tensor, output tensor.\n\n Examples:\n >>> ResNet(ResidualBlock,\n >>> [3, 4, 6, 3],\n >>> [64, 256, 512, 1024],\n >>> [256, 512, 1024, 2048],\n >>> [1, 2, 2, 2],\n >>> 10)\n \"\"\"\n\n def __init__(self,\n block,\n layer_nums,\n in_channels,\n out_channels,\n strides,\n num_classes):\n super(ResNet, self).__init__()\n\n if not len(layer_nums) == len(in_channels) == len(out_channels) == 4:\n raise ValueError(\"the length of layer_num, in_channels, out_channels list must be 4!\")\n\n self.conv1 = _conv7x7(3, 64, stride=2)\n self.bn1 = _bn(64)\n self.relu = P.ReLU()\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, pad_mode=\"same\")\n\n self.layer1 = self._make_layer(block,\n layer_nums[0],\n in_channel=in_channels[0],\n out_channel=out_channels[0],\n stride=strides[0])\n self.layer2 = self._make_layer(block,\n layer_nums[1],\n in_channel=in_channels[1],\n out_channel=out_channels[1],\n stride=strides[1])\n self.layer3 = self._make_layer(block,\n layer_nums[2],\n in_channel=in_channels[2],\n out_channel=out_channels[2],\n stride=strides[2])\n self.layer4 = self._make_layer(block,\n layer_nums[3],\n in_channel=in_channels[3],\n out_channel=out_channels[3],\n stride=strides[3])\n\n self.mean = P.ReduceMean(keep_dims=True)\n self.flatten = nn.Flatten()\n self.end_point = _fc(out_channels[3], num_classes)\n\n def _make_layer(self, block, layer_num, in_channel, out_channel, stride):\n \"\"\"\n Make stage network of ResNet.\n\n Args:\n block (Cell): Resnet block.\n layer_num (int): Layer number.\n in_channel (int): Input channel.\n out_channel (int): Output channel.\n stride (int): Stride size for the first convolutional layer.\n\n Returns:\n SequentialCell, the output layer.\n\n Examples:\n >>> _make_layer(ResidualBlock, 3, 128, 256, 2)\n \"\"\"\n layers = []\n\n resnet_block = block(in_channel, out_channel, stride=stride)\n layers.append(resnet_block)\n\n for _ in range(1, layer_num):\n resnet_block = block(out_channel, out_channel, stride=1)\n layers.append(resnet_block)\n\n return nn.SequentialCell(layers)\n\n def construct(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n c1 = self.maxpool(x)\n\n c2 = self.layer1(c1)\n c3 = self.layer2(c2)\n c4 = self.layer3(c3)\n c5 = self.layer4(c4)\n\n out = self.mean(c5, (2, 3))\n out = self.flatten(out)\n out = self.end_point(out)\n\n return out\n\n\ndef resnet50(class_num=10):\n \"\"\"\n Get ResNet50 neural network.\n\n Args:\n class_num (int): Class number.\n\n Returns:\n Cell, cell instance of ResNet50 neural network.\n\n Examples:\n >>> net = resnet50(10)\n \"\"\"\n return ResNet(ResidualBlock,\n [3, 4, 6, 3],\n [64, 256, 512, 1024],\n [256, 512, 1024, 2048],\n [1, 2, 2, 2],\n class_num)\n\ndef resnet101(class_num=1001):\n \"\"\"\n Get ResNet101 neural network.\n\n Args:\n class_num (int): Class number.\n\n Returns:\n Cell, cell instance of ResNet101 neural network.\n\n Examples:\n >>> net = resnet101(1001)\n \"\"\"\n return ResNet(ResidualBlock,\n [3, 4, 23, 3],\n [64, 256, 512, 1024],\n [256, 512, 1024, 2048],\n [1, 2, 2, 2],\n class_num)\n","sub_path":"tests/ut/python/model/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":8925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"155960633","text":"# -*- coding: utf-8 -*-\n\n# General\nHOST = 'localhost'\nPORT = 4223\n\n# Bricklet\nUID_LED_STRIP_BRICKLET = 'abc'\n\n# Size of LED Pixel matrix\nLED_ROWS = 20\nLED_COLS = 10\n\n# Position of R, G and B pixel on LED Pixel\nR_INDEX = 2\nG_INDEX = 1\nB_INDEX = 0\n\n# Images Parameters\nIMAGES_FRAME_RATE = 1 # in Hz, valid range: 1 - 100\n","sub_path":"images/python/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"376798092","text":"#!/usr/bin/env python3\nimport json\nimport csv\nfrom collections import OrderedDict\n\n# Example:\n# test = '{\"1\":{\"sec\":\"1\",\"question\":\"1+1=?\",\"choices\":{\"A\":1,\"B\":2,\"C\":3,\"D\":4},\"key\":\"B\",\"explain\":\"1+1=2\"},\"2\":{\"sec\":\"1\",\"question\":\"1+2=?\",\"choices\":{\"A\":1,\"B\":2,\"C\":3,\"D\":4},\"key\":\"C\",\"explain\":\"1+2=3\"}}'\n\ntry:\n\n quiz_filename = 'quiz.csv'\n quiz_list = []\n \n with open(quiz_filename) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader: \n if line_count > 0:\n quiz = OrderedDict()\n quiz_all = OrderedDict()\n choice = OrderedDict()\n quiz_id = row[0].strip()\n quiz['sec'] = row[1].strip()\n quiz['question'] = row[2].strip()\n choice['A'] = row[3].strip()\n choice['B'] = row[4].strip()\n choice['C'] = row[5].strip()\n choice['D'] = row[6].strip()\n quiz['choices'] = choice \n quiz['key'] = row[7].strip()\n quiz['explain'] = row[8].strip()\n quiz_all[str(quiz_id)] = quiz\n quiz_list.append(quiz_all)\n line_count += 1\n\n result = json.dumps(quiz_list, indent=4)\n print('result =',result)\n print()\n\n json_to_write = ','.join(json.dumps(i) for i in quiz_list)\n json_to_write = json_to_write.replace('}},{','},') \n json_to_write = 'test_pool = \\'' + json_to_write + '\\''\n\n with open('test.json', 'w') as fp:\n print('saving...', json_to_write) \n fp.write(json_to_write)\n\nexcept FileNotFoundError:\n print('cannot find quiz.csv')\n\n\n\n","sub_path":"Json generator/Windows/quiz.py","file_name":"quiz.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"358930021","text":"from django.contrib import admin\nfrom .models import Like\n\n\ndef like_delete(modeladmin, request, queryset):\n for obj in queryset:\n if obj.to_show:\n obj.save()\n\n\ndef like_update(modeladmin, request, queryset):\n for obj in queryset:\n if not obj.to_show:\n obj.save()\n\n\nlike_delete.short_description = \"Not to show\"\nlike_update.short_description = \"Show\"\n\n\nclass LikeAdmin(admin.ModelAdmin):\n list_display = ('id', 'author_id', 'content_type_id', 'object_id', 'to_show')\n\n fieldsets = (\n (None, {\n 'fields': ('author', 'content_type', 'object_id', )\n }),\n )\n actions = [like_delete, like_update]\n\n\nadmin.site.register(Like, LikeAdmin)\n","sub_path":"socNetwork/Like/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"339925329","text":"import re\nimport sys\nimport os\nimport numpy as np\nimport pandas as pd\n\ndef data_helper(dataset):\n df = pd.read_csv(dataset)\n\n selected = [\"주야\",\"요일\", \"사망자수\", \"사상자수\",\"중상자수\",\"경상자수\",\"부상신고자수\",\"발생지시도\",\"발생지시군구\",\"사고유형_대분류\",\"사고유형_중분류\",\"법규위반\",\"도로형태_대분류\", \"도로형태\",\"당사자종별_1당_대분류\",\"당사자종별_2당_대분류\"]\n\n col_number = [\"사상자수\", \"사망자수\", \"중상자수\", \"경상자수\", \"부상신고자수\"]\n col_range = [\"주야\", \"요일\", \"발생지시도\", \"발생지시군구\", \"사고유형_대분류\", \"사고유형_중분류\", \"법규위반\", \"도로형태_대분류\", \"도로형태\", \"당사자종별_1당_대분류\", \"당사자종별_2당_대분류\"]\n\n to_drop = list(set(df.columns) - set(selected))\n df =df.drop(to_drop, axis=1)\n default_dict = {}\n for name in col_number:\n col_raw = df[name].tolist()\n avg_val = 0\n for val in col_raw:\n avg_val += int(val)\n default_dict[name] = int(avg_val/len(col_raw)) \n for name in col_range:\n col_raw = df[name].tolist()\n temp_dict = {}\n for val in col_raw:\n if val not in temp_dict:\n temp_dict[val] = 1\n else:\n temp_dict[val] += 1\n top_val = ''\n top_count = 0\n for key, value in temp_dict.items():\n if value > top_count:\n top_val = key\n top_count = value\n default_dict[name] = top_val\n print(default_dict)\n total_converted = []\n for name in selected:\n col_raw = df[name].tolist()\n col_converted = []\n for data in col_raw:\n col_converted.append(name+'-'+str(data).replace(' ','_'))\n total_converted.append(col_converted)\n data=[]\n for i in range(len(total_converted[0])):\n new_row = []\n for elem in total_converted:\n new_row.append(elem[i]) \n data.append(new_row)\n df_new = pd.DataFrame(data, columns = selected)\n df_new.to_csv('accidents.csv', index=False, columns=selected, sep=',')\n \n return data, selected, col_number, col_range, default_dict\n\ndef test_data_helper(dataset):\n df = pd.read_csv(dataset)\n\n selected = [\"주야\",\"요일\", \"사망자수\", \"사상자수\",\"중상자수\",\"경상자수\",\"부상신고자수\",\"발생지시도\",\"발생지시군구\",\"사고유형_대분류\",\"사고유형_중분류\",\"법규위반\",\"도로형태_대분류\", \"도로형태\",\"당사자종별_1당_대분류\",\"당사자종별_2당_대분류\"]\n\n col_number = [\"사상자수\", \"사망자수\", \"중상자수\", \"경상자수\", \"부상신고자수\"]\n col_range = [\"주야\", \"요일\", \"발생지시도\", \"발생지시군구\", \"사고유형_대분류\", \"사고유형_중분류\", \"법규위반\", \"도로형태_대분류\", \"도로형태\", \"당사자종별_1당_대분류\", \"당사자종별_2당_대분류\"]\n\n to_drop = list(set(df.columns) - set(selected))\n df =df.drop(to_drop, axis=1)\n\n total_converted = []\n for name in selected:\n col_raw = df[name].tolist()\n col_converted = []\n for data in col_raw:\n col_converted.append(name+'-'+str(data).replace(' ','_'))\n total_converted.append(col_converted)\n data=[]\n for i in range(len(total_converted[0])):\n new_row = []\n for elem in total_converted:\n new_row.append(elem[i]) \n data.append(new_row)\n df_new = pd.DataFrame(data, columns = selected)\n df_new.to_csv('accidents_test.csv', index=False, columns=selected, sep=',') \n return data\n\ndef count_words(count_dict, text):\n '''Count the number of occurrences of each word in a set of text'''\n for sentence in text:\n for word in sentence.split():\n if word not in count_dict:\n count_dict[word] = 1\n else:\n count_dict[word] += 1\n \ndef pad_sentence_batch(vocab_to_int,sentence_batch):\n \"\"\"Pad sentences with so that each sentence of a batch has the same length\"\"\"\n max_sentence = max([len(sentence) for sentence in sentence_batch])\n result = []\n for sentence in sentence_batch:\n result.append(sentence + [vocab_to_int['PAD']] * (max_sentence - len(sentence)))\n return result\n\ndef convert_to_ints(text,vocab_to_int, word_count, unk_count, eos=False):\n '''Convert words in text to an integer.\n If word is not in vocab_to_int, use UNK's integer.\n Total the number of words and UNKs.\n Add EOS token to the end of texts'''\n ints = []\n for sentence in text:\n sentence_ints = []\n if eos:\n sentence_ints.append(vocab_to_int[\"GO\"]) \n for word in sentence.split():\n word_count += 1\n if word in vocab_to_int:\n sentence_ints.append(vocab_to_int[word])\n else:\n sentence_ints.append(vocab_to_int[\"UNK\"])\n unk_count += 1\n if eos:\n sentence_ints.append(vocab_to_int[\"EOS\"])\n ints.append(sentence_ints)\n return ints, word_count, unk_count\n\ndef convert_to_raws(logits, int_to_vocab):\n raw_logits=[]\n for logit in logits:\n result = [int_to_vocab[j] for j in logit]\n raw_logits.append(result)\n return raw_logits\n\ndef ensemble_logits(test_raw, logit_list, selected, col_number, col_range, default_dict):\n converted_logits = []\n for logit in logit_list:\n new_logit=[]\n for row in logit:\n new_row = []\n for i in range(len(selected)):\n try:\n raw_val = row[i].split('-')[1]\n if selected[i] == row[i].split('-')[0]:\n raw_val = raw_val.replace('_',' ')\n else:\n raw_val = 'nan'\n except:\n raw_val = 'nan'\n new_row.append(raw_val)\n new_logit.append(new_row)\n converted_logits.append(new_logit)\n final_list = []\n for i in range(len(test_raw)):\n final_row = []\n for j in range(len(selected)):\n if test_raw[i][j].split('-')[1] == 'nan':\n if selected[j] in col_number:\n count = 0\n total = 0\n for logit in converted_logits:\n candidate = logit[i][j]\n try:\n candidate = int(candidate)\n total += candidate\n count += 1\n except:\n pass\n if count != 0:\n avg_val = int(total/count)\n else:\n avg_val = default_dict[selected[j]]\n final_row.append(avg_val)\n else:\n candi_dict = {}\n for logit in converted_logits:\n candidate = logit[i][j]\n try:\n temp = int(candidate)\n pass\n except:\n if candidate not in candi_dict:\n candi_dict[candidate] = 1\n else:\n candi_dict[candidate] += 1\n top_val = ''\n top_count = 0\n for key, value in candi_dict.items():\n if value > top_count:\n top_val = key\n top_count = value\n if top_val == 'nan':\n if selected[j] == '발생지시군구' and logit[i][j-1] == '경남':\n top_val = '창원시(통합)'\n else:\n top_val = default_dict[selected[j]]\n final_row.append(top_val)\n else:\n raw_val = test_raw[i][j].split('-')[1]\n raw_val = raw_val.replace('_',' ')\n final_row.append(raw_val)\n final_list.append(final_row)\n print('ensemble fin') \n df_new = pd.DataFrame(final_list, columns = selected)\n df_new.to_csv('final_result_raw.csv', index=False, columns=selected, sep=',') \n return final_list\n \ndef next_epoch(data, selected, min_rand):\n max_num = len(data)\n new_epoch = []\n new_empty_epoch = []\n rand_size = np.random.randint(min_rand, 5, size = max_num).tolist()\n for i in range(len(data)):\n rand_idx = np.random.randint(0,len(data[i]), size = rand_size[i]).tolist() \n new_row = []\n new_empty = []\n for j in range(len(data[i])):\n if j in rand_idx:\n new_row.append(\"UNK\")\n new_empty.append(1)\n else:\n new_row.append(data[i][j])\n new_empty.append(0)\n new_epoch.append(new_row)\n new_empty_epoch.append(new_empty)\n return new_epoch, np.array(new_empty_epoch).astype(np.int32)\n\ndef batch_iter(data, batch_size, num_epochs, shuffle=True):\n \"\"\"Iterate the data batch by batch\"\"\"\n data = np.array(data)\n data_size = len(data)\n num_batches_per_epoch = int(data_size / batch_size) + 1\n\n for epoch in range(num_epochs):\n if shuffle:\n shuffle_indices = np.random.permutation(np.arange(data_size))\n shuffled_data = data[shuffle_indices]\n else:\n shuffled_data = data\n \n for batch_num in range(num_batches_per_epoch):\n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, data_size)\n \n yield shuffled_data[start_index:end_index]\n \ndef next_batch(num, data, data_true, data_empty, shuffle=True):\n idx = np.arange(0 , len(data))\n if shuffle == True:\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n data_shuffle_true = [data_true[i] for i in idx]\n data_shuffle_empty = [data_empty[i] for i in idx] \n return np.asarray(data_shuffle),np.asarray(data_shuffle_true),np.asarray(data_shuffle_empty)\n\ndef next_test_batch(num, data, data_true,data_empty):\n idx = np.arange(0 , len(data))\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n data_shuffle_true = [data_true[i] for i in idx]\n data_shuffle_empty = [data_empty[i] for i in idx] \n return np.asarray(data_shuffle),np.asarray(data_shuffle_true),np.asarray(data_shuffle_empty)","sub_path":"data_processor.py","file_name":"data_processor.py","file_ext":"py","file_size_in_byte":10640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"377615771","text":"from torch import nn\n\nfrom semseg.device import Device\n\n\nclass Criterion(nn.Module):\n CEL = \"cross_entropy\"\n\n def __init__(self, device: Device, name=CEL, reduction=\"sum\"):\n super().__init__()\n\n if name == self.CEL:\n self._loss_func = nn.CrossEntropyLoss(\n reduction=reduction, ignore_index=255)\n else:\n msg = f\"NOT Supported: {name}\"\n raise ValueError(msg)\n\n self._loss_func.to(device.get())\n if device.isParallel:\n self._loss_func = nn.DataParallel(self._loss_func)\n\n def __call__(self, output, label):\n ret = self._loss_func(output, label).sum() / (\n output.shape[0] * output.shape[1] * output.shape[2] * output.shape[3])\n return ret\n","sub_path":"semseg/criterions/criterion.py","file_name":"criterion.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"502874458","text":"import argparse\nimport math\n\n\ndef score(A,B,mask):\n mask = mask.float()\n A,B = A.float(), B.float()\n D = ((A-B)*mask)**2\n avg = D.sum()/mask.sum()\n return math.sqrt(avg)\n\n\ndef match_size(A,B):\n x = A.shape[0]\n y = B.shape[0]\n k = abs(x-y)\n\n if x>y:\n A = A[:-k, :-k]\n elif x tp.Numpy:\r\n init = RFRNetModel()\r\n ret, mmask, fake, comp = init.buildnet(maskedimg, masks, images)\r\n loss, l1_loss = init.get_g_loss(ret, mmask, fake, comp)\r\n lr_scheduler = flow.optimizer.PiecewiseConstantScheduler([], [2e-4])\r\n # Set Adam optimizer\r\n flow.optimizer.Adam(lr_scheduler, do_bias_correction=False).minimize(loss)\r\n return l1_loss\r\n\r\n@flow.global_function(type=\"predict\", function_config=func_config)\r\ndef eval_job(images1: tp.Numpy.Placeholder((6, 3, 256, 256), dtype=flow.float),\r\n masks1: tp.Numpy.Placeholder((6, 3, 256, 256), dtype=flow.float),\r\n maskedimages1: tp.Numpy.Placeholder((6, 3, 256, 256), dtype=flow.float),\r\n ) -> Tuple[tp.Numpy, tp.Numpy, tp.Numpy]:\r\n init = RFRNetModel()\r\n fake_B = init.buildnetest(maskedimages1, masks1)\r\n comp_B1 = fake_B * (1 - masks1) + images1 * masks1\r\n\r\n return comp_B1, masks1, maskedimages1\r\n\r\n\r\ndef train(train_loader, save_path, vgg_path, finetune=False, iters=600000, batch_size=6, epochs=10, ssiter=0):\r\n # writer = SummaryWriter(log_dir=\"log_info\")\r\n # self.G.train(finetune = finetune)\r\n flow.load_variables(flow.checkpoint.get(vgg_path))\r\n # check_point = flow.train.CheckPoint()\r\n # check_point.load(vgg_path)\r\n # if finetune:\r\n # self.optm_G = optim.Adam(filter(lambda p:p.requires_grad, self.G.parameters()), lr = 5e-5)\r\n sum_l1 = 0.0\r\n batch_num = len(train_loader) // batch_size\r\n\r\n print(\"****************** start training *****************\")\r\n for epoch_idx in range(epochs):\r\n train_loader.shuffle(epoch_idx)\r\n print(\"Starting training from iteration:{:d}\".format(ssiter))\r\n s_time = time.time()\r\n while ssiter < iters:\r\n\r\n print(\"iters=\", iters)\r\n print(len(train_loader))\r\n for batch_idx in range(batch_num):\r\n #print(\"ssiter\", ssiter)\r\n imag = []\r\n maskk = []\r\n for idx in range(batch_size):\r\n sample1 = train_loader[batch_idx * batch_size + idx] # list输出是[2,256,256,3]\r\n sample = np.array(sample1)\r\n samp = np.transpose(sample, (0, 3, 1, 2)) # 已经是【2,3,256,256】\r\n samp1 = samp[None, 0, :, :, :]\r\n samp2 = samp[None, 1, :, :, :]\r\n imag.append(samp1)\r\n maskk.append(samp2)\r\n imag = np.ascontiguousarray(np.concatenate(imag, axis=0))\r\n imag2 = imag.astype(np.float32)\r\n maskk = np.ascontiguousarray(np.concatenate(maskk, axis=0))\r\n mask2 = maskk.astype(np.float32)\r\n # gt_images, masks = self.__cuda__(*items)\r\n masked_images = imag2 * mask2\r\n masked_image2 = masked_images.astype(np.float32)\r\n # self.forward(masked_images, masks, gt_images)\r\n # self.buildnet(masked_images, masks, gt_images) #global function\r\n # self.update_parameters()\r\n\r\n l1_loss_value = train_job(masked_image2, mask2, imag2)\r\n sum_l1 += l1_loss_value\r\n #print(l1_loss_value)\r\n # val_psnr += calc_psnr(sr, hr)\r\n # val_ssim += calc_ssim(sr, hr)\r\n ssiter += 1\r\n #\r\n if ssiter % 50 == 0:\r\n e_time = time.time()\r\n int_time = e_time - s_time\r\n print(\"Epoch:%d, Iteration:%d, l1_loss:%.4f, time_taken:%.2f\" % (epoch_idx,ssiter, sum_l1 / 50, int_time))\r\n s_time = time.time()\r\n sum_l1 = 0.0\r\n if ssiter % 300000 == 0:\r\n if not os.path.exists('{:s}'.format(save_path)):\r\n os.makedirs('{:s}'.format(save_path))\r\n save_ckpt('{:s}/epoch_{:d}_g_{:d}'.format(save_path,epoch_idx, ssiter))\r\n if not os.path.exists('{:s}'.format(save_path)):\r\n os.makedirs('{:s}'.format(save_path))\r\n save_ckpt('{:s}/epoch_{:d}_g_{:s}'.format(save_path,epoch_idx, \"final\"))\r\n\r\n\r\nclass RFRNetModel():\r\n def __init__(self):\r\n self.lossNet = None\r\n self.iter = None\r\n self.optm_G = None\r\n self.device = None\r\n self.real_A = None\r\n self.real_B = None\r\n self.fake_B = None\r\n self.comp_B = None\r\n self.l1_loss_val = 0.0\r\n self.G = RFRNet()\r\n\r\n def initialize_model(self, path=None, train=True, it=0):\r\n # self.G = RFRNet()\r\n # self.optm_G = optim.Adam(self.G.parameters(), lr = 2e-4)\r\n # if train:\r\n # self.lossNet = VGG16FeatureExtractor() #那在train里面加载vgg的参数就可以了\r\n try:\r\n load_ckpt(path)\r\n start_iter = it\r\n selfiter = start_iter\r\n if train:\r\n # self.optm_G = optim.Adam(self.G.parameters(), lr = 2e-4)\r\n print('Model Initialized, iter: ', start_iter)\r\n\r\n except:\r\n print('No trained model, from start')\r\n selfiter = 0\r\n return selfiter\r\n\r\n def vgg16bn(self, images, trainable=True, need_transpose=False, channel_last=False, training=True, wd=1.0 / 32768,\r\n reuse=False):\r\n\r\n def _get_regularizer():\r\n return flow.regularizers.l2(0.00005)\r\n\r\n def conv2d_layer(\r\n name,\r\n input,\r\n filters,\r\n kernel_size=3,\r\n strides=1,\r\n padding=\"SAME\",\r\n data_format=\"NCHW\",\r\n dilation_rate=1,\r\n activation=\"Relu\",\r\n use_bias=True,\r\n weight_initializer=flow.variance_scaling_initializer(2, 'fan_out', 'random_normal', data_format=\"NCHW\"),\r\n bias_initializer=flow.zeros_initializer(),\r\n\r\n bn=True,\r\n reuse=False,\r\n trainable=True\r\n ):\r\n time = datetime.datetime.now().strftime('%Y-%m-%d-%H_%M_%S_%f')\r\n name = name + str(time)\r\n name_ = name if reuse == False else name + \"_reuse\"\r\n weight_shape = (filters, input.shape[1], kernel_size, kernel_size)\r\n weight = flow.get_variable(\r\n name + \"_weight\",\r\n shape=weight_shape,\r\n dtype=input.dtype,\r\n initializer=weight_initializer,\r\n trainable=trainable\r\n )\r\n\r\n output = flow.nn.conv2d(\r\n input, weight, strides, padding, data_format, dilation_rate, name=name_\r\n )\r\n if use_bias:\r\n bias = flow.get_variable(\r\n name + \"_bias\",\r\n shape=(filters,),\r\n dtype=input.dtype,\r\n initializer=bias_initializer,\r\n trainable=trainable\r\n )\r\n output = flow.nn.bias_add(output, bias, data_format)\r\n\r\n if activation is not None:\r\n if activation == \"Relu\":\r\n if bn:\r\n # use of_layers(layers) batch_norm\r\n output = layers.batch_norm(output, name + \"_bn\", reuse=reuse)\r\n output = flow.nn.relu(output)\r\n else:\r\n output = flow.nn.relu(output)\r\n else:\r\n raise NotImplementedError\r\n return output\r\n\r\n def _conv_block(in_blob, index, filters, conv_times, reuse=False, trainable=True):\r\n conv_block = []\r\n conv_block.insert(0, in_blob)\r\n for i in range(conv_times):\r\n inputs = conv_block[i]\r\n conv_i = conv2d_layer(\r\n name=\"conv{}\".format(index),\r\n input=inputs,\r\n filters=filters,\r\n kernel_size=3,\r\n strides=1,\r\n bn=True,\r\n reuse=reuse,\r\n trainable=trainable\r\n )\r\n\r\n conv_block.append(conv_i)\r\n index += 1\r\n return conv_block\r\n\r\n if need_transpose:\r\n images = flow.transpose(images, name=\"transpose\", perm=[0, 3, 1, 2])\r\n if channel_last:\r\n # if channel_last=True, then change mode from 'nchw'to 'nhwc'\r\n images = flow.transpose(images, name=\"transpose\", perm=[0, 2, 3, 1])\r\n\r\n time = datetime.datetime.now().strftime('%Y-%m-%d-%H_%M_%S_%f')\r\n results = [images]\r\n conv1 = _conv_block(images, 0, 64, 2, reuse=reuse, trainable=trainable)\r\n # pool1 = flow.nn.max_pool2d(conv1[-1], 2, 2, \"VALID\", \"NCHW\", name=\"pool1\")\r\n pool1 = layers.max_pool2d(conv1[-1], 2, 2, name=\"pool1\" + str(time), reuse=reuse)\r\n results.append(pool1)\r\n\r\n conv2 = _conv_block(pool1, 2, 128, 2, reuse=reuse, trainable=trainable)\r\n # pool2 = flow.nn.max_pool2d(conv2[-1], 2, 2, \"VALID\", \"NCHW\", name=\"pool2\")\r\n pool2 = layers.max_pool2d(conv2[-1], 2, 2, name=\"pool2\" + str(time), reuse=reuse)\r\n results.append(pool2)\r\n\r\n conv3 = _conv_block(pool2, 4, 256, 3, reuse=reuse, trainable=trainable)\r\n pool3 = layers.max_pool2d(conv3[-1], 2, 2, name=\"pool3\" + str(time), reuse=reuse)\r\n results.append(pool3)\r\n return results[1:]\r\n def calc_psnr(self, img1, img2):\r\n ### args:\r\n # img1: [h, w, c], range [0, 255]\r\n # img2: [h, w, c], range [0, 255]\r\n diff = (img1 - img2)\r\n diff[:, :, 0] = diff[:, :, 0] * 25.738 / 256.0\r\n diff[:, :, 1] = diff[:, :, 1] * 25.057 / 256.0\r\n diff[:, :, 2] = diff[:, :, 2] * 25.064 / 256.0\r\n\r\n diff = np.sum(diff, axis=2)\r\n mse = np.mean(np.power(diff, 2))\r\n return -10 * math.log10(mse)\r\n #img1 = img1*255\r\n #img2 = img2*255\r\n #mse = np.mean( (img1 - img2) ** 2 )\r\n #mse = mse/3\r\n #if mse == 0:\r\n #return 100\r\n #PIXEL_MAX = 255.0\r\n #return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))\r\n \r\n def calc_ssim(self, img1, img2):\r\n def ssim(img1, img2):\r\n C1 = (0.01 * 255) ** 2\r\n C2 = (0.03 * 255) ** 2\r\n img1 = img1*255\r\n img2 = img2*255\r\n img1 = img1.astype(np.float64)\r\n img2 = img2.astype(np.float64)\r\n kernel = cv2.getGaussianKernel(11, 1.5)\r\n window = np.outer(kernel, kernel.transpose())\r\n\r\n mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid\r\n mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]\r\n mu1_sq = mu1 ** 2\r\n mu2_sq = mu2 ** 2\r\n mu1_mu2 = mu1 * mu2\r\n sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq\r\n sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq\r\n sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2\r\n\r\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) *\r\n (sigma1_sq + sigma2_sq + C2))\r\n return ssim_map.mean()\r\n\r\n ### args:\r\n # img1: [h, w, c], range [0, 255]\r\n # img2: [h, w, c], range [0, 255]\r\n # the same outputs as MATLAB's\r\n border = 0\r\n img1_y = np.dot(img1, [65.738, 129.057, 25.064]) / 256.0 + 16.0\r\n img2_y = np.dot(img2, [65.738, 129.057, 25.064]) / 256.0 + 16.0\r\n if not img1.shape == img2.shape:\r\n raise ValueError('Input images must have the same dimensions.')\r\n h, w = img1.shape[:2]\r\n img1_y = img1_y[border:h - border, border:w - border]\r\n img2_y = img2_y[border:h - border, border:w - border]\r\n\r\n if img1_y.ndim == 2:\r\n return ssim(img1_y, img2_y)\r\n elif img1.ndim == 3:\r\n if img1.shape[2] == 3:\r\n ssims = []\r\n for i in range(3):\r\n ssims.append(ssim(img1, img2))\r\n return np.array(ssims).mean()\r\n elif img1.shape[2] == 1:\r\n return ssim(np.squeeze(img1), np.squeeze(img2))\r\n else:\r\n raise ValueError('Wrong input image dimensions.')\r\n\r\n def test(self, test_loader, result_save_path, batch_size=6):\r\n # self.G.eval()\r\n # for para in self.G.parameters():\r\n # para.requires_grad = False\r\n\r\n count = 0\r\n batch_num = len(test_loader) // batch_size\r\n\r\n print(\"****************** start testing *****************\")\r\n\r\n # test_loader.shuffle(epoch_idx)\r\n\r\n print(len(test_loader))\r\n sum_ssim = 0.0\r\n sum_psnr = 0.0\r\n for batch_idx in range(batch_num):\r\n imag = []\r\n maskk = []\r\n for idx in range(batch_size):\r\n sample1 = test_loader[batch_idx * batch_size + idx] # list输出是[2,256,256,3]\r\n sample = np.array(sample1)\r\n samp = np.transpose(sample, (0, 3, 1, 2)) # 已经是【2,3,256,256】\r\n samp1 = samp[None, 0, :, :, :]\r\n samp2 = samp[None, 1, :, :, :]\r\n imag.append(samp1)\r\n maskk.append(samp2)\r\n imag = np.ascontiguousarray(np.concatenate(imag, axis=0))\r\n imag2 = imag.astype(np.float32)\r\n maskk = np.ascontiguousarray(np.concatenate(maskk, axis=0))\r\n mask2 = maskk.astype(np.float32)\r\n \r\n maskediii = imag2 * mask2\r\n\r\n comp, maskkk, maskedimage2 = eval_job(imag2, mask2, maskediii)\r\n if not os.path.exists('{:s}/results'.format(result_save_path)):\r\n os.makedirs('{:s}/results'.format(result_save_path))\r\n\r\n sum1_ssim = 0.0\r\n sum1_psnr = 0.0\r\n for k in range(comp.shape[0]):\r\n count += 1\r\n # grid = make_grid(comp[k:k + 1])\r\n\r\n transpose_comp = np.transpose(comp[k],(1,2,0))\r\n transpose_masked = np.transpose(maskediii[k]+1 - mask2[k] ,(1,2,0))\r\n \r\n ssim_sum = self.calc_ssim(transpose_comp,transpose_masked)\r\n psnr_sum = self.calc_psnr(transpose_comp,transpose_masked)\r\n sum1_psnr+=psnr_sum\r\n sum1_ssim+=ssim_sum\r\n\r\n\r\n # file_path = '{:s}/results/img_{:d}.png'.format(result_save_path, count)\r\n # np.save(file_path, transpose_comp)\r\n\r\n\r\n # file_path = '{:s}/results/masked_img_{:d}.png'.format(result_save_path, count)\r\n # np.save(file_path, transpose_masked)\r\n sum2_ssim = sum1_ssim/comp.shape[0]\r\n sum2_psnr = sum1_psnr/comp.shape[0]\r\n sum_ssim += sum2_ssim\r\n sum_psnr += sum2_psnr\r\n if batch_idx % 100 ==0:\r\n print(\"The batch is :\", batch_idx)\r\n print(\"the ssim is :\", sum2_ssim)\r\n print(\"the psnr is :\", sum2_psnr)\r\n total_ssim = sum_ssim/batch_num\r\n total_psnr = sum_psnr/batch_num\r\n print(\"The all batch is :\",batch_num)\r\n print(\"the avg of ssim :\",total_ssim)\r\n print(\"the avg of psnr :\",total_psnr)\r\n\r\n\r\n def buildnet(self, masked_image, mask, gt_image):\r\n # self.real_A = masked_image\r\n print(\"buildnet running\")\r\n\r\n A = masked_image\r\n # self.real_B = gt_image\r\n B = gt_image\r\n # self.mask = mask\r\n real_mask = mask\r\n fake_B1 = self.G.buildnet(masked_image, mask)\r\n\r\n # self.fake_B = fake_B\r\n # self.comp_B = self.fake_B * (1 - mask) + self.real_B * mask\r\n comp_B1 = fake_B1 * (1 - mask) + B * mask\r\n\r\n return B, real_mask, fake_B1, comp_B1\r\n\r\n def buildnetest(self, masked_image, mask):\r\n\r\n # self.real_A = masked_image\r\n print(\"buildnetest running\")\r\n\r\n A = masked_image\r\n\r\n real_mask = mask\r\n fake_B1 = self.G.buildnet(A, real_mask)\r\n\r\n # self.fake_B = fake_B\r\n # self.comp_B = self.fake_B * (1 - mask) + self.real_B * mask\r\n return fake_B1\r\n\r\n # def update_parameters(self):\r\n # self.update_G()\r\n # self.update_D()\r\n #\r\n # ef update_G(self):\r\n # self.optm_G.zero_grad()\r\n # loss_G = self.get_g_loss()\r\n # loss_G.backward()\r\n # self.optm_G.step()\r\n #\r\n # def update_D(self):\r\n # return\r\n\r\n def get_g_loss(self, B, real_mask, fake_B1, comp_B1):\r\n real_B = B\r\n fake_B = fake_B1\r\n comp_B = comp_B1\r\n\r\n # real_B_feats = self.lossNet(real_B)\r\n real_B_feats = self.vgg16bn(real_B)\r\n real_B_feats = np.array(real_B_feats)\r\n # fake_B_feats = self.lossNet(fake_B)\r\n fake_B_feats = self.vgg16bn(fake_B)\r\n fake_B_feats = np.array(fake_B_feats)\r\n # comp_B_feats = self.lossNet(comp_B)\r\n comp_B_feats = self.vgg16bn(comp_B)\r\n comp_B_feats = np.array(comp_B_feats)\r\n print(\"vgg16 running\")\r\n tv_loss = self.TV_loss(comp_B * (1 - real_mask))\r\n style_loss = self.style_loss(real_B_feats, fake_B_feats) + self.style_loss(real_B_feats, comp_B_feats)\r\n preceptual_loss = self.preceptual_loss(real_B_feats, fake_B_feats) + self.preceptual_loss(real_B_feats,\r\n comp_B_feats)\r\n valid_loss = self.l1_loss(real_B, fake_B, real_mask)\r\n hole_loss = self.l1_loss(real_B, fake_B, (1 - real_mask))\r\n\r\n loss_G = (tv_loss * 0.1\r\n + style_loss * 120\r\n + preceptual_loss * 0.05\r\n + valid_loss * 1\r\n + hole_loss * 6)\r\n # self.l1_loss_val += valid_loss.detach() + hole_loss.detach()\r\n l1_loss_val = valid_loss + hole_loss\r\n return loss_G, l1_loss_val\r\n\r\n def l1_loss(self, f1, f2, mask=1):\r\n # return torch.mean(torch.abs(f1 - f2)*mask)\r\n return flow.math.reduce_mean(flow.math.abs(f1 - f2) * mask)\r\n\r\n def style_loss(self, A_feats, B_feats):\r\n assert len(A_feats) == len(B_feats), \"the length of two input feature maps lists should be the same\"\r\n loss_value = 0.0\r\n for i in range(len(A_feats)):\r\n A_feat = A_feats[i]\r\n # A_feat = flow.slice(x=A_feats,begin=[i,None,None,None,None],size=[1,None,None,None,None])\r\n # A_feat = flow.squeeze(input=A_feat,axis=[0])\r\n B_feat = B_feats[i]\r\n # B_feat = flow.slice(x=B_feats, begin=[i, None, None, None,None], size=[1, None, None, None,None])\r\n # B_feat = flow.squeeze(input=B_feat, axis=[0])\r\n # _, c, w, h = A_feat.size()\r\n _, c, w, h = A_feat.shape\r\n # A_feat = A_feat.view(A_feat.size(0), A_feat.size(1), A_feat.size(2) * A_feat.size(3))\r\n A_feat = flow.reshape(A_feat, [A_feat.shape[0], A_feat.shape[1], A_feat.shape[2] * A_feat.shape[3]])\r\n # B_feat = B_feat.view(B_feat.size(0), B_feat.size(1), B_feat.size(2) * B_feat.size(3))\r\n B_feat = flow.reshape(B_feat, [B_feat.shape[0], B_feat.shape[1], B_feat.shape[2] * B_feat.shape[3]])\r\n # A_style = torch.matmul(A_feat, A_feat.transpose(2, 1))\r\n A_style = flow.matmul(A_feat, flow.transpose(A_feat, perm=[0, 2, 1]))\r\n # B_style = torch.matmul(B_feat, B_feat.transpose(2, 1))\r\n B_style = flow.matmul(B_feat, flow.transpose(B_feat, perm=[0, 2, 1]))\r\n loss_value += flow.math.reduce_mean(flow.math.abs(A_style - B_style) / (c * w * h))\r\n return loss_value\r\n\r\n def TV_loss(self, x):\r\n # h_x = x.size(2)\r\n h_x = x.shape[2]\r\n # w_x = x.size(3)\r\n w_x = x.shape[3]\r\n k1 = flow.slice(x=x, begin=[None, None, 1, None], size=[None, None, h_x - 1, None])\r\n k1 = flow.squeeze(input=k1, axis=[2])\r\n k2 = flow.slice(x=x, begin=[None, None, 0, None], size=[None, None, h_x - 1, None])\r\n k2 = flow.squeeze(input=k2, axis=[2])\r\n h_tv = flow.math.reduce_mean(flow.math.abs(k1 - k2))\r\n k3 = flow.slice(x=x, begin=[None, None, None, 1], size=[None, None, None, w_x - 1])\r\n k3 = flow.squeeze(input=k3, axis=[3])\r\n k4 = flow.slice(x=x, begin=[None, None, None, 0], size=[None, None, None, w_x - 1])\r\n k4 = flow.squeeze(input=k4, axis=[3])\r\n w_tv = flow.math.reduce_mean(flow.math.abs(k3 - k4))\r\n return h_tv + w_tv\r\n\r\n def preceptual_loss(self, A_feats, B_feats):\r\n assert len(A_feats) == len(B_feats), \"the length of two input feature maps lists should be the same\"\r\n loss_value = 0.0\r\n for i in range(len(A_feats)):\r\n A_feat = A_feats[i]\r\n # A_feat = flow.slice(x=A_feat, begin=[i, None, None, None], size=[1, None, None, None])\r\n # A_feat = flow.squeeze(input=A_feat, axis=[0])\r\n B_feat = B_feats[i]\r\n # B_feat = flow.slice(x=B_feat, begin=[i, None, None, None], size=[1, None, None, None])\r\n # B_feat = flow.squeeze(input=B_feat, axis=[0])\r\n loss_value += flow.math.reduce_mean(flow.math.abs(A_feat - B_feat))\r\n return loss_value\r\n\r\n\r\n\r\n","sub_path":"RFR-Inpainting/rightmodel.py","file_name":"rightmodel.py","file_ext":"py","file_size_in_byte":22736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"56694880","text":"from django.shortcuts import render,get_object_or_404, redirect\nfrom django.http import HttpResponse\nfrom ..models import Question, Answer, Comment\nfrom django.utils import timezone\nfrom ..forms import QuestionForm,AnswerForm,CommentForm\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\n\n@login_required(login_url='common:login')\ndef answer_create(request,question_id):\n question=get_object_or_404(Question,pk=question_id)\n if request.method==\"POST\":\n form=AnswerForm(request.POST)\n if form.is_valid():\n answer=form.save(commit=False)\n answer.author=request.user\n answer.create_date=timezone.now()\n answer.question=question\n answer.save()\n #insert into answer values(question_id,content,create_date)\n return redirect('pybo:detail',question_id=question.id)\n else:\n form=AnswerForm()\n context={'question':question,'form':form}\n return render(request,'pybo/question_detail.html',context)\n\n\n@login_required(login_url='common:login')\ndef answer_modify(request,answer_id):\n answer=get_object_or_404(Answer,pk=answer_id)\n if request.user!=answer.author:\n messages.error(request,'수정권한이 없습니다.')\n return redirect('pybo:detail',question_id=answer.question.id)\n if request.method==\"POST\":\n form=AnswerForm(request.POST,instance=answer)\n if form.is_valid():\n answer=form.save(commit=False)\n answer.author=request.user\n answer.modify_date=timezone.now()\n answer.save()\n return redirect('pybo:detail',question_id=answer.question.id)\n else:\n form=AnswerForm(instance=answer)\n context={'answer':answer,'form':form}\n return render(request,'pybo/answer_form.html',context)\n\n@login_required(login_url='common:login')\ndef answer_delete(request,answer_id):\n answer=get_object_or_404(Answer,pk=answer_id)\n if request.user != answer.author:\n messages.error(request,'삭제권한이 없습니다.')\n else:\n answer.delete()\n return redirect('pybo:detail',question_id=answer.question.id)\n\n","sub_path":"pybo/views/answer_views.py","file_name":"answer_views.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"68263468","text":"from django.shortcuts import render, redirect\nfrom .models import Contact\nfrom django.core.mail import send_mail\nfrom django.contrib import messages\nfrom tmonyblog.settings import EMAIL_HOST_USER\n\n\n\n# Create your views here.\ndef contact (request):\n if request.method== 'POST':\n name = request.POST['name']\n email = request.POST['email']\n phone=request.POST['phone']\n subject = request.POST['subject']\n message = request.POST['message']\n subjects= subject , phone\n\n contact = Contact(name=name, email=email, message=message,subject=subjects)\n contact.save()\n send_mail(\n subject,\n message,\n EMAIL_HOST_USER,\n ['adetulatestimony@gmail.com'],\n fail_silently=False,\n ) \n messages.success(request, 'Thanks for reaching out to us at Blogbox')\n return redirect('contact')\n else:\n content={\n\n }\n return render(request,'contact.html',content)","sub_path":"contacts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"298256904","text":"import dis\ndef cond():\n x=3\n if x<5:\n return 'yes'\n else:\n return 'no'\ndef loop():\n x=1\n while x<5:\n x=x+1\n return x\ndef loop2():\n x=1\n for i in range(1,5):\n x+=1\n return x\ndef test3():\n return [x for x in range(4)]\ndef loop():\n x = 1\n while x < 5:\n if x==3:\n break\n x = x + 1\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n # print(cond())\n # print(cond.__code__)\n # print(cond.__code__.co_code)\n # temp=list(bytearray(cond.__code__.co_code))\n # print(temp,len(temp))\n # print(dis.dis(cond))\n # # print(dis.opname[100])\n # # print(loop())\n # # print(loop2())\n # # print(dis.dis(loop))\n # print(dis.dis(test3))\n # print([(i, dis.opname[i]) for i in dis.hasname])\n # print(dis.opname[100])\n print(list(bytearray(loop.__code__.co_code)))\n print(dis.dis(loop))","sub_path":"12.interpreter/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"289493989","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 19 09:29:24 2019\n\n@author: SRIJAN\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndf = pd.read_csv('dataset/train_E6oV3lV.csv', encoding='latin-1')\ndf.head()\n\nsns.countplot(df.label)\nplt.xlabel('Label')\nplt.ylabel('Number of Tweets')\n\ndf['length'] = df['tweet'].apply(len)\nmpl.rcParams['patch.force_edgecolor'] = True\nplt.style.use('seaborn-bright')\ndf.hist(column='length', by='label', bins=50, figsize=(11,5))\n\nhate_words = ['hate', 'kill', 'racist', 'racism', 'black', 'motherfucker', 'white','libtard', 'amp', 'misogynist']\n\nimport re\nimport string\nimport nltk\nfrom nltk.stem import WordNetLemmatizer \n\n# nltk.download('stopwords') #only if you have not downloaded the stopwords of nltk\ndef preprocess_text(text):\n # remove all punctuation\n text = re.sub(r'[^\\w\\d\\s]', ' ', text)\n # convert to lower case\n text = re.sub(r'^\\s+|\\s+?$', '', text.lower()) \n # remove superscripts numbers\n #text = re.sub(r'\\p{No}', ' ', text)\n # remove other unwanted characters\n text = re.sub(r'\\d', '', text)\n text = re.sub('ã', '', text)\n text = re.sub('â', '', text)\n text = re.sub('user', '', text)\n text = re.sub('µ', '', text)\n text = re.sub('¼', '', text)\n text = re.sub('¾', '', text)\n text = re.sub('½', '', text)\n text = re.sub('³', '', text)\n text = re.sub('ª', '', text)\n text = re.sub('º', '', text)\n text = re.sub('¹', '', text) \n text = re.sub('²', '', text)\n \n # collapse all white spaces\n text = re.sub(r'\\s+', ' ', text)\n # remove stop words and perform stemming\n stop_words = nltk.corpus.stopwords.words('english')\n lemmatizer = WordNetLemmatizer() \n return ' '.join(\n lemmatizer.lemmatize(term) \n for term in text.split()\n if term not in set(stop_words)\n )\n\ndf['processed_text'] = df.tweet.apply(lambda row : preprocess_text(row))\ndf.head()\n\ndef hate_label(text):\n \n for term in text.split():\n if term in hate_words:\n return 1\n else:\n continue\n \n\ndf['hate_label'] = df.processed_text.apply(lambda row : hate_label(row))\ndf['hate_label'] = df['hate_label'].fillna(0)\ndf.head()\n\ndf.hist(column='hate_label', by='label', bins=50, figsize=(11,5))\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"eda.py","file_name":"eda.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"220354151","text":"# https://leetcode.com/problems/expressive-words/description/\nclass Solution:\n def expressiveWords(self, S, words):\n \"\"\"\n :type S: str\n :type words: List[str]\n :rtype: int\n \"\"\" \n return sum(self.check(S, W) for W in words)\n def check(self, S, W):\n i, j, i2, j2, n, m = 0, 0, 0, 0, len(S), len(W)\n while i < n and j < m:\n if S[i] != W[j]: return False\n while i2 < n and S[i2] == S[i]: i2 += 1\n while j2 < m and W[j2] == W[j]: j2 += 1\n if i2 - i != j2 - j and i2 - i < max(3, j2 - j): return False\n i, j = i2, j2\n return i == n and j == m","sub_path":"code/809#Expressive Words.py","file_name":"809#Expressive Words.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"249595416","text":"import sys\nsys.path.append('/global/homes/p/peterm/petermpython')\nsys.path.append('/global/homes/p/peterm/paperplots/python/scripts')\nimport os\nimport numpy as np\nimport time\nfrom planck import Planck\nfrom planck.metadata import latest_exchange\nfrom glob import glob\nimport pyfits\nimport testenv\nfrom planck.metadata import latest_exchange\nimport datetime\nfrom planck_util_prm import get_ucds\n\nnow=datetime.datetime.now()\nformatted_date= now.strftime(\"%Y%m%d\")\nfreq=int(sys.argv[1])\ngmf={}\nprint(freq)\t\nucds=get_ucds(db='/global/homes/p/peterm/ucds-dx11-delta.db', freq=freq)\nkeys=ucds.keys()\nfor key in keys:\n\tfor d in ['0','1']:\n\t\tuchan=key+d\n\t\tprint(uchan)\n\t\tdchan=uchan.replace('S','S1')\n\t\tdchan=dchan.replace('M','M0')\n\t\tgmf[dchan]=np.mean(ucds[key]['vsky'+d])/np.mean(ucds[key]['vref'+d])\n\nconf={}\nconf['cal_tag']='usp_1'\npl=Planck()\n\nweights=np.genfromtxt('/global/homes/p/peterm/weights_march15_2010.txt',dtype=str,skip_header=1,autostrip=True,delimiter=',')\ndiodeweights={}\nfor weight in weights:\n\tdiodeweights[weight[0]]=float(weight[1])\n\ndef get_raw_diff(chan,targetod,effobt,gmf,diodeweights,rawdir='/global/scratch2/sd/planck/user/peterm/rawdata/adc_12_corrected/'):\n\t#function to grab 3 OD's of raw data (+-1 od), cut to match eff obt, difference and return\n\thorn=chan[3:5]\n\trad=chan[-1]\n\tdiodes={}\n\tdiodes['M']=['00','01']\n\tdiodes['S']=['10','11']\n\tdiff=np.zeros(len(effobt))\n\tfor dnum,diode in enumerate(diodes[rad]):\n\t\tsky=np.array([])\n\t\tref=np.array([])\n\t\trawobt=np.array([])\n\t\tfor od in [targetod-1,targetod,targetod+1]:\n\t\t\trawfile=rawdir+'/od%s_rca%s%s.fits' %(str(od),horn,diode)\n\t\t\tif not(os.path.exists(rawfile)):\n\t\t\t\tprint('no raw file',rawfile)\n\t\t\t\tstat=False\n\t\t\t\treturn stat,diff\n\t\t\thdulist=pyfits.open(rawfile)\n\t\t\trawobt=np.concatenate([rawobt,hdulist[1].data['TIME']])\n\t\t\tsky=np.concatenate([sky,hdulist[1].data['SKY']])\n\t\t\tref=np.concatenate([ref,hdulist[1].data['REF']])\n\t\tsky=sky[(rawobt>=effobt[0]) & (rawobt<=effobt[-1])]\n\t\tref=ref[(rawobt>=effobt[0]) & (rawobt<=effobt[-1])]\n\t\t#cut to match effobt\n\t\tif dnum==0:\n\t\t\trawobt=rawobt[(rawobt>=effobt[0]) & (rawobt<=effobt[-1])]\n\t\t\trawdiff = np.interp(effobt,rawobt,diodeweights[chan+'-'+diode]*(sky-ref*gmf[chan+diode]))\n\t\telse:\n\t\t\trawobt=rawobt[(rawobt>=effobt[0]) & (rawobt<=effobt[-1])]\n\t\t\trawdiff += np.interp(effobt,rawobt,diodeweights[chan+'-'+diode]*(sky-ref*gmf[chan+diode]))\n\t\t\tdiff=rawdiff\n\t\tstat=True\n\tif np.isnan(diff).sum() != 0:\n\t\tstat=False \n\treturn stat,diff\n\t\nbadlist=[]\n\nfor od in range(91,1605):\n\tprint(od)\n\tif od==1540:\n\t\tcontinue\n\tfilename = '%s%03d-%04d-%s-%s.fits' % (\"L\", freq, od, \"C\", formatted_date)\n\toutput_folder = \"/global/scratch2/sd/planck/user/peterm/data/%s/%04d/\" % (conf[\"cal_tag\"], od)\n\tif os.path.isfile(output_folder+filename):\n\t\tcontinue\n\tefftype = \"C\"\n\teff_infilename = latest_exchange(freq, ods=od, exchangefolder = \"/project/projectdirs/planck/data/mission/lfi_ops_dx11_delta/\", type = efftype)\n\twith pyfits.open(eff_infilename) as eff_infile:\n\t\tch = pl.f[freq].ch[0]\n\t\tchans = [ext.name for ext in eff_infile[2:]]# if ch.tag.replace(\"-\",\"_\").upper() in ext.name] \n\t\tfor chan in chans:\n\t\t\teffobt=eff_infile['OBT'].data['OBT']\n\t\t\tstat,diffdata=get_raw_diff(chan,od,effobt,gmf,diodeweights)\n\t\t\tif stat==False:\n\t\t\t\tprint('some Nans, od= ',od)\n\t\t\teff_infile[chan].data[chan] = diffdata \n\t\tif stat==False:\n\t\t\tbadlist.append(od)\n\t\t\tcontinue\n\t\ttry:\n\t\t\tos.mkdir(output_folder)\n\t\texcept:\n\t\t\tpass\n\t\teff_infile.writeto(output_folder + filename, clobber=True)","sub_path":"differencing_script.py","file_name":"differencing_script.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"45730007","text":"from django.shortcuts import render\r\nfrom django.http import HttpResponse,JsonResponse\r\nfrom utils import Paginator\r\nfrom df_user import decorator\r\nfrom . import models\r\n# Create your views here.\r\n\r\n@decorator.login\r\ndef index(request):\r\n typelist = models.TypeInfo.objects.all()\r\n goods_new,goods_click = {},{}\r\n for type in typelist:\r\n goods_new[type.id]=type.goodsinfo_set.order_by('-id')[0:4]\r\n goods_click[type.id] = type.goodsinfo_set.order_by('-gclick')[0:4]\r\n context = {\r\n 'title': '首页',\r\n 'typelist':typelist,\r\n 'goods_new':goods_new,\r\n 'goods_click':goods_click,\r\n }\r\n return render(request,'df_goods/index.html',context)\r\n\"\"\"\r\nsort:排序(0-默认-id)(1-价格)(2-点击量)\r\n\"\"\"\r\n@decorator.login\r\ndef list(request,type_id,sort,page_num):\r\n selected_type = models.TypeInfo.objects.filter(id=type_id).first()\r\n adv_goods = selected_type.goodsinfo_set.filter(gadv=True)[0:2]\r\n if sort == 0:\r\n goods_list = selected_type.goodsinfo_set.order_by('-id')\r\n elif sort == 1:\r\n goods_list = selected_type.goodsinfo_set.order_by('gprice')\r\n elif sort == 2:\r\n goods_list = selected_type.goodsinfo_set.order_by('-gclick')\r\n\r\n paginator = Paginator.CustomPaginator(goods_list,10)\r\n page = paginator.page(page_num)\r\n page_num_range = paginator.page_num_range(page_num)\r\n context = {\r\n 'sort':sort,\r\n 'selected_type':selected_type,\r\n 'adv_goods':adv_goods,\r\n 'page':page,\r\n 'page_num_range':page_num_range,\r\n }\r\n return render(request,'df_goods/list.html',context)\r\n\r\n\r\n@decorator.login\r\ndef detail(request,goods_id):\r\n goods = models.GoodsInfo.objects.filter(id=goods_id)[0]\r\n goods.gclick += 1\r\n goods.save()\r\n\r\n adv_goods = models.GoodsInfo.objects.filter(gtype_id = goods.gtype.id,gadv=True)[0:2]\r\n context = {\r\n 'title':goods.gtype.ttitle,\r\n 'goods':goods,\r\n 'adv_goods':adv_goods,\r\n }\r\n\r\n response = render(request, 'df_goods/detail.html', context)\r\n # 记录最近浏览,在用户中心使用\r\n if request.session.has_key('user_id'): # 判断是否已经登录\r\n goods_ids = request.COOKIES.get('goods_ids', '') # 获取浏览记录, 获取的值为str型\r\n\r\n goods_id = str(goods.id) # 将int型转化为str类型\r\n if goods_ids != '': # 判断是否有浏览记录,如果则继续判断\r\n goods_ids1 = goods_ids.split(',') # 以逗号分隔切片 切片后为list型\r\n if goods_ids1.count(goods_id) >= 1: # 如果已经存在,删除掉\r\n goods_ids1.remove(goods_id)\r\n goods_ids1.insert(0, goods_id) # 添加到第一个\r\n if len(goods_ids1) >= 6: # 如果超过6个则删除最后一个\r\n del goods_ids1[5]\r\n goods_ids = ','.join(goods_ids1) # 's'.join(seq) 以s作为分隔符,将seq所有的元素合并成一个新的字符串,为str型\r\n else:\r\n goods_ids = goods_id # 如果没有记录则直接加 , str型\r\n\r\n response.set_cookie('goods_ids', goods_ids) # 写入cookie\r\n return response\r\n\r\n","sub_path":"dailyfresh2/df_goods/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"598975338","text":"\nimport numpy as np\nimport matplotlib\nfrom scipy.linalg import eigh\n\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nnp.random.seed(1)\n\n\ndef data_generation(n=1000):\n a = 3. * np.pi * np.random.rand(n)\n x = np.stack(\n [a * np.cos(a), 30. * np.random.random(n), a * np.sin(a)], axis=1)\n return a, x\n\n\ndef LapEig(x, d=2, k=10):\n W = []\n for x_i in x:\n threshold = np.array([np.dot(x_i - x_j, x_i - x_j) for x_j in x]).argsort()[:k]\n knn_list = list(map(lambda x: x in threshold, np.arange(x.shape[0])))\n W.append(knn_list)\n W = np.array(W)\n W = np.where(np.logical_or(W, W.T), 1, 0)\n \n D = np.diag(W.sum(axis=1))\n L = D - W\n \n eig_val, eig_vec = eigh(L, D)\n eig_vec = eig_vec.T\n indexs = np.argsort(eig_val)\n eig_vec = eig_vec[indexs]\n phi = eig_vec[1:d+1]\n \n return phi.T\n\ndef visualize(x, z, a):\n fig = plt.figure(figsize=(12, 6))\n ax = fig.add_subplot(1, 2, 1, projection='3d')\n ax.scatter3D(x[:, 0], x[:, 1], x[:, 2], c=a, marker='o')\n ax = fig.add_subplot(1, 2, 2)\n ax.scatter(z[:, 0], z[:, 1], c=a, marker='o')\n fig.savefig('report.png')\n\n\na, x = data_generation()\nz = LapEig(x)\nvisualize(x, z, a)\n","sub_path":"report12.py","file_name":"report12.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"533942230","text":"\"\"\" Fixtures file for template version manager\n\"\"\"\nfrom core_main_app.components.template.models import Template\nfrom core_main_app.components.template_version_manager.models import (\n TemplateVersionManager,\n)\nfrom core_main_app.utils.integration_tests.fixture_interface import (\n FixtureInterface,\n)\n\n\nclass TemplateVersionManagerFixtures(FixtureInterface):\n \"\"\"Template Version Manager fixtures\"\"\"\n\n template_1_1 = None\n template_1_2 = None\n template_1_3 = None\n template_2_1 = None\n template_vm_1 = None\n template_vm_2 = None\n template_vm_collection = None\n\n def insert_data(self):\n \"\"\"Insert a set of Templates and Template Version Managers.\n\n Returns:\n\n \"\"\"\n self.template_vm_1 = TemplateVersionManager(\n title=\"template 1\",\n user=None,\n is_disabled=False,\n )\n self.template_vm_1.save_version_manager()\n self.template_1_1 = Template(\n filename=\"template1_1.xsd\",\n content=\"content1_1\",\n hash=\"hash1_1\",\n version_manager=self.template_vm_1,\n )\n self.template_1_1.save()\n self.template_1_2 = Template(\n filename=\"template1_2.xsd\",\n content=\"content1_2\",\n hash=\"hash1_2\",\n is_disabled=True,\n version_manager=self.template_vm_1,\n )\n self.template_1_2.save()\n self.template_1_3 = Template(\n filename=\"template1_3.xsd\",\n content=\"content1_3\",\n hash=\"hash1_3\",\n is_current=True,\n version_manager=self.template_vm_1,\n )\n self.template_1_3.save()\n\n self.template_vm_2 = TemplateVersionManager(\n title=\"template 2\",\n user=\"1\",\n is_disabled=False,\n )\n self.template_vm_2.save_version_manager()\n self.template_2_1 = Template(\n filename=\"template2_1.xsd\",\n content=\"content2_1\",\n hash=\"hash2_1\",\n is_current=True,\n version_manager=self.template_vm_2,\n )\n self.template_2_1.save()\n\n self.template_vm_collection = [self.template_vm_1, self.template_vm_2]\n\n\nclass TemplateVersionManagerAccessControlFixtures(FixtureInterface):\n \"\"\"Template Version Manager fixtures\"\"\"\n\n user1_template = None\n user2_template = None\n global_template = None\n user1_tvm = None\n user2_tvm = None\n global_tvm = None\n template_vm_collection = None\n\n def insert_data(self):\n \"\"\"Insert a set of Templates and Template Version Managers.\n\n Returns:\n\n \"\"\"\n # Make a connexion with a mock database\n xsd = (\n ''\n ''\n )\n\n self.user1_tvm = TemplateVersionManager(\n title=\"template 1\",\n user=\"1\",\n is_disabled=False,\n )\n self.user1_tvm.save_version_manager()\n\n self.user2_tvm = TemplateVersionManager(\n title=\"template 2\",\n user=\"2\",\n is_disabled=False,\n )\n self.user2_tvm.save_version_manager()\n\n self.global_tvm = TemplateVersionManager(\n title=\"global template\",\n user=None,\n is_disabled=False,\n )\n self.global_tvm.save_version_manager()\n\n self.user1_template = Template(\n filename=\"template1.xsd\",\n content=xsd,\n hash=\"hash1\",\n user=\"1\",\n is_current=True,\n version_manager=self.user1_tvm,\n )\n self.user1_template.save()\n self.user2_template = Template(\n filename=\"template2.xsd\",\n content=xsd,\n hash=\"hash2\",\n user=\"2\",\n is_current=True,\n version_manager=self.user2_tvm,\n )\n self.user2_template.save()\n self.global_template = Template(\n filename=\"global_template.xsd\",\n content=xsd,\n hash=\"global hash\",\n user=None,\n is_current=True,\n version_manager=self.global_tvm,\n )\n self.global_template.save()\n\n self.template_vm_collection = [\n self.user1_tvm,\n self.user2_tvm,\n self.global_tvm,\n ]\n\n\nclass TemplateVersionManagerOrderingFixtures(FixtureInterface):\n \"\"\"Template Version Manager Ordering fixtures\"\"\"\n\n user1_template = None\n global_template = None\n tvm1 = None\n tvm2 = None\n global_tvm1 = None\n global_tvm2 = None\n template_vm_collection = None\n\n def insert_data(self):\n \"\"\"Insert a set of Templates and Template Version Managers.\n\n Returns:\n\n \"\"\"\n # Make a connexion with a mock database\n xsd = (\n ''\n ''\n )\n\n self.tvm1 = TemplateVersionManager(\n title=\"template 1\",\n user=\"1\",\n is_disabled=False,\n )\n self.tvm1.save_version_manager()\n\n self.tvm2 = TemplateVersionManager(\n title=\"template 2\",\n user=\"1\",\n is_disabled=False,\n )\n self.tvm2.save_version_manager()\n\n self.global_tvm1 = TemplateVersionManager(\n title=\"global template1\",\n user=None,\n is_disabled=False,\n )\n self.global_tvm1.save_version_manager()\n\n self.global_tvm2 = TemplateVersionManager(\n title=\"global template2\",\n user=None,\n is_disabled=False,\n )\n self.global_tvm2.save_version_manager()\n\n self.user1_template = Template(\n filename=\"template1.xsd\",\n content=xsd,\n hash=\"hash1\",\n user=\"1\",\n is_current=True,\n version_manager=self.tvm1,\n )\n self.user1_template.save()\n\n self.global_template = Template(\n filename=\"global_template.xsd\",\n content=xsd,\n hash=\"global hash\",\n user=None,\n is_current=True,\n version_manager=self.global_tvm1,\n )\n self.global_template.save()\n\n self.template_vm_collection = [\n self.tvm1,\n self.tvm2,\n self.global_tvm1,\n self.global_tvm2,\n ]\n","sub_path":"tests/components/template_version_manager/fixtures/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":6470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"537428255","text":"from configparser import ConfigParser\nimport datetime\nimport nltk\nfrom pathlib import Path\n\nfrom .model.logger import Logger\nfrom .model.trainer import SpanTrainer\n\n\ncfg = None\ntrainer = None\nlogger = None\n\n\ndef entity_query(source):\n jsentences = nltk.sent_tokenize(source)\n jtokens = [nltk.word_tokenize(jsentence) for jsentence in jsentences]\n print(jtokens)\n\n # Parse document\n jdocument = []\n for jtoken in jtokens:\n doc = {\"tokens\": jtoken, \"entities\": []}\n jdocument.append(doc)\n logger.info('Document Parsed:\\n%s' % jdocument)\n\n # Predict\n start_time = datetime.datetime.now()\n jpredictions = trainer.eval(jdoc=jdocument)\n end_time = datetime.datetime.now()\n logger.info('Predicting time : %d' % (end_time - start_time).seconds)\n\n return jpredictions\n\n\ndef inst_entity():\n global cfg\n global trainer\n global logger\n cfg = ConfigParser()\n configuration_path = Path(__file__).resolve(strict=True).parent / 'configs' / 'entity_eval.conf'\n cfg.read(configuration_path)\n logger = Logger(cfg)\n logger.info('Configuration Parsed: %s' % cfg.sections())\n trainer = SpanTrainer(cfg, logger)\n","sub_path":"sciencehammer/application/entity/entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"374978175","text":"import csv\nimport os\nimport string\nimport math\nimport scipy\nimport scipy.integrate\nimport warnings\nfrom autograd.scipy.integrate import odeint\nimport autograd.numpy as agnp\nimport numdifftools as nd\nimport copy\nimport pandas as pd\nimport numpy as np\nfrom holoviews import opts\nimport bootcamp_utils.hv_defaults\nimport numdifftools as nd\nimport bokeh.io\n\nimport holoviews as hv\n\n\nimport panel as pn\npn.extension()\n\n\nbokeh.io.output_notebook()\nhv.extension('bokeh')\n\n\nimport IPython.display\n\n\nfrom collections import namedtuple\nSimulationData = namedtuple(\"SimulationData\", [\"params\", \"ts\", \"solution\"])\n\ndef moving_average(a, n=3):\n \n sums = np.zeros(len(a) - n)\n st = len(a) - n\n for i in range(st):\n \n sums[i] = np.max(a[i:i + n])\n \n \n return sums\ndef simulate(system_dv_dt, params, state_inits, t_max, n_times):\n '''\n Run a scipy simulation. \n \n Params:\n system_dv_dt: A function that takes the parameters xs and params, in that order,\n where xs is a state vector of the system and params is a list of \n parameters, and returns the derivative of the system.\n params: A (numpy array) vector of parameters.\n state_inits: A (numpy array) vector of initial states.\n t_max: Time to simulate out to, in (arbitrary) seconds.\n n_times: The number of points to record. The higher this number, the higher\n the time resolution of the simulation.\n \n Returns: A SimulationData object, which is a named tuple containing params,\n ts (times, as a n_times-long vector), and solution (as a <# species>x\n numpy array). \n '''\n t0 = 0\n dt = (t_max - t0) / n_times\n ts = np.linspace(t0, t_max, n_times)\n\n def dv_dt(t, xs):\n return system_dv_dt(xs, params)\n \n ode = scipy.integrate.ode(dv_dt).set_integrator('lsoda')#, method='bdf', order = 5)\n ode.set_initial_value(state_inits, t0)\n solution = np.zeros((n_times, len(state_inits)))\n solution[0,:] = state_inits\n i = 1\n while ode.successful() and ode.t < t_max and i < n_times:\n solution[i,:] = ode.integrate(ode.t+dt)\n i += 1\n\n return SimulationData(params = params, ts = ts, solution = solution)\n\n\ndef pos_hill(X, k, n):\n Xn = X**n\n kn = k**n\n \n return Xn/(Xn + kn)\n\ndef neg_hill(X, k, n):\n Xn = X**n\n kn = k**n\n return kn/(Xn + kn)\n\ndef find_ss_opt(dv_dt_generator, params, state_inits, debug = False, \n max_iters = 5000, tol = 1e-3, verbose=False):\n '''\n Calculate the (non-zero) steady-state vector, if one can\n be found, using Scipy to find zeroes of the ODEs for the system.\n\n params (partial):\n init_state: Initial condition for search. \n max_iters: If a steady state value is found with negative\n concentration of any species (or zero concentration of\n all species), a new seed will be chosen and the\n algorithm will try again, up to max_iters times.\n verbose: Determines whether certain warnings will be printed.\n\n Searches from init_state (within bounds) and looks for a root.\n If it's zero, repeat some number of times before giving up. Raises an\n error if no steady state value found.\n '''\n dv_dt = dv_dt_generator(params)\n\n def opt_func(state):\n return dv_dt(state)\n\n def try_optimization(init_state):\n # Define function for calculating Jacobian\n jacobian_at = nd.Jacobian(opt_func)\n# with warnings.catch_warnings():\n# warnings.filterwarnings(\"error\",\n# message = \"The iteration is not making good progress.*\")\n# try:\n ss_vector, info, ier, mesg = \\\n scipy.optimize.fsolve(opt_func, state_inits,\n fprime = jacobian_at, \n full_output = 1)\n # ss = optimize.root(opt_func, [0, 0], jac=jac, method='hybr')\n #ss_vector = ss.x\n if verbose:\n print(\"ss_vector: \" + str(ss_vector))\n print(\"info: \" + str(info))\n print(\"ier: \" + str(ier))\n print(\"mesg: \" + str(mesg))\n if np.any(np.abs(info['fvec']) > tol):\n if verbose:\n print(\"fvec too high: \" + str(info['fvec']))\n return None\n# except RuntimeWarning as e:\n# if verbose:\n# print(e)\n# return None\n\n # Screen out solutions with negative concentrations, fudging\n # anything that's clearly numerical error to 0.\n if np.any(ss_vector < 0):\n if np.any(ss_vector < -1e-8):\n if verbose:\n print(\"Steady state vector has negative values: \" + str(ss_vector))\n return None\n ss_vector = np.clip(ss_vector, a_min = 0, a_max = None)\n return ss_vector\n \n solution = try_optimization(state_inits)\n if verbose:\n print(\"solution: \" + str(solution))\n if solution is not None:\n if debug:\n plt.clf()\n sim = simulate(dv_dt_generator, params, state_inits, \n t_max = 50000, n_times = 10000)\n for i in range(sim.solution.shape[1]):\n plt.plot(sim.ts, sim.solution[:,i], label = names[i])\n plt.axhline(solution[0], color = \"black\")\n plt.xlabel(\"Time (s, arbitrary)\")\n plt.ylabel(\"Concentration (nM, arbitrary)\")\n plt.title(\"Open-loop example trace\")\n # plt.ylim([0, 50])\n plt.legend()\n plt.show()\n return solution\n else:\n raise ValueError(\"Unable to find non-zero steady state of function!\")\n\ndef double_param_search_ss3(param2, dvdt, state_inits, default_params, names,\n param1 = 'N',\n param1s = np.logspace(4, 8, 10), \n param2s = np.logspace(-2, 2, 10)):\n '''\n \n Finds numerical steady state solution to system of ODEs dvdt\n \n Params:\n param2: Parameter to alter with parameters param2s (string)\n dvdt: A function that takes the parameters xs and params, in that order,\n where xs is a state vector of the system and params is a list of \n parameters, and returns the derivative of the system.\n state_inits: A (numpy array) vector of initial guesses for the solution.\n default_params: A dictionary of parameters\n names: Names of species in the state vector\n param1: The first parameter to alter (string)\n param1s: numpy array of param1 values to simulate\n param2s: numpy array of param2 values to simulate\n \n Returns: A tidy data frame in which each entry is a as follows: [species name, param1, param2, concentration]\n '''\n\n new_solutions = np.zeros((len(param2s), \n len(param1s), len(state_inits)))\n new_solutions_2 = np.zeros((len(param1s)*len(param2s), 2 + len(state_inits)))\n \n k = 0 \n for j, p2 in enumerate(param2s):\n temp_params = copy.copy(default_params)\n temp_params[param2] = p2\n for i, p1 in enumerate(param1s):\n temp_params[param1] = p1\n\n soln = find_ss_opt(lambda params: (lambda x: dvdt(x, params)), temp_params, state_inits,\n verbose = False)\n \n new_solutions[j, i,:] = soln \n new_solutions_2[k, 0] = p1\n new_solutions_2[k, 1] = p2\n \n \n new_solutions_2[k, 2:] = new_solutions[j, i,:]\n \n k = k + 1 \n \n df = pd.DataFrame(new_solutions_2, columns = [param1, param2] + names)\n \n df_tidy = pd.melt(df, value_vars = names, id_vars = [param1, param2],\n value_name = 'concentration',\n var_name = 'species')\n\n return df_tidy \n\n\ndef find_ss_sim(dv_dt_generator, params, state_inits, dt = 0.1, debug = False, \n max_n = 60000, tol = 1e-5):\n t0 = 0\n dv_dt = dv_dt_generator(params)\n \n ode = scipy.integrate.ode(dv_dt).set_integrator('lsoda')#, method='bdf', order = 5)\n ode.set_initial_value(state_inits, t0)\n last_time = np.zeros(len(state_inits))\n i = 0\n broken = False\n while ode.successful():\n last_time = ode.integrate(ode.t+dt)\n i += 1\n if np.all(dv_dt(0, last_time) < tol):\n break\n if i >= max_n:\n broken = True\n break\n if debug:\n plt.clf()\n sim = simulate(dv_dt_generator, params, state_inits, t_max = dt*i, n_times = 10000)\n for i in range(sim.solution.shape[1]):\n plt.plot(sim.ts, sim.solution[:,i], label = names[i])\n plt.axhline(last_time[0], color = \"black\")\n plt.xlabel(\"Time (s, arbitrary)\")\n plt.ylabel(\"Concentration (nM, arbitrary)\")\n plt.title(\"Open-loop example trace\")\n # plt.ylim([0, 50])\n plt.legend()\n plt.show()\n \n if broken:\n raise Exception(\"Max iterations reached without finding steady state.\")\n return last_time\n\n\n\n\n\ndef bound(A, max = 1000):\n return np.max(np.min((A, 1000)), 0)\n\ndef get_df(simdata, names, normalize = False):\n simdata_array = np.copy(simdata[2])\n if normalize: \n for i in range(len(names)):\n simdata_array[:,i ] = simdata_array[:, i] / np.max(simdata_array[:,i])\n df_sim = pd.DataFrame(simdata_array, columns = names)\n df_sim['time'] = simdata[1]\n\n df_tidy = pd.melt(df_sim, value_vars = names, id_vars = ['time'],\n value_name = 'concentration',\n var_name = 'species')\n \n \n return df_tidy\n\n\n\ndef plot_param_trajectories(dvdt, state_inits, names, params, \n species = 'H', \n param = 'N',\n param_range = np.logspace(-2, 1, 5), tmax = 500):\n\n \n '''\n \n Finds numerical steady state solution to system of ODEs dvdt\n \n Params:\n param2: Parameter to alter with parameters param2s (string)\n dvdt: A function that takes the parameters xs and params, in that order,\n where xs is a state vector of the system and params is a list of \n parameters, and returns the derivative of the system.\n state_inits: A (numpy array) vector of initial guesses for the solution.\n default_params: A dictionary of parameters\n names: Names of species in the state vector\n param1: The first parameter to alter (string)\n param1s: numpy array of param1 values to simulate\n param2s: numpy array of param2 values to simulate\n \n Returns: A tidy data frame in which each entry is a as follows: [species name, param1, param2, concentration]\n '''\n \n p.xaxis.axis_label = 'time'\n p.yaxis.axis_label = 'concentration'\n ind = names.index(species)\n for i, par in enumerate(param_range):\n temp_params = copy.copy(params)\n temp_params[param] = par\n sim = simulate(dvdt, \n temp_params, state_inits, \n t_max = tmax, n_times =1000)\n \n p.line(x = sim.ts, y = sim.solution[:, ind], color = cmap[i])\n \n color_mapper = bokeh.models.LogColorMapper(palette=\"Viridis256\", low=1e-2, high=1e1)\n \n color_bar = bokeh.models.ColorBar(color_mapper=color_mapper, ticker=bokeh.models.LogTicker(),\n label_standoff=12, border_line_color=None, location=(0,0))\n p.add_layout(color_bar, 'right')\n \n return p\n \n \n \ndef hv_plot(df_tidy, to_plot = 'all'):\n if to_plot == 'all':\n\n \n hv_fig = hv.Curve(df_tidy, \n kdims = ['time', 'concentration'], \n vdims = ['species']\n ).groupby('species'\n ).overlay(\n ).opts(frame_height=250,frame_width=250 * 3 // 2)\n else:\n df_small = df_tidy.loc[df_tidy['species'].isin(to_plot), :]\n hv_fig = hv.Curve(df_small, \n kdims = ['time', 'concentration'], \n vdims = ['species']\n ).groupby('species'\n ).overlay(\n ).opts(frame_height=250,frame_width=250 * 3 // 2)\n\n # Take out the Bokeh object\n p = hv.render(hv_fig)\n return p\n\ndef time_plot(df, p1, p2, logx = True):\n points = hv.Points(\n data=df, kdims=[p1, 'time'], vdims=[p2],\n \n )\n if logx:\n points.opts(color = p2, cmap = 'Reds', \n logx=True, title ='time to ss', colorbar = True, size= 7,\n frame_height=200, frame_width=200 * 3 // 2,)\n else: \n points.opts(color = p2, cmap = 'Reds', \n title = 'time to ss', colorbar = True, size= 7,\n frame_height=200, frame_width=200 * 3 // 2,)\n p = hv.render(points)\n return p\n \ndef make_gridplot(df_tidy, names, p1, p2, to_plot = 'concentration', logx = True,\n yrange = bokeh.models.Range1d(0, 15)):\n plots = []\n for name in names:\n df_small = df_tidy.loc[df_tidy['species'] == name, :]\n points = hv.Points(\n data=df_small, kdims=[p1, to_plot], vdims=[p2],\n \n )\n if logx:\n \n points.opts(color = p2, cmap = 'Blues', \n logx=True, title = name, colorbar = True, size= 7,\n frame_height=200, frame_width=200 * 3 // 2,)\n \n else: \n points.opts(color = p2, cmap = 'Blues', \n title = name, colorbar = True, size= 7,\n frame_height=200, frame_width=200 * 3 // 2,)\n # curve = hv.Curve(data = df_small, kdims=[p1, \"concentration\"],\n # vdims=[p2]).opts(logx=True,frame_height=200, frame_width=200 * 3 // 2)\n # overlay = hv.Overlay([points, curve])\n p = hv.render(points)\n if name == 'H':\n p.y_range = yrange\n plots.append(p)\n return bokeh.layouts.gridplot(plots, ncols = 2)\n\n\ndef make_smallplot(df_tidy, names, p1, p2, name = 'H', to_plot = 'concentration', logx = True):\n df_small = df_tidy.loc[df_tidy['species'] == name, :]\n points = hv.Points(\n data=df_small, kdims=[p1, to_plot], vdims=[p2])\n if logx:\n points.opts(color = p2, cmap = 'Blues', \n logx=True, title = name, colorbar = True, size= 7,\n frame_height=200, frame_width=200 * 3 // 2,)\n else: \n points.opts(color = p2, cmap = 'Blues', \n title = name, colorbar = True, size= 7,\n frame_height=200, frame_width=200 * 3 // 2,)\n p = hv.render(points)\n return p \n \n\n\n\n\ndef double_param_search(param2, dv_dt, state_inits, default_params, names, title,\n param1 = 'N',\n param1s = np.logspace(4, 8, 10), \n normalize = False,\n \n param2s = np.logspace(-2, 2, 10), tmax = 500, n_times = 1000, log_y = False):\n\n new_solutions = np.zeros((len(param2s), \n len(param1s), len(state_inits)))\n new_solutions_2 = np.zeros((len(param1s)*len(param2s), 2 + len(state_inits)))\n \n k = 0 \n for j, p2 in enumerate(param2s):\n temp_params = copy.copy(default_params)\n temp_params[param2] = p2\n for i, p1 in enumerate(param1s):\n temp_params[param1] = p1\n simdata = simulate(dv_dt, \n temp_params, state_inits,\n t_max = tmax, n_times = n_times)\n \n sim = simdata.solution[-int(new_solutions.shape[0]/5):,:]\n \n new_solutions[j, i,:] = simdata.solution[-int(new_solutions.shape[0]/5):,:].mean(axis = 0) \n new_solutions_2[k, 0] = p1\n new_solutions_2[k, 1] = p2\n \n new_solutions_2[k, 2:] = new_solutions[j, i,:]\n \n k = k + 1 \n \n df = pd.DataFrame(new_solutions_2, columns = [param1, param2] + names)\n \n df_tidy = pd.melt(df, value_vars = names, id_vars = [param1, param2],\n value_name = 'concentration',\n var_name = 'species')\n\n return df_tidy \n\n\n\ndef get_param_trajectories(system, state_inits, names, params, \n species = 'H', \n param = 'N',\n param_range = np.logspace(-2, 1, 5), tmax = 500 ):\n\n \n ind = names.index(species)\n dfs = []\n for i, par in enumerate(param_range):\n temp_params = copy.copy(params)\n temp_params[param] = par\n sim = simulate(system, \n temp_params, state_inits, \n t_max = tmax, n_times =1000)\n \n \n \n df_small = pd.DataFrame(data = {'time': sim.ts, species: sim.solution[:, ind]})\n df_small[param] = par\n dfs.append(df_small)\n \n \n \n return pd.concat(dfs)\n\n \ndef hv_plot_param(df_tidy, species = 'H', param = 'N'): \n hv_fig = hv.Curve(df_tidy, \n kdims = ['time', species], \n vdims = [param],\n \n ).groupby(param\n ).overlay(\n ).opts(frame_height=250,frame_width=250 * 3 // 2)\n hv_fig.opts(opts.Curve(color=hv.Palette('Viridis'), width=600))\n\n\n # Take out the Bokeh object\n p = hv.render(hv_fig)\n return p\n\n\n\ndef double_param_search_ss2(param2, dv_dt, state_inits, default_params, names, title,\n param1 = 'N',\n param1s = np.logspace(4, 8, 10), \n normalize = False,\n \n param2s = np.logspace(-2, 2, 10), tmax = 500, n_times = 1000, log_y = False):\n\n new_solutions = np.zeros((len(param2s), \n len(param1s), len(state_inits)))\n new_solutions_2 = np.zeros((len(param1s)*len(param2s), 2 + len(state_inits)))\n \n k = 0 \n for j, p2 in enumerate(param2s):\n temp_params = copy.copy(default_params)\n temp_params[param2] = p2\n for i, p1 in enumerate(param1s):\n temp_params[param1] = p1\n # simdata = simulate(dv_dt, \n # temp_params, state_inits,\n # t_max = tmax, n_times = n_times)\n \n # sim = simdata.solution[-int(new_solutions.shape[0]/5):,:]\n soln = find_ss_opt(dv_dt_generator, default_params, state_inits)\n \n new_solutions[j, i,:] = soln # simdata.solution[-int(new_solutions.shape[0]/5):,:].mean(axis = 0) \n new_solutions_2[k, 0] = p1\n new_solutions_2[k, 1] = p2\n \n new_solutions_2[k, 2:] = new_solutions[j, i,:]\n \n k = k + 1 \n \n df = pd.DataFrame(new_solutions_2, columns = [param1, param2] + names)\n \n df_tidy = pd.melt(df, value_vars = names, id_vars = [param1, param2],\n value_name = 'concentration',\n var_name = 'species')\n\n return df_tidy \n\n\n\n\ndef get_plateau(paper_dvdt, default_params, state_inits, names, param_vary = 'gamma',\n solve = False, species = 'H', thresh = .9, \n param_range = np.logspace(np.log10(.005), np.log10(.02), 10),\n param_N_range = np.logspace(-2, 1, 10) ):\n if solve:\n pass\n else: \n df_tidy = double_param_search(param_vary, paper_dvdt, state_inits, \n default_params, names,\n \n param_vary,\n log_y = False,\n normalize = False,\n \n \n \n param1s = param_N_range,\n param2s = param_range,\n tmax = 5000, n_times = 10000,\n )\n df_tidy_small = df_tidy.loc[df_tidy['species'] == species, :]\n plateau_Ns = np.zeros(len(df_tidy[param_vary].unique()))\n unique_Ns = df_tidy['N'].unique()\n for i, p in enumerate(df_tidy[param_vary].unique()):\n df_tidy_p= df_tidy_small.loc[df_tidy_small[param_vary] == p, :]\n concs = df_tidy_p['concentration'].values\n final = df_tidy_p['concentration'].values[-1]\n diffs = np.abs(final - concs)\n\n N_val = unique_Ns[np.where(concs >= thresh*final)[0][0]]\n plateau_Ns[i] = N_val\n \n df_plat = pd.DataFrame(data = {param_vary: df_tidy[param_vary].unique(), 'plat': plateau_Ns})\n \n return df_plat\n \n \ndef plats_param_search(paper_dvdt, default_params, state_inits, names,\n param, param_vals, \n solve = False, species = 'H', thresh = .9, \n param_range = np.logspace(np.log10(.005), np.log10(.02), 10),\n param_N_range = np.logspace(-2, 1, 10)):\n dfs = []\n for p in param_vals:\n temp_params = copy.copy(default_params)\n temp_params[param] = p \n df_plat = get_plateau(paper_dvdt, temp_params, state_inits, names,\n solve = solve, species = species, thresh = thresh, \n param_range = param_range,\n param_N_range = param_N_range )\n df_plat[param] = p\n dfs.append(df_plat)\n return pd.concat(dfs)\n \n \n \n \ndef get_gamma_rob(paper_dvdt, default_params, state_inits, names, param_vary = 'N',\n solve = False, species = 'H', thresh = .9, \n param_range = np.logspace(np.log10(.005), np.log10(.02), 10),\n param_N_range = np.logspace(-2, 1, 10) ):\n if solve:\n pass\n else: \n df_tidy = double_param_search('gamma', paper_dvdt, state_inits, \n default_params, names,\n \n \n 'gamma',\n param1 = param_vary,\n log_y = False,\n normalize = False,\n \n \n \n param1s = param_N_range,\n param2s = param_range,\n tmax = 5000, n_times = 10000,\n )\n df_tidy_small = df_tidy.loc[df_tidy['species'] == species, :]\n rob_gammas = np.zeros(len(df_tidy[param_vary].unique()))\n \n for i, p in enumerate(df_tidy[param_vary].unique()):\n df_tidy_p= df_tidy_small.loc[df_tidy_small[param_vary] == p, :]\n concs = df_tidy_p['concentration'].values\n # should I change this?? \n diff = np.max(concs)/np.min(concs) # - np.min(concs))/(np.mean(concs)) \n \n rob_gammas[i] = diff\n \n df_plat = pd.DataFrame(data = {param_vary: df_tidy[param_vary].unique(), 'rob_gamma': rob_gammas})\n \n return df_plat\n\n\ndef gamma_stuff(param1, param2, paper_dvdt, default_params, state_inits, names, \n param_vary = 'N', \n param_range = np.logspace(np.log10(.005), np.log10(.02), 10),\n param_N_range = np.logspace(-1, 2, 15), ar_range = np.logspace(-1, 2, 15),\n include_original_params = False,\n ):\n dfs = []\n \n\n\n temp_params = copy.copy(default_params)\n if include_original_params:\n param_vary = param2\n plats = get_gamma_rob(paper_dvdt, temp_params, state_inits, names, thresh = .95, \n param_vary = param_vary, \n param_range = param_range,\n param_N_range = param_N_range\n \n \n )\n plats[param1] = temp_params[param1]\n dfs.append(plats)\n \n \n param_vary = param1\n plats = get_gamma_rob(paper_dvdt, temp_params, state_inits, names, thresh = .95, \n param_vary = param_vary, \n param_range = param_range,\n param_N_range = param_N_range\n \n \n )\n plats[param2] = temp_params[param2]\n dfs.append(plats)\n \n \n param_vary = param1\n for v in ar_range: \n \n temp_params[param2] = v\n # print(temp_params)\n \n plats = get_gamma_rob(paper_dvdt, temp_params, state_inits, names, thresh = .95, \n param_vary = param_vary, \n param_range = param_range,\n param_N_range = param_N_range\n \n \n )\n plats[param2] = v\n dfs.append(plats)\n \n df_full = pd.concat(dfs)\n\n #df_full.to_csv(f'{circuit_name}_df_gamma_rob_{param1}_{param2}_layered.csv')\n return df_full\n\n\n\n\n \ndef get_plat_rob(paper_dvdt, default_params, state_inits, names, param1, param2,\n solve = False, species = 'H', thresh = .95, \n param1_range = np.logspace(-2, 2, 10),\n param2_range = np.logspace(-2, 2, 10),\n param_N_range =np.logspace(-1, 2, 20)\n ):\n if solve:\n pass\n else: \n dfs = []\n vmax_range = np.logspace(-2, 2, 10)\n temp_params = copy.copy(default_params)\n for v in vmax_range: \n temp_params[param1] = v # param1\n\n param_vary = param2\n plats = get_plateau(paper_dvdt, temp_params, state_inits, names, thresh = .95, \n param_vary = param_vary,\n \n #param_N_range = np.linspace(.05, 1, 20),\n param_N_range = np.logspace(-1, 2, 20),\n param_range = np.logspace(-2, 2, 10))\n plats[param1] = v\n dfs.append(plats)\n \n df_full = pd.concat(dfs) \n return df_full\n\n\n\n\ndef get_overshoot(simdata, names, species = 'H', eps_ratio = .02, span = 10, normalize = True ):\n ind = names.index(species)\n\n data = simdata.solution[:, ind ]\n \n\n end_point = np.mean(data[-span:])\n #print(names[ind], simdata.solution.shape, end_point, np.max(data))\n max_value = np.max(data)\n\n return max_value/end_point\n\ndef stimulus_species(simdata, system, params, names, \n tmax, ntimes = 1000, to_botch = ['H'], factor = .5):\n end_point = np.copy(simdata.solution[-1, :])\n \n for name in to_botch: \n ind = names.index(name)\n end_point[ind] = end_point[ind] + end_point[ind]*factor\n \n simdata_2 = simulate(system, \n params, end_point, \n t_max = tmax, n_times = ntimes)\n return simdata_2\n\n\n \ndef double_param_overshoot(param2, dv_dt, state_inits, default_params, names, \n param1 = 'N',\n param1s = np.logspace(4, 8, 10), \n \n eps_ratio = .02, \n normalize = True, \n species = 'H',\n \n param2s = np.logspace(-2, 2, 10), tmax = 500, n_times = 1000, log_y = False):\n \n\n\n new_solutions_2 = np.zeros((len(param1s)*len(param2s), 3))\n \n k = 0 \n for j, p2 in enumerate(param2s):\n temp_params = copy.copy(default_params)\n temp_params[param2] = p2\n for i, p1 in enumerate(param1s):\n temp_params[param1] = p1\n simdata = simulate(dv_dt, \n temp_params, state_inits,\n t_max = tmax, n_times = n_times)\n \n # simdata_recovery = stimulus_species(simdata, dv_dt, temp_params, names, \n #tmax, ntimes = 1000, to_botch = ['H'], factor = .5)\n \n over_shoot = get_overshoot(simdata, names, species = species, eps_ratio = eps_ratio, normalize = normalize )\n \n new_solutions_2[k, 0] = p1\n new_solutions_2[k, 1] = p2\n \n new_solutions_2[k, 2] = over_shoot\n \n k = k + 1 \n \n df = pd.DataFrame(new_solutions_2, columns = [param1, param2, 'over'])\n\n return df\n\ndef plot_sensitivities(df_tidy, name = 'H', logx = True, plot_abs = False, param = 'N'):\n df_tidy_n = df_tidy.loc[df_tidy['species'] == name, :]\n plots = []\n for sense in [param, 'gamma']:\n \n df_small = df_tidy_n.loc[df_tidy_n['sensitivity_to'] == sense, :]\n if plot_abs:\n df_small['abs_sensitivity'] = np.abs(df_small['sensitivity'].values)\n\n points = hv.Points(\n data=df_small, kdims=[param, 'abs_sensitivity'], vdims=['gamma'],\n \n )\n else: \n points = hv.Points(\n data=df_small, kdims=[param, 'sensitivity'], vdims=['gamma'],\n \n )\n\n\n points.opts(color = 'gamma', cmap = 'Purples', logx = logx,\n title = sense, colorbar = True, size= 7,\n frame_height=200, frame_width=200 * 3 // 2,)\n p = hv.render(points)\n plots.append(p)\n \n return plots\n\ndef double_sensitivity_params(paper2_dvdt, default_params, names,param = 'N',\n param_N_range = np.logspace(-2, 1, 10), \n param_g_range = np.logspace(np.log10(.005), np.log10(.02), 10),\n \n tspan2 = agnp.linspace(0, 2000.), \n x0 = (0,0,0)):\n\n \n def C2(K):\n gamma, N = K \n \n\n\n def dC2dt(xs, t, gamma, N):\n \n return paper2_dvdt(xs, gamma, N, default_params)\n sol = odeint(dC2dt, x0, tspan2, tuple((gamma, N)))\n return sol\n \n \n k = 0 \n gamma_sensitivities = np.zeros((len(param_N_range)*len(param_g_range), 2 + len(names)))\n N_sensitivities = np.zeros((len(param_N_range)*len(param_g_range), 2 + len(names)))\n\n for j, p2 in enumerate(param_g_range):\n\n for i, p1 in enumerate(param_N_range):\n \n K2 = [p2, p1]\n # print(K2)\n\n \n sensitivities = nd.Jacobian(C2)(K2).T\n \n gamma_sensitivities[k, 2:] = sensitivities[:, 0, -1]\n N_sensitivities[k, 2:] = sensitivities[:, 1, -1]\n gamma_sensitivities[k, 0] = p1\n N_sensitivities[k, 0] = p1 \n gamma_sensitivities[k, 1] = p2\n N_sensitivities[k, 1] = p2 \n\n k = k + 1 \n \n df_g = pd.DataFrame(gamma_sensitivities, columns = [param, 'gamma'] + names)\n df_g['sensitivity_to'] = 'gamma'\n df_N = pd.DataFrame(N_sensitivities, columns = [param, 'gamma'] + names)\n df_N['sensitivity_to'] = 'N'\n \n df_tidy_g = pd.melt(df_g, value_vars = names, id_vars = [param, 'gamma'],\n value_name = 'sensitivity',\n var_name = 'species')\n df_tidy_g['sensitivity_to'] = 'gamma'\n df_tidy_N = pd.melt(df_N, value_vars = names, id_vars = [param, 'gamma'],\n value_name = 'sensitivity',\n var_name = 'species')\n df_tidy_N['sensitivity_to'] = 'N'\n return pd.concat([df_tidy_N, df_tidy_g]) \n\n\ndef time_to_ss(simdata, names, species = 'H', eps_ratio = .02, span = 50):\n ind = names.index(species)\n #print(species, names, ind)\n data = simdata.solution[:, ind]\n end_point = np.mean(data[-span:])\n \n changes = np.abs(data - end_point)\n # print(changes)\n \n \n error_moving_avg = moving_average(changes, n = span)\n #print(error_moving_avg.shape)\n ss_ind = np.where(error_moving_avg < eps_ratio*end_point)[0][0]\n ss_time = simdata.ts[ss_ind]\n # print('k', ss_time, ss_ind, np.max(data[ss_ind:ss_ind + 50]), np.min(data[ss_ind:ss_ind + 50]), end_point)\n # print(end_point, data[ss_ind])\n return ss_time, ss_ind, end_point\n\ndef double_param_search_times(param2, dv_dt, state_inits, default_params, names, title,\n param1 = 'N',\n species = 'H',\n param1s = np.logspace(4, 8, 2), \n normalize = False,\n \n param2s = np.logspace(-2, 2, 2),\n tmax = 1000, n_times = 1000, stimulate = False, \n log_y = False):\n\n new_solutions = np.zeros((len(param2s), \n len(param1s), 2))\n new_solutions_2 = np.zeros((len(param1s)*len(param2s), 2 + 2))\n \n k = 0 \n for j, p2 in enumerate(param2s):\n temp_params = copy.copy(default_params)\n temp_params[param2] = p2\n for i, p1 in enumerate(param1s):\n temp_params[param1] = p1\n \n simdata = simulate(dv_dt, \n temp_params, state_inits,\n t_max = tmax, n_times = n_times)\n \n if stimulate: \n simdata = stimulus_species(simdata, dv_dt, temp_params, names, 500)\n sim = simdata.solution[-int(new_solutions.shape[0]/5):,:]\n \n \n \n ss_time, ss_ind, end_point = time_to_ss(simdata,\n names, species = 'H',\n span = 50\n )\n # if ss_time < 50:\n # print(p1, p2, ss_time, end_point, sim[-1])\n \n \n new_solutions_2[k, 0] = p1\n new_solutions_2[k, 1] = p2\n new_solutions_2[k, 2] = ss_time\n # print(p1, p1)\n \n new_solutions_2[k, 3] = end_point\n \n k = k + 1 \n \n df = pd.DataFrame(new_solutions_2, columns = [param1, param2, 'time', species])\n \n # df_tidy = pd.melt(df, value_vars = names, id_vars = [param1, param2],\n # value_name = 'concentration',\n # var_name = 'species')\n\n return df\n\n","sub_path":"oldcircuits/circuit_sim_bokeh.py","file_name":"circuit_sim_bokeh.py","file_ext":"py","file_size_in_byte":34397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"393016133","text":"# Copyright 2015 Confluent Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom ducktape.services.service import Service\nfrom ducktape.tests.test import Test\nfrom ducktape.errors import TimeoutError\nfrom threading import Thread\nimport time\n\nclass RemoteAccountTestService(Service):\n \"\"\"Simple service that allocates one node for performing tests of RemoteAccount functionality\"\"\"\n\n LOG_FILE = \"/tmp/test.log\"\n\n def __init__(self, context):\n super(RemoteAccountTestService, self).__init__(context, 1)\n\n\n def start_node(self, node):\n pass\n\n def stop_node(self, node):\n pass\n\n def clean_node(self, node):\n node.account.ssh(\"rm -f \" + self.LOG_FILE)\n\n def write_to_log(self, msg):\n self.nodes[0].account.ssh(\"echo -e -n \" + repr(msg) + \" >> \" + self.LOG_FILE)\n\nclass RemoteAccountTest(Test):\n\n def __init__(self, test_context):\n super(RemoteAccountTest, self).__init__(test_context)\n self.account_service = RemoteAccountTestService(test_context)\n\n def setUp(self):\n self.account_service.start()\n\n def test_monitor_log(self):\n \"\"\"Tests log monitoring by writing to a log in the background thread\"\"\"\n\n node = self.account_service.nodes[0]\n\n # Make sure we start the log with some data, including the value we're going to grep for\n self.account_service.write_to_log(\"foo\\nbar\\nbaz\")\n\n # Background thread that simulates a process writing to the log\n self.wrote_log_line = False\n def background_logging_thread():\n # This needs to be large enough that we can verify we've actually\n # waited some time for the data to be written, but not too long that\n # the test takes a long time\n time.sleep(3)\n self.wrote_log_line = True\n self.account_service.write_to_log(\"foo\\nbar\\nbaz\")\n\n with node.account.monitor_log(self.account_service.LOG_FILE) as monitor:\n logging_thread = Thread(target=background_logging_thread)\n logging_thread.start()\n monitor.wait_until('foo', timeout_sec=10, err_msg=\"Never saw expected log\")\n assert self.wrote_log_line\n\n logging_thread.join(5.0)\n if logging_thread.isAlive():\n raise Exception(\"Timed out waiting for background thread.\")\n\n def test_monitor_log_exception(self):\n \"\"\"Tests log monitoring correctly throws an exception when the regex was not found\"\"\"\n\n node = self.account_service.nodes[0]\n\n # Make sure we start the log with some data, including the value we're going to grep for\n self.account_service.write_to_log(\"foo\\nbar\\nbaz\")\n\n timeout = 3\n try:\n with node.account.monitor_log(self.account_service.LOG_FILE) as monitor:\n start = time.time()\n monitor.wait_until('foo', timeout_sec=timeout, err_msg=\"Never saw expected log\")\n assert False, \"Log monitoring should have timed out and thrown an exception\"\n except TimeoutError:\n # expected\n end = time.time()\n assert end - start > timeout, \"Should have waited full timeout period while monitoring the log\"\n","sub_path":"systests/cluster/test_remote_account.py","file_name":"test_remote_account.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"179425560","text":"\"\"\"\"\nGiven an array of equal-length strings, you'd like to know if it's possible to rearrange the order of the elements in such a way that each consecutive pair of strings differ by exactly one character. Return true if it's possible, and false if not.\n\nNote: You're only rearranging the order of the strings, not the order of the letters within the strings!\n\nExample\n\nFor inputArray = [\"aba\", \"bbb\", \"bab\"], the output should be\nstringsRearrangement(inputArray) = false.\n\nThere are 6 possible arrangements for these strings:\n\n[\"aba\", \"bbb\", \"bab\"]\n[\"aba\", \"bab\", \"bbb\"]\n[\"bbb\", \"aba\", \"bab\"]\n[\"bbb\", \"bab\", \"aba\"]\n[\"bab\", \"bbb\", \"aba\"]\n[\"bab\", \"aba\", \"bbb\"]\nNone of these satisfy the condition of consecutive strings differing by 1 character, so the answer is false.\n\nFor inputArray = [\"ab\", \"bb\", \"aa\"], the output should be\nstringsRearrangement(inputArray) = true.\n\nIt's possible to arrange these strings in a way that each consecutive pair of strings differ by 1 character (eg: \"aa\", \"ab\", \"bb\" or \"bb\", \"ab\", \"aa\"), so return true.\n\n\"\"\"\"\"\nimport itertools\ndef stringsRearrangement(inputArray):\n possible_permutation = itertools.permutations(inputArray)\n for perm in possible_permutation:\n almatch = True\n for i in range(len(perm)-1):\n if not isDifferByOneChar(perm[i], perm[i+1]):\n almatch = False\n break\n if almatch:\n return True\n return False\ndef isDifferByOneChar(str1, str2):\n count = 0\n for i in range(len(str1)):\n if str1[i] != str2[i]:\n count +=1\n return count ==1\n \n \n \n\n\n","sub_path":"Arcade/Intro/Through the Fog/stringArrangements.py","file_name":"stringArrangements.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"283212715","text":"from __future__ import unicode_literals\n\nfrom operator import attrgetter\n\nfrom django.test import TestCase\n\nfrom django.db import models\n\nfrom .models import Post, Question, Answer\n\n\nclass OrderWithRespectToTests(TestCase):\n def test_basic(self):\n q1 = Question.objects.create(text=\"Which Beatle starts with the letter 'R'?\")\n q2 = Question.objects.create(text=\"What is your name?\")\n\n Answer.objects.create(text=\"John\", question=q1)\n Answer.objects.create(text=\"Jonno\", question=q2)\n Answer.objects.create(text=\"Paul\", question=q1)\n Answer.objects.create(text=\"Paulo\", question=q2)\n Answer.objects.create(text=\"George\", question=q1)\n Answer.objects.create(text=\"Ringo\", question=q1)\n\n # The answers will always be ordered in the order they were inserted.\n self.assertQuerysetEqual(\n q1.answer_set.all(), [\n \"John\", \"Paul\", \"George\", \"Ringo\",\n ],\n attrgetter(\"text\"),\n )\n\n # We can retrieve the answers related to a particular object, in the\n # order they were created, once we have a particular object.\n a1 = Answer.objects.filter(question=q1)[0]\n self.assertEqual(a1.text, \"John\")\n a2 = a1.get_next_in_order()\n self.assertEqual(a2.text, \"Paul\")\n a4 = list(Answer.objects.filter(question=q1))[-1]\n self.assertEqual(a4.text, \"Ringo\")\n self.assertEqual(a4.get_previous_in_order().text, \"George\")\n\n # Determining (and setting) the ordering for a particular item is also\n # possible.\n id_list = [o.pk for o in q1.answer_set.all()]\n self.assertEqual(a2.question.get_answer_order(), id_list)\n\n a5 = Answer.objects.create(text=\"Number five\", question=q1)\n\n # It doesn't matter which answer we use to check the order, it will\n # always be the same.\n self.assertEqual(\n a2.question.get_answer_order(), a5.question.get_answer_order()\n )\n\n # The ordering can be altered:\n id_list = [o.pk for o in q1.answer_set.all()]\n x = id_list.pop()\n id_list.insert(-1, x)\n self.assertNotEqual(a5.question.get_answer_order(), id_list)\n a5.question.set_answer_order(id_list)\n self.assertQuerysetEqual(\n q1.answer_set.all(), [\n \"John\", \"Paul\", \"George\", \"Number five\", \"Ringo\"\n ],\n attrgetter(\"text\")\n )\n\n def test_recursive_ordering(self):\n p1 = Post.objects.create(title='1')\n p2 = Post.objects.create(title='2')\n p1_1 = Post.objects.create(title=\"1.1\", parent=p1)\n p1_2 = Post.objects.create(title=\"1.2\", parent=p1)\n Post.objects.create(title=\"2.1\", parent=p2)\n p1_3 = Post.objects.create(title=\"1.3\", parent=p1)\n self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])\n\n def test_duplicate_order_field(self):\n\n class Bar(models.Model):\n pass\n\n class Foo(models.Model):\n bar = models.ForeignKey(Bar)\n order = models.OrderWrt()\n\n class Meta:\n order_with_respect_to = 'bar'\n\n count = 0\n for field in Foo._meta.local_fields:\n if isinstance(field, models.OrderWrt):\n count += 1\n\n self.assertEqual(count, 1)\n","sub_path":"django-master/tests/order_with_respect_to/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"580611872","text":"from tkinter import *\nimport itertools as it\n\ndef setVol(vol):\n print(\"setVolume\")\n\ndef setProg(event):\n print(v.get())\n\ndef playAudio(event):\n print(\"Playing audio\")\n\ndef getMusic(event):\n l = musicBox.curselection()\n print(musicBox.get(l))\n\n\nroot = Tk()\nroot.title('Music Player')\nroot.minsize(width=500,height=400)\nroot.maxsize(width=500,height=400)\nroot.resizable(width=False, height=False)\n\nalbumFrame = Frame(root,width=500,height=145, bd = 3,bg='lightblue')\ntoolBar = Frame(root,width=500,height=115, bd = 2,bg='white')\nmusicList = Frame(root,width=500,height=100, bd = 2)\n\n\n\nvolumeIcon = PhotoImage(file='volume.png').subsample(2,2)\nvolumeUpIcon = PhotoImage(file='volume_up.png').subsample(3,3)\nvolumeDownIcon = PhotoImage(file='volume_down.png').subsample(3,3)\nplayLastIcon = PhotoImage(file='play_last.png').subsample(2,2)\nplayNextIcon = PhotoImage(file='play_next.png').subsample(2,2)\nplayIcon = PhotoImage(file='play.png').subsample(1,1)\npauseIcon = PhotoImage(file='pause.png').subsample(1,1)\nstopIcon = PhotoImage(file='stop.png').subsample(1,1)\nlyricIcon = PhotoImage(file='lyric.png').subsample(2,2)\n\n\nvolumeButton = Button(toolBar, image = volumeIcon, width = 35, height = 35,relief=\"solid\",bd=0,bg='white')\nvolumeButton.bind('', setVol)\nvolumeButton.place(x=15,y=23)\n\nvolumeDownButton = Button(toolBar, image = volumeDownIcon, width = 35, height = 35,relief=\"solid\",bd=0,bg='white')\nvolumeDownButton.bind('', setVol)\nvolumeDownButton.place(x=59,y=41)\n\nvolumeUpButton = Button(toolBar, image = volumeUpIcon, width = 35, height = 35,relief=\"solid\",bd=0,bg='white')\nvolumeUpButton.bind('', setVol)\nvolumeUpButton.place(x=59,y=6)\n\nplayLastButton = Button(toolBar, image = playLastIcon, width = 35, height = 35,relief=\"solid\",bd=0,bg='white')\nplayLastButton.bind('', playAudio)\nplayLastButton.place(x=115,y=25)\n\npauseButton = Button(toolBar, image = pauseIcon, width = 50, height = 50,relief=\"solid\",bd=0,bg='white')\npauseButton.bind('', playAudio)\npauseButton.place(x=165,y=16)\n\nplayButton = Button(toolBar, image = playIcon, width = 50, height = 50,relief=\"solid\",bd=0,bg='white')\nplayButton.bind('', playAudio)\nplayButton.place(x=235,y=16)\n\nstopButton = Button(toolBar, image = stopIcon,width = 50, height = 50,relief=\"solid\",bd=0,bg='white')\nstopButton.bind('', playAudio)\nstopButton.place(x=305,y=16)\n\nplayNextButton = Button(toolBar, image = playNextIcon, width = 35, height = 35,relief=\"solid\",bd=0,bg='white')\nplayNextButton.bind('', playAudio)\nplayNextButton.place(x=383,y=25)\n\nlyricButton = Button(toolBar, image = lyricIcon,width = 35, height = 35,relief=\"solid\",bd=0,bg='white')\nlyricButton.bind('', playAudio)\nlyricButton.place(x=447,y=24)\n\n\nv = StringVar()\nprog = Scale(\n toolBar,\n orient = 'horizontal',\n from_ = 0, to = 100,\n showvalue = False,\n command = setProg,\n length = 490,\n bg = 'lightblue',\n variable = v\n)\nprog.place(x=1,y=80)\nmusiclist=['music 1','music 2','music 3','music 4']\nmusicBox = Listbox(musicList, width = 80, height = 8, activestyle = 'dotbox')\nfor item in musiclist:\n musicBox.insert(END,item)\nmusicBox.bind('',getMusic)\nmusicBox.grid()\n\ntoolBar.grid_propagate(False)\n\nalbumFrame.grid()\ntoolBar.grid(rowspan = 2)\nmusicList.grid()\n\nroot.mainloop()\n","sub_path":"old file/MusicPlayerGUI - Copy.py","file_name":"MusicPlayerGUI - Copy.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"177344866","text":"from math import sqrt\n\n\ndef squares(n):\n \"\"\" Given an integer n, return the minimum number of squares that\n need to be summed together to obtain n.\n \"\"\"\n return squaresDyn(n) \n # return squaresMemo(n) # we could use this as well\n\n\ndef squaresRec(DP, n):\n\tif DP[n]<0:\n\t\tDP[n] = n\n\t\tfor k in range(1, int(sqrt(n))+1):\n\t\t\ttemp = squaresRec(DP, n-k*k)+1\n\t\t\tDP[n] = min(DP[n], temp)\n\treturn DP[n]\n\t\t\ndef squaresMemo(n):\n\tDP = [-1]*(n+1)\n\tDP[0] = 0\n\treturn squaresRec(DP,n)\n\ndef squaresDyn(n):\n\tDP = [-1]*(n+1)\n\tDP[0] = 0\n\tfor i in range(1,n+1):\n\t\tDP[i] = i\n\t\tfor k in range(1, int(sqrt(i))+1):\n\t\t\tDP[i] = min(DP[i], DP[i-k*k]+1)\n\treturn DP[n]\n","sub_path":"past-exams/2018-01-16/FIRSTNAME-LASTNAME-ID/exercise2_solution.py","file_name":"exercise2_solution.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"113863784","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dec 7 20:41:00 2019\r\n\r\n@author: Mahip\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import confusion_matrix\r\n\r\nclass LR:\r\n def __init__(self, lr=0.001, num_iters=1000):\r\n self.lr = lr\r\n self.num_iters = num_iters\r\n self.weights = None\r\n self.bias = None\r\n \r\n def __sigmoid(self, x):\r\n return 1 / (1 + np.exp(-x))\r\n \r\n def fit(self, X, y):\r\n n_samples, n_features = X.shape\r\n self.weights = np.zeros(n_features)\r\n self.bias = 0\r\n \r\n for _ in range(self.num_iters):\r\n linear_model = np.dot(X, self.weights) + self.bias\r\n y_pred = self.__sigmoid(linear_model)\r\n \r\n dw = (1 / n_samples) * np.dot(X.T, (y_pred - y))\r\n db = (1 / n_samples) * np.sum(y_pred - y)\r\n \r\n self.weights -= self.lr * dw\r\n self.bias -= self.lr * db\r\n \r\n def predict(self, X):\r\n linear_model = np.dot(X, self.weights) + self.bias\r\n y_pred = self.__sigmoid(linear_model)\r\n y_pred_classes = [1 if i > 0.5 else 0 for i in y_pred]\r\n return y_pred_classes\r\n\r\ndef LRaccuracy():\r\n data = pd.read_csv(\"CreditCardDefault.csv\")\r\n data = data.drop(data.columns[0], axis=1)\r\n\r\n norm_cols = ['bill_sept', 'bill_aug', 'bill_july', 'bill_june', 'bill_may',\r\n 'bill_apr', 'paid_sept', 'paid_aug', 'paid_july', 'paid_june', 'paid_may', \r\n 'paid_apr']\r\n\r\n data[norm_cols] = data[norm_cols].apply(lambda x: (x - np.mean(x)) / np.std(x))\r\n\r\n X = data.iloc[:, 6:24]\r\n y = data.iloc[:, -1]\r\n \r\n \r\n \r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)\r\n\r\n logreg = LR(lr=0.01, num_iters=500)\r\n logreg.fit(X_train, y_train)\r\n\r\n predictions = logreg.predict(X_test)\r\n\r\n conf_mat = confusion_matrix(y_test, predictions)\r\n\r\n \r\n return 100 * (conf_mat[0][0] + conf_mat[1][1]) / len(predictions)\r\n","sub_path":"main/CCDPS_LogisticRegression.py","file_name":"CCDPS_LogisticRegression.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"186318192","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport requests\nimport hashlib\nimport re\n\nr = requests.get('https://api.github.com/repos/wsjcpp/wsjcpp/releases')\n\nlatest_tag_name_release = r.json()[0]['tag_name']\nprint(\"latest release \" + latest_tag_name_release)\n\nurl = 'https://github.com/wsjcpp/wsjcpp/archive/' + latest_tag_name_release + '.tar.gz'\nprint(\"Download archive \" + url)\nr = requests.get(url, allow_redirects=True)\nsha256_ = hashlib.sha256(r.content).hexdigest()\nprint(\"sha256 = \" + sha256_)\n\ndef replace2(file, pattern, subst):\n # Read contents from file as a single string\n file_handle = open(file, 'r')\n file_string = file_handle.read()\n file_handle.close()\n\n # Use RE package to allow for replacement (also allowing for (multiline) REGEX)\n file_string = (re.sub(pattern, subst, file_string))\n\n # print(file_string)\n\n # Write contents to file.\n # Using mode 'w' truncates the file.\n file_handle = open(file, 'w')\n file_handle.write(file_string)\n file_handle.close()\n\nprint(\"Update version and sha256 in wsjcpp.rb\")\nreplace2(\"./wsjcpp.rb\",\"/v\\\\d*\\\\.\\\\d*\\\\.\\\\d*\\\\.tar\\\\.gz\\\"\",\"/\" + latest_tag_name_release + \".tar.gz\\\"\")\nreplace2(\"./wsjcpp.rb\", \"sha256 \\\"[a-fA-F0-9]*\\\"\", \"sha256 \\\"\" + sha256_ + \"\\\"\")\n\nprint(\"Done.\")","sub_path":"auto_update_wsjcpp_rb.py","file_name":"auto_update_wsjcpp_rb.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"161810321","text":"from rest_framework.response import Response\nfrom rest_framework.generics import ListAPIView\n#\nfrom _common.views.user_create import UserCreateOnlyOne\nfrom _common.views.no_token import NoTokenView\n#\nfrom . import models, serializers\n\n\n# Create your views here.\n\n\n# -----------------\n\n\nclass ProductRateView:\n queryset = models.ProductRateModel.objects.all()\n serializer_class = serializers.ProductRateSerializer\n\n\n# ----------------\n\n\nclass ProductRateCommonViewL(ProductRateView, ListAPIView):\n\n def get_queryset(self):\n product_model = self.request.query_params.get('product_model')\n\n return self.queryset.filter(product_model=product_model)\n\n\nclass ProductRateDataView(ProductRateCommonViewL):\n\n def get_rate_arr(self):\n queryset = self.get_queryset()\n\n return {'rate_arr': [\n len(queryset.filter(num_rate=5).values_list('num_rate', flat=True)),\n len(queryset.filter(num_rate=4).values_list('num_rate', flat=True)),\n len(queryset.filter(num_rate=3).values_list('num_rate', flat=True)),\n len(queryset.filter(num_rate=2).values_list('num_rate', flat=True)),\n len(queryset.filter(num_rate=1).values_list('num_rate', flat=True)),\n ]}\n\n def get_data_response(self):\n queryset = self.get_queryset()\n serializer = self.get_serializer(queryset[0:3], many=True)\n\n return {'data': serializer.data, 'count': queryset.count()}\n\n def get(self, request, *args, **kwargs):\n data = {\n **self.get_data_response(),\n **self.get_rate_arr()\n }\n\n return Response(data)\n\n\n# ----------\n\n\nclass ProductRateTokenDataView(ProductRateDataView):\n\n def get_data_response(self):\n queryset = self.get_queryset()\n user_rate_queryset = queryset.filter(profile_model=self.request.user.id)\n\n if user_rate_queryset:\n serializer_user = self.get_serializer(user_rate_queryset, many=True)\n serializer_common = self.get_serializer(\n queryset.exclude(profile_model=self.request.user.id)[0:2],\n many=True\n )\n #\n data = serializer_user.data + serializer_common.data\n else:\n serializer_common = self.get_serializer(queryset[0:3], many=True)\n #\n data = serializer_common.data\n\n return {'data': data, 'count': queryset.count()}\n\n\nclass ProductRateNoTokenDataView(ProductRateDataView):\n pass\n\n\n#\nclass ProductRateViewL(ProductRateCommonViewL):\n pass\n\n\n#\nclass ProductRateViewC(ProductRateView, UserCreateOnlyOne):\n\n def get_instance_create(self):\n user_id = self.request.user.id\n product_id = self.request.data.get('product_model')\n\n return self.queryset.get(profile_model=user_id, product_model=product_id)\n\n def handle_exists(self, instance):\n serializer = self.get_serializer(instance=instance, data=self.request.data, partial=True)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n","sub_path":"shopee/child_app/shop/product/rate/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"152857903","text":"# -*- coding: UTF-8 -*-\n\n# app: mx.ine.cmi\n# módulo: money\n# descripción: Formularios para el aplicativo de control de presupuesto.\n# autor: Javier Sanchez Toledano\n# fecha: jueves, 16 de abril de 2015\n\n\nfrom django import forms\nfrom django.forms import ModelForm\n\nfrom .models import Reporte\n\n\nclass ReporteForm(ModelForm):\n class Meta:\n model = Reporte\n fields = ['entidad', 'sitio', 'fecha', 'tipo', 'ministrado',\n 'comprobado', 'reintegrado', 'saldo', 'oficio', 'estado', 'libro']\n widgets = {\n # Se deprecia el campo `anterior`\n\n 'ministrado': forms.NumberInput(\n attrs={\n 'step': '0.01',\n 'class': 'input-field',\n 'type': 'number',\n 'onblur': 'saldos();',\n 'size': 12,\n }\n ),\n 'comprobado': forms.NumberInput(\n attrs={\n 'step': '0.01',\n 'class': 'input-field',\n 'type': 'number',\n 'onblur': 'saldos();',\n 'size': 12,\n }\n ),\n 'reintegrado': forms.NumberInput(\n attrs={\n 'step': '0.01',\n 'class': 'input-field',\n 'type': 'number',\n 'onblur': 'saldos();',\n 'size': 12,\n }\n ),\n 'saldo': forms.NumberInput(\n attrs={\n 'step': '0.01',\n 'class': 'input-field',\n 'type': 'number',\n 'size': 12,\n }\n ),\n 'fecha': forms.TextInput(attrs={'class': 'datepicker'})\n }\n","sub_path":"src/money/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"107797885","text":"import socket\n\n# Attacks on target\nATTACK_TYPE = [\n\t'ARP_POISON',\n\t'DNS_HIJACK',\n\t'DNS_AMPLIFY',\n\t'SMURF',\n\t'SYN_FLOOD',\n\t'NTP_AMPLIFY',\n\t'SYN_SCAN',\n\t'ACK_SCAN',\n\t'XMAS_SCAN',\n\t'FIN_SCAN',\n\t'NULL_SCAN'\n\t'INVALID'\n]\n\nclass AttackerBaseClass():\n\tdef __init__(self, target:str, spoof_ip:str=None, attack=None):\n\t\tself.target_ipv4 = socket.gethostbyname(target)\n\n\t\tif spoof_ip is not None:\n\t\t\tself.spoof_ip = socket.gethostbyname(spoof_ip)\n\n\t\tif attack in ATTACK_TYPE:\n\t\t\tself.attack = attack\n\t\telse:\n\t\t\tself.attack = 'INVALID'\n\n\tdef print_target_ip(self):\n\t\tprint(\"[*] Target IP: \" + self.target_ipv4)\n\n\tdef __repr__(self):\n\t\t#return \"AttackerBaseClass('{}', '{}')\".format(self.target_ipv4, self.spoof_ip)\n\t\treturn \"AttackerBaseClass('{}')\".format(self.target_ipv4)\n\n\tdef setup_config(self):\n\t\tpass\n\ndef main():\n\ta = AttackerBaseClass(\"192.168.1.2\", attack=\"SYN_FLOOD\")\n\tprint(a.__dict__)\n\ta.print_target_ip()\n\tprint(a)\n\n\tb = AttackerBaseClass(\"www.absolute.com\")\n\tprint(b.__dict__)\n\tb.print_target_ip()\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"netattacker/attacker.py","file_name":"attacker.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"186819089","text":"from core.db import DB\nfrom bson.objectid import ObjectId\n\n\nclass CharacterException(Exception):\n def __init__(self, text_message):\n self.text_message = text_message\n\n def __str__(self):\n return repr(self.text_message)\n\n\nclass Attribute(object):\n def __init__(self, name, data):\n self.name = name\n self.value = data[0]\n self.min = data[1]\n self.max = data[2]\n self.modifiers = []\n\n def __repr__(self):\n return repr('{} / {}'.format(self.value, self.max))\n\n def get(self):\n total_value = self.value\n for mod in self.modifiers:\n total_value += mod[1]\n return total_value\n\n def modify(self, modifier):\n self.modifiers += modifier\n # modifier should look like this:\n # ('Name', )\n # for example:\n # ('Weakness', -1)\n # or\n # ('Oxygenized', 1)\n\n\nclass Character(object):\n def __init__(self, _id):\n character_doc = DB['characters'].find_one({'_id': ObjectId(_id)})\n\n self.name = character_doc['name']\n self.nickname = character_doc['nickname']\n self.metatype = character_doc['metatype']\n self.age = character_doc['age']\n self.karma = character_doc['karma']\n\n self.knowledges = character_doc['knowledges']\n self.skills = character_doc['skills']\n self.spells = character_doc['spells']\n self.nyuen = character_doc['nyuen']\n self.contacts = character_doc['contacts']\n self.inventory = character_doc['inventory']\n\n self.body = Attribute('body', character_doc['attributes']['body'])\n self.agility = Attribute('agility', character_doc['attributes']['agility'])\n self.reaction = Attribute('reaction', character_doc['attributes']['reaction'])\n self.strength = Attribute('strength', character_doc['attributes']['strength'])\n self.willpower = Attribute('willpower', character_doc['attributes']['willpower'])\n self.logic = Attribute('logic', character_doc['attributes']['logic'])\n self.intuition = Attribute('intuition', character_doc['attributes']['intuition'])\n self.charisma = Attribute('charisma', character_doc['attributes']['charisma'])\n self.edge = Attribute('edge', character_doc['attributes']['edge'])\n self.essence = Attribute('essence', character_doc['attributes']['essence'])\n self.magic = Attribute('magic', character_doc['attributes']['magic'])\n\n # Shortcuts\n self.attributes = {\n 'body': self.body,\n 'agility': self.agility,\n 'reaction': self.reaction,\n 'strength': self.strength,\n 'willpower': self.willpower,\n 'logic': self.logic,\n 'intuition': self.intuition,\n 'charisma': self.charisma,\n 'edge': self.edge,\n 'essence': self.essence,\n 'magic': self.magic\n }\n\n self.physical = character_doc['physical']\n self.stun = character_doc['stun']\n self.overflow = character_doc['overflow']","sub_path":"core/character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"184351881","text":"\"\"\"Given a spec, assuming we're in the homework folder, run the spec against the folder\"\"\"\n\nimport os\nfrom typing import TYPE_CHECKING\n\nfrom .record_result import RecordResult\nfrom .submission_warnings import SubmissionWarnings\nfrom .supporting import import_supporting, remove_supporting\nfrom ..common import get_assignment_first_submit_time\nfrom ..process_file import process_file\nfrom ..toolkit import global_vars\n\nif TYPE_CHECKING:\n from ..specs.spec import Spec\n from ..student.student_result import StudentResult\n\n\ndef process_assignment(*,\n student: 'StudentResult',\n spec: 'Spec',\n basedir: str,\n interact: bool,\n skip_web_compile: bool) -> RecordResult:\n \"\"\"Run a spec against the current folder\"\"\"\n cwd = os.getcwd()\n try:\n first_submit = ''\n\n if not global_vars.CI:\n first_submit = get_assignment_first_submit_time(spec, cwd)\n\n result = RecordResult(spec_id=spec.id,\n first_submission=first_submit,\n student=student.name)\n\n # prepare the current folder\n supporting_dir, written_files = import_supporting(spec=spec,\n basedir=basedir)\n\n # process the assignment\n for file_spec in spec.files:\n file_result = process_file(file_spec=file_spec,\n supporting_dir=supporting_dir,\n interact=interact,\n skip_web_compile=skip_web_compile)\n result.file_results.append(file_result)\n\n # now we remove any compiled binaries\n remove_execs(spec)\n\n # and we remove any supporting files\n remove_supporting(written_files)\n\n return result\n\n except Exception as err:\n if global_vars.DEBUG:\n raise err\n else:\n return RecordResult(student=student.name,\n spec_id=spec.id,\n warnings=SubmissionWarnings(recording_err=str(err)))\n\n\ndef remove_execs(spec: 'Spec'):\n \"\"\"Remove executable files (identified by a .exec extension)\"\"\"\n for file in spec.files:\n try:\n os.remove('{}.exec'.format(file.file_name))\n except FileNotFoundError:\n pass\n","sub_path":"stograde/process_assignment/process_assignment.py","file_name":"process_assignment.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"44830527","text":"import constants\nimport glob\nimport numpy as np\nimport os\nimport util\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage import measurements\n\n\ntrain = ['031317T', '031616', '013018S', '041318S', '050318S',\n '032318c', '032818', '022318S', '013018L', '021218S',\n '040218', '013118L', '022618', '031615', '031317L',\n '012115', '032318d', '031516', '050917', '021218L',\n '040716', '032318b', '021015', '040417', '041818',\n '022318L', '041017']\n\nsamples = [i.split('/')[-1] for i in glob.glob('data/predict_cleaned/unet3000/*')]\nos.makedirs(f'data/volumes/', exist_ok=True)\nvar = {}\n\nfor s in sorted(samples):\n print(s)\n segs = np.array([util.read_vol(f) for f in sorted(glob.glob(f'data/predict_cleaned/unet3000/{s}/{s}_*.nii.gz'))])\n\n if s in constants.TWINS:\n brains = [measurements.label(seg)[0] for seg in segs]\n vols = [measurements.sum(segs[0], brains[0], [1,2])]\n for i in range(1, len(brains)):\n intersect = brains[i-1] * brains[i]\n if 1 not in intersect and 4 not in intersect:\n brains[i] = - brains[i] + 3\n vols.append(measurements.sum(segs[i], brains[i], [1,2]))\n vols = np.array(vols).T\n else:\n vols = [np.sum(segs, axis=(1, 2, 3, 4))]\n\n for i in range(len(vols)):\n var[f'{s}_{i}'] = np.var(vols[i])\n x = np.arange(len(segs))\n y = (vols[i] / vols[i][0] - 1) * 100\n plt.ylabel('Change in Volume (%)')\n plt.plot(x, y, marker='', linewidth=1)\n plt.savefig(f'data/volumes/{s}_{i}.png')\n plt.close()\n\nsort = sorted(var.items(), key=lambda x: x[1])\nplt.figure(figsize=(10,8))\nbar = plt.bar([s[0] for s in sort], [s[1] for s in sort])\nfor i in range(len(sort)):\n if sort[i][0].split('_')[0] in train:\n bar[i].set_color('#d65555')\nplt.tick_params(axis='x', which='both', bottom=False, labelbottom=False)\nplt.ylabel('Variance in Volume')\nplt.savefig('data/variance.png')\nplt.close()\n","sub_path":"volume_plot.py","file_name":"volume_plot.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"22926753","text":"# coding:utf-8\n__author__ = 'yamamoto'\n\nimport os\nimport shutil\n\n# 作業ディレクトリをTeachingAssistantにする\nos.chdir('..')\n\n# Dropbox\\\\test_db内のsamples.dbを消去する\n# DBファイルの場所としてDropboxのpathを取得\ndata_path = os.getenv(\"HOMEDRIVE\") + \\\n os.getenv(\"HOMEPATH\") + \\\n \"\\\\Dropbox\\\\teach_db\\\\samples.db\"\n\nif os.path.isfile(data_path):\n os.remove(data_path)\n\n# FaceClipper\\static\\imagesを消去する\nif os.path.isdir('FaceClipper\\\\static\\\\images'):\n shutil.rmtree('FaceClipper\\\\static\\\\images')\n\n\n# AddTrainImages\\images_newを消去する\nif os.path.isdir('AddTrainImages\\\\images_new'):\n shutil.rmtree('AddTrainImages\\\\images_new')\n\n\n# AddTrainImages\\\\TrainData.csvを消去する\nif os.path.isfile('AddTrainImages\\\\TrainData.csv'):\n os.remove('AddTrainImages\\\\TrainData.csv')\n\n\n# CollectTrainImages\\\\TrainData.csvを消去する\nif os.path.isfile('CollectTrainImages\\\\TrainData_collect.csv'):\n os.remove('CollectTrainImages\\\\TrainData_collect.csv')\n\n\n# DBOutput\\\\bg.txtを消去する\nif os.path.isfile('DBOutput\\\\bg.txt'):\n os.remove('DBOutput\\\\bg.txt')\n\n\n# DBOutput\\\\info.datを消去する\nif os.path.isfile('DBOutput\\\\info.dat'):\n os.remove('DBOutput\\\\info.dat')\n\n\n# DBOutput\\\\TeacherData.csvを消去する\nif os.path.isfile('DBOutput\\\\TeacherData.csv'):\n os.remove('DBOutput\\\\TeacherData.csv')\n\n\n# DBOutput\\\\progress.csvを消去する\nif os.path.isfile('DBOutput\\\\progress.csv'):\n os.remove('DBOutput\\\\progress.csv')","sub_path":"TeachingAssistant/InitializeSetting/InitializeSetting.py","file_name":"InitializeSetting.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"84044471","text":"#!/usr/bin/env python\n\nimport rospy\nfrom h264_image_transport.msg import H264Packet\nfrom geometry_msgs.msg import Twist\nfrom tello_driver.msg import TelloStatus\nfrom std_msgs.msg import Empty, UInt8\nfrom tello_driver.msg import test\nimport av\nimport cv2\nimport numpy as np\nimport threading\nimport traceback\nimport time\nimport math\nimport apriltag\n\nclass StandaloneVideoStream(object):\n def __init__(self):\n self.cond = threading.Condition()\n self.queue = []\n self.closed = False\n\n def read(self, size):\n self.cond.acquire()\n try:\n if len(self.queue) == 0 and not self.closed:\n self.cond.wait(2.0)\n data = bytes()\n while 0 < len(self.queue) and len(data) + len(self.queue[0]) < size:\n data = data + self.queue[0]\n del self.queue[0]\n finally:\n self.cond.release()\n return data\n\n def seek(self, offset, whence):\n return -1\n\n def close(self):\n self.cond.acquire()\n self.queue = []\n self.closed = True\n self.cond.notifyAll()\n self.cond.release()\n\n def add_frame(self, buf):\n self.cond.acquire()\n self.queue.append(buf)\n self.cond.notifyAll()\n self.cond.release()\n\n\nstream = StandaloneVideoStream()\n\nglobal cont\ncont = True\n\ndef callback(msg):\n #rospy.loginfo('frame: %d bytes' % len(msg.data))\n #if len(msg.data) > 1000: \n stream.add_frame(msg.data)\n\ndef call(data):\n global cont\n #f.write(str(data))\n if int(data.fly_mode) == 12:\n cont = False\n\ndef TO():\n takeoff_pub = rospy.Publisher('/tello/takeoff',Empty,queue_size = 1)\n rospy.init_node('turtlesim_pub',anonymous = True)\n rate = rospy.Rate(10)\n msg = Empty()\n rospy.loginfo(msg)\n takeoff_pub.publish(msg)\n rate.sleep()\n\ndef L():\n global cont\n land_sub = rospy.Subscriber('/tello/status',TelloStatus,call)\n land_pub = rospy.Publisher('/tello/land',Empty,queue_size = 1)\n rate = rospy.Rate(10)\n while cont == True:\n msg = Empty()\n land_pub.publish(msg)\n rate.sleep()\n\ndef flip():\n cmd_pub = rospy.Publisher('/tello/cmd_vel',Twist,queue_size = 10)\n rate = rospy.Rate(10)\n count = 20\n while not rospy.is_shutdown():\n if count >0:\n msg = Twist()\n msg.linear.y = -0.3\n cmd_pub.publish(msg)\n rate.sleep()\n count -= 1\n else:\n cmd_pub.publish(Twist())\n rate.sleep()\n break\n \n \ndef round():\n round_pub = rospy.Publisher('/tello/cmd_vel',Twist,queue_size = 10)\n rate = rospy.Rate(10)\n count = 20\n while not rospy.is_shutdown():\n if count>0:\n msg = Twist()\n msg.angular.z = 0.6\n round_pub.publish(msg)\n rate.sleep()\n count -= 1\n else:\n round_pub.publish(Twist())\n rate.sleep()\n break\ndef back():\n forward_pub = rospy.Publisher('/tello/cmd_vel',Twist,queue_size = 10)\n cmd_flip = rospy.Publisher('/tello/flip',UInt8,queue_size = 10)\n rate = rospy.Rate(10)\n count = 50\n while not rospy.is_shutdown():\n if count>0 and count != 1:\n msg = Twist()\n msg.linear.x = 0.3\n forward_pub.publish(msg)\n rate.sleep()\n count -= 1\n elif count == 1:\n cmd_flip.publish(0)\n rate.sleep()\n time.sleep(3)\n count -= 1\n else:\n msg = Twist()\n msg.linear.x = 0.0\n rospy.loginfo(msg)\n forward_pub.publish(msg)\n rate.sleep()\n break\n\n\ndef findMask(img):\n lr0 = np.array([0,150,0])\n ur0 = np.array([5,255,255])\n lr1 = np.array([175,150,0])\n ur1 = np.array([180,255,255])\n #lb = np.array([112,170,0])\n #ub = np.array([128,255,255])\n rm0 = cv2.inRange(img, lr0, ur0)\n rm1 = cv2.inRange(img, lr1, ur1)\n #bm = cv2.inRange(img, lb, ub)\n rm = cv2.bitwise_or(rm0, rm1)\n #m = cv2.bitwise_or(rm, bm)\n return rm\n\ndef findMask1(img):\n lb = np.array([100,30,0])\n ub = np.array([140,255,255])\n bm = cv2.inRange(img, lb, ub)\n return bm\n\ndef main():\n old_center = [0,0]\n fourcc = cv2.VideoWriter_fourcc('X','V','I','D')\n out = cv2.VideoWriter('test_contour.avi', fourcc, 30.0, (1920, 720))\n #rospy.init_node('h264_listener')\n rospy.Subscriber(\"/tello/image_raw/h264\", H264Packet, callback)\n pub = rospy.Publisher('/selfDefined', test, queue_size = 1)\n container = av.open(stream)\n rospy.loginfo('main: opened')\n detector = apriltag.Detector()\n frame_skip = 300\n t = 0\n thr = 0.32\n for frame in container.decode(video=0):\n if 0 < frame_skip:\n frame_skip -= 1\n continue\n start_time = time.time()\n image = cv2.cvtColor(np.array(frame.to_image()), cv2.COLOR_RGB2BGR)\n img = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n blurred_img = cv2.GaussianBlur(image, (13, 13), 0)\n result = detector.detect(img)\n #print(result[0].tag_id)\n if len(result)!=0:\n print(result[0].tag_id)\n if result[0].tag_id == 0:\n flip()\n elif result[0].tag_id == 1:\n round()\n elif result[0].tag_id == 2:\n back()\n time.sleep(3)\n L()\n else:\n continue\n\n '''hsv_img = cv2.cvtColor(blurred_img.copy(), cv2.COLOR_BGR2HSV)\n if t == 1:\n red_mask = findMask(hsv_img)\n thr = 0.32\n elif t == 0:\n red_mask = findMask1(hsv_img)\n thr = 0.3\n (c_i, c_c, c_h) = cv2.findContours(red_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n show_image = cv2.cvtColor(c_i, cv2.COLOR_GRAY2BGR)\n cv2.drawContours(show_image, c_c, 0, (0,0,255), -1)\n if(len(c_c) == 0):\n pub.publish(test([0,0,0]))\n continue\n out_max_contours = max(c_c, key = cv2.contourArea)\n rect = cv2.minAreaRect(out_max_contours)\n rect_width, rect_height = rect[1]\n if(rect_width*rect_height < 0.2*960*720.0):\n pub.publish(test([0,0,0]))\n continue\n #avg_x = []\n #avg_y = []\n #for c in out_max_contours:\n # avg_x.append(c[0][0])\n # avg_y.append(c[0][1])\n ce_x = rect[0][0] + 1/2*rect_width\n ce_y = rect[0][1] + 1/2*rect_height\n if old_center[0] == 0 and old_center[1] == 0:\n old_center = [int(ce_x),int(ce_y)]\n pub.publish(test([int(old_center[0]),int(old_center[1]),1]))\n else:\n #print(math.sqrt( (int(mean_y) - old_center[0])**2 + (int(mean_x) - old_center[1])**2 ))\n cv2.putText(show_image, str(rect_width*rect_height / (960*720.0)), (10,40),5 ,2, 255)\n if rect_width*rect_height >= 960*720*thr:\n pub.publish(test([old_center[0],old_center[1],-1]))\n print(\">= 100\")\n temp = time.time()\n while time.time() - temp < 3.1:\n pass\n t = 1\n else:\n old_center = [int(ce_x),int(ce_y)]\n pub.publish(test([int(old_center[0]),int(old_center[1]),1]))\n \n out.write(np.concatenate((blurred_img, show_image), axis=1))\n cv2.imshow('result', np.concatenate((blurred_img, show_image), axis=1))\n cv2.waitKey(1)'''\n if frame.time_base < 1.0/60:\n time_base = 1.0/60\n else:\n time_base = frame.time_base\n frame_skip = int((time.time() - start_time)/time_base)\n\nif __name__ == '__main__':\n try:\n TO()\n main()\n except BaseException:\n traceback.print_exc()\n finally:\n stream.close()\n cv2.destroyAllWindows()\n","sub_path":"src/test_h264_fsm_contour.py","file_name":"test_h264_fsm_contour.py","file_ext":"py","file_size_in_byte":7555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"478638580","text":"import autograd.numpy as np\nimport autograd.numpy.random as npr\n\nfrom sds import rARHMM\nfrom sds.observations import LinearGaussianObservation\nfrom sds.utils import ensure_args_are_viable_lists\n\n\nclass erARHMM(rARHMM):\n\n def __init__(self, nb_states, dm_obs, dm_act, trans_type='poly',\n init_state_prior={}, init_obs_prior={}, trans_prior={}, obs_prior={}, ctl_prior={},\n init_state_kwargs={}, init_obs_kwargs={}, trans_kwargs={}, obs_kwargs={}, ctl_kwargs={},\n learn_dyn=True, learn_ctl=False):\n\n super(erARHMM, self).__init__(nb_states, dm_obs, dm_act, trans_type,\n init_state_prior=init_state_prior, init_obs_prior=init_obs_prior, obs_prior=obs_prior, trans_prior=trans_prior,\n init_state_kwargs=init_state_kwargs, init_obs_kwargs=init_obs_kwargs, obs_kwargs=obs_kwargs, trans_kwargs=trans_kwargs)\n\n self.learn_dyn = learn_dyn\n self.learn_ctl = learn_ctl\n\n self.controls = LinearGaussianObservation(self.nb_states, self.dm_obs, self.dm_act,\n prior=ctl_prior, **ctl_kwargs)\n\n @ensure_args_are_viable_lists\n def initialize(self, obs, act=None, **kwargs):\n super(erARHMM, self).initialize(obs, act, **kwargs)\n if self.learn_ctl:\n self.controls.initialize(obs, act, **kwargs)\n\n def log_priors(self):\n lp = 0.\n if self.learn_dyn:\n lp += super(erARHMM, self).log_priors()\n if self.learn_ctl:\n lp += self.controls.log_prior()\n return lp\n\n @ensure_args_are_viable_lists\n def log_likelihoods(self, obs, act=None):\n loginit, logtrans, logobs = super(erARHMM, self).log_likelihoods(obs, act)\n\n if self.learn_ctl:\n total_logobs = []\n logctl = self.controls.log_likelihood(obs, act)\n for _logobs, _logctl in zip(logobs, logctl):\n total_logobs.append(_logobs + _logctl)\n return [loginit, logtrans, total_logobs]\n else:\n return [loginit, logtrans, logobs]\n\n def mstep(self, gamma, zeta,\n obs, act,\n init_mstep_kwargs,\n trans_mstep_kwargs,\n obs_mstep_kwargs, **kwargs):\n\n ctl_mstep_kwargs = kwargs.get('ctl_mstep_kwargs', {})\n\n if self.learn_dyn:\n self.init_state.mstep([_gamma[0, :] for _gamma in gamma], **init_mstep_kwargs)\n self.transitions.mstep(zeta, obs, act, **trans_mstep_kwargs)\n self.observations.mstep(gamma, obs, act, **obs_mstep_kwargs)\n if self.learn_ctl:\n self.controls.mstep(gamma, obs, act, **ctl_mstep_kwargs)\n\n def permute(self, perm):\n super(erARHMM, self).permute(perm)\n self.controls.permute(perm)\n\n @ensure_args_are_viable_lists\n def mean_observation(self, obs, act=None):\n if self.learn_ctl:\n loglikhds = self.log_likelihoods(obs, act)\n alpha = self.forward(loglikhds)\n beta = self.backward(loglikhds)\n gamma = self.marginals(alpha, beta)\n\n mu_obs = self.observations.smooth(gamma, obs, act)\n mu_ctl = self.controls.smooth(gamma, obs, act)\n return mu_obs, mu_ctl\n else:\n return super(erARHMM, self).mean_observation(obs, act)\n\n def sample(self, act=None, horizon=None, stoch=True):\n if self.learn_ctl:\n state = []\n obs = []\n act = []\n\n for n in range(len(horizon)):\n _state = np.zeros((horizon[n],), np.int64)\n _obs = np.zeros((horizon[n], self.dm_obs))\n _act = np.zeros((horizon[n], self.dm_act))\n\n _state[0] = self.init_state.sample()\n _obs[0, :] = self.init_observation.sample(_state[0], stoch=stoch)\n _act[0, :] = self.observations.controls.sample(_state[0], _obs[0, :], stoch=stoch)\n for t in range(1, horizon[n]):\n _state[t] = self.transitions.sample(_state[t - 1], _obs[t - 1, :], _act[t - 1, :])\n _obs[t, :] = self.observations.sample(_state[t], _obs[t - 1, :], _act[t - 1, :], stoch=stoch)\n _act[t, :] = self.controls.sample(_state[t], _obs[t, :], stoch=stoch)\n\n state.append(_state)\n obs.append(_obs)\n act.append(_act)\n\n return state, obs, act\n else:\n return super(erARHMM, self).sample(act, horizon, stoch)\n\n def step(self, hist_obs=None, hist_act=None, stoch=True, infer='viterbi'):\n if self.learn_ctl:\n if infer == 'viterbi':\n _, _state_seq = self.viterbi(hist_obs, hist_act)\n _state = _state_seq[0][-1]\n else:\n _belief = self.filter(hist_obs, hist_act)\n _state = npr.choice(self.nb_states, p=_belief[0][-1, ...])\n\n _act = hist_act[-1, :]\n _obs = hist_obs[-1, :]\n\n nxt_state = self.transitions.sample(_state, _obs, _act)\n nxt_obs = self.observations.sample(nxt_state, _obs, _act, stoch=stoch)\n nxt_act = self.controls.sample(nxt_state, nxt_obs, stoch=stoch)\n return nxt_state, nxt_obs, nxt_act\n else:\n return super(erARHMM, self).step(hist_obs, hist_act, stoch, infer)\n\n def forcast(self, hist_obs=None, hist_act=None, nxt_act=None,\n horizon=None, stoch=True, infer='viterbi'):\n if self.learn_ctl:\n nxt_state = []\n nxt_obs = []\n nxt_act = []\n\n for n in range(len(horizon)):\n _hist_obs = hist_obs[n]\n _hist_act = hist_act[n]\n\n _nxt_act = np.zeros((horizon[n] + 1, self.dm_act))\n _nxt_obs = np.zeros((horizon[n] + 1, self.dm_obs))\n _nxt_state = np.zeros((horizon[n] + 1,), np.int64)\n\n if infer == 'viterbi':\n _, _state_seq = self.viterbi(_hist_obs, _hist_act)\n _state = _state_seq[0][-1]\n else:\n _belief = self.filter(_hist_obs, _hist_act)\n _state = npr.choice(self.nb_states, p=_belief[0][-1, ...])\n\n _nxt_state[0] = _state\n _nxt_obs[0, :] = _hist_obs[-1, ...]\n _nxt_act[0, :] = _hist_act[-1, ...]\n\n for t in range(horizon[n]):\n _nxt_state[t + 1] = self.transitions.sample(_nxt_state[t], _nxt_obs[t, :], _nxt_act[t, :])\n _nxt_obs[t + 1, :] = self.observations.sample(_nxt_state[t + 1], _nxt_obs[t, :], _nxt_act[t, :], stoch=stoch)\n _nxt_act[t + 1, :] = self.controls.sample(_nxt_state[t + 1], _nxt_obs[t + 1, :], stoch=stoch)\n\n nxt_state.append(_nxt_state)\n nxt_obs.append(_nxt_obs)\n nxt_act.append(_nxt_act)\n\n return nxt_state, nxt_obs, nxt_act\n else:\n return super(erARHMM, self).forcast(hist_obs, hist_act, nxt_act, horizon, stoch, infer)\n\n @ensure_args_are_viable_lists\n def kstep_mse(self, obs, act, horizon=1, stoch=True, infer='viterbi'):\n if self.learn_ctl:\n from sklearn.metrics import mean_squared_error, explained_variance_score\n\n mse, norm_mse = [], []\n for _obs, _act in zip(obs, act):\n _hist_obs, _hist_act = [], []\n _target, _prediction = [], []\n\n _nb_steps = _obs.shape[0] - horizon\n for t in range(_nb_steps):\n _hist_obs.append(_obs[:t + 1, :])\n _hist_act.append(_act[:t + 1, :])\n\n _hr = [horizon for _ in range(_nb_steps)]\n _, _obs_hat, _act_hat = self.forcast(hist_obs=_hist_obs, hist_act=_hist_act,\n nxt_act=None, horizon=_hr,\n stoch=stoch, infer=infer)\n\n for t in range(_nb_steps):\n _target.append(np.hstack((_obs[t + horizon, :], _act[t + horizon, :])))\n _prediction.append(np.hstack((_obs_hat[t][-1, :], _act_hat[t][-1, :])))\n\n _target = np.vstack(_target)\n _prediction = np.vstack(_prediction)\n\n _mse = mean_squared_error(_target, _prediction)\n _norm_mse = explained_variance_score(_target, _prediction, multioutput='variance_weighted')\n\n mse.append(_mse)\n norm_mse.append(_norm_mse)\n\n return np.mean(mse), np.mean(norm_mse)\n else:\n return super(erARHMM, self).kstep_mse(obs, act, horizon=horizon, stoch=stoch, infer=infer)\n","sub_path":"sds/erarhmm.py","file_name":"erarhmm.py","file_ext":"py","file_size_in_byte":8757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"396886752","text":"import os\nimport django\ndjango.setup()\nfrom sefaria.model import *\nfrom sources.functions import UnicodeReader, get_index_api, post_index\nfrom sefaria.helper.schema import migrate_to_complex_structure\nif __name__ == \"__main__\":\n files = [f for f in os.listdir('.') if f.endswith(\".csv\")]\n nodes = []\n for f in files:\n schema = SchemaNode()\n en_title = f.replace(\".csv\", \"\")\n he_title = library.get_index(en_title).get_title('he')\n schema.add_primary_titles(en_title, he_title)\n reader = UnicodeReader(open(f))\n for row in reader:\n he, en, first, last = row\n node = ArrayMapNode()\n node.add_primary_titles(en, he)\n node.depth = 0\n node.wholeRef = \"Arukh HaShulchan, {} {}-{}\".format(en_title, first, last)\n node.refs = []\n schema.append(node)\n nodes.append(schema.serialize())\n\n index = get_index_api(\"Arukh HaShulchan\", server=\"http://draft.sefaria.org\")\n index['alt_structs'] = {\"Subject\": {\"nodes\": nodes}}\n # post_index(index, server=\"http://draft.sefaria.org\")\n mapping = {\n \"Arukh HaShulchan 1\": \"Arukh HaShulchan, Orach Chaim\",\n \"Arukh HaShulchan 2\": \"Arukh HaShulchan, Yoreh Deah\",\n \"Arukh HaShulchan 3\": \"Arukh HaShulchan, Even HaEzer\",\n \"Arukh HaShulchan 4\": \"Arukh HaShulchan, Choshen Mishpat\"\n }\n\n migrate_to_complex_structure(\"Arukh HaShulchan\", mapping)","sub_path":"sources/Arukh HaShulchan/alt_toc.py","file_name":"alt_toc.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"345733353","text":"\"\"\"\n netvisor.schemas.common\n ~~~~~~~~~~~~~~~~~~~~~~~\n\n :copyright: (c) 2013-2016 by Fast Monkeys Oy | 2019- by Heltti Oy\n :license: MIT, see LICENSE for more details.\n\"\"\"\nfrom marshmallow import (\n MarshalResult,\n Schema,\n ValidationError,\n fields,\n pre_dump,\n pre_load,\n)\n\nfrom .fields import Decimal\n\n\nclass RejectUnknownFieldsSchema(Schema):\n @pre_dump\n def check_unknown_fields(self, data):\n field_names = set()\n for field_name, field in self.fields.items():\n attribute = getattr(field, \"attribute\", None)\n field_names.add(field_name if attribute is None else attribute)\n for k in data:\n if k not in field_names:\n raise ValidationError(\"Unknown field name: '{}'\".format(k))\n\n\nclass FlattenElementSchema(Schema):\n @pre_load\n def pre_load(self, data):\n if isinstance(data, (str,)):\n return {\"#text\": data}\n return data\n\n def load(self, *args, **kwargs):\n result = super(FlattenElementSchema, self).load(*args, **kwargs)\n return MarshalResult(result.data.get(\"text\"), result.errors)\n\n\nclass DateSchema(FlattenElementSchema):\n text = fields.Date(load_from=\"#text\")\n\n\nclass StringSchema(FlattenElementSchema):\n text = fields.String(load_from=\"#text\")\n\n\nclass DecimalSchema(FlattenElementSchema):\n text = Decimal(load_from=\"#text\")\n","sub_path":"netvisor_api_client/schemas/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"600985265","text":"from io import BytesIO\nimport base64\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.contrib.staticfiles.templatetags.staticfiles import static\nfrom .utils import inputs_form, label_form, network\n\nimport numpy as np\n\nnet = network()\n\ndef mnist_cgan(request):\n if request.method == 'POST':\n noiseform = inputs_form(data=request.POST)\n labelform = label_form(data=request.POST)\n noise = [float(request.POST['input_noise_%d'%i]) for i in range(64)]\n label_data = list(map(int, list(request.POST['labels_input'])))\n noise = np.array(noise)\n noise = np.tile(noise, (len(label_data), 1))\n label = np.identity(10)[label_data]\n image = net.prediction(noise, label)\n buffer = BytesIO()\n image.save(buffer, format='PNG')\n base64img = base64.b64encode(buffer.getvalue()).decode().replace(\"'\", \"\")\n else:\n noiseform = inputs_form({})\n labelform = label_form({})\n base64img = None\n param = {'noise' : noiseform, 'label' : labelform, 'b64img' : base64img}\n return render(request, 'tfd/mnist_cgan.html', context=param)","sub_path":"tfd/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"333104202","text":"def Delta_W(pars):\n \"\"\"\n Plot STDP biphasic exponential decaying function\n \n Args:\n pars : parameter dictionary\n \n Returns:\n dW : instantaneous change in weights\n \"\"\"\n \n # Get parameters\n A_plus, A_minus, tau_stdp = pars['A_plus'], pars['A_minus'], pars['tau_stdp']\n \n # pre_spike time - post_spike time\n time_diff = np.linspace(-5*tau_stdp, 5*tau_stdp, 50)\n \n # STDP change\n dW = np.zeros(len(time_diff))\n dW[time_diff<=0] = A_plus * np.exp(time_diff[time_diff<=0]/tau_stdp) #LTP\n dW[time_diff>0] = -A_minus * np.exp(-time_diff[time_diff>0]/tau_stdp) #LTD\n\n with plt.xkcd():\n plt.figure()\n plt.plot([-5*tau_stdp,5*tau_stdp],[0,0],'k',linestyle=':')\n plt.plot([0,0],[-A_minus,A_plus],'k',linestyle=':')\n\n plt.plot(time_diff[time_diff<=0], dW[time_diff<=0], 'ro')\n plt.plot(time_diff[time_diff>0], dW[time_diff>0], 'bo')\n\n plt.xlabel(r't$_{\\mathrm{pre}}$ - t$_{\\mathrm{post}}$ (ms)')\n plt.title('Biphasic STDP', fontweight='bold')\n plt.show()\n \npars = default_pars_STDP()\nDelta_W(pars)","sub_path":"tutorials/W3D1_RealNeurons/solutions/W3D1_Tutorial4_Solution_92eaf485.py","file_name":"W3D1_Tutorial4_Solution_92eaf485.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"576515470","text":"from discord.ext import commands\n\n\ndef set_disabled(command):\n if not hasattr(command, \"disabled_in\"):\n setattr(command, \"disabled_in\", {})\n\n\nasync def set_disable_state(ctx, command, state):\n return await ctx.bot.db.execute(\n \"INSERT INTO `disable` VALUES (?, ?, ?)\",\n ctx.guild.id, command.qualified_name, state,\n with_commit=True)\n\n\ndef disabled_command():\n\n async def predicate(ctx):\n if ctx.bot.is_owner(ctx.author):\n return True\n\n set_disabled(ctx.command)\n\n if ctx.guild.id not in ctx.command.disabled_in:\n ctx.command.disabled_in[ctx.guild.id] = True\n raise commands.DisabledCommand()\n\n return True\n\n return commands.check(predicate)","sub_path":"src/cogs/utils/disable.py","file_name":"disable.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"599541893","text":"import sys\nread=lambda:sys.stdin.readline().strip()\nwrite=lambda x:sys.stdout.write(x+\"\\n\")\nT = int(read())\nOFF = 32768\ndef possible(a, b):\n iy, ix = a\n jy, jx = b\n return (abs(iy - jy) + abs(ix - jx)) <= 1000\n\nfor i in range(T):\n n = int(read())\n h_x, h_y = map(int, read().split())\n h = h_y, h_x = h_y+OFF, h_x+OFF\n\n\n convs = set()\n for j in range(n):\n x, y = map(int, read().split())\n convs.add((y+OFF, x+OFF))\n r_x, r_y = map(int, read().split())\n r = r_y, r_x = r_y+OFF, r_x+OFF \n\n coords = convs.union({h, r})\n dist = {(a, b):{(c, d):False for c, d in coords} for a, b in coords}\n for i in coords:\n for j in coords: \n dist[i][j] = possible(i,j)\n\n if dist[h][r]:\n write(\"happy\")\n continue\n \n for k in coords:\n if dist[h][r]:\n break\n for i in coords:\n A = dist[i][k]\n if not A:\n continue\n for j in coords:\n if (i == j) or (j == k):\n continue\n B = dist[k][j]\n if not B:\n continue\n C = dist[i][j]\n if not C:\n dist[i][j] = True\n\n\n if dist[h][r]:\n write(\"happy\")\n else:\n write(\"sad\")","sub_path":"graph_problems/Shortest_path/floyd_warshall/take3_9205.py","file_name":"take3_9205.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"454779265","text":"import popplerqt5\nfrom PyQt5 import QtGui, QtCore, QtWidgets, uic, QtPrintSupport\nimport os\nimport subprocess\nfrom .widgets.textitem import TextItem\nfrom .widgets.pdfpageitem import PdfPageItem\nfrom .widgets.item import ItemBase, ImageItem, RectItem\nfrom .widgets.strikethrough import StrikethroughItem\n\n\nclass ObjectTreeModel(QtCore.QAbstractItemModel):\n def __init__(self, project):\n QtCore.QAbstractItemModel.__init__(self)\n self.project = project\n\n def columnCount(self, parent):\n return 1\n\n def rowCount(self, parent):\n p = self.project\n if parent.isValid():\n p = parent.internalPointer()\n if isinstance(p, Project):\n return len(p.pages)\n elif isinstance(p, Page):\n return len(p.objects)\n else:\n return 0\n\n def data(self, index, role):\n if not index.isValid():\n return None\n if role != QtCore.Qt.DisplayRole:\n return None\n i = index.internalPointer()\n if isinstance(i, Page):\n return \"Page %i\" % (i.number + 1)\n elif isinstance(i, ItemBase):\n return i.getName()\n return None\n\n def parent(self, index):\n if not index.isValid():\n return None\n p = index.internalPointer()\n if isinstance(p, Page):\n return self.createIndex(0, 0, p.project)\n elif isinstance(p, ItemBase):\n return self.createIndex(0, 0, p.page)\n return QtCore.QModelIndex()\n\n def index(self, row, column, parent):\n p = self.project\n if parent.isValid():\n p = parent.internalPointer()\n if row < 0:\n return None\n if isinstance(p, Project):\n if row >= len(p.pages):\n return None\n return self.createIndex(row, column, p.pages[row])\n elif isinstance(p, Page):\n if row >= len(p.objects):\n return None\n return self.createIndex(row, column, p.objects[row])\n else:\n return None\n\n\nclass Page(QtCore.QObject):\n def __init__(self, project, i):\n QtCore.QObject.__init__(self)\n self.number = i\n self.objects = []\n\n self.scene = QtWidgets.QGraphicsScene()\n self.scene.setBackgroundBrush(QtCore.Qt.gray)\n self.pageItem = PdfPageItem(project.document.page(i), self)\n self.scene.addItem(self.pageItem)\n\n self.project = project\n\n def text_selection_changed(self, nonempty):\n if nonempty:\n self.scene.clearSelection()\n\n def insertV(self, v_point):\n v_text = self._addText(v_point, \"topleft\", focus=False)\n v_text.setPlainText(\"v\")\n return v_text\n\n def insertText(self, topleft):\n return self._addText(topleft, \"topleft\", focus=True)\n\n def insertStrikethrough(self, line_bbox):\n item = StrikethroughItem(self, line_bbox)\n self.scene.addItem(item)\n self.objects.append(item)\n return item\n\n def addTextUnderCursor(self, application):\n pos = application.pageView.mapToScene(\n application.pageView.mapFromGlobal(QtGui.QCursor.pos())\n )\n anchor = \"baseline\"\n self._addText(pos, \"baseline\", focus=True)\n\n def _addText(self, pos, anchor, focus):\n text = TextItem(self, self.myFont)\n if anchor == \"baseline\":\n font_metrics = QtGui.QFontMetrics(text.font())\n topleft = QtCore.QPointF(\n pos.x(), pos.y() - font_metrics.ascent() - font_metrics.leading() - 1\n )\n elif anchor == \"topleft\":\n topleft = pos\n else:\n raise ValueError(anchor)\n text.setPos(topleft)\n self.scene.addItem(text)\n self.objects.append(text)\n if focus:\n text.setSelected(True)\n text.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction)\n selection = text.textCursor()\n selection.select(QtGui.QTextCursor.Document)\n text.setTextCursor(selection)\n text.setFocus()\n return text\n\n def save(self, stream, version):\n stream.writeUInt32(len(self.objects))\n for obj in self.objects:\n stream.writeUInt32(obj.id())\n obj.save(stream, version)\n\n def load(self, stream, version):\n count = stream.readUInt32()\n for i in range(count):\n d = stream.readUInt32()\n for t in [ImageItem, RectItem, TextItem, StrikethroughItem]:\n if t.id() != d:\n continue\n item = t(self)\n item.load(stream, version)\n self.scene.addItem(item)\n self.objects.append(item)\n\n def deleteSelection(self):\n for item in self.scene.selectedItems():\n self.scene.removeItem(item)\n self.objects.remove(item)\n\n def itemSelected(self, item):\n self.parent.itemSelected.emit(item)\n\n def changeFont(self, font):\n self.myFont = font\n for item in self.scene.selectedItems():\n if isinstance(item, TextItem):\n item.setFont(font)\n\n\nclass Project(QtCore.QObject):\n itemSelected = QtCore.pyqtSignal([QtWidgets.QGraphicsItem])\n\n def __init__(self):\n super().__init__()\n self.undoStack = QtWidgets.QUndoStack()\n self.document = None\n self.pages = []\n self.treeModel = ObjectTreeModel(self)\n self.path = None\n\n def load_pdf(self, pdfData):\n self.undoStack.clear()\n self.pdfData = pdfData\n self.document = popplerqt5.Poppler.Document.loadFromData(pdfData)\n self.document.setRenderHint(popplerqt5.Poppler.Document.Antialiasing, True)\n self.document.setRenderHint(popplerqt5.Poppler.Document.TextAntialiasing, True)\n self.pages = [Page(self, i) for i in range(self.document.numPages())]\n\n def create(self, path):\n if not os.path.exists(path):\n raise IOError(\"%s does not exist\" % (path,))\n pdf = QtCore.QFile(path)\n pdf.open(QtCore.QIODevice.ReadOnly)\n pdfData = pdf.readAll()\n self.load_pdf(pdfData)\n self.path = os.path.splitext(str(path))[0] + \".pep\"\n\n def save(self):\n f = QtCore.QFile(self.path)\n f.open(QtCore.QIODevice.WriteOnly)\n stream = QtCore.QDataStream(f)\n stream.writeUInt32(0x2a04c304)\n version = 0\n stream.writeUInt32(version)\n stream.writeQString(self.path)\n stream.writeBytes(self.pdfData)\n stream.writeUInt32(len(self.pages))\n for page in self.pages:\n page.save(stream, version)\n\n def saveas(self, path):\n self.path = str(path)\n self.save()\n\n def load(self, path):\n f = QtCore.QFile(path)\n f.open(QtCore.QIODevice.ReadOnly)\n stream = QtCore.QDataStream(f)\n if stream.readUInt32() != 0x2a04c304:\n return None\n version = stream.readUInt32()\n if version > 0:\n return None\n self.path = stream.readQString()\n pdfData = stream.readBytes()\n self.load_pdf(pdfData)\n pages = stream.readUInt32()\n for i in range(pages - len(self.pages)):\n self.addPage()\n for page in self.pages:\n page.load(stream, version)\n self.changeFont(self.font)\n\n def addPage():\n pass\n\n def export(self, path):\n printer = QtPrintSupport.QPrinter()\n printer.setColorMode(QtPrintSupport.QPrinter.Color)\n printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat)\n printer.setOutputFileName(path + \"~1\")\n printer.setPageMargins(0, 0, 0, 0, QtPrintSupport.QPrinter.Point)\n page = self.document.page(0)\n printer.setPaperSize(page.pageSizeF(), QtPrintSupport.QPrinter.Point)\n\n painter = QtGui.QPainter()\n if not painter.begin(printer):\n return\n\n first = True\n for page in self.pages:\n if first:\n first = False\n else:\n printer.newPage()\n page.pageItem.hide()\n bg = page.scene.backgroundBrush()\n page.scene.setBackgroundBrush(QtGui.QBrush(QtCore.Qt.NoBrush))\n page.scene.render(painter, QtCore.QRectF(), page.pageItem.boundingRect())\n page.scene.setBackgroundBrush(bg)\n page.pageItem.show()\n painter.end()\n del painter\n del printer\n f = QtCore.QFile(path + \"~2\")\n f.open(QtCore.QIODevice.WriteOnly)\n f.write(self.pdfData)\n f.close()\n subprocess.call(\n [\"pdftk\", path + \"~1\", \"multibackground\", path + \"~2\", \"output\", path]\n )\n os.remove(path + \"~1\")\n os.remove(path + \"~2\")\n\n def changeFont(self, font):\n self.font = font\n for page in self.pages:\n page.changeFont(font)\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n currentPageChanged = QtCore.pyqtSignal(Page)\n\n def setCurrentPage(self, page):\n if page == self.currentPage:\n return\n self.currentPage = page\n self.currentPageChanged.emit(page)\n self.treeView.clearSelection()\n if page:\n self.treeView.selectionModel().setCurrentIndex(\n self.project.treeModel.createIndex(0, 0, page),\n QtCore.QItemSelectionModel.ClearAndSelect,\n )\n\n def currentObjectChanged(self, current, previous):\n p = current.internalPointer()\n if isinstance(p, Page):\n self.setCurrentPage(p)\n elif isinstance(p, ItemBase):\n self.setCurrentPage(p.page)\n\n def __init__(self):\n QtCore.QObject.__init__(self)\n uic.loadUi(\n os.path.join(os.path.dirname(os.path.realpath(__file__)), \"main.ui\"), self\n )\n\n self.textToolBar.addWidget(self.fontCombo)\n\n self.textToolBar.addWidget(self.fontSizeCombo)\n self.fontSizeCombo.setValidator(QtGui.QIntValidator(2, 64, self))\n\n self.project = Project()\n self.project.itemSelected.connect(self.itemSelected)\n\n self.currentPage = None\n\n # self.actionAddImage.triggered.connect(self.addImage)\n\n # Action group ensures that when one action is selected, the others are unselected\n toolGroup = QtWidgets.QActionGroup(self)\n toolGroup.addAction(self.actionSizeTool)\n toolGroup.addAction(self.actionRectangleTool)\n toolGroup.addAction(self.actionLineTool)\n toolGroup.addAction(self.actionTextTool)\n self.actionSizeTool.setChecked(True)\n\n self.treeView.setModel(self.project.treeModel)\n self.treeView.selectionModel().currentChanged.connect(self.currentObjectChanged)\n\n self.handleFontChange()\n\n def doNewProject(self, path):\n self.setCurrentPage(None)\n self.project.create(path)\n if self.project.pages:\n self.setCurrentPage(self.project.pages[0])\n self.handleFontChange()\n\n def newProject(self):\n path = QtWidgets.QFileDialog.getOpenFileName(\n self, \"Open PDF file\", \"\", \"PDF document (*.pdf);;All files (*)\"\n )\n if path:\n self.doNewProject(path)\n\n def export(self):\n a, e = os.path.splitext(str(self.project.path))\n path = a + \"_ann.pdf\"\n # path = QtWidgets.QFileDialog.getSaveFileName(\n # self, \"Export pdf\", \"\", \"Pdf Documents (*.pdf);;All files (*)\")\n if path:\n self.project.export(path)\n\n def saveas(self):\n path = QtWidgets.QFileDialog.getSaveFileName(\n self,\n \"Save Project\",\n self.project.path if self.project.path else \"\",\n \"Pro Documents (*.pro);;All files (*)\",\n )\n if path:\n self.project.saveas(path)\n\n def doLoad(self, path):\n self.setCurrentPage(None)\n self.project.load(path)\n if self.project.pages:\n self.setCurrentPage(self.project.pages[0])\n\n def load(self):\n path = QtWidgets.QFileDialog.getOpenFileName(\n self,\n \"Open Project\",\n self.project.path if self.project.path else \"\",\n \"Pro Documents (*.pro);;All files (*)\",\n )\n if path:\n self.doLoad(path)\n\n def save(self):\n if not self.project.path:\n self.saveas()\n else:\n self.project.save()\n\n def addImage(self):\n path = QtWidgets.QFileDialog.getOpenFileName(\n self,\n \"Add image\",\n \"\",\n \"Image Formats (*.bmp *.jgp *.jpeg *.mng *.png *.pbm *.ppm \"\n \"*.tiff);;All files(*)\",\n )\n if path:\n pass\n\n def addTextUnderCursor(self):\n self.currentPage.addTextUnderCursor(self)\n\n def deleteSelection(self):\n self.currentPage.deleteSelection()\n\n def exportSaveAndQuit(self):\n self.save()\n self.export()\n self.close()\n\n def handleFontChange(self, *_):\n font = self.fontCombo.currentFont()\n font.setPointSize(int(self.fontSizeCombo.currentText()))\n font.setWeight(\n QtGui.QFont.Bold if self.actionBold.isChecked() else QtGui.QFont.Normal\n )\n font.setItalic(self.actionItalic.isChecked())\n font.setUnderline(self.actionUnderline.isChecked())\n self.project.changeFont(font)\n\n def itemSelected(self, item):\n font = item.font()\n # color = item.defaultTextColor()\n self.fontCombo.setCurrentFont(font)\n self.fontSizeCombo.setEditText(str(font.pointSize()))\n self.boldAction.setChecked(font.weight() == QtGui.QFont.Bold)\n self.italicAction.setChecked(font.italic())\n self.underlineAction.setChecked(font.underline())\n","sub_path":"pdfannotator/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"625185868","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\nimport os\nimport urllib.request\n\n\ndef check_exist_or_download(url):\n\n download_dir = '/tmp/'\n name = url.rsplit('/', 1)[-1]\n filename = os.path.join(download_dir, name)\n\n if not os.path.isfile(filename):\n print(\"Downloading %s\" % url)\n urllib.request.urlretrieve(url, filename)\n else:\n print(\"Already Downloaded: %s\" % url)\n\n\nif __name__ == '__main__':\n\n #url of the mnist dataset\n train_x_url = 'http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz'\n train_y_url = 'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz'\n valid_x_url = 'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz'\n valid_y_url = 'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz'\n\n #download the mnist dataset\n check_exist_or_download(train_x_url)\n check_exist_or_download(train_y_url)\n check_exist_or_download(valid_x_url)\n check_exist_or_download(valid_y_url)\n","sub_path":"examples/cnn/data/download_mnist.py","file_name":"download_mnist.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"184725026","text":"#\n# Representation of a reverse loop with no sidings\n#\n\nfrom section import *\nfrom turnout import turnout\nfrom sensor import sensor\nfrom logger import log\nfrom utility import *\nfrom symbols import *\n\narg_table = { 'prefer_thrown' : False,\n 'prefer_normal' : False,\n 'turnout' : REQUIRED,\n 'half_way' : '0.5',\n }\n\nclass loop_section(section) :\n\n def __init__(self, name, **args) :\n construct(self, arg_table, args)\n section.__init__(self, name, **args)\n if not isinstance(self.turnout, turnout) :\n self.turnout = turnout(self.turnout, container=self, \\\n normal_section=self, thrown_section=self)\n try :\n self.half_way = float(self.half_way) * self.length\n self.half_way_sensor = None\n except ValueError :\n self.half_way = None\n self.half_way_sensor = sensor.get(self.half_way)\n self.half_way_sensor.listen(self.half_way_listen)\n self.reached_half_way = 'no'\n self.hold = True\n self.book_through = False\n\n def enter(self, from_, offset=0) :\n if not self.is_occupied() :\n self.reached_half_way = 'no'\n self.hold = True\n self.enter_base(from_, offset)\n\n def half_way_listen(self) :\n self.reached_half_way = 'yes'\n\n def _can_cruise(self) :\n return self.reached_half_way=='no'\n\n def enliven_connections_v(self) :\n self.enliven_connections_base()\n\n def review_position(self) :\n if self.half_way :\n if self.position > self.half_way >= self.prev_position :\n self.reached_half_way = 'yes'\n if self.reached_half_way == 'yes' :\n self.leave_previous()\n self.reached_half_way = 'done'\n self.hold = False\n prev_state = self.state\n self.state = SECTION_OCCUPIED\n self.direction = reverse_direction(self.direction)\n self._log_me(\"half way\", \"old_state %s\", self.show_state(prev_state))\n self.review_position_base()\n \n def prepare(self, sect) :\n self.prepare_base(sect)\n if prefer_thrown :\n self.turnout.throw(True)\n elif prefer_normal :\n self.turnout.throw(False)\n\nsection.enroll_type('loop', loop_section)\n \n\n \n","sub_path":"loop_section.py","file_name":"loop_section.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"521290088","text":"from tkinter import filedialog\n\nfrom Data_manager.src.orders_manager import Order_manager\nfrom Data_manager.src.product_manager import product_manager\nfrom Data_manager.src.bill_manager import bill_manager\nfrom Data_manager.src.Order_detail_manager import Order_detail_manager\nfrom Data_manager.Controller import Controler\nclass user_manager_controller:\n def __init__(self):\n self.order_control=Order_manager()\n self.product_control=product_manager()\n self.bill_control=bill_manager()\n self.controller = Controler(\"\")\n self.order_detail_control = Order_detail_manager()\n\n self.info = None\n self.deb_bills = None\n self.location = None\n self.status = \"\"\n def tong_bill(self, trv):\n\n self.delete_trv(trv)\n quantity, self.info, total = self.order_control.show_bill_infor_and_calculate_total()\n self.controller.insert_treview(trv, self.info)\n total_and_quantity = [ (\"1\",\" \",\" \",\"số lượng bill\", quantity), (\"2\",\" \",\" \",\"Tổng Tiền\", total),]\n self.controller.insert_treview(trv, total_and_quantity)\n self.status = \"all\"\n\n\n\n def delete_trv(self, treeview):\n for item in treeview.get_children():\n treeview.delete(item)\n\n\n\n def no(self, trv):\n self.delete_trv(trv)\n quantity, total, self.deb_bills = self.order_control.get_debtor_bills()\n total_and_quantity = [(\"1\", \" \", \" \", \"số lượng bill\", quantity), (\"2\", \" \", \" \", \"Tổng Tiền\", total), ]\n self.controller.insert_treview(trv, self.deb_bills)\n self.controller.insert_treview(trv, total_and_quantity)\n\n self.status = \"no\"\n\n\n def delete_individual(self, trv):\n id = trv.selection()\n for i in id:\n try:\n trv.delete(i)\n self.order_control.delete(i)\n self.order_detail_control.delete_product_from_order(i)\n except:\n pass\n\n def delete_all(self, trv):\n trv.delete(\"1\")\n trv.delete(\"2\")\n if self.status == \"all\":\n for i in self.info:\n trv.delete(i[0])\n self.order_control.delete(i[0])\n self.order_detail_control.delete_product_from_order(i[0])\n elif self.status == \"no\":\n for i in self.deb_bills:\n trv.delete(i[0])\n self.order_control.delete(i[0])\n self.order_detail_control.delete_product_from_order(i[0])\n\n\n\n\n def xem_bill(self, trv, show_bill_widget):\n try:\n self.controller.clear_bill(show_bill_widget)\n except:\n pass\n id = trv.selection()[0]\n self.location = self.order_control.get_location(id)\n self.bill_control.show_bill_to_label(show_bill_widget, self.location)\n\n def print_bill(self):\n self.bill_control.in_Bill(self.location)\n\n\n def them_san_pham(self):\n filename = filedialog.askopenfilename(initialdir=\"/\",\n title=\"Select a File\",\n filetypes=((\"Text files\",\n \"*.xlsx*\"),\n (\"all files\",\n \"*.*\")))\n\n self.product_control.read_file_and_insert_product(filename, option2=\"\")\n return\n\n","sub_path":"App/src_code/Data_manager/User_manager_controller.py","file_name":"User_manager_controller.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"188113953","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'mmm_match.views.home', name='home'),\n # url(r'^mmm_match/', include('mmm_match.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n\n url(r'^$', 'match.views.index'), # root page\n url(r'^welcome$', 'match.views.index'), # root page\n \n url(r'^demographic$', 'match.views.demographic'), # answer demographic questions\n\n \n url(r'^quiz$', 'match.views.take_quiz'), # answer demographic questions\n \n )\n","sub_path":"mmm_match/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"502244095","text":"import random\r\n\r\n'INFININITE VALUE'\r\ninf=1000000\r\n\r\n'MAIN BRAIN OF TIC TAC TOE'\r\ndef brain(l,p,d,al,bt):\r\n if checkwinner(l)!=0:\r\n return checkwinner(l) \r\n if moveavl(l):\r\n return 0\r\n if p:\r\n best=-inf\r\n for i in range(9):\r\n if l[i]==8:\r\n l[i]=p\r\n best=max(best,brain(l,1-p,d+1,al,bt))\r\n al=max(best,al)\r\n l[i]=8\r\n if bt<=al:\r\n break\r\n return best\r\n else:\r\n best=inf\r\n for i in range(9):\r\n if l[i]==8:\r\n l[i]=p\r\n best=min(best,brain(l,1-p,d+1,al,bt))\r\n bt=min(best,bt)\r\n l[i]=8 \r\n if bt<=al:\r\n break \r\n return best\r\n \r\n'REFINING ITS DECISION'\r\ndef decision(l):\r\n bv=-inf\r\n k=-1\r\n for i in range(9):\r\n if l[i]==8:\r\n l[i]=1\r\n mv=brain(l,0,0,-inf,inf)\r\n l[i]=8\r\n if mv>bv:\r\n k=i+1\r\n bv=mv\r\n return k\r\n\r\n'BOT2'\r\ndef decision1(l):\r\n a=[]\r\n for i in range(9):\r\n if l[i]==8:\r\n a.append(i)\r\n return a[random.randint(0,len(a)-1)]+1\r\n\r\n'EVALUATES THE BOARD'\r\ndef boardevaluation(l,v):\r\n if l[0]==v and l[3]==v and l[6]==v:\r\n return True\r\n if l[1]==v and l[4]==v and l[7]==v:\r\n return True\r\n if l[2]==v and l[5]==v and l[8]==v:\r\n return True\r\n if l[0]==v and l[1]==v and l[2]==v:\r\n return True\r\n if l[3]==v and l[4]==v and l[5]==v:\r\n return True\r\n if l[6]==v and l[7]==v and l[8]==v:\r\n return True\r\n if l[0]==v and l[4]==v and l[8]==v:\r\n return True\r\n if l[6]==v and l[4]==v and l[2]==v:\r\n return True\r\n return False\r\n\r\n'CHECK WINNER'\r\ndef checkwinner(l):\r\n if boardevaluation(l,0):\r\n return -10\r\n elif boardevaluation(l,1):\r\n return 10\r\n else:\r\n return 0\r\n \r\n'CHECKS FOR MOVES AVAILABLE OR NOT'\r\ndef moveavl(l):\r\n return 8 not in l\r\n \r\n\r\n \r\n\r\n \r\n \r\n \r\n\r\n\r\n \r\n \r\n \r\n","sub_path":"Tic-tac-toe/BOT.py","file_name":"BOT.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"335290827","text":"record_list=[]\nrecord_id=0\ndef record_input():\n name = input('输入姓名:')\n phone = input('输入电话号码:')\n record={'name':name,'phone':phone}\n return record\ndef add_record():\n record = record_input()\n global record_id\n record_id += 1\n record['record_id'] = record_id\n record_list.append(record)\n print('添加成功')\n return record_list\n #return '添加成功'\ndef query_record():\n #query_result=[]\n #query_ids=[]\n if len(record_list) == 0:\n return '不存在'\n else:\n condi = input('请输入查询条件(姓名或电话):')\n for record in record_list:\n if record['name']==condi:\n #return record['name'],record['phone'],record['record_id']\n\n return record\n #print(record)\n elif int(record['record_id'])==int(condi):\n #return record['name'],record['phone'],record['record_id']\n return record\n #print(record)\n elif record['phone']==condi:\n #return record['name'],record['phone'],record['record_id']\n return record\n # print(record)\n else:\n return '没有电话记录'\ndef delete_record():\n if len(record_list)<1:\n return '不存在'\n else :\n decondi=input('请输入删除条件(姓名或电话):')\n for record in record_list:\n if record['name']==decondi:\n record_list.remove(record)\n print(record_list)\n return '删除成功'\n elif int(record['record_id'])==int(decondi):\n record_list.remove(record)\n print(record_list)\n return '删除成功'\n elif record['phone']==decondi:\n record_list.remove(record)\n print(record_list)\n return '删除成功'\n else:\n return '没有电话记录'\ndef change_record():\n if len(record_list)>=1:\n record=query_record()\n change=input('请选择修改内容\"name\"or\"phone\":')\n if change in ['name','phone']:\n if change=='name':\n name=input('修改姓名为:')\n record['name']=name\n else:\n change=='phone'\n phone=input('修改手机号为:')\n record['phone']=phone\n else:\n print('不存在')\n print(record_list)\n return record\n else:\n return '不存在'\n\nif __name__=='__main__':\n while True:\n menu=\"\"\"1.添加,2.查找,3.删除,4.修改,5.退出\"\"\"\n print(menu)\n choose=input('请选择操作:')\n if choose=='1':\n print(add_record())\n elif choose=='2':\n print('查询结果:')\n print(query_record())\n elif choose=='3':\n print('删除后的结果:')\n print(delete_record())\n elif choose=='4':\n print(change_record())\n print('修改成功')\n elif choose=='5':\n print('退出')\n break\n else:\n print('无操作')\n continue\n\n\n","sub_path":"plac.py","file_name":"plac.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"113515781","text":"#!/usr/bin/env python3\n\"\"\"\n Acquire NFRAMES images every DELTASEC seconds.\n Save them to OUTPUTFOLDER.\n\"\"\"\nimport argparse\nimport os\nimport threading\nimport time\nimport warnings\n\nimport datetime as dt\nimport numpy as np\nimport pymba\nfrom scipy import misc, optimize\n\nPARSER = argparse.ArgumentParser( \\\n description='Acquire a series of frames from an Allied Vision GigE camera.')\nPARSER.add_argument('--nframes', '-n', metavar='num', type=int, nargs=1, required=True,\n help='number of frames to collect (>=1)')\nPARSER.add_argument('--dt', '-t', metavar='time', type=float, nargs=1, required=True,\n help='time period between frames, '\n 'in case of exponential periods it\\'s the first period')\nPARSER.add_argument('--exptmax', '-e', metavar='time', type=float, nargs=1,\n help='if set, will use exponentially increasing periods between shots, '\n 'dt_0 = dt (argument), dt_{n+1} = \\\\tau dt_n, where \\\\tau > 1, '\n 'up to total time exptmax since the first shot')\nPARSER.add_argument('--output', '-o', metavar='path', type=str, nargs=1, required=True,\n help='output folder')\nPARSER.add_argument('--format', '-f', metavar='format', type=str, nargs=1, default=['png'],\n help='output format')\nPARSER.add_argument('--nohc', '-c', action='store_true', help='don\\'t generate hi-contrast images')\nPARSER.add_argument('--onlyhc', '-l', action='store_true', help='generate only hi-contrast images')\nARGS = PARSER.parse_args()\n\nNFRAMES = ARGS.nframes[0]\nDELTASEC = ARGS.dt[0]\nOUTPUTFOLDER = ARGS.output[0]\nHICONTRASTFOLDER = OUTPUTFOLDER + \"/hicontrast\"\nif not ARGS.nohc:\n if not os.path.exists(HICONTRASTFOLDER):\n os.makedirs(HICONTRASTFOLDER)\nelse:\n if not os.path.exists(OUTPUTFOLDER):\n os.makedirs(OUTPUTFOLDER)\n\ndef saveimages(imgdata, opath=None, hcpath=None):\n \"\"\" Save a raw and an enchanted image, to be called in a separate thread \"\"\"\n if opath is not None:\n misc.imsave(opath, imgdata)\n if hcpath is not None:\n mindata, maxdata = imgdata.min(), imgdata.max()\n misc.imsave(hcpath, (imgdata-mindata)/(maxdata-mindata))\n print('{}: saved shot(s) ({} threads)'.format(dt.datetime.utcnow(), \\\n threading.active_count()))\n\nwith pymba.Vimba() as vimba:\n SYSTEM = vimba.getSystem()\n\n if SYSTEM.GeVTLIsPresent:\n SYSTEM.runFeatureCommand(\"GeVDiscoveryAllOnce\")\n time.sleep(0.2)\n CAMERAIDS = vimba.getCameraIds()\n assert len(CAMERAIDS) > 0, \"No cameras found!\"\n CAMERA0 = vimba.getCamera(CAMERAIDS[0])\n CAMERA0.openCamera()\n CAMERA0.AcquisitionMode = 'SingleFrame'\n\n if ARGS.exptmax is None:\n TIMEDELTA = dt.timedelta(seconds=DELTASEC)\n ACQUISITIONTIMES = [dt.datetime.utcnow()+j*TIMEDELTA for j in range(NFRAMES)]\n else:\n BASE = 2 # semi-arbitrary, influences the algorithm's effective range\n TAUMAX = ARGS.exptmax[0] / DELTASEC\n FUNC = lambda x: BASE**(x*(NFRAMES-1)) - 1 - TAUMAX*(BASE**x - 1)\n\n XX = np.logspace(-8, 2, 100)\n I0 = None\n with warnings.catch_warnings():\n # Overflow is expected here\n warnings.simplefilter(\"ignore\")\n YY = FUNC(XX)\n for i, v in enumerate(YY[:-1]*YY[1:]):\n if v < 0:\n I0 = i\n break\n A, B = XX[I0], XX[I0+1]\n\n TAU = BASE**optimize.brentq(FUNC, A, B)\n TIMEDELTALIST = [dt.timedelta(seconds=0)] \\\n + [dt.timedelta(seconds=DELTASEC*TAU**i) for i in range(NFRAMES-1)]\n ACQUISITIONTIMES = dt.datetime.utcnow() + np.cumsum(TIMEDELTALIST)\n\n for i, t in enumerate(ACQUISITIONTIMES):\n frame0 = CAMERA0.getFrame()\n frame0.announceFrame()\n\n CAMERA0.startCapture()\n frame0.queueFrameCapture()\n CAMERA0.runFeatureCommand('AcquisitionStart')\n CAMERA0.runFeatureCommand('AcquisitionStop')\n frame0.waitFrameCapture()\n TIMESTAMP = dt.datetime.utcnow()\n\n imgData = np.ndarray(buffer=frame0.getBufferByteData(),\n dtype=np.uint8,\n shape=(frame0.height, frame0.width))\n\n outputpath, hicontrastpath = None, None\n if not ARGS.onlyhc:\n outputpath = '{}/{}.{}'.format(OUTPUTFOLDER, TIMESTAMP, ARGS.format[0])\n if not ARGS.nohc:\n hicontrastpath = '{}/{}.{}'.format(HICONTRASTFOLDER, TIMESTAMP, ARGS.format[0])\n threading.Thread(target=saveimages, args=[np.array(imgData), \\\n outputpath, hicontrastpath]).start()\n\n if i+1 < NFRAMES:\n naptime = (ACQUISITIONTIMES[i+1] - dt.datetime.utcnow()).total_seconds()\n #print(naptime)\n if naptime > 0:\n time.sleep(naptime)\n\n CAMERA0.endCapture()\n CAMERA0.revokeAllFrames()\n","sub_path":"pymbaseries.py","file_name":"pymbaseries.py","file_ext":"py","file_size_in_byte":4927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"491991712","text":"import gdb\nimport pwndbg.commands\nimport pwndbg.commands.context\nimport pwndbg.ida\nimport pwndbg.regs\n\n\n@pwndbg.commands.ParsedCommand\n@pwndbg.commands.OnlyWhenRunning\n@pwndbg.events.stop\ndef j(*args):\n \"\"\"\n Synchronize IDA's cursor with GDB\n \"\"\"\n pc = int(gdb.selected_frame().pc())\n pwndbg.ida.Jump(pc)\n\n\nif pwndbg.ida.available():\n @pwndbg.commands.Command\n @pwndbg.commands.OnlyWhenRunning\n def up(n=1):\n \"\"\"\n Select and print stack frame that called this one.\n An argument says how many frames up to go.\n \"\"\"\n f = gdb.selected_frame()\n\n for i in range(n):\n o = f.older()\n if o:\n o.select()\n\n bt = pwndbg.commands.context.context_backtrace(with_banner=False)\n print('\\n'.join(bt))\n\n j()\n\n @pwndbg.commands.Command\n @pwndbg.commands.OnlyWhenRunning\n def down(n=1):\n \"\"\"\n Select and print stack frame called by this one.\n An argument says how many frames down to go.\n \"\"\"\n f = gdb.selected_frame()\n\n for i in range(n):\n o = f.newer()\n if o:\n o.select()\n\n bt = pwndbg.commands.context.context_backtrace(with_banner=False)\n print('\\n'.join(bt))\n\n j()\n\n\nclass ida(gdb.Function):\n \"\"\"\n Return a value from IDA that can be used in\n native GDB expressions.\n \"\"\"\n def __init__(self):\n super(ida, self).__init__('ida')\n def invoke(self, name):\n return pwndbg.ida.LocByName(name.string())\n\nida()\n","sub_path":"pwndbg/commands/ida.py","file_name":"ida.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"491949699","text":"# coding: utf-8\nimport unittest\nfrom hello_replier import HelloReplier\nimport datetime\n\nclass TestHelloReplier(unittest.TestCase):\n def test_is_reply_when_unmatch_text(self):\n replier = HelloReplier()\n text = u'test'\n time = datetime.datetime.today()\n self.assertFalse(replier.is_reply(text, time))\n\n def test_is_reply_when_not_include_at(self):\n replier = HelloReplier()\n text = u'おはよう'\n time = datetime.datetime.today()\n self.assertFalse(replier.is_reply(text, time))\n\n def test_is_reply_when_not_today(self):\n replier = HelloReplier()\n text = u'@nozomi_miraha おはよう'\n time = datetime.datetime(2000, 1, 1)\n self.assertFalse(replier.is_reply(text, time))\n\n def test_is_reply_when_true(self):\n replier = HelloReplier()\n text = u'@nozomi_miraha おはよう'\n time = datetime.datetime.today()\n self.assertTrue(replier.is_reply(text, time))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_hello_replier.py","file_name":"test_hello_replier.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"81246441","text":"import math\r\nlist=[]\r\nfor i in range(100,1000):\r\n a=int(i/100)\r\n b=int(i/10%10)\r\n c=int(i%10)\r\n if a**3+b**3+c**3==i:\r\n list.append(str(i))\r\n\r\nprint(list)","sub_path":"Study/水仙花数.py","file_name":"水仙花数.py","file_ext":"py","file_size_in_byte":173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"120085044","text":"\"\"\"EnergyPandas module.\n\nAn extension of pandas DataFrames and Series for Energy modelers.\n\"\"\"\n\nimport copy\nimport os\nimport time\nimport warnings\nfrom datetime import timedelta\n\nimport tsam.timeseriesaggregation as tsam\nfrom matplotlib import cm\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import LightSource\nfrom numpy import asarray, meshgrid, ndarray\nfrom pandas.core.frame import DataFrame\nfrom pandas.core.generic import NDFrame\nfrom pandas.core.indexes.datetimes import DatetimeIndex, date_range\nfrom pandas.core.indexes.multi import MultiIndex\nfrom pandas.core.reshape.pivot import pivot_table\nfrom pandas.core.series import Series\nfrom pandas.core.tools.datetimes import to_datetime\nfrom pandas.plotting._matplotlib.tools import _flatten, _subplots\nfrom pint import Quantity, Unit\nfrom sklearn import preprocessing\n\nimport archetypal.settings as settings\nfrom archetypal.utils import log\n\n\nclass EnergySeries(Series):\n \"\"\"A Series object designed to store energy related data.\"\"\"\n\n _metadata = [\n \"bin_edges_\",\n \"bin_scaling_factors_\",\n \"base_year\",\n \"frequency\",\n \"units\",\n \"name\",\n ]\n\n @property\n def _constructor(self):\n return EnergySeries\n\n @property\n def _constructor_expanddim(self):\n def f(*args, **kwargs):\n # adapted from https://github.com/pandas-dev/pandas/issues/19850#issuecomment-367934440\n return EnergyDataFrame(*args, **kwargs).__finalize__(self, method=\"inherit\")\n\n f._get_axis_number = super(EnergySeries, self)._get_axis_number\n\n return f\n\n def __init__(\n self,\n data=None,\n index=None,\n dtype=None,\n name=None,\n copy=False,\n fastpath=False,\n units=None,\n **kwargs,\n ):\n \"\"\"Initiate EnergySeries.\n\n Args:\n data (array-like, Iterable, dict, or scalar value): Contains data stored\n in Series.\n index (array-like or Index (1d)): Values must be hashable and have the\n same length as `data`. Non-unique index values are allowed. Will\n default to RangeIndex (0, 1, 2, ..., n) if not provided. If both a\n dict and index sequence are used, the index will override the keys\n found in the dict.\n dtype (str, numpy.dtype, or ExtensionDtype, optional): Data type for the\n output Series. If not specified, this will be inferred from `data`.\n See the :ref:`user guide ` for more usages.\n name (str, optional): The name to give to the Series.\n copy (bool): Copy input data. Defaults to False\n fastpath (bool): Defaults to False\n units (:obj:`str`, optional): The series units. Parsed as Pint units.\n \"\"\"\n super(EnergySeries, self).__init__(\n data=data, index=index, dtype=dtype, name=name, copy=copy, fastpath=fastpath\n )\n self.bin_edges_ = None\n self.bin_scaling_factors_ = None\n self.units = units\n\n for k, v in kwargs.items():\n EnergySeries._metadata.append(k)\n setattr(EnergySeries, k, v)\n\n def __finalize__(self, other, method=None, **kwargs):\n \"\"\"Propagate metadata from other to self.\"\"\"\n if isinstance(other, NDFrame):\n for name in other.attrs:\n self.attrs[name] = other.attrs[name]\n # For subclasses using _metadata. Set known attributes and update list.\n for name in other._metadata:\n try:\n object.__setattr__(self, name, getattr(other, name))\n except AttributeError:\n pass\n if name not in self._metadata:\n self._metadata.append(name)\n return self\n\n def __repr__(self):\n \"\"\"Adds units to repr\"\"\"\n result = super(EnergySeries, self).__repr__()\n return result + f\", units:{self.units:~P}\"\n\n @classmethod\n def with_timeindex(\n cls,\n data,\n base_year=2018,\n frequency=\"H\",\n index=None,\n dtype=None,\n name=None,\n copy=False,\n fastpath=False,\n units=None,\n **kwargs,\n ):\n # handle DateTimeIndex\n es = cls(\n data=data,\n index=index,\n dtype=dtype,\n name=name,\n copy=copy,\n fastpath=fastpath,\n units=units,\n **kwargs,\n )\n start_date = str(base_year) + \"0101\"\n newindex = date_range(start=start_date, freq=frequency, periods=len(es))\n es.index = newindex\n return es\n\n @property\n def units(self):\n return self._units\n\n @units.setter\n def units(self, value):\n if isinstance(value, str):\n self._units = settings.unit_registry.parse_expression(value).units\n elif isinstance(value, (Unit, Quantity)):\n self._units = value\n elif value is None:\n self._units = settings.unit_registry.parse_expression(value).units\n else:\n raise TypeError(f\"Unit of type {type(value)}\")\n\n @classmethod\n def from_reportdata(\n cls,\n df,\n name=None,\n base_year=2018,\n units=None,\n normalize=False,\n sort_values=False,\n ascending=False,\n to_units=None,\n agg_func=\"sum\",\n ):\n \"\"\"Create a.\n\n Args:\n df (DataFrame):\n name:\n base_year:\n units:\n normalize (bool): Normalize between 0 and 1.\n sort_values:\n ascending:\n to_units (str): Convert original values to this unit. Dimensionality\n check performed by `pint`.\n agg_func (callable): The aggregation function to use in the case\n that multiple values have the same index value. If a function,\n must either work when passed a DataFrame or when passed to\n DataFrame.apply. For a DataFrame, can pass a dict, if the keys\n are DataFrame column names.\n\n Accepted Combinations are:\n - string function name\n - function\n - list of functions\n - dict of column names -> functions (or list of functions)\n \"\"\"\n index = to_datetime(\n {\n \"year\": base_year,\n \"month\": df.Month,\n \"day\": df.Day,\n \"hour\": df.Hour,\n \"minute\": df.Minute,\n }\n )\n # Adjust timeindex by timedelta\n index -= df.Interval.apply(lambda x: timedelta(minutes=x))\n index = DatetimeIndex(index)\n # get data\n data = df.Value\n data.index = index\n units = [units] if units else set(df.Units)\n if len(units) > 1:\n raise ValueError(\"The DataFrame contains mixed units: {}\".format(units))\n else:\n units = next(iter(units), None)\n # group data by index value (level=0) using the agg_func\n if agg_func:\n grouped_Data = data.groupby(level=0).agg(agg_func)\n else:\n df[\"DateTimeIndex\"] = index\n grouped_Data = df.set_index([\"DateTimeIndex\", \"Name\"]).Value\n # Since we create the index, don't need to use .with_timeindex() constructor\n energy_series = cls(\n grouped_Data.values,\n name=name,\n units=units,\n index=grouped_Data.index,\n base_year=base_year,\n )\n if normalize:\n energy_series.normalize(inplace=True)\n if sort_values:\n energy_series.sort_values(ascending=ascending, inplace=True)\n if to_units:\n energy_series.to_units(to_units, inplace=True)\n return energy_series\n\n def to_units(self, to_units=None, inplace=False):\n \"\"\"returns the multiplier to convert units\n\n Args:\n to_units (str, pint.Unit):\n inplace:\n \"\"\"\n cdata = settings.unit_registry.Quantity(1, self.units).to(to_units).m\n if inplace:\n self[:] *= cdata\n self.units = to_units\n else:\n # create new instance using constructor\n result = self._constructor(\n data=self.values * cdata, index=self.index, copy=False\n )\n # Copy metadata over\n result.__finalize__(self)\n result.units = to_units\n return result\n\n def normalize(self, feature_range=(0, 1), inplace=False):\n \"\"\"Returns a normalized EnergySeries\n\n Args:\n feature_range:\n inplace:\n \"\"\"\n x = self.values # returns a numpy array\n min_max_scaler = preprocessing.MinMaxScaler()\n x_scaled = min_max_scaler.fit_transform(x.reshape(-1, 1)).ravel()\n if inplace:\n # replace whole data with array\n self[:] = x_scaled\n # change units to dimensionless\n self.units = settings.unit_registry.dimensionless\n else:\n # create new instance using constructor\n result = self._constructor(data=x_scaled, index=self.index, copy=False)\n # Copy metadata over\n result.__finalize__(self)\n return result\n\n def ldc_source(self, SCOPH=4, SCOPC=4):\n \"\"\"Returns the Load Duration Curve from the source side of theoretical\n Heat Pumps\n\n Args:\n SCOPH: Seasonal COP in Heating\n SCOPC: Seasonal COP in Cooling\n\n Returns:\n (EnergySeries) Load Duration Curve\n \"\"\"\n\n result = self.ldc.apply(\n lambda x: x * (1 - 1 / SCOPH) if x > 0 else x * (1 + 1 / SCOPC)\n )\n return result\n\n def source_side(self, SCOPH=None, SCOPC=None):\n \"\"\"Returns the Source Side EnergySeries given a Seasonal COP. Negative\n values are considered like Cooling Demand.\n\n Args:\n SCOPH: Seasonal COP in Heating\n SCOPC: Seasonal COP in Cooling\n\n Returns:\n (EnergySeries) Load Duration Curve\n \"\"\"\n if SCOPC or SCOPH:\n result = self.apply(\n lambda x: x * (1 - 1 / SCOPH) if SCOPH else x * (1 + 1 / SCOPC)\n )\n return result\n else:\n raise ValueError(\"Please provide a SCOPH or a SCOPC\")\n\n def discretize_tsam(self, inplace=False, **kwargs):\n \"\"\"Clusters time series data to typical periods. See\n :class:`tsam.timeseriesaggregation.TimeSeriesAggregation` for more info.\n\n Returns:\n EnergySeries:\n \"\"\"\n try:\n import tsam.timeseriesaggregation as tsam\n except ImportError:\n raise ImportError(\"tsam is required for discretize_tsam()\")\n if not isinstance(self.index, DatetimeIndex):\n raise TypeError(\"To use tsam, index of series must be a \" \"DateTimeIndex\")\n\n timeSeries = self.to_frame()\n agg = tsam.TimeSeriesAggregation(timeSeries, **kwargs)\n\n agg.createTypicalPeriods()\n result = agg.predictOriginalData()\n if inplace:\n self.loc[:] = result.values.ravel()\n else:\n # create new instance using constructor\n result = self._constructor(\n data=result.values.ravel(), index=self.index, copy=False\n )\n # Copy metadata over\n result.__finalize__(self)\n return result\n\n def plot3d(self, *args, **kwargs):\n \"\"\"Generate a plot of the EnergySeries.\n\n Wraps the ``plot_energyseries()`` function, and documentation is\n copied from there.\n\n Args:\n *args:\n **kwargs:\n \"\"\"\n return plot_energyseries(self, *args, **kwargs)\n\n def plot2d(self, *args, **kwargs):\n \"\"\"\n Args:\n *args:\n **kwargs:\n \"\"\"\n return plot_energyseries_map(self, **kwargs)\n\n @property\n def p_max(self):\n if isinstance(self.index, MultiIndex):\n return self.groupby(level=0).max()\n else:\n return self.max()\n\n @property\n def monthly(self):\n if isinstance(self.index, DatetimeIndex):\n data = self.resample(\"M\").mean()\n return self._constructor(\n data, index=data.index, frequency=\"M\", units=self.units\n )\n else:\n return None\n\n @property\n def capacity_factor(self):\n max = self.max()\n mean = self.mean()\n return mean / max\n\n @property\n def bin_edges(self):\n return self.bin_edges_\n\n @property\n def time_at_min(self):\n return self.idxmin()\n\n @property\n def bin_scaling_factors(self):\n return self.bin_scaling_factors_\n\n @property\n def duration_scaling_factor(self):\n return list(map(tuple, self.bin_scaling_factors.values))\n\n @property\n def ldc(self):\n nb_points = len(self)\n newdata = self.sort_values(ascending=False).reset_index(drop=True)\n return newdata.__finalize__(self)\n\n @property\n def nseries(self):\n if self.data.ndim == 1:\n return 1\n else:\n return self.data.shape[1]\n\n\ndef save_and_show(\n fig, ax, save, show, close, filename, file_format, dpi, axis_off, extent\n):\n \"\"\"Save a figure to disk and show it, as specified.\n\n Args:\n fig (matplotlib.figure.Figure): the figure\n ax (matplotlib.axes.Axes or list(matplotlib.axes.Axes)): the axes\n save (bool): whether to save the figure to disk or not\n show (bool): whether to display the figure or not\n close (bool): close the figure (only if show equals False) to prevent\n display\n filename (string): the name of the file to save\n file_format (string): the format of the file to save (e.g., 'jpg',\n 'png', 'svg')\n dpi (int): the resolution of the image file if saving (Dots per inch)\n axis_off (bool): if True matplotlib axis was turned off by plot_graph so\n constrain the saved figure's extent to the interior of the axis\n extent:\n\n Returns:\n (tuple) fig, ax\n \"\"\"\n # save the figure if specified\n\n if save:\n start_time = time.time()\n\n # create the save folder if it doesn't already exist\n if not os.path.exists(settings.imgs_folder):\n os.makedirs(settings.imgs_folder)\n path_filename = os.path.join(\n settings.imgs_folder, os.extsep.join([filename, file_format])\n )\n\n if not isinstance(ax, (ndarray, list)):\n ax = [ax]\n if file_format == \"svg\":\n for ax in ax:\n # if the file_format is svg, prep the fig/ax a bit for saving\n ax.axis(\"off\")\n ax.set_position([0, 0, 1, 1])\n ax.patch.set_alpha(0.0)\n fig.patch.set_alpha(0.0)\n fig.savefig(\n path_filename,\n bbox_inches=0,\n format=file_format,\n facecolor=fig.get_facecolor(),\n transparent=True,\n )\n else:\n if extent is None:\n if len(ax) == 1:\n if axis_off:\n for ax in ax:\n # if axis is turned off, constrain the saved\n # figure's extent to the interior of the axis\n extent = ax.get_window_extent().transformed(\n fig.dpi_scale_trans.inverted()\n )\n else:\n extent = \"tight\"\n fig.savefig(\n path_filename,\n dpi=dpi,\n bbox_inches=extent,\n format=file_format,\n facecolor=fig.get_facecolor(),\n transparent=True,\n )\n log(\n \"Saved the figure to disk in {:,.2f} seconds\".format(\n time.time() - start_time\n )\n )\n\n # show the figure if specified\n if show:\n start_time = time.time()\n plt.show()\n # fig.show()\n log(\"Showed the plot in {:,.2f} seconds\".format(time.time() - start_time))\n # if show=False, close the figure if close=True to prevent display\n elif close:\n plt.close()\n\n return fig, ax\n\n\ndef plot_energyseries(\n energy_series,\n kind=\"polygon\",\n axis_off=True,\n cmap=None,\n fig_height=None,\n fig_width=6,\n show=True,\n view_angle=-60,\n save=False,\n close=False,\n dpi=300,\n file_format=\"png\",\n color=None,\n axes=None,\n vmin=None,\n vmax=None,\n filename=None,\n timeStepsPerPeriod=24,\n **kwargs,\n):\n \"\"\"\n Args:\n energy_series (EnergySeries):\n kind (str):\n axis_off (bool):\n cmap:\n fig_height (float):\n fig_width (float):\n show (bool):\n view_angle (float):\n save (bool):\n close (bool):\n dpi (int):\n file_format (str):\n color (str):\n axes:\n vmin (float):\n vmax (float):\n filename (str):\n timeStepsPerPeriod (int): The number of discrete timesteps which\n describe one period.\n **kwargs:\n \"\"\"\n if energy_series.empty:\n warnings.warn(\n \"The EnergyProgile you are attempting to plot is \"\n \"empty. Nothing has been displayed.\",\n UserWarning,\n )\n return axes\n\n import matplotlib.pyplot as plt\n\n # noinspection PyUnresolvedReferences\n from mpl_toolkits.mplot3d import Axes3D\n\n if isinstance(energy_series.index, MultiIndex):\n groups = energy_series.groupby(level=0)\n nax = len(groups)\n else:\n nax = 1\n groups = [(\"unnamed\", energy_series)]\n\n if fig_height is None:\n fig_height = fig_width * nax\n\n # Set up plot\n fig, axes = plt.subplots(\n nax,\n 1,\n subplot_kw=dict(projection=\"3d\"),\n figsize=(fig_width, fig_height),\n dpi=dpi,\n )\n if not isinstance(axes, ndarray):\n axes = [axes]\n\n for ax, (name, profile) in zip(axes, groups):\n values = profile.values\n\n vmin = values.min() if vmin is None else vmin\n vmax = values.max() if vmax is None else vmax\n\n if kind == \"polygon\":\n import tsam.timeseriesaggregation as tsam\n\n z, _ = tsam.unstackToPeriods(profile, timeStepsPerPeriod=timeStepsPerPeriod)\n nrows, ncols = z.shape\n\n xs = z.columns\n zs = z.index.values\n\n verts = []\n for i in zs:\n ys = z.iloc[int(i), :]\n verts.append(_polygon_under_graph(xs, ys))\n\n _plot_poly_collection(\n ax,\n verts,\n zs,\n edgecolors=kwargs.get(\"edgecolors\", None),\n facecolors=kwargs.get(\"facecolors\", None),\n linewidths=kwargs.get(\"linewidths\", None),\n cmap=cmap,\n )\n elif kind == \"surface\":\n import tsam.timeseriesaggregation as tsam\n\n z, _ = tsam.unstackToPeriods(profile, timeStepsPerPeriod=timeStepsPerPeriod)\n nrows, ncols = z.shape\n x = z.columns\n y = z.index.values\n\n x, y = meshgrid(x, y)\n _plot_surface(ax, x, y, z.values, cmap=cmap, **kwargs)\n elif kind == \"contour\":\n import tsam.timeseriesaggregation as tsam\n\n z, _ = tsam.unstackToPeriods(profile, timeStepsPerPeriod=timeStepsPerPeriod)\n nrows, ncols = z.shape\n x = z.columns\n y = z.index.values\n\n x, y = meshgrid(x, y)\n _plot_contour(ax, x, y, z.values, cmap=cmap, **kwargs)\n else:\n raise NameError('plot kind \"{}\" is not supported'.format(kind))\n\n if filename is None:\n filename = \"unnamed\"\n\n # set the extent of the figure\n ax.set_xlim3d(-1, ncols)\n ax.set_xlabel(kwargs.get(\"xlabel\", \"hour of day\"))\n ax.set_ylim3d(-1, nrows)\n ax.set_ylabel(kwargs.get(\"ylabel\", \"day of year\"))\n ax.set_zlim3d(vmin, vmax)\n z_label = \"{} [{:~P}]\".format(\n energy_series.name if energy_series.name is not None else \"Z\",\n energy_series.units,\n )\n ax.set_zlabel(z_label)\n\n # configure axis appearance\n xaxis = ax.xaxis\n yaxis = ax.yaxis\n zaxis = ax.zaxis\n\n xaxis.get_major_formatter().set_useOffset(False)\n yaxis.get_major_formatter().set_useOffset(False)\n zaxis.get_major_formatter().set_useOffset(False)\n\n # if axis_off, turn off the axis display set the margins to zero and\n # point the ticks in so there's no space around the plot\n if axis_off:\n ax.axis(\"off\")\n ax.margins(0)\n ax.tick_params(which=\"both\", direction=\"in\")\n xaxis.set_visible(False)\n yaxis.set_visible(False)\n zaxis.set_visible(False)\n fig.canvas.draw()\n if view_angle is not None:\n ax.view_init(30, view_angle)\n ax.set_proj_type(kwargs.get(\"proj_type\", \"persp\"))\n fig.canvas.draw()\n fig, axes = save_and_show(\n fig=fig,\n ax=axes,\n save=save,\n show=show,\n close=close,\n filename=filename,\n file_format=file_format,\n dpi=dpi,\n axis_off=axis_off,\n extent=None,\n )\n return fig, axes\n\n\ndef plot_energyseries_map(\n data,\n periodlength=24,\n subplots=False,\n vmin=None,\n vmax=None,\n axis_off=True,\n cmap=\"RdBu\",\n fig_height=None,\n fig_width=6,\n show=True,\n view_angle=-60,\n save=False,\n close=False,\n dpi=300,\n file_format=\"png\",\n color=None,\n ax=None,\n filename=\"untitled\",\n extent=\"tight\",\n sharex=False,\n sharey=False,\n layout=None,\n layout_type=\"vertical\",\n **kwargs,\n):\n \"\"\"\n Args:\n data (EnergySeries or EnergyDataFrame):\n periodlength:\n subplots:\n vmin:\n vmax:\n axis_off:\n cmap:\n fig_height:\n fig_width:\n show:\n view_angle:\n save:\n close:\n dpi:\n file_format:\n color:\n ax:\n filename:\n extent:\n sharex:\n sharey:\n layout:\n layout_type:\n **kwargs:\n \"\"\"\n if fig_height is None:\n fig_height = fig_width / 3\n figsize = (fig_width, fig_height)\n\n if not ax:\n if subplots:\n if isinstance(data, EnergySeries):\n data = data.unstack(level=0)\n n = data.shape[1]\n else:\n n = 1\n fig, axes = plt.subplots(\n nrows=n, ncols=1, figsize=(fig_width, fig_height), dpi=dpi\n )\n else:\n fig = ax.get_figure()\n if figsize is not None:\n fig.set_size_inches(figsize)\n axes = ax\n\n stacked, timeindex = tsam.unstackToPeriods(copy.deepcopy(data), periodlength)\n cmap = plt.get_cmap(cmap)\n im = axes.imshow(\n stacked.values.T, interpolation=\"nearest\", vmin=vmin, vmax=vmax, cmap=cmap\n )\n axes.set_aspect(\"auto\")\n axes.set_ylabel(\"Hour of day\")\n axes.set_xlabel(\"Day of year\")\n plt.title(f\"{data.name}\")\n\n # fig.subplots_adjust(right=1.1)\n cbar = fig.colorbar(im, ax=axes)\n cbar.set_label(f\"[{data.units:~P}]\")\n\n fig, axes = save_and_show(\n fig, axes, save, show, close, filename, file_format, dpi, axis_off, extent\n )\n\n return fig, axes\n\n\ndef _plot_poly_collection(\n ax, verts, zs=None, color=None, cmap=None, vmin=None, vmax=None, **kwargs\n):\n \"\"\"\n Args:\n ax:\n verts:\n zs:\n color:\n cmap:\n vmin:\n vmax:\n **kwargs:\n \"\"\"\n from matplotlib.collections import PolyCollection\n\n # if None in zs:\n # zs = None\n # color=None overwrites specified facecolor/edgecolor with default color\n if color is not None:\n kwargs[\"color\"] = color\n import matplotlib as mpl\n\n norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)\n\n poly = PolyCollection(verts, **kwargs)\n if zs is not None:\n poly.set_array(asarray(zs))\n poly.set_cmap(cmap)\n poly.set_clim(vmin, vmax)\n\n ax.add_collection3d(poly, zs=zs, zdir=\"y\")\n # ax.autoscale_view()\n return poly\n\n\ndef _plot_surface(ax, x, y, z, cmap=None, **kwargs):\n \"\"\"\n Args:\n ax:\n x:\n y:\n z:\n cmap:\n **kwargs:\n \"\"\"\n if cmap is None:\n cmap = cm.gist_earth\n\n ls = LightSource(270, 45)\n # To use a custom hillshading mode, override the built-in shading and pass\n # in the rgb colors of the shaded surface calculated from \"shade\".\n rgb = ls.shade(z, cmap=cm.get_cmap(cmap), vert_exag=0.1, blend_mode=\"soft\")\n surf = ax.plot_surface(\n x,\n y,\n z,\n rstride=1,\n cstride=1,\n facecolors=rgb,\n linewidth=0,\n antialiased=False,\n shade=False,\n **kwargs,\n )\n return surf\n\n\ndef _plot_contour(ax, x, y, z, cmap=None, **kwargs):\n \"\"\"\n Args:\n ax:\n x:\n y:\n z:\n cmap:\n **kwargs:\n \"\"\"\n if cmap is None:\n cmap = cm.gist_earth\n surf = ax.contour3D(x, y, z, 150, cmap=cmap, **kwargs)\n return surf\n\n\ndef _polygon_under_graph(xlist, ylist):\n \"\"\"Construct the vertex list which defines the polygon filling the space\n under the (xlist, ylist) line graph. Assumes the xs are in ascending order.\n\n Args:\n xlist:\n ylist:\n \"\"\"\n return [(xlist[0], 0.0), *zip(xlist, ylist), (xlist[-1], 0.0)]\n\n\nEnergySeries.plot3d.__doc__ = plot_energyseries.__doc__\nEnergySeries.plot2d.__doc__ = plot_energyseries_map.__doc__\n\n\nclass EnergyDataFrame(DataFrame):\n \"\"\"An EnergyDataFrame object is a pandas.DataFrame that has energy related\n data. In addition to the standard DataFrame constructor arguments,\n EnergyDataFrame also accepts the following keyword arguments:\n\n\n \"\"\"\n\n # temporary properties\n _internal_names = DataFrame._internal_names\n _internal_names_set = set(_internal_names)\n\n # normal properties\n _metadata = [\"units\", \"name\"]\n\n @property\n def _constructor(self):\n return EnergyDataFrame\n\n @property\n def _constructor_sliced(self):\n # return EnergySeries\n def f(*args, **kwargs):\n # adapted from https://github.com/pandas-dev/pandas/issues/13208#issuecomment-326556232\n return EnergySeries(*args, **kwargs).__finalize__(self, method=\"inherit\")\n\n return f\n\n def __init__(\n self,\n data,\n units=None,\n index=None,\n columns=None,\n dtype=None,\n copy=True,\n **kwargs,\n ):\n super(EnergyDataFrame, self).__init__(\n data, index=index, columns=columns, dtype=dtype, copy=copy\n )\n self.units = units\n for k, v in kwargs.items():\n EnergyDataFrame._metadata.append(k)\n setattr(EnergyDataFrame, k, v)\n\n def __finalize__(self, other, method=None, **kwargs):\n \"\"\"Propagate metadata from other to self.\"\"\"\n if isinstance(other, NDFrame):\n for name in other.attrs:\n self.attrs[name] = other.attrs[name]\n # For subclasses using _metadata. Set known attributes and update list.\n for name in other._metadata:\n try:\n object.__setattr__(self, name, getattr(other, name))\n except AttributeError:\n pass\n if name not in self._metadata:\n self._metadata.append(name)\n return self\n\n @classmethod\n def from_reportdata(\n cls,\n df,\n name=None,\n base_year=2018,\n units=None,\n normalize=False,\n sort_values=False,\n to_units=None,\n ):\n \"\"\"From a ReportData DataFrame\"\"\"\n # get data\n units = [units] if units else set(df.Units)\n if len(units) > 1:\n raise ValueError(\"The DataFrame contains mixed units: {}\".format(units))\n else:\n units = next(iter(units), None)\n # group data by index value (level=0) using the agg_func\n grouped_Data = pivot_table(\n df, index=\"TimeIndex\", columns=[\"KeyValue\"], values=[\"Value\"]\n ).droplevel(axis=1, level=0)\n df = pivot_table(\n df,\n index=\"TimeIndex\",\n columns=None,\n values=[\"Month\", \"Day\", \"Hour\", \"Minute\", \"Interval\"],\n )\n index = to_datetime(\n {\n \"year\": base_year,\n \"month\": df.Month,\n \"day\": df.Day,\n \"hour\": df.Hour,\n \"minute\": df.Minute,\n }\n )\n\n # Adjust timeindex by timedelta\n index -= df.Interval.apply(lambda x: timedelta(minutes=x))\n index = DatetimeIndex(index)\n grouped_Data.index = index\n # Since we create the index, use_timeindex must be false\n edf = cls(grouped_Data, units=units, index=grouped_Data.index, name=name)\n if to_units:\n edf.to_units(to_units=to_units, inplace=True)\n if normalize:\n edf.normalize(inplace=True)\n if sort_values:\n edf.sort_values(sort_values, inplace=True)\n return edf\n\n @property\n def units(self):\n return self._units\n\n @units.setter\n def units(self, value):\n if isinstance(value, str):\n self._units = settings.unit_registry.parse_expression(value).units\n elif isinstance(value, (Unit, Quantity)):\n self._units = value\n elif value is None:\n self._units = settings.unit_registry.parse_expression(value).units\n else:\n raise TypeError(f\"Unit of type {type(value)}\")\n\n def to_units(self, to_units=None, inplace=False):\n \"\"\"returns the multiplier to convert units\n\n Args:\n to_units (str or pint.Unit):\n inplace:\n \"\"\"\n cdata = settings.unit_registry.Quantity(1, self.units).to(to_units).m\n if inplace:\n self[:] *= cdata\n self.units = to_units\n else:\n # create new instance using constructor\n result = self._constructor(\n data=self * cdata, index=self.index, columns=self.columns, copy=False\n )\n # Copy metadata over\n result.__finalize__(self)\n result.units = to_units\n return result\n\n def normalize(self, inplace=False):\n x = self.values # returns a numpy array\n min_max_scaler = preprocessing.MinMaxScaler()\n x_scaled = min_max_scaler.fit_transform(x)\n if inplace:\n # replace whole data with array\n self[:] = x_scaled\n # change units to dimensionless\n self.units = settings.unit_registry.dimensionless\n else:\n # create new instance using constructor\n result = self._constructor(\n data=x_scaled, index=self.index, columns=self.columns, copy=False\n )\n # Copy metadata over\n result.__finalize__(self)\n return result\n\n def plot2d(self, **kwargs):\n return plot_energydataframe_map(self, **kwargs)\n\n @property\n def nseries(self):\n if self._data.ndim == 1:\n return 1\n else:\n return self._data.shape[0]\n\n def discretize_tsam(self, inplace=False, **kwargs):\n \"\"\"Clusters time series data to typical periods. See\n :class:`tsam.timeseriesaggregation.TimeSeriesAggregation` for more info.\n\n Returns:\n EnergyDataFrame:\n \"\"\"\n try:\n import tsam.timeseriesaggregation as tsam\n except ImportError:\n raise ImportError(\"tsam is required for discretize_tsam()\")\n if not isinstance(self.index, DatetimeIndex):\n raise TypeError(\"To use tsam, index of series must be a \" \"DateTimeIndex\")\n timeSeries = self.copy()\n agg = tsam.TimeSeriesAggregation(timeSeries, **kwargs)\n\n agg.createTypicalPeriods()\n result = agg.predictOriginalData()\n if inplace:\n self.loc[:] = result.values\n else:\n # create new instance using constructor\n result = self._constructor(\n data=result.values, index=self.index, columns=self.columns, copy=False\n )\n # Copy metadata over\n result.__finalize__(self)\n return result\n\n discretize_tsam.__doc__ = tsam.TimeSeriesAggregation.__init__.__doc__\n\n\ndef plot_energydataframe_map(\n data,\n periodlength=24,\n subplots=False,\n vmin=None,\n vmax=None,\n axis_off=True,\n cmap=\"RdBu\",\n fig_height=None,\n fig_width=6,\n show=True,\n view_angle=-60,\n save=False,\n close=False,\n dpi=300,\n file_format=\"png\",\n color=None,\n ax=None,\n filename=\"untitled\",\n extent=\"tight\",\n sharex=True,\n sharey=True,\n layout=None,\n layout_type=\"vertical\",\n **kwargs,\n):\n if fig_height is None:\n fig_height = fig_width / 3\n figsize = (fig_width, fig_height)\n nseries = data.nseries\n fig, axes = _setup_subplots(\n subplots, nseries, sharex, sharey, figsize, ax, layout, layout_type\n )\n cols = data.columns\n for ax, col in zip(axes, cols):\n plot_energyseries_map(\n data[col],\n periodlength=periodlength,\n subplots=subplots,\n vmin=vmin,\n vmax=vmax,\n axis_off=axis_off,\n cmap=cmap,\n fig_height=fig_height,\n fig_width=fig_width,\n show=False,\n save=False,\n close=False,\n dpi=dpi,\n file_format=file_format,\n color=color,\n ax=ax,\n filename=filename,\n extent=extent,\n sharex=sharex,\n sharey=sharey,\n layout=layout,\n layout_type=layout_type,\n **kwargs,\n )\n\n fig, axes = save_and_show(\n fig, axes, save, show, close, filename, file_format, dpi, axis_off, extent\n )\n\n return fig, axes\n\n\ndef _setup_subplots(\n subplots,\n nseries,\n sharex=False,\n sharey=False,\n figsize=None,\n ax=None,\n layout=None,\n layout_type=\"vertical\",\n):\n \"\"\"prepares the subplots\"\"\"\n\n if subplots:\n fig, axes = _subplots(\n naxes=nseries,\n sharex=sharex,\n sharey=sharey,\n figsize=figsize,\n ax=ax,\n layout=layout,\n layout_type=layout_type,\n )\n else:\n if ax is None:\n fig = plt.figure(figsize=figsize)\n axes = fig.add_subplot(111)\n else:\n fig = ax.get_figure()\n if figsize is not None:\n fig.set_size_inches(figsize)\n axes = ax\n\n axes = _flatten(axes)\n\n return fig, axes\n","sub_path":"archetypal/energypandas.py","file_name":"energypandas.py","file_ext":"py","file_size_in_byte":35201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"602534647","text":"import logging\nimport os\nimport random\n\nfrom telegram.ext import CommandHandler, Filters, MessageHandler, Updater\n\nfrom handlers import *\n\nTOKEN = os.environ.get('TG_BOT_TOKEN')\nPORT = int(os.environ.get('PORT'))\n\nupdater = Updater(TOKEN)\n\ndispatcher = updater.dispatcher\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\n\ngame_sessions = {}\n\n\ndef start(update, context):\n bot.send_message(chat_id=update.message.chat_id,\n text=\"Привет!\\nОтправь /help чтобы узнать подробнее о моих командах!\")\n\n\ndef help_mes(update, context):\n help_list = [\n \"/new_game - начать новую игру\",\n \"/letter А - отгадать букву 'А'\",\n \"/word СЛОВО - отгадать слово полностью\",\n \"/help - получить это сообщение\"\n ]\n bot.send_message(chat_id=update.message.chat_id,\n text=\"\\n\".join(help_list))\n\n\n\ndispatcher.add_handler(CommandHandler('start', start))\ndispatcher.add_handler(CommandHandler('help', help_mes))\n\nupdater.start_webhook(listen='0.0.0.0',\n port=PORT,\n url_path=TOKEN)\nupdater.bot.set_webhook(\"https://yet-another-rpg-bot.herokuapp.com/\" + TOKEN)\nupdater.idle()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"388716611","text":"import pygame\nimport Vetores\n\npygame.init()\nscrw, scrh = 1100, 600\nscreen = pygame.display.set_mode([scrw, scrh])\nkg = True\ntimer = pygame.time.Clock()\nfont = pygame.font.SysFont(\"sourcecodeproblack\", 12)\n\n\ndef constrain(a, min, max):\n return max if a >= max else min if a <= min else a\n\n\nclass Slider:\n # poder digitar max, min, valor ( e mudar posicao do botao nos casos certos )\n def __init__(self, pos, bgcolor, max, min, name):\n self.rect = pygame.Rect(100*pos, 0, 100, scrh)\n self.bgcolor = bgcolor\n self.slider_rail = pygame.Rect(100*pos+55, 50, 10, scrh - 2*50)\n self.button_w = 20\n self.button_h = 10\n self.button_rect = pygame.Rect(self.slider_rail.centerx - self.button_w/2,\n self.slider_rail.bottom - self.button_h/2, self.button_w, self.button_h)\n self.max = max\n self.min = min\n self.grabbed = False\n self.name = name\n self.edit = 0 # 1 é upper, 2 é middle e 3 é lower\n\n def get_value(self):\n return self.min + (self.button_rect.centery - self.slider_rail.bottom) * (self.max - self.min)/(self.slider_rail.top - self.slider_rail.bottom)\n\n def set_value(self, value):\n value = constrain(value, self.min, self.max)\n self.button_rect.centery = self.slider_rail.top + \\\n (value - self.max) * (self.slider_rail.bottom -\n self.slider_rail.top)/(self.min - self.max)\n\n def write(self, text):\n name_text = font.render(self.name, True, (0, 0, 0))\n name_text_rect = name_text.get_rect()\n name_text_rect.centerx = self.rect.centerx\n name_text_rect.y = 5\n screen.blit(name_text, name_text_rect)\n cores = []\n for x in [1, 2, 3]:\n cores.append((255, 255, 255) if self.edit == x else (0, 0, 0))\n\n upper_string = f\"{text if self.edit == 1 else self.max}\"\n upper_text = font.render(\n upper_string, True, cores[0])\n upper_text_rect = upper_text.get_rect()\n upper_text_rect.centerx = self.slider_rail.centerx\n upper_text_rect.centery = self.slider_rail.top - \\\n (upper_text_rect.height)\n self.upper_text_rect = upper_text_rect\n screen.blit(upper_text, upper_text_rect)\n\n middle_string = f\"{text if self.edit == 2 else self.get_value():.2f}\"\n middle_text = font.render(\n middle_string, True, cores[1])\n middle_text_rect = middle_text.get_rect()\n middle_text_rect.centerx = self.slider_rail.x - middle_text_rect.width/2 - 5\n middle_text_rect.centery = self.slider_rail.centery\n self.middle_text_rect = middle_text_rect\n\n lower_string = f\"{text if self.edit == 3 else self.min}\"\n lower_text = font.render(\n lower_string, True, cores[2])\n lower_text_rect = lower_text.get_rect()\n lower_text_rect.centerx = self.slider_rail.centerx\n lower_text_rect.centery = self.slider_rail.bottom + 15\n self.lower_text_rect = lower_text_rect\n screen.blit(lower_text, lower_text_rect)\n\n screen.blit(middle_text, middle_text_rect)\n\n def update(self, pos, text):\n if self.grabbed:\n # limita o button no rail e muda pos do button de acordo com mouse\n if self.slider_rail.top <= pos[1] <= self.slider_rail.bottom:\n self.button_rect.centery = pos[1]\n elif pos[1] < self.slider_rail.top:\n self.button_rect.centery = self.slider_rail.top\n elif pos[1] > self.slider_rail.bottom:\n self.button_rect.centery = self.slider_rail.bottom\n # desenha o plano de fundo\n pygame.draw.rect(screen, self.bgcolor, self.rect)\n # slider rail\n pygame.draw.rect(screen, (50, 50, 50), self.slider_rail)\n # button\n pygame.draw.rect(screen, (200, 200, 200), self.button_rect)\n\n self.write(text)\n\n\nclass LineFollower:\n def __init__(self):\n # fazer pausa\n self.line = scrh/2\n self.height = scrh/2 - 100\n self.displacement = self.height - self.line # proporcional\n self.hor_speed = 5\n self.vert_speed = 0 # diferencial\n self.vert_acc = 0\n self.integral = 0 # p controle integral\n self.x = int((300+scrw)/2)\n # lista dos pontos anteriores para visuazilação\n # a bolinha em si não se move\n self.old_points_h = []\n # posições horizontais, não é alterada\n self.old_points_x = [300 + self.hor_speed *\n t for t in range(int((scrw-300)/2/self.hor_speed))]\n\n def update(self, p, i, d):\n self.old_points_h.append(self.height)\n if len(self.old_points_h) > len(self.old_points_x):\n self.old_points_h.pop(0)\n self.vert_acc = - (p*self.displacement + i *\n self.integral + d*self.vert_speed) / 1000\n self.vert_speed += self.vert_acc\n self.height += self.vert_speed\n self.displacement = self.height - self.line\n self.integral += self.displacement/100\n\n def render(self):\n # mostrar valores do PID\n pygame.draw.line(screen, (255, 255, 255), [\n 300, self.line], [scrw, self.line])\n pygame.draw.circle(screen, (150, 0, 200), [\n self.x, int(self.height)], 10)\n for y, x in zip(self.old_points_h[::-1], self.old_points_x[::-1]):\n # listas invertidas p considerar casos em que self.old_points_h ainda\n # não foi completamente preenchida\n pygame.draw.circle(screen, (0, 200, 150), [int(x), int(y)], 2)\n\n\nprop = Slider(0, (255, 0, 0), 100, 0, \"Proporcional\")\nintegral = Slider(1, (0, 255, 0), 0.1, 0, \"Integral\")\ndifer = Slider(2, (0, 0, 255), 100, 0, \"Diferencial\")\nsliders = [prop, integral, difer]\na = LineFollower()\ntxt = \"\"\nwhile kg:\n for ev in pygame.event.get():\n if ev.type == pygame.QUIT:\n kg = False\n if ev.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n editing = 0\n new_edit = 0\n for slider in sliders:\n if slider.edit:\n editing = slider\n break\n for slider in sliders:\n if slider.slider_rail.collidepoint(pos):\n slider.grabbed = True\n if slider.upper_text_rect.collidepoint(pos):\n new_edit = slider\n slider.edit = 1\n txt = str(slider.max)\n if slider.middle_text_rect.collidepoint(pos):\n new_edit = slider\n slider.edit = 2\n txt = str(slider.get_value())\n if slider.lower_text_rect.collidepoint(pos):\n new_edit = slider\n slider.edit = 3\n txt = str(slider.min)\n if new_edit:\n try:\n editing.edit = 0\n except AttributeError:\n pass\n if ev.type == pygame.KEYDOWN:\n for slider in sliders:\n if slider.edit:\n if ev.key == pygame.K_RETURN or ev.key == pygame.K_KP_ENTER:\n txt = txt.replace(\",\", \".\")\n for slider in sliders:\n if slider.edit:\n if slider.edit == 1:\n slider.max = float(txt)\n elif slider.edit == 2:\n slider.set_value(float(txt))\n elif slider.edit == 3:\n slider.min = float(txt)\n slider.edit = 0\n txt = \"\"\n elif ev.key == pygame.K_BACKSPACE:\n txt = txt[:-1]\n else:\n txt += ev.unicode\n if ev.type == pygame.MOUSEBUTTONUP:\n for slider in sliders:\n slider.grabbed = False\n screen.fill((0, 0, 0))\n pos = pygame.mouse.get_pos()\n for slider in sliders:\n slider.update(pos, txt)\n a.update(prop.get_value(), integral.get_value(), difer.get_value())\n a.render()\n pygame.display.update()\n timer.tick(60)\npygame.quit()\n","sub_path":"SimuladorPID.py","file_name":"SimuladorPID.py","file_ext":"py","file_size_in_byte":8386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"140498236","text":"import pytest\nimport numpy as np\nfrom solarforecastarbiter.metrics import valuation\n\n\n@pytest.mark.parametrize(\"fx,obs,cost,value\", [\n # cost: 10 USD per kW\n (np.array([1, 2, 3]), np.array([1, 2, 3]), 10, 0.0),\n (np.array([1, 2, 3]), np.array([2, 3, 4]), 10, 3 * 10),\n\n # cost: 1 USD per W/m^2\n (np.array([500, 600, 650]), np.array([500, 580, 630]), 1, 20 + 20),\n])\ndef test_fixed_cost(fx, obs, cost, value):\n return valuation.fixed_error_cost(obs, fx, cost) == value\n","sub_path":"solarforecastarbiter/metrics/tests/test_valuation.py","file_name":"test_valuation.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"544487916","text":"import os\nimport numpy as np\nimport tensorflow as tf\nimport cPickle\nimport pdb\nimport matplotlib.pyplot as plt\n\n\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = cPickle.load(fo)\n return dict\n\n\n\ndef read_labeled_image_list(img_list_path, img_dir):\n \"\"\"Reads a .txt file containing pathes and labeles\n Args:\n img_list_path: a .txt file with one /path/to/image with one label per line\n img_dir: path of directory that contains images\n Returns:\n List with all filenames\n \"\"\"\n f = open(img_list_path, 'r')\n img_paths = []\n labs = []\n for line in f:\n img_name, lab = line[:-1].split(' ')\n img_paths.append(img_dir + img_name)\n # pdb.set_trace()\n labs.append(int(lab))\n f.close()\n return img_paths, labs\n\n\ndef read_images_from_disk(input_queue):\n \"\"\"Consumes a single filename and label as a ' '-delimited string\n Args:\n filename_and_label_tensor: A scalar string tensor\n Returns:\n Two tensors: the decoded image, and the string label\n \"\"\"\n lab = input_queue[1]\n img_path = tf.read_file(input_queue[0])\n img = tf.image.decode_png(img_path, channels=3)\n return img, lab\n\n\n\ndef read_images_from_queue(input_queue):\n \"\"\"Consumes a single image and label\n Args:\n image_and_label_tensor: 1 dim Tensor image and a single label tensor\n Returns:\n Two tensors: the reshaped image, and the label\n \"\"\"\n lab = input_queue[1]\n img = input_queue[0]\n # pdb.set_trace()\n return img, lab\n\n\ndef read_images(batch_file):\n \"\"\" Unpickles the specified batch file\n Args:\n batch_file_name\n # Returns:\n Two numpy ndarrays : Images and their labels\n \"\"\"\n data = unpickle(batch_file)\n lab = data['labels']\n img = data['data']\n return img, lab\n\n\n\ndef get_loader(root, batch_size, normalize_data, flip_augment_data, crop_augment_data, split=None, shuffle=True):\n \"\"\" Get a data loader for tensorflow computation graph\n Args:\n root: Path/to/dataset/root/, a string\n batch_size: Batch size, a integer\n split: Data for train/val/test, a string\n shuffle: If the data should be shuffled every epoch, a boolean\n Returns:\n img_batch: A (float) tensor containing a batch of images.\n lab_batch: A (int) tensor containing a batch of labels.\n \"\"\"\n fname = root + '/datasets/' + split\n imgs_np, labs_np = read_images(fname)\n imgs_np = imgs_np.reshape([-1, 3, 32, 32])\n imgs_np = imgs_np.transpose([0, 2, 3, 1])\n\n with tf.device('/cpu:0'):\n imgs = tf.convert_to_tensor(imgs_np, dtype=tf.float64)\n labs = tf.convert_to_tensor(labs_np, dtype=tf.int64)\n input_queue = tf.train.slice_input_producer([imgs, labs],\n shuffle=shuffle, capacity=10*batch_size)\n img, lab = read_images_from_queue(input_queue)\n img.set_shape([32, 32, 3])\n img = tf.cast(img, tf.float32)\n if flip_augment_data:\n img = tf.image.random_flip_left_right(img)\n if normalize_data:\n img = tf.image.per_image_standardization(img)\n if crop_augment_data:\n img = tf.pad(img, paddings=[[4, 4], [4, 4], [0, 0]])\n img = tf.random_crop(img, size=[32, 32, 3])\n\n img_batch, lab_batch = tf.train.batch([img, lab], num_threads=1,\n batch_size=batch_size, capacity=10*batch_size)\n\n return img_batch, lab_batch\n\n\ndef get_loader_for_adversarial(root, batch_size, normalize_data, class_idx, split=None):\n \"\"\" Get a data loader for tensorflow computation graph\n Args:\n root: Path/to/dataset/root/, a string\n batch_size: Batch size, a integer\n split: Data for train/val/test, a string\n shuffle: If the data should be shuffled every epoch, a boolean\n Returns:\n img_batch: A (float) tensor containing a batch of images.\n lab_batch: A (int) tensor containing a batch of labels.\n \"\"\"\n fname = root + '/datasets/' + split\n imgs_np, labs_np = read_images(fname)\n imgs_np = imgs_np.reshape([-1, 3, 32, 32])\n imgs_np = imgs_np.transpose([0, 2, 3, 1])\n labs_np = np.array(labs_np)\n\n idx = np.random.choice((np.where(labs_np == class_idx))[0], 1)\n\n # Extract 1 image of the required class and create a large batch of the same image \n imgs_np = np.tile(imgs_np[idx,:], (batch_size, 1, 1, 1))\n labs_np = np.tile(labs_np[idx], (batch_size, 1))\n\n if normalize_data:\n imgs_np_mean = np.mean(imgs_np)\n imgs_np_std = np.std(imgs_np)\n imgs_np = (imgs_np - imgs_np_mean) / imgs_np_std\n else:\n imgs_np_mean = 0\n imgs_np_std = 1\n\n return imgs_np, labs_np, imgs_np_mean, imgs_np_std\n\n\n\ndef get_loader_for_testing_adversarial(root, batch_size, normalize_data, split=None, shuffle=False):\n print(root)\n img_paths_np, labs_np = read_labeled_image_list(root+'/adv_test/'+split+'.txt', root+'/adv_test/imgs/')\n\n with tf.device('/cpu:0'):\n img_paths = tf.convert_to_tensor(img_paths_np, dtype=tf.string)\n labs = tf.convert_to_tensor(labs_np, dtype=tf.int64)\n\n input_queue = tf.train.slice_input_producer([img_paths, labs],\n shuffle=shuffle, capacity=10*batch_size)\n\n img, lab = read_images_from_disk(input_queue)\n\n img.set_shape([32, 32, 3])\n img = tf.cast(img, tf.float32)\n\n if normalize_data:\n img = tf.image.per_image_standardization(img)\n\n img_batch, lab_batch = tf.train.batch([img, lab], num_threads=1,\n batch_size=batch_size, capacity=10*batch_size)\n\n return img_batch, lab_batch\n","sub_path":"HW2/utils/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"394871940","text":"from eICU_preprocessing.split_train_test import create_folder\nfrom models.run_lstm import BaselineLSTM\nfrom models.initialise_arguments import initialise_lstm_arguments\nfrom models.final_experiment_scripts.best_hyperparameters import best_lstm\n\n\nif __name__=='__main__':\n\n c = initialise_lstm_arguments()\n c['exp_name'] = 'StandardLSTM'\n c['dataset'] = 'eICU'\n c = best_lstm(c)\n\n log_folder_path = create_folder('models/experiments/final/eICU/LoS', c.exp_name)\n baseline_lstm = BaselineLSTM(config=c,\n n_epochs=c.n_epochs,\n name=c.exp_name,\n base_dir=log_folder_path,\n explogger_kwargs={'folder_format': '%Y-%m-%d_%H%M%S{run_number}'})\n baseline_lstm.run()","sub_path":"models/final_experiment_scripts/eICU/LoS/standard_lstm.py","file_name":"standard_lstm.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"31046800","text":"#\n# Modell trainieren\n#\n\nimport tensorflow as tf\nfrom tensorflow.python import keras\nfrom tensorflow.python.keras.layers import Dense, Activation\nfrom tensorflow.python.keras.models import Sequential, load_model,model_from_json\nfrom tensorflow.python.keras.optimizers import SGD\nfrom tensorflow.python.keras import metrics\nfrom pprint import pprint\nimport numpy as np\n\n# Einfaches Addieren \ninput_data = np.array([\n[\t1\t,\t1\t]\t,\n[\t2\t,\t2\t]\t,\n[\t3\t,\t3\t]\t,\n[\t4\t,\t4\t]\t,\n[\t5\t,\t5\t]])\n\noutput_data = np.array([[\t2\t],\n[\t4\t],\n[\t6\t],\n[\t8\t],\n[\t10\t]])\n\nmy_model = Sequential()\nmy_model.add(Dense(1024,input_dim=2,activation=\"linear\"))\nmy_model.add(Dense(1,activation=\"linear\"))\nmy_model.summary()\n\nsgd = SGD(lr=0.001)\nmy_model.compile(loss=\"mean_squared_error\", optimizer=sgd,metrics=[metrics.mae])\n\ndef simple_generator():\n i = 0\n limit = 10\n inputs = []\n outputs = []\n print(\"Bin der Generator!\")\n while True:\n for i in range(10):\n i = i + 1\n inputs.append([i,i])\n outputs.append([i])\n\n yield inputs, outputs\n #if(i==limit):\n # return\n\n\nmy_model.fit_generator(simple_generator(),initial_epoch=0,epochs=5,steps_per_epoch=100)\n\n# my_model.fit(input_data, output_data, batch_size=1, epochs=100, verbose=1)\n\n\n\n\n","sub_path":"samples/densepose/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"47684332","text":"from connections import models\n\nimport json\nfrom pkg_resources import resource_stream\nimport codecs\n\nimport pytest\n\nfrom results import models as results_models\n\n\n@pytest.fixture\ndef sample_datastore_response_json():\n with resource_stream('connections.tests.resources',\n 'sample_datastore_response.json') as f:\n\n reader = codecs.getreader(\"utf-8\")\n return json.load(reader(f))\n\n\n@pytest.mark.django_db\ndef test_datastore_connection(sample_datastore_response_json):\n dc = models.DatastoreConnection(url=\"https://example.com/\",\n token=\"00000000-0000-0000-0000-000000000000\")\n\n dc.retrieve_summary(test_data=sample_datastore_response_json)\n\n datastore_retrievals = results_models.DatastoreRetrieval.objects.all()\n registered_projects = results_models.RegisteredProject.objects.all()\n meter_result_summaries = results_models.MeterResultSummary.objects.all()\n\n assert len(datastore_retrievals) == 1\n assert len(registered_projects) == 1\n assert len(meter_result_summaries) == 8\n","sub_path":"connections/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"290796287","text":"from typing import TYPE_CHECKING\n\nfrom discordmenu.embed.base import Box\nfrom discordmenu.embed.components import EmbedThumbnail, EmbedMain, EmbedField\nfrom discordmenu.embed.text import Text, BoldText, LabeledText\nfrom discordmenu.embed.view import EmbedView\n\nfrom tsutils.enums import LsMultiplier\nfrom tsutils.menu.footers import embed_footer_with_state\nfrom tsutils.query_settings import QuerySettings\n\nfrom padinfo.common.config import UserConfig\nfrom padinfo.common.external_links import puzzledragonx\nfrom padinfo.view.common import leader_skill_header\nfrom padinfo.view.components.monster.header import MonsterHeader\nfrom padinfo.view.components.monster.image import MonsterImage\nfrom padinfo.view.components.view_state_base import ViewStateBase\nfrom padinfo.view.id import IdView\n\nif TYPE_CHECKING:\n from dbcog.models.monster_model import MonsterModel\n\nBASE_EMOJI = '\\N{DOWN-POINTING RED TRIANGLE}'\nTRANSFORM_EMOJI = '\\N{UP-POINTING RED TRIANGLE}'\n\n\nclass TransformInfoViewState(ViewStateBase):\n def __init__(self, original_author_id, menu_type, raw_query, color, base_mon, transformed_mon,\n acquire_raw, monster_ids, is_jp_buffed, query_settings,\n reaction_list):\n super().__init__(original_author_id, menu_type, raw_query, extra_state=None)\n self.color = color\n self.base_mon = base_mon\n self.transformed_mon = transformed_mon\n self.acquire_raw = acquire_raw\n self.monster_ids = monster_ids\n self.is_jp_buffed = is_jp_buffed\n self.query_settings: QuerySettings = query_settings\n self.reaction_list = reaction_list\n\n def serialize(self):\n ret = super().serialize()\n ret.update({\n 'query_settings': self.query_settings.serialize(),\n 'resolved_monster_ids': self.monster_ids,\n 'reaction_list': self.reaction_list\n })\n return ret\n\n @staticmethod\n async def deserialize(dbcog, user_config: UserConfig, ims: dict):\n raw_query = ims['raw_query']\n original_author_id = ims['original_author_id']\n menu_type = ims['menu_type']\n monster_ids = ims['resolved_monster_ids']\n base_mon_id = monster_ids[0]\n transformed_mon_id = monster_ids[1]\n query_settings = QuerySettings.deserialize(ims.get('query_settings'))\n\n base_mon = dbcog.get_monster(base_mon_id, server=query_settings.server)\n transformed_mon = dbcog.get_monster(transformed_mon_id, server=query_settings.server)\n\n acquire_raw = await TransformInfoViewState.do_query(dbcog, base_mon, transformed_mon)\n reaction_list = ims['reaction_list']\n is_jp_buffed = dbcog.database.graph.monster_is_discrepant(base_mon) \\\n or dbcog.database.graph.monster_is_discrepant(transformed_mon)\n\n return TransformInfoViewState(original_author_id, menu_type, raw_query, user_config.color,\n base_mon, transformed_mon, acquire_raw, monster_ids, is_jp_buffed,\n query_settings,\n reaction_list=reaction_list)\n\n @staticmethod\n async def do_query(dbcog, base_mon, transformed_mon):\n db_context = dbcog.database\n acquire_raw = db_context.graph.monster_acquisition(transformed_mon)\n return acquire_raw\n\n\ndef _get_tf_stat_diff_text(stat, tf_stat):\n return Box(\n Text(str(stat)),\n Text('-> {}'.format(tf_stat)),\n delimiter=' '\n )\n\n\ndef transformat(text: str):\n return '__{}__'.format(text)\n\n\ndef base_info(m: \"MonsterModel\"):\n return Box(\n Box(\n BASE_EMOJI,\n IdView.normal_awakenings_row(m) if len(m.awakenings) != 0\n else Box(Text('No Awakenings')),\n delimiter=' '\n ),\n IdView.super_awakenings_row(m)\n )\n\n\ndef card_info(base_mon: \"MonsterModel\", transformed_mon: \"MonsterModel\", acquire_raw):\n rarity = Box(\n LabeledText('Rarity', '{} -> {}'.format(base_mon.rarity, transformed_mon.rarity)),\n Text(\"\" if base_mon.orb_skin_id is None else \"(Orb Skin)\"),\n delimiter=' '\n )\n cost = LabeledText('Cost', '{} -> {}'.format(base_mon.cost, transformed_mon.cost))\n acquire = BoldText(acquire_raw) if acquire_raw else None\n\n return Box(rarity, cost, acquire)\n\n\ndef stats(base_mon: \"MonsterModel\", transformed_mon: \"MonsterModel\"):\n base_hp, base_atk, base_rcv, base_weighted = base_mon.stats()\n tf_hp, tf_atk, tf_rcv, tf_weighed = transformed_mon.stats()\n return Box(\n LabeledText('HP', _get_tf_stat_diff_text(base_hp, tf_hp)),\n LabeledText('ATK', _get_tf_stat_diff_text(base_atk, tf_atk)),\n LabeledText('RCV', _get_tf_stat_diff_text(base_rcv, tf_rcv))\n )\n\n\ndef transform_active_header(m: \"MonsterModel\"):\n active_skill = m.active_skill\n active_cd = '({} cd)'.format(active_skill.turn_min) if active_skill else 'None'\n return Box(\n TRANSFORM_EMOJI,\n BoldText('Transform Active Skill {}'.format(active_cd)),\n delimiter=' '\n )\n\n\ndef base_active_header(m: \"MonsterModel\"):\n return Box(\n BASE_EMOJI,\n BoldText('Base'),\n IdView.active_skill_header(m, m),\n delimiter=' '\n )\n\n\ndef leader_header(m: \"MonsterModel\", is_base: bool, lsmultiplier: LsMultiplier, base_mon: \"MonsterModel\"):\n if is_base:\n emoji = BASE_EMOJI\n label = 'Base'\n else:\n emoji = TRANSFORM_EMOJI\n label = 'Transform'\n\n return Box(\n emoji,\n BoldText(label),\n leader_skill_header(m, lsmultiplier, base_mon).to_markdown(),\n delimiter=' '\n )\n\n\nclass TransformInfoView:\n VIEW_TYPE = 'TransformInfo'\n\n @staticmethod\n def embed(state: TransformInfoViewState):\n base_mon = state.base_mon\n transformed_mon = state.transformed_mon\n lsmultiplier = state.query_settings.lsmultiplier\n fields = [\n EmbedField(\n '/'.join(['{}'.format(t.name) for t in transformed_mon.types]),\n Box(\n Box(\n TRANSFORM_EMOJI,\n IdView.normal_awakenings_row(transformed_mon)\n if len(transformed_mon.awakenings) != 0 else Box(Text('No Awakenings')),\n delimiter=' '\n ),\n base_info(base_mon),\n IdView.killers_row(base_mon, base_mon)\n ),\n ),\n EmbedField(\n BoldText(transformat('Card info')),\n card_info(base_mon, transformed_mon, state.acquire_raw),\n inline=True\n ),\n EmbedField(\n BoldText('Stats -> ' + transformat('Transform')),\n stats(base_mon, transformed_mon),\n inline=True\n ),\n EmbedField(\n transformat(transform_active_header(transformed_mon).to_markdown()),\n Box(\n Text(transformed_mon.active_skill.desc if transformed_mon.active_skill\n else 'None'),\n base_active_header(base_mon).to_markdown(),\n Text(base_mon.active_skill.desc if base_mon.active_skill else 'None')\n )\n ),\n EmbedField(\n transformat(leader_header(transformed_mon, False, lsmultiplier, base_mon).to_markdown()),\n Box(\n Text(transformed_mon.leader_skill.desc if transformed_mon.leader_skill\n else 'None'),\n leader_header(base_mon, True, lsmultiplier, base_mon).to_markdown(),\n Text(base_mon.leader_skill.desc if base_mon.leader_skill else 'None')\n )\n )\n ]\n\n return EmbedView(\n EmbedMain(\n color=state.color,\n title=MonsterHeader.fmt_id_header(transformed_mon,\n False,\n state.is_jp_buffed).to_markdown(),\n url=puzzledragonx(transformed_mon)\n ),\n embed_thumbnail=EmbedThumbnail(MonsterImage.icon(transformed_mon)),\n embed_footer=embed_footer_with_state(state),\n embed_fields=fields\n )\n","sub_path":"padinfo/view/transforminfo.py","file_name":"transforminfo.py","file_ext":"py","file_size_in_byte":8340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"27085038","text":"import re\n\n\nDefaultResourceRequestsPrefix: str = \"requests.\"\nResourceDefaultNamespacePrefix: str = \"kubernetes.io/\"\nResourceHugePagesPrefix: str = \"hugepages-\"\nResourceAttachableVolumesPrefix: str = \"attachable-volumes-\"\n\nQualifiedNameMaxLength: int = 63\nQnameCharFmt: str = r\"[A-Za-z0-9]\"\nQnameExtCharFmt: str = r\"[-A-Za-z0-9_.]\"\nQualifiedNameFmt: str = f\"({QnameCharFmt}{QnameExtCharFmt}*)?{QnameCharFmt}\"\nQualifiedNameRegexp = re.compile(f\"^{QualifiedNameFmt}$\")\n\n\ndef is_prefixed_native_resource_name(name: str) -> bool:\n \"\"\"\n Returns true if the `name` contains `kubernetes.io/`\n \"\"\"\n\n return ResourceDefaultNamespacePrefix in name\n\n\ndef is_native_resource_name(name: str) -> bool:\n \"\"\"\n Returns true if the `name` contains `kubernetes.io/` or `name`\n does not contain `/`\n \"\"\"\n\n return \"/\" not in name or is_prefixed_native_resource_name(name)\n\n\ndef is_huge_page_resource_name(name: str) -> bool:\n \"\"\"\n Returns true if the resource name has the huge page resource prefix\n \"\"\"\n return name.startswith(ResourceHugePagesPrefix)\n\n\ndef is_qualified_name(name: str) -> bool:\n parts = name.split(\"/\")\n parts_len = len(parts)\n\n if parts_len == 1:\n name = parts[0]\n elif parts_len == 2:\n prefix, name = parts\n if len(prefix) == 0:\n return False\n else:\n return False\n\n if (\n not name\n or len(name) > QualifiedNameMaxLength\n or not QualifiedNameRegexp.match(name)\n ):\n return False\n\n return True\n\n\ndef is_extended_resource_name(name: str) -> bool:\n if is_native_resource_name(name) or name.startswith(DefaultResourceRequestsPrefix):\n return False\n\n name_for_quota = f\"{DefaultResourceRequestsPrefix}{name}\"\n return is_qualified_name(name_for_quota)\n\n\ndef is_attachable_volume_resource_name(name: str) -> bool:\n return name.startswith(ResourceAttachableVolumesPrefix)\n\n\ndef is_scalar_resource_name(name: str) -> bool:\n return (\n is_extended_resource_name(name)\n or is_huge_page_resource_name(name)\n or is_prefixed_native_resource_name(name)\n or is_attachable_volume_resource_name(name)\n )\n","sub_path":"airport/kube/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"193041238","text":"import time\nimport graph_tool.all as gt\nfrom aux import get_delay, get_instance\n\n\n# graph\ng = gt.Graph(directed=False)\n\n# vertex list, cost map, delay map\nv_list, cost, delay = get_instance(g)\n\n# add budget\nbudget = 10\n\nbest = [float('Inf'), None]\n\ndef brute_force(graph, delay, cost, budget, upgrade, i, pcost):\n global best\n if (i == len(list(graph.vertices()))):\n d = get_delay(graph, delay, upgrade)\n tree = gt.min_spanning_tree(graph, weights=d)\n pdelay = sum([a*b for a,b in zip(list(tree),list(d))])\n\n if (pdelay < best[0] and pcost <= budget):\n best[0] = pdelay\n best[1] = upgrade\n\n else:\n upgrade2 = upgrade.copy()\n upgrade[i] = 0\n brute_force(graph, delay, cost, budget, upgrade, i+1, pcost)\n upgrade2[i] = 1\n brute_force(graph, delay, cost, budget, upgrade2, i+1, pcost+cost[i])\n\n return 0\n\n\n#******************************** BACKTRACK *********************************#\nprint(\"Running brute force algorithm...\")\nstart = time.time()\nbrute_force(g, delay, cost, budget, [-1]*len(list(g.vertices())), 0, 0)\nend = time.time()\nprint(\"MST delay: \", best[0])\n#print(\"Upgraded nodes: \", best[1])\nprint(\"Elapsed time: \", end-start)\n#*****************************************************************************#","sub_path":"bruteforce.py","file_name":"bruteforce.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"401695325","text":"\"\"\"The main framwork for this work.\nSee README for usage.\n\"\"\"\n\nimport argparse\nimport torch\n\ntry:\n from mpi4py import MPI\nexcept ImportError:\n MPI = None\nimport os\nimport sys\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\n# set key parameters\ndef argsparser():\n parser = argparse.ArgumentParser(\"WDAIL\")\n parser.add_argument('--env_name', help='environment ID', default='HalfCheetah-v1')\n parser.add_argument('--algo', help='algorithm ID', default='WDAIL')\n parser.add_argument('--log-dir', default='/tmp/gym/', help='directory to save agent logs (default: /tmp/gym)')\n # general\n parser.add_argument('--total_steps', help='total steps', type=int, default=10e6)\n parser.add_argument('--num_env_steps', help='total steps', type=int, default=10e6)\n parser.add_argument('--evaluate_every', help='evaluate every', type=int, default=2e10)\n parser.add_argument('--save_condition', help='save_condition', type=int, default=1000)\n parser.add_argument('--num_model', help='num_model', type=int, default=10)\n parser.add_argument('--use_device', help='use_device', type=bool, default=True)\n parser.add_argument('--cuda', help='num_model', type=int, default=0)\n parser.add_argument('--seed', help='seed', type=int, default=5)\n parser.add_argument('--use_linear_lr_decay', help='use linear lr decay', type=bool, default=True)\n parser.add_argument('--recurrent-policy', action='store_true', default=False, help='use a recurrent policy')\n\n #ppo\n parser.add_argument('--num_processes', help='num_processes', type=int, default=1)\n parser.add_argument('--num-steps', help='num-steps', type=int, default=2048)\n parser.add_argument('--lr', help='learning rate', type=float, default=3e-4)\n parser.add_argument('--batch_size', help='batch size', type=int, default=64)\n parser.add_argument('--ppo_epoch', help='ppo epoch num', type=int, default=10)\n parser.add_argument('--hidden_size', help='hidden size', type=int, default=64)\n parser.add_argument('--ppo_entcoeff', help='entropy coefficiency of policy', type=float, default=1e-3) #default=1e-3\n parser.add_argument('--ppo_obs_norm', help='ppo_vec_norm', type=bool, default=True)\n parser.add_argument('--num-mini-batch', type=int, default=32, help='number of batches for ppo (default: 32)')\n parser.add_argument('--clip-param', type=float, default=0.2, help='ppo clip parameter (default: 0.2)')\n parser.add_argument('--eps', type=float, default=1e-5, help='RMSprop optimizer epsilon (default: 1e-5)')\n parser.add_argument('--alpha', type=float, default=0.99, help='RMSprop optimizer apha (default: 0.99)')\n parser.add_argument('--gamma', type=float, default=0.99, help='discount factor for rewards (default: 0.99)')\n parser.add_argument('--use-gae', action='store_true', default=True, help='use generalized advantage estimation')\n parser.add_argument('--gae-lambda', type=float, default=0.95, help='gae lambda parameter (default: 0.95)')\n parser.add_argument('--entropy-coef', type=float, default=0.00, help='entropy term coefficient (default: 0.01)')\n parser.add_argument('--value-loss-coef', type=float, default=0.5, help='value loss coefficient (default: 0.5)')\n parser.add_argument('--max-grad-norm', type=float, default=0.5, help='max norm of gradients (default: 0.5)')\n\n # #gail\n parser.add_argument('--gail', help='if gail', type=bool, default=True)\n parser.add_argument('--expert_path', help='trajs path', type=str, default='../data/baseline/stochastic.trpo.HalfCheetah.0.00.npz')\n # parser.add_argument('--expert_path', help='trajs path', type=str, default='../data/baseline/deterministic.trpo.HalfCheetah.0.00.npz')\n # parser.add_argument('--expert_path', help='trajs path', type=str, default='../data/ikostirkov/trajs_ant.h5')\n parser.add_argument('--gail-experts-dir',default='./gail_experts', help='directory that contains expert demonstrations for gail')\n parser.add_argument('--gail_batch_size', type=int, default=128, help='gail batch size (default: 128)')\n parser.add_argument('--gail_thre', help='number of steps to train discriminator in each epoch', type=int, default=10)\n parser.add_argument('--gail_pre_epoch', help='number of steps to train discriminator in each epoch', type=int, default=100)\n parser.add_argument('--gail_epoch', help='number of steps to train discriminator in each epoch', type=int, default=5)\n parser.add_argument('--num_trajs', help='num trajs', type=int, default=5)\n parser.add_argument('--subsample_frequency', help='num trajs', type=int, default=1)\n parser.add_argument('--adversary_entcoeff', help='entropy coefficiency of discriminator', type=float, default=1e-3)\n parser.add_argument('--use-proper-time-limits', action='store_true', default=True, help='compute returns taking into account time limits')\n parser.add_argument('--log-interval', type=int, default=1, help='log interval, one log per n updates (default: 10)')\n\n parser.add_argument('--reward_type', type=int, default=0, help='0,1,2,3,4')\n parser.add_argument('--update_rms', type=bool, default=True, help='False or True')\n\n\n return parser.parse_args()\n\ndef train(args):\n\n # from ppo_gail_iko.algo.ppo4multienvs import PPO, ReplayBuffer\n from ppo_wdail_BL.algo.ppo import PPO\n from ppo_wdail_BL.tools.storage import RolloutStorage\n from ppo_wdail_BL.tools.model import Policy\n\n from ppo_wdail_BL.algo.wdgail import Discriminator, ExpertDataset\n from ppo_wdail_BL.algo.mujoco_dset_zm_base import Mujoco_Dset\n\n from ppo_wdail_BL.tools.learn import gailLearning_mujoco_origin, gailLearning_mujoco_BL\n from ppo_wdail_BL.tools.envs import make_vec_envs\n\n from ppo_wdail_BL.tools import utli\n from ppo_wdail_BL.tools import utils\n\n from collections import deque\n import time\n import numpy as np\n\n\n # from nets.network import ActorCritic_mujoco as ActorCritic\n cl_args = args\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed_all(args.seed)\n\n # if args.cuda and torch.cuda.is_available() and args.cuda_deterministic:\n # torch.backends.cudnn.benchmark = False\n # torch.backends.cudnn.deterministic = True\n\n log_dir = os.path.expanduser(args.log_dir)\n eval_log_dir = log_dir + \"_eval\"\n utils.cleanup_log_dir(log_dir)\n utils.cleanup_log_dir(eval_log_dir)\n\n torch.set_num_threads(1)\n\n device = torch.device('cuda:'+ str(cl_args.cuda) if torch.cuda.is_available() else 'cpu')\n # device = torch.device('cpu')\n\n envs = make_vec_envs(args.env_name, args.seed, args.num_processes,\n args.gamma, args.log_dir, device, False)\n\n # envs_eval = make_vec_envs(args.env_name, args.seed, args.num_processes,\n # args.gamma, args.log_dir, device, False)\n envs_eval = []\n temp = envs.observation_space.shape\n # network\n actor_critic = Policy(\n envs.observation_space.shape,\n envs.action_space,\n base_kwargs={'recurrent': args.recurrent_policy})\n actor_critic.to(device)\n\n agent = PPO(\n actor_critic,\n args.clip_param,\n args.ppo_epoch,\n args.num_mini_batch,\n args.value_loss_coef,\n args.entropy_coef,\n lr=args.lr,\n eps=args.eps,\n max_grad_norm=args.max_grad_norm)\n\n # discriminator\n discr = Discriminator(envs.observation_space.shape[0] + envs.action_space.shape[0], 100, device, args.reward_type, args.update_rms)\n\n # file_name = os.path.join(\n # args.gail_experts_dir, \"trajs_{}.pt\".format(\n # args.env_name.split('-')[0].lower()))\n #\n # gail_train_loader = torch.utils.data.DataLoader(\n # ExpertDataset(\n # file_name, num_trajectories=args.num_trajs, subsample_frequency=args.subsample_frequency),\n # batch_size=args.gail_batch_size,\n # shuffle=True,\n # drop_last=True)\n\n # The buffer\n rollouts = RolloutStorage(args.num_steps, args.num_processes,\n envs.observation_space.shape, envs.action_space,\n actor_critic.recurrent_hidden_state_size)\n\n # The buffer for the expert -> refer to dataset/mujoco_dset.py\n # expert_path = cl_args.expert_path+cl_args.env_id+\".h5\"\n expert_buffer = Mujoco_Dset(cl_args.expert_path, traj_limitation=cl_args.num_trajs, subsample_frequency=args.subsample_frequency)\n\n\n model = gailLearning_mujoco_BL(cl_args=cl_args,\n envs=envs,\n envs_eval=envs_eval,\n actor_critic=actor_critic,\n agent=agent,\n discriminator=discr,\n rollouts=rollouts,\n expert_buffer=expert_buffer,\n device=device,\n utli=utli)\n\n return 0\n\n\ndef main(args):\n\n model, env = train(args)\n\n # if args.play:\n #\n # obs = env.reset()\n #\n # state = model.initial_state if hasattr(model, 'initial_state') else None\n # dones = np.zeros((1,))\n #\n # episode_rew = 0\n # while True:\n # if state is not None:\n # actions, _, state, _ = model.step(obs,S=state, M=dones)\n # else:\n # actions, _, _, _ = model.step(obs)\n #\n # obs, rew, done, _ = env.step(actions)\n # episode_rew += rew[0] if isinstance(env, VecEnv) else rew\n # env.render()\n # done = done.any() if isinstance(done, np.ndarray) else done\n # if done:\n # print(f'episode_rew={episode_rew}')\n # episode_rew = 0\n # obs = env.reset()\n #\n # env.close()\n\n return model\n\nif __name__ == '__main__':\n\n args = argsparser()\n main(args)\n\n","sub_path":"WDAIL/ppo_wdail_BL/wdail_halfcheetah.py","file_name":"wdail_halfcheetah.py","file_ext":"py","file_size_in_byte":9965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"78480964","text":"from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder\nimport awswrangler as wr\n\nfrom settings import S3_FOLDER\n\n\ndef encoder_from_s3(name):\n \"\"\"get encoder from s3\"\"\"\n if name == \"team\":\n team_map = wr.s3.read_csv(S3_FOLDER + \"encoders/team_map_all.csv\")\n encoder = OrdinalEncoder()\n encoder.fit(team_map[[\"teamids\"]])\n elif name == \"player\":\n player_map = wr.s3.read_csv(S3_FOLDER + \"encoders/player_map_all.csv\")\n encoder = OrdinalEncoder(handle_unknown=\"use_encoded_value\", unknown_value=-1)\n encoder.fit(player_map[[\"playerids\"]])\n elif name == \"event\":\n event_map = wr.s3.read_csv(S3_FOLDER + \"encoders/event_map_all.csv\")\n encoder = OneHotEncoder()\n # encoder = OneHotEncoder([event_map[\"events\"].tolist()])\n encoder.fit(event_map[[\"events\"]])\n else:\n raise ValueError(f\"{name} encoder does not exist.\")\n return encoder\n","sub_path":"processing/nbastats/common/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"533383384","text":"from panda3d.core import *\n\nfrom src.core.showbase import *\n\nclass Skybox:\n def __init__(self, systemName, root):\n self.root = root\n self.name = systemName\n self.model = loader.loadModel(\"data/skyboxes/\" + systemName + \"/model\")\n self.model.setLightOff()\n self.model.reparentTo(root)\n self.model.setPos(base.camera.getPos(render))\n self.model.setScale(100)\n self.model.setDepthWrite(False)\n self.model.setBin(\"background\", 50)\n\n self.lights = []\n\n dataFile = open(\"data/skyboxes/\" + systemName + \"/data.txt\", \"r\")\n data = dataFile.read()\n dataFile.close()\n data = data.split(\"\\n\")\n\n for line in data:\n lineData = line.split(\":\")\n if lineData[0] == \"ambientLight\":\n alight = AmbientLight('alight')\n alight.setColor(VBase4(float(lineData[1]), float(lineData[2]), float(lineData[3]), 1))\n alnp = root.attachNewNode(alight)\n root.setLight(alnp)\n self.lights.append(alnp)\n if lineData[0] == \"directionalLight\":\n dlight = DirectionalLight(\"dlight\")\n dlight.setColor(Vec4(float(lineData[1]), float(lineData[2]), float(lineData[3]), 1))\n dlight.setSpecularColor(Vec4(float(lineData[1]), float(lineData[2]), float(lineData[3]), 1))\n dlnp = root.attachNewNode(dlight)\n dlnp.setHpr(float(lineData[4]), float(lineData[5]), 0)\n root.setLight(dlnp)\n self.lights.append(dlnp)\n\n def update(self):\n self.model.setPos(base.camera.getPos(render))\n\n def destroy(self):\n self.model.removeNode()\n for l in self.lights:\n self.root.clearLight(l)\n l.removeNode()","sub_path":"src/game/skybox.py","file_name":"skybox.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"99909976","text":"ip_add = input(\"Enter the ip address in format X.X.X.X/Z: \")\n\nsubnet = ip_add.split(\"/\")[0]\nsubnet_mask = ip_add.split(\"/\")[1]\n\nsubnet_list = subnet.split(\".\")\noct1 = subnet_list[0]\noct2 = subnet_list[1]\noct3 = subnet_list[2]\noct4 = subnet_list[3]\n\nsubnet_mask_int = int(subnet_mask)\ninteresting_octet = int(subnet_mask_int/8)\nsubnet_mask_str = \"1\" * int(subnet_mask)\nnum_zeros = 32 - subnet_mask_int\nnum_zeros_str = \"0\" * num_zeros\nsubnet_mask_str = subnet_mask_str + num_zeros_str\nmask_oct1 = subnet_mask_str[:8] \nmask_oct2 = subnet_mask_str[8:16] \nmask_oct3 = subnet_mask_str[16:24] \nmask_oct4 = subnet_mask_str[24:32]\n\noct1 = int(oct1) & int(mask_oct1, 2)\noct2 = int(oct2) & int(mask_oct2, 2)\noct3 = int(oct3) & int(mask_oct3, 2)\noct4 = int(oct3) & int(mask_oct4, 2)\n\nprint(\"Network:\")\nprint(\"{:<8} {:<8} {:<8} {:<8}\".format(oct1, oct2, oct3, oct4))\nprint(\"{:08b} {:08b} {:08b} {:08b} \\n\".format(oct1, oct2, oct3, oct4))\n\nprint(\"Mask:\")\nprint(subnet_mask)\nprint(\"{:8} {:8} {:8} {:8}\".format(str(int(mask_oct1, 2)), str(int(mask_oct2, 2)), str(int(mask_oct3, 2)), str(int(mask_oct4, 2))))\nprint(\"{:8} {:8} {:8} {:8}\".format(mask_oct1, mask_oct2, mask_oct3, mask_oct4))","sub_path":"solutions/task_5_2a.py","file_name":"task_5_2a.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"574128340","text":"#!/usr/bin/python\nimport argparse\nimport json\nimport web3\nimport sys\nimport logging\nimport pymongo\nimport progressbar\nimport requests\nimport time\n\nfrom pymongo import MongoClient\nfrom bson import Decimal128\n\nfrom mnemonic import Mnemonic\n\nfrom datetime import datetime\nfrom web3 import Web3\nfrom hexbytes import HexBytes\n\nfrom helper import query_yes_no\n\nlogging.basicConfig(level=logging.INFO)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-a', '--addr', type=str, help='Address for which the txs will be scraped', required=True)\nparser.add_argument('-d', '--database', type=str, help='Name of the MongoDB database', required=True)\nparser.add_argument('-s', '--start-block', type=int, help='Start block', default=0)\nparser.add_argument('-e', '--end-block', type=int, help='End block', default=99999999)\nparser.add_argument('--drop', action='store_true', help='Drop existing DB before scraping')\nparser.add_argument('--skip-confirmation', action='store_true', help='Skip asking for confirmation for dropping the DB')\nparser.add_argument('--delay', type=int, help='Scraping delay in seconds', default=5)\n\n\ndef get_url(addr, start, end):\n return \"http://api.etherscan.io/api?module=account&action=txlist&address=%s&startblock=%d&endblock=%d&sort=asc\"%(addr, start, end)\n\ndef tx_to_dict(tx):\n result = {}\n for key, val in tx.items():\n if isinstance(val, HexBytes):\n result[key] = val.hex()\n else:\n result[key] = val\n\n if 'value' in result: result['value'] = Decimal128(str(result['value']))\n if 'gasPrice' in result: result['gasPrice'] = Decimal128(str(result['gasPrice']))\n\n return result\n\ndef block_to_dict(tx):\n result = {}\n for key, val in tx.items():\n if isinstance(val, HexBytes):\n result[key] = val.hex()\n else:\n result[key] = val\n\n if 'difficulty' in result: result['difficulty'] = Decimal128(str(result['difficulty']))\n if 'totalDifficulty' in result: result['totalDifficulty'] = Decimal128(str(result['totalDifficulty']))\n\n return result\n\n\ndef __main__():\n args = parser.parse_args()\n\n client = MongoClient()\n\n dbnames = client.list_database_names()\n\n if args.drop and args.database in dbnames:\n if not args.skip_confirmation:\n if not query_yes_no('Are you sure you want to drop existing DB: '+args.database, default='no'):\n sys.exit()\n\n client.drop_database(args.database)\n\n db = client[args.database]\n\n tx_collection = db['transactions']\n tx_collection.create_index([(\"hash\", pymongo.ASCENDING)], unique=True)\n\n filtered_addrs = []\n if args.addr:\n filtered_addrs += args.addr.split(',')\n elif args.file:\n filtered_addrs += open(args.file, 'r').read().split('\\n')\n\n filtered_addrs = [i.lower() for i in filtered_addrs if Web3.isAddress(i)]\n\n bar = progressbar.ProgressBar(max_value=args.end_block-args.start_block)\n\n tx_count = 0\n\n start = args.start_block\n end = args.end_block\n\n while True:\n response = requests.get(get_url(args.addr, start, end))\n txs = response.json()['result']\n\n if txs == None:\n time.sleep(args.delay)\n print('Nothing returned. Repeating API call.')\n continue\n\n # txs = sorted(txs, key=lambda x: x['blockNumber'])\n\n for n, tx in enumerate(txs):\n try:\n tx_collection.insert_one(tx_to_dict(tx))\n tx_count += 1\n except pymongo.errors.DuplicateKeyError:\n pass\n\n if len(txs) == 0:\n break\n\n if int(txs[-1]['blockNumber']) >= end:\n break\n\n start = int(txs[-1]['blockNumber'])\n # end = txs[-1]['blockNumber']\n\n print('Scraped', txs[0]['blockNumber'], '-',txs[-1]['blockNumber'])\n\n time.sleep(args.delay)\n\n import ipdb; ipdb.set_trace()\n\n\n\n logging.info('Finished importing %d txs from %d blocks'%(tx_count, args.end_block-args.start_block))\n\n\nif __name__ == '__main__':\n __main__()\n","sub_path":"scrape_txs_etherscan.py","file_name":"scrape_txs_etherscan.py","file_ext":"py","file_size_in_byte":4033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"510270885","text":"#-*- coding:utf-8 -*-\n\nimport sys, os\nsys.path.append(os.path.realpath(os.path.dirname(__file__))+\"/../..\")\n\nimport pytest\nimport json\nfrom autoremovetorrents.torrent import Torrent\nfrom autoremovetorrents.torrentstatus import TorrentStatus\nfrom autoremovetorrents.compatibility.open import _open\n\n@pytest.fixture(scope=\"module\")\ndef test_data():\n # Load input data\n input_torrents = []\n with _open(os.path.join(os.path.realpath(os.path.dirname(__file__)),'data.json'), encoding='utf-8') as f:\n data = json.load(f)\n for torrent in data:\n input_torrents.append(Torrent(\n torrent['hash'],\n torrent['name'],\n torrent['category'],\n torrent['tracker'],\n TorrentStatus[str(torrent['state']).capitalize()],\n torrent['is_stalled'],\n torrent['size'],\n torrent['ratio'],\n torrent['uploaded'],\n torrent['added_on'],\n torrent['seeding_time']\n ))\n\n return input_torrents\n\n@pytest.fixture(scope=\"module\")\ndef test_env():\n with _open(os.path.join(os.path.realpath(os.path.dirname(__file__)), 'environment.json'), encoding='utf-8') as f:\n env = json.load(f)\n return env","sub_path":"pytest/test_strategies/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"325807398","text":"from django.db import models\nfrom django.utils import timezone\n\nimport requests, json\nimport ipdb\n\n# Create your models here.\n\nclass Node(models.Model):\n\n INSTALL_STATES = (\n ('CL', 'Clean'),\n ('CO', 'Configured'),\n ('IN', 'Installed'),\n ('ER', 'Error')\n )\n\n razor_id = models.CharField(unique=True, max_length=30)\n created = models.DateTimeField() \n install_state = models.CharField(\n max_length=2,\n choices=INSTALL_STATES,\n default='CL'\n )\n\n def __init__(self, *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n \n def save(self, *args, **kwargs):\n\n if not self.id:\n self.created = timezone.now()\n\n super().save()\n \n def ip(self):\n return get_node_ip(self.razor_id)\n \n\nclass Log(models.Model):\n node = models.ForeignKey(Node, on_delete=models.CASCADE)\n text = models.CharField(max_length=100)\n created = models.DateTimeField()\n \n def save(self, *args, **kwargs):\n ''' On save, set created'''\n if not self.id:\n self.created = timezone.now()\n\n super().save()\n \ndef create_new_log(node_name, message):\n \n node = Node.objects.get(razor_id=node_name)\n Log.objects.create(node=node, text=message)\n \n\nclass RazorCantConnectException(Exception):\n pass\n\ndef get_id_from_ip(ip):\n '''Gets the razor_id corresponding with the given mac-address'''\n do_refresh_nodes\n\n nodes = get_nodes_from_razor()\n\n for node in nodes:\n if check_node_ip(node['name'], ip):\n return node['name']\n\n return None\n \ndef check_node_ip(node_id, ip):\n\n node_ip = get_node_ip(node_id)\n \n if node_ip == ip:\n return True\n else:\n return False\n\ndef get_node_ip(node_id):\n node_obj = get_node_object_from_razor(node_id)\n\n return node_obj['facts']['ipaddress']\n\ndef get_node_object_from_razor(node_id):\n node_reply = do_request('http://127.0.0.1:8150/api/collections/nodes/'+node_id)\n node_obj = json.loads(node_reply.text)\n\n return node_obj\n \ndef do_refresh_nodes():\n\n nodes = get_nodes_from_razor()\n check_node_list(nodes)\n\ndef check_node_list(nodes):\n\n for node in nodes:\n try:\n Node.objects.get(razor_id=node['name'])\n except Node.DoesNotExist:\n Node.objects.create(razor_id=node['name'])\n\ndef get_nodes_from_razor():\n '''TODO: make setting of the URL of the razor API''' \n \n try:\n reply = do_request('http://127.0.0.1:8150/api/collections/nodess')\n\n except requests.ConnectionError:\n raise RazorCantConnectException\n\n reply_obj = json.loads(reply.text)\n return reply_obj['items']\n\ndef do_request(url):\n \n try:\n reply = requests.get(url)\n except requests.ConnectionError:\n raise requests.ConnectionError\n \n return reply\n\ndef get_razor_data(node_id):\n '''Gets the data for 'node_id' from the razor API'''\n '''IS REDUNDANT'''\n \n try:\n reply = do_request('http://127.0.0.1:8150/api/collections/nodes/'+node_id)\n\n except requests.ConnectionError:\n raise RazorCantConnectException \n\n reply_obj = json.loads(reply.text)\n\n return reply_obj \n\n","sub_path":"osinstall/nodes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"4936392","text":"from functools import lru_cache\n\nimport pygame\n\nfrom wclib.constants import ASSETS\n\n\n@lru_cache()\ndef font(size=20, name=None):\n \"\"\"Load a font from the wclib/assets folder. Results are cached.\"\"\"\n #name = name or \"regular\"\n #path = ASSETS / (name + \".ttf\")\n return pygame.font.SysFont(name, size)\n\n\n@lru_cache(5000)\ndef text(txt, color, size=20, font_name=None):\n \"\"\"Render a text on a surface. Results are cached.\"\"\"\n return font(size, font_name).render(str(txt), True, color)\n\n\n@lru_cache(None)\ndef load_image(name: str, alpha=True):\n \"\"\"Load an image from disk. Results are cached.\"\"\"\n img = pygame.image.load(ASSETS / f\"{name}.png\")\n if alpha:\n return img.convert_alpha()\n else:\n return img.convert()\n\n\ndef clamp(value, mini, maxi):\n \"\"\"Clamp value between mini and maxi\"\"\"\n if value < mini:\n return mini\n elif maxi < value:\n return maxi\n else:\n return value\n\n\n@lru_cache()\ndef overlay(image: pygame.Surface, color, alpha=255):\n \"\"\"Overlays a color on a surface.\"\"\"\n img = pygame.Surface(image.get_size())\n img.set_colorkey((0, 0, 0))\n img.blit(image, (0, 0))\n\n mask = pygame.mask.from_surface(image)\n overlay = mask.to_surface(setcolor=color, unsetcolor=(255, 255, 0, 0))\n overlay.set_alpha(alpha)\n img.blit(overlay, (0, 0))\n\n return img\n","sub_path":"wclib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"27992011","text":"import wx\nimport slippy_map as sm\n\nclass AppFrame(wx.Frame):\n\tdef __init__(self):\n\t\tsuper(AppFrame, self).__init__(parent=None, title=\"Demo\")\n\t\tself.SetClientSize((800,600))\n\t\tsizer = wx.BoxSizer(wx.VERTICAL)\n\t\t# sizer.Add(item=wx.StaticText(parent=self,label=\"some text\"))\n\t\tself.panel = sm.SlippyMap(49.25765, 7.04550, 16, parent=self)\n\t\tsizer.Add(item=self.panel, flag= wx.ALL | wx.EXPAND)\n\n\nif __name__ == \"__main__\":\n\tapp = wx.App(redirect=False)\n\tappFrame = AppFrame()\n\tappFrame.Show()\n\tapp.MainLoop()","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"631650654","text":"import pygame\n\n\nclass Level(object):\n blank = '.'\n block = 'b'\n enemy = '^'\n exit = 'X'\n\n blockWidth = 75\n blockHeight = 75\n \n def __init__(self, level_data_filename):\n import re\n with open(level_data_filename, 'r') as f:\n self.levelRaw = f.readlines()\n # replace any of the visual blocks with just a regular block only for the collision layer\n self.collisionLayer = [re.sub(\"0\", \"b\", row.strip('\\n')) for row in self.levelRaw]\n\n self.levelWidth = len(self.collisionLayer[0])\n self.levelHeight = len(self.collisionLayer)\n \n self.leftEdge = 0\n self.topEdge = 0\n self.rightEdge = self.levelWidth * self.blockWidth\n self.bottomEdge = self.levelHeight * self.blockHeight\n \n \n self.blockSurf = pygame.Surface((self.blockWidth, self.blockHeight))\n self.blockSurf.fill((255,255,255))\n self.blockSurf.set_alpha(100)","sub_path":"lib/level.py","file_name":"level.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316160194","text":"from interface import implements\nfrom os.path import dirname, split\nfrom exceptions.custom_exception import CustomException\nfrom orchestration.common import helper\nfrom orchestration.data.blob_storage import BlobStorage\nfrom orchestration.models.content_type import ContentType\nfrom orchestration.integration.cli.aad_client import AADClientCli\nfrom orchestration.integration.cli.keyvault_client import KeyVaultClientCli\nfrom orchestration.integration.sdk.policy_client import PolicyClientSdk\nfrom orchestration.integration.sdk.resource_management_client import ResourceManagementClientSdk\nfrom orchestration.integration.sdk.management_lock_client import ManagementLockClientSdk\nfrom orchestration.ibusiness import BusinessInterface\nfrom orchestration.common.parameter_initializer import ParameterInitializer\nfrom orchestration.data.idata import DataInterface\nfrom orchestration.common.module_version import ModuleVersionRetrieval\nfrom orchestration.models.resource_module import ResourceModule\nimport json\nimport sys\nimport logging\n\nclass ResourceValidation(implements(BusinessInterface)):\n\n _logger = logging.getLogger(__name__)\n _vdc_storage_output_container_name: str = 'output'\n\n def __init__(\n self,\n data_store: DataInterface,\n management_lock_integration_service: ManagementLockClientSdk,\n resource_management_integration_service: ResourceManagementClientSdk,\n policy_integration_service: PolicyClientSdk,\n aad_cli_integration_service: AADClientCli,\n keyvault_cli_integration_service: KeyVaultClientCli,\n module_version_retrieval: ModuleVersionRetrieval,\n vdc_storage_account_name: str,\n vdc_storage_account_subscription_id: str,\n vdc_storage_account_resource_group: str,\n validate_deployment: bool,\n delete_validation_modules: bool,\n deploy_all_modules: bool,\n deployment_configuration_path: str,\n module_deployment_order: list,\n resource_group: str,\n single_module: str,\n deploy_module_dependencies: bool,\n upload_scripts: bool,\n create_vdc_storage: bool,\n shared_services_deployment_name: str,\n deployment_name: str,\n location: str,\n tenant_id: str,\n subscription_id: str,\n shared_services_subscription_id: str,\n service_principals: list,\n organization_name: str,\n encryption_keys_for: list,\n module_dependencies: list,\n environment_type: str,\n json_parameters: dict,\n import_module: str,\n custom_scripts_path: str,\n environment_keys: dict):\n\n ''' Class initializer\n \n :param data_store: Data storage instance used by VDC to store deployment outputs and custom scripts\n :type data_store: DataInterface\n :param sdk_integration_service: Integration instance that calls SDK commands\n :type sdk_integration_service: IntegrationInterface\n :param aad_cli_integration_service: Integration instance that calls CLI commands that interacts with AAD\n :type aad_cli_integration_service: ADClientCli\n :param keyvault_cli_integration_service: Integration instance that calls CLI commands that interacts with KeyVault and creates Certificates and Encryption Keys\n :type keyvault_cli_integration_service: KeyVaultClientCli\n :param vdc_storage_account_name: VDC Storage Account Name, storage account that stores scripts and deployment outputs\n :type vdc_storage_account_name: str\n :param vdc_storage_account_subscription_id: Subscription Id where VDC Storage Account resides\n :type vdc_storage_account_subscription_id: str\n :param vdc_storage_account_resource_group: Resource group containing VDC Storage Account resides\n :type vdc_storage_account_resource_group: str\n :param validate_deployment: Indicates whether or not the deployment is running in validation mode\n :type validate_deployment: bool\n :param delete_validation_modules: Indicates whether or not to delete validation modules created during the validation process. Validation modules such as KeyVault\n :type delete_validation_modules: bool\n :param deploy_all_modules: Indicates whether or not all modules are being deployed\n :type deploy_all_modules: bool\n :param deployment_configuration_path: Archetype path containing deployment configuration information\n :type deployment_configuration_path: str\n :param module_deployment_order: List containing modules to be deployed\n :type module_deployment_order: list\n :param resource_group: If passed, all resources will be deployed in this resource group\n :type resource_group: str\n :param single_module: When -r argument is passed, indicates that a single module will getß deployed\n :type single_module: str\n :param deploy_module_dependencies: Indicates whether or not all module dependencies must be deployed first\n :type deploy_module_dependencies: bool\n :param upload_scripts: Indicates whether or not to upload scripts to VDC Storage Account\n :type upload_scripts: bool\n :param create_vdc_storage: Indicates whether or not VDC Storage Account will get created\n :type create_vdc_storage: bool\n :param shared_services_deployment_name: When deploying a shared_services, this value is the same as deployment_name. When deploying a workload, this value will be different\n :type shared_services_deployment_name: str\n :param deployment_name: Deployment name\n :type deployment_name: str\n :param location: Location to use when creating a resource group\n :type location: str\n :param tenant_id: Tenant Id\n :type tenant_id: str\n :param subscription_id: Subscription Id\n :type subscription_id: str\n :param shared_services_subscription_id: Shared Services Subscription Id\n :type shared_services_subscription_id: str\n :param service_principals: List of service principals, this list is used to grant access (by using azure cli) to KeyVault\n :type service_principals: list\n :param organization_name: Organization name\n :type organization_name: str\n :param encryption_keys_for: List used to create KeyVault encryption keys (these values are used in Azure Disk Encryption VM extension)\n :type encryption_keys_for: list\n :param module_dependencies: Main list containing all module dependencies from the main parameter file\n :type module_dependencies: list\n :param environment_type: Deployment type, this could be: Shared Services | Workload | On-premises\n :type environment_type: str\n :param json_parameters: Dictionary representation of main parameters file\n :type json_parameters: dict\n :param import_module: Value of the main module\n :type import_module: str\n :param custom_scripts_path: Custom scripts path\n :type custom_scripts_path: str\n :param environment_keys: Dictionary containing command line argument information\n :type environment_keys: dict\n\n :raises: :class:`CustomException`\n '''\n \n self._default_parameters = dict() \n self._modules_already_provisioned = list() \n self._data_store = data_store\n self._resource_management_integration_service = resource_management_integration_service\n self._policy_integration_service = policy_integration_service\n self._management_lock_integration_service = management_lock_integration_service\n self._aad_cli_integration_service = aad_cli_integration_service\n self._keyvault_cli_integration_service = keyvault_cli_integration_service\n self._module_version_retrieval = module_version_retrieval\n self._vdc_storage_account_name = vdc_storage_account_name\n self._vdc_storage_account_subscription_id = vdc_storage_account_subscription_id\n self._vdc_storage_account_resource_group = vdc_storage_account_resource_group\n self._validation_mode_on = validate_deployment\n self._deploy_all_modules = deploy_all_modules\n self._deployment_configuration_path = deployment_configuration_path\n self._module_deployment_order = module_deployment_order\n self._resource_group = resource_group\n self._single_module = single_module\n self._deploy_module_dependencies = deploy_module_dependencies\n self._upload_scripts = upload_scripts\n self._create_vdc_storage = create_vdc_storage\n self._shared_services_deployment_name = shared_services_deployment_name\n self._deployment_name = deployment_name\n self._location = location\n self._tenant_id = tenant_id\n self._subscription_id = subscription_id\n self._shared_services_subscription_id = shared_services_subscription_id\n self._service_principals = service_principals\n self._organization_name = organization_name\n self._encryption_keys_for = encryption_keys_for\n self._module_dependencies = module_dependencies\n self._environment_type = environment_type\n self._json_parameters = json_parameters\n self._import_module = import_module\n self._custom_scripts_path = custom_scripts_path\n self._environment_keys = environment_keys\n self._deployment_prefix = self.get_deployment_prefix(\n self._organization_name,\n self._environment_type,\n self._deployment_name)\n self._module_validation_dependencies = []\n self._validation_resource_groups = []\n self._delete_validation_modules = delete_validation_modules\n self._logger.info(\"Using the following output parameter deployment prefix: {}\".format(\n self._deployment_prefix))\n \n def create(self) -> list:\n\n '''Main function used to execute a module(s) deployment.\n\n This function creates a storage repository to place all deployment outputs, and to to place\n custom scripts if --upload-scripts argument passed is set to true.\n :param parameter_initializer: Object containing all required properties used during a module provisioning\n :type parameter_initializer: ParameterInitializer\n :param deployment_path: Path that contains deployment and parameters folders\n :type deployment_path: str\n :raises: :class:`CustomException`\n '''\n \n try: \n \n # Append dummy sas key to default parameters, the key will now be\n # appended to all deploy templates \n self.append_to_default_parameters(dict(\n {\n 'sas-key': 'xxxxxxxxxx', \n 'output-params-storage-key': 'xxxxxxxxxx', \n 'output-params-storage-account-name': 'xxxxxxxxxx'\n }))\n\n module_names = list()\n\n if self._deploy_all_modules == True:\n # Let's get all the deployment folders\n module_names = self._module_deployment_order\n self._logger.info('validating all modules:{}'.format(\n module_names))\n else:\n if self._single_module is None or self._single_module == '':\n raise CustomException('No module has been passed')\n\n # Single module, let's add it to the list\n module_names.append(self._single_module)\n \n # Let's create a dummy resource group for the validation to pass\n self._resource_management_integration_service\\\n .create_or_update_resource_group(\n self._resource_group, \n self._location)\n \n self._provision_module_validation_dependencies(\n self._module_dependencies)\n \n for module in module_names:\n self._deploy(\n self._module_dependencies,\n module, \n self._resource_group)\n\n # Let's prepare to delete resource groups created during the validation process\n self._validation_resource_groups.append(self._resource_group)\n\n self._logger\\\n .info('About to delete the following resource groups: {}'.format(\n self._validation_resource_groups))\n \n for validation_resource_group in self._validation_resource_groups:\n # After the validation, let's delete the dummy resource group\n self._logger\\\n .info('Deleting the following resource group: {}'.format(\n validation_resource_group))\n self._management_lock_integration_service\\\n .delete_all_resource_group_locks(\n validation_resource_group)\n self._resource_management_integration_service\\\n .delete_resource_group(\n validation_resource_group)\n\n return list()\n \n except Exception as ex:\n self._logger.error('There was an unhandled error while provisioning the modules.')\n self._logger.error(ex)\n sys.exit(1) # Exit the module as it is not possible to progress the deployment.\n raise ex\n\n def _deploy(\n self, \n all_modules: list,\n module_to_deploy: str,\n resource_group_to_deploy: str = None):\n\n \"\"\"Function that analyzes the module to be deployed. If dependencies are found, \n these will get provisioned first (recursive call), following the deployment order from the \n main template (module-deployment-order property). \n\n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :param module_to_deploy: The name of the module to deploy. \n Resource should exist in deployments/shared_services|workload/ folder (i.e. deployments/shared_services/vnet)\n The name is case sensitive.\n :type module_to_deploy: str (optional)\n :param resource_group_to_deploy: A resource deployment will use this name as resource group.\n If no value is provided, a default name gets created with the following format:\n organizationName-shared-services|workload-module (i.e. contoso-shared-services-net)\n :type resource_group_to_deploy: str\n :raises: :class:`Exception`\n \"\"\"\n \n self._logger\\\n .info('***** validating module: {} *****'.format(\n module_to_deploy.upper()))\n\n # Find the module and check if there are dependencies, \n # if yes, execute the dependency provisioning first\n module_found = self.find_module(\n self._module_dependencies,\n module_to_deploy)\n \n if self._deploy_module_dependencies and \\\n module_found is not None and \\\n len(module_found._dependencies) > 0:\n \n self._logger\\\n .info('dependencies found: {}'.format(\n module_found._dependencies))\n \n # Let's sort the dependencies based on module-deployment-order \n # parameter (from shared_services or workload folder -> /parameters/azureDeploy.parameters.json)\n dependencies = self.sort_module_deployment_list(\n module_found._dependencies)\n\n for dependency in dependencies:\n self._logger.info('validating dependency: {} on resource group: {}'.format(\n dependency, \n resource_group_to_deploy))\n\n # Let's deploy all the dependencies recursively\n self._deploy(\n all_modules,\n dependency, \n resource_group_to_deploy)\n \n create_resource_group = True\n \n # Not need to validate the validation process dependencies again, these got already validated and provisioned\n if module_to_deploy not in self._module_validation_dependencies:\n # Now, let's deploy the module (after a recursive loop or from single module - if no dependencies were found) \n self._deploy_initial(\n all_modules,\n module_to_deploy, \n resource_group_to_deploy, \n create_resource_group)\n\n def _deploy_initial(\n self, \n all_modules: list,\n module_to_deploy: str, \n resource_group_to_deploy: str,\n create_resource_group: bool = True):\n\n \"\"\"Main function that executes the module provisioning.\n\n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :param module_to_deploy: The name of the module to deploy. \n Resource should exist in deployments/shared_services|workload/ folder (i.e. deployments/shared_services/vnet)\n The name is case sensitive.\n :type module_to_deploy: str\n :param resource_group_to_deploy: A resource deployment will use this name as resource group.\n This function creates a resource group if it does not exist.\n :type resource_group_to_deploy: str\n :param create_resource_group: Value to instruct if a resource group will be created.\n By default, a module deployment creates a resource group, but there are two situations \n where a module will be deployed in an existing resource group:\n 1. Nested deployment \n (in parameters/shared_services|workload/azureDeploy.parameters.json: module-dependencies -> create-resource-group property)\n 2. Resource dependency to use dependent resource group \n (in parameters/shared_services|workload/azureDeploy.parameters.json: module-dependencies -> same-resource-group property)\n :type create_resource_group: bool (optional)\n :raises: :class:`Exception`\n \"\"\"\n \n if module_to_deploy in self._modules_already_provisioned:\n self._logger\\\n .info('{} already provisioned'.format(module_to_deploy))\n else:\n # Add module to list of already provisioned modules\n self._modules_already_provisioned.append(module_to_deploy)\n \n template_file: dict = self.get_deployment_template_contents(\n all_modules,\n module_to_deploy)\n \n parameters_file: dict = self.get_parameters_template_contents(\n all_modules,\n module_to_deploy)\n \n # This function checks if there are dependencies, if yes, the function \n # appends output parameters from the blob storage into the parameters file and also appends\n # the values from _default_parameters (dict)\n parameters_file = self.append_dependency_parameters(\n all_modules,\n module_to_deploy)\n \n # Since we are appending all output parameters coming from a file, there is a chance that not all of\n # the parameters appended are present in the template file.\n # To avoid an exception that a parameter is passed and is not present\n # in the original file, we'll append the parameters that are not present to the template file\n template_file = self.append_parameters_not_present_in_template(\n parameters_file,\n template_file)\n\n if parameters_file is not None:\n \n import copy\n # Replace tokens, if any\n parameters_file = \\\n helper.replace_all_tokens(\n dict_with_tokens=copy.deepcopy(parameters_file),\n parameters=self._json_parameters,\n organization_name=self._organization_name,\n shared_services_deployment_name=self._shared_services_deployment_name,\n workload_deployment_name=self._deployment_name,\n storage_container_name=self._vdc_storage_output_container_name,\n environment_keys=self._environment_keys,\n storage_access=self._data_store,\n validation_mode=self._validation_mode_on)\n\n # Let's execute operations, if any\n replaced_string = helper.operations(\n json.dumps(parameters_file), \n self._json_parameters)\n\n parameters_file = \\\n json.loads(replaced_string)\n \n self._logger\\\n .info('parameters and deployment files successfully loaded')\n\n deployment_name = '{}-deployment-{}'.format(\n self._deployment_prefix,\n module_to_deploy)\n\n current_milliseconds = \\\n helper.get_current_time_milli()\n\n milliseconds_length = \\\n len(str(current_milliseconds))\n\n # Max length is 60 chars\n deployment_name_max_length = \\\n 60 - milliseconds_length\n\n if len(deployment_name) > deployment_name_max_length:\n # We do -1 to accomodate the hyphen character\n deployment_name = \\\n deployment_name[:deployment_name_max_length - 1]\n\n deployment_name = '{}-{}'.format(\n deployment_name,\n current_milliseconds)\n\n # Execute the deployment\n self._resource_management_integration_service\\\n .validate_deployment(\n mode='Incremental',\n template=template_file,\n parameters=parameters_file,\n resource_group_name=resource_group_to_deploy,\n deployment_name=deployment_name)\n\n # Save output paramaters to Azure storage so that dependent modules can read it\n self._logger.info('***** module deployment validation completed successfully *****')\n\n def _provision_module_validation_dependencies(\n self,\n all_modules: list):\n \"\"\"Function that validates and provision validation-module dependencies.\n These modules are required to be provisioned first in order to pass the validation process.\n An example is KeyVault, if KeyVault is referenced in a parameters file (say to retrieve a secret), \n then validation process expects KeyVault to exist, for this reason, KeyVault needs to be temporally provisioned for\n the validation process to succeed. The module gets temporally created because at the end of the validation process\n the resource group gets deleted.\n\n This function, besides provisioning the modules, will also append any resource group created to\n the list: _validation_resource_groups, this list is used later to delete all resource groups created\n\n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :raises: :class:`Exception`\n \"\"\"\n # module-validation-dependencies are modules that get provisioned prior running any validation\n if 'module-validation-dependencies' in self._json_parameters['orchestration'] \\\n and len(self._json_parameters['orchestration']['module-validation-dependencies']) > 0:\n self._module_validation_dependencies = \\\n self._json_parameters['orchestration']['module-validation-dependencies']\n \n # Let's sort the module-validation-dependencies\n self._module_validation_dependencies = \\\n self.sort_module_deployment_list(\n self._module_validation_dependencies)\n \n self._logger\\\n .info('module-validation dependencies found: {}'.format(\n self._module_validation_dependencies))\n \n if len(self._module_validation_dependencies) > 0:\n for module_validation_dependency in self._module_validation_dependencies:\n \n self._logger.info('module_validation found: {}'.format(\n module_validation_dependency))\n\n # Let's get the resource group name\n resource_group_to_deploy = \\\n self._get_resource_group_name(\n all_modules=all_modules,\n module_name=module_validation_dependency, \n resource_group=None)\n\n self._logger\\\n .info('resource group to create: {}'.format(\n resource_group_to_deploy))\n \n # Let's provision the module_validation_dependency dependency resource group\n self._resource_management_integration_service\\\n .create_or_update_resource_group(\n resource_group_to_deploy, \n self._location)\n\n # Let's run the validation process prior provisioning the module\n self._deploy(\n all_modules,\n module_validation_dependency, \n resource_group_to_deploy)\n self._logger\\\n .info('module-validation dependencies successfully validated')\n \n self._logger\\\n .info('About to provision module-validation dependencies')\n \n # If all succeeded, let's provision the module-validation dependencies (an example of a validation \n # module dependency is: KeyVault, that is referenced in the parameters file to retrieve secret information for instance) \n for module_validation_dependency in self._module_validation_dependencies: \n from orchestration.resource_deployment import ResourceDeployment\n \n # Let's update parameter_initializer to deploy only the module-validation\n deploy_all_modules = False\n single_module = module_validation_dependency\n validate_deployment = True\n deploy_module_dependencies = True\n \n # Invoke deployment and append resulting resource groups created, these RGs \n # will get deleted\n \n resourceDeployment = ResourceDeployment(\n self._data_store, \n self._resource_management_integration_service,\n self._policy_integration_service,\n self._aad_cli_integration_service,\n self._keyvault_cli_integration_service,\n self._module_version_retrieval,\n self._vdc_storage_account_name,\n self._vdc_storage_account_subscription_id,\n self._vdc_storage_account_resource_group,\n validate_deployment,\n deploy_all_modules,\n self._deployment_configuration_path,\n self._module_deployment_order,\n None,\n single_module,\n deploy_module_dependencies,\n self._upload_scripts,\n self._create_vdc_storage,\n self._shared_services_deployment_name,\n self._deployment_name,\n self._location,\n self._tenant_id,\n self._subscription_id,\n self._shared_services_subscription_id,\n self._service_principals,\n self._organization_name,\n self._encryption_keys_for,\n self._module_dependencies,\n self._environment_type,\n self._json_parameters,\n self._import_module,\n self._custom_scripts_path,\n self._environment_keys)\n\n resource_groups_provisioned = \\\n resourceDeployment.create()\n\n if self._delete_validation_modules:\n self._validation_resource_groups = \\\n self._validation_resource_groups + resource_groups_provisioned\n \n def _get_resource_group_name(\n self,\n all_modules: list,\n module_name: str,\n resource_group: str):\n \"\"\"Function that evaluates a module object's properties to generate a resource group name or use an existing one.\n \n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :param module_name: Resource name, this value is used to construct a default resource group\n :type module_name: str\n :param resource_group: Resource group name, if passed, it is used to create a resource group\n :type resource_group: str\n \"\"\"\n \n module_found = self.find_module(\n all_modules,\n module_name)\n\n dependent_module_found = \\\n self.is_a_dependency_deployable_in_dependent_rg(\n all_modules,\n module_name)\n \n # If a resource group value is passed from the command line argument, let's use it\n if resource_group is not None and \\\n resource_group != '':\n resource_group_to_deploy = resource_group\n elif dependent_module_found is not None and \\\n dependent_module_found._resource_group_name != '':\n # Let's grab the resource-group-name value of the dependent module found\n resource_group_to_deploy = \\\n dependent_module_found._resource_group_name\n elif dependent_module_found is not None:\n # Let's create a resource group name based on the dependent module found\n resource_group_to_deploy = \\\n self.create_default_resource_group_name(\n dependent_module_found._module)\n elif module_found is not None and \\\n not module_found._create_resource_group:\n \n # Let's use the resource group name of the first dependency found.\n # This is the case when the resource specifies create-resource-group = false.\n # When executing nested deployments, ARM expects a resource group name to be passed\n # (even if the template specifies resource group information). \n # For this reason, we need to pass a resource group name that exists,\n # to prevent an ARM validation error.\n resource_group_to_deploy = \\\n self._get_resource_group_name(\n all_modules=all_modules,\n module_name=module_found._dependencies[0],\n resource_group=None)\n elif module_found is not None and \\\n module_found._resource_group_name != '' :\n # Let's grab the resource-group-name value of the module found\n resource_group_to_deploy = module_found._resource_group_name\n else:\n # Let's create a resource group name based on the module found\n resource_group_to_deploy = \\\n self.create_default_resource_group_name(\n module_name)\n \n return resource_group_to_deploy\n\n def create_vdc_storage(\n self):\n pass\n\n def get_deployment_template_contents(\n self,\n all_modules: list,\n module_name: str):\n \"\"\"Function that reads a local folder to fetch a deployment template file.\n \n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :param module_name: Resource name used to construct the file path \n (i.e. /shared_services/deployments/net/azureDeploy.json)\n :type module_name: str\n\n :raises: :class:`Exception`\n \"\"\"\n\n module_found = self.find_module(\n all_modules=all_modules,\n module_to_find=module_name)\n\n if module_found is None:\n module_found = \\\n ResourceModule()\\\n .create_default(module_name=module_name)\n \n return self._module_version_retrieval.get_template_file(\n version=module_found._source._version,\n module_name=module_found._module,\n path=module_found._source._template_path)\n\n def get_parameters_template_contents(\n self,\n all_modules: list,\n module_name: str):\n \"\"\"Function that reads a local folder to fetch a deployment parameters file.\n \n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :param module_name: Resource name used to construct the file path \n (i.e. parameters/shared_services/net/azureDeploy.json)\n :type module_name: str\n\n :raises: :class:`Exception`\n \"\"\"\n\n module_found = self.find_module(\n all_modules=all_modules,\n module_to_find=module_name)\n\n if module_found is None:\n module_found = \\\n ResourceModule()\\\n .create_default(module_name=module_name)\n\n return self._module_version_retrieval.get_parameters_file(\n version=module_found._source._version,\n module_name=module_found._module,\n path=module_found._source._parameters_path)\n\n def create_policies(\n self,\n all_modules: list,\n module_name: str=None,\n resource_group_name: str=None,\n is_subscription_policy: bool = False):\n \"\"\"Function that creates and assigns policies.\n \n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :param module_name: Resource name used to construct the file path \n (i.e. policies/shared_services/net/arm.policies.json)\n :type module_name: str\n :param resource_group_name: Resource group name used in the policy assignment. \n This value is required when is_subscription_policy is set to True\n :type resource_group_name: str\n :param is_subscription_policy: Instructs the function to assign a policy to a subscription (true)\n or resource group (false)\n :type is_subscription_policy: bool\n\n :raises: :class:`CustomException`\n \"\"\"\n pass\n\n def store_deployment_outputs(\n self,\n container_name: str,\n output_name: str,\n output_content_data: str):\n \"\"\"Function that stores deployment outputs.\n\n :param container_name: The name of container where the outputs (in json format) will be placed. \n :type container_name: str\n :param output_name: Name of the output file\n :type output_name: str\n :param output_content_data: Deployment output data (deserialized json)\n :type output_name: str\n \n :raises: :class:`Exception`\n \"\"\"\n pass\n\n def store_custom_scripts(\n self):\n \"\"\"Function that stores custom scripts (from scripts folder).\n\n :raises: :class:`Exception`\n \"\"\"\n pass\n\n def find_module(\n self,\n all_modules: list,\n module_to_find: str) -> ResourceModule:\n \"\"\"Function that returns a module from parameters/shared_services|workload/azureDeploy.parameters.json -> module-dependencies\n\n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :param module_to_find: Resource name to find in module-dependencies\n :type module_to_find: str\n \n :return: module or None if no module was found\n :rtype: dict\n :raises: :class:`Exception`\n \"\"\"\n\n strongly_typed_modules = \\\n list(map(ResourceModule, all_modules))\n \n resource_module: ResourceModule = None\n\n for resource_module in strongly_typed_modules:\n if resource_module._module == module_to_find:\n return resource_module\n \n # If not found, return None\n return None\n\n def find_dependencies(\n self,\n all_modules: list,\n module_to_find: str) -> list:\n \"\"\"Function that returns module dependencies, if any (parameters/shared_services|workload/azureDeploy.parameters.json -> module-dependencies -> dependencies)\n\n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :param module_name_to_find: Resource name to analyze if dependencies property contains any values\n :type module_name_to_find: str\n \n :return: module dependencies or None if no values were found\n :rtype: dict\n :raises: :class:`Exception`\n \"\"\"\n\n module_found = self.find_module(\n all_modules=all_modules,\n module_to_find= module_to_find)\n\n if module_found is not None and\\\n len(module_found._dependencies) > 0:\n return module_found._dependencies\n else:\n return None\n\n def append_dependency_parameters(\n self,\n all_modules: list,\n module_name: str):\n \"\"\"Function that appends dependency parameters to parameters file. If a module contains\n dependencies (module-dependencies -> dependencies) and these dependencies generated an\n output, then these values get appended to the parameters file.\n This is similar to a linked template where the deployment contains \n outputs [reference('').outputs..value].\n\n This function also appends the values from _default_parameters. \n By default there are three\n values:\n {\n 'sas-key': sas_key, \n 'output-params-storage-key': storage_account_key, \n 'output-params-storage-account-name': self._vdc_storage_account_name\n }\n\n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :param module_name: Resource name used to construct the parameters file path \n :type module_name: str\n :param template_file_contents: Template file deserialized\n :type template_file_contents: str\n \n :return: deployment parameters\n :rtype: dict\n :raises: :class:`Exception`\n \"\"\"\n dependencies = self.find_dependencies(\n all_modules=all_modules,\n module_to_find=module_name)\n \n parameters_file_contents = \\\n self.get_parameters_template_contents(\n all_modules,\n module_name)\n \n # Let's initialize the dict if a file does not exists\n if parameters_file_contents is None:\n parameters_file_contents = dict()\n \n if dependencies is not None and len(dependencies) > 0: \n \n self._logger\\\n .info(\"appending dependency output parameters to parent: {}\".format(\n module_name))\n\n for module_dependency in dependencies: \n \n template_file = self.get_deployment_template_contents(\n all_modules,\n module_dependency)\n \n if 'outputs' in template_file:\n output_data = template_file['outputs']\n \n output_parameters = dict()\n # Outputs format is as follows:\n # \"default-subnet-nsg-id\": {\n # \"type\": \"string\",\n # \"value\": \"[resourceId('Microsoft.Network/networkSecurityGroups', variables('nsg-name'))]\"\n # },\n for dictKey, dictValue in output_data.items():\n # dictValue contains the value object (from above -> type and value properties) this is why we use dictValue['value']\n # to fetch the actual value of \"value\" property\n output_parameters.update({\n dictKey : {\n \"value\": self.get_default_value(dictValue['type']) \n }\n })\n\n # Let's append the output parameters to the parameters file\n parameters_file_contents.update(output_parameters)\n\n # Let's append the values from _default_parameters (i.e. storage sas key\n # storage account name, etc.)\n parameters_file_contents.update(self._default_parameters)\n\n return parameters_file_contents\n\n def get_default_value(\n self,\n type: str):\n\n if type.lower() == 'string':\n return \"vdc-validation-test-rg\"\n elif type.lower() == 'int':\n return 1\n else:\n return \"\"\n\n def is_a_dependency_deployable_in_dependent_rg(\n self, \n all_modules: list,\n module_to_find: str) -> ResourceModule:\n \"\"\"Function that evaluates if a module dependency will be deployed in a dependent resource group.\n If parameters/shared_services|workload/azureDeploy.parameters.json -> module-dependencies -> same-resource-group is set to true, it means\n that the dependencies will be deployed in the dependent resource group\n\n :param all_modules: List containing an array of all modules. \n This array is retrieved from main parameters file -> module-dependencies -> modules array\n :type all_modules: list\n :param module_to_find: Resource to find in dependencies property\n parameters/shared_services|workload/azureDeploy.parameters.json -> module-dependencies -> dependencies\n :type module_to_find: str\n\n :raises: :class:`Exception`\n \"\"\"\n\n # Let's get all the modules\n \n strongly_typed_modules = \\\n list(map(ResourceModule, all_modules))\n\n resource_module: ResourceModule = None\n\n for resource_module in strongly_typed_modules:\n \n # Let's analyze the dependencies\n dependencies = resource_module._dependencies\n \n if len(dependencies) > 0 and\\\n module_to_find in dependencies and\\\n resource_module._same_resource_group:\n \n self._logger.info(\n 'Provision dependencies in same resource group as {} module'.format(resource_module._module))\n \n # Dependency found, and has same-resource-group flag \n # set to True\n return resource_module\n\n return None\n\n def get_deployment_prefix(\n self, \n organization_name: str,\n environment_type: str,\n deployment_name: str):\n \"\"\"Constructs a default deployment prefix value using the following format:\n OrganizationName-Shared-Services|Workload (i.e. contoso-shared-services)\n\n :param organization_name: The organization name to be used.\n :type organization_name: str\n :param environment_type (optional): The deployment type to be used (shared_services or workload). \n :type environment_type: str\n :param deployment_name (optional): The deployment name to be used. \n :type deployment_name: str\n\n :return: deployment prefix\n :rtype: str\n :raises: :class:`Exception`\n \"\"\"\n\n return '{}-{}-{}'.format(\n organization_name,\n environment_type,\n deployment_name)\n\n def append_to_default_parameters(\n self, \n args : dict):\n \"\"\"Appends parameters to a global variable called _default_parameters.\n _default_parameters is a dictionary that gets appended on every module deployment.\n Make sure to add these values to the deployment template\n\n :param args: The parameters to be appended to _default_parameters.\n :type args: dict\n\n :raises: :class:`Exception`\n \"\"\"\n\n for arg in args:\n self._logger.debug(\"Appending: {}, Value: {}\".format(arg, args[arg]))\n self._default_parameters[arg] = {'value': args[arg]}\n\n def sort_module_deployment_list(\n self, \n module_list: list):\n \"\"\"Function that sorts all modules based on module-deployment-order\n\n :param module_list: List of unsorted modules.\n :type module_list: list\n\n :return: sorted list\n :rtype: list\n :raises: :class:`Exception`\n \"\"\"\n\n if self._module_deployment_order is not None and module_list is not None:\n module_list = helper.sort_module_deployment(\n module_list,\n self._module_deployment_order)\n \n return module_list\n\n def create_default_resource_group_name(\n self, \n module_name: str):\n \"\"\"Function that creates a default resource group name using the following format:\n OrganizationName-Shared-Services|Workload-Resource-rg (i.e. contoso-shared-services-net-rg)\n\n :param module_name: Resource name to be used as part of the resource group name.\n :type module_name: str\n\n :return: resource group name\n :rtype: str\n :raises: :class:`Exception`\n \"\"\"\n\n return '{}-{}-{}-rg'.format(\n self._organization_name,\n self._deployment_name,\n module_name)\n\n def append_parameters_not_present_in_template(\n self,\n parameters_to_append: dict,\n template_file: dict):\n \"\"\"Function that evaluates what are the parameters coming from a dependency - output\n that do not exist in the template file, and proceeds to append them temporally (these missing parameters\n do not get persisted), this function ensures that ARM won't throw an exception due to missing\n parameters in the original template.\n\n :param parameters_to_append: Parameters to be appended\n The ones not present in template_file will get appended\n :type parameters_to_append: dict\n :param template_file: Template file serialized\n :type template_file: dict\n \n :return: deployment template\n :rtype: dict\n :raises: :class:`Exception`\n \"\"\"\n\n parameters_from_template = template_file['parameters']\n paremeters_not_present = [item for item in parameters_to_append if item not in parameters_from_template]\n \n # Now let's append the parameters that are not present using a default format\n for paremeter_not_present in paremeters_not_present:\n \n paremeter_not_present_value = parameters_to_append[paremeter_not_present]['value'] if 'value' in parameters_to_append[paremeter_not_present] else 'vdc'\n paremeter_not_present_type = parameters_to_append[paremeter_not_present]['type'] if 'type' in parameters_to_append[paremeter_not_present] else 'string'\n \n template_file['parameters'].update({\n paremeter_not_present : {\n \"defaultValue\": paremeter_not_present_value,\n \"type\": paremeter_not_present_type\n }\n })\n\n return template_file","sub_path":"orchestration/resource_validation.py","file_name":"resource_validation.py","file_ext":"py","file_size_in_byte":48663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"471648448","text":"# -*- coding: utf-8 -*-\n'''\nThis is an example for preprocessing a raw text corpus, which is The Tragedy of Romeo and Juliet in The Complete Works of William Shakespeare from Project Gutenberg.\nOf course, we could easily get it via nltk.corpus package as shown in the latter part of the code, which even tokenized the words for us.\nThus, it is indeed more helpful knowing how to preprocess/normalize raw text as we could have a full grasp of our dataset.\n\nnltk requirements:\n```\nimport nltk\nnltk.download('shakespeare')\nnltk.download('punkt')\n```\n'''\n\nfrom nltk import word_tokenize\nimport pickle\n\n# Corpus path\npath = f'data/shakespeare.txt'\n\nwith open(path, 'r') as f:\n corpus = []\n start = False\n for line in f:\n if start == True and line != '\\n':\n # Rules to ignore some lines\n if line.isupper() or line.strip('\\n').isnumeric() or line.startswith(' ') or line.startswith('Scene') or line.startswith('Contents') or line.startswith('SCENE') or line.startswith('ACT'):\n continue\n else: corpus.append(line.strip('\\n').strip())\n if line == 'THE TRAGEDY OF ROMEO AND JULIET\\n':\n # Ignore text until title is found (fully matches string)\n start = True\n\n# # Tokenize sentences to words\n# text = []\n# for sentence in corpus:\n# words = word_tokenize(sentence)\n# for word in words:\n# text.append(word)\n\n# Export to pickle file\npath = 'data/sentences.pickle'\nwith open(path, 'wb') as f:\n pickle.dump(corpus, f)\n f.close()\n\nprint(f'Tokens: {len(corpus)}')\n\n# from nltk.corpus import shakespeare\n\n# text = shakespeare.words('r_and_j.xml')\n# # Since there are forewords included, we need to remove them\n# text = text[50:]\n\n# print(f'Tokens: {len(text)}')\n","sub_path":"code/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"292272026","text":"import httplib2\nimport urllib\nimport json\n\ndef uploadFileToDB(sourceFile,destinationFile,accessToken):\n \n\thttp = httplib2.Http()\n\tpayload=open(sourceFile,'r')\n\t \n\tcontent = http.request('https://content.dropboxapi.com/2/files/upload', \n\t\t\t\t\t\t method=\"POST\", \n\t\t\t\t\t\t headers={\"Authorization\": \"Bearer %s\"%accessToken, \"Dropbox-API-Arg\": \"{\\\"path\\\": \\\"%s\\\",\\\"mode\\\": \\\"add\\\",\\\"autorename\\\": false,\\\"mute\\\": false,\\\"strict_conflict\\\": false}\"%destinationFile,\"Content-Type\": \"application/octet-stream\"},\n\t\t\t\t\t\t body=payload )[1]\n\n#uploadFileToDB('C:/Users/Chris/Desktop/someFile.txt','/Homework/math/Matrices.txt','')\n\n\ndef listFiles(dbFolder,accessToken):\n\thttp = httplib2.Http()\n\tpayload=\"{\\\"path\\\": \\\"%s\\\",\\\"recursive\\\": false,\\\"include_media_info\\\": false,\\\"include_deleted\\\": false,\\\"include_has_explicit_shared_members\\\": false,\\\"include_mounted_folders\\\": true,\\\"include_non_downloadable_files\\\": false}\"%dbFolder\n \t#request db folder list\n\tcontent = http.request('https://api.dropboxapi.com/2/files/list_folder', \n\t\t\t\t\t method=\"POST\", \n\t\t\t\t\t headers={\"Authorization\": \"Bearer %s\"%accessToken,\"Content-Type\": \"application/json\"},\n\t\t\t\t\t body=payload )[1]\n\n\t#convert json data to dict\n\tfolders = []\n\tcontentDict = json.loads(content)\n\tfor n in contentDict['entries']:\n\t\tfolders.append(n['name'])\n\n\treturn folders","sub_path":"moveFiles/httpDropbox.py","file_name":"httpDropbox.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"185409577","text":"#Read input file\n# parameters:\n# input file - .i input file\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\ndef read_input_file(input_file):\n inputs = {}\n with open(input_file) as f:\n for line in f:\n if '=' in line:\n inputs[line.split(\"=\")[0].strip().lower()] = line.split(\"=\")[1].strip()\n else: pass\n if len(inputs) != 11:\n print(\"Please recheck the input file since some parameter is missing...\")\n print(\"Exiting program...\")\n exit()\n else:\n print(\"Successfully read in input file\")\n for key,val in inputs.items():\n if is_number(val) == True:\n inputs[key] = float(val)\n return inputs\n","sub_path":"GeneralUse/Misc/read_input.py","file_name":"read_input.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"70392354","text":"def count_substring(s, ss):\n n=0\n #gave n=0 so we can add onto it later\n for i in range(0,len(s)):\n #declared a fucniton from 0 yo yhe length of the main string\n if s[i:i+len(ss)] == ss:\n #if the portion of main string from i to length of ss was equal to ss.\n s = s[:i:]+s[i+1::]\n #that portion was removed\n n += 1\n #and 1 was added to n and the code was rerun\n return(n)\n\n\n\n\n#calling the function\nif __name__ == '__main__':\n string = input().strip()\n sub_string = input().strip()\n \n count = count_substring(string, sub_string)\n print(count)","sub_path":"hackerrank pytho problems upto gold/3(non unique lapping over).py","file_name":"3(non unique lapping over).py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"243019799","text":"from src.utils.error_messages import ErrorMessages\nfrom src.utils.utils import Utils\nfrom src.model.dealer import Dealer\n\n\nclass Player(Dealer):\n def __init__(self, balance):\n \"\"\"\n Represents a single player at a blackjack table.\n :param balance:\n \"\"\"\n super().__init__()\n Utils.require_non_negative(balance)\n self.balance = balance\n self.bet = 0\n\n def make_bet(self, bet_amount):\n if bet_amount <= self.balance:\n self.balance -= bet_amount\n self.bet = bet_amount\n else:\n raise ValueError(ErrorMessages.InsufficientFundsError.error_message())\n\n\n","sub_path":"src/model/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"278175693","text":"#!/usr/bin/python3\n\nimport cgi\nimport os\nimport json\n\nclass Upload(object):\n def __init__(self, filename=None, file_object=None):\n if filename is None:\n raise Exception('No file name!')\n return None\n if file_object is None:\n raise Exception('No file!')\n return None\n\n self.filename = os.path.basename(filename)\n self.file_object = file_object\n self.application_type = \"Content-Type: application/json\\n\\n\"\n self.status = {\n 'ok' : \"Status: 200 OK\\n\\n\",\n 'error' : \"Status: 400 Bad Request\\n\\n\"\n }\n\n def __str__(self):\n return \"[Uploader ]\".format(self.filename.__str__())\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n return self\n\n def act(self):\n print(self.application_type)\n try:\n result = self.save_file()\n if result == True:\n print(self.status['ok'])\n else:\n print(self.status['error'])\n except Exception as ex:\n print(self.status['error'])\n output = json.dumps({\n 'error' : ex.__str__()\n })\n print(output)\n\n def save_file(self):\n if self.filename is None or self.file_object is None:\n raise Exception('Nothing to save to!')\n return False\n else:\n directory = '/tmp/{0}'.format(self.filename)\n open(directory, 'wb').write(fileitem.file.read())\n return True\n\nif __name__ == '__main__':\n form = cgi.FieldStorage()\n fileitem = form['filename']\n\n with Upload(fileitem.filename, fileitem.file) as upload:\n upload.act()\n","sub_path":"cgi-bin/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"176671689","text":"import sqlite3\n\nwith sqlite3.connect(\"cars.db\") as connection:\n\tc = connection.cursor()\n\n\tcars = [\n\t\t\t\t('Ford','Focus', 27),\n\t\t\t\t('Ford','Fiesta', 74),\n\t\t\t\t('Ford','Model T', 35),\n\t\t\t\t('Honda','Accord', 62),\n\t\t\t\t('Honda','Civic', 10)\n\t]\n\n\tc.executemany(\"INSERT INTO inventory(Make, Model, Quantity) values (?, ?, ?)\", cars)","sub_path":"sql/hw-sqlb.py","file_name":"hw-sqlb.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"99758533","text":"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.6.0\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# # HPSegNet\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom pytorch_memlab import profile\nfrom models.blocks import ResBlock, CBR, GlobalAvgPool2d, AttentionBlock\n\n\n# ## Define Network Architecture\n\nclass HPNet(nn.Module):\n def __init__(self):\n super().__init__()\n self.cbr1 = CBR(3, 64, kernel_size=7, stride=2, padding=3)\n self.atmap = AttentionBlock(64)\n self.cbr2 = CBR(64, 64, kernel_size=7, stride=2, padding=3)\n self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n self.block0 = self._build_resblock(256, channel_in=64)\n self.block1 = nn.ModuleList([self._build_resblock(256) for _ in range(2)])\n\n self.conv2 = nn.Conv2d(256, 512, kernel_size=1, stride=2)\n self.block2 = nn.ModuleList([self._build_resblock(512) for _ in range(4)])\n\n self.conv3 = nn.Conv2d(512, 1024, kernel_size=1, stride=2)\n self.block3 = nn.ModuleList([self._build_resblock(1024) for _ in range(6)])\n\n self.conv4 = nn.Conv2d(1024, 2048, kernel_size=1, stride=2)\n self.block4 = nn.ModuleList([self._build_resblock(2048) for _ in range(3)])\n\n self.avg_pool = GlobalAvgPool2d()\n self.fc1 = nn.Linear(2048, 1000)\n self.fc2 = nn.Linear(1000, 100)\n self.out = nn.Linear(100, 9)\n\n @profile\n def forward(self, x):\n h = self.cbr1(x)\n h = self.atmap(h)\n h = self.cbr2(h)\n h = self.pool(h)\n h = self.block0(h)\n for block in self.block1:\n h = block(h)\n h = self.conv2(h)\n for block in self.block2:\n h = block(h)\n h = self.conv3(h)\n for block in self.block3:\n h = block(h)\n h = self.conv4(h)\n for block in self.block4:\n h = block(h)\n h = self.avg_pool(h)\n h = self.fc1(h)\n h = F.relu(h)\n h = self.fc2(h)\n h = F.relu(h)\n h = self.out(h)\n y = torch.sigmoid(h)\n return y\n\n def _build_resblock(self, channel_out, channel_in=None):\n if channel_in is None:\n channel_in = channel_out\n return ResBlock(channel_in, channel_out)\n","sub_path":"dlkit/HPSegNet_004.py","file_name":"HPSegNet_004.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"272697394","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\nfrom torch.autograd import Function\nfrom model import predictor,feature_extractor\nfrom utils.LoadData import DATASET\nimport sys\nimport utils.grad_reverse as my_function\n\nimport argparse\nimport os\nimport random\nimport shutil\nimport time\nimport warnings\n\nclass ToRGB(object):\n\n\tdef __init__(self):\n\t\tpass\n\t\t\n\tdef __call__(self, sample):\n\n\t\tsample = sample.convert('RGB')\n\t\treturn sample\n\n\n###\t\tbasic setting \t ###\ncuda = torch.cuda.is_available()\ndevice = torch.device('cuda' if cuda else 'cpu')\ndownload = True\nBATCH_SIZE = 256\nEP = 30\n###\t\t-------------\t ###\n\nmean, std = np.array([0.5, 0.5, 0.5]), np.array([0.5, 0.5, 0.5])\n\nrgb_transform = transforms.Compose([\n\ttransforms.Resize((32, 32)),\n\ttransforms.ToTensor(),\n\ttransforms.Normalize(mean, std)\n\t])\n\ngray2rgb_transform = transforms.Compose([\n\tToRGB(),\n\ttransforms.Resize((32, 32)),\n\ttransforms.ToTensor(),\n\ttransforms.Normalize(mean, std)\n\t])\n\n\ndef train(encoder, cls_model_1, cls_model_2, optimizer_encoder, optimizer_clf_1, optimizer_clf_2, ep, train_loader, test_loader, src_name, tar_name):\n\tloss_fn_cls = nn.CrossEntropyLoss()\n\tloss_l1 = nn.L1Loss()\n\tac_list, loss_list = [], []\n\tmax_= 0\n\n\tend = time.time()\n\n\tfor i in range(ep):\n\n\t\tcls_model_1.train()\n\t\tcls_model_2.train()\n\t\tencoder.train()\n\n\t\tprint(i,'/', ep)\n\t\tfor index, (src_batch, tar_batch) in enumerate(zip(train_loader, test_loader)):\n\t\t\t\n\t\t\t# step 1\n\t\t\tx, y = src_batch\n\t\t\tx = x.to(device)\n\t\t\ty = y.to(device)\n\t\t\ty = y.view(-1)\n\n\t\t\tfeature = encoder(x)\n\t\t\tpred1 = cls_model_1(feature)\n\t\t\tpred2 = cls_model_2(feature)\n\n\t\t\tloss1 = loss_fn_cls(pred1, y) \n\t\t\tloss2 = loss_fn_cls(pred2, y)\n\t\t\tloss = loss1 + loss2\n\t\t\n\t\t\toptimizer_encoder.zero_grad()\n\t\t\toptimizer_clf_1.zero_grad()\n\t\t\toptimizer_clf_2.zero_grad()\n\t\t\tloss.backward()\n\t\t\toptimizer_encoder.step()\n\t\t\toptimizer_clf_1.step()\n\t\t\toptimizer_clf_2.step()\n\n\n\t\t\toptimizer_encoder.zero_grad()\n\t\t\toptimizer_clf_1.zero_grad()\n\t\t\toptimizer_clf_2.zero_grad()\n\t\t\t# step 2\n\t\t\ttar_x, _ = tar_batch\n\t\t\ttar_x = tar_x.to(device)\n\n\t\t\ts_feature = encoder(x)\n\t\t\tpred_s_1 = cls_model_1(s_feature)\n\t\t\tpred_s_2 = cls_model_2(s_feature)\n\n\t\t\tt_feature = encoder(tar_x)\n\t\t\tpred_tar_1 = cls_model_1(t_feature)\n\t\t\tpred_tar_2 = cls_model_2(t_feature)\n\n\t\t\tsrc_loss = loss_fn_cls(pred_s_1, y) + loss_fn_cls(pred_s_2, y)\n\t\t\t#discrepency_loss = torch.mean(torch.abs(F.softmax(pred_tar_1, dim=1) - F.softmax(pred_tar_2, dim=1)))\n\t\t\tdiscrepency_loss = loss_l1(F.softmax(pred_tar_1, dim=1), F.softmax(pred_tar_2, dim=1))\n\n\t\t\tloss = src_loss - discrepency_loss\n\n\t\t\toptimizer_clf_1.zero_grad()\n\t\t\toptimizer_clf_2.zero_grad()\n\n\t\t\tloss.backward()\n\n\t\t\toptimizer_clf_1.step()\n\t\t\toptimizer_clf_2.step()\n\n\t\t\toptimizer_encoder.zero_grad()\n\t\t\toptimizer_clf_1.zero_grad()\n\t\t\toptimizer_clf_2.zero_grad()\n\n\t\t\t# step 3\n\t\t\tfor i in range(3):\n\t\t\t\tt_feature = encoder(tar_x)\n\n\t\t\t\tpred_tar_1 = cls_model_1(t_feature)\n\t\t\t\tpred_tar_2 = cls_model_2(t_feature)\n\n\t\t\t\t#discrepency_loss = torch.mean(abs(F.softmax(pred_tar_1, dim=1) - F.softmax(pred_tar_2, dim=1)))\n\t\t\t\tdiscrepency_loss = loss_l1(F.softmax(pred_tar_1, dim=1), F.softmax(pred_tar_2, dim=1))\n\n\t\t\t\tdiscrepency_loss.backward()\n\t\t\t\toptimizer_encoder.step()\n\n\t\t\t\toptimizer_encoder.zero_grad()\n\t\t\t\toptimizer_clf_1.zero_grad()\n\t\t\t\toptimizer_clf_2.zero_grad()\n\n\n\n\t\t\tif index % 10 == 0:\n\t\t\t\tprint('[%d]/[%d]' % (index, min([len(train_loader), len(test_loader)])))\n\n\t\tif i % 10 == 0:\n\t\t\ttorch.save(cls_model_1.state_dict(), './model/epoch'+i+'_'+src_name+'2'+tar_name+'_1.pth')\n\t\t\ttorch.save(cls_model_2.state_dict(), './model/epoch'+i+'_'+src_name+'2'+tar_name+'_2.pth')\n\t\t\ttorch.save(encoder.state_dict(), './model/epoch'+i+'_'+src_name+'2'+tar_name+'.pth')\n\t\t\t\n\n\t\tcls_model_1.eval()\n\t\tcls_model_2.eval()\n\t\tencoder.eval()\n\n\t\tac_1 = 0\n\t\tac_2 = 0\n\t\tac_3 = 0\n\n\t\teval_loader = DATASET(tar_name, tar_name+'_train.csv', mode = False)\n\t\teval_loader = torch.utils.data.DataLoader(\n\t\t\tdataset = eval_loader,\n\t\t\tbatch_size = BATCH_SIZE,\n\t\t\tshuffle = True,\n\t\t)\n\n\n\t\ttotal_loss=0\n\t\twith torch.no_grad():\n\t\t\tfor batch in eval_loader:\n\t\t\t\t\n\t\t\t\tx, y = batch\n\t\t\t\tx = x.to(device)\n\t\t\t\ty = y.to(device)\n\t\t\t\ty = y.view(-1)\n\n\t\t\t\tfeature = encoder(x)\n\t\t\t\t\n\t\t\t\tpred_c1 = cls_model_1(feature)\n\t\t\t\tpred_c2 = cls_model_2(feature)\n\t\t\t\tpred_combine = pred_c1 + pred_c2\n\n\t\t\t\tac_1 += np.sum(np.argmax(pred_c1.cpu().detach().numpy(), axis=1) == y.cpu().detach().numpy())\n\t\t\t\tac_2 += np.sum(np.argmax(pred_c2.cpu().detach().numpy(), axis=1) == y.cpu().detach().numpy())\n\t\t\t\tac_3 += np.sum(np.argmax(pred_combine.cpu().detach().numpy(), axis=1) == y.cpu().detach().numpy())\n\n\t\t\t\ttotal_loss += loss.item()\n\t\t\n\t\tprint('Accuracy : [%.3f], Avg Loss : [%.4f]' % ((ac_1 / len(eval_loader) / BATCH_SIZE), (total_loss / len(eval_loader))) ) \n\t\tprint('Accuracy : [%.3f], Avg Loss : [%.4f]' % ((ac_2 / len(eval_loader) / BATCH_SIZE), (total_loss / len(eval_loader))) ) \n\t\tprint('Accuracy : [%.3f], Avg Loss : [%.4f]' % ((ac_3 / len(eval_loader) / BATCH_SIZE), (total_loss / len(eval_loader))) ) \n\t\t\n\t\tac = max([ac_1, ac_2, ac_3])\n\n\t\tac_list.append(ac/len(eval_loader)/BATCH_SIZE)\n\t\tloss_list.append(total_loss / len(eval_loader) / BATCH_SIZE)\n\t\tif (ac / len(eval_loader) / BATCH_SIZE) > max_:\n\t\t\tmax_ = (ac / len(eval_loader) / BATCH_SIZE)\n\t\t\ttorch.save(cls_model_1.state_dict(), './model/mcd_'+src_name+'2'+tar_name+'_1.pth')\n\t\t\ttorch.save(cls_model_2.state_dict(), './model/mcd_'+src_name+'2'+tar_name+'_2.pth')\n\t\t\ttorch.save(encoder.state_dict(), './model/mcd_'+src_name+'2'+tar_name+'.pth')\n\n\treturn ac_list, loss_list\n\ndef weights_init_uniform(m):\n\tclassname = m.__class__.__name__\n\t# for every Linear layer in a model..\n\tif classname.find('Linear') != -1:\n\t\t# apply a uniform distribution to the weights and a bias=0\n\t\tm.weight.data.uniform_(0.0, 1.0)\n\t\tm.bias.data.fill_(0)\n\n\n\ndef main(src, tar):\n\n\tG = feature_extractor().to(device)\n\n\tcls_c1 = predictor().to(device)\n\tcls_c2 = predictor().to(device)\n\n\tcls_c1.apply(weights_init_uniform)\n\tcls_c2.apply(weights_init_uniform)\n\n\t###\t\t dataloader \t ###\n\tif src == 'sketch':\n\t\tsrc_train_set = DATASET('sketch', 'sketch_train.csv' )\n\n\telif src == 'infograph':\n\t\tsrc_train_set = DATASET('infograpth', 'infograph_train.csv')\n\n\telif src == 'real':\n\t\tsrc_train_set = DATASET('real', 'real_train.csv')\n\n\telif src == 'quickdraw':\n\t\tsrc_train_set = DATASET('quickdraw', 'quickdraw_train.csv')\n\n\n\tif tar == 'sketch':\n\t\ttar_train_set = DATASET('sketch', 'sketch_train.csv' )\n\n\telif tar == 'infograph':\n\t\ttar_train_set = DATASET('infograpth', 'infograph_train.csv')\n\n\telif tar == 'real':\n\t\ttar_train_set = DATASET('real', 'real_train.csv')\n\n\telif tar == 'quickdraw':\n\t\ttar_train_set = DATASET('quickdraw', 'quickdraw_train.csv')\n\n\n\n\tsrc_train_loader = torch.utils.data.DataLoader(\n\t\tdataset = src_train_set,\n\t\tbatch_size = BATCH_SIZE,\n\t\tshuffle = True,\n\t\t)\n\n\ttar_train_loader = torch.utils.data.DataLoader(\n\t\tdataset = tar_train_set,\n\t\tbatch_size = BATCH_SIZE,\n\t\tshuffle = True,\n\t\t)\n\n\toptimizer_encoder = optim.Adam(G.parameters() , lr=2e-4, weight_decay=0.0005)\n\toptimizer_clf_1 = optim.Adam(cls_c1.parameters(), lr=2e-4, weight_decay=0.0005)\n\toptimizer_clf_2 = optim.Adam(cls_c2.parameters(), lr=2e-4, weight_decay=0.0005)\n\n\t# train\n\tac_list, loss_list = train(G, cls_c1, cls_c2, optimizer_encoder, optimizer_clf_1, optimizer_clf_2, EP, src_train_loader, tar_train_loader, src, tar)\n\tac_list = np.array(ac_list).flatten()\n\t\n\t# plot tsne\n\tloss_list = np.array(loss_list).flatten()\n\t#epoch = [i for i in range(EP)]\n\t#my_function.tsne_plot(G, src_train_loader, tar_train_loader, src, tar, BATCH_SIZE, 'mcd', mode=False)\n\n\t### plot learning curve ###\n\tplt.figure()\n\tplt.plot(epoch, ac_list)\n\tplt.xlabel('EPOCH')\n\tplt.ylabel('Accuracy')\n\tplt.title('domian_adapt : ' + src + ' to ' + tar)\n\tplt.savefig('./learning_curve/domian_adapt_' + src + '_to_' + tar + '_accuracy.jpg')\n\n\tplt.figure()\n\tplt.plot(epoch, loss_list)\n\tplt.xlabel('EPOCH')\n\tplt.ylabel('Loss')\n\tplt.title('domian_adapt : ' + src + ' to ' + tar)\n\tplt.savefig('./learning_curve/domian_adapt_' + src + '_to_' + tar + '_loss.jpg')\n\n\nif __name__ == '__main__':\n\n\tsource, target = sys.argv[1:]\n\tmain(source, target)\n\n\n","sub_path":"mcd.py","file_name":"mcd.py","file_ext":"py","file_size_in_byte":8374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"473391976","text":"from typing import TYPE_CHECKING, Any\nif TYPE_CHECKING:\n\tfrom Platforms.Web.index import WebIndex\n\nfrom aiohttp.web import Request\nfrom Utils.Classes.htmlformatter import HTMLFormatter\nfrom Utils.Classes.webuserinfo import WebUserInfo\nfrom Utils.Classes.discordwebuserinfo import DiscordWebUserInfo\nfrom Utils.Classes.storeclasses import GlobalStorage\n\n# templating and stuff\ndef getNavbar(active:str=\"\") -> HTMLFormatter:\n\t\"\"\"\n\t\tget the upper nav bar html,\n\t\twith all applied styles based on current location\n\t\"\"\"\n\n\tNavbar:HTMLFormatter = HTMLFormatter(\"Platforms/Web/Content/Html/Navbar/default.html\")\n\n\tNavbar.replace(\n\t\taccount_modal=getAccountModal()\n\t)\n\n\tNavbar.setRegex(r\"\\{selected_(.+?)\\}\")\n\tNavbar.replace(replace_empty=True, **{active:\"active\"})\n\n\treturn Navbar\n\ndef getAccountModal() -> HTMLFormatter:\n\t\"\"\"\n\t\tget the global login form with all applied formated links etc...\n\t\"\"\"\n\ttry:\n\t\tdiscord_login_link:str = GlobalStorage.get(\"Phaazebot\").Vars.DISCORD_LOGIN_LINK\n\texcept:\n\t\tdiscord_login_link:str = \"/discord?error\"\n\n\tAccountModal:HTMLFormatter = HTMLFormatter(\"Platforms/Web/Content/Html/Modal/account.html\")\n\tAccountModal.replace(\n\t\treplace_empty=True,\n\t\tdiscord_login_link=discord_login_link\n\t)\n\treturn AccountModal\n\n# web translator\nasync def getWebUserInfo(cls:\"WebIndex\", WebRequest:Request, **kwargs:Any) -> WebUserInfo:\n\t\"\"\"\n\t\tTryes to get a WebUser, takes get, post, and cookie in process\n\t\tkwargs are given to WebUserInfo\n\n\t\tWebUserInfo kwargs:\n\t\t\tforce_method\n\t\t\tphaaze_session\n\t\t\tphaaze_token\n\t\t\tphaaze_username\n\t\t\tphaaze_password\n\t\"\"\"\n\n\tif hasattr(WebRequest, \"WebUser\"):\n\t\tcls.Web.BASE.Logger.debug(f\"(Web) Used stored infos: {str(WebRequest.WebUser)}\", require=\"web:debug\")\n\t\treturn WebRequest.WebUser\n\n\tWebUser:WebUserInfo = WebUserInfo(cls.Web.BASE, WebRequest, **kwargs)\n\tawait WebUser.auth()\n\tWebRequest.WebUser = WebUser\n\n\treturn WebRequest.WebUser\n\nasync def getDiscordUserInfo(cls:\"WebIndex\", WebRequest:Request, **kwargs:Any) -> DiscordWebUserInfo:\n\t\"\"\"\n\t\tTryes to get a DiscordUser, takes get, post, and cookie in process\n\t\tkwargs are given to DiscordWebUserInfo\n\n\t\tDiscordWebUserInfo kwargs:\n\t\t\tforce_method\n\t\t\tphaaze_discord_session\n\t\"\"\"\n\n\tif hasattr(WebRequest, \"DiscordUser\"):\n\t\tcls.Web.BASE.Logger.debug(f\"(Web) Used stored discord infos: {str(WebRequest.DiscordUser)}\", require=\"web:debug\")\n\t\treturn WebRequest.DiscordUser\n\n\tDiscordUser:DiscordWebUserInfo = DiscordWebUserInfo(cls.Web.BASE, WebRequest, **kwargs)\n\tawait DiscordUser.auth()\n\tWebRequest.DiscordUser = DiscordUser\n\n\treturn WebRequest.DiscordUser\n\n# db managment\nasync def getWebUsers(cls:\"WebIndex\", where:str, values:tuple=None, limit:int=None, offset:int=None) -> list:\n\t\"\"\"\n\t\tSearch user via custom 'where' statement\n\t\t'where' can include LIMIT and OFFSET,\n\t\tbut not GROUP BY or ORDER\n\t\"\"\"\n\tstatement:str = f\"\"\"\n\t\tSELECT\n\t\t\t`user`.*,\n\t\t\tGROUP_CONCAT(`role`.`name` SEPARATOR ';;;') AS `roles`\n\t\tFROM `user`\n\t\tLEFT JOIN `user_has_role`\n\t\t\tON `user_has_role`.`user_id` = `user`.`id`\n\t\tLEFT JOIN `role`\n\t\t\tON `role`.`id` = `user_has_role`.`role_id`\n\t\tWHERE {where}\n\t\tGROUP BY `user`.`id`\"\"\"\n\n\tif limit:\n\t\tstatement += f\" LIMIT {limit}\"\n\n\tif offset:\n\t\tstatement += f\" OFFSET {offset}\"\n\n\tres:list = cls.Web.BASE.PhaazeDB.selectQuery(statement, values)\n\n\treturn_list:list = []\n\tfor user in res:\n\t\tWebUser:WebUserInfo = WebUserInfo(cls.Web.BASE, None)\n\t\tawait WebUser.finishUser(user)\n\t\treturn_list.append(WebUser)\n\n\treturn return_list\n\nasync def getWebUserAmount(cls:\"WebIndex\", where:str=\"1=1\", values:tuple=()) -> int:\n\t\"\"\" simply gives a number of all matched user \"\"\"\n\n\tres:list = cls.Web.BASE.PhaazeDB.selectQuery(f\"SELECT COUNT(*) AS `I` FROM `user` WHERE {where}\", values)\n\n\treturn res[0]['I']\n","sub_path":"Platforms/Web/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"429339791","text":"\"\"\"\ndescription: A parser to parse the default loop report obtained from loop iphone application. Converts the readme\nsections and lines into high level dictionaries and list objects.\n\nauthor: Russell Wilson\ndependencies:\n* <>\nlicense: BSD-2-Clause\n\"\"\"\n\n\nclass Sections:\n LOOP_VERSION = \"loop_version\"\n DEVICE_DATA_MANAGER = \"device_data_manager\"\n RILEY_LINK_DEVICE = \"riley_link_device\"\n CARB_STORE = \"carb_store\"\n DOSE_STORE = \"dose_store\"\n MINIMED_PUMP_MANAGER = \"minimed_pump_manager\"\n OMNIPOD_PUMP_MAANGER = \"omnipod_pump_manager\"\n WATCH_DATA_MANAGER = \"watch_data_manager\"\n LOOP_DATA_MANAGER = \"loop_data_manager\"\n\n\ndef _split_key_value(line, separator):\n end_loc = line.find(separator)\n key = line[0:end_loc]\n value = line[end_loc + 1 : len(line)]\n return key, value\n\n\ndef parse_loop_report(dataPathAndName):\n current_section = \"\"\n all_sections = {}\n new_line = False\n\n with open(dataPathAndName, \"r\") as reader:\n for line in reader:\n if line.startswith(\"Generated:\"):\n key, value = _split_key_value(line, \":\")\n generated = {}\n generated[key] = value\n all_sections[\"generated\"] = generated\n new_line = False\n\n elif line.startswith(\"Loop\"):\n key, value = _split_key_value(line, \":\")\n loop = {}\n loop[\"loop_version\"] = key\n all_sections[\"loop_version\"] = loop\n new_line = False\n\n elif line.startswith(\"## DeviceDataManager\"):\n device_data_manager = {}\n current_section = \"device_data_manager\"\n all_sections[\"device_data_manager\"] = device_data_manager\n new_line = False\n\n elif line.startswith(\"## G5CGMManager\"):\n g5_cgm_manager = {}\n current_section = \"g5_cgm_manager\"\n all_sections[\"g5_cgm_manager\"] = g5_cgm_manager\n new_line = False\n\n elif line.startswith(\"## DexCGMManager\"):\n dex_cgm_manager = {}\n current_section = \"dex_cgm_manager\"\n all_sections[\"dex_cgm_manager\"] = dex_cgm_manager\n new_line = False\n\n elif line.startswith(\"## MinimedPumpManager\"):\n minimed_pump_manager = {}\n current_section = \"minimed_pump_manager\"\n all_sections[\"minimed_pump_manager\"] = minimed_pump_manager\n new_line = False\n\n elif line.startswith(\"## RileyLinkPumpManager\"):\n riley_link_pump_manager = {}\n current_section = \"riley_link_pump_manager\"\n all_sections[\"riley_link_pump_manager\"] = riley_link_pump_manager\n new_line = False\n\n elif line.startswith(\"## RileyLinkDeviceManager\"):\n riley_link_device_manager = {}\n current_section = \"riley_link_device_manager\"\n all_sections[\"riley_link_device_manager\"] = riley_link_device_manager\n new_line = False\n\n elif line.startswith(\"## RileyLinkDevice\"):\n riley_link_device = {}\n current_section = \"riley_link_device\"\n all_sections[\"riley_link_device\"] = riley_link_device\n new_line = False\n\n elif line.startswith(\"## StatusExtensionDataManager\"):\n status_extension_data_manager = {}\n current_section = \"status_extension_data_manager\"\n all_sections[\n \"status_extension_data_manager\"\n ] = status_extension_data_manager\n new_line = False\n\n elif line.startswith(\"## LoopDataManager\"):\n loop_data_manager = {}\n current_section = \"loop_data_manager\"\n all_sections[\"loop_data_manager\"] = loop_data_manager\n new_line = False\n\n elif line.startswith(\"insulinCounteractionEffects:\"):\n insulin_counteraction_effects = []\n current_section = \"insulin_counteraction_effects\"\n all_sections[\n \"insulin_counteraction_effects\"\n ] = insulin_counteraction_effects\n new_line = False\n\n elif line.startswith(\"predictedGlucose:\"):\n predicted_glucose = []\n current_section = \"predicted_glucose\"\n all_sections[\"predicted_glucose\"] = predicted_glucose\n new_line = False\n\n elif line.startswith(\"retrospectivePredictedGlucose\"):\n retrospective_predicted_glucose = {}\n current_section = \"retrospective_predicted_glucose\"\n all_sections[\n \"retrospective_predicted_glucose\"\n ] = retrospective_predicted_glucose\n new_line = False\n\n elif line.startswith(\"cacheStore: ## PersistenceController\"):\n persistence_controller = {}\n current_section = \"persistence_controller\"\n all_sections[\"persistence_controller\"] = persistence_controller\n new_line = False\n\n elif line.startswith(\"## GlucoseStore\"):\n glucose_store = {}\n current_section = \"glucose_store\"\n all_sections[\"glucose_store\"] = glucose_store\n new_line = False\n\n elif line.startswith(\"### cachedGlucoseSamples\"):\n cached_glucose_samples = {}\n current_section = \"cached_glucose_samples\"\n all_sections[\"cached_glucose_samples\"] = cached_glucose_samples\n new_line = False\n\n elif line.startswith(\"## CarbStore\"):\n carb_store = {}\n current_section = \"carb_store\"\n all_sections[\"carb_store\"] = carb_store\n new_line = False\n\n elif line.startswith(\"cachedCarbEntries:\"):\n cached_carb_entries = {}\n current_section = \"cached_carb_entries\"\n all_sections[\"cached_carb_entries\"] = cached_carb_entries\n new_line = False\n\n elif line.startswith(\"deletedCarbEntries:\"):\n deleted_carb_entries = {}\n current_section = \"deleted_carb_entries\"\n all_sections[\"deleted_carb_entries\"] = deleted_carb_entries\n new_line = False\n\n elif line.startswith(\"## DoseStore\"):\n dose_store = {}\n current_section = \"dose_store\"\n all_sections[\"dose_store\"] = dose_store\n new_line = False\n\n elif line.startswith(\"### getReservoirValues\"):\n get_reservoir_values = []\n current_section = \"get_reservoir_values\"\n all_sections[\"get_reservoir_values\"] = get_reservoir_values\n new_line = False\n\n elif line.startswith(\"### getPumpEventValues\"):\n get_pump_event_values = []\n current_section = \"get_pump_event_values\"\n all_sections[\"get_pump_event_values\"] = get_pump_event_values\n new_line = False\n\n elif line.startswith(\n \"### getNormalizedPumpEventDoseEntriesOverlaidWithBasalEntries\"\n ):\n normalized_pump_event_dose = {}\n current_section = \"normalized_pump_event_dose\"\n all_sections[\"normalized_pump_event_dose\"] = normalized_pump_event_dose\n new_line = False\n\n elif line.startswith(\"### InsulinDeliveryStore\"):\n insulin_delivery_store = {}\n current_section = \"insulin_delivery_store\"\n all_sections[\"insulin_delivery_store\"] = insulin_delivery_store\n new_line = False\n\n elif line.startswith(\"## WatchDataManager\"):\n watch_data_manager = {}\n current_section = \"watch_data_manager\"\n all_sections[\"watch_data_manager\"] = watch_data_manager\n new_line = False\n\n elif line.startswith(\"## OmnipodPumpManager\"):\n omnipod_pump_manager = {}\n current_section = \"omnipod_pump_manager\"\n all_sections[\"omnipod_pump_manager\"] = omnipod_pump_manager\n new_line = False\n\n elif line.startswith(\"\\n\"):\n new_line = True\n\n elif (\n line.startswith(\"#\") or line.startswith(\"##\") or line.startswith(\"###\")\n ):\n print(f\"UNHANDLED SECTION: {line}\")\n new_line = False\n\n else:\n if (\n current_section == \"insulin_counteraction_effects\"\n or current_section == \"get_reservoir_values\"\n or current_section == \"predicted_glucose\"\n or current_section == \"get_pump_event_values\"\n ):\n new_line = False\n i_list = all_sections[current_section]\n if line.startswith(\"*\"):\n line = line[1:]\n if line.startswith(\" \"):\n line = line[1:]\n if line.endswith(\"\\n\"):\n line = line[:-1]\n\n i_list.append(line)\n\n elif current_section:\n new_line = False\n dict = all_sections[current_section]\n key, value = _split_key_value(line, \":\")\n if key or value != \"\\n\":\n if key.startswith(\"*\"):\n key = key[1:]\n if key.startswith(\" \"):\n key = key[1:]\n if value.endswith(\"\\n\"):\n value.replace(\"\\n\", \"\")\n dict[key] = value.replace(\"\\n\", \"\")\n\n return all_sections\n\n\ndef list_sections_in_loop_report(file_path):\n section_list = []\n existing_sections = []\n new_line = None\n with open(file_path, \"r\") as reader:\n for line in reader:\n if line == \"\\n\":\n new_line = \"newline\"\n elif (\n line.startswith(\"#\") or line.startswith(\"##\") or line.startswith(\"###\")\n ):\n if new_line == \"newline\":\n if line not in existing_sections:\n section_list.append(line)\n existing_sections.append(line)\n else:\n new_line = None\n\n return section_list\n","sub_path":"projects/parsers/loop_report_parser.py","file_name":"loop_report_parser.py","file_ext":"py","file_size_in_byte":10642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"334983014","text":"import os\nfrom subprocess import call\nfrom os import path\nimport sys\n\n# Executables\nexecutable = 'python'\n\n# Paths\nrootdir = '../..'\nscriptname = 'run.py'\ncwd = os.path.dirname(os.path.abspath(__file__))\noutdir = os.path.join(cwd, 'out/conopt_conv3')\n\nargs = [\n# Architecture\n'--image-size', '375',\n'--output-size', '32',\n'--c-dim', '3',\n'--z-dim', '256',\n'--gf-dim', '64',\n'--df-dim', '64',\n'--g-architecture', 'dcgan3_nobn',\n'--d-architecture', 'dcgan3_nobn',\n'--gan-type','standard',\n# Training\n'--optimizer', 'conopt',\n'--nsteps', '150000',\n'--ntest', '1000',\n'--learning-rate', '1e-4',\n'--reg-param', '1e-1', \n'--batch-size', '64',\n'--log-dir', os.path.join(outdir, 'tf_logs'),\n'--sample-dir', os.path.join(outdir, 'samples'),\n'--is-inception-scores',\n'--inception-dir', './inception',\n# Data set\n'--dataset', 'cifar-10',\n'--data-dir', './data',\n'--split', 'train'\n]\n\n# Run\nmy_env = os.environ.copy()\ncall([executable, scriptname] + args, env=my_env, cwd=rootdir)\n","sub_path":"experiments/inception_score/conopt_conv3.py","file_name":"conopt_conv3.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"246935888","text":"# -*- coding: utf-8 -*-\n\"\"\"\nA module to show orbital parameters for a given satellite.\n\"\"\"\n\nimport pyorbital.orbital as orbitl\nimport easygui as eg\nfrom datetime import datetime\nfrom utilities import get_sat, settings\n\nif settings['update_tles_on_run']:\n from utilities import update_tle_filename\n execfile(update_tle_filename)\n\nsatellite = get_sat()\n\no = orbitl.Orbital(satellite.platform,\n line1=satellite.line1,\n line2=satellite.line2)\n\nel = o.orbit_elements\nsgdp4 = o._sgdp4\n\nkep = sgdp4.propagate(datetime.now())\ncart = orbitl.kep2xyz(kep)\n\ns = \"{}\\nPlatform: {}\\n\\nKep:\\n\".format(datetime.now(), satellite.platform)\nfor key in kep:\n s += \"{0:7s}: {1:15s}\\n\".format(key, str(kep[key]))\ns += '\\nCartesian:\\n'\nfor i in cart:\n s += str(i) + '\\n'\ns += '\\nRaw:\\n'\nfor key in el.__dict__:\n s += \"{0:28s}: {1:30s}\\n\".format(key, str(el.__dict__[key]))\n\n\neg.codebox(title='Satellite',\n msg='',\n text=s)\n\ndel cart, datetime, eg, el, i, kep, key, o, orbitl, s, satellite, settings\ndel sgdp4, get_sat","sub_path":"Source/Orbit helper.py","file_name":"Orbit helper.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"525469685","text":"import numpy as np\n\nif __name__ == \"__main__\":\n # Let's be explicit instead of implicit:\n i = 0\n nreads = 5000\n read_length = 200\n mu = 0.0005\n nreps = 3\n for nrep in range(nreps):\n for pi in np.linspace(0.7,1.0,num=50,endpoint=False):\n for gamma in [0.01, 0.02, 0.03]:\n string = \"python3 experiment/simulate_dataset.py --n_reads {nreads} --refs res/H3N2_HA_nfu.m.fa --dmat res/H3N2_HA_nfu.dmat.npy --min_d 1 --max_d 1000 --pi {pi} --read_length {read_length} --gamma {gamma} --mu {mu} --out_prefix tmp/runA2_%d\".format(pi=pi,gamma=gamma,nreads=nreads,read_length=read_length,mu=mu) % i\n i += 1\n print(string)\n","sub_path":"codetect/experiment/generate_data_simulation_commands_A2.py","file_name":"generate_data_simulation_commands_A2.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90098665","text":"from pprint import pprint\nfrom matplotlib import pyplot as plt\nfrom housing.utils import get_housing_data, print_full\nfrom sklearn.model_selection import StratifiedShuffleSplit\nimport numpy as np\nimport pandas as pd\n\n\ndef main():\n housing_data = get_housing_data()\n head = housing_data.head()\n info = housing_data.info()\n\n pprint(info) # prints the information with regards to the data frame\n pprint(head) # prints the top 5 rows with regards to the data frame\n pprint(housing_data[\n \"ocean_proximity\"].value_counts()) # prints the count of all possible values `ocean_proximity` contains\n\n print_full(housing_data.describe()) # prints the statistical summary of the housing_data\n housing_data.hist(bins=50, figsize=(20, 15))\n\n # split the dataset between training sets and test sets.\n # use stratified approach when dealing with small sets of data since we could bias the sampling\n # ( we want the sets of data to represent the overall population)\n training_set, test_set = stratified_split(housing_data)\n training_set.hist(bins=50, figsize=(20, 15))\n test_set.hist(bins=50, figsize=(20, 15))\n plt.show()\n\n # visualizes data to try to see patterns\n visualize_housing_data(housing_data)\n plt.show()\n\n\ndef visualize_housing_data(data):\n cp = data.copy()\n cp.plot(kind=\"scatter\", x=\"longitude\", y=\"latitude\", alpha=0.4, s=cp[\"population\"] / 100, label=\"population\",\n c=\"median_house_value\", cmap=plt.get_cmap(\"jet\"), colorbar=True, figsize=(10, 7))\n\n\ndef stratified_split(data, test_size=0.2, seed=42):\n data[\"income_cat\"] = pd.cut(data[\"median_income\"], bins=[0., 1.5, 3.0, 4.5, 6., np.inf], labels=[1, 2, 3, 4, 5])\n\n split = StratifiedShuffleSplit(n_splits=1, test_size=test_size, random_state=seed)\n for train_index, test_index in split.split(data, data[\"income_cat\"]):\n strat_train_set = data.loc[train_index]\n strat_test_set = data.loc[test_index]\n for set_ in (strat_train_set, strat_test_set):\n set_.drop(\"income_cat\", axis=1, inplace=True)\n return strat_train_set, strat_test_set\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"housing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259728358","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('comdir', '0006_auto_20150806_1152'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Service',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('service', models.CharField(unique=True, max_length=200)),\n ],\n ),\n migrations.AddField(\n model_name='company',\n name='services',\n field=models.ManyToManyField(to='comdir.Service'),\n ),\n ]\n","sub_path":"comdir/migrations/0007_auto_20150806_1515.py","file_name":"0007_auto_20150806_1515.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"153469032","text":"def gener():\r\n yield('1')\r\n yield('2')\r\n pop = yield('3')\r\n print(pop)\r\n yield('end')\r\n\r\n\r\ndef main():\r\n g = gener()\r\n n = 0\r\n try:\r\n while True:\r\n if n <= 2 or n > 3:\r\n print(g.send(None))\r\n n += 1\r\n else:\r\n print(g.send('Vishlo blyat!!'))\r\n n += 1\r\n except StopIteration:\r\n print(\"\"\"Generator is over, good luck\r\n and see you soon\"\"\")\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"380590208","text":"# To set the http_proxy environment variable\nimport os\n# For making the site requests and overall request management\nfrom stackoversight.scraping.stack_overflow import StackOverflow\n# For child link queue\nfrom queue import Queue\n# For threading the scraping process\nimport threading\n# For serialization\nimport json\n# For thread management\nfrom stackoversight.scraping.thread_executioner import ThreadExecutioner\n\n\nclass StackOversight(object):\n def __init__(self, client_keys: list, proxy=None):\n if proxy:\n # address of the proxy server\n self.proxy = 'http://localhost:5050'\n\n # set the environment variable http_proxy and such\n os.environ['http_proxy'] = proxy\n os.environ['HTTP_PROXY'] = proxy\n os.environ['https_proxy'] = proxy\n os.environ['HTTPS_PROXY'] = proxy\n\n self.site = StackOverflow(client_keys)\n\n self.thread_handles = []\n self.file_handles = []\n\n self.code_lock = threading.Lock()\n self.text_lock = threading.Lock()\n\n def start(self, parent_link_queue: Queue, code_file_name='code.txt', text_file_name='text.txt'):\n code_io_handle = open(code_file_name, 'w')\n text_io_handle = open(text_file_name, 'w')\n\n self.file_handles.extend((code_io_handle, text_io_handle))\n\n child_link_queue = Queue()\n kill = threading.Event()\n\n parent_link_thread = threading.Thread(target=ThreadExecutioner.execute,\n args=(parent_link_queue, self.site, child_link_queue, kill))\n parent_link_thread.setName(\"StackExchange API Manager\")\n\n child_link_thread = threading.Thread(target=ThreadExecutioner.execute,\n args=(child_link_queue, self.site, code_io_handle, text_io_handle, kill))\n child_link_thread.setName(\"StackOverflow Scraping Manager\")\n\n self.thread_handles.extend((parent_link_thread, child_link_thread))\n\n for handle in self.thread_handles:\n handle.start()\n\n kill.wait()\n\n for handle in self.thread_handles:\n was_alive = ThreadExecutioner.murder(handle)\n print(f'{handle.getName()} is {[\"not \"] if [not was_alive] else [\"\"]} healthy.')\n\n for file_handle in self.file_handles:\n file_handle.close()\n\n def scrape_parent_links(self, input_queue: Queue, site: StackOverflow, output_queue: Queue,\n failure: threading.Event):\n ThreadExecutioner.execute(self.scrape_parent_link, input_queue, site, output_queue, failure)\n\n def scrape_child_links(self, input_queue: Queue, site: StackOverflow, code_io_handle, text_io_handle,\n failure: threading.Event):\n ThreadExecutioner.execute(self.scrape_child_link, input_queue, site, code_io_handle,\n text_io_handle, failure)\n\n def scrape_parent_link(self, link: str, used_parents: Queue, site: StackOverflow, output_queue: Queue,\n failure: threading.Event):\n try:\n has_more = True\n while has_more:\n try:\n # TODO: handle None response\n # TODO: make sure actually incrementing page\n response = site.get_child_links(link, pause=True)\n except SystemExit:\n raise\n except:\n # TODO: logging\n failure.set()\n raise\n\n has_more = response[1]\n response = response[0]\n list(map(output_queue.put, response))\n\n if not has_more:\n used_parents.put(threading.currentThread())\n break\n except SystemExit:\n print()\n # TODO: logging\n\n def scrape_child_link(self, link: str, used_children: Queue, site: StackOverflow, code_io_handle, text_io_handle,\n failure: threading.Event):\n try:\n # TODO: thread this point on in this method for each link\n # TODO: handle None response\n try:\n response = site.process_request(link, pause=True)[0]\n except SystemExit:\n raise\n except:\n # TODO: logging\n failure.set()\n raise\n\n for code in site.get_code(response):\n snippet = {'snippet': code}\n\n with self.code_lock:\n json.dump(snippet, code_io_handle)\n # code_io_handle.write(code)\n\n for text in site.get_text(response):\n snippet = {'snippet': text}\n\n with self.text_lock:\n json.dump(snippet, text_io_handle)\n # text_io_handle.write(text)\n\n used_children.put(threading.current_thread())\n\n except SystemExit:\n print()\n # TODO: logging\n\n\n# for debugging only\nkeys = ['RGaU7lYPN8L5KbnIfkxmGQ((', '1yfsxJa1AC*GlxN6RSemCQ((']\n\npython_posts = StackOverflow.create_parent_link(sort=StackOverflow.Sorts.votes.value,\n order=StackOverflow.Orders.descending.value,\n tag=StackOverflow.Tags.python.value, page_size=100)\n\nlink_queue = Queue()\nlink_queue.put(python_posts)\n\nscraper = StackOversight(keys)\nscraper.start(link_queue)\n","sub_path":"stackoversight/scraping/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":5499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"238147797","text":"\nimport gramaticaAscendente3D as g\n\n#import gramaticaAscendente as gr\nimport re\nimport reportes as h\nimport os\nimport sys\nimport platform\n\n\n\ndef ejecucionATraduccion(input):\n print(\"--------------------------------Archivo Ejecucion---------------------------------------\")\n prueba =g.parse(input)\n print(prueba)\n h.textosalida+=\"--------------------INICIO DE LA TRADUCCION--------------------\\n\"\n h.textosalida+=prueba\n h.textosalida+=\"--------------------FIN DE LA TRADUCCION--------------------\\n\"\n escribir3D(prueba)\n return h.textosalida\n\n\ndef escribir3D(var3):\n try:\n state_script_dir = os.getcwd()\n report_dir = state_script_dir + \"\\\\codigo3D.py\"\n with open(report_dir, \"w\") as f:\n f.write(var3)\n f.closed\n print(\"Si se escribio el archivo 3D :D!\")\n except:\n print(\"no se genero el reporte :(\")\n box_tilte = \"Report Error\"\n box_msg = \"El archivo del codigo no existe\"\n messagebox.showinfo(box_tilte, box_msg)\n\n ","sub_path":"parser/fase2/team06/traductor.py","file_name":"traductor.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"359376926","text":"import time as t\r\nimport matplotlib.pyplot as plt\r\n\r\ntempos = []\r\nvezes = []\r\nlegenda = []\r\nvez = 1\r\nrepete = 3\r\n\r\nprint ('Este programa marcará o tempo gasto para digitar a palavra PROGRAMÇÃO. Você terá que digita-la '+str(repete)+' vezes.')\r\ninput ('Aperte enter para começar.')\r\n\r\nwhile vez <= repete:\r\n inicio = t.perf_counter ()\r\n input ('Digite a palavra: ')\r\n fim = t.perf_counter ()\r\n tempo = round(fim - inicio,2)\r\n tempos.append (tempo)\r\n vezes.append (vez)\r\n vezstr = str(vez)+'a vez'\r\n legenda.append(vezstr)\r\n vez += 1\r\n\r\n#legenda = ['1a vez','2a vez','3a vez','4a vez','5a vez']\r\nplt.xticks(vezes,legenda)\r\nplt.plot (vezes,tempos)\r\ngraf = plt.show()\r\nprint (graf)\r\nprint ('Fim do programa.')","sub_path":"Curso do Ivan Gomes/Básico/exercicio time-matplotlib.py","file_name":"exercicio time-matplotlib.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"471040865","text":"import pandas as pd\nimport csv\nfrom pathlib import Path\n\nprint(f\"Current Working Directory:{Path.cwd()}\")\n\ncsvpath = Path('/Users/jiwookkim/Desktop/python-homework/PyBank/budget_data.csv')\n\n#Instantiaing variables\nmonths = 0\nnpl = 0\nmonthly_change = 0\nnext_value = 0\ndates = []\nprofits = []\n\n#instantiate for best and worst performance\nbest_increase = 0\nworst_decrease= 0\n\n#open the csv file as an object\nwith open(csvpath, 'r') as csvfile:\n csvreader = csv.reader(csvfile)\n \n #read the header\n header = next(csvreader)\n \n #get previous values for calculating the changes\n previous_value = next(csvreader)\n npl += int(previous_value[1])\n months += 1\n \n #Read each row of data after the header\n for row in csvreader:\n \n #into empty dates list, append date from csv Date column\n dates.append(row[0])\n months += 1\n \n #month to month change average\n #calculating change\n monthly_change = int(row[1]) - int(previous_value[1])\n profits.append(monthly_change)\n average_monthly_change = round(sum(profits) / months, 2)\n \n #update previous_value\n previous_value = row\n\n \n #calculating total profit/losses\n npl = npl + int(row[1])\n \n #monthly_change comparison\n if monthly_change >= best_increase:\n best_increase = monthly_change\n best_increase_month = row[0]\n elif monthly_change <= worst_decrease:\n worst_decrease = monthly_change\n worst_decrease_month = row[0]\n \n \n\n\n \n \nprint(f\"Financial Analysis\")\nprint(f\"-----------------------------------\")\nprint(f\"Total Months: {months}\")\nprint(f\"Total : {npl}\")\nprint(f\"Average Change : ${average_monthly_change}\")\nprint(f\"Greatest Increase in Profits: {best_increase_month} (${best_increase})\")\nprint(f\"Worst Decrease in Profits {worst_decrease_month} (${worst_decrease})\")\n\n\n#Set the path for the output.csv\noutput_path = Path('/Users/jiwookkim/Desktop/python-homework/PyBank/output.txt')\n\n#open the output path as a file \nwith open(output_path, 'w', newline='') as file:\n file.write(f\"Financial Analysis:\\n\")\n file.write(f\"-----------------------------------\\n\")\n file.write(f\"Total Months: {months}\\n\")\n file.write(f\"Total : {npl} USD\\n\")\n file.write(f\"Average Change : ${average_monthly_change} USD\\n\")\n file.write(f\"Greatest Increase in Profits: {best_increase_month} (${best_increase}) USD\\n\")\n file.write(f\"Worst Decrease in Profits {worst_decrease_month} (${worst_decrease}) USD\")\n \n file.close()\n\n","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"264742478","text":"import random\nimport argparse\nimport numpy as np\n\nfrom detection_dataloader import parse_voc_annotation\nimport json\n\ndef IOU(ann, centroids):\n w, h = ann\n similarities = []\n\n for centroid in centroids:\n c_w, c_h = centroid\n\n if c_w >= w and c_h >= h:\n similarity = w*h/(c_w*c_h)\n elif c_w >= w and c_h <= h:\n similarity = w*c_h/(w*h + (c_w-w)*c_h)\n elif c_w <= w and c_h >= h:\n similarity = c_w*h/(w*h + c_w*(c_h-h))\n else: #means both w,h are bigger than c_w and c_h respectively\n similarity = (c_w*c_h)/(w*h)\n similarities.append(similarity) # will become (k,) shape\n\n return np.array(similarities)\n\ndef avg_IOU(anns, centroids):\n n,d = anns.shape\n sum = 0.\n\n for i in range(anns.shape[0]):\n sum+= max(IOU(anns[i], centroids))\n\n return sum/n\n\ndef print_anchors(centroids):\n out_string = ''\n\n anchors = centroids.copy()\n\n widths = anchors[:, 0]\n sorted_indices = np.argsort(widths)\n\n r = \"anchors: [\"\n for i in sorted_indices:\n out_string += str(int(anchors[i,0]*416)) + ',' + str(int(anchors[i,1]*416)) + ', '\n \n print(out_string[:-2])\n\ndef run_kmeans(ann_dims, anchor_num):\n ann_num = ann_dims.shape[0]\n iterations = 0\n prev_assignments = np.ones(ann_num)*(-1)\n iteration = 0\n old_distances = np.zeros((ann_num, anchor_num))\n\n indices = [random.randrange(ann_dims.shape[0]) for i in range(anchor_num)]\n centroids = ann_dims[indices]\n anchor_dim = ann_dims.shape[1]\n\n while True:\n distances = []\n iteration += 1\n for i in range(ann_num):\n d = 1 - IOU(ann_dims[i], centroids)\n distances.append(d)\n distances = np.array(distances) # distances.shape = (ann_num, anchor_num)\n\n print(\"iteration {}: dists = {}\".format(iteration, np.sum(np.abs(old_distances-distances))))\n\n #assign samples to centroids\n assignments = np.argmin(distances,axis=1)\n\n if (assignments == prev_assignments).all() :\n return centroids\n\n #calculate new centroids\n centroid_sums=np.zeros((anchor_num, anchor_dim), np.float)\n for i in range(ann_num):\n centroid_sums[assignments[i]]+=ann_dims[i]\n for j in range(anchor_num):\n centroids[j] = centroid_sums[j]/(np.sum(assignments==j) + 1e-6)\n\n prev_assignments = assignments.copy()\n old_distances = distances.copy()\n\ndef _main_():\n num_anchors = 9\n \n root = 'F:\\\\Learning\\\\tensorflow\\\\detect\\\\Dataset\\\\'\n '''\n train_imgs, train_labels = parse_voc_annotation(\n root+'VOC2012\\\\Annotations\\\\',\n root+'VOC2012\\\\JPEGImages\\\\',\n 'data.pkl',\n ['person','head','hand','foot','aeroplane','tvmonitor','train','boat','dog','chair',\n 'bird','bicycle','bottle','sheep','diningtable','horse','motorbike','sofa','cow',\n 'car','cat','bus','pottedplant']\n )\n '''\n '''\n train_imgs, train_labels = parse_voc_annotation(\n root+'Fish\\\\Annotations\\\\',\n root+'Fish\\\\JPEGImages\\\\',\n 'data.pkl',\n ['heidiao','niyu','lvqimamiantun','hualu','heijun','dalongliuxian','tiaoshiban']\n )\n '''\n train_imgs, train_labels = parse_voc_annotation(\n root+'Fish\\\\Annotations\\\\',\n root+'Fish\\\\JPEGImages\\\\',\n 'data.pkl',\n ['aeroplane','bicycle','bird','boat','bottle','bus','car','cat','chair','cow','diningtable','dog','horse','motorbike',\n 'person','pottedplant','sheep','sofa','train','tvmonitor']\n )\n # run k_mean to find the anchors\n annotation_dims = []\n for image in train_imgs:\n print(image['filename'])\n for obj in image['object']:\n relative_w = (float(obj['xmax']) - float(obj['xmin']))/image['width']\n relatice_h = (float(obj[\"ymax\"]) - float(obj['ymin']))/image['height']\n annotation_dims.append(tuple(map(float, (relative_w,relatice_h))))\n \n annotation_dims = np.array(annotation_dims)\n centroids = run_kmeans(annotation_dims, num_anchors)\n\n # write anchors to file\n print('\\naverage IOU for', num_anchors, 'anchors:', '%0.2f' % avg_IOU(annotation_dims, centroids))\n print_anchors(centroids)\n\nif __name__ == '__main__':\n _main_()\n #raccon 117,142, 151,233, 188,341, 245,378, 248,223, 288,302, 349,379, 374,274, 383,387\n #voc 24,35, 48,87, 71,192, 120,293, 126,100, 173,186, 218,330, 330,193, 361,362\n # 24,34, 46,84, 68,185, 116,286, 122,97, 171,180, 214,327, 326,193, 359,359\n #voc 18,27, 28,75, 49,132, 55,43, 65,227, 84,86, 108,162, 109,288, 162,329, 174,103, 190,212, 245,348\n # 321,150, 343,256, 372,379\n #fish 25,31, 36,52, 42,96, 59,33, 62,64, 65,134, 100,229, 107,82, 111,134, 159,180, 162,308, 223,131,\n # 255,198, 272,331, 412,412\n #fish 33,36, 53,69, 71,144, 106,85, 137,151, 145,269, 240,173, 257,326, 412,412","sub_path":"generate_anchors.py","file_name":"generate_anchors.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"336153892","text":"class Solution:\n def maxArea(self, height):\n n = len(height)\n left = 0\n right = n - 1\n id = sorted(range(len(height)), key=lambda k: height[k])\n res = 0\n k = 0\n while k < n-1:\n i = id[k]\n h = height[i]\n while h > height[left]:\n left += 1\n while h > height[right]:\n right -= 1\n res0 = h * (right - left)\n if res0 > res:\n res =res0\n k += 1\n return res\n\n \nif __name__ == \"__main__\":\n so = Solution()\n print(so.maxArea([1,8,6,2,5,4,8,3,7]))","sub_path":"py/P0011.py","file_name":"P0011.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"415188154","text":"import cv2\nimport os\nimport numpy as np\nimport pprint\nfrom tqdm import tqdm\nimport pprint\n\nimport sys\nsys.path.append(\"../\")\n\n\nlabel_path = \"/home/arron/Documents/grey/rssrai/label_crop/\"\noutput_path = \"/home/arron/Documents/grey/rssrai/label_npy/\"\n\nRS_COLORMAP = [[0, 0, 0], [200, 0, 0], [0, 200, 0], [200, 200, 0],\n [250, 200, 0], [150, 250, 0], [250, 0, 150], [200, 150, 150],\n [250, 150, 150], [150, 200, 150], [0, 0, 200], [200, 0, 200],\n [0, 150, 200], [150, 0, 250], [150, 150, 250], [0, 200, 250]]\nRS_CLASSES = [\n '其他类别', '工业用地', '水田', '人工草地', '天然草地', '水浇地', '城市住宅', '村镇住宅', '交通运输', '旱耕地',\n '河流', '园地', '湖泊', '乔木林地', '灌木林地', '坑塘'\n]\n\n\ndef label_indices(mask, mask_colormap):\n # # colormap2label\n colormap2label = np.zeros(256**3)\n for i, colormap in enumerate(mask_colormap):\n colormap2label[(colormap[0] * 256 + colormap[1]) * 256 +\n colormap[2]] = i\n # colormap2mask\n mask = mask.astype('int32')\n idx = ((mask[:, :, 0] * 256 + mask[:, :, 1]) * 256 + mask[:, :, 2])\n return colormap2label[idx].astype('int32')\n\n\ndef load_label_map(input_path, num_classes=16):\n print(\"start making label...\")\n stat = np.zeros(num_classes)\n label_imgs = os.listdir(input_path)\n\n for label_img in tqdm(label_imgs):\n img_name = label_img.strip().split(\".\")[0]\n label_split_name = img_name.strip().split(\"_\")\n if label_split_name[-3] == \"label\":\n img = cv2.imread(input_path + label_img)[:, :, ::-1]\n label_mat = label_indices(img, RS_COLORMAP)\n for i in range(num_classes):\n stat[i] += (label_mat == i).sum()\n \n label_split_name.remove(\"label\")\n label_split_name.append(\"label\")\n label_name = \"_\".join(label_split_name)\n # print(\"_\".join(label_split_name))\n np.save(os.path.join(output_path,\"\".join([label_name,\".npy\"])),label_mat)\n \n \nif __name__ == \"__main__\":\n load_label_map(label_path) ","sub_path":"utils/making_label.py","file_name":"making_label.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"653220646","text":"\"\"\"\n利用动态规划来求解ARC的最小成本生成树\n主要是确定各个状态以及状态之间的转移函数,\n然后从下往上进行迭代求取各个阶段的成本\n最终的生成树通过递归函数get_root函数获取\n\"\"\"\n\nimport numpy as np\nimport random\nimport os\n\n\ndef get_matrix(weight_list):\n n = len(weight_list)\n cost_matrix = []\n for row in range(n):\n cost_matrix.append([[0, 0] for j in range(n)])\n return cost_matrix\n\n\ndef arc_matrix(cost_matrix, weight_list):\n n = len(cost_matrix)\n for i in range(n-1, -1, -1):\n for j in range(i, n):\n if i == j:\n cost_matrix[i][j][0] = 0\n elif j - i == 1:\n cost_matrix[i][j][0] = weight_list[i] + weight_list[j]\n else:\n min = np.iinfo(np.int16).max\n for d in range(i, j):\n temp = cost_matrix[i][d][0] + cost_matrix[d+1][j][0] + sum(weight_list[i:j+1])\n if temp < min:\n min = temp\n min_d = d\n cost_matrix[i][j][0] = min\n cost_matrix[i][j][1] = min_d\n return cost_matrix\n\n\ndef get_root(first, last, cost_matrix):\n partition = cost_matrix[first][last][1]\n if partition == 0:\n return\n else:\n print(partition)\n get_root(first, partition, cost_matrix)\n get_root(partition+1, last, cost_matrix)\n\n\ndef main():\n print(\"请输入随机序列的形式...\")\n start = int(input(\"随机序列元素的下界:\"))\n end = int(input(\"随机序列元素的上界:\"))\n length = int(input(\"随机序列的长度:\"))\n weight_list = []\n for i in range(length):\n weight_list.append(random.randint(start, end+1))\n weight_list.sort()\n print(\"排序后的权重序列为:\\n\", weight_list)\n matrix = get_matrix(weight_list)\n cost = arc_matrix(matrix, weight_list)\n print(\"生成的成本矩阵为...\")\n for i in range(len(weight_list)):\n print(cost[i])\n print(\"最小成本 = \", cost[0][length-1][0])\n print(\"得到的分界索引位置...(仅有两个元素时就不需要递归了)\")\n get_root(0, len(weight_list)-1, cost)\n\n\nif __name__ == '__main__':\n main()\n os.system(\"pause\")\n","sub_path":"arc.py","file_name":"arc.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"408960104","text":"\"\"\"\n 声明:\n 以下的视频和代码内容,只作为学习和研究使用,如果需要进行实盘交易,\n 请您本人进行仔细测试和研究,如果使用该代码进行交易,造成的损失由个人承担全部责任\n 51bitquant本人不保证所以的代码和交易思路的正确性. 谨慎使用.\n\n 交易所链接:\n 币安交易所链接:https://www.binance.com/en/register?ref=22795115\n bybit交易所链接:https://www.bybit.com/app/register?ref=yXjOz\n\n 1.注意事项:\n 1. 生成的API-key 要保管好,防止泄露,因为是期货交易,如果高杠杆的情况下,很容易爆仓\n 2. 切记开仓的仓位数量过大, 开仓做好止损.\n 3. 建议小资金测试,确认交易的策略能够盈利,且代码逻辑没有问题.\n\n\"\"\"\nfrom binance_trade.gateway.binance_ws import BinanceDataWebsocket\nfrom binance_trade.gateway.binance_http import BinanceFutureHttp\nfrom apscheduler.schedulers.background import BackgroundScheduler\nimport time\nfrom datetime import datetime\nfrom binance_trade.strategies.DoubleEMAStrategy import DoubelEMAStrategy\n\nimport logging\nformat = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\nlogging.basicConfig(level=logging.INFO, format=format, filename='ema_strategy.txt')\nlogging.getLogger('apscheduler').setLevel(logging.WARNING) # 设置apscheduler日记类型.\n\nif __name__ == '__main__':\n\n key = \"2prTS89tkGv53BbE4Xtvh3HvI8wskWzAg5MYwkbvByHgWOhG49Ud0j8sGKZD5oIs\"\n secret = 'ow0aZVI5AQyqqf6VxTN21VzDRd5YaxZ10vZVSzJBLOcYuOF1usFIyyMj6lqr9coz'\n binance = BinanceFutureHttp(key=key, secret=secret)\n\n symbol = 'BTCUSDT'\n double_ema_strategy = DoubelEMAStrategy(http_client=binance, symbol=symbol)\n scheduler = BackgroundScheduler()\n\n # 子线程执行。\n binance_ws = BinanceDataWebsocket(on_tick_callback=double_ema_strategy.on_tick)\n binance_ws.subscribe(symbol)\n\n # scheduler在子线程里面执行.\n # 获取K线数据.\n scheduler.add_job(double_ema_strategy.on_1hour_kline_data, trigger='cron', args=(symbol,), hour='*/1')\n\n # 获取当前的挂单没有成交的订单. 30 秒请求一次.\n scheduler.add_job(double_ema_strategy.on_open_orders, trigger='cron', args=(symbol,), second='*/30')\n\n # 获取当前的仓位信息.\n scheduler.add_job(double_ema_strategy.on_position, trigger='cron', args=(symbol,), second='*/15')\n\n scheduler.start()\n\n #\n double_ema_strategy.on_1hour_kline_data(symbol)\n\n while True:\n double_ema_strategy.check_position()\n time.sleep(60) # 2min.\n # 每两分钟需要检查下仓位信息, 检查订单有没有成交,\n # 是否符合自己的要求.\n\n\n","sub_path":"binance_main.py","file_name":"binance_main.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"381104440","text":"\r\nimport numpy as np\r\n\r\n\r\ndef im2col(x, hh, ww, stride):\r\n \"\"\"\r\n Args:\r\n x: image matrix to be translated into columns, (C,H,W)\r\n hh: filter height\r\n ww: filter width\r\n stride: stride\r\n Returns:\r\n col: (new_h*new_w,hh*ww*C) matrix, each column is a cube that will convolve with a filter\r\n new_h = (H-hh) // stride + 1, new_w = (W-ww) // stride + 1\r\n \"\"\"\r\n c, h, w = x.shape\r\n new_h = (h-hh) // stride + 1\r\n new_w = (w-ww) // stride + 1\r\n col = np.zeros([new_h*new_w, c*hh*ww])\r\n for i in range(new_h):\r\n for j in range(new_w):\r\n patch = x[..., i*stride:i*stride+hh, j*stride:j*stride+ww]\r\n col[i*new_w+j, :] = np.reshape(patch, -1)\r\n return col\r\n\r\n\r\ndef col2im(mul, h_prime, w_prime, C):\r\n \"\"\"\r\n Args:\r\n mul: (h_prime*w_prime*w,F) matrix, each col should be reshaped to C*h_prime*w_prime when C>0, or h_prime*w_prime when C = 0\r\n h_prime: reshaped filter height\r\n w_prime: reshaped filter width\r\n C: reshaped filter channel, if 0, reshape the filter to 2D, Otherwise reshape it to 3D\r\n Returns:\r\n if C == 0: (F,h_prime,w_prime) matrix\r\n Otherwise: (F,C,h_prime,w_prime) matrix\r\n \"\"\"\r\n F = mul.shape[1]\r\n if C == 1:\r\n out = np.zeros([F, h_prime, w_prime])\r\n for i in range(F):\r\n col = mul[:, i]\r\n out[i, :, :] = np.reshape(col, (h_prime, w_prime))\r\n else:\r\n out = np.zeros([F, C, h_prime, w_prime])\r\n for i in range(F):\r\n col = mul[:, i]\r\n out[i, :, :] = np.reshape(col, (C, h_prime, w_prime))\r\n return out\r\n\r\n\r\ndef col2im_back(dim_col, h_prime, w_prime, stride, hh, ww, c):\r\n \"\"\"\r\n Args:\r\n dim_col: gradients for im_col,(h_prime*w_prime,hh*ww*c)\r\n h_prime,w_prime: height and width for the feature map\r\n strid: stride\r\n hh,ww,c: size of the filters\r\n Returns:\r\n dx: Gradients for x, (C,H,W)\r\n \"\"\"\r\n H = (h_prime - 1) * stride + hh\r\n W = (w_prime - 1) * stride + ww\r\n dx = np.zeros([c, H, W])\r\n for i in range(h_prime*w_prime):\r\n row = dim_col[i, :]\r\n h_start = int((i / w_prime) * stride)\r\n w_start = int((i % w_prime) * stride)\r\n dx[:, h_start:h_start+hh, w_start:w_start+ww] += np.reshape(row, (c, hh, ww))\r\n return dx\r\n","sub_path":"CNN_with_python/img_and_col.py","file_name":"img_and_col.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"166064026","text":"\nimport requests\nfrom bs4 import BeautifulSoup\nimport re,time\n\nurl = 'http://www.ip138.com/'\nresponse = requests.get(url)\nresponse.encoding = 'gbk'\ndata = BeautifulSoup(response.text,'html.parser')\nrealurl = data.find(name='iframe',attrs={'rel':'nofollow'})['src']\nres = requests.get(realurl)\nres.encoding = 'gbk'\ndata2 = res.text\nresult = re.findall(r\"\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\", data2)\nip = result[0]\nprint('The program will exit after 60 seconds')\nprint(ip)\ntime.sleep(60)\n\n","sub_path":"ip.py","file_name":"ip.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"425613170","text":"from django.conf.urls import patterns, url\n\nfrom dainty import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index),\n url(r'^index/$', views.index),\n url(r'^join/$', views.join),\n url(r'^sign/$', views.sign),\n url(r'^user/(?P[0-9a-zA-Z]*)/$', views.user),\n url(r'^signout/$', views.signout),\n url(r'^addlink/$', views.addlink),\n url(r'^user/delete/(?P[0-9]+)/$', views.deletebmk),\n)\n\n","sub_path":"dainty/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"544974552","text":"\"\"\"Make modules of observations based on cooccurence networks and collapse table\"\"\"\n\nfrom __future__ import division\n\nimport networkx as nx\nimport numpy as np\nfrom biom import Table\nimport os\n\n\ndef make_modules(graph, k=3, prefix=\"module\"):\n \"\"\"make modules with networkx k-clique communities and annotate network\"\"\"\n premodules = list(nx.k_clique_communities(graph, k))\n # reverse modules so observations will be added to smallest modules\n premodules = list(enumerate(premodules))\n premodules.reverse()\n\n modules = dict()\n seen = set()\n for i, module in premodules:\n # process module\n module = module-seen\n seen = seen | module\n modules[prefix+\"_\"+str(i)] = module\n for node in module:\n graph.node[node][prefix] = i\n return graph, modules\n\n\ndef make_modules_multik(graph, k=None):\n \"\"\"make modules with networkx k-clique communities and annotate network\"\"\"\n if k is None:\n k = [2, 3, 4, 5, 6]\n communities = dict()\n for k_val in list(k):\n cliques = list(nx.k_clique_communities(graph, k_val))\n cliques = [list(i) for i in cliques]\n communities[k_val] = cliques\n for i, clique in enumerate(cliques):\n for node in clique:\n graph.node[node]['k_' + str(k_val)] = i\n return graph, {k: list(v) for k, v in communities.iteritems()}\n\n\ndef collapse_modules(table, modules):\n \"\"\"collapse created modules in a biom table, members of multiple modules will be added to the smallest module\"\"\"\n table = table.copy()\n module_array = np.zeros((len(modules), table.shape[1]))\n\n seen = set()\n for i, module in modules.iteritems():\n seen = seen | module\n # sum everything in the module\n module_array[int(i.split(\"_\")[-1])] = np.sum([table.data(feature, axis=\"observation\") for feature in module],\n axis=0)\n\n table.filter(seen, axis='observation', invert=True)\n\n # make new table\n new_table_matrix = np.concatenate((table.matrix_data.toarray(), module_array))\n new_table_obs = list(table.ids(axis='observation')) + modules.keys()\n return Table(new_table_matrix, new_table_obs, table.ids())\n\n\ndef write_modules_to_dir(table, modules):\n # for each module merge values and print modules to file\n os.makedirs(\"modules\")\n # reverse modules so observations will be added to smallest modules\n for i, module in modules.iteritems():\n # make biom tables for each module and write to file\n module_table = table.filter(module, axis='observation', inplace=False)\n module_table.to_json(\"modulemaker.py\", open(\"modules/%s.biom\" % i, 'w'))\n\n\ndef write_modules_to_file(modules):\n # write all modules to file\n with open(\"modules.txt\", 'w') as f:\n for i, module in modules.iteritems():\n f.write(i + '\\t' + '\\t'.join([str(j) for j in module]) + '\\n')\n\n\ndef collapse_modules_multik(table, cliques, prefix=\"module_\"):\n \"\"\"collapse created modules in a biom table\"\"\"\n in_module = set()\n modules = np.zeros((len(cliques), table.shape[1]))\n\n # for each clique merge values\n for i, clique in enumerate(cliques):\n in_module = in_module | set(clique)\n for feature in clique:\n modules[i] += table.data(feature, axis='observation')\n table.filter(in_module, axis='observation')\n\n # make new table\n new_table_matrix = np.concatenate((table.matrix_data.toarray(), modules))\n new_table_obs = list(table.ids(axis='observation')) + [prefix + str(i) for i in range(0, len(cliques))]\n return Table(new_table_matrix, new_table_obs, table.ids(), table.metadata(axis=\"observation\"),\n table.metadata(axis=\"sample\"))\n","sub_path":"SCNIC/module_maker.py","file_name":"module_maker.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"97521589","text":"#!/usr/bin/env python3\nfrom webvtt import WebVTT, Caption\nfrom io import StringIO\nfrom TranslationDriver import TranslationDriver\nfrom bs4 import BeautifulSoup\nimport subprocess\nimport argparse\nimport sys\nimport os\nfrom ansicolor import red, green\n\nparser = argparse.ArgumentParser(description='Translate subtitles')\nparser.add_argument('lang', help='The lang code like \"sv\" to translate to')\nparser.add_argument('yturl', help='The Youtube URL of the video with english subtitles')\nargs = parser.parse_args()\n\nout = subprocess.check_output([\"youtube-dl\", \"--sub-lang\", \"en\", \"--write-sub\", \"--skip-download\", args.yturl.partition(\"&\")[0]])\n\n# Find VTT file<\ndef vtt_file(out):\n for line in out.decode(\"utf-8\").split(\"\\n\"):\n if \"Writing video subtitles to: \" in line:\n return line.partition(\":\")[2].strip()\n return None\n\nfilename = vtt_file(out)\nif not filename:\n print(red(\"Video does not seem to have english subs\", bold=True))\n sys.exit(1)\n\n# Read source VTT & convert to HTML\nvtt = WebVTT()\nvtt.read(filename)\n\nstmp = StringIO()\nprint(\"
\", file=stmp)\nfor caption in vtt:\n print('{}'.format(caption.start, caption.end, caption.text), file=stmp)\nprint(\"
\", file=stmp)\n\n# Translate\ndriver = TranslationDriver(args.lang)\nstrans = driver.translate(stmp.getvalue())\n\n# Convert translated HTML back to VTT\nvtt = WebVTT()\n\nsoup = BeautifulSoup(strans, \"lxml\")\nfor span in soup.find_all(\"span\"):\n start = span[\"data-start\"]\n end = span[\"data-end\"]\n caption = Caption(start, end, span.text)\n vtt.captions.append(caption)\n\n# Remove the english file\nos.remove(filename)\n\noutfile = filename.replace(\".en.\", \".{}.\".format(args.lang));\nvtt.save(outfile)\nprint(green(outfile, bold=True))","sub_path":"TranslateSubtitles.py","file_name":"TranslateSubtitles.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"146808903","text":"# coding=utf-8\nimport requests\n\n\ndef get_address_balance(address_list):\n \"\"\"\n 获得地址的余额\n :param address_list:\n :return:\n \"\"\"\n s = requests.Session()\n s.headers.update({'content-type': 'application/x-www-form-urlencoded'})\n url = \"https://api.omniwallet.org/v2/address/addr/\"\n data = {'addr': address_list}\n\n response = s.post(url=url, data=data)\n\n res = {}\n for address in address_list:\n address_balance = []\n for omni_balance in response.json().get(address)['balance']:\n if int(omni_balance['id']) > 0:\n address_balance.append({\n \"property_id\": omni_balance['id'],\n \"name\": omni_balance[\"propertyinfo\"][\"propertyname\"],\n \"balance\": float(omni_balance['value']) / 100000000\n })\n res[address] = address_balance\n\n print(res)\n\n\n# addresses = ['xxxxx', 'xxxx']\n# get_address_balance(addresses)\n","sub_path":"block-chain-tools/src/omni/omni_address_balance.py","file_name":"omni_address_balance.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"427893946","text":"message = input(\"TYPE HERE\")\r\ncharacterCount = 0\r\nwordCount = 1\r\nfor a in message:\r\n characterCount = characterCount + 1\r\n if(a == \" \"):\r\n wordCount = wordCount + 1\r\nprint(\"number of words in the string:\")\r\nprint(wordCount)\r\nprint(\"number of characters in the string:\")\r\nprint(characterCount)","sub_path":"Class 97/CountingNumbers.py","file_name":"CountingNumbers.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"522433705","text":"import os\nos.environ['PYTHONUNBUFFERED'] = '1'\nos.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT'] = '0'\nos.environ['MXNET_ENABLE_GPU_P2P'] = '0'\nthis_dir = os.path.dirname(__file__)\n\nimport train\nimport test\n\nif __name__ == \"__main__\":\n train.main()\n test.main()\n\n\n\n\n","sub_path":"tools/train_test.py","file_name":"train_test.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"69872564","text":"import os\nfrom datetime import datetime\nimport pytz\n\nfrom django.core.management.base import BaseCommand, CommandError\nimport piexif\n\nfrom images.models import RootFolder, SyncFolder, Image\n\n\nclass Command(BaseCommand):\n help = 'Scan root folder, make sure you have root folder into config'\n rootInstance = None\n\n def get_exif(self, relative_path):\n info = piexif.load(relative_path)\n return info[\"Exif\"][36867]\n\n def get_sync_info(self):\n \"\"\"\n get previous values of folder updated_at\n # TODO get uniq image id and use it as uniq ID on model Image\n \"\"\"\n res = {}\n syncs = SyncFolder.objects.all()\n for sync in syncs:\n res[sync.path] = sync.updated_at\n return res\n\n def need_update(self, path, sync_info):\n \"\"\"\n check was folder been updated from previous scan\n return bool\n \"\"\"\n is_need_update = True\n time_update = datetime.fromtimestamp(\n int(os.path.getmtime(path))\n )\n if sync_info.get(path, None):\n if time_update <= sync_info.get(path, None).replace(tzinfo=None):\n is_need_update = False\n else:\n is_need_update = True\n else:\n is_need_update = True\n obj, created = SyncFolder.objects.get_or_create(\n path=path,\n defaults={\n 'updated_at': time_update.replace(tzinfo=pytz.UTC),\n 'root_folder_id': self.rootInstance.id\n },\n )\n obj.updated_at = time_update.replace(tzinfo=pytz.UTC)\n obj.save()\n return is_need_update\n\n def handle(self, *args, **options):\n self.stdout.write(\n self.style.NOTICE('Scan start, it can take much time.')\n )\n try:\n rootInstance = RootFolder.objects.get()\n except RootFolder.DoesNotExist:\n raise CommandError('Root folder does not set into config')\n self.rootInstance = rootInstance\n sync_info = self.get_sync_info()\n for root, dirs, files in os.walk(rootInstance.scan_path):\n path = os.path.join(root)\n for directory in dirs:\n path = os.path.join(root, directory)\n is_need_update = self.need_update(path, sync_info)\n if not is_need_update:\n dirs.remove(directory)\n\n if self.need_update(path, sync_info):\n for f in files:\n # only jp photos\n parts = f.split(\".\")\n if len(parts):\n if parts[-1].lower() not in [\"jpg\", \"jpeg\"]:\n continue\n else:\n continue\n r = self.get_exif(os.path.join(root, f))\n created_at = datetime.strptime(\n r.decode('utf-8'),\n \"%Y:%m:%d %H:%M:%S\"\n )\n new_image, created = Image.objects.update_or_create(\n file_name=f,\n created_at=created_at.replace(tzinfo=pytz.UTC),\n defaults={\n 'created_at': created_at.replace(tzinfo=pytz.UTC),\n 'file_name': f,\n 'abs_path': os.path.join(root, f)\n }\n )\n new_image.save()\n self.stdout.write(\n self.style.SUCCESS('Scan finished.')\n )\n","sub_path":"images/management/commands/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"254604333","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 25 10:13:13 2019\n\n@author: Pranav Nair\n\"\"\"\n\nimport pandas as pd\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\n\ndef calculate(message):\n # create data frame from yelp reviews\n print(message)\n dataset = pd.read_csv('yelp_labelled.txt', sep='\\t', header=None)\n # print(dataset.head())\n dataset.columns = ['Text','Class']\n train_x = dataset['Text'].values\n train_y = dataset['Class'].values\n \n # Vectorizer to represent our data\n vectorizer = TfidfVectorizer()\n vectorized_train_x = vectorizer.fit_transform(train_x)\n print(\"vectorized_train_x shape::{0}\".format(vectorized_train_x.shape))\n \n # Create logistic regression model\n print(train_x)\n print(vectorized_train_x)\n classifier = LogisticRegression()\n classifier.fit(vectorized_train_x, train_y)\n \n # Use test message and convert to vector representation\n sentence = [message]\n vectorized_message = vectorizer.transform(sentence)\n prediction = classifier.predict_proba(vectorized_message)\n \n # Get probabilities\n negative_score = prediction[0][0]\n positive_score = prediction[0][1]\n \n if negative_score >= .33 and positive_score >= .33:\n sentiment = 'neutral'\n elif negative_score > .66:\n sentiment = 'negative'\n else:\n sentiment = 'positive'\n \n print(\"Sentiment: {0}\".format(sentiment))\n \n print(\"Negative score: {0}, Positive Score {1}\".format(negative_score, positive_score))\n\n\n#message = \"Can I go negative on Workday for vacation days?\"\nmessage = \"Very slow service\"\n\ncalculate(message)\n\n\n\n","sub_path":"sentiment_analysis_logical_regression.py","file_name":"sentiment_analysis_logical_regression.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"39256548","text":"#!/usr/bin/env python\n\nimport numpy as np\nfrom roboticstoolbox.robot.ERobot import ERobot\nfrom pathlib import Path\nimport roboticstoolbox as rp\n\n\nclass UR10(ERobot):\n\n def __init__(self):\n\n mpath = Path(rp.__file__).parent\n fpath = mpath / 'models' / 'xacro' / 'ur_description' / 'urdf'\n fname = 'ur10_joint_limited_robot.urdf.xacro'\n\n args = super(UR10, self).urdf_to_ets_args((fpath / fname).as_posix())\n\n super().__init__(\n args[0],\n name=args[1],\n manufacturer = 'Universal Robotics'\n )\n\n self.addconfiguration(\"qz\", np.array([0, 0, 0, 0, 0, 0]))\n self.addconfiguration(\"qr\", np.array([np.pi, 0, 0, 0, np.pi/2, 0]))\n\n\nif __name__ == '__main__':\n\n robot = UR10()\n print(robot)","sub_path":"roboticstoolbox/models/URDF/UR10.py","file_name":"UR10.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"2408839","text":"#permite fazer uma requisição http que em seguida será utilizado para extriar o html da página\nimport requests\n\n#permite extrair informações do html utilizando seletores html/css. \nfrom bs4 import BeautifulSoup\n\n#Permite a limpagem dos dados para serem utilizados como npumeros ou para a finalidade desejada\nimport pandas as pd\n\n#1-acessado pelo google.colab para gerar o arquivo csv e salvar na pasta do google drive\n#2-foi comentado para não dar erro se executado fora do colab\n#3-precisa ser montado para funcionar\n#from google.colab import drive\n\n#função para realizar o webscraping\ndef scrap_state_info(state: str) -> dict: \n\n \"\"\"\n retorna informações dos estados brasileiros\n :param state: nome do estado\n :returns state_direct: Dicionários com indicadores do estado \n \"\"\"\n print(f'Picking {state} info...')\n \n #variável state_url recebe a url que se deseja fazer a extração dos dados brutos, recebe o UF do estado na variável {state}\n state_url = f'https://www.ibge.gov.br/cidades-e-estados/{state}.html'\n \n #faz a requisição passando a variável com a URL desejada\n page=requests.get(state_url)\n \n #parseia o html da página para que possa ser usado os seletores html/css para extração\n soup = BeautifulSoup(page.content, 'html.parser')\n \n #selecionando todas as classes '.indicador' para pegar a label e os value de cada classe\n indicadors = soup.select('.indicador')\n \n #percorrendo a lista aplicando seletores e guardando em uma variável do tipo dicionário\n state_dict = {\n ind.select('.ind-label')[0].text: ind.select('.ind-value')[0].text \n for ind in indicadors\n }\n \n #criando uma chave chamada Estado para receber o UF de cada estado\n state_dict['Estado'] = state\n \n #retona\n return state_dict\n\n#lista com todas as UFs para ser passada para a função de extração dos dados de cada estado\nstates = ['AC','AL','AP','AM','BA','CE','DF','ES','GO','MA','MT','MS','MG','PA','PB','PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO']\n#states = ['AC']\n#executando a função de extração dos dados para cada estado constante da lista 'states'\nstates_data = [scrap_state_info(state) for state in states]\n\n\n#passando a lista pronta para o panda\ndf = pd.DataFrame(states_data)\n\n#mostra os dados extraídos de forma bruta, mostra as primeiras linhas da tabela\n#print(df.head())\n#informação importantes dos dados extraídos\n#df.info()\n\n#fazendo uma cópia como boas práticas antes de tratar dos dados\nstates_df = df.copy()\n\n#mudando o nome das colunas\nstates_df.columns = ['governador','capital','gentilico','area','população','densidade','matrícula-no-ensino-fundamental','idh','receita-realizada','despesas-empenhadas','rendimento-mensal-per-capita','total-de-veiculos','estado']\n\n#organizando as colunas por dados de texto e numéricos resposctivamente\nstates_df = states_df[['estado','governador','capital','gentilico','area','população','densidade','matrícula-no-ensino-fundamental','idh','receita-realizada','despesas-empenhadas','rendimento-mensal-per-capita','total-de-veiculos']]\n\n#fazendo o split dos dados retirando caracteres indesejados\nstates_df = states_df.replace({\n '\\.':'',\n ',':'.',\n '\\[\\d+\\]':'',\n ' hab/km²':'',\n ' km²':'',\n ' pessoas':'',\n ' matrículas':'',\n 'R\\$.*':'',\n ' veículos':''\n}, regex=True)\n\n#separando as colunas numéricas\ncolunas_numericas = ['area','população','densidade','matrícula-no-ensino-fundamental','idh','receita-realizada','despesas-empenhadas','rendimento-mensal-per-capita','total-de-veiculos']\n\n#aplica a função split do panda que tira espaços nas bordas de uma string\nstates_df[colunas_numericas] = states_df[colunas_numericas].apply(lambda x: x.str.strip())\n\n#usa a função do panda para converter em números\nstates_df[colunas_numericas] = states_df[colunas_numericas].apply(pd.to_numeric)\nprint(states_df.head())\n#1 usar com o google colabe após ser montado para exportar o arquivo .csv\n#2 cira o arquivo .csv com o tratamento feito e coloca dentro da pasta do google drive escolhida\n#states_df.to_csv('/content/drive/MyDrive/Webscraping_Ibge/ibge_estados.csv')","sub_path":"Cloud9_Lista_Python/ListaPython/environment/atividade03/webscrap_ibge.py","file_name":"webscrap_ibge.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"340655179","text":"import pytest\n\nfrom graphs.common import one_shard\nfrom xqa.perf import wait_for_e2e_ingest_to_complete\nfrom xqa.testing_support.chart import save_values_for_graphs, create_graphs\nfrom xqa.testing_support.database import create_stats_db\n\nINGEST_THREADS = 1\n\ningest_balancer = [\n {'image': 'xqa-ingest-balancer:latest',\n 'name': 'xqa-ingest-balancer',\n 'command': ['-message_broker_host', 'xqa-message-broker',\n '-pool_size', '%s' % INGEST_THREADS,\n '-insert_thread_wait', '60000',\n '-insert_thread_secondary_wait', '1000'],\n 'network': 'xqa'},\n]\n\n\n@pytest.fixture\ndef dockerpy_1_shard():\n return one_shard + ingest_balancer\n\n\nstats_db = create_stats_db()\n\n\ndef test_1_shards_1_client(dockerpy_1_shard):\n wait_for_e2e_ingest_to_complete()\n save_values_for_graphs(stats_db, INGEST_THREADS, 1)\n create_graphs(stats_db, INGEST_THREADS)\n","sub_path":"test/graphs/dell/test_worst_case_scenario.py","file_name":"test_worst_case_scenario.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"430827727","text":"# -*- coding: utf-8 -*-\n\n\nimport sys\nimport os\n\n\nfrom os import listdir\nfrom os.path import isfile, join\n\nimport json\n\nimport statistics\n\nfrom pymongo import MongoClient\n\ndef filterMinus999(tab):\n newTab = []\n for x in tab:\n if(x != -999):\n newTab.append(x)\n return newTab\n\ndef filterDash(tab):\n tabtemp = []\n for x in tab:\n if(x[0] != \"-\"):\n tabtemp.append(x)\n return tabtemp\n\n\nprint(\"startLoaderCompile\")\nclient = MongoClient()\nclient = MongoClient('localhost', 27027)\ndb = client.rdv\nprint(\"connected\")\n\npublicFolder = \"/u/malricp/rdv/public/\"\n\npathTab = []\npathTab.append({\"name\":\"so_detail\",\"path\":[\"localNcmD_detail\",\"so\"],\"soft\":\"so\"})\npathTab.append({\"name\":\"mcff_detail\",\"path\":[\"localNcmD_detail\",\"mcff\"],\"soft\":\"mcff\"})\npathTab.append({\"name\":\"so_ncm\",\"path\":[\"localNcmD\",\"so\"],\"soft\":\"so\"})\npathTab.append({\"name\":\"mcff_ncm\",\"path\":[\"localNcmD\",\"mcff\"],\"soft\":\"mcff\"})\n\n\ndi = '/u/malricp/rdv/public/JSON_FOLDER_test/'\ndirs = [o for o in os.listdir(di) \n if o.startswith(\"ETERNA\")]\n\nfor folderName in dirs:\n onlyfiles = [f for f in listdir(di+folderName) if isfile(join(di+folderName, f))]\n\n #onlyfiles = [file for file in listdir(mypath) if isfile(join(mypath, file))]\n\n rnaTab = []\n counter = 0\n\n for file in onlyfiles:\n if(file.endswith(\".json\") and not file.endswith(\"file_id_short.json\")):\n print(\"i : \"+str(counter))\n counter += 1\n if(counter > 100000):\n break\n rna = json.loads(open(di+folderName+\"/\"+file,\"r\").read())\n for dPath in pathTab:\n d = {}\n rnaD = {}\n t = rna[\"nts\"]\n filtered = filterMinus999(rna[\"scoreTab\"])\n nts_score_mean = statistics.mean(filtered)\n nts_score_sd = statistics.stdev(filtered)\n hi_threshold = nts_score_mean + nts_score_sd\n low_threshold = nts_score_mean \n for nt in t:\n o = nt\n for p in dPath[\"path\"]:\n #print(\"keys : \"+str(o.keys()))\n o = o[p]\n tab = o.keys()\n for v in tab:\n url = \"http://majsrv1.iric.ca:3000/\"+folderName+\"|\"+str(rna[\"rna_id\"])+\"|\"+str(nt[\"position\"])\n #tbTemp.append(str(v))\n root = v\n freq = str(o[v])\n score = str(nt[\"score\"])\n so_pairee = str(nt[\"freqPairee_so\"])\n mcff_pairee = str(nt[\"freqPairee_mcff\"])\n if(nt[\"score\"] < low_threshold and nt[\"score\"] != -999 and o[v] > 0.1 and o[v] > 0.1):\n label =\"Low\"\n db.ncm_50.insert({\"ncm\":root,\"soft\":dPath[\"soft\"],\"url\":url,\"freq\":freq,\"score\":score,\"so_pairee\":so_pairee,\"mcff_pairee\":mcff_pairee,\"label\":label})\n \n if(nt[\"score\"] > hi_threshold):\n label = \"Hi\"\n db.ncm_50.insert({\"ncm\":root,\"soft\":dPath[\"soft\"],\"url\":url,\"freq\":freq,\"score\":score,\"so_pairee\":so_pairee,\"mcff_pairee\":mcff_pairee,\"label\":label})\n \n if((nt[\"score\"] < hi_threshold and nt[\"score\"] != -999) and nt[\"score\"] > low_threshold and o[v] > 0.1 ):\n label = \"Bg\"\n db.ncm_50.insert({\"ncm\":root,\"soft\":dPath[\"soft\"],\"url\":url,\"freq\":freq,\"score\":score,\"so_pairee\":so_pairee,\"mcff_pairee\":mcff_pairee,\"label\":label})\n \n \n \n ","sub_path":"compileNcmScore.py","file_name":"compileNcmScore.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"409298544","text":"from django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.forms import ModelForm\n\nfrom inoks.models import Profile\n\nCHOICES_WITH_BLANK = (\n ('', '--------'),\n\n)\n\n\nclass ProfileForm(ModelForm):\n isContract = forms.BooleanField(required=False)\n\n class Meta:\n model = Profile\n\n fields = (\n 'profileImage', 'mobilePhone', 'gender', 'tc', 'birthDate', 'job', 'city', 'educationLevel',\n 'district', 'isContract', 'iban', 'ibanAdSoyad')\n widgets = {\n # 'address': forms.Textarea(\n # attrs={'class': 'form-control ', 'placeholder': 'Adres', 'rows': '2', 'required': 'required'}),\n 'mobilePhone': forms.TextInput(\n attrs={'class': 'form-control ', 'placeholder': '(5XX)-XXX-XX-XX', 'required': 'required',\n 'maxlength': '10', 'minlength': '10'}),\n 'gender': forms.Select(attrs={'class': 'form-control select2 select2-hidden-accessible',\n 'style': 'width: 100%;', 'required': 'required'}),\n 'tc': forms.TextInput(\n attrs={'class': 'form-control', 'placeholder': 'T.C. Kimlik Numarası', 'required': 'required',\n 'maxlength': '11', 'minlength': '11'}),\n\n 'birthDate': forms.DateInput(\n attrs={'class': 'form-control pull-right', 'type': 'date', 'autocomplete': 'off',\n }),\n\n\n\n 'city': forms.Select(attrs={'class': 'form-control select2 select2-hidden-accessible',\n 'style': 'width: 100%; ', 'required': 'required', \"onChange\": 'ilceGetir()'}),\n\n 'district': forms.Select(choices=CHOICES_WITH_BLANK,\n attrs={'class': 'form-control select2 select2-hidden-accessible',\n 'style': 'width: 100%; ', 'id': 'ilce_id'}\n ),\n\n 'job': forms.Select(attrs={'class': 'form-control select2 select2-hidden-accessible',\n 'style': 'width: 100%;', 'required': 'required'}),\n\n 'educationLevel': forms.Select(attrs={'class': 'form-control select2 select2-hidden-accessible',\n 'style': 'width: 100%;', 'required': 'required'}),\n\n 'iban': forms.TextInput(\n attrs={'class': 'form-control iban', 'placeholder': 'iban',\n 'required': 'required',\n }),\n 'ibanAdSoyad': forms.TextInput(\n attrs={'class': 'form-control', 'placeholder': 'Hesap Adı ve Soyadı', 'required': 'required'\n\n })\n\n }\n\n def clean_tc(self):\n tc = self.cleaned_data['tc']\n if Profile.objects.filter(tc=tc).exists():\n raise ValidationError(\"Girdiğiniz TC başka bir üyemiz tarafından kullanılmakta.\")\n return tc\n\n def clean_mobilePhone(self):\n mobilePhone = self.cleaned_data['mobilePhone']\n if Profile.objects.filter(mobilePhone=mobilePhone).exists():\n raise ValidationError(\"Girdiğiniz Telefon numarası başka bir üyemiz tarafından kullanılmakta.\")\n return mobilePhone\n","sub_path":"inoks/Forms/ProfileFormForMember.py","file_name":"ProfileFormForMember.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"510748821","text":"import argparse\nimport base64\nimport json\nimport os\nimport urllib\nfrom zipfile import ZipFile\n\nfrom azure.identity import DefaultAzureCredential\nfrom azure.ai.ml import MLClient\nfrom azure.ai.ml.entities import Data\nfrom azure.ai.ml.constants import AssetTypes\n\n\ndef create_ml_table_file(filename):\n \"\"\"Create ML Table definition\"\"\"\n\n return (\n \"paths:\\n\"\n \" - file: ./{0}\\n\"\n \"transformations:\\n\"\n \" - read_json_lines:\\n\"\n \" encoding: utf8\\n\"\n \" invalid_lines: error\\n\"\n \" include_path_column: false\\n\"\n \" - convert_column_types:\\n\"\n \" - columns: image_url\\n\"\n \" column_type: stream_info\"\n ).format(filename)\n\n\ndef save_ml_table_file(output_path, mltable_file_contents):\n with open(os.path.join(output_path, \"MLTable\"), \"w\") as f:\n f.write(mltable_file_contents)\n\n\ndef create_jsonl_and_mltable_files(uri_folder_data_path, dataset_dir):\n print(\"Creating jsonl files\")\n\n dataset_parent_dir = os.path.dirname(dataset_dir)\n\n # We will copy each JSONL file within its related MLTable folder\n training_mltable_path = os.path.join(dataset_parent_dir, \"training-mltable-folder\")\n validation_mltable_path = os.path.join(\n dataset_parent_dir, \"validation-mltable-folder\"\n )\n\n # Create MLTable folders, if they don't exist\n os.makedirs(training_mltable_path, exist_ok=True)\n os.makedirs(validation_mltable_path, exist_ok=True)\n\n train_validation_ratio = 5\n\n # Path to the training and validation files\n train_annotations_file = os.path.join(\n training_mltable_path, \"train_annotations.jsonl\"\n )\n validation_annotations_file = os.path.join(\n validation_mltable_path, \"validation_annotations.jsonl\"\n )\n\n # Baseline of json line dictionary\n json_line_sample = {\"image_url\": uri_folder_data_path, \"label\": \"\"}\n\n index = 0\n # Scan each sub directary and generate a jsonl line per image, distributed on train and valid JSONL files\n with open(train_annotations_file, \"w\") as train_f:\n with open(validation_annotations_file, \"w\") as validation_f:\n for class_name in os.listdir(dataset_dir):\n sub_dir = os.path.join(dataset_dir, class_name)\n if not os.path.isdir(sub_dir):\n continue\n\n # Scan each sub directary\n print(f\"Parsing {sub_dir}\")\n for image in os.listdir(sub_dir):\n json_line = dict(json_line_sample)\n json_line[\"image_url\"] += f\"{class_name}/{image}\"\n json_line[\"label\"] = class_name\n\n if index % train_validation_ratio == 0:\n # Validation annotation\n validation_f.write(json.dumps(json_line) + \"\\n\")\n else:\n # Train annotation\n train_f.write(json.dumps(json_line) + \"\\n\")\n index += 1\n print(\"done\")\n\n # Create and save train mltable\n train_mltable_file_contents = create_ml_table_file(\n os.path.basename(train_annotations_file)\n )\n save_ml_table_file(training_mltable_path, train_mltable_file_contents)\n\n # Create and save validation mltable\n validation_mltable_file_contents = create_ml_table_file(\n os.path.basename(validation_annotations_file)\n )\n save_ml_table_file(validation_mltable_path, validation_mltable_file_contents)\n\n\ndef upload_data_and_create_jsonl_mltable_files(ml_client, dataset_parent_dir):\n # Create directory, if it does not exist\n os.makedirs(dataset_parent_dir, exist_ok=True)\n\n # Download data\n print(\"Downloading data.\")\n download_url = \"https://cvbp-secondary.z19.web.core.windows.net/datasets/image_classification/fridgeObjects.zip\"\n\n # Extract current dataset name from dataset url\n dataset_name = os.path.basename(download_url).split(\".\")[0]\n # Get dataset path for later use\n dataset_dir = os.path.join(dataset_parent_dir, dataset_name)\n\n # Get the name of zip file\n data_file = os.path.join(dataset_parent_dir, f\"{dataset_name}.zip\")\n\n # Download data from public url\n urllib.request.urlretrieve(download_url, filename=data_file)\n\n # Extract files\n with ZipFile(data_file, \"r\") as zip:\n print(\"extracting files...\")\n zip.extractall(path=dataset_parent_dir)\n print(\"done\")\n # Delete zip file\n os.remove(data_file)\n\n # Upload data and create a data asset URI folder\n print(\"Uploading data to blob storage\")\n my_data = Data(\n path=dataset_dir,\n type=AssetTypes.URI_FOLDER,\n description=\"Fridge-items images\",\n name=\"fridge-items-images-2\",\n )\n\n uri_folder_data_asset = ml_client.data.create_or_update(my_data)\n\n print(uri_folder_data_asset)\n print(\"\")\n print(\"Path to folder in Blob Storage:\")\n print(uri_folder_data_asset.path)\n create_jsonl_and_mltable_files(\n uri_folder_data_path=uri_folder_data_asset.path, dataset_dir=dataset_dir\n )\n\n\ndef read_image(image_path):\n with open(image_path, \"rb\") as f:\n return f.read()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Prepare data for image classification\"\n )\n\n parser.add_argument(\"--subscription\", type=str, help=\"Subscription ID\")\n parser.add_argument(\"--group\", type=str, help=\"Resource group name\")\n parser.add_argument(\"--workspace\", type=str, help=\"Workspace name\")\n parser.add_argument(\n \"--data_path\", type=str, default=\"./data\", help=\"Dataset location\"\n )\n\n args, unknown = parser.parse_known_args()\n args_dict = vars(args)\n\n credential = DefaultAzureCredential()\n ml_client = None\n subscription_id = args.subscription\n resource_group = args.group\n workspace = args.workspace\n ml_client = MLClient(credential, subscription_id, resource_group, workspace)\n\n upload_data_and_create_jsonl_mltable_files(\n ml_client=ml_client, dataset_parent_dir=args.data_path\n )\n\n sample_image = os.path.join(\n args.data_path, \"fridgeObjects\", \"milk_bottle\", \"99.jpg\"\n )\n huggingface_request_json = {\n \"input_data\": {\n \"columns\": [\"image\"],\n \"data\": [base64.encodebytes(read_image(sample_image)).decode(\"utf-8\")],\n }\n }\n huggingface_request_file_name = \"huggingface_sample_request_data.json\"\n with open(huggingface_request_file_name, \"w\") as huggingface_request_file:\n json.dump(huggingface_request_json, huggingface_request_file)\n","sub_path":"cli/foundation-models/system/finetune/image-classification/multiclass-classification/prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":6578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"237287507","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.views.generic import View\nfrom .models import Courses\nfrom IPython import embed\n\n\n# Create youer views here.\n\nclass Courses_view(View):\n def get(self,request):\n courses = Courses.course_list()\n course_list = []\n for course in courses:\n course = {'finish_date':course[0],'description': course[1], 'duration': course[2],'start_date': course[3], 'id':course[4],'coursename':course[5] }\n course_list.append(course)\n \n return render(request, 'courses/index.html',{'courses': course_list})\n def post(self,request):\n \n params = request.POST\n parameters = [params['finishdate'],params['description'],params['duration'],params['startdate'],params['coursename']]\n Courses.insert_course(parameters)\n\n return redirect('/academy/courses')\n\n\ndef delete_course(request,pk):\n Courses.delete_course(pk)\n return redirect('/academy/courses/')\n\n\ndef edit_course(request,pk):\n if request.method == 'GET':\n course = Courses.select_course(pk) \n start_date = '%s-%s-%s' % (course[3].year, course[3].month, course[3].day)\n finish_date = '%s-%s-%s' % (course[0].year, course[0].month, course[0].day)\n course = {'finish_date':finish_date ,'description': course[1], 'duration': course[2],'start_date': start_date, 'id':course[4],'coursename':course[5] }\n return render(request, 'courses/form_edit.html', {'course':course})\n elif request.method == 'POST':\n params = request.POST\n parameters = [params['course_id'], params['finishdate'],params['description'],params['duration'],params['startdate'],params['coursename']]\n Courses.update_course(parameters)\n return redirect('/academy/course/%s' % pk)\n\ndef course(request,pk):\n course = Courses.select_course(pk)\n course = {'finish_date':course[0],'description': course[1], 'duration': course[2],'start_date': course[3], 'id':course[4],'coursename':course[5] }\n return render(request, 'courses/course.html',{'course': course})\n\ndef form(request):\n return render(request, 'courses/form.html')\n\n\n\n\n\n\n\"\"\"\"\n\nEXAMPLE CODE OF SIMPLE HTML RENDERING\n\n# def index(request):\n# latest_question_list = Question.objects.order_by('-pub_date')[:5]\n# template = loader.get_template('polls/index.html')\n# context = {\n# 'latest_question_list': latest_question_list,\n# }\n# return HttpResponse(template.render(context, request))\n\n\"\"\"","sub_path":"academy/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"38916520","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n\"\"\"\n500 test samples\n\"\"\"\n\nfrom keras import models\nfrom PIL import Image\nimport numpy\nimport os\nimport shutil\n\n# import model\nmodel = models.load_model(\"new_structure.h5\")\n\n# get source root directory\nimage_dir_path = os.getcwd() + \"\\data\\predict\"\n\n# get each of picture's path\nimage_name_list = os.listdir(image_dir_path)\nimage_path_list = [os.path.join(image_dir_path, image_name) for image_name in image_name_list]\n\n# save classify result\nresult = dict()\nfor item in range(10):\n result[item] = []\n\n# predict\nfor name, path in zip(image_name_list, image_path_list):\n img = Image.open(path)\n img_array = numpy.array(img)\n img_array = img_array.reshape(1, 28, 28, 1)\n predict = model.predict_classes(img_array, 1, verbose=1)[0]\n result[predict].append((name, path))\n\n# get archive root directory\narchive_root_dir_path = os.getcwd() + \"\\data\\\\archive\"\n\n# archive\n# Example,if the prediction is 0, the picture will be moved to directory whose name is 0\nfor key, value in result.items():\n archive_dir_path = os.path.join(archive_root_dir_path, str(key))\n os.mkdir(archive_dir_path)\n\n for item in value:\n new_path = os.path.join(archive_dir_path, item[0])\n shutil.copy(item[1], new_path)\n","sub_path":"datum_process/predict_number.py","file_name":"predict_number.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"270473908","text":"#!/usr/bin/python3\n\nimport os\nimport pygame\n\npygame.init()\n\ndisplay_width = 800\ndisplay_height = 600\nblack = (0,0,0)\nwhite = (255,255,255)\n\ngameDisplay = pygame.display.set_mode((display_width,display_height))\npygame.display.set_caption('Testing')\n\n\nclock = pygame.time.Clock()\ncrashed = False\ncarImg = pygame.transform.scale2x(pygame.image.load('open.png'))\n\ndef car(x,y):\n gameDisplay.blit(pygame.transform.scale2x(carImg), (x,y))\n\nx = (display_width * 0.45)\ny = (display_height * 0.8)\n\ngameDisplay.fill(white)\ncar(x,y)\n\npygame.display.flip()\n\nwhile not crashed:\n\n# for event in pygame.event.get():\n# if event.type == pygame.QUIT:\n# crashed = True\n\n# print(event)\n y=y-1\n gameDisplay.fill(white)\n car(x,y)\n\n if y < 10:\n crashed = True\n\n pygame.display.flip()\n# clock.tick(10)\n\npygame.quit()\nquit()\n","sub_path":"gametest.py","file_name":"gametest.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"353707457","text":"# File: chaos.py\r\n# Created 12/11/18 by Macauley Tosi\r\n# A simple program illustrating chaotic behavior.\r\n\r\ndef main():\r\n print(\"This program illustrates a chaotic function\")\r\n x = eval(input(\"Enter a number between 0 and 1: \"))\r\n n = eval(input(\"How many numbers should i print? \"))\r\n for i in range(n):\r\n x = 3.9 * x - 3.9 * x * x \r\n print(x)\r\nmain()\r\n","sub_path":"Chaos.py","file_name":"Chaos.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"367539818","text":"import os\nfrom core import execute\nfrom core import utils\n\nclass ScreenShot(object):\n\t\"\"\"Screenshot all domain on common service\"\"\"\n\tdef __init__(self, options):\n\t\tutils.print_banner(\"Services Scanning\")\n\t\tutils.make_directory(options['env']['WORKSPACE'] + '/screenshot')\n\t\t# utils.make_directory(options['env']['WORKSPACE'] + '/screenshot/all')\n\t\tself.options = options\n\t\tself.initial()\n\n\t\t#check if the screenshot success or not, if not run it again\n\t\twhile True:\n\t\t\tif not os.listdir(utils.replace_argument(self.options, '$WORKSPACE/screenshot/')):\n\t\t\t\tutils.print_bad('Something wrong with these module ... run it again')\n\t\t\t\tself.initial()\n\t\t\telse:\n\t\t\t\tbreak\n\n\tdef initial(self):\n\t\tself.aquaton()\n\t\t# really slow the flow so disable for now\n\t\t# self.eyewitness_common()\n\n\tdef aquaton(self):\n\t\tutils.print_good('Starting aquatone')\n\t\tcmd ='cat $WORKSPACE/subdomain/final-$TARGET.txt | $GO_PATH/aquatone -threads 20 -out $WORKSPACE/screenshot/$OUTPUT-aquatone.html'\n\t\tcmd = utils.replace_argument(self.options, cmd)\n\t\tutils.print_info(\"Execute: {0} \".format(cmd))\n\t\texecute.run(cmd)\n\t\tutils.check_output(self.options, '$WORKSPACE/screenshot/$OUTPUT-aquatone.html')\n\n\n\tdef eyewitness_common(self):\n\t\tutils.print_good('Starting EyeWitness for web')\n\t\tcmd = 'python $PLUGINS_PATH/EyeWitness/EyeWitness.py -f $WORKSPACE/subdomain/final-$TARGET.txt --web --prepend-https --threads 20 -d $WORKSPACE/screenshot/eyewitness-$TARGET/'\t\n\t\tcmd = utils.replace_argument(self.options, cmd)\n\t\tutils.print_info(\"Execute: {0} \".format(cmd))\n\t\texecute.run(cmd)\n\t\tutils.check_output(self.options, '$WORKSPACE/screenshot/')\n\t\t\n","sub_path":"modules/screenshot.py","file_name":"screenshot.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"254479102","text":"import os\nimport pandas as pd\nimport pathlib\n\n\nimport airflow.utils.dates\nfrom airflow import DAG\nfrom airflow.operators.python import PythonOperator\nfrom airflow.sensors.python import PythonSensor\n\nfrom utils import *\n\n\ndef _wait_for_file(path: str):\n return os.path.exists(path)\n\n\ndef _predict(\n test_data_path: str,\n model_path: str,\n transformer_path: str,\n output_dir: str,\n):\n output_path = os.path.join(output_dir, 'predictions.csv')\n pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)\n\n data = pd.read_csv(test_data_path)\n transformer = load_pickle(transformer_path)\n features = transformer.transform(data)\n model = load_pickle(model_path)\n preds = model.predict(features)\n pd.DataFrame(np.array(preds).T, columns=['target']).to_csv(output_path, index=False)\n print(f'Predict test data and save into {output_path}')\n\n\nwith DAG(\n dag_id='predict',\n start_date=airflow.utils.dates.days_ago(1),\n schedule_interval='@daily',\n max_active_runs=1,\n) as dag:\n data_sensor = PythonSensor(\n task_id='data_sensor',\n python_callable=_wait_for_file,\n op_kwargs={'path': '/opt/airflow/data/raw/{{ ds }}/test.csv'},\n timeout=60,\n poke_interval=10,\n retries=100,\n mode='poke',\n )\n\n model_sensor = PythonSensor(\n task_id='model_sensor',\n python_callable=_wait_for_file,\n op_kwargs={'path': '{{ var.value.model_path }}'}, #Variable.get('model_path')},\n timeout=60,\n poke_interval=10,\n retries=100,\n mode='poke',\n )\n\n transformer_sensor = PythonSensor(\n task_id='transformer_sensor',\n python_callable=_wait_for_file,\n op_kwargs={'path': '{{ var.value.transformer_path }}'},\n timeout=60,\n poke_interval=10,\n retries=100,\n mode='poke',\n )\n\n predict = PythonOperator(\n task_id='predict',\n python_callable=_predict,\n op_kwargs={\n 'test_data_path': '/opt/airflow/data/raw/{{ ds }}/test.csv',\n 'model_path': '{{ var.value.model_path }}',\n 'transformer_path': '{{ var.value.transformer_path }}',\n 'output_dir': '/opt/airflow/data/predictions/{{ ds }}/',\n }\n )\n\n [data_sensor, model_sensor, transformer_sensor] >> predict\n","sub_path":"airflow_ml_dags/dags/dag_predict.py","file_name":"dag_predict.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"236169901","text":"# -*- coding: utf-8 -*-\n#COMECE AQUI ABAIXO\nn = int(input('Digite o número de termos: '))\nvalor = 0\nsoma = 0\nsomaQuadrada\nfor i in range(1,n+1,1):\n valor = float(input('Digite o valor do termo '+str(i)+': '))\n soma = soma+valor\n somaQuadrada=somaQuadrada+(valor**2)\nmedia = soma/n \ndesvio=((somaQuadrada/n)-(media**2))**0.5\n","sub_path":"moodledata/vpl_data/59/usersdata/251/44824/submittedfiles/testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"521019085","text":"class Solution:\n def nextPermutation(self, nums):\n \t# 倒序遍历\n for i in range(len(nums)-1, -1, -1):\n # 找到第一个数值变小的点,这样代表右边有大的可以和它换,而且可以保证是next permutation\n if i > 0 and nums[i] > nums[i-1]:\n # 找到后再次倒序遍历,找到第一个比刚才那个数值大的点,互相交换\n for j in range(len(nums)-1, i-1, -1):\n if nums[j] > nums[i-1]:\n nums[j], nums[i-1] = nums[i-1], nums[j]\n # 因为之前保证了,右边这段数从右到左是一直变大的,所以直接双指针reverse\n left, right = i, len(nums)-1\n while left <= right:\n nums[left], nums[right] = nums[right], nums[left]\n left += 1 \n right -= 1 \n return nums\n \t# 如果循环结束了,表示没找到能替换的数,表示序列已经是最大的了\n nums.reverse()\n return nums","sub_path":"python/2019/nextPermutation.py","file_name":"nextPermutation.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"24844427","text":"#!/usr/bin/env python \n#Guys WE GOT THE PICK AND PLACE!!!\n#The code for now is only a pick and place for cube C, it miss the pick and place for the others cubes\n#and the E that need the help of right arm\n\n\n#libraries \nfrom __future__ import print_function\n\nimport rospy\nimport sys\nimport copy\nimport time\nimport moveit_commander \nimport moveit_msgs.msg\nimport geometry_msgs.msg \nimport trajectory_msgs.msg\nfrom moveit_msgs.msg import Constraints, JointConstraint, PositionConstraint, OrientationConstraint, BoundingVolume\nfrom sensor_msgs.msg import JointState\nfrom moveit_msgs.msg import RobotState, RobotTrajectory\nfrom geometry_msgs.msg import Quaternion, Pose, PoseStamped\nfrom std_msgs.msg import String\nfrom moveit_commander.conversions import pose_to_list\nfrom human_baxter_collaboration.msg import BaxterTrajectory, UnityTf\n\nglobal my_data\n\n#callback for subscriber that we need for position of cubes and bluebox\ndef callback(data):\n global my_data\n my_data = data.frames\n #rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", data.frames)\n\n\ndef move_right(cube):\n global my_data, pub\n\n frame = cube\n\n move_group = moveit_commander.MoveGroupCommander('right_arm')\n #first field of baxter_msg, the arm \n baxter_msg = BaxterTrajectory()\n baxter_msg.arm = 'right'\n\n\n #setting of the initial state of the robot\n joint_state = JointState()\n joint_state.name = ['head_pan', 'right_s0', 'right_s1', 'right_e0', 'right_e1', 'right_w0', 'right_w1', 'right_w2', 'left_s0', 'left_s1', 'left_e0', 'left_e1', \n 'left_w0', 'left_w1', 'left_w2', 'l_gripper_l_finger_joint', 'l_gripper_r_finger_joint', 'r_gripper_l_finger_joint', 'r_gripper_r_finger_joint']\n joint_state.position = [0.0, 0.5235987755982988, -1.2217304763960306, 0.0, 1.7278759594743864, 0.0, 0.7504915783575616, 0.0, -0.5235987755982988, \n -1.2217304763960306, 0.0, 1.7278759594743864, 0.0, 0.7504915783575616, 0.0, 0.0, 0.0, 0.0, 0.0]\n moveit_robot_state = RobotState()\n moveit_robot_state.joint_state = joint_state\n move_group.set_start_state(moveit_robot_state)\n \n \n #Now the planning step \n #1st go over the cube\n #2nd pick the cube\n #3rd go up\n #4th place the cube in the bluebox\n #for doing each steps we need first the pose_goal of the robot, then do a plan&execute and\n #for updating the position we neeed the last position\n \n #################_FIRST STEP GO OVER THE CUBE_#################\n print(\"cube position: %s\", my_data[frame])\n pose_goal = geometry_msgs.msg.Pose()\n pose_goal.orientation.x = my_data[frame].pose.orientation.x\n pose_goal.orientation.y = my_data[frame].pose.orientation.y\n pose_goal.orientation.z = my_data[frame].pose.orientation.z\n pose_goal.orientation.w = my_data[frame].pose.orientation.w\n pose_goal.position.x = my_data[frame].pose.position.x \n pose_goal.position.y = my_data[frame].pose.position.y \n pose_goal.position.z = my_data[frame].pose.position.z + 0.2\n\n move_group.set_pose_target(pose_goal)\n plan_overcube = move_group.plan()\n move_group.execute(plan_overcube[1])\n\n joint_state = JointState()\n joint_state.name = move_group.get_active_joints()\n joint_state.position = move_group.get_current_joint_values()\n moveit_robot_state = RobotState()\n moveit_robot_state.joint_state = joint_state\n move_group.set_start_state(moveit_robot_state)\n ################################################################\n\n #################_SECOND STEP PICK THE CUBE_#################\n pose_goal = geometry_msgs.msg.Pose()\n pose_goal.orientation.x = my_data[frame].pose.orientation.x\n pose_goal.orientation.y = my_data[frame].pose.orientation.y\n pose_goal.orientation.z = my_data[frame].pose.orientation.z\n pose_goal.orientation.w = my_data[frame].pose.orientation.w\n pose_goal.position.x = my_data[frame].pose.position.x \n pose_goal.position.y = my_data[frame].pose.position.y \n pose_goal.position.z = my_data[frame].pose.position.z - 0.02\n\n move_group.set_pose_target(pose_goal)\n plan_pick = move_group.plan()\n move_group.execute(plan_pick[1])\n\n joint_state = JointState()\n joint_state.name = move_group.get_active_joints()\n joint_state.position = move_group.get_current_joint_values()\n moveit_robot_state = RobotState()\n moveit_robot_state.joint_state = joint_state\n move_group.set_start_state(moveit_robot_state)\n ################################################################\n\n #################_THIRD STEP GO AGAIN OVER THE CUBE_#################\n pose_goal = geometry_msgs.msg.Pose()\n pose_goal.orientation.x = my_data[frame].pose.orientation.x\n pose_goal.orientation.y = my_data[frame].pose.orientation.y\n pose_goal.orientation.z = my_data[frame].pose.orientation.z\n pose_goal.orientation.w = my_data[frame].pose.orientation.w\n pose_goal.position.x = my_data[frame].pose.position.x \n pose_goal.position.y = my_data[frame].pose.position.y \n pose_goal.position.z = my_data[frame].pose.position.z + 0.2\n \n move_group.set_pose_target(pose_goal)\n plan_cubeup = move_group.plan()\n move_group.execute(plan_cubeup[1])\n\n joint_state = JointState()\n joint_state.name = move_group.get_active_joints()\n joint_state.position = move_group.get_current_joint_values()\n moveit_robot_state = RobotState()\n moveit_robot_state.joint_state = joint_state\n move_group.set_start_state(moveit_robot_state)\n ################################################################\n\n #################_FOURTH STEP PLACE IN THE BLUEBOX_#################\n pose_goal = geometry_msgs.msg.Pose()\n pose_goal.orientation.x = my_data[23].pose.orientation.x\n pose_goal.orientation.y = my_data[23].pose.orientation.y\n pose_goal.orientation.z = my_data[23].pose.orientation.z\n pose_goal.orientation.w = my_data[23].pose.orientation.w\n pose_goal.position.x = my_data[23].pose.position.x \n pose_goal.position.y = my_data[23].pose.position.y \n pose_goal.position.z = my_data[23].pose.position.z + 0.1\n \n move_group.set_pose_target(pose_goal)\n plan_place = move_group.plan()\n move_group.execute(plan_place[1])\n\n joint_state = JointState()\n joint_state.name = move_group.get_active_joints()\n joint_state.position = move_group.get_current_joint_values()\n moveit_robot_state = RobotState()\n moveit_robot_state.joint_state = joint_state\n move_group.set_start_state(moveit_robot_state)\n ################################################################\n\n #second field of baxter_msg to fill, and all the plans go inside it\n baxter_msg.trajectory.extend([plan_overcube[1], plan_pick[1], plan_cubeup[1], plan_place[1]])\n\n #publish the message and see the simulation\n #time.sleep(10)\n \n pub.publish(baxter_msg)\n \n\n\n\n\n#our main function\ndef main():\n global my_data, pub\n #moveit_commander's initialization\n moveit_commander.roscpp_initialize(sys.argv)\n #node's initialization with publisher to /baxter_moveit_trajectory for move the robot\n #and subscriber to /unity_tf for the positions of objects\n rospy.init_node('move_right_arm')\n pub = rospy.Publisher(\"/baxter_moveit_trajectory\", BaxterTrajectory, queue_size=100)\n scene = moveit_commander.PlanningSceneInterface()\n time.sleep(2)\n box_pose = geometry_msgs.msg.PoseStamped()\n box_pose.header.frame_id = \"world\"\n box_pose.pose.orientation.x = 0.0\n box_pose.pose.orientation.y = 0.0\n box_pose.pose.orientation.z = 0.0\n box_pose.pose.position.x = 0.0\n box_pose.pose.position.y = 0.0\n box_pose.pose.position.z = 0.0\n box_name = \"table\"\n scene.add_box(box_name, box_pose, size=(1, 1, 1))\n rospy.Subscriber('/unity_tf', UnityTf, callback)\n time.sleep(1)\n \n \n #variables for logging robot state and the move_group that needs for moving right or left arm\n robot = moveit_commander.RobotCommander()\n scene = moveit_commander.PlanningSceneInterface()\n\n E_cube = 11\n M_cube = 20\n move_right(E_cube)\n move_right(M_cube)\n \n \n \n \n\nif __name__ == '__main__':\n main()\n ","sub_path":"human_baxter_collaboration/scripts/right_arm.py","file_name":"right_arm.py","file_ext":"py","file_size_in_byte":8113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"568168746","text":"#!/usr/bin/env python3\n\nimport setuptools\n\nwith open(\"README.md\") as readme:\n long_description = readme.read()\n\nsetuptools.setup(\n name=\"potodo\",\n version=\"0.5.0\",\n description=\"Will list all .po files that are to be transated\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\", # This is important!\n author=\"Jules Lasne\",\n author_email=\"jules.lasne@gmail.com\",\n url=\"https://github.com/seluj78/potodo\",\n packages=[\"potodo\"],\n package_dir={\"potodo\": \"potodo\"},\n entry_points={\"console_scripts\": [\"potodo=potodo.potodo:main\"]},\n include_package_data=True,\n install_requires=[\"polib\", \"requests\"],\n license=\"MIT license\",\n zip_safe=False,\n keywords=\"potodo\",\n classifiers=[\n \"Development Status :: 2 - Pre-Alpha\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Natural Language :: English\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"652060668","text":"import pygame\nfrom random import randint\nfrom pprint import pprint\nimport math\n\ndef main():\n pygame.init() \n screen = pygame.display.set_mode((600, 400))\n w, h = pygame.display.get_surface().get_size()\n xc, yc = w//2, h//2\n r = 150\n running = True\n #clock = pygame.time.Clock()\n WHITE = (255, 255, 255)\n BLACK = (0, 0, 0)\n RED = (255, 0, 0)\n GREEN = (0, 255, 0)\n screen.fill(WHITE)\n\n\n def get_random_dot():\n x = randint(0, w)\n y = randint(0, h)\n return x, y\n\n while running:\n col = RED\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n \n pygame.draw.circle(screen, BLACK, (xc, yc), r, 4)\n xp, yp = get_random_dot()\n d = math.sqrt(math.pow((xp - xc), 2) + math.pow((yp - yc), 2))\n if d < r-1:\n col = GREEN\n pygame.draw.circle(screen, col, (xp, yp), 3, 0)\n pygame.display.flip()\n #clock.tick(240)\n\n\nif __name__==\"__main__\":\n main()\n","sub_path":"cirlce_rand_dots.py","file_name":"cirlce_rand_dots.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"652597721","text":"\"\"\"\nWrite an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:\n* Integers in each row are sorted from left to right.\n* The first integer of each row is greater than the last integer of the previous row.\n\nInput: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\nOutput: true\n\nbinary search: log(m*n)\n\"\"\"\n\nfrom typing import List\n\ndef searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n M, N = len(matrix), len(matrix[0])\n low, high = 0, M * N - 1\n \n while low <= high:\n mid = (low + high) // 2\n num = matrix[mid // N][mid % N]\n if target == num:\n return True\n elif target < num:\n high = mid - 1\n else:\n low = mid + 1\n return False\n","sub_path":"others/matrix_search.py","file_name":"matrix_search.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"571904697","text":"from __future__ import absolute_import, division, print_function\n\nimport libtbx.phil\n\nhelp_message = '''\n\n'''\n\nphil_scope= libtbx.phil.parse(\"\"\"\ninclude scope dials.util.options.geometry_phil_scope\noutput {\n datablock = modified_datablock.json\n .type = path\n experiments = modified_experiments.json\n .type = path\n}\n\"\"\", process_includes=True)\n\n\ndef run(args):\n\n from dials.util.options import OptionParser\n from dials.util.options import flatten_datablocks\n from dials.util.options import flatten_experiments\n import libtbx.load_env\n\n usage = \"%s [options] datablock.json | experiments.json\" %(\n libtbx.env.dispatcher_name)\n\n parser = OptionParser(\n usage=usage,\n phil=phil_scope,\n read_datablocks=True,\n read_experiments=True,\n check_format=False,\n epilog=help_message)\n\n params, options = parser.parse_args(show_diff_phil=True)\n experiments = flatten_experiments(params.input.experiments)\n datablocks = flatten_datablocks(params.input.datablock)\n\n if len(experiments) == 0 and len(datablocks) == 0:\n parser.print_help()\n exit(0)\n\n from dials.command_line.dials_import import ManualGeometryUpdater\n update_geometry = ManualGeometryUpdater(params)\n\n if len(experiments):\n imagesets = experiments.imagesets()\n\n elif len(datablocks):\n\n assert len(datablocks) == 1\n imagesets = datablocks[0].extract_imagesets()\n\n for imageset in imagesets:\n imageset_new = update_geometry(imageset)\n imageset.set_detector(imageset_new.get_detector())\n imageset.set_beam(imageset_new.get_beam())\n imageset.set_goniometer(imageset_new.get_goniometer())\n imageset.set_scan(imageset_new.get_scan())\n\n from dxtbx.serialize import dump\n if len(experiments):\n print(\"Saving modified experiments to %s\" %params.output.experiments)\n dump.experiment_list(experiments, params.output.experiments)\n elif len(datablocks):\n print(\"Saving modified datablock to %s\" %params.output.datablock)\n dump.datablock(datablocks, params.output.datablock)\n\nif __name__ == '__main__':\n import sys\n run(sys.argv[1:])\n","sub_path":"command_line/modify_geometry.py","file_name":"modify_geometry.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"60910430","text":"import torch\nfrom torchvision import transforms as transform\nfrom torch.utils.data import dataloader\nimport utils\nimport loss\nimport time\nfrom models import *\nfrom data import *\nfrom option import args\nfrom test_model import test\n\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else 'cpu')\nresult = []\n\ndef main():\n train_transforms = transform.Compose([\n transform.Resize(256),\n transform.CenterCrop(224),\n transform.RandomHorizontalFlip(),\n transform.ToTensor(),\n transform.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ])\n\n val_transforms = transform.Compose([\n transform.Resize(256), \n transform.CenterCrop(224),\n transform.RandomHorizontalFlip(),\n transform.ToTensor(),\n transform.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ])\n \n\n # weight = get_weight()\n # size = len(weight)*2\n # weights = torch.Tensor(weight)\n # wei_sampler = torch.utils.data.sampler.WeightedRandomSampler(weights, size, True)\n\n train_dataset = Dataset(args, train_transforms, 'train')\n # train_loader = dataloader.DataLoader(train_dataset, batch_size=8, num_workers = 0, sampler = wei_sampler)\n train_loader = dataloader.DataLoader(train_dataset, batch_size=8, num_workers=0, shuffle=True)\n val_dataset = Dataset(args, val_transforms, 'val')\n val_loader = dataloader.DataLoader(val_dataset, shuffle = True, batch_size=8, drop_last=True, num_workers=0)\n net = VitAge()\n net = nn.DataParallel(net).cuda()\n rank = torch.Tensor([i for i in range(101)]).cuda()\n for i in range(60):\n lr = 0.001 if i < 30 else 0.0001\n optimizer = utils.make_optimizer(args, net, lr)\n print('Learning rate:{}'.format(lr))\n start_time = time.time()\n for j, inputs in enumerate(train_loader):\n img, label, age = inputs\n img = img.to(device)\n label = label.to(device)\n age = age.to(device)\n optimizer.zero_grad()\n outputs = net(img)\n ages = torch.sum(outputs*rank, dim=1)\n loss1 = loss.kl_loss(outputs, label)\n loss2 = loss.L1_loss(ages, age)\n total_loss = loss1 + loss2\n total_loss.backward()\n optimizer.step()\n current_time = time.time()\n print('[Epoch:{}] \\t[batch:{}]\\t[loss={:.4f}]'.format(i, j, total_loss.item()))\n start_time = time.time()\n torch.save(net, './pretrained/{}.pt'.format(args.model_name))\n torch.save(net.state_dict(), './pretrained/{}_dict.pt'.format(args.model_name))\n print('Test: Epoch=[{}]'.format(i))\n torch.save(net, 'out_model/vit_pretrained.pth')\n\nif __name__=='__main__':\n main()\n","sub_path":"main_vit.py","file_name":"main_vit.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"86059075","text":"import unittest\nimport scipy.io.wavfile as wavfile\nfrom scipy.signal import spectrogram\nimport numpy as np\nimport random\nimport os\nimport ec602lib\n\n# framerate * tone_time must be 800 for extract to work\nrefcode={'lines':18,'words':99}\n\nprogname = \"dialer.py\"\n\nDialerTests = [('6', 8000, 0.1), \n('19', 8000, 0.1), \n('321', 4000, 0.2), \n('147', 8000, 0.1), \n('258', 8000, 0.1), \n('963', 8000, 0.1), \n('9123456780', 8000, 0.1), \n('8675309', 8000, 0.1), \n('6178675309', 16000, 0.05)]\n\n\nDTMF = {'3': (697, 1477), '8': (852, 1336), '9': (852, 1477), '7': (852, 1209), '5': (770, 1336), '1': (697, 1209), '2': (697, 1336), '4': (770, 1209), '0': (941, 1336), '6': (770, 1477)}\n\ndef extract_digits(signal,frame_rate):\n tone_length = 200\n\n f,t,Sxx= spectrogram(signal,fs=frame_rate,window='boxcar',nperseg=tone_length)\n\n df = frame_rate//tone_length\n\n mapDTMF={}\n for dig in DTMF:\n mapDTMF[tuple(f[round(x/df)] for x in DTMF[dig])] = dig\n\n last=None\n\n result=[]\n i = 0 \n while i1:\n result.append((mapDTMF[top_freq],count))\n return \"\".join(x[0] for x in result)\n\n\n\nclass DialerTestCase(unittest.TestCase):\n def test_signal(self):\n \"a. extract touch tones from wave file\"\n for dig,frame_rate,time_of_tone in DialerTests:\n with self.subTest(CASE= dig):\n error = None\n try:\n n = random.randint(10000,1000000)\n fname='studentdialer{}.wav'.format(n)\n dialer(fname,frame_rate,dig,time_of_tone)\n st_frame_rate, st_signal=wavfile.read(fname)\n os.remove(fname)\n except Exception as e:\n error = e\n\n if error:\n self.fail('Reading from the created wav file failed. Exception: {}'.format(error))\n\n # test rate\n if st_frame_rate != frame_rate:\n self.fail('Frame rate mismatch: {} vs {}'.format(st_frame_rate,frame_rate))\n\n # test shape\n N = int(len(dig)*time_of_tone*frame_rate)\n if (N,) != st_signal.shape:\n self.fail('Shape mismatch: {} vs {}'.format((N,),st_signal.shape))\n\n\n\n # test digit creation\n result_digits = extract_digits(st_signal, st_frame_rate)\n if result_digits != dig:\n self.fail('Detect tones mismatch: {} vs {}'.format(result_digits,dig))\n \n\n\n\nif __name__ == '__main__':\n from dialer import dialer\n _,results,_ = ec602lib.overallpy(progname,DialerTestCase,refcode)\n #unittest.main()\n print(results)\n\n unittest.main()","sub_path":"HWK7/dialer_checker.py","file_name":"dialer_checker.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"232382377","text":"from .LoadTpl import *\n\n\nclass Player:\n _playername: str = ''\n _raiting: int = 0\n\n def __init__(self, q, instance_url):\n self._q = q\n self._instance_url = instance_url\n\n def show(self, self_id):\n print(loadTpl('show_player').format(\n self._q['student'].value,\n self_id,\n self._playername,\n self._raiting\n ))\n\n def show_edit(self):\n print(loadTpl('save_player').format(\n self._instance_url,\n self._q['student'].value,\n self._q['player_id'].value,\n True,\n self._playername,\n self._raiting\n ))\n\n def set_parameters(self):\n self._playername = self._q['playername'].value\n self._raiting = self._q['raiting'].value\n\n def set_q_and_url(self, q, _instance_url):\n self._q = q\n self._instance_url = _instance_url","sub_path":"cgi-bin/st25/Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"203632963","text":"#-*-coding: utf-8-*-\nfrom socket import *\nfrom threading import Thread\n#este programa es para una clase que estoy haciendo en la escuela\nclass Master:\n\tdef __init__(self, host, port):\n\t\tself.sock = socket(AF_INET, SOCK_STREAM)\n\t\tself.sock.bind((host, port))\n\t\tself.sock.listen(1)\n\tdef hearPrey(self):\n\t\tself.conn, addr = self.sock.accept()\n\t\tprint(addr)\n\t\tself.conn.settimeout(0.0)\n\t\twhile True:\n\t\t\ttry: \n\t\t\t\tmsj = self.conn.recv(3072)\n\t\t\t\tmsj = msj.decode()\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tprint(\"{}\\n\".format(msj))\n\tdef huntPrey(self):\n\t\tcmd = \"\"\n\t\twhile cmd != \"exit\":\n\t\t\tcmd = input(\">>>\")\n\t\t\tself.conn.send(cmd.encode())\n\t\texit()\n\ndef getMyIp():\n\ts = socket(AF_INET, SOCK_DGRAM)\n\ts.connect((\"8.8.8.8\", 80))\n\treturn s.getsockname()[0]\ndef main():\n\tserver = Master(\"127.0.0.1\", 5000)\n\tears = Thread(target=server.hearPrey)\n\tears.deamon = True\n\tears.start()\n\tserver.huntPrey()\n\nif __name__ == '__main__':\n\tmain()","sub_path":"cacadevaca.py","file_name":"cacadevaca.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"375357857","text":"from django.urls import path\nfrom django.urls import re_path\nfrom . import views\n\napp_name = \"public\"\nurlpatterns = [\n path('ajax_search_categories', views.ajax_search_categories, name='ajax_search_categories'),\n path('ajax_control_email', views.ajax_control_email, name='ajax_control_email'),\n path('ajax_get_messages', views.ajax_get_messages, name='ajax_get_messages'),\n path('ajax_set_new_message', views.ajax_set_new_message, name='ajax_set_new_message'),\n path('ajax_send_sms', views.ajax_send_sms, name=\"ajax_send_sms\"),\n path('ajax_control_sms_code', views.ajax_control_sms_code, name=\"ajax_control_sms_code\"),\n path('ajax_approved_phone_number', views.ajax_approved_phone_number, name=\"ajax_approved_phone_number\")\n]\n","sub_path":"otomabak/public/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"184067757","text":"from collections import OrderedDict\nimport numpy as np\n\nfrom torch import optim as optim\n\nfrom rlkit.misc.eval_util import create_stats_ordered_dict\nfrom rlkit.policies.simple import RandomPolicy\nfrom rlkit.samplers.util import rollout\nfrom rlkit.torch import pytorch_util as ptu\nfrom rlkit.torch.torch_rl_algorithm import TorchRLAlgorithm\nfrom rlkit.torch.data_management.normalizer import TorchFixedNormalizer\n\n\nclass ModelTrainer(TorchRLAlgorithm):\n def __init__(\n self,\n env,\n model,\n mpc_controller,\n obs_normalizer: TorchFixedNormalizer=None,\n action_normalizer: TorchFixedNormalizer=None,\n delta_normalizer: TorchFixedNormalizer=None,\n num_paths_for_normalization=0,\n learning_rate=1e-3,\n exploration_policy=None,\n **kwargs\n ):\n if exploration_policy is None:\n exploration_policy = mpc_controller\n super().__init__(\n env,\n exploration_policy=exploration_policy,\n eval_policy=mpc_controller,\n **kwargs\n )\n self.model = model\n self.mpc_controller = mpc_controller\n self.learning_rate = learning_rate\n self.optimizer = optim.Adam(\n self.model.parameters(),\n lr=self.learning_rate,\n )\n self.obs_normalizer = obs_normalizer\n self.action_normalizer = action_normalizer\n self.delta_normalizer = delta_normalizer\n self.num_paths_for_normalization = num_paths_for_normalization\n\n def _do_training(self):\n losses = []\n if self.collection_mode == 'batch':\n \"\"\"\n Batch mode we'll assume you want to do epoch-style training\n \"\"\"\n all_obs = self.replay_buffer._observations[:self.replay_buffer._top]\n all_actions = self.replay_buffer._actions[:self.replay_buffer._top]\n all_next_obs = self.replay_buffer._next_obs[:self.replay_buffer._top]\n\n num_batches = len(all_obs) // self.batch_size\n idx = np.asarray(range(len(all_obs)))\n np.random.shuffle(idx)\n for bn in range(num_batches):\n idxs = idx[bn*self.batch_size: (bn+1)*self.batch_size]\n obs = all_obs[idxs]\n actions = all_actions[idxs]\n next_obs = all_next_obs[idxs]\n\n obs = ptu.np_to_var(obs, requires_grad=False)\n actions = ptu.np_to_var(actions, requires_grad=False)\n next_obs = ptu.np_to_var(next_obs, requires_grad=False)\n\n ob_deltas_pred = self.model(obs, actions)\n ob_deltas = next_obs - obs\n if self.delta_normalizer:\n normalized_errors = (\n self.delta_normalizer.normalize(ob_deltas_pred)\n - self.delta_normalizer.normalize(ob_deltas)\n )\n squared_errors = normalized_errors**2\n else:\n squared_errors = (ob_deltas_pred - ob_deltas)**2\n loss = squared_errors.mean()\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n losses.append(ptu.get_numpy(loss))\n else:\n batch = self.get_batch()\n obs = batch['observations']\n actions = batch['actions']\n next_obs = batch['next_observations']\n ob_deltas_pred = self.model(obs, actions)\n ob_deltas = next_obs - obs\n if self.delta_normalizer:\n normalized_errors = (\n self.delta_normalizer.normalize(ob_deltas_pred)\n - self.delta_normalizer.normalize(ob_deltas)\n )\n squared_errors = normalized_errors**2\n else:\n squared_errors = (ob_deltas_pred - ob_deltas)**2\n loss = squared_errors.mean()\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n losses.append(ptu.get_numpy(loss))\n\n if self.need_to_update_eval_statistics:\n self.need_to_update_eval_statistics = False\n self.eval_statistics.update(create_stats_ordered_dict(\n 'Model Loss',\n losses,\n always_show_all_stats=True,\n exclude_max_min=True,\n ))\n self.eval_statistics.update(create_stats_ordered_dict(\n 'Obs Deltas',\n ptu.get_numpy(ob_deltas),\n ))\n self.eval_statistics.update(create_stats_ordered_dict(\n 'Predicted Obs Deltas',\n ptu.get_numpy(ob_deltas_pred),\n ))\n\n def pretrain(self):\n if (\n self.num_paths_for_normalization == 0\n or (self.obs_normalizer is None and self.action_normalizer is None)\n ):\n return\n\n pretrain_paths = []\n random_policy = RandomPolicy(self.env.action_space)\n while len(pretrain_paths) < self.num_paths_for_normalization:\n path = rollout(self.env, random_policy, self.max_path_length)\n pretrain_paths.append(path)\n ob_mean, ob_std, delta_mean, delta_std, ac_mean, ac_std = (\n compute_normalization(pretrain_paths)\n )\n if self.obs_normalizer is not None:\n self.obs_normalizer.set_mean(ob_mean)\n self.obs_normalizer.set_std(ob_std)\n if self.delta_normalizer is not None:\n self.delta_normalizer.set_mean(delta_mean)\n self.delta_normalizer.set_std(delta_std)\n if self.action_normalizer is not None:\n self.action_normalizer.set_mean(ac_mean)\n self.action_normalizer.set_std(ac_std)\n\n def _can_evaluate(self):\n return self.eval_statistics is not None\n\n @property\n def networks(self):\n return [\n self.model\n ]\n\n def get_epoch_snapshot(self, epoch):\n snapshot = super().get_epoch_snapshot(epoch)\n snapshot['model'] = self.model\n snapshot['mpc_controller'] = self.mpc_controller\n return snapshot\n\n def offline_evaluate(self, epoch):\n return self.evaluate(epoch)\n\n\ndef compute_normalization(paths):\n obs = np.vstack([path[\"observations\"] for path in paths])\n next_obs = np.vstack([path[\"next_observations\"] for path in paths])\n deltas = next_obs - obs\n ob_mean = np.mean(obs, axis=0)\n ob_std = np.std(obs, axis=0)\n delta_mean = np.mean(deltas, axis=0)\n delta_std = np.std(deltas, axis=0)\n actions = np.vstack([path[\"actions\"] for path in paths])\n ac_mean = np.mean(actions, axis=0)\n ac_std = np.std(actions, axis=0)\n return ob_mean, ob_std, delta_mean, delta_std, ac_mean, ac_std\n","sub_path":"rlkit/torch/mpc/model_trainer.py","file_name":"model_trainer.py","file_ext":"py","file_size_in_byte":6843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"326718432","text":"from scipy.io import loadmat\nimport numpy as np\nfrom zyradlib import tools as dt\nfrom zyradlib import utilities as ut\nfrom zyradlib import datamanager as dec\nimport os\nimport pickle\n\nmatfile = loadmat('D:\\TestData\\deneme.mat')\n\nData_mat = matfile['Data']\n\nData_raw = Data_mat.transpose()\ntime = len(Data_raw[1]) / 1000\ntime = np.arange(0, time, 0.001)\nData_raw[0] = time\n\n# ut.peekData(time, Data_raw[22])\n# ut.peekData(time, Data_raw[20])\n# ut.peekData(time, Data_raw[19])\n#\nut.peekData(time, Data_raw[11])\nut.peekData(time, Data_raw[10]) # resolver\nut.peekData(time, Data_raw[8])\n\n# whole data\n# start = 52000 # 73000\n# end = 191000\n\n#trimmed data\nstart = 52000 # 73000\nend = 100000\n\n#\nstart = 1000 # 73000\nend = 35000\n\nData_raw = ut.pickfromrange(range(start, end), Data_raw)\n\ntime = Data_raw[0]\n\n# raw data + column numbers + labels ==> Data class dictionary labeled with variable names\n# preDataDict = dec.genPreDataDict(Data_raw, [11, 9, 8] , ['trq', 'gyro', 'enc'])\n# preDataDict = dec.genPreDataDict(Data_raw, [22, 20, 19], ['trq', 'gyro', 'enc'])\n\nut.peekData(time, Data_raw[11])\nut.peekData(time, Data_raw[10]) # resolver\nut.peekData(time, Data_raw[8])\n\npreDataDict = dec.genPreDataDict(Data_raw, [11, 10, 8], ['trq', 'resspd', 'enc'])\ninp = []\ntgt = []\n# windows = [3, 5, 8, 13, 21, 34, 55, 89, 144] # window is defined in number of samples\nwindows = [13, 21, 55]\ntarget_delay = 10 # samples to be delayed for output\nfor label in preDataDict:\n temp_Data = preDataDict[label]\n print('Processing ' + label)\n for window in windows:\n print('-Processing window:' + str(window))\n runMean_temp, diff_temp = dt.meandiff(time, temp_Data.Data, window)\n inp.append(temp_Data.Data[:-target_delay])\n inp.append(runMean_temp[:-target_delay])\n inp.append(diff_temp[:-target_delay])\n if not label == 'trq':\n tgt.append(temp_Data.Data[target_delay:])\n\nwith open(os.path.dirname(__file__) + '/../data/traindata_13_21_55.p', 'wb') as fp:\n pickle.dump([inp, tgt], fp)\n\n# out = pickle.load(open(\"/../data/traindata.p\", \"rb\"))\n","sub_path":"zyradscripts/generateTrainDataSet.py","file_name":"generateTrainDataSet.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"338477554","text":"\"\"\"The request for analysis by a client. It contains analysis instances.\n\n$Id: AnalysisRequest.py 2567 2010-09-27 14:51:15Z anneline $\n\"\"\"\nfrom AccessControl import ClassSecurityInfo\nfrom AccessControl.Permissions import delete_objects\nfrom DateTime import DateTime\nfrom Products.ATContentTypes.content import schemata\nfrom Products.ATExtensions.ateapi import DateTimeField, DateTimeWidget\nfrom Products.ATExtensions.widget.records import RecordsWidget\nfrom Products.Archetypes import atapi\nfrom Products.Archetypes.config import REFERENCE_CATALOG\nfrom Products.Archetypes.public import *\nfrom Products.Archetypes.references import HoldingReference\nfrom Products.Archetypes.utils import shasattr\nfrom Products.CMFCore import permissions\nfrom Products.CMFCore.WorkflowCore import WorkflowException\nfrom Products.CMFCore.permissions import View, ModifyPortalContent\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFPlone.utils import transaction_note\nfrom bika.lims.browser.fields import ARAnalysesField\nfrom bika.lims.config import I18N_DOMAIN, PROJECTNAME, \\\n ManageInvoices\nfrom bika.lims.content.bikaschema import BikaSchema\nfrom bika.lims.interfaces import IAnalysisRequest\nfrom bika.lims.utils import sortable_title, generateUniqueId\nfrom decimal import Decimal\nfrom email.Utils import formataddr\nfrom types import ListType, TupleType\nfrom zope.app.component.hooks import getSite\nfrom zope.interface import implements\nimport sys\nimport time\nfrom bika.lims import bikaMessageFactory as _\n\nschema = BikaSchema.copy() + Schema((\n StringField('RequestID',\n required = 1,\n searchable = True,\n widget = StringWidget(\n label = 'Request ID',\n label_msgid = 'label_requestid',\n description = 'The ID assigned to the client''s request by the lab',\n description_msgid = 'help_requestid',\n i18n_domain = I18N_DOMAIN,\n visible = {'edit':'hidden'},\n ),\n ),\n ReferenceField('Contact',\n required = 1,\n vocabulary = 'getContactsDisplayList',\n default_method = 'getContactUIDForUser',\n vocabulary_display_path_bound = sys.maxint,\n allowed_types = ('Contact',),\n referenceClass = HoldingReference,\n relationship = 'AnalysisRequestContact',\n ),\n ReferenceField('CCContact',\n multiValued = 1,\n vocabulary = 'getContactsDisplayList',\n vocabulary_display_path_bound = sys.maxint,\n allowed_types = ('Contact',),\n referenceClass = HoldingReference,\n relationship = 'AnalysisRequestCCContact',\n ),\n ReferenceField('Attachment',\n multiValued = 1,\n allowed_types = ('Attachment',),\n referenceClass = HoldingReference,\n relationship = 'AnalysisRequestAttachment',\n ),\n StringField('CCEmails',\n widget = StringWidget(\n label = 'CC Emails',\n label_msgid = 'label_ccemails',\n i18n_domain = I18N_DOMAIN,\n ),\n ),\n ReferenceField('Sample',\n required = 1,\n vocabulary_display_path_bound = sys.maxint,\n allowed_types = ('Sample',),\n referenceClass = HoldingReference,\n relationship = 'AnalysisRequestSample',\n ),\n ARAnalysesField('Analyses',\n required = 1,\n ),\n StringField('ClientOrderNumber',\n searchable = True,\n widget = StringWidget(\n label = 'Client Order ID',\n label_msgid = 'label_client_order_id',\n i18n_domain = I18N_DOMAIN,\n ),\n ),\n ReferenceField('Invoice',\n vocabulary_display_path_bound = sys.maxint,\n allowed_types = ('Invoice',),\n referenceClass = HoldingReference,\n relationship = 'AnalysisRequestInvoice',\n ),\n ReferenceField('Profile',\n allowed_types = ('ARProfile',),\n referenceClass = HoldingReference,\n relationship = 'AnalysisRequestProfile',\n ),\n BooleanField('InvoiceExclude',\n default = False,\n widget = BooleanWidget(\n label = \"Invoice Exclude\",\n label_msgid = \"label_invoice_exclude\",\n description = \"Select if analyses to be excluded from invoice\",\n description_msgid = 'help_invoiceexclude',\n ),\n ),\n BooleanField('ReportDryMatter',\n default = False,\n widget = BooleanWidget(\n label = \"Report as dry matter\",\n label_msgid = \"label_report_dry_matter\",\n description = \"Select if result is to be reported as dry matter\",\n description_msgid = 'help_report_dry_matter',\n ),\n ),\n DateTimeField('DateRequested',\n required = 1,\n default_method = 'current_date',\n widget = DateTimeWidget(\n label = 'Date requested',\n label_msgid = 'label_daterequested',\n visible = {'edit':'hidden'},\n ),\n ),\n DateTimeField('DateReceived',\n widget = DateTimeWidget(\n label = 'Date received',\n label_msgid = 'label_datereceived',\n visible = {'edit':'hidden'},\n ),\n ),\n DateTimeField('DatePublished',\n widget = DateTimeWidget(\n label = 'Date published',\n label_msgid = 'label_datepublished',\n visible = {'edit':'hidden'},\n ),\n ),\n TextField('Notes',\n default_content_type = 'text/plain',\n allowable_content_types = ('text/plain',),\n widget = TextAreaWidget(\n label = 'Notes'\n ),\n ),\n FixedPointField('MemberDiscount',\n default_method = 'getDefaultMemberDiscount',\n widget = DecimalWidget(\n label = 'Member discount %',\n label_msgid = 'label_memberdiscount_percentage',\n description = 'Enter percentage value eg. 33.0',\n description_msgid = 'help_memberdiscount_percentage',\n i18n_domain = I18N_DOMAIN,\n ),\n ),\n ComputedField('ClientUID',\n expression = 'here.aq_parent.UID()',\n widget = ComputedWidget(\n visible = False,\n ),\n ),\n ComputedField('ClientReference',\n expression = 'here.getSample() and here.getSample().getClientReference()' ,\n widget = ComputedWidget(\n visible = False,\n ),\n ),\n ComputedField('ClientSampleID',\n expression = 'here.getSample() and here.getSample().getClientSampleID()',\n widget = ComputedWidget(\n visible = False,\n ),\n ),\n ComputedField('SampleTypeTitle',\n expression = \"here.getSample() and here.getSample().getSampleType() and here.getSample().getSampleType().Title() or ''\",\n widget = ComputedWidget(\n visible = False,\n ),\n ),\n ComputedField('SamplePointTitle',\n expression = \"here.getSample() and here.getSample().getSamplePoint() and here.getSample().getSamplePoint().Title() or ''\",\n widget = ComputedWidget(\n visible = False,\n ),\n ),\n ComputedField('SampleUID',\n expression = 'here.getSample() and here.getSample().UID()',\n widget = ComputedWidget(\n visible = False,\n ),\n ),\n ComputedField('ContactUID',\n expression = 'here.getContact() and here.getContact().UID()',\n widget = ComputedWidget(\n visible = False,\n ),\n ),\n ComputedField('ProfileUID',\n expression = 'here.getProfile( and here.getProfile().UID()',\n widget = ComputedWidget(\n visible = False,\n ),\n ),\n),\n)\n\nschema['title'].required = False\n\nclass AnalysisRequest(BaseFolder):\n implements(IAnalysisRequest)\n security = ClassSecurityInfo()\n schema = schema\n displayContentsTab = False\n\n _has_dependant_calcs = False\n\n def hasBeenInvoiced(self):\n if self.getInvoice():\n return True\n else:\n return False\n\n def Title(self):\n \"\"\" Return the Request ID as title \"\"\"\n return self.getRequestID()\n\n security.declarePublic('generateUniqueId')\n def generateUniqueId (self, type_name, batch_size = None):\n return generateUniqueId(self, type_name, batch_size)\n\n def getDefaultMemberDiscount(self):\n \"\"\" compute default member discount if it applies \"\"\"\n if hasattr(self, 'getMemberDiscountApplies'):\n if self.getMemberDiscountApplies():\n plone = getSite()\n settings = plone.bika_setup\n return settings.getMemberDiscount()\n else:\n return \"0.00\"\n\n security.declareProtected(View, 'getResponsible')\n def getResponsible(self):\n \"\"\" Return all manager info of responsible departments \"\"\"\n managers = {}\n departments = []\n for analysis in self.objectValues('Analysis'):\n department = analysis.getService().getDepartment()\n if department is None:\n continue\n department_id = department.getId()\n if department_id in departments:\n continue\n departments.append(department_id)\n manager = department.getManager()\n if manager is None:\n continue\n manager_id = manager.getId()\n if not managers.has_key(manager_id):\n managers[manager_id] = {}\n managers[manager_id]['name'] = manager.getFullname()\n managers[manager_id]['email'] = manager.getEmailAddress()\n managers[manager_id]['phone'] = manager.getBusinessPhone()\n managers[manager_id]['signature'] = '%s/Signature' % manager.absolute_url()\n managers[manager_id]['dept'] = ''\n mngr_dept = managers[manager_id]['dept']\n if mngr_dept:\n mngr_dept += ', '\n mngr_dept += department.Title()\n managers[manager_id]['dept'] = mngr_dept\n mngr_keys = managers.keys()\n mngr_info = {}\n mngr_info['ids'] = mngr_keys\n mngr_info['dict'] = managers\n\n return mngr_info\n\n security.declareProtected(View, 'getResponsible')\n def getManagers(self):\n \"\"\" Return all managers of responsible departments \"\"\"\n manager_ids = []\n manager_list = []\n departments = []\n for analysis in self.objectValues('Analysis'):\n department = analysis.getService().getDepartment()\n if department is None:\n continue\n department_id = department.getId()\n if department_id in departments:\n continue\n departments.append(department_id)\n manager = department.getManager()\n if manager is None:\n continue\n manager_id = manager.getId()\n if not manager_id in manager_ids:\n manager_ids.append(manager_id)\n manager_list.append(manager)\n\n return manager_list\n\n security.declareProtected(View, 'getLate')\n def getLate(self):\n \"\"\" return True if any analyses are late \"\"\"\n wf_tool = getToolByName(self, 'portal_workflow')\n review_state = wf_tool.getInfoFor(self, 'review_state', '')\n if review_state in ['sample_due', 'published']:\n return False\n\n now = DateTime()\n for analysis in self.objectValues('Analysis'):\n review_state = wf_tool.getInfoFor(analysis, 'review_state', '')\n if review_state == 'published':\n continue\n if analysis.getDueDate() < now:\n return True\n return False\n\n security.declareProtected(View, 'getBillableItems')\n def getBillableItems(self):\n \"\"\" Return all items except those in 'not_requested' state \"\"\"\n wf_tool = getToolByName(self, 'portal_workflow')\n items = []\n for analysis in self.objectValues('Analysis'):\n review_state = wf_tool.getInfoFor(analysis, 'review_state', '')\n if review_state != 'not_requested':\n items.append(analysis)\n return items\n\n security.declareProtected(View, 'getSubtotal')\n def getSubtotal(self):\n \"\"\" Compute Subtotal\n XXX invoked MANY times during a single AR's creation\n \"\"\"\n return sum(\n [Decimal(obj.getService() and obj.getService().getPrice() or 0) \\\n for obj in self.getBillableItems()])\n\n security.declareProtected(View, 'getVAT')\n def getVAT(self):\n \"\"\" Compute VAT \"\"\"\n return Decimal(self.getTotalPrice()) - Decimal(self.getSubtotal())\n\n security.declareProtected(View, 'getTotalPrice')\n def getTotalPrice(self):\n \"\"\" Compute TotalPrice \"\"\"\n billable = self.getBillableItems()\n TotalPrice = Decimal(0, 2)\n for item in billable:\n service = item.getService()\n if not service:\n # XXX invokeFactory can cause us to be catalogued before we're ready.\n return Decimal(0, 2)\n itemPrice = Decimal(service.getPrice() or 0)\n VAT = Decimal(service.getVAT() or 0)\n TotalPrice += Decimal(itemPrice) * (Decimal(1, 2) + VAT)\n return TotalPrice\n getTotal = getTotalPrice\n\n def setDryMatterResults(self):\n \"\"\" get results of analysis requiring DryMatter reporting \"\"\"\n analyses = []\n DryMatter = None\n settings = getToolByName(self, 'bika_setup')\n dry_service = settings.getDryMatterService()\n for analysis in self.getAnalyses(full_objects = True):\n if analysis.getReportDryMatter():\n analyses.append(analysis)\n try:\n if analysis.getServiceUID() == dry_service.UID():\n DryMatter = Decimal(analysis.getResult())\n except:\n DryMatter = None\n\n for analysis in analyses:\n if DryMatter:\n try:\n wet_result = Decimal(analysis.getResult())\n except:\n wet_result = None\n if DryMatter and wet_result:\n dry_result = '%.2f' % ((wet_result / DryMatter) * 100)\n else:\n dry_result = None\n analysis.setResultDM(dry_result)\n\n return\n\n security.declareProtected(ManageInvoices, 'issueInvoice')\n def issueInvoice(self, REQUEST = None, RESPONSE = None):\n \"\"\" issue invoice\n \"\"\"\n # check for an adhoc invoice batch for this month\n now = DateTime()\n batch_month = now.strftime('%b %Y')\n batch_title = '%s - %s' % (batch_month, 'ad hoc')\n invoice_batch = None\n for b_proxy in self.portal_catalog(portal_type = 'InvoiceBatch',\n Title = batch_title):\n invoice_batch = b_proxy.getObject()\n if not invoice_batch:\n first_day = DateTime(now.year(), now.month(), 1)\n start_of_month = first_day.earliestTime()\n last_day = first_day + 31\n while last_day.month() != now.month():\n last_day = last_day - 1\n end_of_month = last_day.latestTime()\n\n invoices = self.invoices\n batch_id = invoices.generateUniqueId('InvoiceBatch')\n invoices.invokeFactory(id = batch_id, type_name = 'InvoiceBatch')\n invoice_batch = invoices._getOb(batch_id)\n invoice_batch.edit(\n title = batch_title,\n BatchStartDate = start_of_month,\n BatchEndDate = end_of_month,\n )\n invoice_batch.processForm()\n\n client_uid = self.getClientUID()\n invoice_batch.createInvoice(client_uid, [self, ])\n\n RESPONSE.redirect(\n '%s/analysisrequest_invoice' % self.absolute_url())\n\n security.declarePublic('printInvoice')\n def printInvoice(self, REQUEST = None, RESPONSE = None):\n \"\"\" print invoice\n \"\"\"\n invoice = self.getInvoice()\n invoice_url = invoice.absolute_url()\n RESPONSE.redirect('%s/invoice_print' % invoice_url)\n\n def addARAttachment(self, REQUEST = None, RESPONSE = None):\n \"\"\" Add the file as an attachment\n \"\"\"\n workflow = getToolByName(self, 'portal_workflow')\n\n this_file = self.REQUEST.form['AttachmentFile_file']\n if self.REQUEST.form.has_key('Analysis'):\n analysis_uid = self.REQUEST.form['Analysis']\n else:\n analysis_uid = None\n\n attachmentid = self.generateUniqueId('Attachment')\n self.aq_parent.invokeFactory(id = attachmentid, type_name = \"Attachment\")\n attachment = self.aq_parent._getOb(attachmentid)\n attachment.edit(\n AttachmentFile = this_file,\n AttachmentType = self.REQUEST.form['AttachmentType'],\n AttachmentKeys = self.REQUEST.form['AttachmentKeys'])\n attachment.processForm()\n attachment.reindexObject()\n\n if analysis_uid:\n tool = getToolByName(self, REFERENCE_CATALOG)\n analysis = tool.lookupObject(analysis_uid)\n others = analysis.getAttachment()\n attachments = []\n for other in others:\n attachments.append(other.UID())\n attachments.append(attachment.UID())\n analysis.setAttachment(attachments)\n if workflow.getInfoFor(analysis, 'review_state') == 'attachment_due':\n workflow.doActionFor(analysis, 'attach')\n else:\n others = self.getAttachment()\n attachments = []\n for other in others:\n attachments.append(other.UID())\n attachments.append(attachment.UID())\n\n self.setAttachment(attachments)\n\n RESPONSE.redirect(\n '%s/manage_results' % self.absolute_url())\n\n def delARAttachment(self, REQUEST = None, RESPONSE = None):\n \"\"\" delete the attachment \"\"\"\n tool = getToolByName(self, REFERENCE_CATALOG)\n if self.REQUEST.form.has_key('ARAttachment'):\n attachment_uid = self.REQUEST.form['ARAttachment']\n attachment = tool.lookupObject(attachment_uid)\n parent = attachment.getRequest()\n elif self.REQUEST.form.has_key('AnalysisAttachment'):\n attachment_uid = self.REQUEST.form['AnalysisAttachment']\n attachment = tool.lookupObject(attachment_uid)\n parent = attachment.getAnalysis()\n\n others = parent.getAttachment()\n attachments = []\n for other in others:\n if not other.UID() == attachment_uid:\n attachments.append(other.UID())\n parent.setAttachment(attachments)\n client = attachment.aq_parent\n ids = [attachment.getId(), ]\n BaseFolder.manage_delObjects(client, ids, REQUEST)\n\n RESPONSE.redirect(\n '%s/manage_results' % self.absolute_url())\n\n security.declarePublic('getContactUIDForUser')\n def get_verifier(self):\n wtool = getToolByName(self, 'portal_workflow')\n mtool = getToolByName(self, 'portal_membership')\n\n verifier = None\n try:\n review_history = wtool.getInfoFor(self, 'review_history')\n except:\n return 'access denied'\n\n if not review_history:\n return 'no history'\n for items in review_history:\n action = items.get('action')\n if action != 'verify':\n continue\n actor = items.get('actor')\n member = mtool.getMemberById(actor)\n verifier = member.getProperty('fullname')\n if verifier is None or verifier == '':\n verifier = actor\n return verifier\n\n security.declarePublic('getContactUIDForUser')\n def getContactUIDForUser(self):\n \"\"\" get the UID of the contact associated with the authenticated\n user\n \"\"\"\n user = self.REQUEST.AUTHENTICATED_USER\n user_id = user.getUserName()\n r = self.portal_catalog(\n portal_type = 'Contact',\n getUsername = user_id\n )\n if len(r) == 1:\n return r[0].UID\n\n security.declarePublic('getCCDisplays')\n def getCCDisplays(self):\n \"\"\" get a string of titles of the contacts\n \"\"\"\n cc_uids = ''\n cc_titles = ''\n for cc in self.getCCContact():\n if cc_uids:\n cc_uids = cc_uids + ', ' + cc.UID()\n cc_titles = cc_titles + ', ' + cc.Title()\n else:\n cc_uids = cc.UID()\n cc_titles = cc.Title()\n return [cc_uids, cc_titles]\n\n security.declareProtected(delete_objects, 'manage_delObjects')\n def manage_delObjects(self, ids = [], REQUEST = None):\n \"\"\" recalculate state from remaining analyses \"\"\"\n BaseFolder.manage_delObjects(self, ids, REQUEST)\n #self._escalateWorkflowAction()\n\n security.declarePublic('current_date')\n def current_date(self):\n \"\"\" return current date \"\"\"\n return DateTime()\n\natapi.registerType(AnalysisRequest, PROJECTNAME)\n","sub_path":"bika/lims/content/analysisrequest.py","file_name":"analysisrequest.py","file_ext":"py","file_size_in_byte":21008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"317485983","text":"# Basic addition calculator\ntry:\n # Get the first number\n number_input = input('Enter the first number: ')\n # Parse the string input as an integer\n number_one = int(number_input)\n\n# In case the user doesn't give an integer\n\nexcept:\n number_one = int(input('Please enter a whole number: '))\n\n# Repeat the process for the second number\ntry:\n number_input = input('Enter the second number: ')\n number_two = int(number_input)\nexcept:\n number_two = int(input('Please enter a whole number: '))\n\n\n# Add the numbers together as part of the output\nprint('The answer is', number_one + number_two)","sub_path":"pythonProj/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"539503740","text":"import numpy as np\nfrom numpy.core.fromnumeric import size\nfrom numpy.lib.type_check import imag\nimport open3d as o3d\nfrom config import Config as cfg\nimport os.path as op\nfrom PIL import Image\n# import cv2 \nimport matplotlib.pyplot as plt\nfrom kitti_util import Calibration\nfrom transformation import Transformation\nfrom torchvision import transforms\n\n# import torch\n\n\nclass LidarCluster:\n def projection_img(self, images, pcd, cal, labels):\n # file = '{0:06d}.png' .format(index)\n pts = np.asarray(pcd.points)\n bottom = np.ones((pts.shape[0],1))\n\n pts = np.concatenate((pts, bottom), axis=1)\n\n V2C = cal.V2C\n v2c = np.vstack((V2C, [0,0,0,1]))\n\n pts_c = np.dot(v2c, pts.T)\n pts_v = pts_c[:3, :]\n cal.P = cal.P[:3,:3]\n\n projection = np.dot(cal.P, pts_v)\n projection = projection / projection[2, :]\n\n proj = projection[:2, :]\n image_n = np.array(images)\n img_shape = image_n.shape\n # print('img shape:', img_shape)\n img = images\n # print('img shape:', img_shape)\n # tf = transforms.ToPILImage()\n # img = tf(images)\n\n img_n = np.array(img)\n\n zeros = np.zeros((img_shape[0],img_shape[1]))\n # print(zeros.shape)\n for i in (range(proj.shape[1])):\n x = int(proj[0][i])\n y = int(proj[1][i])\n # print(x,y)\n if (0 0:\n black = np.zeros((img_n.shape[0],img_n.shape[1]))\n # print('unique index:', index)\n split_index = np.where(zeros == i)\n # tf224 = Transformation(224) \n resize_list = cfg.Lidar_set.resize_list\n for (a, b, c, d) in resize_list:\n cluster_target = {}\n\n y1, x1, y2, x2 = np.min(split_index[0]) + a, np.min(split_index[1]) + b, np.max(split_index[0]) + c, np.max(split_index[1]) + d\n crop_axis_x = np.array([x1, x2])\n crop_axis_y = np.array([y1, y2])\n crop_axis_x = np.clip(crop_axis_x, 0, img_n.shape[1])\n crop_axis_y = np.clip(crop_axis_y, 0, img_n.shape[0])\n crop_axis = np.array([crop_axis_x[0], crop_axis_y[0], crop_axis_x[1], crop_axis_y[1]])\n # print('crop axis : ' , crop_axis)\n crop_img = img.crop((crop_axis))\n # img = np.array(img)\n # crop_img = img[crop_axis[0]:crop_axis[2], crop_axis[1]:crop_axis[3],: ]\n # print(crop_img)\n black[split_index] = i\n # trnasform image\n # print('test:',crop_img.size)\n # print('img shape:', np.array(crop_img).shape)\n # try:\n # # image = tf224(crop_img)\n # # plt.imshow(crop_img)\n # # plt.show()\n # images.append(crop_img)\n # bboxes.append([crop_axis])\n # except:\n # continue\n if (crop_img.size[0] != 0) and (crop_img.size[1] != 0):\n # image = tf224(crop_img)\n # plt.imshow(crop_img)\n # plt.show()\n images.append(crop_img)\n bboxes.append([crop_axis])\n\n\n # print('bbbb:', bboxes)\n # select_region = Propose_region(images, bboxes)\n # plt.imshow(crop_img)\n # plt.show()\n return images, bboxes\n\n\n def preprocess(self, points):\n x_range, y_range, z_range = (3, 30), (-15, 15), (-1.3, 2.5)\n # print(points.shape)\n points1 = points[np.logical_and.reduce((points[:,0] > x_range[0], points[:,0] < x_range[1], \\\n points[:,1] > y_range[0], points[:,1] < y_range[1], \\\n points[:,2] > z_range[0], points[:,2] < z_range[1]))]\n # points[:,2 ] = 0\n x_range, y_range, z_range = (30, 60), (-15, 15), (-1.3, 2.5)\n # print(points.shape)\n points2 = points[np.logical_and.reduce((points[:,0] > x_range[0], points[:,0] < x_range[1], \\\n points[:,1] > y_range[0], points[:,1] < y_range[1], \\\n points[:,2] > z_range[0], points[:,2] < z_range[1]))]\n\n eps_ = 10\n m_points = 20\n z_axis = points1[:, 2].copy() * 50\n # print('z_axis:',z_axis)\n points1[:, 2] = 0\n points1 = points1 * 50\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(points1)\n # pcd = pcd.voxel_down_sample(voxel_size=0.2)\n pcd.paint_uniform_color([0.5, 0.5, 0.5]) \n\n with o3d.utility.VerbosityContextManager(\n o3d.utility.VerbosityLevel.Debug) as cm:\n # print('cluster: ',len(pcd.cluster_dbscan(eps=eps_, min_points=m_points)))\n labels = np.array(\n pcd.cluster_dbscan(eps=eps_, min_points=m_points, print_progress=False))\n\n target_pcd = np.asarray(pcd.points)\n # target = np.array(target_pcd)\n\n target_pcd[:, 2] = z_axis\n # print('target:', target_pcd)\n point_list = []\n # print(labels.shape)\n for i in range(0, labels.max()+1):\n num = labels[ labels == i]\n # print(f'num: {i}', len(num)) \n if (len(num) < 2500) or (i == 0):\n target = target_pcd[ labels == i]\n # print(target.shape)\n point_list.extend(target)\n\n eps_ = 20\n m_points = 20\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(point_list)\n pcd.paint_uniform_color([0.5, 0.5, 0.5]) \n\n with o3d.utility.VerbosityContextManager(\n o3d.utility.VerbosityLevel.Debug) as cm:\n # print('cluster: ',len(pcd.cluster_dbscan(eps=eps_, min_points=m_points)))\n labels = np.array(\n pcd.cluster_dbscan(eps=eps_, min_points=m_points, print_progress=False))\n\n max_label = labels.max()\n # print(f\"point cloud has {max_label+1} clusters\")\n\n colors1 = plt.get_cmap(\"tab20\")(labels / (max_label if max_label > 0 else 1))\n colors1[labels < 0] = 0\n\n\n pcd.colors = o3d.utility.Vector3dVector(colors1[:, :3])\n\n return pcd, labels\n\n def view_points(self, pts):\n # print('proj',proj.shape)\n # zeros = np.zeros((proj.shape[1])).reshape((1, -1))\n # pts = np.concatenate((proj, zeros), axis=0)\n # print('pts:',pts.shape)\n pts = pts.T\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(pts)\n pcd = pcd.voxel_down_sample(voxel_size=0.9)\n pcd.paint_uniform_color([0.5, 0.5, 0.5]) \n # print(\"bbox:\", x)\n eps_ = 0.5\n m_points = 10\n with o3d.utility.VerbosityContextManager(\n o3d.utility.VerbosityLevel.Debug) as cm:\n # print('cluster: ',len(pcd.cluster_dbscan(eps=eps_, min_points=m_points)))\n labels = np.array(\n pcd.cluster_dbscan(eps=eps_, min_points=m_points, print_progress=False))\n\n max_label = labels.max()\n # print(f\"point cloud has {max_label+1} clusters\")\n\n colors = plt.get_cmap(\"tab20\")(labels / (max_label if max_label > 0 else 1))\n colors[labels < 0] = 0\n pcd.colors = o3d.utility.Vector3dVector(colors[:, :3])\n\n # o3d.visualization.draw_geometries([pcd],\n # zoom=0.7,\n # front=[0.5439, -0.2333, -0.8060],\n # lookat=[2.4615, 2.1331, 1.338],\n # up=[-0.1781, -0.9708, 0.1608]) \n\n def __call__(self, images,lidar, targets, cal):\n\n points = lidar['points']\n\n pcd, labels = self.preprocess(points)\n images, bboxes = self.projection_img(images, pcd, cal, labels) \n check = len(np.unique(labels))\n return images, bboxes, check\n\n\n# def main(index):\n \n# velo_index = '{0:06d}.bin' .format(index)\n# cal_index = '{0:06d}.txt' .format(index) \n# cal_path = op.join(cfg.CALPATH, cal_index)\n# cal = Calibration(cal_path)\n# points = np.fromfile(op.join(cfg.VELOPATH, velo_index), dtype=np.float32).reshape(-1, 4)\n# # points = np.asarray()\n# intensity = points[:, 3]\n# # print(intensity.shape)\n# # z_axis = points[:, 2]\n# points = points[:, 0:3]\n\n# pcd, labels = preprocess(points)\n# images, bboxes = projection_img(index, pcd, cal, labels) \n# # view_points(proj)\n\n\n# if __name__ == \"__main__\":\n# for index in range(200):\n# main(index)\n\n","sub_path":"cluster_part.py","file_name":"cluster_part.py","file_ext":"py","file_size_in_byte":9196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"454042110","text":"def solution(citations):\n answer = 0\n sortedCitations = sorted(citations)\n\n for i in range(len(sortedCitations)):\n h = len(sortedCitations) - i\n\n if i <= h <= sortedCitations[i] and h > answer:\n answer = h\n\n return answer\n\n# def solution(citations):\n# citations.sort(reverse=True)\n# answer = max(map(min, enumerate(citations, start=1)))\n# return answer\n\nif __name__ == '__main__':\n print(solution([0, 1, 4, 4, 6]))\n","sub_path":"python/programmers/sort/H-index.py","file_name":"H-index.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"251504556","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom selenium.webdriver.chrome.options import Options\nfrom datetime import datetime, date, timedelta\nfrom selenium import webdriver\nfrom lxml import etree\nimport requests\nimport re, csv, os\nimport time\nfrom selenium.webdriver.chrome.service import Service\n\ndef _write_log(name, txt, s, log_path, len_data=0):\n with open('./logs/{}/{}.txt'.format(log_path, name), 'a', encoding='utf-8') as f:\n if s == 1:\n f.write('采集开始'+txt+'\\n')\n elif s == 2:\n f.write('结束采集,满足条件计入数据\\n')\n f.write('剩余'+str(len_data)+'场比赛\\n')\n elif s == 3:\n f.write('结束采集,比赛75分钟前没有发生6个进球\\n')\n f.write('剩余' + str(len_data) + '场比赛\\n')\n elif s == 4:\n f.write('该链接抓取失败,尝试重抓\\n')\n f.write('剩余' + str(len_data) + '场比赛\\n')\n elif s == 5:\n f.write('没有详细事件\\n')\n f.write('剩余' + str(len_data) + '场比赛\\n')\n\n\ndef _get_page(new_url):\n \"\"\"打开页面,返回html\"\"\"\n # 实现无可视化界面的操作\n c_service = Service(r'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe')\n c_service.command_line_args()\n c_service.start()\n chrome_options = Options()\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument('blink-settings=imagesEnabled=false')\n driver = webdriver.Chrome(chrome_options=chrome_options) # 参数添加\n driver.set_page_load_timeout(10)\n try:\n driver.get(new_url)\n time.sleep(1)\n page_text = driver.page_source\n driver.quit()\n c_service.stop()\n return page_text\n except:\n print('访问超时')\n driver.quit()\n c_service.stop()\n\n\ndef _go_daxiaoqiu(id):\n zcdxp = ''\n zcdqsw = ''\n sjq = ''\n url = 'http://vip.win007.com/changeDetail/overunder.aspx?id={}&companyID=3&l=0'.format(id)\n html = etree.HTML(_get_page(url))\n tr_list3 = html.xpath('//*[@id=\"odds2\"]/table//tr')\n sj = html.xpath('//*[@id=\"odds2\"]/table//tr/td[1]/text()')\n if tr_list3:\n if '中场' in sj:\n zcdxp, zcdqsw, sjq = _get_zcdata(tr_list3)\n if not zcdxp:\n if '45' in sj:\n zcdxp, zcdqsw, sjq = _get_45data(tr_list3)\n if not zcdxp:\n if '46' in sj:\n zcdxp, zcdqsw, sjq = _get_46data(tr_list3)\n elif '46' in sj:\n zcdxp, zcdqsw, sjq = _get_46data(tr_list3)\n elif '45' in sj:\n zcdxp, zcdqsw, sjq = _get_45data(tr_list3)\n if not zcdxp:\n if '46' in sj:\n zcdxp, zcdqsw, sjq = _get_46data(tr_list3)\n elif '46' in sj:\n zcdxp, zcdqsw, sjq = _get_46data(tr_list3)\n return [zcdxp, zcdqsw, sjq]\n else:\n print('无大小球变化表')\n return ['无大小球变化表', '无大小球变化表', '无大小球变化表']\n\n\ndef _get_zcdata(tr_list3):\n zcdxp = ''\n zcdqsw = ''\n sjq = ''\n for tr in tr_list3:\n if tr.xpath('./td[1]/text()') == ['中场']:\n if tr.xpath('./td[3]//b/text()') != ['封']:\n # 中场大小盘\n zcdxp = tr.xpath('./td[4]/font/text()')[0]\n # print(zcdxp)\n # 中场大球水位\n zcdqsw = tr.xpath('./td[3]//b/text()')[0] + '/' + tr.xpath('./td[5]//b/text()')[0]\n # 上半场进球\n sjq = tr.xpath('./td[2]/text()')[0].split('-')\n sjq = int(sjq[0]) + int(sjq[1])\n break\n return [zcdxp, zcdqsw, sjq]\n\n\ndef _get_45data(tr_list3):\n zcdxp = ''\n zcdqsw = ''\n sjq = ''\n for tr in tr_list3:\n if tr.xpath('./td[1]/text()') == ['45']:\n if tr.xpath('./td[3]//b/text()') != ['封']:\n # 中场大小盘\n zcdxp = tr.xpath('./td[4]/font/text()')[0]\n # print(zcdxp)\n # 中场大球水位\n zcdqsw = tr.xpath('./td[3]//b/text()')[0] + '/' + tr.xpath('./td[5]//b/text()')[0]\n # 上半场进球\n sjq = tr.xpath('./td[2]/text()')[0].split('-')\n sjq = int(sjq[0]) + int(sjq[1])\n break\n return [zcdxp, zcdqsw, sjq]\n\n\ndef _get_46data(tr_list3):\n zcdxp = ''\n zcdqsw = ''\n sjq = ''\n for tr in tr_list3:\n if tr.xpath('./td[1]/text()') == ['46']:\n if tr.xpath('./td[3]//b/text()') != ['封']:\n # 中场大小盘\n zcdxp = tr.xpath('./td[4]/font/text()')[0]\n # print(zcdxp)\n # 中场大球水位\n zcdqsw = tr.xpath('./td[3]//b/text()')[0] + '/' + tr.xpath('./td[5]//b/text()')[0]\n # 上半场进球\n sjq = tr.xpath('./td[2]/text()')[0].split('-')\n sjq = int(sjq[0]) + int(sjq[1])\n return [zcdxp, zcdqsw, sjq]\n\n\ndef _go_xiangxishijian(id):\n notimeurl = 'http://live.win007.com/detail/{}cn.htm'.format(id)\n eh = etree.HTML(_get_page(notimeurl))\n trs = eh.xpath('.//*[@id=\"teamEventDiv_detail\"]//tr')\n if len(trs) > 1:\n tr = trs[1]\n zzjqs = int(tr.xpath('./td[1]//text()')[0]) + int(tr.xpath('./td[3]//text()')[0])\n sjq = 0 # 上半场���球数\n jqs80 = 0 # 80分钟后进球\n jqs75 = 0 # 75分钟后进球\n for i in trs[2:]:\n if i.xpath('./td[2]/text()') == ['点球']:\n break\n elif i.xpath('./td[2]/text()') == ['时间']:\n continue\n else:\n jq = i.xpath('./td[2]/img/@title')\n jq2 = i.xpath('./td[4]/img/@title')\n if jq == ['入球'] or jq == ['点球'] or jq == ['乌龙'] or \\\n jq2 == ['入球'] or jq2 == ['点球'] or jq2 == ['乌龙']:\n jqtime = i.xpath('./td[3]//text()')[0][:-1]\n if '+' not in jqtime:\n jqtime = int(jqtime)\n elif '+' in jqtime:\n jqtime = int(jqtime.split('+')[0])\n if jqtime <= 45:\n sjq += 1\n if jqtime >= 75:\n jqs75 += 1\n if jqtime >= 80:\n jqs80 += 1\n return [sjq, zzjqs, jqs75, jqs80]\n else:\n print('没有详细事件')\n return ['没有详细事件', '没有详细事件', '没有详细事件', '没有详细事件']\n\n\ndef _daxiaoqiu_get_jinqiushuju(id):\n zzjqs = ''\n jqs80 = ''\n jqs75 = ''\n after80 = ''\n after75 = ''\n url = 'http://vip.win007.com/changeDetail/overunder.aspx?id={}&companyID=3&l=0'.format(id)\n html = etree.HTML(_get_page(url))\n tr_list3 = html.xpath('//*[@id=\"odds2\"]/table//tr')\n tr = tr_list3[1]\n if tr.xpath('./td[2]/text()') and int(tr.xpath('./td[1]/text()')[0]) > 80:\n zzjqs = tr.xpath('./td[2]/text()')[0].split('-')\n zzjqs = int(zzjqs[0]) + int(zzjqs[1])\n # 75分钟80分钟后进球数\n s = True\n for tr in tr_list3:\n if tr.xpath('./td[1]/text()'):\n if int(tr.xpath('./td[1]/text()')[0]) <= 79 and s:\n # 80分钟进球数\n s = False\n jqs80 = tr.xpath('./td[2]/text()')[0].split('-')\n jqs80 = int(jqs80[0]) + int(jqs80[1])\n if int(tr.xpath('./td[1]/text()')[0]) <= 74:\n # 75分钟进球数\n jqs75 = tr.xpath('./td[2]/text()')[0].split('-')\n jqs75 = int(jqs75[0]) + int(jqs75[1])\n after80 = zzjqs - jqs80\n after75 = zzjqs - jqs75\n break\n return [zzjqs, after75, after80]\n\n\ndef _write_csv(data, csv_path):\n \"\"\"将数据写入csv\"\"\"\n with open(csv_path, 'a', encoding='utf_8_sig', newline='') as f:\n data = [str(i) + '\\t' for i in data]\n w = csv.writer(f)\n w.writerow(data)\n\n\ndef create_csv(csv_path):\n \"\"\"创建存储数据的csv\"\"\"\n with open(csv_path, 'w', encoding='utf_8_sig', newline='') as f:\n f.write(\n '当日链接,比赛详情链接,日期,联赛名,主队,客队,初盘亚盘,终盘亚盘,终盘亚盘水位,初盘大球盘口,终盘大球盘口,终盘大球水位,中场大小盘,中场大球水位,上半场进球数,最终进球数,下半场75前进球数,75分钟后进球数,80分钟后进球数\\n')\n\n\ndef _get_75data(html):\n before75 = 0\n html = etree.HTML(html)\n trs = html.xpath('.//*[@id=\"teamEventDiv_detail\"]//tr')\n if len(trs) > 1:\n for i in trs[1:]:\n if i.xpath('./td[2]/text()') == ['点球']:\n break\n elif i.xpath('./td[2]/text()') == ['时间']:\n continue\n else:\n jq = i.xpath('./td[2]/img/@title')\n jq2 = i.xpath('./td[4]/img/@title')\n if jq == ['入球'] or jq == ['点球'] or jq == ['乌龙'] or \\\n jq2 == ['入球'] or jq2 == ['点球'] or jq2 == ['乌龙']:\n jqtime = i.xpath('./td[3]//text()')[0][:-1]\n if '+' not in jqtime:\n jqtime = int(jqtime)\n elif '+' in jqtime:\n jqtime = int(jqtime.split('+')[0])\n if jqtime < 75:\n before75 += 1\n return before75\n else:\n print('没有详细事件')\n return '没有详细事件'\n\n\ndef _get_yz(url):\n html = _get_page(url)\n if html != '':\n tree = etree.HTML(html)\n # 时间\n time1 = tree.xpath('//div[@class=\"vs\"]/div[1]/text()')\n time1 = ''.join(time1).strip().split(' ')[0].replace('-','.')\n # 联赛名\n LName = tree.xpath('//a[@class=\"LName\"]/text()')[0].strip()\n # 主场球队\n home = tree.xpath('//*[@class=\"header\"]//*[@class=\"home\"]/a/text()')[0]\n home = home.split(' ')[0]\n # 客场球队\n guest = tree.xpath('//*[@class=\"header\"]//*[@class=\"guest\"]/a/text()')[0]\n guest = guest.strip()\n cpyp, zpyp, zpypsw = ['没有Crown','没有Crown','没有Crown']\n tr_list = tree.xpath('//*[@id=\"odds\"]//tr')\n for tr in tr_list:\n # print(tr.xpath('./td[1]/text()'))\n if tr.xpath('./td[1]/text()') == ['Crown']:\n cpyp = tr.xpath('./td[4]/text()')[0] # 初盘亚盘\n zpyp = tr.xpath('./td[10]/text()')[0] # 终盘亚盘\n # 终盘亚盘水位\n zpypsw = tr.xpath('./td[9]/text()')[0] + '/' + tr.xpath('./td[11]/text()')[0]\n break\n return [time1, LName, home, guest, cpyp, zpyp, zpypsw]\n else:\n print('亚指页面为无内容')\n return ['亚指页面为无内容', '亚指页面为无内容', '亚指页面为无内容', '亚指页面为无内容', '亚指页面为无内容', '亚指页面为无内容', '亚指页面为无内容']\n\n\ndef _get_dx(url):\n html = _get_page(url)\n if html != '':\n tree = etree.HTML(html)\n tr_list = tree.xpath('//*[@id=\"odds\"]//tr')\n cp, zp, zpdqsw = ['没有Crown', '没有Crown', '没有Crown']\n for tr in tr_list:\n if tr.xpath('./td[1]/text()') == ['Crown']:\n cp = tr.xpath('./td[4]/text()')[0] # 初盘大球盘口\n zp = tr.xpath('./td[10]/text()')[0] # 终盘大球盘口\n # 终盘大球水位\n zpdqsw = tr.xpath('./td[9]/text()')[0] + '/' + tr.xpath('./td[11]/text()')[0]\n break\n return [cp, zp, zpdqsw]\n else:\n print('大小页面为无内容')\n return ['大小页面为无内容', '大小页面为无内容', '大小页面为无内容']\n\n\ndef first_login(url, csv_path, log_path):\n log_name = url[-12:-4]\n print(\"开始采集{}数据\".format(log_name))\n with open('./logs/{}/{}.txt'.format(log_path, log_name), 'w', encoding='utf-8') as f:\n f.write(\"开始采集{}数据{}\\n\".format(url, str(datetime.now())))\n page_text = _get_page(url)\n # print(page_text)\n reobj = re.compile(\n r'[\\d\\D]*?[\\d\\D]*?',re.MULTILINE)\n num_list = reobj.findall(page_text)\n # print(num_list)\n num_list2 = ['http://live.win007.com/detail/{}cn.htm'.format(i)\\\n for i in num_list] # 单场比赛详细事件页面\n # print(len(num_list2))\n # print(num_list2)\n _second_login(num_list2, url, log_name, csv_path, log_path)\n with open('./logs/{}/{}.txt'.format(log_path, log_name), 'a', encoding='utf-8') as f:\n f.write(\"结束采集{}\\n\".format(str(datetime.now())))\n return None\n\n\ndef _second_login(num_list2, date_url, log_name, csv_path, log_path):\n boolen = False\n while num_list2:\n url = num_list2.pop(0)\n _write_log(log_name, url, 1, log_path)\n data = [date_url, url]\n try:\n html = _get_page(url)\n before75 = _get_75data(html)\n if before75 == '没有详细事件':\n print('没有详细事件')\n _write_log(log_name, url, 5, log_path, len(num_list2))\n elif before75 == 6:\n # 发生了6个进球,收集数据\n id = url[-13:-6]\n yzurl = 'http://vip.win007.com/AsianOdds_n.aspx?id={}'.format(id)\n # print(yzurl)\n time1, LName, home, guest, cpyp, zpyp, zpypsw = _get_yz(yzurl)\n # print(time1, LName, home, guest, cpyp, zpyp, zpypsw)\n data += [time1, LName, home, guest, cpyp, zpyp, zpypsw]\n # print(data)\n dxurl = 'http://vip.win007.com/OverDown_n.aspx?id={}&l=0'.format(id)\n cp, zp, zpdqsw = _get_dx(dxurl)\n data += [cp, zp, zpdqsw]\n zcdxp, zcdqsw, sjq = _go_daxiaoqiu(id)\n if zcdxp == '无大小球变化表':\n # 没有大小球变化表\n sjq, zzjqs, jqs75, jqs80 = _go_xiangxishijian(id)\n data.append(zcdxp)\n data.append(zcdqsw)\n data.append(sjq)\n data.append(zzjqs)\n if zzjqs != '没有详细事件':\n before75_sjq = before75 - sjq\n data.append(before75_sjq)\n else:\n data.append('无大小球变化表也没有详细事件')\n data.append(jqs75)\n data.append(jqs80)\n elif not zcdxp and not zcdqsw and not sjq:\n # 没有中场或45或46\n sjq, zzjqs, jqs75, jqs80 = _go_xiangxishijian(id)\n data.append('没有中场或45或46')\n data.append('没有中场或45或46')\n data.append(sjq)\n data.append(zzjqs)\n if zzjqs != '没有详细事件':\n before75_sjq = before75 - sjq\n data.append(before75_sjq)\n else:\n data.append('没有中场或45或46也没有详细事件')\n data.append(jqs75)\n data.append(jqs80)\n else:\n data.append(zcdxp)\n data.append(zcdqsw)\n data.append(sjq)\n sjq, zzjqs, jqs75, jqs80 = _go_xiangxishijian(id)\n data.append(zzjqs)\n if zzjqs != '没有详细事件':\n before75_sjq = before75 - sjq\n data.append(before75_sjq)\n else:\n data.append('没有详细事件')\n data.append(jqs75)\n data.append(jqs80)\n _write_csv(data, csv_path)\n _write_log(log_name, url, 2, log_path, len(num_list2))\n else:\n print('比赛75分钟前没有发生6个进球')\n _write_log(log_name, url, 3, log_path, len(num_list2))\n print(data)\n print(len(num_list2))\n time.sleep(1)\n except Exception as e:\n print(e)\n num_list2.insert(0, url)\n print(len(num_list2))\n print(url, '该链接抓取失败')\n _write_log(log_name, url, 4, log_path, len(num_list2))\n time.sleep(60)\n return None\n\n\n# _second_login([\n# 'http://vip.win007.com/AsianOdds_n.aspx?id=1825699',\n# ], 'a','a','a.csv','a2.csv')\n\n\n\n\ndef main(url_list, csv_path, log_path):\n isExists = os.path.exists(csv_path)\n if not isExists:\n create_csv(csv_path)\n for url in url_list:\n first_login(url, csv_path, log_path)\n\n","sub_path":"celue3/celue3.py","file_name":"celue3.py","file_ext":"py","file_size_in_byte":17205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"629003598","text":"import numpy as np\nimport statistics as std\n\ncoCreativities = ['Random', \"MinUnique\", \"MaxUnique\", \"MaxSMB\", \"MaxReward\", \"MaxKI\", \"MaxEnemies\", \"Last\", \"First\", \"FiftyFifty\"]\n# mergedIdentifier = \"mergedLevel\"\nkiFolders = [\"level1\", \"level2\", \"level3\", \"level4\", \"level5\", \"level6\"]\nkiFiles = [\"mergedlevel1\", \"mergedlevel2\", \"mergedlevel3\", \"mergedlevel4\", \"mergedlevel5\", \"mergedlevel6\"]\nmarioFolders = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\"]\nmarioFiles = [\"mergedlevel1\", \"mergedlevel2\", \"mergedlevel3\", \"mergedlevel4\", \"mergedlevel5\", \"mergedlevel6\", \"mergedlevel7\", \"mergedlevel8\", \"mergedlevel9\", \"mergedlevel10\", \"mergedlevel11\", \"mergedlevel12\", \"mergedlevel13\", \"mergedlevel14\", \"mergedlevel15\" ]\n# KILengths = [173, 203, 281, 159, 206, 233]\n\nfor coCreativity in coCreativities:\n kiLinearityFactor = []\n smbLinearityFactor = []\n nonLinearities = []\n for kiFolder, kiFile in zip(kiFolders, kiFiles):\n kiLinearityFactor = []\n with open(\"../generatedSections/\" + coCreativity + \"/KI Generated/\" + kiFolder + \"/\" + kiFile + \".txt\",\"rt\") as kiInfile:\n # currentKILevel = np.loadtxt(\"../generatedSections/\" + coCreativity + \"/KI Generated/\" + kiFolder + \"/\" + kiFile + \".txt\", dtype='V')\n currentKILevel = np.matrix([list(line.strip(\"\\n\")) for line in kiInfile.readlines()])\n # do something here\n pass\n for k in range(0, currentKILevel.shape[0]):\n for m in range(0, currentKILevel.shape[1]):\n if currentKILevel[k, m] != '-':\n kiLinearityFactor.append(m)\n nonLinearity = sum(kiLinearityFactor)/len(kiLinearityFactor)\n print (\"The non-linearity of \" + \"co-creativity type \" + coCreativity + \" and level \" + kiFolder + \" is: \" + str(sum(kiLinearityFactor)/len(kiLinearityFactor)))\n nonLinearities.append(nonLinearity)\n print(\"\\n\")\n for smbFolder, smbFile in zip(marioFolders, marioFiles):\n smbLinearityFactor = []\n with open(\"../generatedSections/\" + coCreativity + \"/SMB Generated/\" + smbFolder + \"/\" + smbFile + \".txt\",\"rt\") as smbInfile:\n currentSMBLevel = np.matrix([list(line.strip(\"\\n\")) for line in smbInfile.readlines()])\n for k in range(0, currentSMBLevel.shape[0]):\n for m in range(0, currentSMBLevel.shape[1]):\n if currentSMBLevel[k, m] != '-':\n smbLinearityFactor.append(k )\n nonLinearity = sum(smbLinearityFactor)/len(smbLinearityFactor)\n print (\"The non-linearity of \" + \"co-creativity type \" + coCreativity + \" and level \" + smbFolder + \" is: \" + str(sum(smbLinearityFactor)/len(smbLinearityFactor)))\n # # do something here\n # pass\n nonLinearities.append(nonLinearity)\n print(\"The mean of the nonLinearities for \" + \"co-creativity type \" + coCreativity + \" is: \" + str(std.mean(nonLinearities)) )\n print(\"\\nThe SD of the nonLinearities for \" + \"co-creativity type \" + coCreativity + \" is: \" + str(std.stdev(nonLinearities)))\n print(\"\\n\")\n print(\"-----------------------------------------------------\")\n ","sub_path":"Evaluation Scripts/nonLinearityCalculation.py","file_name":"nonLinearityCalculation.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"155748802","text":"\nimport sys\nimport arff\nimport pprint\nimport random\nimport math\nfrom arff import *\nfrom scipy.stats import chi2\n\n# -------------------------------------------------------------------------------------------\n# Tree Node representation\n# -------------------------------------------------------------------------------------------\n\nclass Tree(object):\n \"Generic tree node.\"\n def __init__(self, name='root', value = None, children=None):\n self.name = name\n self.value = value\n self.children = []\n self.positive = 0\n self.negative = 0\n if children is not None:\n for child in children:\n self.add_child(child)\n def __repr__(self):\n return self.name\n def add_child(self, node):\n assert isinstance(node, Tree)\n self.children.append(node)\n ChildCount()\n def assign_label(self, label):\n self.name=label\n def assign_value(self, value):\n self.value = value\n def assign_counts(self, pos, neg):\n self.positive = pos\n self.negative = neg\n\n# -------------------------------------------------------------------------------------------\n# ID3 decision tree builder\n# -------------------------------------------------------------------------------------------\n\ndef ID3(Examples, Targetattribute, Attributes, confidence, usegainratio):\n \"Algorithm for ID3 Machine Learning\"\n CustomPrint(\"TotalDataCount:\" + str(len(Examples)))\n CustomPrint(\"TotalAttrinDataCount:\" + str(len(Examples[0])))\n CustomPrint(\"TotalAttributeCount:\" + str(len(Attributes)))\n root = Tree();\n positiveCount = negativeCount = 0\n targetAttrIndex = GetAttrIndex(Attributes, Targetattribute)\n CustomPrint(\"targetAttrIndex=\" + str(targetAttrIndex))\n \n # Count positive and negative examples\n for member in Examples:\n if member[targetAttrIndex] == '+':\n positiveCount += 1\n if member[targetAttrIndex] == '-':\n negativeCount += 1\n CustomPrint(positiveCount)\n CustomPrint(negativeCount)\n if positiveCount+negativeCount != len(Examples):\n CustomPrint(\"Bad comparisons\")\n root.assign_counts(positiveCount, negativeCount)\n \n # All positive case\n if negativeCount == 0:\n root.assign_label(\"+\")\n CustomPrint(\"Assigned True\")\n return root\n \n # All negative case\n if positiveCount == 0:\n root.assign_label(\"-\")\n CustomPrint(\"Assigned False\")\n return root\n \n # Out of attributes - assign the most occurring label\n if len(Attributes) == 0 or len(Attributes) == 1:\n if positiveCount > negativeCount:\n root.assign_label(\"+\")\n CustomPrint(\"Assigned True\")\n return root\n else:\n root.assign_label(\"-\")\n CustomPrint(\"Assigned False\")\n return root\n \n # Choose the best attribute based on the given setting\n bestAttr = ChooseBestAttribute(Examples, Targetattribute, Attributes, confidence, usegainratio)\n \n # If we did not find an attribute, assign the most occurring label\n if bestAttr is None:\n if positiveCount > negativeCount:\n root.assign_label(\"+\")\n CustomPrint(\"Assigned True\")\n return root\n else:\n root.assign_label(\"-\")\n CustomPrint(\"Assigned False\")\n return root\n bestAttrIndex = GetAttrIndex(Attributes, bestAttr)\n \n CustomPrint(\"Best Attr:\" + bestAttr[0])\n CustomPrint(\"Best Attr Indx:\" + str(bestAttrIndex))\n \n # Assign label as attribute name\n root.assign_label(bestAttr[0])\n \n # Add a branch for each possible value\n for value in bestAttr[1]:\n CustomPrint(\"Adding child with value:\" + str(value))\n exampleSubset = []\n for member in Examples:\n #CustomPrint(member[bestAttrIndex])\n if member[bestAttrIndex] == value:\n newmember = member[:]\n exampleSubset.append(newmember)\n CustomPrint(\"Child has count:\" + str(len(exampleSubset)))\n if len(exampleSubset) == 0:\n child = Tree('root', value, None)\n root.add_child(child)\n if positiveCount > negativeCount:\n CustomPrint(\"Assigned True\")\n child.assign_label(\"+\")\n else:\n CustomPrint(\"Assigned False\")\n child.assign_label(\"-\")\n else:\n newAttrSet = Attributes[:]\n del newAttrSet[bestAttrIndex]\n for member in exampleSubset:\n del member[bestAttrIndex]\n child = ID3(exampleSubset, Targetattribute, newAttrSet, confidence, usegainratio)\n root.add_child(child)\n child.assign_value(value)\n if len(root.children) == 0:\n print(\"Attribute node does not have any child\")\n return root\n \n# -------------------------------------------------------------------------------------------\n# Choosing best attribute logic\n# -------------------------------------------------------------------------------------------\n\ndef ChooseBestAttribute(Examples, Targetattribute, Attributes, confidence, usegainratio):\n \"Chooses best attribute for the current node\"\n bestattr = None\n \n # First get the best attribute\n if usegainratio:\n bestattr = ChooseBestAttributeByGainRatio(Examples, Targetattribute, Attributes)\n else:\n bestattr = ChooseBestAttributeByGain(Examples, Targetattribute, Attributes)\n \n return bestattr\n \n # Verify through ChiSquare test that it is indeed worth adding this branch\n # if ShouldStopByChiSquare(Examples, Targetattribute, Attributes, bestattr, confidence):\n # return None\n # else:\n # return bestattr\n \ndef ChooseBestAttributeByGain(Examples, Targetattribute, Attributes):\n \"Choose the best attribute by the gain in entropy it provides\"\n pos = neg = totalCount = 0\n targetAttrIndex = GetAttrIndex(Attributes, Targetattribute)\n \n # Count the positive and negative examples\n for data in Examples:\n if data[targetAttrIndex] == \"+\":\n pos += 1\n totalCount += 1\n elif data[targetAttrIndex] == \"-\":\n neg += 1\n totalCount += 1\n \n # Calculate entropy of the current examples\n entropys = 0\n if pos != 0:\n entropys -= pos/(totalCount) * math.log2(pos/(totalCount))\n if neg != 0:\n entropys -= neg/(totalCount) * math.log2(neg/(totalCount))\n \n # Calculate entropy of each child and assess the gain this attribute provides\n bestgain = 0\n bestattr = None\n for attr in Attributes:\n if attr != Targetattribute:\n gain = entropys\n attrIndex = GetAttrIndex(Attributes, attr)\n for value in attr[1]:\n pos = neg = count = 0\n for data in Examples:\n if data[attrIndex] == value:\n count += 1\n if data[targetAttrIndex] == \"+\":\n pos += 1\n elif data[targetAttrIndex] == \"-\":\n neg += 1\n if count != 0:\n #CustomPrint(str(count) + \" \" + str(pos) + \" \" + str(neg))\n newentropy = 0\n if pos != 0:\n newentropy -= pos/(count) * math.log2(pos/(count))\n if neg != 0:\n newentropy -= neg/(count) * math.log2(neg/(count))\n gain -= count/totalCount * newentropy\n if gain > bestgain and gain != entropys:\n bestattr = attr\n bestgain = gain\n CustomPrint(\"Best gain is \" + str(bestgain))\n \n # Return the best attribute which gives the highest gain\n if bestattr is None:\n CustomPrint(\"Returning none attr as best attr\")\n return bestattr\n \ndef ChooseBestAttributeByGainRatio(Examples, Targetattribute, Attributes):\n \"Choose best attribute by highest gain ratio\"\n pos = neg = totalCount = 0\n targetAttrIndex = GetAttrIndex(Attributes, Targetattribute)\n \n # Count the positive and negative examples\n for data in Examples:\n if data[targetAttrIndex] == \"+\":\n pos += 1\n totalCount += 1\n elif data[targetAttrIndex] == \"-\":\n neg += 1\n totalCount += 1\n \n # Calculate entropy of the current examples\n entropys = 0\n if pos != 0:\n entropys -= pos/(totalCount) * math.log2(pos/(totalCount))\n if neg != 0:\n entropys -= neg/(totalCount) * math.log2(neg/(totalCount))\n \n # Calculate entropy of each child and assess the gain ratio this attribute provides\n bestgainratio = 0\n bestattr = None\n for attr in Attributes:\n if attr != Targetattribute:\n gain = entropys\n split = 0\n attrIndex = GetAttrIndex(Attributes, attr)\n for value in attr[1]:\n pos = neg = count = 0\n for data in Examples:\n if data[attrIndex] == value:\n count += 1\n if data[targetAttrIndex] == \"+\":\n pos += 1\n elif data[targetAttrIndex] == \"-\":\n neg += 1\n if count != 0:\n #CustomPrint(str(count) + \" \" + str(pos) + \" \" + str(neg))\n newentropy = 0\n if pos != 0:\n newentropy -= pos/(count) * math.log2(pos/(count))\n if neg != 0:\n newentropy -= neg/(count) * math.log2(neg/(count))\n gain -= count/totalCount * newentropy\n split -= count/totalCount * math.log2(count/totalCount)\n if split != 0:\n gainratio = gain/split\n if gainratio > bestgainratio and gain != entropys:\n bestattr = attr\n bestgainratio = gainratio\n CustomPrint(\"Best gain ratio is \" + str(bestgainratio))\n \n # Return the best attribute which gives the highest gain\n if bestattr is None:\n CustomPrint(\"Returning none attr as best attr\")\n return bestattr\n\n# -------------------------------------------------------------------------------------------\n# Chi Square Split Stopping\n# -------------------------------------------------------------------------------------------\n\ndef ShouldStopByChiSquare(Examples, Targetattribute, Attributes, bestattr, confidence):\n \"Calculates Chi Square heuristic to decide whether to stop splitting\"\n if bestattr == None:\n return True\n \n # Get the corresponding critical value\n limit = chi2.isf(1 - confidence, len(bestattr[1]) - 1 - 1)\n CustomPrint(\"Critical value:\" + str(limit))\n totalpos = totalneg = 0\n targetAttrIndex = GetAttrIndex(Attributes, Targetattribute)\n bestAttrIndex = GetAttrIndex(Attributes, bestattr)\n chisquare = 0\n \n # 1. Count the total positive and negative examples\n for data in Examples:\n if data[targetAttrIndex] == \"+\":\n totalpos += 1\n elif data[targetAttrIndex] == \"-\":\n totalneg += 1\n \n # Calculate chi square test statistic by iterating over every possible value\n for value in bestattr[1]:\n pos = neg = 0\n expos = exneg = 0\n for data in Examples:\n if data[bestAttrIndex] == value:\n if data[targetAttrIndex] == \"+\":\n pos += 1\n elif data[targetAttrIndex] == \"-\":\n neg += 1\n expos = totalpos * (pos + neg) / (totalpos + totalneg)\n exneg = totalneg * (pos + neg) / (totalpos + totalneg)\n if expos != 0:\n chisquare += (pos - expos)**2 / expos \n if exneg != 0:\n chisquare += (neg - exneg)**2 / exneg\n CustomPrint(\"Chisquare:\" + str(chisquare))\n \n # Reject if lesser than critical value\n if chisquare > limit:\n return False\n return True\n\n# -------------------------------------------------------------------------------------------\n# Evaluation and Prediction functions \n# -------------------------------------------------------------------------------------------\n\ndef BaggingEvaluate(treeSet, testSet, TargetAttribute, Attributes):\n \"Evaluate a test set with the given built decision tree\"\n CustomPrint(\"At Eval total Attr:\" + str(len(Attributes)))\n CustomPrint(\"At Eval total testSet Attr:\" + str(len(testSet[0])))\n totalCount = len(testSet)\n positive = good = 0\n targetAttrIndex = GetAttrIndex(Attributes, TargetAttribute)\n \n expectedPositives = expectedNegatives = predictedPositives = preditedNegatives = 0\n correctlyPredictedPositives = 0\n \n # PRedict for every test case\n for test in testSet:\n expected = test[targetAttrIndex]\n posVotes = negVotes = 0\n for i in range(len(treeSet)):\n val = GetPrediction(treeSet[i], test, TargetAttribute, Attributes)\n if val == \"+\":\n posVotes += 1\n else:\n negVotes += 1\n CustomPrint(\"Votes: \" + str(posVotes) + \" \" + str(negVotes))\n if posVotes >= negVotes:\n actual = \"+\"\n else:\n actual = \"-\"\n if expected == \"+\":\n expectedPositives += 1\n if expected == \"-\":\n expectedNegatives += 1\n if actual == \"+\":\n predictedPositives += 1\n if actual == \"-\":\n preditedNegatives += 1\n #CustomPrint(test)\n if expected == actual:\n positive += 1\n if expected == \"+\":\n correctlyPredictedPositives += 1\n if actual == \"+\" or actual == \"-\":\n good += 1\n CustomPrint(\"Good eval:\" + str(float(good/totalCount)*100))\n CustomPrint(correctlyPredictedPositives)\n CustomPrint(predictedPositives)\n CustomPrint(expectedPositives)\n \n CustomPrint(\"Precision: \" + str(float(correctlyPredictedPositives/predictedPositives)))\n CustomPrint(\"Recall: \" + str(float(correctlyPredictedPositives/expectedPositives)))\n \n # REturn the accuracy\n return float(positive/totalCount)*100\n\ndef Evaluate(tree, testSet, TargetAttribute, Attributes):\n \"Evaluate a test set with the given built decision tree\"\n CustomPrint(\"At Eval total Attr:\" + str(len(Attributes)))\n CustomPrint(\"At Eval total testSet Attr:\" + str(len(testSet[0])))\n totalCount = len(testSet)\n positive = good = 0\n targetAttrIndex = GetAttrIndex(Attributes, TargetAttribute)\n \n expectedPositives = expectedNegatives = predictedPositives = preditedNegatives = 0\n correctlyPredictedPositives = 0\n \n # PRedict for every test case\n for test in testSet:\n expected = test[targetAttrIndex]\n actual = GetPrediction(tree, test, TargetAttribute, Attributes)\n if expected == \"+\":\n expectedPositives += 1\n if expected == \"-\":\n expectedNegatives += 1\n if actual == \"+\":\n predictedPositives += 1\n if actual == \"-\":\n preditedNegatives += 1\n #CustomPrint(test)\n if expected == actual:\n positive += 1\n if expected == \"+\":\n correctlyPredictedPositives += 1\n if actual == \"+\" or actual == \"-\":\n good += 1\n CustomPrint(\"Good eval:\" + str(float(good/totalCount)*100))\n CustomPrint(correctlyPredictedPositives)\n CustomPrint(predictedPositives)\n CustomPrint(expectedPositives)\n \n print(\"Precision: \" + str(float(correctlyPredictedPositives/predictedPositives)))\n print(\"Recall: \" + str(float(correctlyPredictedPositives/expectedPositives)))\n \n # REturn the accuracy\n return float(positive/totalCount)*100\n\ndef GetPrediction(tree, test, TargetAttribute, Attributes):\n \"Evaluate a single test case on the given built tree and return the predicted target attribute\"\n # Root is a leaf node\n if str(tree) == \"+\":\n return \"+\"\n elif str(tree) == \"-\":\n return \"-\"\n else:\n # Root is a non-leaf node. FInd the attribute it is referring to\n for attr in Attributes:\n if str(tree) == attr[0]:\n # Find the branch to continue the search by checking values on each branch for current attribute\n for child in tree.children: \n if child.value == test[GetAttrIndex(Attributes, attr)]:\n # Found the branch, proceed with the prediction on this subtree\n return GetPrediction(child, test, TargetAttribute, Attributes)\n return str(tree)\n\n# -------------------------------------------------------------------------------------------\n# Helper Functions\n# -------------------------------------------------------------------------------------------\n\ndef ChildCount():\n \"A counter to keep track of number of nodes\"\n global g\n g += 1\n #print(str(g))\n\nclass Queue:\n \"Generic Queue Implementation\"\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def enqueue(self, item):\n self.items.insert(0,item)\n\n def dequeue(self):\n return self.items.pop()\n\n def size(self):\n return len(self.items)\n\ndef PrintTree(root):\n \"Helper function to print the tree\"\n myq = Queue()\n myq.enqueue(None)\n myq.enqueue(root);\n while myq.size() != 0:\n el = myq.dequeue()\n if el is None:\n CustomPrint('')\n if myq.size() != 0:\n myq.enqueue(None)\n continue\n # CustomPrint(el.value, end='')\n # CustomPrint(\"-\", end='')\n # CustomPrint(el.name, end=' ')\n for child in el.children:\n myq.enqueue(child)\n\ndef FindAndPrintBestTrueLabel(root):\n \"Find and print the best path for positive case\"\n maxPositive = FindMaxValue(root, True)\n PrintBestPath(root,maxPositive, True)\n \ndef FindAndPrintBestFalseLabel(root):\n \"Find and print the best path for negative case\"\n maxPositive = FindMaxValue(root, False)\n PrintBestPath(root,maxPositive, False)\n \ndef PrintBestPath(curr, max, positive):\n \"Prints the best path containing the max positive/negative value for the tree rooted at the given node\"\n if len(curr.children) == 0:\n if positive:\n if max == curr.positive and curr.name == \"+\":\n print(str(curr.name) + \" \" + str(curr.value) + \":\")\n return True\n else:\n if max == curr.negative and curr.name == \"-\":\n print(str(curr.name) + \" \" + str(curr.value) + \":\")\n return True\n for child in curr.children:\n if True == PrintBestPath(child, max, positive):\n print(str(curr.name) + \" \" + str(curr.value) + \":\")\n return True\n return False\n\ndef FindMaxValue(root, positive):\n \"Find the maximum positive/negative value in the tree rooted at the given node\"\n max = 0 \n myq = Queue()\n myq.enqueue(None)\n myq.enqueue(root);\n while myq.size() != 0:\n el = myq.dequeue()\n if el is None:\n CustomPrint('')\n if myq.size() != 0:\n myq.enqueue(None)\n continue\n if positive:\n if el.positive > max and len(el.children) == 0 and el.name == \"+\":\n max = el.positive\n else:\n if el.negative > max and len(el.children) == 0 and el.name == \"-\":\n max = el.negative\n for child in el.children:\n myq.enqueue(child)\n return max\n\ndef GetAttrIndex(Attributes, TargetAttribute):\n \"Given an attribute and set of all attributes returns the index of the given attribute in the attribute set\"\n for i in range(len(Attributes)):\n if Attributes[i][0] == TargetAttribute[0]:\n return i\n \ndef CustomPrint(string):\n #print(string)\n return string\n\n \ndef Sample(data):\n newdata = []\n for i in range(len(data)):\n newdata.append(data[random.randint(0,len(data) - 1)]);\n \n CustomPrint(len(newdata))\n return newdata\n\n# -------------------------------------------------------------------------------------------\n# Main function logic starts here\n# -------------------------------------------------------------------------------------------\n\n# Initialize node counter\ng = 0\n\n# Load training data\na = arff.load(open('train.arff'))\n\n# Various possible settings\n# Add and remove settings as appropriate\nconfidenceset = [0.99] #[0, 0.95, 0.99]\nusegainratioset = [False] #[True, False]\nsamplingCount = [1,3,5,10,20]\nrunCount = 1000\n\n# Iterate over all possible settings\nfor sampleCount in samplingCount:\n for confidence in confidenceset:\n for usegainratio in usegainratioset:\n sumAccuracy = 0\n for j in range(runCount):\n # Reset node counter\n g=0\n #print(\"Configuration Confidence:\" + str(confidence) + \" Usegainratio:\" + str(usegainratio))\n \n treeSet = []\n for i in range(sampleCount):\n treeSet.append(ID3(Sample(a['data']), a['attributes'][0], a['attributes'], confidence, usegainratio))\n\n #PrintTree(tree)\n \n #FindAndPrintBestTrueLabel(tree)\n #FindAndPrintBestFalseLabel(tree)\n\n #print(\"Tree built with nodecount:\" + str(g+1))\n\n # Load test data\n testData = arff.load(open('test.arff'))\n\n # Calculate the accuracy of the tree with test data \n sumAccuracy += BaggingEvaluate(treeSet, testData['data'], testData['attributes'][0], testData['attributes'])\n\n print(\"Testing Accuracy:\" + str(sumAccuracy/runCount))\n\n# -------------------------------------------------------------------------------------------\n# Main function logic ends here\n# -------------------------------------------------------------------------------------------\n\n# Testing Accuracy:75.85625\n# Testing Accuracy:79.35\n# Testing Accuracy:80.340625\n# Testing Accuracy:80.703125\n# Testing Accuracy:82.296875","sub_path":"Assignment3/P3/main3.py","file_name":"main3.py","file_ext":"py","file_size_in_byte":22209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"362182574","text":"'''\n\n'''\nfrom __future__ import absolute_import\n\nimport logging\nlog = logging.getLogger(__name__)\n\nfrom tornado import gen\n\nfrom ..session import ServerSession\nfrom ..exceptions import ProtocolError\n\nclass ServerHandler(object):\n '''\n\n '''\n\n def __init__(self):\n self._handlers = dict()\n\n self._handlers['PULL-DOC-REQ'] = ServerSession.pull\n self._handlers['PUSH-DOC'] = ServerSession.push\n self._handlers['PATCH-DOC'] = ServerSession.patch\n self._handlers['SERVER-INFO-REQ'] = self._server_info_req\n\n @gen.coroutine\n def handle(self, message, connection):\n handler = self._handlers.get((message.msgtype, message.revision), None)\n\n if handler is None:\n handler = self._handlers.get(message.msgtype, None)\n\n if handler is None:\n raise ProtocolError(\"%s not expected on server\" % message)\n\n try:\n work = yield handler(message, connection)\n except Exception as e:\n log.error(\"error handling message %r: %r\", message, e)\n log.debug(\" message header %r content %r\", message.header, message.content, exc_info=1)\n work = connection.error(message, repr(e))\n raise gen.Return(work)\n\n @gen.coroutine\n def _server_info_req(self, message, connection):\n raise gen.Return(connection.protocol.create('SERVER-INFO-REPLY', message.header['msgid']))\n\n","sub_path":"lib/python2.7/site-packages/bokeh/server/protocol/server_handler.py","file_name":"server_handler.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"329797085","text":"x,y=map(int,input().split())\nl=[]\nfor num in range(x,y+1):\n if(num>1):\n for i in range(2,num):\n if(num%i==0):\n break\n else:\n l.append(num)\nprint(len(l))\n","sub_path":"player10.py","file_name":"player10.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"91020872","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport base\nfrom config.schema import User, Relation, Project\nimport util.database\nfrom util.monitor import UserMonitorDetail,SimpleUser\n\nclass ProjectMonitorDetailHandler(base.BaseHandler):\n def get(self):\n self.check()\n session = util.database.Session()\n \n try:\n id = self.get_secure_cookie(\"id\")\n except:\n self.redirect(\"/user/login\")\n \n projectid = self.get_secure_cookie(\"projectid\")\n \n project = session.query(Project).filter(Project.id == projectid).first()\n\n if id:\n user = session.query(User).filter(User.id == id).first()\n if user:\n monitordetail = UserMonitorDetail(id = user.id, name = user.name, email = user.email)\n else:\n self.redirect(\"/user/login\")\n\n target_list = session.query(Relation).filter(Relation.rater_id == id).order_by(Relation.finish).all()\n for row in target_list:\n target = session.query(User).filter(User.id == row.target_id).first()\n if target:\n simplerater = SimpleUser(id = target.id, name = target.name, email = target.email, finish = row.finish )\n monitordetail.addgroup(simpleuser = simplerater, group = row.level)\n\n else:\n monitordetail = None\n\n info = None\n projectlogo = \"/static/logo/project_\" + projectid + \".jpg\"\n self.render(\"user/projectmonitordetail.html\", monitordetail = monitordetail, project = project, projectlogo = projectlogo, error = \"\", info = info )\n \n session.close()\n\n\n def post(self):\n pass\n","sub_path":"src/handlers/user/projectmonitordetail.py","file_name":"projectmonitordetail.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"233902224","text":"from flask import Blueprint\nfrom google.oauth2 import service_account\nfrom google.auth.transport.requests import AuthorizedSession\nfrom google.cloud import datastore\nfrom google.cloud import bigquery\nfrom google.cloud import storage\nimport datetime\nimport time\nimport dataflow_pipeline.massive as pipeline\nimport cloud_storage_controller.cloud_storage_controller as gcscontroller\nimport dataflow_pipeline.telefonia.detalle_predictivo_opt_beam as detalle_predictivo_opt_beam\nfrom procesos.Telefonia.extraccion_service import (extraccion_service_general)\n\ndetalle_predictivo_opt_api = Blueprint('detalle_predictivo_opt_api', __name__)\n\n########################### DEFINICION DE VARIABLES ###########################\nfecha = time.strftime('%Y%m%d')\nKEY_REPORT = \"detalle_predictivo_opt\" \nCODE_REPORT = \"campaing_3\" \nsin_datos = ''\ntype_report = 'api_reports_manager'\ntype_api = 'report'\ntable_id = '`contento-bi.telefonia.detalle_predictivo_opt`'\nkey_delete = 'ipdial_code'\n\n########################### CODIGO #####################################################################################\n\n@detalle_predictivo_opt_api.route(\"/detalle_predictivo_opt\", methods=['GET']) #[[[[[[[[[[[[[[[[[[***********************************]]]]]]]]]]]]]]]]]]\ndef Ejecutar():\n print ('################################# ENTRO AL DETALLE PREDICTIVO OPT')\n schema = ['ID CAMPAIGN',\n 'NAME',\n 'LAST NAME',\n 'ID',\n 'DATE',\n 'TELEPHONE',\n 'RESULT',\n 'OPT1',\n 'OPT2',\n 'OPT3',\n 'OPT4',\n 'OPT5',\n 'OPT6',\n 'OPT7',\n 'OPT8',\n 'OPT9',\n 'OPT10',\n 'OPT11',\n 'OPT12',\n 'ID CALL' \n\n ]\n\n print ('################################################## LLAMAMOS AL SERVICIO')\n extraccion = extraccion_service_general(KEY_REPORT,CODE_REPORT,sin_datos,schema, table_id, key_delete, type_api, type_report) \n print (extraccion) \n \n if len(extraccion) == 5:\n return ('Proceso no ejecutado (TODAS LAS INSTANCIAS ERRADAS)') \n else:\n filename = extraccion[0]\n cloud_storage_rows = extraccion[1]\n output = extraccion[2] \n cont_excepciones = extraccion[3] \n cont_no_contenido = extraccion[4]\n cont_registros = extraccion[5]\n cont_token = extraccion[6]\n lista_instancias_excepcion = extraccion[7] \n lista_instancias_sin_contenido = extraccion[8] \n lista_instancias_token = extraccion[9]\n sub_path = extraccion[10]\n dateini = extraccion[11]\n dateend = extraccion[12]\n\n gcscontroller.create_file(filename, cloud_storage_rows, \"ct-telefonia\")\n ejecutar = detalle_predictivo_opt_beam.run(output, KEY_REPORT)\n storage_client = storage.Client() \n bucket = storage_client.get_bucket('ct-telefonia')\n blob = bucket.blob(sub_path + fecha + '.csv') \n\n return (\"Se acaba de ejecutar el proceso de \" + KEY_REPORT + \" Para actualizar desde: \" + dateini + \" hasta \" + dateend +' con '+str(cont_registros)+' registros' +'\\n' + \"INFORMACION: instancias con error --> \"+str(cont_excepciones) +'\\n' +'DETALLE:'+str(lista_instancias_excepcion) + '\\n'+'---------------------------------------' +'\\n'+'instancias sin contenido: ' +str(cont_no_contenido)+ '\\n' +'DETALLE:' +str(lista_instancias_sin_contenido) +'---------------------------------------'+'\\n'+'instancias con problemas de TOKEN: '+str(cont_token) + '\\n'+'DETALLE: '+str(lista_instancias_token)+ '')\n\n","sub_path":"procesos/Telefonia/detalle_predictivo_opt.py","file_name":"detalle_predictivo_opt.py","file_ext":"py","file_size_in_byte":3703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"192612053","text":"# -*- coding: utf-8 -*-\n\nimport pika\n\nconn = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))\nchannel = conn.channel()\n\nchannel.queue_declare(queue='test')\n\nchannel.basic_publish(exchange='', routing_key='test', body='hahahaha world.')\n\nprint('[x] sent message..')\n\nconn.close()\n","sub_path":"rq/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"99975075","text":"import eventlet\n# Needed to get threading and stuff to work, so fun\neventlet.monkey_patch()\n\nimport argparse\nimport os\nimport secrets\n\nimport sqlite3\n\nfrom flask import g\nfrom flask import flash\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import request, redirect, url_for\nfrom flask_socketio import SocketIO\nfrom werkzeug.utils import secure_filename\nfrom multiprocessing.managers import BaseManager\n\nimport vmm\n\n\nenv_or_default = lambda e, d: os.getenv(e) if os.getenv(e) else d\n\napp = Flask(__name__)\n\napp.secret_key = secrets.token_bytes(16)\n#socketio = SocketIO(app, logger=True, engineio_logger=True)\nsocketio = SocketIO(app)\n\nDISK_UPLOAD_DIR = env_or_default(\"OOOWS_DISK_UPLOAD_DIR\", \"/tmp/disks/\")\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nDATABASE = os.path.join(BASE_DIR, 'ooows-web.db')\n\nvmms = None\n\ndef make_dicts(cursor, row):\n return dict((cursor.description[idx][0], value)\n for idx, value in enumerate(row))\n\n# initialize vmm workers if the db has VMs\ndef init_vmms():\n vmms = dict()\n vms = query_db(\"select * from vms\")\n for vm in vms:\n vmms[vm['id']] = vmm.VmmWorker(name=vm['name'])\n return vmms\n\ndef get_db():\n db = getattr(g, '_database', None)\n if db is None:\n db = g._database = sqlite3.connect(DATABASE)\n db.row_factory = make_dicts\n return db\n\ndef get_vmm(vmid):\n global vmms\n if vmms is None:\n vmms = init_vmms()\n if not vmid in vmms:\n vmms[vmid] = vmm.VmmWorker()\n return vmms[vmid]\n\n@app.teardown_appcontext\ndef close_connection(exception):\n db = getattr(g, '_database', None)\n if db is not None:\n db.close()\n\ndef query_db(query, args=(), one=False):\n cur = get_db().execute(query, args)\n rv = cur.fetchall()\n cur.close()\n return (rv[0] if rv else None) if one else rv\n\ndef init_db():\n with app.app_context():\n db = get_db()\n with app.open_resource('schema.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n@app.route(\"/\")\ndef index():\n # query db and list available VMs\n\n vms = query_db(\"select * from vms\")\n for vm in vms:\n vm['running'] = not get_vmm(vm['id']).stopped()\n\n return render_template(\"index.html\", vms=vms)\n\n@app.route(\"/new\", methods=['POST'])\ndef new():\n disk = request.files['disk']\n if not disk:\n flash(\"No file uploaded\")\n return redirect(url_for('index'))\n\n vmname = disk.filename\n\n if not len(vmname) < 32:\n flash(\"VM name must be less than 32 character\")\n return redirect(url_for('index'))\n\n if not vmname.isalnum():\n flash(\"VM name must be alphanumeric\")\n return redirect(url_for('index'))\n\n VM_LIMIT = 3\n count = query_db(\"select count(id) as count from vms\", one=True)\n if int(count['count']) >= VM_LIMIT:\n flash(f\"Already have {VM_LIMIT} vms\")\n return redirect(url_for('index'))\n\n vm = query_db(\"select id from vms where name = ?\", [vmname], True)\n if not vm is None:\n # TODO: flash, vm with name already exists\n flash(\"VM with name already exists\")\n return redirect(url_for('index'))\n\n # write this information to the sqlite database\n get_db().execute(\"insert into vms (name, disk) values(?, ?)\",\n (vmname, secure_filename(disk.filename)))\n\n get_db().commit()\n\n # the id of the vm will now be how we refer to it\n vm = query_db(\"select id, name from vms where name = ?\", [vmname], True)\n if vm is None:\n # TODO : flash, weird error\n return redirect(url_for('index'))\n\n diskpath = os.path.join(DISK_UPLOAD_DIR, secure_filename(vmname))\n disk.save(diskpath)\n\n # instantiate runtime store using the vmm manager\n vmm = get_vmm(vm['id'])\n vmm.new(vm['name'], diskpath)\n\n return redirect(url_for('index'))\n\n@app.route('/delete/')\ndef delete(vmid):\n\n # get the vmname and disk file\n vm = query_db(\"select id, name, disk from vms where id = ?\", [vmid], True)\n if vm is None:\n # TODO: flash 'invalid vm'\n flash(\"Invalid VM\")\n return redirect(url_for('index'))\n\n vmm = get_vmm(vm['id'])\n if not vmm.stopped():\n vmm.stop()\n\n vmm.delete()\n\n global vmms\n del vmms[vm['id']]\n\n # delete the row from the table\n get_db().execute(\"delete from vms where id = ?\", [vmid])\n get_db().commit()\n\n return redirect(url_for('index'))\n\n@app.route('/start/')\ndef start(vmid):\n # resolve vm id to get disk and name info\n\n vm = query_db(\"select id, name, disk from vms where id = ?\",\n [vmid], True)\n if vm is None:\n # TODO: flash 'invalid vm'\n flash(\"Invalid VM\")\n return redirect(url_for('index'))\n\n # start the thread running the vmm\n vmm = get_vmm(vm['id'])\n\n # make sure VM is not already running (in db)\n if not vmm.stopped():\n # TODO: flash 'vm already running'\n flash(\"VM already running\")\n return redirect(url_for('index'))\n\n vmm.start()\n\n return redirect(url_for('index'))\n\n@app.route('/stop/')\ndef stop(vmid):\n # resolve vm id to get disk and name info\n\n vm = query_db(\"select id, name, disk from vms where id = ?\",\n [vmid], True)\n if vm is None:\n # TODO: flash 'invalid vm'\n flash(\"Invalid VM\")\n return redirect(url_for('index'))\n\n vmm = get_vmm(vm['id'])\n\n # make sure VM is already running\n if vmm.stopped():\n # TODO: flash 'vm not running'\n flash(\"VM not running\")\n return redirect(url_for('index'))\n\n vmm.stop()\n\n return redirect(url_for('index'))\n\n@app.route('/console/')\ndef console(vmid):\n\n # resolve vm id\n vm = query_db(\"select id, name from vms where id = ?\", [vmid], True)\n if vm is None:\n # TODO: flash 'invalid vm'\n flash(\"Invalid VM\")\n return redirect(url_for('index'))\n\n # get vmm session\n vmm = get_vmm(vm['id'])\n\n # make sure vm is already running\n if vmm.stopped():\n # TODO: flash 'vm not running'\n flash(\"VM not running\")\n return redirect(url_for('index'))\n\n # drop client into template with websocket console session\n return render_template(\"console.html\", vm=vm)\n\n@app.route('/view/')\ndef view(vmid):\n\n # resolve vm id to get virtd session id\n vm = query_db(\"select id, name from vms where id = ?\", [vmid], True)\n if vm is None:\n # TODO: flash 'invalid vm'\n flash(\"Invalid VM\")\n return redirect(url_for('index'))\n\n vmm = get_vmm(vm['id'])\n\n # make sure vm is already running\n if vmm.stopped():\n # TODO: flash 'vm not running'\n flash(\"VM not running\")\n return redirect(url_for('index'))\n\n return render_template(\"view.html\", vm=vm)\n\n@socketio.event\ndef view_video(message):\n # User is ready for a websocket VGA connection, so give it to them\n vmid = int(message['vmid'])\n\n vmm = get_vmm(vmid)\n vmm.video(socketio, vmid)\n return\n\n@socketio.event\ndef view_console(message):\n # User is ready for a websocket console connection, so give it to them\n vmid = int(message['vmid'])\n\n vmm = get_vmm(vmid)\n vmm.console(socketio, vmid)\n return\n\n@socketio.event\ndef console_rx(message):\n # User is ready for a websocket console connection, so give it to them\n vmid = int(message['vmid'])\n\n vmm = get_vmm(vmid)\n vmm.txConsoleData(message['data'])\n return\n\n\n@socketio.event\ndef connect():\n return\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(prog=\"app\")\n parser.add_argument(\"--debug\", action=\"store_true\", help=\"Enable debugging\")\n parser.add_argument(\"--port\", type=int, default=5000, help=\"Port to listen on [default: 5000]\")\n parser.add_argument(\"--host\", default='127.0.0.1', help=\"Host to listen on [default: 127.0.0.1]\")\n\n args = parser.parse_args()\n\n socketio.run(app, host=args.host, port=args.port, debug=args.debug)\n","sub_path":"web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"554595307","text":"import cv2\nimport numpy as np\nimg = cv2.imread('out.jpg', 1)\ngn = cv2.GaussianBlur(img, (5,5), 0)\nuimg = cv2.addWeighted(img, 1.5, gn, -0.5, 0)\nlab= cv2.cvtColor(uimg, cv2.COLOR_BGR2LAB)\ncv2.imshow(\"lab\",lab)\n\n#-----Splitting the LAB image to different channels-------------------------\nl, a, b = cv2.split(lab)\n\n#-----Applying CLAHE to L-channel-------------------------------------------\nclahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))\ncl = clahe.apply(l)\n\n#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------\nlimg = cv2.merge((cl,a,b))\n\n#-----Converting image from LAB Color model to RGB model--------------------\nfinal = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\ncv2.imshow(\"In\", img)\ncv2.imshow('final', final)\ncv2.waitKey(0)","sub_path":"Optical Domain/um.py","file_name":"um.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"83721430","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def findBottomLeftValue(self, root):\n return self.findLeftMostNode(root)\n \n def findLeftMostNode(self, root):\n self.max_depth = -1\n self.res = -1\n \n self.dfs(root, 0)\n return self.res\n \n def dfs(self, root, depth):\n if not root:\n return\n \n if depth > self.max_depth:\n self.max_depth = depth\n self.res = root.val\n \n self.dfs(root.left, depth + 1)\n self.dfs(root.right, depth + 1)\n \n","sub_path":"Leetcode/Algorithm/python/Find Left Most Element.py","file_name":"Find Left Most Element.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"232694460","text":"\"\"\"lab_01_dice.py\r\n\r\nThis program simulates a street craps game. It is designed to demonstrate\r\nthe use of loops and decision making structures. Note the use of the\r\nrandrange function instead of the less Pythonic randint. It is\r\nimportant to know the difference between the two.\r\n\"\"\"\r\n\r\nfrom random import randrange \r\ndef dice_rolls():\r\n return randrange(1,7) + randrange(1,7) \r\n\r\nmoney = 100\r\nplays = 0\r\ncontin = 'y'\r\nprint('Beginning Balance = ${0:,d}'.format(money))\r\n# print 'Beginning Balance = $%d' % money # Older formatting\r\nwhile contin == 'y' or contin == 'Y': # Loop that controls the game\r\n plays = plays + 1\r\n firstroll = True # Flag showing whether this is the first roll\r\n win_lose = '' # This is an empty string until there is a win or loss\r\n while win_lose == '': # Loop controlling individual wins/losses\r\n myroll = dice_rolls()\r\n print(myroll, end=' ')\r\n if firstroll:\r\n if myroll < 4 or myroll == 12:\r\n win_lose = 'L'\r\n continue\r\n if myroll == 7 or myroll == 11:\r\n win_lose = 'W'\r\n continue\r\n point = myroll\r\n firstroll = False\r\n continue\r\n if myroll == 7:\r\n win_lose = 'L'\r\n continue\r\n if myroll == point:\r\n win_lose = 'W'\r\n continue\r\n if win_lose == 'L':\r\n money = money - 10 # or money -= 10\r\n print('You lose!')\r\n if money <= 0:\r\n break\r\n if win_lose == 'W':\r\n money = money + 10\r\n print('You win!')\r\n print('Balance = ${0:,d}'.format(money), end=' ')\r\n contin = input('Play again? y/n: ') # Any entry other than y or Y ends play\r\n\r\nprint('\\nNumber of plays -', plays)\r\nprint(f'Ending Balance = ${money:,d}') # Newest (requires Python 3.6)\r\nprint('Ending Balance = ${0:,d}'.format(money)) # Newer formatting\r\nprint('Ending Balance = $%d' % money) # Older formatting\r\n \r\n \r\n \r\n \r\n","sub_path":"Python2/Labs/LastLabPy2/lab_01_dice.py","file_name":"lab_01_dice.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"161467056","text":"# https://leetcode.com/problems/restore-ip-addresses/submissions/\n\nclass Solution:\n def restoreIpAddresses(self, s: str) -> [str]:\n if len(s) < 4:\n return []\n \n s = list(s)\n \n answer = set()\n \n self.backtrack(s, 0, [], answer)\n \n return answer\n \n def backtrack(self, s, index, current_path, answer):\n # print(index, current_path)\n \n # Define boundaries and conditions\n if len(current_path) == 4: # make sure we stop at 4th octet of IP adr\n ans = \".\".join(current_path.copy())\n if len(ans) == (len(s)+3): # Input and answer match in length. 3 is added to account for 3 '.' that join the current_path\n answer.add(ans)\n return\n \n # Don't process if index is higher than len(s)\n if index >= len(s):\n return\n \n for i in range(1,4):\n ip_part_string = \"\".join(s[index:index+i])\n # Skip blank strings\n if ip_part_string:\n # Make sure the IP is in valid range\n if 0 <= int(ip_part_string) <= 255: \n # Handle the case of 0 being in the beginning of ip_part_string e.g. int('010') => 10. Example input => \"10101010\"\n if len(ip_part_string) == len(str(int(ip_part_string))):\n current_path.append(ip_part_string)\n self.backtrack(s, index+i, current_path, answer)\n del current_path[-1] # Backtrack\n \n# \"25525511135\"\n# \"1111\"\n# \"2552552550\"\n# \"10101010\"\n# \"256256256256\"\n# \"00010\"\n# \"19216801\"","sub_path":"python/Backtracking/restore-ip-addresses.py","file_name":"restore-ip-addresses.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"172521002","text":"import random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple\nfrom recommender.biknn import BIKNN\n\n\nclass GABIKNN:\n\t\"\"\"\n\tGenetic Algorithm for tuning the B1, B2 hyperparameter\n\tfor BIKNN\n\n\tParameters\n\t----------\n\tgeneration : int\n\t\tnumber of iteration to train the algorithm\n\n\tpop_size : int\n\t\tnumber of chromosomes in the population\n\n\tlow, high : int\n\t\tlower_bound and upper_bound possible value of the randomly generated chromosome\n\n\tretain_rate : float 0 ~ 1\n\t\tthe fraction of the best chromosome to retain. used to mate\n\t\tthe children for the next generation\n\n\tmutate_rate : float 0 ~ 1\n\t\tthe probability that each chromosome will mutate\n\n\tBIKNN : class BIKNN\n\t\ta fitted BIKNN model\n\n\tverbose : boolean\n\t\twhether to print the best chromo (B1, B2) during each generation\n\n\tExample\n\t-------\n\timport pandas as pd\n\tfrom recommender import BIKNN, GABIKNN\n\n\t# movielens, column order: user id, item id, ratings and timestamp\n\t# the fourth column is the timestamp, exclude it\n\ttrain = pd.read_csv( 'data/u1.base', sep = '\\t', header = None )\n\ttrain = train.iloc[ :, 0:3 ]\n\ttest = pd.read_csv( 'data/u1.test', sep = '\\t', header = None )\n\ttest = test.iloc[ :, 0:3 ]\n\tcolumn_names = [ 'user_ids', 'item_ids', 'ratings' ]\n\ttrain.columns = column_names\n\ttest.columns = column_names\n\n\t# make sure all the items and users that are in the testing data\n\t# has been seen in training \n\tcontain_items = test['item_ids'].isin( train['item_ids'].unique() )\n\tcontain_users = test['user_ids'].isin( train['user_ids'].unique() )\n\ttest = test[ contain_users & contain_items ]\n\n\tbiknn1 = BIKNN( K = 20, B1 = 25, B2 = 25, iterations = 100000 )\n\tbiknn1.fit( data = train, column_names = [ 'user_ids', 'item_ids', 'ratings' ] )\n\tga1 = GABIKNN( \n\t\tgeneration = 2, \n\t\tpop_size = 5,\n\t\tlow = 0, \n\t\thigh = 100, \n\t\tretain_rate = 0.5, \n\t\tmutate_rate = 0.2,\n\t\tBIKNN = biknn1\n\t)\n\tga1.fit(test)\n\tga1.convergence_plot()\n\t\"\"\"\n\tdef __init__( self, generation, pop_size, low, high, \n\t\t\t\t retain_rate, mutate_rate, BIKNN, verbose = False ):\t\t\n\n\t\tself.low = low\n\t\tself.high = high\n\t\t\n\t\tif not BIKNN.is_fitted:\n\t\t\traise ValueError('BIKNN model is not fitted, call .fit() first')\n\t\t\n\t\tself.BIKNN = BIKNN\n\t\tself.verbose = verbose\n\t\tself.pop_size = pop_size\n\t\tself.generation = generation\n\t\tself.retain_len = int( pop_size * retain_rate )\n\t\tself.mutate_rate = mutate_rate\n\n\t\t# only tunes two hyperpameter, thus the chromo size is fixed\n\t\tself.chromo_size = 2 \n\t\tself.info = namedtuple( 'info', [ 'cost', 'chromo' ] )\n\t\n\t\n\tdef fit( self, data ):\n\t\t\"\"\"\n\t\tPass in the data and fits the model\n\n\t\tParameters\n\t\t----------\n\t\tdata : DataFrame\n\t\t\tbase training data\n\n\t\tcolumn_names : list of strings\n\t\t\tspecifying the column names of the DataFrame,\n\t\t\thas to be the combination of [ 'user_id', 'item_id', 'ratings' ]\n\t\t\"\"\"\n\t\t\n\t\t# randomly generate the initial population, and evaluate its cost\n\t\tarray_size = self.pop_size, self.chromo_size\n\t\tpop = np.random.random_integers( self.low, self.high, array_size )\t\t\n\t\tgraded_pop = self._compute_cost( pop, data )\n\n\t\t# store the best chromosome and its cost for each generation,\n\t\t# so we can get an idea of when the algorithm converged\n\t\tself.generation_history = []\n\t\tfor i in range(self.generation):\n\t\t\tgraded_pop, generation_best = self._evolve( graded_pop, data )\n\t\t\tself.generation_history.append(generation_best)\n\t\t\tif self.verbose:\n\t\t\t\tprint( \"generation {}'s best chromo: {}\".format( i + 1, generation_best ) )\n\n\t\tself.best = self.generation_history[self.generation - 1]\n\t\tself.is_fitted = True\n\t\treturn self\n\n\n\tdef _compute_cost( self, pop, data ):\n\t\t\"\"\"\n\t\tcompute the cost (mae) for different B1, B2 hyperparameter\n\t\tcombine the cost and chromosome into one list and sort them\n\t\tin ascending order\n\t\t\"\"\"\n\t\tgraded = []\n\t\tfor p in pop:\n\t\t\tp_B1, p_B2 = p\n\t\t\tself.BIKNN.B1 = p_B1\n\t\t\tself.BIKNN.B2 = p_B2\n\t\t\tpred = self.BIKNN.predict(data)\n\t\t\tcost = self.BIKNN.evaluate( pred, data['ratings'] )\n\t\t\tgraded.append( self.info( cost, list(p) ) )\n\t\t\n\t\tgraded = sorted(graded)\n\t\treturn graded\n\n\t\n\tdef _evolve( self, graded_pop, data ):\n\t\t\"\"\"\n\t\tcore method that does the crossover, mutation to generate\n\t\tthe possibly best children for the next generation\n\t\t\"\"\"\n\t\t\n\t\t# retain the best chromos (number determined by the retain_len)\n\t\tgraded_pop = graded_pop[:self.retain_len]\n\t\tparent = [ p.chromo for p in graded_pop ]\n\n\t\t# generate the children for the next generation \n\t\tchildren = []\n\t\twhile len(children) < self.pop_size:\n\t\t\tchild = self._crossover(parent)\n\t\t\tchild = self._mutate(child)\n\t\t\tchildren.append(child)\n\n\t\t# evaluate the children chromosome and retain the overall best,\n\t\t# overall simply means the best from the parent and the children, where\n\t\t# the size retained is determined by the population size\n\t\tgraded_children = self._compute_cost( children, data )\n\t\tgraded_pop.extend(graded_children)\n\t\tgraded_pop = sorted(graded_pop)\n\t\tgraded_pop = graded_pop[:self.pop_size]\n\t\t\n\t\t# also return the current generation's best chromosome and its cost\n\t\tgeneration_best = graded_pop[0]\n\t\treturn graded_pop, generation_best \n\n\n\tdef _crossover( self, parent ):\n\t\t\"\"\"\n\t\tmate the children by randomly choosing two parents and mix \n\t\tthe first half element of one parent with the later half \n\t\telement of the other\n\t\t\"\"\"\n\t\tindex1, index2 = random.sample( range(self.retain_len), k = 2 )\n\t\tmale, female = parent[index1], parent[index2]\n\t\tpivot = len(male) // 2\n\t\tchild = male[:pivot] + female[pivot:]\n\t\treturn child\n\n\n\tdef _mutate( self, child ):\n\t\t\"\"\"\n\t\trandomly change one element of the chromosome if it\n\t\texceeds the user-specified threshold (mutate_rate)\n\t\t\"\"\"\n\t\tif self.mutate_rate > random.random():\n\t\t\tidx_to_mutate = random.randrange(self.chromo_size)\n\t\t\tchild[idx_to_mutate] = random.randint( self.low, self.high )\n\n\t\treturn child\n\n\n\tdef convergence_plot(self):\n\t\tgh = self.generation_history\n\t\tcosts = [ g.cost for g in gh ]\n\t\tplt.plot( range( 1, len(gh) + 1 ), costs, '-o' )\n\t\tplt.title( 'Cost Convergence Plot' )\n\t\tplt.xlabel('Iteration')\n\t\tplt.ylabel('Cost')\n\t\tplt.ylim( 0, costs[0] + 0.5 )\n\t\tplt.tight_layout()\n\t\tplt.show()\n\n","sub_path":"recommendation/BIKNN/recommender/gabiknn.py","file_name":"gabiknn.py","file_ext":"py","file_size_in_byte":6081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"325214767","text":"import os\nimport numpy as np\nimport urllib.request\nimport scipy.sparse as sp_sparse\nimport csv\nimport gzip\n\nfrom .dataset import GeneExpressionDataset\n\n\nclass CbmcDataset(GeneExpressionDataset):\n def __init__(self, type='train'):\n self.save_path = 'data/'\n self.download_name = \"GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz\"\n self.data_filename = 'cbmc_expression_%s.npy' % type\n self.gene_names = 'genes_names.npy'\n self.download_and_preprocess()\n super(CbmcDataset, self).__init__([sp_sparse.csr_matrix(np.load(self.save_path + self.data_filename))],\n gene_names=np.load(self.save_path + self.gene_names))\n\n def download(self):\n url = \"https://www.ncbi.nlm.nih.gov/geo/download/\" + \\\n \"?acc=GSE100866&format=file&file=GSE100866%5FCBMC%5F8K%5F13AB%5F10X%2DRNA%5Fumi%2Ecsv%2Egz\"\n print(\"Downloading CBMC data\")\n\n # Create the path to save the data\n if not os.path.exists(self.save_path):\n os.makedirs(self.save_path)\n\n with urllib.request.urlopen(url) as response, open(self.save_path + self.download_name, 'wb') as out_file:\n data = response.read() # a `bytes` object\n out_file.write(data)\n\n def preprocess(self):\n print(\"Preprocessing CBMC data\")\n rows = []\n gene_names = []\n with gzip.open(self.save_path + self.download_name, \"rt\", encoding=\"utf8\") as csvfile:\n data_reader = csv.reader(csvfile, delimiter=',')\n for i, row in enumerate(data_reader):\n rows.append(row[1:])\n gene_names.append(row[0])\n\n expression_data = np.array(rows[1:], dtype=np.int).T\n gene_names = np.array(gene_names[1:], dtype=np.str)\n\n selected = np.std(expression_data, axis=0).argsort()[-600:][::-1]\n expression_data = expression_data[:, selected]\n gene_names = gene_names[selected]\n\n # train test split for log-likelihood scores\n expression_train, expression_test = GeneExpressionDataset.train_test_split(expression_data)\n\n np.save(self.save_path + \"cbmc_expression_train.npy\", expression_train)\n np.save(self.save_path + \"cbmc_expression_test.npy\", expression_test)\n np.save(self.save_path + self.gene_names, gene_names)\n\n def download_and_preprocess(self):\n if not (os.path.exists(self.save_path + self.data_filename)):\n if not os.path.exists(self.save_path + self.download_name):\n self.download()\n self.preprocess()\n","sub_path":"scvi/dataset/cbmc.py","file_name":"cbmc.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"230383","text":"# -*- coding: utf-8 -*-\n\n\nimport os\nimport sys\nimport time\nimport argparse\nfrom threading import Thread\n\nsys.path.append(os.getcwd())\n\nfrom config import Config\nfrom log import Logger\nfrom fcoin import Fcoin\nfrom fcoin_client import Fcoin_Client\nfrom trade_scalping import Trade_Scalping\nfrom hang_scalping import Hang_Scalping\nfrom sort_scalping import Sort_Scalping\nfrom margin_trade_scalping import Margin_Trade_Scalping\nfrom margin_hang_scalping import Margin_Hang_Scalping\nfrom margin_sort_scalping import Margin_Sort_Scalping\n\n# 定义全局变量\n# strategy fuc\n__strategy = {\n \"trade_scalping\": Trade_Scalping,\n \"hang_scalping\": Hang_Scalping,\n \"sort_scalping\": Sort_Scalping,\n \"margin_trade_scalping\": Margin_Trade_Scalping,\n \"margin_hang_scalping\": Margin_Hang_Scalping,\n \"margin_sort_scalping\": Margin_Sort_Scalping\n}\n\n# main\nif __name__ == '__main__':\n # parser and option\n _parser = argparse.ArgumentParser()\n _parser.add_argument('-c', '--config', type=str, default='config',\n help=\"user config file, default 'config'\") # user config file\n _option = _parser.parse_args()\n # 声明 local var\n # config\n _config = Config(_option.config)\n\n # logger\n _logger = Logger(_config)\n\n # fcoin\n _fcoin = Fcoin()\n if _config._Proxy_proxy:\n _fcoin.auth(_config._Exchange_api_key,\n _config._Exchange_api_secret, _config._Proxy_url)\n else:\n _fcoin.auth(_config._Exchange_api_key, _config._Exchange_api_secret)\n\n # fcoin_client\n if _config._Proxy_proxy:\n _fcoin_client = Fcoin_Client(\n _logger, _config._Proxy_host, _config._Proxy_port)\n else:\n _fcoin_client = Fcoin_Client(_logger)\n\n # app start\n _logger.info('----------------------------------------')\n try:\n _strategy = __strategy[_config._Main_strategy](\n _fcoin,\n _fcoin_client,\n _config._Main_base_currency,\n _config._Main_quote_currency,\n _config._Main_price_decimal,\n _config._Main_amount_decimal,\n _config._Main_min_amount,\n _config._Main_fast_init,\n _config._Main_order_epoch,\n _config._Main_order_timeout,\n _config._Main_order_position,\n _config._Main_max_position,\n _config._Main_min_position,\n _config._Main_max_fluctuate,\n _config._Main_max_retracement,\n _logger)\n _thread = Thread(target=_strategy.client_start)\n _thread.start()\n _thread.join()\n # before\n _strategy.before()\n # run loop\n while True:\n time.sleep(1)\n try:\n flag_continue = _strategy.is_Continue()\n if flag_continue:\n _strategy.process()\n except Exception as err:\n time.sleep(5)\n _logger.error(\"Unknown Error, msg=%s\" % err)\n except KeyboardInterrupt:\n # after\n _strategy.after()\n _logger.info(\"CTRL+C Pressed, Bye!\")\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"35987755","text":"# -*- coding: utf-8 -*-\nimport random\nimport string\n\nfrom django.utils.text import slugify\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.response import Response\nfrom rest_framework.status import (\n HTTP_400_BAD_REQUEST,\n HTTP_404_NOT_FOUND,\n HTTP_200_OK,\n HTTP_201_CREATED,\n HTTP_204_NO_CONTENT,\n HTTP_500_INTERNAL_SERVER_ERROR,\n HTTP_401_UNAUTHORIZED,\n)\n\nfrom apps.common.errors import ERRORS_MAP\n\n\nSTATUS_MAP = {\n 200: HTTP_200_OK,\n 201: HTTP_201_CREATED,\n 204: HTTP_204_NO_CONTENT,\n 400: HTTP_400_BAD_REQUEST,\n 401: HTTP_401_UNAUTHORIZED,\n 404: HTTP_404_NOT_FOUND,\n 500: HTTP_500_INTERNAL_SERVER_ERROR\n}\n\n\nclass DefaultPagination(PageNumberPagination):\n \"\"\"\n Customizando paginador por defecto.\n \"\"\"\n page_size = 20\n page_size_query_param = 'page_size'\n page_query_param = 'page'\n max_page_size = 100\n\n\ndef send_response(msg=None, data=None, status=200):\n response = {\n 'success': True,\n 'msg': msg,\n 'data': data\n }\n return Response(response, status=STATUS_MAP.get(status))\n\n\ndef send_error(code=None, msg=None, data=None):\n response = {\n 'code': code,\n 'error': ERRORS_MAP[code]['message'],\n 'message': msg,\n 'description': ERRORS_MAP[code]['description'],\n 'errors': data\n }\n return Response(response, status=ERRORS_MAP[code]['status'])\n\n\ndef random_string_generator(size=10,\n chars=string.ascii_lowercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef unique_slug_generator(instance, new_slug=None):\n if new_slug is not None:\n slug = new_slug\n else:\n slug = slugify(instance.name)\n Klass = instance.__class__\n qs_exists = Klass.objects.filter(slug=slug).exists()\n\n if qs_exists:\n new_slug = \"{slug}-{randstr}\".format(\n slug=slug, randstr=random_string_generator(size=4))\n\n return unique_slug_generator(instance, new_slug=new_slug)\n return slug\n","sub_path":"apps/common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"601144660","text":"# This is a sample Python script.\n#copy of working code in trial5\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\nimport re\nimport math\nimport ast\nimport csv\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\nregra = re.compile(r'phase_centre_ra_deg.*?([0-9.-]+)')\nregdec = re.compile(r'phase_centre_dec_deg.*?([0-9.-]+)')\nregfile = re.compile(r'output_text_file=../../../../OSKAR-2.7-Example-Data/[\\w-]+\\.[\\w-]+')\nphase_ra = []\nphase_dec = []\noutput_file = []\nwith open('oskar_sim_interferometer.ini') as f:\n for line in f:\n match1 = regra.match(line)\n match2 = regdec.match(line)\n match3 = regfile.match(line)\n if match1:\n phase_ra.append(match1.group(1))\n print(phase_ra)\n if match2:\n phase_dec.append(match2.group(1))\n print(phase_dec)\n\n if match3:\n output_file.append(match3.group(0))\n new_string = line.split('/')[-1]\n new_string1 = new_string.strip()\n print(new_string1)\nf.close()\nphase_ra = \", \".join(phase_ra)\nphase_dec = \", \".join(phase_dec)\nphase_ra = math.radians(float(phase_ra))\nphase_dec = math.radians(float(phase_dec))\nprint(phase_ra)\nf2 = open('newfilename10.txt','w')\nwriter = csv.writer(f2)\nthe_file = open(new_string1, 'r')\nreader = csv.reader(the_file, skipinitialspace=True)\nheader = next(reader)\nwriter.writerow(header)\nheader = next(reader)\nwriter.writerow(header)\nprint(header)\nfor line in the_file:\n x = line.strip().split(',')\n print(x)\n ra_file = math.radians(float(x[0]))\n dec_file = math.radians(float(x[1]))\n inner_radius = math.radians(-10)\n outer_radius = math.radians(10)\n sin_delta_lat = math.sin(0.5 * (phase_dec - dec_file));\n sin_delta_lon = math.sin(0.5 * (phase_ra - ra_file));\n dist = 2.0 * math.asin(math.sqrt(sin_delta_lat * sin_delta_lat + math.cos(dec_file) * math.cos(phase_dec) * sin_delta_lon * sin_delta_lon));\n# if (not(dist >= inner_radius and dist < outer_radius)):\n if (dist >= inner_radius and dist < outer_radius):\n# print([line])\n writer.writerow(x)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"79460860","text":"\"\"\"\r\n# -*- coding: utf-8 -*-\r\n# SQL 原生语句来:增删改查\r\n# @Author:AI悦创 @DateTime :2019/9/29 22:10 @Function :功能 Development_tool :PyCharm\r\n# code is far away from bugs with the god animal protecting\r\n    I love animals. They taste delicious.\r\n              ┏┓      ┏┓\r\n            ┏┛┻━━━┛┻┓\r\n            ┃      ☃      ┃\r\n            ┃  ┳┛  ┗┳  ┃\r\n            ┃      ┻      ┃\r\n            ┗━┓      ┏━┛\r\n                ┃      ┗━━━┓\r\n                ┃  神兽保佑    ┣┓\r\n                ┃ 永无BUG!   ┏┛\r\n                ┗┓┓┏━┳┓┏┛\r\n                  ┃┫┫  ┃┫┫\r\n               ��  ┗┻┛  ┗┻┛\r\n\"\"\"\r\n# 连接数据库的样板代码\r\nfrom sqlalchemy import create_engine,MetaData,Table,engine\r\nfrom sqlalchemy import Column,String,Integer,DateTime,Boolean\r\n\r\n\r\nengine = create_engine(\r\n\t\"mysql+pymysql://root:123456@127.0.0.1:3306/test\",# (里面的 root 要填写你的密码),注意:mysql+pymysql 之间不要加空格\r\n\t# \"mysql + pymysql://root:root@localhost/test\",\r\n\tmax_overflow = 5, # 超过连接池大小之后,外最多可以创建的链接\r\n\tpool_size = 10, # 连接池大小\r\n\techo = True, # 调试信息展示\r\n)\r\n\r\n# ---------创建表-------------\r\nmetadata = MetaData() # 获得元数据,介绍数据库\r\n# 定义表\r\nuser = Table('user',metadata,\r\n # 数据库表名称,元素据\r\n Column('id',Integer,primary_key=True,autoincrement=True),\r\n Column('name',String(10)))\r\nmetadata.create_all(engine) # 创建数据表\r\n\r\n# ---------------实施增删查改的操作--------------\r\n\r\n# test_database = input()\r\n# engine.execute(\"insert into user (name) values (test_database)\")\r\n# 增加数据\r\nengine.execute(\"insert into user (name) values ('AI悦创')\")\r\n# 更新数据\r\nengine.execute(\"update user set id=5,name='python' where id =5;\")\r\n# 更新数据方法二\r\nengine.execute(\"update user set name='python' where id =5;\")\r\n# 更新数据方法三\r\nengine.execute(\"update user set name='20191001'\")\r\n# 删除数据\r\n# engine.execute(\"delete from user\") # 删除全部\r\n# 删除指定位置\r\n# engine.execute(\"delete from user where id=2\")\r\n# 查看数据\r\na = engine.execute(\"select * from user\")\r\n# print(a)\r\nfor text in a:\r\n\tprint(text)\r\n\tprint(type(text))\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","sub_path":"Coder_Old/pycharm_daima/爬虫大师班/知识点/DataBase/databases_3.py","file_name":"databases_3.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"69494131","text":"import pandas as pd\n\nData = pd.read_csv('data/Allegheny County Crash Data.csv')\n\n\ndef extract_column(type):\n \"\"\"\n :param type: data type\n :return: write a csv file contains the specific column\n \"\"\"\n if type in Data:\n Data[type].to_csv('data/' + type + '.csv')\n else:\n print(type + ' dose not exist!')\n\n\ndef extract_columns(types):\n \"\"\"\n :param types: list of types\n :return: write a csv file contains all types from given list\n \"\"\"\n assert isinstance(types, list)\n columns = []\n \"\"\"check if column exists\"\"\"\n for type in types:\n if type in Data:\n columns.append(type)\n else:\n print(type + 'does not exist!')\n \"\"\"set output filename\"\"\"\n filename = ''\n for count, value in enumerate(columns):\n filename += value\n if count == len(columns)-1:\n filename += '.csv'\n else:\n filename += '_'\n \"\"\"write data\"\"\"\n Data.to_csv('data/' + filename, columns=columns)\n\n\n\"\"\"extraction examples\"\"\"\nextract_column('CRASH_YEAR')\nextract_columns(['CRASH_MONTH', 'DAY_OF_WEEK', 'HOUR_OF_DAY', 'TIME_OF_DAY'])\n","sub_path":"old versions/v1/Data_Extraction.py","file_name":"Data_Extraction.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"502913660","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 7 19:21:59 2016\n\n@author: Benben\n\"\"\"\n\n\n\n\n\ndef sol(IF):\n temp=IF.readline().split()\n B=int(temp[0])\n M=int(temp[1])\n res=''\n if M>2**(B-2):\n return 'IMPOSSIBLE'\n else:\n bb=bin(M-1)[2:]\n res='POSSIBLE\\n'\n res+='0'*(B-1-len(bb))+bb+'1'+'\\n'\n \n for i in range(2,B+1):\n res+='0'*(i)+'1'*(B-i)+'\\n'\n return res[:-1]\n \n\n\n\nIF=open('B-large.in','r')\nOF=open('B-large-output','w')\nCaseN=int(IF.readline())\nfor i in range(1, CaseN+1):\n pretext='Case #{}: '.format(i)\n ans=sol(IF)\n if i int : depth used for markov algorithm\n # _maxLength -> int : safety, the markov algorithm should stop by itself\n # _csvPath -> string : path to the csv file containing the town names\n def __init__(self, _depth, _maxLength):\n\n #Class attributes\n #private\n #Zero initialized\n self.__occurences={}\n self.__totalOccurences={}\n self.__firstStr={}\n self.__totalFirstStr={}\n self.__towns = []\n self.__populatedDepths = []\n\n #public\n self.maxLength = _maxLength\n\n dirname = os.path.dirname(__file__)\n _csvPath = os.path.join(dirname, 'communes-01012019.csv')\n\n #Getting all town names from the CV file\n with open(_csvPath, encoding='UTF-8') as csv_handle:\n reader = csv.reader(csv_handle, delimiter=',')\n for row in reader:\n #Row eight is the name of the town\n town_name = row[8].lower()\n self.__towns.append( town_name )\n\n #We now can populate occurences maps\n #it will use the now defined self.__depth\n self.changeDepth(_depth)\n # End init ------------------------------\n\n\n # Start populateMap ---------------------\n #Populating maps using self.depth\n def __populateMap( self ):\n\n #New map of starting words for this depth\n self.__firstStr[self.__depth] = {}\n self.__totalFirstStr[self.__depth] = 0\n\n #Getting depth self.__firstStrMaps into dedicated variables\n self.__firstStrDepth = self.__firstStr[self.__depth]\n\n #Iterating through each town name\n for word in self.__towns:\n\n strLen = len(word)\n\n if strLen < self.__depth:\n continue\n\n strTmp = word[0:self.__depth]\n\n if strTmp not in self.__firstStrDepth:\n #Start at 0 as this will be used as an index\n self.__firstStrDepth[strTmp] = 0\n else:\n self.__firstStrDepth[strTmp] += 1\n self.__totalFirstStr[self.__depth] += 1\n\n #Iterating through each chars of the town name\n for it in range(0, strLen - self.__depth):\n\n\n keyStr = word[it:self.__depth+it]\n\n if keyStr not in self.__occurences:\n self.__occurences[keyStr] = {}\n #Start at 0 as this will be used as an index\n self.__totalOccurences[keyStr] = 0\n\n strMap = self.__occurences[keyStr]\n\n nextChar = word[it + self.__depth]\n\n if nextChar not in strMap:\n strMap[nextChar] = 0\n else:\n strMap[nextChar]+= 1\n\n self.__totalOccurences[keyStr] += 1\n\n #Keying the last world of size self.__depth with\n #'\\0' this will allow us to end prematurely\n #the string generation with a coherent ending\n tmpStr = word[strLen-self.__depth:strLen]\n if tmpStr not in self.__occurences:\n self.__occurences[tmpStr] = {}\n self.__totalOccurences[tmpStr] = 0\n tmpMap = self.__occurences[tmpStr]\n tmpChar = '\\0'\n if tmpChar not in tmpMap:\n tmpMap[tmpChar] = 0\n else:\n tmpMap[tmpChar] += 1\n self.__totalOccurences[tmpStr] += 1\n # End populateMap -------------------------\n\n\n # Start generateMarkov --------------------\n #Generate the random string\n #Function will use self.depth and self.maxLength\n def __generateMarkov( self ):\n #We get a random word in the starting word pool\n #This will assure that the string starts with something coherent\n markovStr = \"\"\n rand = random.randrange( 0, self.__totalFirstStr[self.__depth] )\n markovStr += self.getWordAtIndex( rand, self.__firstStr[self.__depth] )\n\n #Start iterating at depth as the string as already n depth chars\n for i in range( self.__depth, self.maxLength ):\n\n #Getting the last n = depth char to use as key in the occurences maps\n strCheck = markovStr[i-self.__depth:i]\n #Draw a random number between 0 and the number of occurence of this word\n rand = random.randrange( 0, self.__totalOccurences[strCheck] )\n tmpChar = self.getWordAtIndex( rand, self.__occurences[strCheck] )\n\n #Getting a '\\0' means that the algorithm has chosen to end the string here\n if tmpChar == '\\0':\n break\n #Otherwise we continue until maxLength is reached\n markovStr += tmpChar\n\n return markovStr\n # End generateMarkov ------------------------\n\n\n '''\n getWordAtIndex( index, map )\n\n Get the letter at the given random index\n This works by drawing a random number between\n 0 and the total number of any occurences found\n after this letter\n We then iterate through the occurences to find\n the occurence a the random \"index\"\n\n Ex :\n Consider and occurence map as follows :\n {'l': 4739, 'a': 2006, 'b': 3432, 'v': 2272 }\n\n We have a total of 12449 occurences\n If we draw anything between 0 and 4738 then this\n the function will return 'l'\n If we draw anything between 4739 and 6744 then this\n the function will return 'a'\n\n This functions doesn't know the total number of self.__occurences\n it will return an empty string if the _index is out of range.\n '''\n def getWordAtIndex( self, _index, _inmap ):\n #Iterating through the occurence map\n #_map = dict(sorted(_inmap.items(), key=lambda item: item[1], reverse=True))\n tmp = 0;\n for key in _inmap:\n #increment the number of self.__occurences for this key and continue\n tmp += _inmap[key] + 1\n\n #If the combined number of self.__occurences we encountered\n #is superior to the index, then we passed it, the kay can be returned\n if tmp >= _index:\n return key\n\n\n #Should never be reached\n raise \"Reached getWordAtIndex() end\"\n # End generateMarkov -----------------------\n\n\n # Start changeDepth ------------------------\n #Setter for depth, maps need to be populated with given depth\n def changeDepth( self, _depth ):\n self.__depth = _depth\n\n #Only populate if necessary\n if _depth not in self.__populatedDepths:\n self.__populateMap()\n self.__populatedDepths.append(_depth)\n # End changeDepth --------------------------\n\n\n # Start getMarkovString --------------------\n #Generate and returns a single random string\n def getMarkovString( self ):\n\n markov = self.__generateMarkov()\n #We don't want a name that already exists\n while markov in self.__towns:\n markov = self.__generateMarkov()\n #Capitalize for flair\n markov = markov.capitalize()\n return markov\n # End getMarkovString ----------------------\n\n\n # Start getMarkovList ----------------------\n #Generate and returns a list of _nb random strings\n def getMarkovList( self, _nb ):\n\n markovs = []\n for i in range(0, _nb):\n markovs.append( self.getMarkovString() )\n return markovs\n # End getMarkovList -----------------------\n\n#-----------------------------------------------------------------#\n# End Markov Generator #\n#-----------------------------------------------------------------#\n","sub_path":"MarkovGenerator/TownNameGenerator.py","file_name":"TownNameGenerator.py","file_ext":"py","file_size_in_byte":8569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"413005050","text":"#!/usr/bin/python\r\n# # -*- coding=utf-8 -*-\r\n\r\nimport random\r\nfrom sklearn import metrics\r\nfrom keras.utils import np_utils\r\nimport numpy as np\r\nfrom keras.models import Sequential,load_model\r\nfrom keras.layers import Dense,SimpleRNN,Activation,BatchNormalization,Dense,LSTM,Conv1D,MaxPool1D,Flatten\r\nfrom common_func import loss_history,evaluate_method,read_data\r\nfrom keras import optimizers\r\nfrom tensorflow import set_random_seed\r\nset_random_seed(6)\r\nnp.random.seed(6)\r\ntrain_x, train_y_1D = read_data.read_data('train_data_yongxin.csv')\r\ntest_x, test_y_1D = read_data.read_data('test_data_yongxin.csv')\r\ntrain_y = np_utils.to_categorical(train_y_1D, 2)\r\ntest_y = np_utils.to_categorical(test_y_1D, 2)\r\n\r\ntrain_x = np.expand_dims(train_x,axis=2)\r\ntest_x = np.expand_dims(test_x,axis=2)\r\n\r\nmodel = Sequential()\r\nmodel.add(LSTM(50, batch_input_shape=(None, 16, 1), unroll=True))\r\n# model.add(Dropout(0.5))\r\nmodel.add(Dense(2))\r\nmodel.add(Activation('softmax'))\r\noptimizer = optimizers.Adam()\r\nmodel.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])\r\n# Fit the model\r\n\r\nprint(model.summary())\r\nhistory = loss_history.LossHistory()\r\nmodel.fit(train_x,train_y,validation_data= (test_x,test_y),verbose=2,callbacks=[history],batch_size=32,epochs=100)\r\n\r\n# model = load_model('my_model_lstm.h5')\r\n\r\ny_prob_test = model.predict(test_x) #output predict probability\r\ny_probability_first = [prob[1] for prob in y_prob_test]\r\n\r\nacc = evaluate_method.get_acc(test_y_1D, y_probability_first) # AUC value\r\ntest_auc = metrics.roc_auc_score(test_y_1D,y_probability_first)\r\nkappa = evaluate_method.get_kappa(test_y_1D, y_probability_first)\r\nIOA = evaluate_method.get_IOA(test_y_1D, y_probability_first)\r\nMCC = evaluate_method.get_mcc(test_y_1D, y_probability_first)\r\nrecall = evaluate_method.get_recall(test_y_1D, y_probability_first)\r\nprecision = evaluate_method.get_precision(test_y_1D, y_probability_first)\r\nf1 = evaluate_method.get_f1(test_y_1D, y_probability_first)\r\n# MAPE = evaluate_method.get_MAPE(test_y_1D,y_probability_first)\r\n\r\n# evaluate_method.get_ROC(test_y_1D,y_probability_first,save_path='roc_lstm.txt')\r\nprint(\"ACC = \" + str(acc))\r\nprint(\"AUC = \" + str(test_auc))\r\nprint(' kappa = '+ str(kappa))\r\nprint(\"IOA = \" + str(IOA))\r\nprint(\"MCC = \" + str(MCC))\r\nprint(' precision = '+ str(precision))\r\nprint(\"recall = \" + str(recall))\r\nprint(\"f1 = \" + str(f1))\r\n\r\nmodel.save('my_model_lstm1.h5')\r\n# history.loss_plot('epoch')\r\n\r\n","sub_path":"lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"221975977","text":"\"\"\"Part 1\nFor this assignment, first you'll be writing a Hashcash validator. Given a Hashcash token, you should be able to verify whether the Hashcash is valid.\n(This function will be stateless, so we won't be trying to detect double spends.)\nThe Hashcash format we'll be using is Hashcash version 1, which is formatted as follows: VERSION:DATE:EMAIL:NONCE.\nThe value for the version should always be 1. The date should span no more than 6 digits, and the nonce should be no more than 16 hex characters.\nYour function will be provided the Hashcash token as a string, the date (formatted as a string), the email, and the difficulty in bits (as an int).\nRecall that the difficulty level is the number of leading 0s measured in bits.\nWe've provided a helper function that will count the number of binary leading 0s in a hex string (given a 256-bit value).\n\nThe hash function we'll be using is SHA-2.\nHere's an example of a valid Hashcash token at difficulty 20: 1:081031:satoshin@gmx.com:b4c26b1694691666\nHere's an example of an invalid Hashcash token at difficulty 20: 1:081031:satoshin@gmx.com:835b8121ee4da3f8\n\n\nPart 2\nFor part 2 of the assignment, you'll be writing your own Hashcash minter. This will be the complement of the Hashcash validator.\nAgain, your nonce should be no more than 16 hex digits. The hash function we'll be using is SHA-2.\nYou will be provided the date as a String, email as a string, and the difficulty in bits as an Integer.\nYou need to compute the proof of work and output a valid Hashcash token. Your function should return the token as a string.\n\"\"\"\n\nfrom hashlib import sha256\n\n\ndef binary_leading_0s(hex_str: str):\n binary_representation = bin(int(hex_str, 16))[2:].zfill(256)\n return len(binary_representation) - len(binary_representation.lstrip('0'))\n\ndef is_valid(token: str, date: str, email: str, difficulty: int) -> bool:\n version = '1'\n to_validate = version + ':' + date[:6] + ':' + email + ':' + token.split(':')[-1][:16]\n digest = sha256(to_validate.encode()).hexdigest()\n return binary_leading_0s(digest) >= difficulty\n\ndef mint(date: str, email: str, difficulty: int) -> str:\n version = '1'\n prefix = version + ':' + date[:6] + ':' + email + ':'\n nonce = int('0000000000000000', 16)\n token = prefix + str(nonce)\n while not is_valid(token, date[:6], email, difficulty):\n nonce += 1\n token = prefix + str(nonce)\n return token\n","sub_path":"hashcash.py","file_name":"hashcash.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"523690057","text":"import argparse\n\nfrom bemani.format import IIDXMusicDB\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(description=\"A utility to patch a IIDX music database.\")\n parser.add_argument(\n \"infile\",\n help=\"Music DB to work with.\",\n type=str,\n )\n parser.add_argument(\n \"outfile\",\n help=\"Music DB to overwrite.\",\n type=str,\n )\n parser.add_argument(\n \"--hide-leggendarias\",\n help=\"Hide leggendarias in normal folders.\",\n action=\"store_true\",\n )\n args = parser.parse_args()\n\n fp = open(args.infile, 'rb')\n data = fp.read()\n fp.close()\n\n db = IIDXMusicDB(data)\n if args.hide_leggendarias:\n for song in db.songs:\n if song.title[-1:] == '†' or (\n song.difficulties[0] == 0 and\n song.difficulties[1] == 0 and\n song.difficulties[2] == 12\n ):\n print('Patching \\'{}\\' to only appear in leggendaria folder!'.format(song.title))\n song.folder = 0x5C\n\n print('Generating new database file...')\n fp = open(args.outfile, 'wb')\n fp.write(db.get_new_db())\n fp.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bemani/utils/iidxutils.py","file_name":"iidxutils.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"427319884","text":"testScore = 0.0\nscoreTotal = 0.0\nscoreCount = 0\nscoreAvg = 0.0\nnum = 0\n\nfor num in range(5):\n testScore = float(input(\"Please enter a test score:\"))\n scoreCount +=1\n scoreTotal += testScore\nprint(\"The average test score is\", scoreTotal/scoreCount)\n","sub_path":"Week6/For6.py","file_name":"For6.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"241186339","text":"from __future__ import annotations\n\nimport glob\nimport json\nimport os\nimport javalang\nimport argparse\nfrom typing import Any, Optional, Dict, List, Tuple\nfrom collections import defaultdict\n\n\nclass ParsedNode:\n def __init__(self, **kwargs):\n self._decl = kwargs.get('jln', None)\n self.type = kwargs.get('type', self.__try_override_type())\n self.token = kwargs.get('token', None)\n self.parent = kwargs.get('parent', None)\n self.children = kwargs.get('children', [])\n\n def __try_override_type(self) -> str:\n t = type(self._decl).__name__ if self._decl else f''\n return self.__type_map[t] or t\n\n @property\n def __type_map(self) -> defaultdict[Any, str]:\n return defaultdict(str, dict(\n VariableDeclarator='Variable',\n ))\n\n def __repr__(self):\n return self.type or self.token or ''\n\n @staticmethod\n def clone(node: ParsedNode) -> ParsedNode:\n clone = ParsedNode(type=node.type, token=node.token)\n for c in node.children:\n child_clone = ParsedNode.clone(c)\n child_clone.relink(clone)\n return clone\n\n def unlink(self) -> None:\n if self.parent:\n index = self.parent.children.index(self)\n self.parent.children = self.parent.children[:index] + self.parent.children[index+1:]\n self.parent = None\n\n def relink(self, node) -> None:\n if node:\n self.unlink()\n self.parent = node\n node.children.append(self)\n\n def child_of_type(self, node_type) -> Optional[ParsedNode]:\n for c in self.children:\n if c.type == node_type:\n return c\n return None\n\n\nclass CustomNode(ParsedNode):\n def __init__(self):\n super().__init__(type=self.__class__.__name__)\n\n\nclass CustomTokenizedNode(CustomNode):\n def __init__(self, name):\n super(CustomTokenizedNode, self).__init__()\n self.children.append(ParsedNode(token=name, parent=self))\n\n\nclass Package(CustomTokenizedNode):\n def __init__(self, name):\n super(Package, self).__init__(name)\n\n\nclass PackageMember(CustomTokenizedNode):\n def __init__(self, path):\n super(PackageMember, self).__init__(path)\n\n\nclass Identifier(CustomTokenizedNode):\n def __init__(self, name):\n super(Identifier, self).__init__(name)\n\n\nclass Value(CustomTokenizedNode):\n def __init__(self, name):\n super(Value, self).__init__(name)\n\n\nclass Accessor(CustomTokenizedNode):\n def __init__(self, name):\n super(Accessor, self).__init__(name)\n\n\nclass OperatorSpecification(CustomTokenizedNode):\n def __init__(self, name):\n super(OperatorSpecification, self).__init__(name)\n\n\nclass PrefixOperators(CustomNode):\n def __init__(self, operators):\n super(PrefixOperators, self).__init__()\n self.children = operators\n for c in self.children:\n c.parent = self\n\n\nclass PostfixOperators(CustomNode):\n def __init__(self, operators):\n super(PostfixOperators, self).__init__()\n self.children = operators\n for c in self.children:\n c.parent = self\n\n\nclass Signature(CustomNode):\n def __init__(self, nodes=None):\n super(Signature, self).__init__()\n self.children = nodes or []\n for c in self.children:\n c.parent = self\n\n\nclass Body(CustomNode):\n def __init__(self, nodes=None):\n super(Body, self).__init__()\n self.children = nodes or []\n for c in self.children:\n c.parent = self\n\n\nclass Condition(CustomNode):\n def __init__(self, nodes=None):\n super(Condition, self).__init__()\n self.children = nodes or []\n for c in self.children:\n c.parent = self\n\n\nclass InvocationArguments(CustomNode):\n def __init__(self, nodes=None):\n super(InvocationArguments, self).__init__()\n self.children = nodes or []\n for c in self.children:\n c.parent = self\n\n\nclass CompilationUnit(ParsedNode):\n def __init__(self, javalang_node):\n super().__init__(jln=javalang_node)\n if not self._decl:\n return\n package = self._decl.package\n if package:\n self.children.append(Package(package))\n for c in self.children:\n c.parent = self\n\n\nclass Import(ParsedNode):\n def __init__(self, javalang_node):\n super().__init__(jln=javalang_node)\n if not self._decl:\n return\n package = self._decl.path\n if package:\n self.children.append(PackageMember(package))\n for c in self.children:\n c.parent = self\n\n\nclass Declaration(ParsedNode):\n def __init__(self, javalang_node):\n super().__init__(jln=javalang_node)\n if not self._decl:\n return\n identifier = self._decl.name\n if identifier:\n self.children.append(Identifier(identifier))\n for c in self.children:\n c.parent = self\n\n\nclass Type(ParsedNode):\n def __init__(self, javalang_node):\n super().__init__(jln=javalang_node)\n if not self._decl:\n return\n decl_type = self._decl.name + ('[]' * len(self._decl.dimensions) if self._decl.dimensions else '')\n if decl_type:\n self.children.append(Identifier(decl_type))\n for c in self.children:\n c.parent = self\n\n\nclass Expression(ParsedNode):\n def __init__(self, javalang_node):\n super().__init__(jln=javalang_node)\n self._core = ParsedNode()\n\n def _build(self) -> None:\n if not self._decl:\n return\n\n if self._decl.qualifier:\n self.children.append(Accessor(self._decl.qualifier))\n\n self.children.append(self._core)\n\n if self._decl.prefix_operators:\n operators = self._decl.prefix_operators\n if operators:\n self.children.append(PrefixOperators([UnaryOperation(i) for i in operators]))\n\n if self._decl.postfix_operators:\n operators = self._decl.postfix_operators\n if operators:\n self.children.append(PostfixOperators([UnaryOperation(i) for i in operators]))\n\n for c in self.children:\n c.parent = self\n\n @property\n def __map(self) -> defaultdict[Any, str]:\n return defaultdict(lambda: 'Custom', {\n '+': 'Plus',\n '-': 'Minus',\n '++': 'Increment',\n '--': 'Decrement',\n '!': 'LogicalComplement'\n })\n\n\nclass Invocation(Expression):\n def __init__(self, javalang_node):\n super(Invocation, self).__init__(javalang_node)\n self._core = Identifier(self._decl.member)\n self._build()\n\n\nclass Reference(Expression):\n def __init__(self, javalang_node):\n super(Reference, self).__init__(javalang_node)\n self._core = Identifier(self._decl.member)\n self._build()\n\n\nclass Literal(Expression):\n def __init__(self, javalang_node):\n super(Literal, self).__init__(javalang_node)\n self._core = Value(self._decl.value)\n self._build()\n\n\nclass Assignment(ParsedNode):\n def __init__(self, javalang_node):\n super().__init__(jln=javalang_node)\n if not self._decl:\n return\n self.children.append(OperatorSpecification(self.__map[self._decl.type]))\n for c in self.children:\n c.parent = self\n\n @property\n def __map(self) -> defaultdict[Any, str]:\n return defaultdict(lambda: 'Regular', {\n '+=': 'Addition',\n '-=': 'Subtraction',\n '*=': 'Multiplication',\n '/=': 'Division',\n '%=': 'Modulo',\n '&=': 'BitwiseAnd',\n '|=': 'BitwiseOr',\n '^=': 'ExclusiveOr',\n '>>=': 'ShiftRight',\n '<<=': 'ShiftLeft',\n })\n\n\nclass UnaryOperation(CustomNode):\n def __init__(self, operator):\n super().__init__()\n self.children.append(OperatorSpecification(self.__map[operator]))\n for c in self.children:\n c.parent = self\n\n @property\n def __map(self) -> defaultdict[Any, str]:\n return defaultdict(lambda: 'Custom', {\n '+': 'Plus',\n '-': 'Minus',\n '++': 'Increment',\n '--': 'Decrement',\n '!': 'LogicalComplement',\n })\n\n\nclass BinaryOperation(ParsedNode):\n def __init__(self, javalang_node):\n super().__init__(jln=javalang_node)\n if not self._decl:\n return\n self.children.append(OperatorSpecification(self.__map[self._decl.operator]))\n for c in self.children:\n c.parent = self\n\n @property\n def __map(self) -> defaultdict[Any, str]:\n return defaultdict(lambda: 'Custom', {\n '==': 'Equals',\n '!=': 'NotEquals',\n '>': 'GreaterThan',\n '<': 'LessThan',\n '>=': 'GreaterThanOrEqual',\n '<=': 'LessThanOrEqual',\n '&&': 'LogicalAnd',\n '||': 'LogicalOr',\n '+': 'Addition',\n '-': 'Subtraction',\n '*': 'Multiplication',\n '/': 'Division',\n '%': 'Modulo',\n '&': 'BitwiseAnd',\n '|': 'BitwiseOr',\n '^': 'ExclusiveOr',\n '>>': 'ShiftRight',\n '<<': 'ShiftLeft',\n })\n\n\nclass JavaST:\n def __init__(self, source_code: str = None, source_code_path: str = None, root: ParsedNode = None):\n self.__javalang_root = javalang.parse.parse(source_code) if source_code else None\n if not self.__javalang_root and source_code_path:\n with open(source_code_path, 'r', encoding='utf-8') as fp:\n self.__javalang_root = javalang.parse.parse(fp.read())\n self.__node_map = defaultdict(lambda: lambda javalang_node: ParsedNode(jln=javalang_node), dict(\n CompilationUnit=lambda javalang_node: CompilationUnit(javalang_node),\n Import=lambda javalang_node: Import(javalang_node),\n ClassDeclaration=lambda javalang_node: Declaration(javalang_node),\n MethodDeclaration=lambda javalang_node: Declaration(javalang_node),\n FormalParameter=lambda javalang_node: Declaration(javalang_node),\n VariableDeclarator=lambda javalang_node: Declaration(javalang_node),\n Literal=lambda javalang_node: Literal(javalang_node),\n MemberReference=lambda javalang_node: Reference(javalang_node),\n MethodInvocation=lambda javalang_node: Invocation(javalang_node),\n Assignment=lambda javalang_node: Assignment(javalang_node),\n BinaryOperation=lambda javalang_node: BinaryOperation(javalang_node),\n Type=lambda javalang_node: Type(javalang_node),\n BasicType=lambda javalang_node: Type(javalang_node),\n ReferenceType=lambda javalang_node: Type(javalang_node),\n ))\n self.root = root or ParsedNode()\n self.__repr = []\n if self.__javalang_root:\n self.__traverse()\n self.__fixup()\n\n def __traverse(self) -> None:\n parent_stack = []\n prev_depth = 0\n prev_node = ParsedNode()\n for path, node in self.__javalang_root:\n depth = len(path)\n name = type(node).__name__\n parsed = self.__node_map[name](node)\n\n if depth == 0:\n self.root = parsed\n elif depth < prev_depth:\n while True:\n d, n = parent_stack.pop()\n if d < depth:\n parent_stack.append((d, n))\n _, parent = parent_stack[-1]\n parent.children.append(parsed)\n parsed.parent = parent\n break\n elif depth >= prev_depth:\n if depth > prev_depth:\n parent_stack.append((prev_depth, prev_node))\n _, parent = parent_stack[-1]\n parent.children.append(parsed)\n parsed.parent = parent\n\n prev_node = parsed\n prev_depth = depth\n\n def __fixup(self, root: ParsedNode = None) -> None:\n root = root or self.root\n children = root.children[:]\n signature, body, condition = None, None, None\n for c in children:\n if root.type in [\n 'ClassDeclaration',\n 'MethodDeclaration',\n ]:\n if root.type == 'MethodDeclaration':\n body = root.child_of_type('Body')\n if not body:\n body = Body()\n body.parent = root\n root.children = [body] + root.children\n\n signature = root.child_of_type('Signature')\n if not signature:\n signature = Signature()\n signature.parent = root\n root.children = [signature] + root.children\n\n if c.type in [\n 'Identifier',\n 'BasicType',\n 'ReferenceType',\n 'FormalParameter',\n ]:\n c.relink(signature)\n elif body:\n c.relink(body)\n\n if 'Type' in root.type:\n if c.type not in [\n 'Identifier',\n ]:\n if root.parent.type == 'Signature' and c.type != 'FormalParameter':\n body = root.parent.parent.child_of_type('Body')\n c.relink(body)\n elif root.parent.type == 'ClassCreator':\n if c._decl in root.parent._decl.arguments:\n arguments = root.parent.child_of_type('InvocationArguments')\n if not arguments:\n arguments = InvocationArguments()\n arguments.parent = root.parent\n root.parent.children = root.parent.children + [arguments]\n c.relink(arguments)\n else:\n c.relink(root.parent)\n\n if root.type == 'BinaryOperation':\n if children.index(c) >= 3:\n c.relink(root.parent)\n\n if root.type in [\n 'WhileStatement',\n 'IfStatement',\n ]:\n if c.type not in [\n 'BlockStatement',\n ]:\n condition = root.child_of_type('Condition')\n if not condition:\n condition = Condition()\n condition.parent = root\n root.children = [condition] + root.children\n c.relink(condition)\n\n if root.type in [\n 'MethodInvocation',\n 'ClassCreator',\n ]:\n if c.type not in [\n 'Accessor',\n 'Identifier',\n 'PrefixOperators',\n 'PostfixOperators',\n 'ReferenceType',\n 'BasicType',\n ]:\n if c._decl in root._decl.arguments:\n arguments = root.child_of_type('InvocationArguments')\n if not arguments:\n arguments = InvocationArguments()\n arguments.parent = root\n root.children = root.children + [arguments]\n c.relink(arguments)\n\n self.__fixup(c)\n\n def __traverse_repr(self, root: ParsedNode = None, depth: int = 0) -> str:\n if not root:\n self.__repr = []\n root = self.root\n indent = ' ' * depth\n self.__repr.append(f'{indent}{root}')\n for c in root.children:\n if c:\n self.__traverse_repr(c, depth + 1)\n return '\\n'.join(self.__repr)\n\n def __repr__(self):\n return self.__traverse_repr().strip('\\n')\n\n def __traverse_json(self, root: ParsedNode = None) -> Dict[str, Any]:\n root = root or self.root\n jo = dict()\n if root.type and root.type != 'None':\n jo['Type'] = root.type\n if root.token and root.token != 'None':\n jo['Token'] = root.token\n if root.children:\n jo['Children'] = []\n\n for c in root.children:\n jo['Children'].append(self.__traverse_json(c))\n\n return jo\n\n def __traverse_statements(self, root: ParsedNode = None, sequence: List[JavaST] = None, prune: bool = False) -> List[JavaST]:\n root = root or ParsedNode.clone(self.root)\n sequence = sequence or []\n for c in root.children[:]:\n if c.type in [\n 'ClassDeclaration',\n 'ConstructorDeclaration',\n 'MethodDeclaration',\n 'FieldDeclaration',\n 'LocalVariableDeclaration',\n 'StatementExpression',\n 'ForStatement',\n 'WhileStatement',\n 'IfStatement',\n 'ReturnStatement',\n 'TryStatement',\n 'CatchClause',\n 'MethodInvocation',\n ]:\n c.unlink()\n sequence.append(JavaST(root=c))\n self.__traverse_statements(c, sequence, prune)\n\n if prune:\n can_unlink = False\n can_unlink |= c.type in [\n 'Value',\n 'Accessor',\n 'CatchClause',\n ]\n if c.token:\n can_unlink = True\n can_unlink &= root.type not in [\n 'OperatorSpecification',\n ]\n if root.type == 'Identifier':\n can_unlink &= str.lower(c.token) not in [\n 'i', 'j', 'k', 'l', 'm', 'n',\n ]\n can_unlink &= root.parent.type not in [\n #'BasicType',\n #'ReferenceType',\n ]\n if can_unlink:\n c.unlink()\n if prune:\n if root.type in ['Identifier', 'OperatorSpecification']:\n if root.children:\n c = root.children[0]\n c.unlink()\n i = root.parent.children.index(root)\n root.parent.children[i] = c\n else:\n root.unlink()\n filtered_sequence = []\n for tree in sequence:\n if tree.root.children:\n filtered_sequence.append(tree)\n return filtered_sequence\n\n def as_json(self) -> Dict[str, Any]:\n return self.__traverse_json()\n\n def as_vocab(self) -> Dict[str, int]:\n vocab = defaultdict(int)\n queue = [self.root]\n while len(queue) > 0:\n node = queue[0]\n queue = queue[1:]\n for c in node.children:\n queue.append(c)\n vocab[node.type or node.token] += 1\n return vocab\n\n def as_statement_tree_sequence(self, prune: bool = False) -> List[JavaST]:\n return self.__traverse_statements(prune=prune)\n\n def flatten(self, root: ParsedNode = None, index: int = 0) -> Tuple[List[str], int]:\n root = root or self.root\n children_indices = []\n flattened = [f'{root}\\t']\n for c in root.children:\n index += 1\n children_indices.append(index)\n c_flat, index = self.flatten(c, index)\n for child in c_flat:\n flattened.append(child)\n flattened[0] = flattened[0] + ' '.join(map(str, children_indices))\n return flattened, index\n\n def flatten_level(self, root: ParsedNode = None, level: int = 0) -> List[str]:\n root = root or self.root\n flattened = [f'{level}\\t{root}\\t']\n for c in root.children:\n flattened += self.flatten(c, level + 1)\n flattened[0] = flattened[0] + [i for i, _ in enumerate(root.children)]\n return flattened\n\n\ndef generate_tree_representations(args) -> None:\n path = args.path\n pre, ext = os.path.splitext(path)\n try:\n with open(path, 'r', encoding='utf-8') as fp:\n tree = JavaST(source_code=fp.read())\n except:\n if not args.silent:\n print(f'Couldn\\'t read {path}')\n\n try:\n with open(pre + '.java.ast', 'w', encoding='utf-8') as fp:\n print(tree, file=fp, sep='')\n if not args.silent:\n print(f'Generated {pre + \".java.ast\"}')\n except:\n if not args.silent:\n print(f'Couldn\\'t generate {pre + \".java.ast\"}')\n\n if args.json:\n try:\n with open(pre + '.java.ast.json', 'w', encoding='utf-8') as fp:\n json.dump(tree.as_json(), fp, indent=4)\n if not args.silent:\n print(f'Generated {pre + \".java.ast.json\"}')\n except:\n if not args.silent:\n print(f'Couldn\\'t generate {pre + \".java.ast.json\"}')\n\n try:\n seq = tree.as_statement_tree_sequence(args.prune)\n with open(pre + '.java.ast.stm', 'w', encoding='utf-8') as fp:\n for block in seq:\n print(f'{block}\\n', file=fp)\n if not args.silent:\n print(f'Generated {pre + \".java.ast.stm\"}')\n\n with open(pre + '.java.ast.stm.flat', 'w', encoding='utf-8') as fp:\n for block in seq:\n flattened = '\\n'.join(block.flatten()[0])\n print(f'{flattened}\\n', file=fp)\n if not args.silent:\n print(f'Generated {pre + \".java.ast.stm.flat\"}')\n except:\n if not args.silent:\n print(f'Couldn\\'t generate {pre + \".java.ast.stm\"}')\n print(f'Couldn\\'t generate {pre + \".java.ast.stm.flat\"}')\n\n\nif __name__ == '__main__':\n argparser = argparse.ArgumentParser(description='Build syntax tree for Java source code.')\n argparser.add_argument('path',\n help='path to .java file',\n action='store')\n argparser.add_argument('-a', '--all',\n help='iterate over each `.java` in folder',\n action='store_true')\n argparser.add_argument('-j', '--json',\n help='additionally stores the tree as a JSON object',\n action='store_true')\n argparser.add_argument('-s', '--silent',\n help='silent',\n action='store_true')\n argparser.add_argument('--prune',\n help='prune tree',\n action='store_true')\n\n args = argparser.parse_args()\n if args.all:\n for i in glob.iglob(pathname=os.path.join(args.path, '**\\*.java'), recursive=True):\n args.path = i\n generate_tree_representations(args)\n else:\n generate_tree_representations(argparser.parse_args())\n","sub_path":"utils/java_ast/java_ast_provider.py","file_name":"java_ast_provider.py","file_ext":"py","file_size_in_byte":23133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"498071107","text":"from kivymd.app import MDApp\r\nfrom kivymd.uix.screen import MDScreen\r\nfrom kivymd.uix.label import MDLabel\r\nfrom kivymd.uix.button import MDIconButton, MDFlatButton, MDRectangleFlatButton\r\nfrom kivy.lang import Builder\r\nfrom kivymd.uix.dialog import MDDialog\r\nfrom helpers import username_helper\r\n\r\n\r\nclass Agro(MDApp):\r\n def build(self):\r\n self.theme_cls.primary_palette = \"Green\"\r\n self.theme_cls.primary_hue = \"A700\"\r\n self.theme_cls.theme_style = \"Light\"\r\n screen = MDScreen()\r\n # username_input = MDTextField(text='Enter user name', pos_hint={'center_x': 0.5, 'center_y': 0.5},\r\n # size_hint_x=None, width=300)\r\n label = MDLabel(text='Hello world', halign='center',\r\n font_size=30, theme_text_color='Primary')\r\n self.username_input = Builder.load_string(username_helper)\r\n btn_rect = MDRectangleFlatButton(text='Login', pos_hint={'center_x': 0.5, 'center_y': 0.3},\r\n on_release=self.show_data)\r\n screen.add_widget(btn_rect)\r\n screen.add_widget(self.username_input)\r\n return screen\r\n\r\n def show_data(self, obj):\r\n close_flat = MDFlatButton(text=\"Close\", on_release=self.close_dialog)\r\n close_icon_btn = MDIconButton(icon='close', on_release=self.close_dialog)\r\n more_flat = MDFlatButton(text=\"More\")\r\n self.dialog = MDDialog(title=\"Login\", text=self.username_input.text, size_hint=(0.7, 1),\r\n buttons=[more_flat, close_icon_btn])\r\n\r\n if self.username_input.text is not \"\":\r\n self.dialog.open()\r\n print('dialog is up')\r\n else:\r\n dialog = MDDialog(title=\"Login\", text=\"Please enter username\", size_hint=(0.7, 1),)\r\n dialog.open()\r\n\r\n def close_dialog(self, obj):\r\n self.dialog.dismiss()\r\n\r\nAgro().run()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"297438447","text":"'''\r\n2元1瓶饮料\r\n2个空瓶可以换一瓶饮料\r\n4个瓶盖可以换一瓶饮料\r\n问带X(x>2)元可以喝几瓶\r\nn # 记录饮料数\r\nbutton # 记录瓶盖\r\nbottle # 记录空瓶\r\nmoney # 记录多少元钱\r\n'''\r\nn = 0\r\ndef drink(money, button=0, bottle=0):\r\n global n\r\n if button >= 4:\r\n button -= 3\r\n bottle += 1\r\n n += 1\r\n drink(money,button,bottle)\r\n elif bottle >= 2:\r\n button += 1\r\n bottle -= 1\r\n n += 1\r\n drink(money,button,bottle)\r\n else:\r\n if money>1:\r\n money -= 2\r\n button += 1\r\n bottle += 1\r\n n += 1\r\n drink(money,button,bottle)\r\n else:\r\n #当钱money不足2元,但瓶盖剩余3个,可以先和老板借一个瓶盖,喝了这瓶饮料将瓶盖还给老板,即botton=0,但空瓶多了一个\r\n if button == 3:\r\n button = 0\r\n bottle += 1\r\n n += 1\r\n drink(money,button,bottle)\r\n # 当钱money不足2元,但空瓶剩余1个,可以先和老板借一个空瓶,喝了这瓶饮料将空瓶还给老板,所以空瓶都不可能有剩余\r\n elif bottle == 1:\r\n bottle = 0\r\n button += 1\r\n n += 1\r\n drink(money,button,bottle)\r\n else:\r\n print('总共喝了%d瓶' % n)\r\n print('剩余%d个瓶盖' % button)\r\n print('剩余%d个瓶子' % bottle)\r\n print('剩余%d元钱' % money)\r\nif __name__ == '__main__':\r\n s=input('请输入你的钱')\r\n","sub_path":"drink.py","file_name":"drink.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"25002868","text":"import os\nimport sys\nfrom sqlalchemy import Column, ForeignKey, Integer, String, Boolean\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\nfrom eralchemy import render_er\n\nBase = declarative_base()\n\nclass Character(Base):\n __tablename__ = 'character'\n # Here we define columns for the table person\n # Notice that each column is also a normal Python instance attribute.\n id = Column(Integer, primary_key=True)\n name = Column(String(250), nullable=False)\n height = Column(Integer,nullable=False)\n hair_color = Column(String(50),nullable=False)\n skin_color = Column(String(50),nullable=False)\n eye_color = Column(String(50),nullable=False)\n birth_year = Column(String(50),nullable=False)\n gender = Column(String(50),nullable=False)\n home_world = Column(String(50),nullable=False)\n\n\nclass Planets(Base):\n __tablename__ = 'planets'\n # Here we define columns for the table address.\n # Notice that each column is also a normal Python instance attribute.\n id = Column(Integer, primary_key=True)\n name = Column(String(250), nullable=False)\n rotationPeriod = Column(Integer, nullable=False)\n orbitalPeriod = Column(Integer, nullable=False)\n diameter = Column(String(250), nullable=False)\n climate = Column(String(50), nullable=False)\n gravity = Column(String(50), nullable=False)\n terrain = Column(String(50), nullable=False)\n surfaceWater = Column(Integer, nullable=False)\n population = Column(Integer, nullable=False)\n\nclass User(Base):\n __tablename__ = 'user'\n id = Column(Integer, primary_key=True)\n name = Column(String(250), nullable=False)\n email = Column(String(50), nullable=False)\n\nclass Favorites(Base):\n __tablename__ = 'favorites'\n id = Column(Integer, primary_key=True)\n user_id = Column(Integer,ForeignKey(User.id))\n character_id = Column(String(50),ForeignKey(Character.id))\n planets_id = Column(String(50),ForeignKey(Planets.id))\n \n def to_dict(self):\n return {}\n\n## Draw from SQLAlchemy base\nrender_er(Base, 'diagram.png')","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"173554839","text":"import subprocess, datetime\n\nprint(\"Commencing speedtest....\")\n\npingServers = [\"google.com\", \"bbc.com\", \"bing.com\"]\n\ndef log(ping):\n\twith open(\"log.txt\", \"a\") as logFile:\n\t\tlogFile.write(\"{}, {}\\n\".format(datetime.datetime.now().time(), ping))\n\ndef speedTest(pingservers, numTries):\n\tresults = []\n\tfor host in pingServers:\n\t\tprint(\"--------------------------------\\nPinging {} {} times:\".format(host, numTries))\n\t\tproc = subprocess.Popen([\"ping\", host, \"-c {}\".format(numTries)], stdout=subprocess.PIPE)\n\t\tline = proc.stdout.readline()#Make sure \"PING example.com\" doesn't increment progress bar\n\n\t\tcounter = 0 \n\t\twhile True:\n\t\t\tprint(\"<|{}{}|>\".format(\"#\" * counter, \" \" * (numTries - counter)), end =\"\\r\")#Increment progress bar after each ping\n\t\t\tline = proc.stdout.readline()\n\t\t\tline = line.decode('utf-8')\n\t\t\t#print(line)\n\t\t\tcounter += 1\n\t\t\tif \"rtt\" in line:\n\t\t\t\teqIndex = line.index(\"=\")\n\t\t\t\tslashIndex = line.find(\"/\", eqIndex) + 1\n\t\t\t\tnextSlashIndex = line.find(\"/\", slashIndex)\n\t\t\t\tavg = line[slashIndex:nextSlashIndex]\n\t\t\t\tprint(\"Average ping to {} from {} attempts: {}\".format(host, numTries, avg))\n\t\t\t\tresults.append(float(avg))\n\t\t\t\tbreak\n\n\tfinalAvg = int(sum(results)/len(results))\n\tprint(\"\\n***************************\\nOverall average ping: {} ms\\n***************************\".format(finalAvg))\n\treturn(finalAvg)\n\nspeed = speedTest(pingServers, 10)\nlog(speed)\n","sub_path":"speed_test.py","file_name":"speed_test.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"442572158","text":"# -*- coding: utf-8 -*-\nimport os, sys, time\n\nimport gevent\nfrom gevent.event import Event\nfrom gevent import monkey; monkey.patch_all()\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../../util'))\nimport config\nimport db\nimport loghelper\n\n\n\n#logger\nloghelper.init_logger(\"remove_bd_sshot\", stream=True)\nlogger = loghelper.get_logger(\"remove_bd_sshot\")\n\n#mongo\nmongo = db.connect_mongo()\n\ncollection_android = mongo.market.android\ncollection_android_market = mongo.market.android_market\n\ncnt = 0\ndef change_update(apkname, Appp):\n global cnt\n apps_new = list(collection_android_market.find({\"appmarket\": {\"$in\": [16010,16020,16030,16040]}, \"apkname\": apkname},{\"apkname\": 1, \"appmarket\":1, \"link\":1,\"version\":1,\"updateDate\":1}))\n if len(apps_new) ==0:\n logger.info(\"no other app\")\n # collection_android.update_one({\"apkname\": apkname},\n # {\"$set\": {\"screenshots\": []}})\n return 1\n else:\n updateDate = None\n link = None\n for app in apps_new:\n if app[\"version\"] == Appp[\"version\"] and app[\"updateDate\"] is not None and (updateDate is None or updateDate < app[\"updateDate\"]) :\n logger.info(\"Change with appmarket: %s, %s\", app[\"appmarket\"], app[\"apkname\"])\n link = app[\"link\"]\n updateDate = app[\"updateDate\"]\n if updateDate is not None and link is not None:\n collection_android.update_one({\"apkname\": apkname},{\"$set\": {\"updateDate\": updateDate, \"link\": link}})\n return 2\n else:\n collection_android.update_one({\"apkname\": apkname}, {\"$set\": {\"updateDate\": Appp[\"createTime\"]}})\n return 3\n\n\n\n\ndef start_run():\n global cnt\n (num0,num1,num2,num3)=(0,0,0,0)\n while True:\n logger.info(\"check screen start...\")\n #run(appmkt, WandoujiaCrawler(), \"com.ctd.m3gd\")\n apps = list(collection_android.find({\"updateDateChecked\": {\"$ne\": True},\"apkname\":{\"$ne\":None}},{\"updateDate\":1, \"apkname\": 1,\"version\":1,\"createTime\":1}, limit=1000))\n for app in apps:\n # logger.info(app[\"_id\"])\n apkname = app[\"apkname\"]\n # logger.info(apkname)\n ud = app[\"updateDate\"]\n collection_android.update_one({\"apkname\": apkname},\n {\"$set\": {\"screenshotchecked\": True}})\n logger.info(apkname)\n if ud is not None:\n pass\n else:\n num0 += 1\n logger.info(\"change************\")\n result = change_update(apkname, app)\n if result == 1: num1+=1\n if result == 2: num2+=1\n if result == 3: num3+=1\n\n collection_android.update_one({\"apkname\": apkname},\n {\"$set\": {\"updateDateChecked\": True}})\n logger.info(\"finish\")\n logger.info(\"*******************total : %s/%s/%s/%s\", num0, num1, num2, num3)#break\n logger.info(\"\\n\\n\\n\\n\")\n # break\n if len(apps) == 0:\n break\n #break\n # logger.info(\"total : %s/%s/%s/%s\", num0,num1,num2,num3)\n\nif __name__ == \"__main__\":\n start_run()","sub_path":"data/spider2/aggregator/market/patch_android_updateDate.py","file_name":"patch_android_updateDate.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"64080793","text":"#python3에서는 시간초과납니다 ㅠㅠ.. pypy3에서는 통과하는 추후에 다시 .\nimport sys\nfrom collections import deque\ninput = sys.stdin.readline\nN, L, R = map(int,input().split())\n\ngraph = [list(map(int,input().split())) for _ in range(N)]\n\ndx = [0, 0, -1, 1]\ndy = [1, -1, 0, 0]\ndef bfs(graph,x,y,visited):\n \n q = deque([[x,y]])\n #x,y를 기준으로 연합 가능한지역을 담을 배열.\n union = [[x,y]]\n cnt = 1\n #x,y를 기준으로 연합 가능한지역의 값들을 합한후 cnt 로나눈값을 담을꺼.\n val = graph[x][y]\n visited[x][y] = 1\n while q:\n x, y = q.popleft()\n for i in range(4):\n nx, ny = x + dx[i], y + dy[i]\n # 이동할곳이 맵 안이어야함.\n if 0 <= nx < N and 0 <= ny < N:\n dif = abs(graph[x][y] - graph[nx][ny])\n #위 아래 왼 오른 중 한군데라도 연합이 가능하면 가능한것.\n if L <= dif <= R and dif != 0 and not visited[nx][ny]:\n visited[nx][ny] = 1\n q.append([nx,ny])\n union.append([nx,ny])\n val += graph[nx][ny]\n cnt += 1\n if cnt == 1:\n return False\n else:\n for x, y in union:\n graph[x][y] = int(val/(cnt))\n return True\nanswer = 0\nwhile True:\n changed = False\n visited = [[0]*N for _ in range(N)]\n for i in range(N):\n for j in range(N):\n if not visited[i][j]:\n k=bfs(graph,i,j,visited)\n if k:\n changed = True\n #한바퀴 돌아도 연합을 만들수 없을경우 종료\n if not changed:\n break\n else:\n answer += 1\nprint(answer)\n","sub_path":"bj16234(나중에 성능올려보기).py","file_name":"bj16234(나중에 성능올려보기).py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"17755949","text":"\"\"\"\nGets data from anilist.co.\n\"\"\"\nimport logging\nfrom datetime import datetime\nfrom typing import List, Tuple\n\nimport requests\n\nfrom ..errors import AnilistException\nfrom .utils import Measure\nfrom ..options import OPTIONS\n\nlogger = logging.getLogger('animethemes-dl')\n\nALURL = 'https://graphql.anilist.co'\nALQUERY = \"\"\"\nquery userList($user: String) {\n MediaListCollection(userName: $user, type: ANIME) {\n lists {\n status\n entries {\n status\n score\n priority\n media {\n idMal\n title {\n romaji\n }\n startDate {\n year\n month\n day\n }\n }\n }\n }\n }\n}\n\"\"\"\n\ndef get_raw_anilist(username: str, query: str=ALQUERY, **vars) -> dict:\n \"\"\"\n Gets an anilist list with a username.\n Takes an optional query and variables.\n `vars['user']` will be set to `username`.\n \"\"\"\n vars['user'] = username\n json_arg = {'query': query, 'variables': vars}\n \n r = requests.post(ALURL,json=json_arg)\n if r.status_code == 200:\n data = r.json()\n else:\n return r.raise_for_status()\n \n if \"errors\" in data:\n errors = '; '.join(i['message'] for i in data['errors'])\n logger.exception(f'[error] {errors}')\n raise AnilistException(errors)\n else:\n lists = data['data'][\"MediaListCollection\"][\"lists\"]\n logger.debug(f'Got {sum(len(i) for i in lists)} enries from anilist.')\n return lists\n\ndef sort_anilist(data: dict) -> List[Tuple[int,str]]:\n \"\"\"\n Filters an anilist list and returns a list of titles.\n Removes all unwanted statuses, scores, priorities.\n Also filters out unreleased anime.\n \"\"\"\n titles = []\n for i in data:\n status = {\n 'CURRENT':1,\n 'COMPLETED':2,\n 'PAUSED':3,\n 'DROPPED':4,\n 'PLANNING':6,\n 'REPEATING':1, # rewatching\n }[i['status']]\n for entry in i['entries']:\n media = entry.pop('media')\n score = entry['score']\n priority = entry['priority']\n start_date = media['startDate']\n malid = media['idMal']\n title = media['title']['romaji']\n \n if not( # animelist options\n status in OPTIONS['statuses'] and\n score >= OPTIONS['animelist']['minscore'] and\n priority >= OPTIONS['animelist']['minpriority']\n ):\n continue\n \n if ( # invalid date\n None in start_date['year'].values() or # didn't start\n datetime(**start_date) > datetime.now() # didn't start yet\n ):\n continue\n titles.append((malid,title))\n \n return titles\n\ndef get_anilist(username: str, **vars) -> List[Tuple[int,str]]:\n \"\"\"\n Gets an anilist list with a username.\n \"\"\"\n measure = Measure()\n raw = get_raw_anilist(username, **vars)\n data = sort_anilist(raw)\n logger.info(f'[get] Got data from anilist in {measure()}s.')\n return data\n\nif __name__ == \"__main__\":\n from pprint import pprint\n pprint(get_anilist('sadru'))\n","sub_path":"animethemes_dl/parsers/anilist.py","file_name":"anilist.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"320118345","text":"# -*- coding: utf-8 -*-\nfrom scrapy import Spider, Request\nfrom scrapy.spiders import Rule, CrawlSpider\nfrom scrapy.linkextractors import LinkExtractor\nfrom baike.items import BaikeHrefItem\n\n\nclass BaiduspiderSpider(CrawlSpider):\n name = \"baidubaike\"\n allowed_domains = [\"baike.baidu.com\"]\n start_urls = (\n 'http://baike.baidu.com/',\n )\n rules = (\n Rule(LinkExtractor(allow=('.*baike.baidu.com/view/.*', ), )),\n Rule(LinkExtractor(allow=('.*baike.baidu.com/subview/.*', ), )),\n )\n POOL = set()\n\n def parse(self, response):\n url = response.url\n url = url.split(\"?\")[0] if \"?\" in url else url\n if \"/view/\" in url or \"/subview/\" in url:\n title = response.xpath('//title/text()').extract()[0]\n title = \"\".join(title.split('_')[:-1])\n if url not in self.POOL:\n self.POOL.add(url)\n yield BaikeHrefItem(url=url, title=title)\n links = response.xpath('//a[@href]/@href').extract()\n for link in links:\n url = link.strip()\n if not url.startswith(\"http\"):\n if url.startswith(\"/view\") or url.startswith(\"/subview\"):\n url = \"http://baike.baidu.com\" + url\n yield Request(url, callback=self.parse)\n","sub_path":"baike/baike/spiders/baiduspider.py","file_name":"baiduspider.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"119258677","text":"class Solution:\n def partition(self, s: str) -> List[List[str]]:\n self.dp = defaultdict(list)\n if not s: \n return [[]]\n if s in self.dp: \n return self.dp[s] \n ans = []\n for i in range(1, len(s) + 1):\n palindrome = s[:i]\n if palindrome == palindrome[::-1]: \n for suffix in self.partition(s[i:]): \n ans.append([palindrome] + suffix)\n self.dp[s] = ans\n return ans","sub_path":"Strings/palindromePartitioning.py","file_name":"palindromePartitioning.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"25463382","text":"from django.conf.urls import include, url, patterns\r\nfrom views import addView, BlogView, BlogId, login1, log_out,addComment\r\nimport models\r\ndic = {'model': models.Kind.objects.all()}\r\nurlpatterns = [\r\n\turl(r'login$',login1),\r\n\turl(r'logout$',log_out),\r\n\turl(r'^.*?/login$',login1),\r\n\turl(r'^.*?/logout$',log_out),\r\n url(r'^$', BlogView, dic),\r\n url(r'^add$', addView, {'model': models.Blog}),\r\n url(r'^(?P\\d+)/$', BlogId, dic),\r\n url(r'^(?P\\d+)/addcomment$',addComment,dic),\r\n url(r'^(?P.+)$', BlogView, dic),\r\n \r\n\r\n]\r\n'''\r\nurl(r'^users/$', listView, {'model': models.User}),\r\nurl(r'^users/add/$', addView, {'model': models.User}),\r\n'''\r\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"625137586","text":"\"\"\"Provides an interface to import numerical libraries using the GPU (if available).\n\nThe main goal of this is to smooth over the differences between numpy and cupy so that\nthe rest of the code can use them interchangably. We also need to monkey patch scipy's ivp solver\nto work on cupy arrays.\n.. note:: Linters **HATE** this module because it's really abusing the import system (by design).\n\n\"\"\"\n\nimport contextlib\n\n# Default imports for cpu code\n# This will be overwritten with a call to .numerical_libs.use_cupy()\nimport numpy as xp\nimport scipy.integrate._ivp.ivp as ivp # noqa: F401 # pylint: disable=unused-import\nimport scipy.sparse as sparse # noqa: F401 # pylint: disable=unused-import\n\nxp.scatter_add = xp.add.at\nxp.optimize_kernels = contextlib.nullcontext\nxp.to_cpu = lambda x, **kwargs: x # one arg noop\n\n\nclass ExperimentalWarning(Warning):\n \"\"\"Simple class to mock the optuna warning if we don't have optuna\"\"\"\n\n\nxp.ExperimentalWarning = ExperimentalWarning\n\n\ndef use_cupy(optimize=False):\n \"\"\"Perform imports for libraries with APIs matching numpy, scipy.integrate.ivp, scipy.sparse.\n\n These imports will use a monkey-patched version of these modules\n that has had all it's numpy references replaced with CuPy.\n\n if optimize is True, place the kernel optimization context in xp.optimize_kernels,\n otherwise make it a nullcontext (noop)\n\n returns nothing but imports a version of 'xp', 'ivp', and 'sparse' to the global scope of this module\n\n Parameters\n ----------\n optimize : bool\n Enable kernel optimization in cupy >=v8.0.0. This will slow down initial\n function call (mostly reduction operations) but will offer better\n performance for repeated calls (e.g. in the RHS call of an integrator).\n\n Returns\n -------\n exit_code : int\n Non-zero value indicates error code, or zero on success.\n\n Raises\n ------\n NotImplementedError\n If the user calls a monkeypatched function of the libs that isn't\n fully implemented.\n\n \"\"\"\n import importlib # pylint: disable=import-outside-toplevel\n import logging # pylint: disable=import-outside-toplevel\n import sys # pylint: disable=import-outside-toplevel\n\n cupy_spec = importlib.util.find_spec(\"cupy\")\n if cupy_spec is None:\n logging.info(\"CuPy not found, reverting to cpu/numpy\")\n return 1\n\n global xp, ivp, sparse # pylint: disable=global-statement\n\n if xp.__name__ == \"cupy\":\n logging.info(\"CuPy already loaded, skipping\")\n return 0\n\n # modify src before importing\n def modify_and_import(module_name, package, modification_func):\n spec = importlib.util.find_spec(module_name, package)\n source = spec.loader.get_source(module_name)\n new_source = modification_func(source)\n module = importlib.util.module_from_spec(spec)\n codeobj = compile(new_source, module.__spec__.origin, \"exec\")\n exec(codeobj, module.__dict__) # pylint: disable=exec-used\n sys.modules[module_name] = module\n return module\n\n import cupy as cp # pylint: disable=import-outside-toplevel\n import numpy as np # pylint: disable=import-outside-toplevel, reimported\n\n cp.cuda.set_allocator(cp.cuda.MemoryPool(cp.cuda.memory.malloc_managed).malloc)\n\n # add cupy search sorted for scipy.ivp (this was only added to cupy sometime between v6.0.0 and v7.0.0)\n if ~hasattr(cp, \"searchsorted\"):\n # NB: this isn't correct in general but it works for what scipy solve_ivp needs...\n def cp_searchsorted(a, v, side=\"right\", sorter=None):\n if side != \"right\":\n raise NotImplementedError\n if sorter is not None:\n raise NotImplementedError # sorter = list(range(len(a)))\n tmp = v >= a\n if cp.all(tmp):\n return len(a)\n return cp.argmax(~tmp)\n\n cp.searchsorted = cp_searchsorted\n\n for name in (\"common\", \"base\", \"rk\", \"ivp\"):\n ivp = modify_and_import(\n \"scipy.integrate._ivp.\" + name,\n None,\n lambda src: src.replace(\"import numpy\", \"import cupy\"),\n )\n\n import cupyx # pylint: disable=import-outside-toplevel\n\n cp.scatter_add = cupyx.scatter_add\n\n spec = importlib.util.find_spec(\"optuna\")\n if spec is None:\n logging.info(\"Optuna not installed, kernel opt is disabled\")\n cp.optimize_kernels = contextlib.nullcontext\n cp.ExperimentalWarning = ExperimentalWarning\n elif optimize:\n import optuna # pylint: disable=import-outside-toplevel\n\n optuna.logging.set_verbosity(optuna.logging.WARN)\n logging.info(\"Using optuna to optimize kernels, the first calls will be slowwwww\")\n cp.optimize_kernels = cupyx.optimizing.optimize\n cp.ExperimentalWarning = optuna.exceptions.ExperimentalWarning\n else:\n cp.optimize_kernels = contextlib.nullcontext\n cp.ExperimentalWarning = ExperimentalWarning\n\n def cp_to_cpu(x, stream=None, out=None):\n if \"cupy\" in type(x).__module__:\n return x.get(stream=stream, out=out)\n return x\n\n cp.to_cpu = cp_to_cpu\n\n # Add a version of np.r_ to cupy that just calls numpy\n # has to be a class b/c r_ uses sq brackets\n class cp_r_:\n def __getitem__(self, inds):\n return cp.array(np.r_[inds])\n\n cp.r_ = cp_r_()\n\n xp = cp\n import cupyx.scipy.sparse as sparse # pylint: disable=import-outside-toplevel,redefined-outer-name\n\n # TODO need to check cupy version is >9.0.0a1 in order to use sparse\n\n return 0\n","sub_path":"bucky/numerical_libs.py","file_name":"numerical_libs.py","file_ext":"py","file_size_in_byte":5590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"19188131","text":"import cv2\r\nimport numpy as np\r\n#red==1\r\nlowerBound1=np.array([160,100,100])\r\nupperBound1=np.array([179,255,255])\r\n#green==2\r\nlowerBound2=np.array([33,80,40])\r\nupperBound2=np.array([90,255,255])\r\n#blue==3\r\nlowerBound3=np.array([100,86,40])\r\nupperBound3=np.array([121,255,255])\r\n#yellow==4\r\nlowerBound4=np.array([20,100,100])\r\nupperBound4=np.array([30,255,255])\r\n#ORANGE==5\r\nlowerBound5=np.array([10,100,100])\r\nupperBound5=np.array([20,255,255])\r\n\r\n\r\ndef findshape(img):\r\n imgGRAY=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n edges = cv2.Canny(imgGRAY, 100, 255)\r\n img2, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n image = 0\r\n\r\n for cnt in contours:\r\n area=cv2.contourArea(cnt)\r\n hull = cv2.convexHull(cnt)\r\n approx = cv2.approxPolyDP(cnt,0.02*cv2.arcLength(cnt,True),True)\r\n if len(approx)==4:\r\n name=\"quadilateral\"\r\n elif len(approx)==5:\r\n name=\"pentagon\"\r\n elif len(approx)==3:\r\n name=\"Triangle\"\r\n\r\n elif len(approx) > 7:\r\n name=\"circle\"\r\n else:\r\n name=\"shape not detect\"\r\n if(area>50):\r\n M=cv2.moments(cnt)\r\n Cx=( int(M['m10']/M['m00']) )\r\n Cy=( int(M['m01']/M['m00']) )\r\n cv2.putText(img, name, (Cx, Cy), cv2.FONT_HERSHEY_SIMPLEX,0.4, (255, 0, 0), 1)\r\ndef findcolor(color):\r\n if color==1:\r\n mask = cv2.inRange(imgHSV, lowerBound1,upperBound1)\r\n col = cv2.bitwise_and(img,img, mask= mask)\r\n #findshape(col)\r\n cv2.imshow(\"image\",img)\r\n cv2.imshow(\"Red coloured Objects\",col)\r\n #cv2.imwrite(\"redout.png\",col)\r\n if color==2:\r\n mask = cv2.inRange(imgHSV, lowerBound2,upperBound2)\r\n col = cv2.bitwise_and(img,img, mask= mask)\r\n #findshape(col)\r\n cv2.imshow(\"image\",img)\r\n cv2.imshow(\"Green coloured Objects\",col)\r\n #cv2.imwrite(\"greenout.png\",col)\r\n if color==3:\r\n mask = cv2.inRange(imgHSV, lowerBound3,upperBound3)\r\n col = cv2.bitwise_and(img,img, mask= mask)\r\n #findshape(col)\r\n cv2.imshow(\"image\",img)\r\n cv2.imshow(\"Blue coloured Objects\",col)\r\n #cv2.imwrite(\"blueout.png\",col)\r\n if color==4:\r\n mask = cv2.inRange(imgHSV, lowerBound4,upperBound4)\r\n col = cv2.bitwise_and(img,img, mask= mask)\r\n #findshape(col)\r\n cv2.imshow(\"image\",img)\r\n cv2.imshow(\"Yellow coloured Objects\",col)\r\n #cv2.imwrite(\"yellowout.png\",col)\r\n if color==5:\r\n mask = cv2.inRange(imgHSV, lowerBound5,upperBound5)\r\n col = cv2.bitwise_and(img,img, mask= mask)\r\n #findshape(col)\r\n cv2.imshow(\"image\",img)\r\n cv2.imshow(\"Orange coloured Objects\",col)\r\n #cv2.imwrite(\"orangeout.png\",col)\r\n\r\ncap = cv2.VideoCapture(1)\r\n#img =cv2.imread(\"45.png\")\r\nwhile(1):\r\n _,img = cap.read()\r\n bluredimg=cv2.GaussianBlur(img,(5,5),1)\r\n imgGRAY=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n imgHSV=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\r\n findcolor(1)\r\n k = cv2.waitKey(5) & 0xFF\r\n if k == 27:\r\n break\r\n\r\n# Destroys all of the HighGUI windows.\r\ncv2.destroyAllWindows()\r\n\r\n# release the captured frame\r\ncap.release()","sub_path":"color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191320239","text":"import numpy as np\nimport pickle as pkl\nimport networkx as nx\nimport scipy.sparse as sp\n\n\ndef parse_index_file(filename):\n index = []\n for line in open(filename):\n index.append(int(line.strip()))\n return index\n\n\ndef load_data(dataset):\n # load the data: x, tx, allx, graph\n names = ['x', 'tx', 'allx', 'graph']\n objects = []\n for i in range(len(names)):\n objects.append(pkl.load(open(\"data/ind.{}.{}\".format(dataset, names[i]))))\n x, tx, allx, graph = tuple(objects)\n # \"\"\"\n # x = <140x1433 sparse matrix of type ''\n # with 2647 stored elements in Compressed Sparse Row format>\n # tx = <1000x1433 sparse matrix of type ''\n # with 17955 stored elements in Compressed Sparse Row format>\n # allx = <1708x1433 sparse matrix of type ''\n # with 31261 stored elements in Compressed Sparse Row format>\n # type(graph) = \n # \"\"\"\n test_idx_reorder = parse_index_file(\"data/ind.{}.test.index\".format(dataset))\n test_idx_range = np.sort(test_idx_reorder)\n\n if dataset == 'citeseer':\n # Fix citeseer dataset (there are some isolated nodes in the graph)\n # Find isolated nodes, add them as zero-vecs into the right position\n test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder)+1)\n tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))\n tx_extended[test_idx_range-min(test_idx_range), :] = tx\n tx = tx_extended\n\n features = sp.vstack((allx, tx)).tolil()\n features[test_idx_reorder, :] = features[test_idx_range, :]\n adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))\n # \"\"\"\n # (Pdb) p features\n # <2708x1433 sparse matrix of type ''\n # with 49216 stored elements in LInked List format>\n # (Pdb) p adj\n # <2708x2708 sparse matrix of type ''\n # with 10556 stored elements in Compressed Sparse Row format>\n # (Pdb) p adj.data.max()\n # 1\n # (Pdb) p adj.data.min()\n # 1\n # (Pdb) p features.data.max()\n # [1.0, 1.0, 1.0, 1.0, 1.0, ..., 1.0, 1.0, 1.0, 1.0, 1.0] (len=30)\n # (Pdb) p features.data.min()\n # [1.0]\n # \"\"\"\n return adj, features\n","sub_path":"gae/input_data.py","file_name":"input_data.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"437801750","text":"import requests\nimport random\nimport logging\nfrom bs4 import BeautifulSoup\nfrom queue import Queue\nfrom threading import Thread, Lock, currentThread\n\nlock = Lock()\nqueue = Queue()\nkinopoisk_pages = {}\n\n\ndef fetch_afisha_page():\n logging.info('Obtaining the list of movies from afisha...')\n afisha_url = 'http://www.afisha.ru/msk/schedule_cinema/'\n return requests.get(afisha_url).text\n\n\ndef parse_afisha_list(raw_html, cinemas_limit):\n soup = BeautifulSoup(raw_html, 'lxml')\n\n movies_titles_tags = soup.find_all('div', {'class': 'm-disp-table'})\n\n afisha_movies_info = {}\n for movie_title_tag in movies_titles_tags:\n cinemas_count = len(movie_title_tag.parent.find_all('td', {'class': 'b-td-item'}))\n if cinemas_count >= cinemas_limit:\n movie_title = movie_title_tag.find('a').text\n movie_afisha_url = movie_title_tag.find('a').attrs['href']\n afisha_movies_info[movie_title] = {\n 'movie_afisha_url': movie_afisha_url,\n 'cinemas_count': cinemas_count\n }\n queue.put(movie_title)\n\n return afisha_movies_info\n\n\ndef fetch_kinopoisk_movie_page(movie_title, proxies_list):\n logging.info('[%s] Get \"%s\"...', currentThread().name, movie_title)\n timeout = 3\n kinopoisk_page_url = 'https://www.kinopoisk.ru/index.php'\n params = {\n 'kp_query': movie_title,\n 'first': 'yes'\n }\n\n while True:\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'Agent:%s'.format(get_random_agent())\n }\n proxy_ip = get_random_proxy(proxies_list)\n proxy = {'http': proxy_ip}\n\n logging.info('[%s] Try proxy %s...', currentThread().name, proxy_ip)\n\n try:\n request = requests.Session().get(\n kinopoisk_page_url,\n params=params,\n headers=headers,\n proxies=proxy,\n timeout=timeout\n )\n except(requests.exceptions.ConnectTimeout,\n requests.exceptions.ConnectionError,\n requests.exceptions.ProxyError,\n requests.exceptions.ReadTimeout):\n logging.exception('[%s] Connect error. Reconnect...', currentThread().name)\n else:\n break\n\n global kinopoisk_pages\n with lock:\n kinopoisk_pages[movie_title] = request.text\n\n\ndef get_text(elem):\n try:\n text = elem.text\n except AttributeError:\n text = None\n return text\n\n\ndef parse_kinopoisk_movie_page(raw_html):\n soup = BeautifulSoup(raw_html, 'lxml')\n\n img_box = soup.find('div', {'class': 'film-img-box'})\n if img_box is not None:\n img = img_box.find('img')\n if img is not None:\n film_img = img.attrs['src']\n else:\n film_img = None\n else:\n film_img = None\n\n kinopoisk_movie_info = {\n 'rating': get_text(soup.find('span', {'class': 'rating_ball'})),\n 'rating_count': get_text(soup.find('span', {'class': 'ratingCount'})),\n 'film_synopsys': get_text(soup.find('div', {'class': 'brand_words film-synopsys'})),\n 'film_img': film_img\n }\n\n return kinopoisk_movie_info\n\n\ndef worker(proxies_list):\n while True:\n movie_title = queue.get()\n if movie_title is None:\n break\n fetch_kinopoisk_movie_page(movie_title, proxies_list)\n queue.task_done()\n\n\ndef get_movies_info(cinemas_limit, threads_count):\n afisha_page = fetch_afisha_page()\n afisha_movies_info = parse_afisha_list(afisha_page, cinemas_limit)\n\n proxies_list = get_proxies_list()\n for thread_num in range(threads_count):\n new_thread = Thread(target=worker,\n kwargs={'proxies_list': proxies_list},\n name='THREAD_{0}'.format(thread_num))\n new_thread.daemon = True\n new_thread.start()\n queue.join()\n\n movies_info = []\n for movie_title in kinopoisk_pages:\n kinopoisk_movie_info = parse_kinopoisk_movie_page(kinopoisk_pages[movie_title])\n movies_info.append({\n 'movie_title': movie_title,\n 'cinemas_count': afisha_movies_info[movie_title]['cinemas_count'],\n 'movie_afisha_url': afisha_movies_info[movie_title]['movie_afisha_url'],\n 'rating': kinopoisk_movie_info['rating'],\n 'rating_count': kinopoisk_movie_info['rating_count'],\n 'film_synopsys': kinopoisk_movie_info['film_synopsys'],\n 'film_img': kinopoisk_movie_info['film_img']\n })\n\n return movies_info\n\n\ndef sort_movies_list(movies):\n return sorted(\n movies,\n key=lambda item: item['rating'] if item['rating'] is not None else '0',\n reverse=True\n )\n\n\ndef get_random_agent():\n agent_list = [\n 'Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0',\n 'Opera/9.80 (Windows NT 6.2; WOW64) Presto/2.12.388 Version/12.17',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0'\n ]\n return random.choice(agent_list)\n\n\ndef get_proxies_list():\n proxy_url = 'http://www.freeproxy-list.ru/api/proxy'\n params = {'anonymity': 'true', 'token': 'demo'}\n request = requests.get(proxy_url, params=params).text\n proxies_list = request.split('\\n')\n return proxies_list\n\n\ndef get_random_proxy(proxy_list):\n return random.choice(proxy_list)\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"cinemas.py","file_name":"cinemas.py","file_ext":"py","file_size_in_byte":5652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"53821075","text":"import time\nimport math\nfrom itertools import combinations \n\n# Naive solution using combinations. Extremely slow.\n# Obvious ways to improve:\n# 1) in numbers[], only include numbers up to sqrt(n)\n# 2) in candidates, remove duplicates such as (1, 2) and (2, 1)\ndef check_square_sum(n,a): \n for i in a:\n n -= i*i\n return n==0\n\ndef sum_of_squares(n):\n print(n)\n numbers = [i for i in range(1,n+1)] \n i = 1\n while i <= n : \n candidates = list(combinations(numbers *i, i)) \n print(candidates)\n for c in candidates:\n if check_square_sum(n,c):\n return i\n i+=1\n \nif __name__ == \"__main__\":\n start = time.time()\n max = 100001\n max_digits=math.floor(math.log10(max))+1\n for i in range(1,max):\n t1 = time.time()\n s = sum_of_squares(i)\n istr = str(i).rjust(max_digits)\n t2 = time.time()\n print(f\"{istr}: sum of {s} perfect squares: computed in {t2-t1} sec. Elapsed time: {t2-start} sec.\")\n end = time.time()\n print(f\"Total elapsed time: {end-start} seconds\") ","sub_path":"sum_of_squares/SumOfPerfectSquares-naive-comb.py","file_name":"SumOfPerfectSquares-naive-comb.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"441255519","text":"from multiprocessing import Process\nfrom multiprocessing import Queue\nfrom datetime import datetime\nimport time\n\nclass server(Process):\n def __init__(self, server_write_q, server_read_q):\n super(server, self).__init__()\n self.read_q = server_read_q\n self.write_q = server_write_q\n\n def run(self):\n while True:\n msg = self.read_q.get()\n self.write_q.put(msg)\n\nclass client(Process):\n def __init__(self, server_write_q, server_read_q):\n super(client, self).__init__()\n self.read_q = server_write_q\n self.write_q = server_read_q\n\n def run(self):\n msg = \"Hello!\"\n msg_cnt = 0\n msg_measure = 50000\n t_meas = datetime.now()\n while True:\n self.write_q.put(msg)\n msg = self.read_q.get()\n\n msg_cnt += 1\n if msg_cnt % msg_measure == 0:\n t_delta = datetime.now() - t_meas\n msg_sec = msg_measure / t_delta.total_seconds()\n t_per_msg = 100000 * t_delta.total_seconds() / msg_measure\n print(\"{} msgs took {} seconds or {} us per msg or {} msgs/sec.\".format( \n msg_measure,\n t_delta.total_seconds(),\n t_per_msg,\n msg_sec))\n\n t_meas = datetime.now()\n\nif __name__ == '__main__':\n server_write_q = Queue()\n server_read_q = Queue()\n aserver = server(server_write_q, server_read_q)\n aclient = client(server_write_q, server_read_q)\n aserver.start()\n aclient.start()\n\n while True:\n time.sleep(10)\n","sub_path":"multiprocess_queue_test.py","file_name":"multiprocess_queue_test.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"88272260","text":"import os\nimport math\nimport librosa\nimport numpy as np\n\nINSTR_DIR = '../dataset/trainset/audio'\nSPEC_DIR = '../dataset/trainset/spectrum'\nSAMPLE_RATE = 11000\nFRAG_LENGTH = 66302\nWIN_LENGTH = 1022\nHOP_LENGTH = 256\n\n# mkdir if not exist\nif os.path.exists(SPEC_DIR) == False:\n os.mkdir(SPEC_DIR)\n\ninstr_class = os.listdir(INSTR_DIR)\nfor instr in instr_class:\n # mkdir if not exist\n spec_dir = os.path.join(SPEC_DIR, instr)\n if os.path.exists(spec_dir) == False:\n os.mkdir(spec_dir)\n \n audio_dir = os.path.join(INSTR_DIR, instr)\n audios = os.listdir(audio_dir)\n for audio in audios:\n # mkdir if not exist\n num = audio[0:-4]\n dst_dir = os.path.join(spec_dir, num)\n if os.path.exists(dst_dir) == False:\n os.mkdir(dst_dir)\n\n # load audio\n audio_path = os.path.join(audio_dir, audio)\n wave, _ = librosa.load(audio_path, sr=SAMPLE_RATE)\n frag_num = math.floor(len(wave)/FRAG_LENGTH)\n for cnt in range(frag_num):\n # STFT\n frag = wave[cnt*FRAG_LENGTH:(cnt+1)*FRAG_LENGTH]\n spec = librosa.stft(frag, n_fft=WIN_LENGTH, hop_length=HOP_LENGTH, center=False)\n\n # save spectrum\n spec_path = os.path.join(dst_dir, str(cnt))\n np.save(spec_path, spec)\n \n print('audio %2s in %s processed.' % (num, instr))\n","sub_path":"code/utils/audio_preprocess.py","file_name":"audio_preprocess.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"570481211","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 6 15:39:22 2020\n\n@author: akloss\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function, unicode_literals\n\nimport numpy as np\nfrom differentiable_filters.contexts import recordio as tfr\nimport logging\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport argparse\nimport sys\n\n\nclass ToyExample():\n def __init__(self, param):\n self.im_size = param.width\n self.out_dir = param.out_dir\n self.name = param.name\n self.num_examples = param.num_examples\n self.sequence_length = param.sequence_length\n self.file_size = min(self.num_examples, param.file_size)\n self.debug = param.debug\n\n self.spring_force = 0.05\n self.drag_force = 0.0075\n\n self.cols = [(0, 255, 0), (0, 0, 255), (0, 255, 255), (255, 0, 255),\n (255, 255, 0), (255, 255, 255)]\n\n if not os.path.exists(self.out_dir):\n os.makedirs(self.out_dir)\n\n # setup logging\n self.log = logging.getLogger(param.name)\n self.log.setLevel(logging.DEBUG)\n # create formatter and add it to the handlers\n formatter = logging.Formatter('%(asctime)s: [%(name)s] ' +\n '[%(levelname)s] %(message)s')\n # create console handler\n ch = logging.StreamHandler(sys.stdout)\n ch.setLevel(logging.DEBUG)\n ch.setFormatter(formatter)\n self.log.addHandler(ch)\n\n # create file handler which logs warnings errors and criticals\n if os.path.exists(os.path.join(self.out_dir,\n self.name + '_error.log')):\n os.remove(os.path.join(self.out_dir,\n self.name + '_error.log'))\n fh = logging.FileHandler(os.path.join(self.out_dir,\n self.name + '_error.log'))\n fh.setLevel(logging.WARNING)\n fh.setFormatter(formatter)\n self.log.addHandler(fh)\n\n def create_dataset(self, num_distractors, hetero_q, corr_q, pos_noise):\n # setup a debug directory\n self.debug_dir = os.path.join(self.out_dir, 'debug', self.name)\n if not os.path.exists(self.debug_dir):\n os.makedirs(self.debug_dir)\n\n mean_rgb = np.zeros(3)\n train_count = 0\n val_count = 0\n test_count = 0\n\n self.keys = ['start_image', 'start_state', 'image', 'state', 'q',\n 'visible']\n train_data = {key: [] for key in self.keys}\n\n self.record_writer_train = \\\n tfr.RecordioWriter(self.out_dir, self.file_size,\n self.name + '_train_')\n self.record_meta_train = tfr.RecordMeta(self.name + '_train_')\n self.record_writer_val = \\\n tfr.RecordioWriter(self.out_dir, self.file_size,\n self.name + '_val_')\n self.record_meta_val = tfr.RecordMeta(self.name + '_val_')\n self.record_writer_test = \\\n tfr.RecordioWriter(self.out_dir, self.file_size,\n self.name + '_test_')\n self.record_meta_test = tfr.RecordMeta(self.name + '_test_')\n\n self.ct = 0\n self.log.info('Starting to generate dataset ' + self.name)\n while train_count < self.num_examples:\n values = self._get_data(num_distractors, hetero_q, corr_q,\n pos_noise)\n self.ct += 1\n mean_rgb += \\\n values['image'].mean(axis=0).mean(axis=0).mean(axis=0)\n for key in self.keys:\n train_data[key] += [values[key]]\n if len(train_data['image']) > self.file_size:\n train_size, val_size, test_size = self._save(train_data)\n train_count += train_size\n val_count += val_size\n test_count += test_size\n train_data = {key: [] for key in self.keys}\n\n if len(train_data['image']) % 250 == 0:\n self.log.info('Done ' + str(len(train_data['image'])) +\n ' of ' + str(self.num_examples))\n if len(train_data['image']) > 0:\n train_size, val_size, test_size = self._save(train_data)\n train_count += train_size\n val_count += val_size\n test_count += test_size\n\n # save the meta information\n count = train_count + val_count + test_count\n fi = open(os.path.join(self.out_dir, 'info_' + self.name + '.txt'),\n 'w')\n fi.write('Num data points: ' + str(count) + '\\n')\n fi.write('Num train: ' + str(train_count) + '\\n')\n fi.write('Num val: ' + str(val_count) + '\\n')\n fi.write('Num test: ' + str(test_count) + '\\n')\n fi.write('mean rgb: ' + str(mean_rgb / (count)) + '\\n')\n fi.close()\n\n self.log.info('Done')\n\n self.record_writer_train.close()\n self.record_writer_test.close()\n self.record_writer_val.close()\n\n return\n\n def _get_data(self, num_distractors, hetero_q, corr_q, pos_noise):\n states = []\n images = []\n qs = []\n rs = []\n\n # the state consists of the red disc's position and velocity\n # draw a random position\n pos = np.random.uniform(-self.im_size//2, self.im_size//2, size=(2))\n # draw a random velocity\n vel = np.random.normal(loc=0, scale=1, size=(2)) * 3\n initial_state = np.array([pos[0], pos[1], vel[0], vel[1]])\n\n distractors = []\n for dist in range(num_distractors):\n # also draw a random starting positions for distractors\n pos = np.random.uniform(-self.im_size//2, self.im_size//2,\n size=(2))\n # draw a random velocity\n vel = np.random.normal(loc=0, scale=1, size=(2)) * 3\n # and a random radius\n rad = np.random.choice(np.arange(3, 10))\n # draw a random color\n col = np.random.choice(len(self.cols))\n distractors += [(rad, np.array([pos[0], pos[1], vel[0], vel[1]]),\n col)]\n\n # generate the initial image\n initial_im, initial_vis = self._observation_model(initial_state,\n distractors)\n last_state = initial_state\n for step in range(self.sequence_length):\n # get the next state\n state, q = self._process_model(last_state, hetero_q, corr_q,\n pos_noise, True)\n # also move the distractors\n new_distractors = []\n for d in distractors:\n d_new, _ = self._process_model(d[1], hetero_q, corr_q,\n pos_noise)\n new_distractors += [(d[0], d_new, d[2])]\n # get the new image\n im, vis = self._observation_model(state, new_distractors)\n\n states += [state]\n images += [im]\n qs += [q]\n rs += [vis]\n distractors = new_distractors\n last_state = state\n\n if self.ct < 3 and self.debug:\n for i, im in enumerate(images):\n fig, ax = plt.subplots()\n ax.set_axis_off()\n ax.imshow(im)\n fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9,\n wspace=0.1, hspace=0.1)\n\n fig.savefig(os.path.join(self.debug_dir, str(self.ct) +\n \"_tracking_\" + str(i)),\n bbox_inches=\"tight\")\n plt.close(fig)\n\n return {'start_image': initial_im, 'start_state': initial_state,\n 'image': np.array(images), 'state': np.array(states),\n 'q': np.array(qs), 'visible': np.array(rs)}\n\n def _observation_model(self, state, distractors):\n im = np.zeros((self.im_size, self.im_size, 3))\n\n # draw the red disc\n cv2.circle(im, (int(state[0]+self.im_size//2),\n int(state[1]+self.im_size//2)),\n radius=7, color=[255, 0, 0], thickness=-1)\n\n # draw the other distractors\n for d in distractors:\n cv2.circle(im, (int(d[1][0]+self.im_size//2),\n int(d[1][1]+self.im_size//2)),\n radius=d[0], color=self.cols[d[2]], thickness=-1)\n\n # get the number of pixels visible from the red disc\n mask = np.logical_and(im[:, :, 0] == 255,\n np.logical_and(im[:, :, 1] == 0,\n im[:, :, 2] == 0))\n\n vis = np.sum(mask)\n im = im.astype(np.float32) / 255.\n return im, vis\n\n def _process_model(self, state, hetero_q, correlated, pos_noise,\n debug=False):\n new_state = np.copy(state)\n pull_force = - self.spring_force * state[:2]\n drag_force = - self.drag_force * state[2:]**2 * np.sign(state[2:])\n new_state[0] += state[2]\n new_state[1] += state[3]\n new_state[2] += pull_force[0] + drag_force[0]\n new_state[3] += pull_force[1] + drag_force[1]\n\n if not correlated:\n position_noise = np.random.normal(loc=0, scale=pos_noise, size=(2))\n if hetero_q:\n if np.abs(state[0]) > self.im_size//2 - self.im_size//6 or \\\n np.abs(state[1]) > self.im_size//2 - self.im_size//6:\n velocity_noise = np.random.normal(loc=0, scale=0.1,\n size=(2))\n q = 0.1\n elif np.abs(state[0]) > self.im_size//2 - self.im_size//3 or \\\n np.abs(state[1]) > self.im_size//2 - self.im_size//3:\n velocity_noise = np.random.normal(loc=0, scale=1.,\n size=(2))\n q = 1.\n else:\n velocity_noise = np.random.normal(loc=0, scale=3.,\n size=(2))\n q = 3.\n else:\n velocity_noise = np.random.normal(loc=0, scale=2.,\n size=(2))\n q = 2.\n\n new_state[:2] += position_noise\n new_state[2:] += velocity_noise\n\n q = np.array([pos_noise, pos_noise, q, q])\n else:\n pn = 3.0\n cn = 2\n c1 = -0.4\n c2 = 0.2\n c3 = 0.9\n c4 = -0.1\n c5 = 0\n\n covar = np.array([[pn**2, c1*pn*pn, c2*pn*cn, c3*pn*cn],\n [c1*pn*pn, pn**2, c4*pn*cn, c5*pn*cn],\n [c2*pn*cn, c4*pn*cn, cn**2, 0],\n [c3*pn*cn, c5*pn*cn, 0, cn**2]])\n\n mean = np.zeros((4))\n noise = np.random.multivariate_normal(mean, covar)\n q = covar\n new_state += noise\n\n return new_state, q\n\n def _save(self, data):\n length = len(data['image'])\n # convert lists to numpy arrays\n for key in self.keys:\n if type(data[key]) == np.ndarray and data[key].dtype == np.float64:\n data[key] = np.array(data[key]).astype(np.float32)\n\n # shuffle the arrays together\n permutation = np.random.permutation(length)\n for key in self.keys:\n vals = np.copy(data[key])\n data[key] = vals[permutation]\n\n train_size = int(np.floor(length * 8. / 10.))\n val_size = int(np.floor(length * 1. / 10.))\n test_size = length - train_size - val_size\n\n if train_size > 0:\n train_data = {}\n for key in self.keys:\n train_data[key] = np.copy(data[key][:train_size])\n rw = self.record_writer_train\n rm = self.record_meta_train\n tfr.write_tfr(train_data, rw, rm, self.out_dir)\n\n if val_size > 0:\n val_data = {}\n for key in self.keys:\n val_data[key] = \\\n np.copy(data[key][train_size:train_size+val_size])\n rw = self.record_writer_val\n rm = self.record_meta_val\n tfr.write_tfr(val_data, rw, rm, self.out_dir)\n\n if test_size > 0:\n test_data = {}\n for key in self.keys:\n test_data[key] = np.copy(data[key][train_size+val_size:])\n rw = self.record_writer_test\n rm = self.record_meta_test\n tfr.write_tfr(test_data, rw, rm, self.out_dir)\n return train_size, val_size, test_size\n\n\ndef main(argv=None):\n parser = argparse.ArgumentParser('toy datset')\n parser.add_argument('--name', dest='name', type=str, default='toy')\n parser.add_argument('--out-dir', dest='out_dir', type=str, required=True,\n help='where to store results')\n parser.add_argument('--sequence-length', dest='sequence_length', type=int,\n default=50, help='length of the generated sequences')\n parser.add_argument('--width', dest='width', type=int, default=120,\n help='width (= height) of the generated observations')\n parser.add_argument('--num-examples', dest='num_examples', type=int,\n default=2000,\n help='how many training examples should be generated')\n parser.add_argument('--file-size', dest='file_size', type=int,\n default=500,\n help='how many examples per file should be saved in ' +\n 'one record')\n parser.add_argument('--hetero-q', dest='hetero_q', type=int,\n default=0, choices=[0, 1],\n help='if the process noise should be heteroscedastic '\n + 'or contstant')\n parser.add_argument('--correlated-q', dest='correlated_q', type=int,\n default=0, choices=[0, 1],\n help='if the process noise should have a full or a '\n + 'diagonal covariance matrix')\n parser.add_argument('--pos-noise', dest='pos_noise', type=float,\n default=0.1,\n help='sigma for the positional process noise')\n parser.add_argument('--num-distractors', dest='num_distractors', type=int,\n default=5, help='number of distractor disc')\n parser.add_argument('--debug', dest='debug', type=int,\n default=0, choices=[0, 1],\n help='Write out images for three sequences as debug ' +\n 'output')\n\n args = parser.parse_args(argv)\n\n name = args.name + '_pn=' + str(args.pos_noise) \\\n + '_d=' + str(args.num_distractors)\n if args.correlated_q:\n name += '_corr'\n if args.hetero_q:\n name += '_hetero'\n else:\n name += '_const'\n\n args.name = name\n\n if not os.path.exists(os.path.join(args.out_dir,\n 'info_' + args.name + '.txt')):\n c = ToyExample(args)\n c.create_dataset(args.num_distractors, args.hetero_q,\n args.correlated_q, args.pos_noise)\n else:\n print('name already exists')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"differentiable_filters/data/create_toy_dataset.py","file_name":"create_toy_dataset.py","file_ext":"py","file_size_in_byte":15506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"577111449","text":"# crawKuaixun.py\n# coding=utf-8\n# author=zhouj\nimport re\nimport urllib\nimport datetime\nimport time\nfrom bs4 import BeautifulSoup\nfrom agent import *\nfrom match import *\nfrom crawArticle import *\n\n#默认utf-8 编码\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n#获取快讯文章\ndef get_kuaixun(url, file_object, got_art_urls):\n\t#获取文章html\n\thtml = url_user_agent(url, 15)\n\tsoup = BeautifulSoup(html, \"html.parser\")\n\tarticles = soup.select('.layout-news')\n\tsqlList = list()\n\tflag = 0\n\tfor article in articles:\n\t\tsoup1 = BeautifulSoup(str(article), \"html.parser\")\n\t\t#标题、前言、时间、链接\n\t\ttitle = get_title(soup1, 15)\n\t\tcreate_time = get_time(soup1, 15)\n\t\tpreinfo = get_content(soup1, 15)\n\t\tre_link = re.findall(r'href=\"([\\s\\S]*?)\"',preinfo)\n\t\tlink = re_link[0]\n\t\t#判断链接是否之前存在\n\t\tif link+'1\\n' in got_art_urls:\n\t\t\tcontinue\n\t\tif time_match(create_time,15) == False:\n\t\t\tcontinue\n\t\t#修改前言, 后尾添加1防止跟之前在魔多爬的网站重复\n\t\tgot_art_urls.append(link+'1\\n')\n\t\tfile_object.write(link+'1\\n')\n\t\tre_info = re.findall(r'>([\\s\\S]*?)= l and int(grafo[l][c]) == 1:\n arestas += 1\n\n print(f\"O grafo tem {arestas} arestas\")\n return arestas\n\ndef info_arestas(grafo, vertices):\n \"\"\"\n Informa quais são as arestas do grafo\n \"\"\"\n print(f\"\\n~=~=~= Info Arestas =~=~=~\")\n for l in range(vertices):\n for c in range(vertices):\n if c >= l and int(grafo[l][c]) == 1:\n print(f\"{l+1} - {c+1}\")\n\ndef grafo_simples(grafo, vertices):\n \"\"\"\n Verifica se o grafo é um grafo simples\n \"\"\"\n for l in range(vertices):\n for c in range(vertices):\n if c >= l and int(grafo[l][c]) > 1: #verifica se tem arestas duplas\n return 0\n elif c == l and int(grafo[l][c]) > 0: #verifica se tem laço\n return 0\n\n print(\"\\nÉ um grafo simples\")\n return 1\n\ndef grafo_completo(grafo, vertices):\n \"\"\"\n Verifica se o grafo é um grafo completo\n \"\"\"\n for l in range(vertices):\n for c in range(vertices):\n if c > l and int(grafo[l][c]) == 0:\n print(\"Não é um grafo completo!\")\n grafo_complementar(grafo, vertices)\n return 0\n\n print(\"É um grafo completo!\")\n\ndef grafo_complementar(grafo, vertices):\n \"\"\"\n Mostra o grafo complementar \n \"\"\"\n cont = 0\n print(f\"\\n~=~ Grafo complementar ~=~\")\n for l in range(vertices):\n for c in range(vertices):\n if c > l and int(grafo[l][c]) == 0:\n print(f\"{l+1} - {c+1}\")\n cont += 1\n\n print(f\"\\nFaltam {cont} arestas para ser um grafo completo!\")\n\ndef soma_graus(grafo, vertices):\n \"\"\"\n Mostra a somatória dos graus do grafo\n \"\"\"\n soma = 0\n\n for l in range(vertices):\n for c in range(vertices):\n if int(grafo[l][c]) == 1:\n if l == c:\n soma += 2\n else:\n soma += 1\n\n print(f\"A soma dos graus do grafo é: {soma}\")\n\ndef grafo_bipartido(grafo, vertices):\n \"\"\"\n verifica se o grafo é bipartido\n \"\"\"\n conj_a, conj_b, conj_c, copia, adj = [], [], [], [], []\n\n for l in range(vertices):\n copia.append(grafo[l])\n\n for l in range(vertices):\n if l == 0:\n for c in range(vertices):\n if int(copia[l][c]) == 1:\n copia[l][c] = \"8\"\n adj.append(c+1)\n teste = adj[:]\n\n if l+1 not in adj:\n for c in range(vertices):\n if int(copia[l][c]) == 1:\n copia[l][c] = \"8\"\n if c+1 not in adj:\n adj.append(c+1)\n\n if l+1 in adj:\n for c in range(vertices):\n if int(copia[l][c]) == 1:\n copia[l][c] = \"9\"\n\n for c in range(vertices):\n cont_a, cont_b = 0, 0\n\n for l in range(vertices):\n if int(copia[l][c]) == 8 or int(copia[l][c]) == 0:\n cont_a += 1\n if int(copia[l][c]) == 9 or int(copia[l][c]) == 0:\n cont_b += 1\n\n if cont_a == vertices:\n conj_a.append(c+1)\n elif cont_b == vertices:\n conj_b.append(c+1)\n else:\n conj_c.append(c+1)\n\n if len(conj_c) == 0:\n msg = \"O grafo é bipartido!\"\n\n if teste == conj_a:\n msg = \"O grafo é bipartido completo!\"\n else:\n msg = \"O grafo não é bipartido!\"\n\n print(msg)\n\ndef grafo_aciclico(grafo, vertices):\n \"\"\"\n Verifica se um grafo simples é aciclico\n \"\"\"\n v = list(range(1, len(grafo) + 1))\n\n for l in range(vertices):\n contador = 0\n for c in range(vertices):\n if int(grafo[l][c]) == 1:\n contador += 1\n if contador == 1:\n del v[v.index(l+1)]\n\n adj = 0\n if len(v) > 2:\n for l in range(vertices):\n cont_adj = 0\n\n if l+1 in v:\n for c in range(vertices):\n if int(grafo[l][c]) == 1 and c+1 in v:\n cont_adj += 1\n\n if cont_adj == len(v)-1:\n adj += 1\n\n if adj == len(v):\n print(\"É um grafo ciclico!\")\n else:\n print(\"É um grafo aciclico\")\n\n\ndef menu():\n while True:\n print(\"~=~=~=~=~=~=~=~=~=~ Menu ~=~=~=~=~=~=~=~=~=~\")\n print(\"[ 1 ] - Gera um grafo aleatório\")\n print(\"[ 2 ] - Mostra informações sobre o grafo\")\n print(\"[ 3 ] - Sair do programa\\n\")\n\n opcao = int(input(\"Escolha: \"))\n\n if opcao == 1:\n gera_grafo()\n elif opcao == 2:\n info_grafo()\n elif opcao == 3:\n system('clear')\n break\n else:\n print(\"\\nOpcao Inválida!\\nEscolha uma opção valida!\")\n sleep(1)\n system('clear') \n\nmenu()\n","sub_path":"Trabalho_Grafos/Trabalho_01.py","file_name":"Trabalho_01.py","file_ext":"py","file_size_in_byte":7617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"577202644","text":"from os.path import join\nfrom typing import Tuple\n\nimport click\nimport socket\nfrom multiprocessing import cpu_count\n\nimport torch\n\nfrom mlcomp.contrib.search.grid import grid_cells\nfrom mlcomp.migration.manage import migrate as _migrate\nfrom mlcomp import ROOT_FOLDER, IP, PORT, \\\n WORKER_INDEX, SYNC_WITH_THIS_COMPUTER, CAN_PROCESS_TASKS\nfrom mlcomp.db.core import Session\nfrom mlcomp.db.enums import DagType, ComponentType, TaskStatus\nfrom mlcomp.db.models import Computer\nfrom mlcomp.db.providers import \\\n ComputerProvider, \\\n TaskProvider, \\\n StepProvider, \\\n ProjectProvider\nfrom mlcomp.utils.config import merge_dicts_smart, dict_from_list_str\nfrom mlcomp.utils.io import yaml_load, yaml_dump\nfrom mlcomp.utils.logging import create_logger\nfrom mlcomp.worker.sync import sync_directed\nfrom mlcomp.worker.tasks import execute_by_id\nfrom mlcomp.utils.misc import memory, disk, get_username\nfrom mlcomp.server.back.create_dags import dag_standard, dag_pipe\n\n_session = Session.create_session(key=__name__)\n\n\ndef _dag(config: str, debug: bool = False, control_reqs=True,\n params: Tuple[str] = ()):\n logger = create_logger(_session, name='_dag')\n logger.info('started', ComponentType.Client)\n\n config_text = open(config, 'r').read()\n config_parsed = yaml_load(config_text)\n params = dict_from_list_str(params)\n config_parsed = merge_dicts_smart(config_parsed, params)\n config_text = yaml_dump(config_parsed)\n\n logger.info('config parsed', ComponentType.Client)\n\n type_name = config_parsed['info'].get('type', 'standard')\n if type_name == DagType.Standard.name.lower():\n cells = grid_cells(\n config_parsed['grid']) if 'grid' in config_parsed else [None]\n dags = []\n for cell in cells:\n dag = dag_standard(\n session=_session,\n config=config_parsed,\n debug=debug,\n config_text=config_text,\n config_path=config,\n control_reqs=control_reqs,\n logger=logger,\n component=ComponentType.Client,\n grid_cell=cell\n )\n dags.append(dag)\n\n return dags\n\n return [\n dag_pipe(\n session=_session, config=config_parsed, config_text=config_text\n )\n ]\n\n\ndef _create_computer():\n tot_m, used_m, free_m = memory()\n tot_d, used_d, free_d = disk(ROOT_FOLDER)\n computer = Computer(\n name=socket.gethostname(),\n gpu=torch.cuda.device_count(),\n cpu=cpu_count(),\n memory=tot_m,\n ip=IP,\n port=PORT,\n user=get_username(),\n disk=tot_d,\n root_folder=ROOT_FOLDER,\n sync_with_this_computer=SYNC_WITH_THIS_COMPUTER,\n can_process_tasks=CAN_PROCESS_TASKS\n )\n ComputerProvider(_session).create_or_update(computer, 'name')\n\n\n@click.group()\ndef main():\n pass\n\n\n@main.command()\ndef migrate():\n _migrate()\n\n\n@main.command()\n@click.argument('config')\n@click.option('--control_reqs', type=bool, default=True)\n@click.option('--params', multiple=True)\ndef dag(config: str, control_reqs: bool, params):\n _dag(config, control_reqs=control_reqs, params=params)\n\n\n@main.command()\n@click.argument('config')\n@click.option('--debug', type=bool, default=True)\n@click.option('--params', multiple=True)\ndef execute(config: str, debug: bool, params):\n _create_computer()\n\n # Fail all InProgress Tasks\n logger = create_logger(_session, __name__)\n\n provider = TaskProvider(_session)\n step_provider = StepProvider(_session)\n\n for t in provider.by_status(\n TaskStatus.InProgress, worker_index=WORKER_INDEX\n ):\n step = step_provider.last_for_task(t.id)\n logger.error(\n f'Task Id = {t.id} was in InProgress state '\n f'when another tasks arrived to the same worker',\n ComponentType.Worker, t.computer_assigned, t.id, step\n )\n provider.change_status(t, TaskStatus.Failed)\n\n # Create dags\n dags = _dag(config, debug, params=params)\n for dag in dags:\n for ids in dag.values():\n for id in ids:\n task = provider.by_id(id)\n task.gpu_assigned = ','.join(\n [str(i) for i in range(torch.cuda.device_count())])\n\n provider.commit()\n execute_by_id(id, exit=False)\n\n\n@main.command()\n@click.argument('project')\n@click.option('--computer', help='sync computer with all the others')\n@click.option(\n '--only_from',\n is_flag=True,\n help='only copy files from the computer to all the others'\n)\n@click.option(\n '--only_to',\n is_flag=True,\n help='only copy files from all the others to the computer'\n)\ndef sync(project: str, computer: str, only_from: bool, only_to: bool):\n _create_computer()\n\n computer = computer or socket.gethostname()\n provider = ComputerProvider(_session)\n project_provider = ProjectProvider(_session)\n computer = provider.by_name(computer)\n computers = provider.all()\n folders_excluded = []\n p = project_provider.by_name(project)\n assert p, f'Project={project} is not found'\n\n ignore = yaml_load(p.ignore_folders)\n excluded = []\n for f in ignore:\n excluded.append(str(f))\n\n folders_excluded.append([join('data', p.name), excluded])\n folders_excluded.append([join('models', p.name), []])\n\n for c in computers:\n if c.name != computer.name:\n if not only_from:\n sync_directed(_session, computer, c, folders_excluded)\n if not only_to:\n sync_directed(_session, c, computer, folders_excluded)\n\n\n@main.command()\ndef init():\n # already done by importing mlcomp\n # that is needed to import it\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"mlcomp/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":5795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"302191393","text":"from tkinter import *\nimport json\nfrom pathlib import Path\nimport os\nfrom tkinter import messagebox\n\ncurrent_path = os.path.dirname(os.path.abspath(__file__))\n\nsettings_file = Path(f\"{current_path}/account.json\")\nif not settings_file.is_file():\n account_info = {\"account_name\": \"\", \"token\": \"\"}\n with open('account.json', 'w') as f:\n json.dump(account_info, f)\n\nif settings_file.is_file():\n with open('account.json', 'r') as f:\n account_info = json.load(f)\n\n\nclass AccountSettings:\n def __init__(self):\n self.account_window = Tk()\n self.account_window.title(\"Account Details\")\n self.account_window.geometry(\"500x500\")\n self.account_window.configure(bg=\"#424242\")\n\n # account name\n self.label_account_name = Label(self.account_window, text=\"Your account name: \", bg=\"#424242\", fg=\"white\")\n self.account_name_input = Entry(self.account_window, width=40, bg=\"#424242\", fg=\"white\")\n if account_info.get(\"account_name\") != \"\":\n self.account_name_input.insert(0, account_info.get(\"account_name\"))\n\n # token\n self.label_token = Label(self.account_window, text=\"Your token: \", bg=\"#424242\", fg=\"white\")\n self.token_input = Entry(self.account_window, width=40, bg=\"#424242\", fg=\"white\")\n if account_info.get(\"token\") != \"\":\n self.token_input.insert(0, account_info.get(\"token\"))\n self.label_token_info = Label(self.account_window,\n text=\"You can get your token from https://twitchapps.com/tmi/\", bg=\"#424242\",\n fg=\"white\")\n\n # save button\n self.save_emotes_button = Button(self.account_window, text=\"save\", command=lambda: self.save_account_details(),\n bg=\"#424242\", fg=\"white\", activebackground=\"#424242\", activeforeground=\"white\")\n\n # grid\n self.label_account_name.grid(row=0, column=0, padx=10, pady=10, sticky=W)\n self.account_name_input.grid(row=0, column=1, padx=10, pady=10, sticky=W)\n\n self.label_token.grid(row=1, column=0, padx=10, pady=10, sticky=W)\n self.token_input.grid(row=1, column=1, padx=10, pady=10, sticky=W)\n self.label_token_info.grid(row=2, column=0, columnspan=2, padx=10, pady=5, sticky=W)\n\n self.save_emotes_button.grid(row=10, column=0, padx=10, pady=10, sticky=W)\n\n def save_account_details(self):\n account_info[\"account_name\"] = str(self.account_name_input.get())\n account_info[\"token\"] = str(self.token_input.get())\n print(str(self.account_name_input.get()))\n print(str(self.token_input.get()))\n if self.account_name_input.get() == \"\" or self.token_input.get() == \"\":\n messagebox.showerror(title=\"Bruh\", message=\"You have to fill in both boxes, dumbass\")\n self.account_window.destroy()\n AccountSettings()\n elif \" \" in self.account_name_input.get() or \" \" in self.token_input.get():\n messagebox.showerror(title=\"Bruh\", message=\"No Blankspaces, bruh\")\n self.account_window.destroy()\n AccountSettings()\n elif self.token_input.get()[0:6] != \"oauth:\":\n messagebox.showerror(title=\"Bruh\", message=\"token has to start with \\\"oauth:\\\" lol\")\n self.account_window.destroy()\n AccountSettings()\n else:\n with open(f\"{current_path}/account.json\", 'w') as f:\n json.dump(account_info, f)\n self.account_window.destroy()\n","sub_path":"Exe UI/AccountWindowClass.py","file_name":"AccountWindowClass.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"184885229","text":"# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license\n\nimport base64\nimport unittest\n\nimport dns.tsigkeyring\n\ntext_keyring = {\n 'keyname.' : 'NjHwPsMKjdN++dOfE5iAiQ=='\n}\n\nrich_keyring = {\n dns.name.from_text('keyname.') : \\\n base64.decodebytes('NjHwPsMKjdN++dOfE5iAiQ=='.encode())\n}\n\nclass TSIGKeyRingTestCase(unittest.TestCase):\n\n def test_from_text(self):\n \"\"\"text keyring -> rich keyring\"\"\"\n rkeyring = dns.tsigkeyring.from_text(text_keyring)\n self.assertEqual(rkeyring, rich_keyring)\n\n def test_to_text(self):\n \"\"\"text keyring -> rich keyring -> text keyring\"\"\"\n tkeyring = dns.tsigkeyring.to_text(rich_keyring)\n self.assertEqual(tkeyring, text_keyring)\n\n def test_from_and_to_text(self):\n \"\"\"text keyring -> rich keyring -> text keyring\"\"\"\n rkeyring = dns.tsigkeyring.from_text(text_keyring)\n tkeyring = dns.tsigkeyring.to_text(rkeyring)\n self.assertEqual(tkeyring, text_keyring)\n","sub_path":"tests/test_tsigkeyring.py","file_name":"test_tsigkeyring.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"499659030","text":"#1 milyonun altındaki hangi asal sayı en uzun serinin(asal sayhıların) toplamı şeklinde yazılabilir\n\n\nfrom fonksiyon import allprimes\nfrom fonksiyon import isprime\n\nasal = allprimes(4000)\n\nfor p in range(5,len(asal)):\n for a in range(0,len(asal)-p):\n if(isprime(sum(asal[a:a+p]))==1 and sum(asal[a:a+p])<1000000):\n toplam = sum(asal[a:a+p])\n\nprint(toplam)\n","sub_path":"PYTHON/DERS13-52.py","file_name":"DERS13-52.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"19878708","text":"import pandas as pd\nimport quandl, math\nimport numpy as np\nfrom sklearn import preprocessing, model_selection , svm\nfrom sklearn.linear_model import LinearRegression\n\nquandl.ApiConfig.api_key = 'KQZ2K2gm6spdG4FZvHi4'\ndf = quandl.get('WIKI/GOOGL')\ndf = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']]\n\ndf['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100\ndf['PCT_CHANGE'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100\n\ndf = df[['Adj. Close', 'HL_PCT', 'PCT_CHANGE', 'Adj. Volume']]\n\nforecast_col = 'Adj. Close'\ndf.fillna(-9999, inplace=True)\n\nforecast_out = int(math.ceil(0.01*len(df)))\nprint(forecast_out)\n\ndf['label'] = df[forecast_col].shift(-forecast_out)\ndf.dropna(inplace=True)\n# print(df.tail())\n\n# X features, y label\nX = np.array(df.drop(['label'], 1))\nX = preprocessing.scale(X)\ny = np.array(df['label'])\n\nX_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.2)\nclassifier = LinearRegression(n_jobs=-1)\nclassifier.fit(X_train, y_train)\n\naccuracy = classifier.score(X_test, y_test)\nprint(accuracy)\n","sub_path":"Machine_Learning_Sentdex/Regression/training_and_testing.py","file_name":"training_and_testing.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"449943849","text":"from __future__ import print_function\n\nimport argparse\nimport sys\n\nimport torch.optim as optim\n\nsys.path.append('./auxiliary/')\nfrom auxiliary.dataset_nd import *\nfrom auxiliary.ndmodel import *\nfrom auxiliary.my_utils import *\nimport os\nimport visdom\n\n# =============PARAMETERS======================================== #\nparser = argparse.ArgumentParser()\nparser.add_argument('--nepoch', type=int, default=1200, help='number of epochs to train for')\nparser.add_argument('--model', type=str, default='', help='optional reload model path')\nparser.add_argument('--num_points', type=int, default=25, help='number of points')\nparser.add_argument('--accelerated_chamfer', type=int, default=0, help='use custom build accelarated chamfer')\nparser.add_argument('--ngpu', type=int, default=1, help='number of gpus')\nparser.add_argument('--lrate', type=float, default=0.001, help='number of gpus')\nopt = parser.parse_args()\nprint(opt)\n\n\n# ========================================================== #\ndef pair_dist_matrix(x):\n return torch.norm(x[None, :, :] - x[:, None, :], p=2, dim=2)\n\n\ndef compute_pair_distance(x):\n x_pair_dist_matrix = pair_dist_matrix(x)\n x_pair_dist_sum = torch.sum(x_pair_dist_matrix, dim=1)\n x_pair_dist_normalized = x_pair_dist_matrix / x_pair_dist_sum[..., None].detach()\n return x_pair_dist_normalized\n\n\ndef compute_pairwise_divergence(space2d, space3d):\n space2d_dist_matrix = compute_pair_distance(space2d)\n space3d_dist_matrix = compute_pair_distance(space3d)\n div = F.relu(space2d_dist_matrix * 0.8 - space3d_dist_matrix)\n return div.sum()\n\n\ndef custom_dischamfer(x, y):\n xx = torch.sum(torch.pow(x, 2), dim=1)\n yy = torch.sum(torch.pow(y, 2), dim=1)\n xy = torch.matmul(x, y.transpose(1, 0))\n\n xx = xx.unsqueeze(0).expand_as(xy)\n yy = yy.unsqueeze(0).expand_as(xy)\n dist = xx.transpose(1, 0) + yy - 2 * xy\n return torch.min(dist, dim=0)[0], torch.min(dist, dim=1)[0]\n\n\ndef yifan_dischamfer(a, b):\n # when a and b are in different size\n dist_ab = torch.norm((a[:, None, :] - b), p=2, dim=2)\n dist_ba = torch.norm((b[:, None, :] - a), p=2, dim=2)\n return torch.min(dist_ab, dim=1)[0], torch.min(dist_ba, dim=1)[0]\n\n\n# =============DEFINE stuff for logs ======================================== #\nvis = visdom.Visdom()\ndir_name = os.path.join('./results/chamfer')\nif not os.path.exists(dir_name):\n os.mkdir(dir_name)\n\nopt.manualSeed = random.randint(1, 10000) # fix seed\nopt.manualSeed = 7269 # fix seed\nprint(\"Random Seed: \", opt.manualSeed)\nrandom.seed(opt.manualSeed)\ntorch.manual_seed(opt.manualSeed)\nbest_val_loss = 10\n# ========================================================== #\n\n# ===================CREATE DATASET================================= #\n# Create train/test dataloader\ndataset = ShapeNet(root='./data/test', npoint=10000)\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, num_workers=8)\nprint('training set', len(dataset))\nlen_dataset = len(dataset)\n# ========================================================== #\n\n# ===================CREATE network================================= #\nnetwork = ND_Map(num_points=opt.num_points, nb_primitives=1)\nnetwork = torch.nn.DataParallel(network, device_ids=range(opt.ngpu))\nnetwork.cuda() # put network on GPU\nnetwork.apply(weights_init) # initialization of the weight\n\nif opt.model != '':\n network.load_state_dict(torch.load(opt.model))\n print(\" Previous weight loaded \")\n# ========================================================== #\n\n# ===================CREATE optimizer================================= #\noptimizer = optim.Adam(network.parameters(), lr=opt.lrate)\n# ========================================================== #\n\n\n# initialize learning curve on visdom, and color for each primitive in visdom displpycharm,ay\ntrain_curve = []\n\n# ========================================================== #\n\n# =============start of the learning loop ======================================== #\n# TRAIN MODE\nnetwork.train()\ngrid_x = torch.arange(100).unsqueeze(0).expand(100, 100).contiguous()\ngrid_y = grid_x.transpose(1, 0).contiguous()\ngrid = torch.cat([grid_x.view(-1, 1), grid_y.view(-1, 1)], dim=-1).cuda().float()\ngrid = (grid - 50) / 50\ncolor_g = torch.ceil(((grid.data.cpu() + 1) / 2) * 255).long()\ncolor_g = torch.cat([color_g, torch.ones_like(color_g[:, :1]) * 133], dim=1)\ncolor_g = color_g.data.numpy()\n\n### Input scale 1\ngrid_x_s1 = torch.arange(-1, 1.000001, 0.5).unsqueeze(0).expand(5, 5).contiguous()\ngrid_y_s1 = grid_x_s1.transpose(1, 0).contiguous()\ngrid_s1 = torch.cat([grid_x_s1.view(-1, 1), grid_y_s1.view(-1, 1)], dim=-1).cuda().float()\n\ncolor_s1 = torch.ceil(((grid_s1.data.cpu() + 1) / 2) * 255).long()\ncolor_s1 = torch.cat([color_s1, torch.ones_like(color_s1[:, :1]) * 133], dim=1)\ncolor_s1 = color_s1.data.numpy()\n\n### Input scale 2\ngrid_x_s2 = torch.arange(-1, 1.000001, 0.2).unsqueeze(0).expand(11, 11).contiguous()\ngrid_y_s2 = grid_x_s2.transpose(1, 0).contiguous()\ngrid_s2 = torch.cat([grid_x_s2.view(-1, 1), grid_y_s2.view(-1, 1)], dim=-1).cuda().float()\n\ncolor_s2 = torch.ceil(((grid_s2.data.cpu() + 1) / 2) * 255).long()\ncolor_s2 = torch.cat([color_s2, torch.ones_like(color_s2[:, :1]) * 133], dim=1)\ncolor_s2 = color_s2.data.numpy()\n\n### Input scale 3\ngrid_x_s3 = torch.arange(-1, 1.000001, 0.08).unsqueeze(0).expand(26, 26).contiguous()\ngrid_y_s3 = grid_x_s3.transpose(1, 0).contiguous()\ngrid_s3 = torch.cat([grid_x_s3.view(-1, 1), grid_y_s3.view(-1, 1)], dim=-1).cuda().float()\n\ncolor_s3 = torch.ceil(((grid_s3.data.cpu() + 1) / 2) * 255).long()\ncolor_s3 = torch.cat([color_s3, torch.ones_like(color_s3[:, :1]) * 133], dim=1)\ncolor_s3 = color_s3.data.numpy()\n\n# learning rate schedule\nfor i, data in enumerate(dataloader, 0):\n loss_net = torch.ones(1).cuda()\n step = -1\n points, file_name = data\n file_name = file_name[0].split('.points.ply')[0].split('/')[-1]\n\n # points=data[1]\n points = points.cuda().contiguous().squeeze() # points.size: [1,10000,3]\n recons = []\n while (loss_net.item() > 5 * 1e-3):\n # sample_index = np.random.randint(low=0, high=points.shape[0], size=opt.num_points)\n # target_points = points[sample_index, :]\n # target_points = points # yfwu: do not do downsample on the original shapes\n # sample_points = torch.rand_like(target_points[:, 0:2]) * 2 - 1\n target_points = points\n\n # color = torch.ceil(((sample_points.data.cpu() + 1) / 2) * 255).long()\n # color = torch.cat([color, color[:, :1]], dim=1)\n # color = color.data.numpy()\n color_t = torch.ceil(((target_points.data.cpu() + 1) / 2) * 255).long().data.numpy()\n\n # optimize each object\n optimizer.zero_grad()\n # END SUPER RESOLUTION\n pointsReconstructed_s1 = network(grid_s1) # 2500,3\n dist1, dist2 = yifan_dischamfer(target_points, pointsReconstructed_s1)\n chamfer_s1 = (torch.mean(dist1)) + (torch.mean(dist2))\n ndiv_s1 = 0.01 * compute_pairwise_divergence(grid_s1, pointsReconstructed_s1)\n loss_net = chamfer_s1 + ndiv_s1\n\n pointsReconstructed_s2 = network(grid_s2)\n dist1, dist2 = yifan_dischamfer(target_points, pointsReconstructed_s2)\n chamfer_s2 = 2 * ((torch.mean(dist1)) + (torch.mean(dist2)))\n ndiv_s2 = 0.001 * compute_pairwise_divergence(grid_s2, pointsReconstructed_s2)\n loss_net = loss_net + chamfer_s2 + ndiv_s2\n\n pointsReconstructed_s3 = network(grid_s3)\n dist1, dist2 = yifan_dischamfer(target_points, pointsReconstructed_s3)\n chamfer_s3 = 4 * ((torch.mean(dist1)) + (torch.mean(dist2)))\n ndiv_s3 = 0.0001 * compute_pairwise_divergence(grid_s3, pointsReconstructed_s3)\n loss_net = loss_net + chamfer_s3 + ndiv_s3\n\n loss_net.backward()\n optimizer.step()\n step += 1\n # VIZUALIZE\n if step % 100 <= 0:\n vis.scatter(X=points.data.cpu(),\n win='Target',\n opts=dict(\n title=\"Target\",\n markersize=3,\n xtickmin=-1,\n xtickmax=1,\n xtickstep=0.5,\n ytickmin=-1,\n ytickmax=1,\n ytickstep=0.5,\n ztickmin=-1,\n ztickmax=1,\n ztickstep=0.5,\n ),\n )\n # vis.scatter(X=target_points.data.cpu(),\n # win='TRAIN_Target',\n # opts=dict(\n # title=\"TRAIN_Target\",\n # markersize=3,\n # xtickmin=-1,\n # xtickmax=1,\n # xtickstep=0.5,\n # ytickmin=-1,\n # ytickmax=1,\n # ytickstep=0.5,\n # ztickmin=-1,\n # ztickmax=1,\n # ztickstep=0.5,\n # ),\n # )\n vis.scatter(X=pointsReconstructed_s1.data.cpu(),\n win='TRAIN_INPUT_RECONSTRUCTED_s1',\n opts=dict(\n markercolor=color_s1,\n title=\"TRAIN_INPUT_RECONSTRUCTED_s1\",\n markersize=3,\n xtickmin=-1,\n xtickmax=1,\n xtickstep=0.5,\n ytickmin=-1,\n ytickmax=1,\n ytickstep=0.5,\n ztickmin=-1,\n ztickmax=1,\n ztickstep=0.5,\n ),\n )\n vis.scatter(X=pointsReconstructed_s2.data.cpu(),\n win='TRAIN_INPUT_RECONSTRUCTED_s2',\n opts=dict(\n markercolor=color_s2,\n title=\"TRAIN_INPUT_RECONSTRUCTED_s2\",\n markersize=3,\n xtickmin=-1,\n xtickmax=1,\n xtickstep=0.5,\n ytickmin=-1,\n ytickmax=1,\n ytickstep=0.5,\n ztickmin=-1,\n ztickmax=1,\n ztickstep=0.5,\n ),\n )\n vis.scatter(X=pointsReconstructed_s3.data.cpu(),\n win='TRAIN_INPUT_RECONSTRUCTED_s3',\n opts=dict(\n markercolor=color_s3,\n title=\"TRAIN_INPUT_RECONSTRUCTED_s3\",\n markersize=3,\n xtickmin=-1,\n xtickmax=1,\n xtickstep=0.5,\n ytickmin=-1,\n ytickmax=1,\n ytickstep=0.5,\n ztickmin=-1,\n ztickmax=1,\n ztickstep=0.5,\n ),\n )\n with torch.no_grad():\n gridReconstructed = network(grid)\n vis.scatter(X=gridReconstructed.data.cpu(),\n win='grid_RECONSTRUCTED',\n opts=dict(\n markercolor=color_g,\n title=\"grid_RECONSTRUCTED\",\n markersize=3,\n xtickmin=-1,\n xtickmax=1,\n xtickstep=0.5,\n ytickmin=-1,\n ytickmax=1,\n ytickstep=0.5,\n ztickmin=-1,\n ztickmax=1,\n ztickstep=0.5,\n ),\n )\n vis.scatter(X=grid.data.cpu().numpy(),\n win='grid_INPUT',\n opts=dict(\n markercolor=color_g,\n title=\"grid_INPUT\",\n markersize=4,\n xtickmin=-1,\n xtickmax=1,\n xtickstep=0.5,\n ytickmin=-1,\n ytickmax=1,\n ytickstep=0.5,\n ztickmin=-1,\n ztickmax=1,\n ztickstep=0.5,\n ),\n )\n\n print(\n '[object id:%d,step: %d] train loss: %f chamfer_s1: %f ndiv_s1: %f chamfer_s2: %f ndiv_s2: %f chamfer_s3: %f ndiv_s3: %f' % (\n i, step, loss_net.item(), chamfer_s1.item(), ndiv_s1.item(), chamfer_s2.item(), ndiv_s2.item(),\n chamfer_s3.item(), ndiv_s3.item()))\n\n # save last network\n print('saving net...')\n torch.save({'state': network.state_dict(), 'steps': step}, './chamfer/%s.pth' % (file_name))\n np.save('./results/chamfer/%s.npy' % (file_name), np.array(recons))\n print(file_name)\n","sub_path":"chamfer_ndiv_yifan.py","file_name":"chamfer_ndiv_yifan.py","file_ext":"py","file_size_in_byte":13458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"54978372","text":"import cv2\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nimport sys\nimport numpy as np\nimport random\nimport stem_detect\n\ndef move_im_to_point(im, point, og_size, fl_size=.05):\n x, y = point\n x_size = og_size[0]\n y_size = og_size[1]\n x_ratio = x / x_size\n y_ratio = y / y_size\n\n \n new_im = Image.new(\"RGBA\", og_size)\n\n \n\n x_size_factor = og_size[0] * fl_size\n y_size_factor = og_size[1] * fl_size\n\n x_est = og_size[0] * x_ratio\n y_est = og_size[1] * y_ratio \n region = [(x_est-x_size_factor*.5), y_est-.3*y_size_factor, \n (x_est+x_size_factor*.5), y_est+.5*y_size_factor]\n region = [int(el) for el in region]\n reg_size = (region[2] - region[0], region[3] - region[1])\n im = im.resize(reg_size, Image.ANTIALIAS)\n \n new_im.paste(im, box=region)\n return new_im\n\ndef check_mask(points, mask):\n approved = []\n for point in points:\n x,y = point.ravel()\n if not (mask[y,x] == [0,0,0]).all():\n approved.append(point)\n return(approved)\n\ndef check_overlap(points, im_size, max_flow_size, clumps=False):\n approved = []\n for point in points:\n clear = True\n point_x, point_y = point.ravel()\n for i in approved:\n x,y = i.ravel()\n x_ratio = x / im_size[0]\n y_ratio = y / im_size[1]\n x_est = im_size[0] * x_ratio\n y_est = im_size[1] * y_ratio \n x_size_factor = im_size[0] * max_flow_size\n y_size_factor = im_size[1] * max_flow_size\n region = [(x_est-x_size_factor*.5), y_est-.3*y_size_factor, \n (x_est+x_size_factor*.5), y_est+.5*y_size_factor]\n if (point_x > region[0] and point_x < region[2] and \n point_y > region[1] and point_y < region[3]):\n if not clumps:\n clear = False\n break\n else:\n if clumps:\n clear = False\n break\n if clear:\n approved.append(point)\n return approved\n\ndef get_placements(img, num):\n\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n corners = cv2.goodFeaturesToTrack(gray, 10000, 0.01, 5)\n corners = np.int0(corners)\n return corners\n\ndef main():\n rand_gen = random.Random()\n fl = cv2.imread(sys.argv[1])\n pl = cv2.imread(sys.argv[2])\n extremes, mask_im = stem_detect.get_stem(fl, pl) #TODO\n fl[np.where((fl == [0,0,0]).all(axis=2))] = [255,255,255]\n corners = get_placements(pl, 10000)\n\n clumps = False\n if len(sys.argv) >= 5:\n clumps = bool(int(sys.argv[4]))\n if len(sys.argv) == 7:\n flower_size = (float(sys.argv[5]), float(sys.argv[6]))\n else:\n flower_size = (.07, .15)\n \n fl = cv2.cvtColor(fl.astype(np.uint8), cv2.COLOR_BGRA2RGBA)\n fl = Image.fromarray(fl)\n pl = cv2.cvtColor(pl, cv2.COLOR_BGR2RGB)\n pl = Image.fromarray(pl)\n \n corners = stem_detect.check_close(corners, (extremes[0],\n extremes[1]), (extremes[2], extremes[3])) \n corners = check_mask(corners, mask_im)\n corners = check_overlap(corners, pl.size, flower_size[1],\n clumps=clumps)\n\n pl = pl.convert('RGBA')\n datas = fl.getdata()\n newData = []\n for item in datas:\n if item[0] == 255 and item[1] == 255 and item[2] == 255:\n newData.append((255, 255, 255, 0))\n else:\n newData.append(item)\n fl.putdata(newData)\n \n final_im = Image.new('RGBA', pl.size, (0,0,0,0))\n \n in_size = int(sys.argv[3])\n sample_size = [in_size,len(corners)][bool(len(corners) < in_size)]\n for point in random.sample(corners, sample_size):\n size = rand_gen.uniform(flower_size[0], flower_size[1]) \n im_point = move_im_to_point(fl, point.ravel(), \n pl.size, fl_size=size) \n \n pl = Image.alpha_composite(pl, im_point)\n \n plt.imshow(pl, zorder=2)\n pl.show()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"impose_flowers.py","file_name":"impose_flowers.py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"51338940","text":"import math\nimport pyqtree\nimport svgwrite\nimport os\nimport os.path\n\ndef vector_angle(x, y):\n\treturn math.atan2(y, x) - math.atan2(0, 1)\n\nclass Point(object):\n\tdef __init__(self, x, y, bearing):\n\t\tself.x = float(x)\n\t\tself.y = float(y)\n\t\tself.bearing = float(bearing)\n\n\tdef distance_to(self, other):\n\t\t'''\n\t\tReturns the distance to another Point or Observation.\n\t\t'''\n\t\treturn math.sqrt((other.x - self.x) * (other.x - self.x) + (other.y - self.y) * (other.y - self.y))\n\n\tdef angle_to(self, other):\n\t\t'''\n\t\tReturns the angle difference to another Point.\n\t\t'''\n\t\td = other.bearing - self.bearing\n\t\treturn abs((d + 180) % 360 - 180)\n\n\tdef __repr__(self):\n\t\treturn '({}, {}, {})'.format(self.x, self.y, self.bearing)\n\nclass PointWithID(Point):\n\tdef __init__(self, id, x, y, bearing):\n\t\tsuper(PointWithID, self).__init__(x, y, bearing)\n\t\tself.id = id\n\nclass Observation(object):\n\tdef __init__(self, x, y):\n\t\tself.x = x\n\t\tself.y = y\n\n\tdef to_point(self, next_obs):\n\t\t'''\n\t\tConverts this Observation into a Point.\n\n\t\tA Point has a bearing whereas an Observation does not. The bearing is estimated\n\t\tfrom next_obs, which should be the observation immediately following this one in\n\t\tthe parent trace.\n\t\t'''\n\t\tbearing = vector_angle(next_obs.x - self.x, next_obs.y - self.y)\n\t\treturn Point(self.x, self.y, math.degrees(bearing))\n\nclass Rectangle(object):\n\tdef __init__(self, min_point, max_point):\n\t\tself.min_point = min_point\n\t\tself.max_point = max_point\n\n\tdef lengths(self):\n\t\treturn self.max_point.x - self.min_point.x, self.max_point.y - self.min_point.y\n\t\n\tdef extend_to_contain(self, point):\n\t\tself.min_point.x = min(self.min_point.x, point.x)\n\t\tself.min_point.y = min(self.min_point.y, point.y)\n\t\tself.max_point.x = max(self.max_point.x, point.x)\n\t\tself.max_point.y = max(self.max_point.y, point.y)\n\t\n\tdef extend_to_contain_rect(self, rect):\n\t\tself.extend_to_contain(rect.min_point)\n\t\tself.extend_to_contain(rect.max_point)\n\ndef get_empty_rectangle():\n\treturn Rectangle(Point(float('inf'), float('inf'), 0), Point(float('-inf'), float('-inf'), 0))\n\nclass Trace(object):\n\tdef __init__(self, observations):\n\t\tself.observations = observations\n\t\n\tdef bounds(self):\n\t\tr = get_empty_rectangle()\n\t\tfor obs in self.observations:\n\t\t\tr.extend_to_contain(obs)\n\t\treturn r\n\ndef read_traces(dir):\n\tfiles = [os.path.join(dir, fbase) for fbase in os.listdir(dir)]\n\tfiles = [fname for fname in files if os.path.isfile(fname)]\n\ttraces = []\n\tfor fname in files:\n\t\twith open(fname, 'r') as f:\n\t\t\tobservations = []\n\t\t\tfor line in f:\n\t\t\t\tparts = line.strip().split(' ')\n\t\t\t\tobservations.append(Observation(float(parts[0]), float(parts[1])))\n\t\t\ttraces.append(Trace(observations))\n\treturn traces\n\nclass Index(object):\n\tdef __init__(self, points):\n\t\t'''\n\t\tCreate an index over the specified points.\n\t\t\n\t\tEach element must have x and y attributes.\n\t\t'''\n\t\t# compute bounding box\n\t\tr = get_empty_rectangle()\n\t\tfor point in points:\n\t\t\tr.extend_to_contain(point)\n\t\tself.index = pyqtree.Index(bbox=(r.min_point.x - 1, r.min_point.y - 1, r.max_point.x + 1, r.max_point.y + 1))\n\t\t\n\t\t# insert points into index, with bounding box being unit square around the point\n\t\tfor point in points:\n\t\t\tself.index.insert(point, (point.x - 0.5, point.y - 0.5, point.x + 0.5, point.y + 0.5))\n\t\n\tdef nearby(self, point, distance):\n\t\t'''\n\t\tReturns points in the index that are within distance to the specified point.\n\t\t'''\n\t\t# convert to Point object in case something else is provided (for distance_to function)\n\t\tpoint = Point(point.x, point.y, 0)\n\t\t\n\t\t# filter points\n\t\tcandidates = self.index.intersect((point.x - distance, point.y - distance, point.x + distance, point.y + distance))\n\t\treturn [candidate for candidate in candidates if point.distance_to(candidate) < distance]\n\nclass Vertex(object):\n\tdef __init__(self, id, x, y):\n\t\tself.id = id\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.in_edges = []\n\t\tself.out_edges = []\n\nclass Edge(object):\n\tdef __init__(self, id, src, dst):\n\t\tself.id = id\n\t\tself.src = src\n\t\tself.dst = dst\n\t\n\tdef length(self):\n\t\tdx = self.dst.x - self.src.x\n\t\tdy = self.dst.y - self.src.y\n\t\treturn math.sqrt(dx * dx + dy * dy)\n\t\n\tdef point_along_edge(self, distance):\n\t\t'''\n\t\tReturns the point along this edge that is distance away from the source vertex.\n\t\t'''\n\t\tfactor = distance / self.length()\n\t\treturn Point(self.src.x + factor * (self.dst.x - self.src.x), self.src.y + factor * (self.dst.y - self.src.y), 0)\n\nclass Graph(object):\n\tdef __init__(self):\n\t\tself.vertices = []\n\t\tself.edges = []\n\t\n\tdef add_vertex(self, x, y):\n\t\tvertex = Vertex(len(self.vertices), x, y)\n\t\tself.vertices.append(vertex)\n\t\treturn vertex\n\t\n\tdef add_edge(self, src, dst):\n\t\tedge = Edge(len(self.edges), src, dst)\n\t\tself.edges.append(edge)\n\t\tsrc.out_edges.append(edge)\n\t\tdst.in_edges.append(edge)\n\t\treturn edge\n\t\n\tdef write(self, fname):\n\t\twith open(fname, 'w') as f:\n\t\t\tfor vertex in self.vertices:\n\t\t\t\tf.write(\"{} {}\\n\".format(vertex.x, vertex.y))\n\t\t\tf.write(\"\\n\")\n\t\t\tfor edge in self.edges:\n\t\t\t\tf.write(\"{} {}\\n\".format(edge.src.id, edge.dst.id))\n\t\n\tdef bounds(self):\n\t\tr = get_empty_rectangle()\n\t\tfor vertex in self.vertices:\n\t\t\tr.extend_to_contain(vertex)\n\t\treturn r\n\ndef read_graph(fname):\n\tgraph = Graph()\n\twith open(fname) as f:\n\t\tsection = 'vertices'\n\t\tfor line in f:\n\t\t\tline = line.strip()\n\t\t\tif section == 'vertices':\n\t\t\t\tif line:\n\t\t\t\t\tparts = line.split(' ')\n\t\t\t\t\tgraph.add_vertex(float(parts[0]), float(parts[1]))\n\t\t\t\telse:\n\t\t\t\t\tsection = 'edges'\n\t\t\telif line:\n\t\t\t\tparts = line.split(' ')\n\t\t\t\tsrc_id = int(parts[0])\n\t\t\t\tdst_id = int(parts[1])\n\t\t\t\tgraph.add_edge(graph.vertices[src_id], graph.vertices[dst_id])\n\treturn graph\n\t\ndef visualize(fname, graphs, traces, points, width):\n\t# automatically determine scale based on the bounding box\n\tr = get_empty_rectangle()\n\tfor graph in graphs:\n\t\tr.extend_to_contain_rect(graph.bounds())\n\tfor trace in traces:\n\t\tr.extend_to_contain_rect(trace.bounds())\n\tfor point in points:\n\t\tr.extend_to_contain(point)\n\tl = max(r.lengths()[0], r.lengths()[1])\n\tscale = 1000 / l\n\tlengths = r.lengths()[0] * scale, r.lengths()[1] * scale\n\torigin = r.min_point\n\tdrawing = svgwrite.Drawing(fname, (int(lengths[0]) + 1, int(lengths[1]) + 1))\n\n\tdef convert_coords(point):\n\t\treturn Point(int((point.x - origin.x) * scale), int(lengths[1] - (point.y - origin.y) * scale), 0)\n\n\tfor graph in graphs:\n\t\tfor edge in graph.edges:\n\t\t\tstart = convert_coords(edge.src)\n\t\t\tend = convert_coords(edge.dst)\n\t\t\tdrawing.add(drawing.line((start.x, start.y), (end.x, end.y), stroke=svgwrite.rgb(10, 10, 16, '%'), stroke_width=width))\n\tfor trace in traces:\n\t\tfor i in xrange(len(trace.observations) - 1):\n\t\t\tstart = convert_coords(trace.observations[i])\n\t\t\tend = convert_coords(trace.observations[i + 1])\n\t\t\tdrawing.add(drawing.line((start.x, start.y), (end.x, end.y), stroke=svgwrite.rgb(10, 10, 16, '%'), stroke_width=width))\n\tfor point in points:\n\t\tc = convert_coords(point)\n\t\tdrawing.add(drawing.circle(center=(c.x, c.y), r=width, fill='blue'))\n\n\tdrawing.save()\n","sub_path":"section3_graphs/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"343341260","text":"'''\nBased on the tutorial:\nhttps://medium.com/@ageitgey/machine-learning-is-fun-part-8-how-to-intentionally-trick-neural-networks-b55da32b7196\n'''\n\nimport numpy as np\nimport PIL\nimport PIL.ImageOps\nimport csv\n\nfrom keras.preprocessing.image import load_img\nfrom keras.models import load_model\nfrom keras import backend as K\nfrom scipy.misc import imresize\nfrom PIL import Image\n\nmodel_name = 'homus_cnn.h5'\nfilename = 'input_example.png'\n\nclassList = []\nclassListName = 'class_list.txt'\n\n\ndef prepareClassList():\n global classList\n with open(classListName, 'r') as f:\n reader = csv.reader(f)\n classList = [row[0] for row in reader]\n return classList\n\n\ndef image_to_batch(im):\n # Add a 4th dimension for batch size (as Keras expects)\n im = imresize(im, (40, 40))\n im = im.reshape(1, 40, 40, 1)\n return im\n\n\ndef load_preprocess_image(filename):\n im = load_img(filename, grayscale=True, target_size=[40, 40]) # PIL image\n\n im = PIL.ImageOps.invert(im)\n np.asarray(im).astype('float32')/255\n\n im = image_to_batch(im) # Final shape is (batch, row, column, channel)\n return im\n\n\ndef predict(model, input_image):\n # Run the image through the neural network\n predictions = model.predict(input_image)\n\n # Convert the predictions into text and print them\n bestScore = np.amax(predictions, axis=1) # Higher prediction score\n bestIndex = np.argmax(predictions, axis=1) # Most probable prediction\n bestClass = classList[int(bestIndex)]\n\n return bestScore, bestIndex, bestClass\n\n\ndef get_model_image(model_name, filename):\n # Load pre-trained image recognition model\n model = load_model(model_name)\n\n # Load the image file and convert it to a numpy array\n input_image = load_preprocess_image(filename)\n\n return model, input_image\n\n\ndef print_prediction(model, image):\n bestScore, bestIndex, bestClass = predict(model, image)\n bestScore = bestScore[0] * 100\n print('Accuracy on {} class: {:.8}%'.format(bestClass, bestScore))\n\n return\n\n\ndef get_loss_gradients_function(model, adversarial_class):\n input_tensor = model.layers[0].input # Example input data\n output_tensor = model.layers[-1].output # Prediction output data\n\n loss = output_tensor[0, adversarial_class] # Accuracy of adversarial class\n\n # Calculate gradient based on atual input and prediction\n gradients = K.gradients(loss, input_tensor) # |Input is modified example\n gradients = gradients[0] # \\prediction is accuracy on adverarial class\n\n learning_phase = K.learning_phase() # Placeholder tensor, 0=test, 1=train\n function_inputs = [input_tensor, learning_phase] # |With input and phase\n function_outputs = [loss, gradients] # \\Compute loss and gradient\n get_loss_gradients = K.function(function_inputs, # |Inputs and outputs\n function_outputs) # \\are all placeholders\n\n return get_loss_gradients\n\n\ndef clipImage(img):\n img = np.clip(img, max_distortion_below, max_distortion_above)\n img = np.clip(img, 0, 1.0) # Our pixels representation are between 0 and 1\n\n return img\n\n\ndef unprocess_save_image(img):\n img = img[0] # |Turn array of shape (batch, row, column, channel)\n img = np.squeeze(img) # \\To array of shape (rows, cols)\n img *= 255.0 # Return image to black and white version\n\n # Save the adversarial example\n img = Image.fromarray(img.astype(np.uint8))\n img = PIL.ImageOps.invert(img) # Re-invert the colors of the image\n img.save('adversarial_example_{}.png'.format(classList[adversarial_class]))\n\n return\n\n\nprepareClassList()\nTEST_PHASE = 0 # We want to operate in test mode\n\nmodel, input_example = get_model_image(model_name, filename)\nprint_prediction(model, input_example)\n\nadversarial_class = 14 # Eight-Note\nadversarial_example = np.copy(input_example) # Use a copy, later show both\nadversarial_example = np.asarray(adversarial_example).astype('float32')\n\nmax_distortion = 20.0 # Range of distortion allowed (percentage)\nmax_distortion_above = input_example + max_distortion # Above\nmax_distortion_below = input_example - max_distortion # Below\n\nloss = 0.0\nlower_bound = 0.999 # Minimum accuracy we want for our adversarial example\nlearning_rate = 0.5 # How much update input each iteration (percentage)\nget_loss_gradients = get_loss_gradients_function(model, adversarial_class)\n\n# Modify input example until confussing the model enought (achieve lower_bound)\n# Thus, we obtain the advesarial example\nwhile loss < lower_bound:\n\n # Loss, accuracy of input (which is being modified) for adversarial class\n # Gradients of input (which is being modified) w.r.t loss\n loss, gradients = get_loss_gradients([adversarial_example, TEST_PHASE])\n\n # Move the input one step further towards confusing the model\n adversarial_example += gradients * learning_rate # Back-propagation\n\n adversarial_example = clipImage(adversarial_example)\n\n print('Accuracy on {} class: {:.8}%'.format(classList[adversarial_class],\n loss*100))\n\nunprocess_save_image(adversarial_example)\n\nprint_prediction(model, input_example)\nprint_prediction(model, adversarial_example)\n","sub_path":"adversarial-example/generate_adversarial_example.py","file_name":"generate_adversarial_example.py","file_ext":"py","file_size_in_byte":5201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"558366955","text":"from azure.identity import DeviceCodeCredential\nfrom tau.core import Signal, HistoricNetworkScheduler, MutableSignal, NetworkScheduler, SignalGenerator\n\nfrom serenity.marketdata.api import MarketdataService, Trade, OrderBook, BookLevel\nfrom serenity.model.exchange import ExchangeInstrument\nfrom serenity.marketdata.tickstore.api import AzureBlobTickstore\nfrom serenity.trading.api import Side\nfrom serenity.utils.config import get_global_defaults\n\n\nclass AzureHistoricMarketdataService(MarketdataService):\n \"\"\"\n A historical replay service based off of Serenity's native AzureBlobTickstore.\n \"\"\"\n\n def __init__(self, scheduler: HistoricNetworkScheduler):\n self.scheduler = scheduler\n self.subscribed_instruments = MutableSignal()\n self.scheduler.get_network().attach(self.subscribed_instruments)\n\n self.start_time = scheduler.get_clock().get_start_time()\n self.end_time = scheduler.get_clock().get_end_time()\n\n self.all_subscribed = set()\n self.book_signal_by_symbol = {}\n self.trade_signal_by_symbol = {}\n\n self.credential = DeviceCodeCredential(client_id=get_global_defaults()['azure']['client_id'],\n tenant_id=get_global_defaults()['azure']['tenant_id'])\n\n def get_subscribed_instruments(self) -> Signal:\n return self.subscribed_instruments\n\n def get_order_book_events(self, instrument: ExchangeInstrument) -> Signal:\n raise NotImplementedError()\n\n def get_order_books(self, instrument: ExchangeInstrument) -> Signal:\n symbol = instrument.get_exchange_instrument_code()\n exchange_code_upper = instrument.get_exchange().get_exchange_code().upper()\n\n order_books = self.book_signal_by_symbol.get(symbol, None)\n if order_books is None:\n self._maybe_notify_subscription(instrument)\n\n order_books = MutableSignal()\n self.scheduler.network.attach(order_books)\n self.book_signal_by_symbol[symbol] = order_books\n\n class OrderBookGenerator(SignalGenerator):\n def __init__(self, mds):\n self.mds = mds\n\n def generate(self, scheduler: NetworkScheduler):\n tickstore = AzureBlobTickstore(self.mds.credential, f'{exchange_code_upper}_BOOKS',\n timestamp_column='time')\n books_df = tickstore.select(symbol, self.mds.start_time, self.mds.end_time)\n for row in books_df.itertuples():\n at_time = row[0].asm8.astype('int64') / 10**6\n best_bid = BookLevel(row[2], row[1])\n best_ask = BookLevel(row[4], row[3])\n book = OrderBook(bids=[best_bid], asks=[best_ask])\n scheduler.schedule_update_at(order_books, book, at_time)\n tickstore.close()\n\n self.scheduler.add_generator(OrderBookGenerator(self))\n\n # workaround: force scheduling of all historic trade events\n self.get_trades(instrument)\n\n return order_books\n\n def get_trades(self, instrument: ExchangeInstrument) -> Signal:\n trade_symbol = instrument.get_exchange_instrument_code()\n exchange_code_upper = instrument.get_exchange().get_exchange_code().upper()\n\n self._maybe_notify_subscription(instrument)\n\n trades = self.trade_signal_by_symbol.get(trade_symbol, None)\n if trades is None:\n trades = MutableSignal()\n self.scheduler.network.attach(trades)\n self.trade_signal_by_symbol[trade_symbol] = trades\n\n class TradeGenerator(SignalGenerator):\n def __init__(self, mds):\n self.mds = mds\n\n def generate(self, scheduler: NetworkScheduler):\n tickstore = AzureBlobTickstore(self.mds.credential, f'{exchange_code_upper}_TRADES',\n timestamp_column='time')\n trades_df = tickstore.select(trade_symbol, self.mds.start_time, self.mds.end_time)\n for row in trades_df.itertuples():\n at_time = row[0].asm8.astype('int64') / 10 ** 6\n trade_id = row[1]\n side = Side.SELL if row[2] == 'sell' else Side.BUY\n qty = row[3]\n price = row[4]\n trade = Trade(instrument, trade_id, trade_id, side, qty, price)\n scheduler.schedule_update_at(trades, trade, at_time)\n\n tickstore.close()\n\n self.scheduler.add_generator(TradeGenerator(self))\n\n # workaround: force scheduling of all historic order book events\n self.get_order_books(instrument)\n\n return trades\n\n def _maybe_notify_subscription(self, instrument: ExchangeInstrument):\n if instrument not in self.all_subscribed:\n self.scheduler.schedule_update(self.subscribed_instruments, instrument)\n self.all_subscribed.add(instrument)\n","sub_path":"src/serenity/marketdata/azure.py","file_name":"azure.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129538894","text":"#this is the one that your are editing and using\r\nimport cv2\r\nimport numpy as np\r\nface_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_default.xml')\r\n\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\n\r\nwhile(True):\r\n # Capture frame-by-frame\r\n ret, frame = cap.read()\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)\r\n for (x,y,w,h) in faces:\r\n print(\"I see you\")\r\n roi_gray = gray[y:y+h,x:x+w]\r\n #img_item = \"myimage.png\"\r\n# cv2.imwrite(img_item, roi_gray)\r\n \r\n #change for diffrent viedo input reseulations \r\n IH = 640\r\n IW = 480 \r\n #test if this is right by puting a blue rim\r\n cv2.rectangle(frame, (0, 0), (IH, IW), (255,0,0), 3)\r\n \r\n \r\n # might use tensorflow to keep learning\r\n \r\n \r\n size = \"Size\"\r\n color = (0, 255, 255)\r\n stroke = 1\r\n X_cord = x + w\r\n Y_cord = y + h\r\n Y_Text = (y - 2)\r\n Y_Text2 = (y + 11)\r\n X_Text = (x + 1)\r\n text = \"Distance={}x{}\".format(x, y, w, h)\r\n text2 = \"Size={}x{}\".format(w, h)\r\n cv2.rectangle(frame, (x, y), (X_cord, Y_cord), color, stroke)\r\n \r\n \r\n cv2.putText(frame, text, (X_Text, Y_Text),\r\n\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.45, (color), stroke)\r\n cv2.putText(frame, text2, (X_Text, Y_Text2),\r\n\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.45, (color), stroke)\r\n # Display the resulting frame\r\n cv2.imshow('faces',frame)\r\n if cv2.waitKey(20) & 0xFF == ord('q'):\r\n break\r\n\r\n# When everything done, release the capture\r\ncap.release()\r\ncv2.destroyAllWindows()","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"589740986","text":"\"\"\"\nCopyright (C) 2016 Skylark Drones\nInventory Overview Page\n\"\"\"\n\nfrom PyQt5.QtWidgets import (QWidget, QVBoxLayout, QSplitter, QHBoxLayout, QTableView, QInputDialog, QAbstractItemView,\n QMessageBox)\nfrom PyQt5.QtGui import QStandardItemModel, QStandardItem\nfrom PyQt5.QtSql import QSqlTableModel, QSqlQuery\nfrom PyQt5.QtCore import Qt\nimport ui.CommonWidgets as CM\n\n\nclass InventoryOverview(QWidget):\n\n def __init__(self, stack, inventoryDatabase):\n super().__init__()\n\n # Inventory Items Model\n self.inventoryItemsModel = QSqlTableModel(self, inventoryDatabase)\n self.inventoryItemsModel.setTable(\"Battery\")\n self.inventoryItemsModel.setHeaderData(0, Qt.Horizontal, \"Name\")\n self.inventoryItemsModel.select()\n\n # Inventory Items TableView\n inventoryItems = QTableView()\n inventoryItems.setModel(self.inventoryItemsModel)\n inventoryItems.setShowGrid(True)\n inventoryItems.setEditTriggers(QAbstractItemView.NoEditTriggers)\n inventoryItems.setSelectionMode(QAbstractItemView.SingleSelection)\n inventoryItems.verticalHeader().setVisible(False)\n inventoryItems.horizontalHeader().setStretchLastSection(True)\n\n # NOTE: Ensure that inventory category name matches the inventory database table names (with the exception\n # of spaces).\n\n # Inventory Category Model\n categoryModel = QStandardItemModel()\n categoryModel.setHorizontalHeaderLabels([\"Category\"])\n categoryModel.appendRow(QStandardItem(\"Battery\"))\n categoryModel.appendRow(QStandardItem(\"Air RFD\"))\n categoryModel.appendRow(QStandardItem(\"Ground RFD\"))\n categoryModel.appendRow(QStandardItem(\"Transmitters\"))\n categoryModel.appendRow(QStandardItem(\"Transmitter Battery\"))\n categoryModel.appendRow(QStandardItem(\"Flight Engineer\"))\n categoryModel.appendRow(QStandardItem(\"Flight Planner\"))\n\n # Inventory Category TableView\n inventoryCategories = QTableView()\n inventoryCategories.setModel(categoryModel)\n inventoryCategories.selectRow(0)\n inventoryCategories.setShowGrid(True)\n inventoryCategories.setEditTriggers(QAbstractItemView.NoEditTriggers)\n inventoryCategories.setSelectionMode(QAbstractItemView.SingleSelection)\n inventoryCategories.verticalHeader().setVisible(False)\n inventoryCategories.horizontalHeader().setStretchLastSection(True)\n inventoryCategories.clicked.connect(self.onInventoryCategoryChanged)\n\n splitter = QSplitter(Qt.Horizontal)\n splitter.addWidget(inventoryCategories)\n splitter.addWidget(inventoryItems)\n splitter.setStretchFactor(0, 3)\n splitter.setStretchFactor(1, 5)\n\n # Add button (insert data into database)\n self.addButton = CM.createButton(\"Add\", tool_tip=\"Add item into inventory list\")\n self.addButton.clicked.connect(lambda: self.addItemIntoDatabase(inventoryCategories.currentIndex(), inventoryDatabase))\n\n # Remove button (remove data from database)\n self.removeButton = CM.createButton(\"Remove\", tool_tip=\"Remove selected item from inventory list\")\n self.removeButton.clicked.connect(lambda: self.removeItemFromDatabase(inventoryCategories.currentIndex(), inventoryItems.currentIndex().data(), inventoryDatabase))\n\n # Back button (to go back to home page)\n self.backButton = CM.createButton(\"Back\", tool_tip=\"Go back to settings overview\")\n self.backButton.clicked.connect(lambda: self.goHome(stack))\n\n self.mainButtonsHBox = QHBoxLayout()\n self.mainButtonsHBox.setSpacing(10)\n self.mainButtonsHBox.addStretch()\n self.mainButtonsHBox.addWidget(self.addButton)\n self.mainButtonsHBox.addWidget(self.removeButton)\n self.mainButtonsHBox.addWidget(self.backButton)\n\n mainColumn = QVBoxLayout()\n mainColumn.setContentsMargins(20, 20, 20, 20)\n mainColumn.setSpacing(20)\n mainColumn.addWidget(splitter)\n mainColumn.addItem(self.mainButtonsHBox)\n\n self.setLayout(mainColumn)\n\n def goHome(self, stack):\n stack.setCurrentIndex(0)\n\n def addItemIntoDatabase(self, index, inventoryDatabase):\n \"\"\"Add item into inventory list database\n\n Args:\n :param index: Current selected inventory category row (QModelIndex)\n :param inventoryDatabase: inventory list database object\n \"\"\"\n title = \"Add {}\".format(index.data())\n subtitle = \"{} Name\".format(index.data())\n\n inputDialog = QInputDialog(self)\n inputDialog.setInputMode(QInputDialog.TextInput)\n inputDialog.setLabelText(subtitle)\n inputDialog.setWindowTitle(title)\n inputDialog.resize(500, 200)\n\n ok = inputDialog.exec_()\n text = inputDialog.textValue()\n\n if ok and text:\n tableName = index.data().replace(\" \", \"_\")\n query = QSqlQuery(inventoryDatabase)\n query.exec_(\"\"\"INSERT INTO '{}' (name) VALUES('{}')\"\"\".format(tableName, text))\n self.inventoryItemsModel.select()\n\n def removeItemFromDatabase(self, index, text, inventoryDatabase):\n \"\"\"Remove item from inventory list database\n\n Args:\n :param index: Current selected inventory category row (QModelIndex)\n :param text: Item to be removed from the inventory (str)\n :param inventoryDatabase: inventory list database object\n \"\"\"\n # Ensure that a row is selected before proceeding to delete it\n if not text:\n return\n\n buttonPressed = QMessageBox.critical(self, \"Confirm deletion?\",\n \"\"\"Are you sure you want to delete {} {} from the inventory?\"\"\".format(index.data(), text),\n QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n\n # Only delete row if user confirms again\n if buttonPressed == QMessageBox.No:\n return\n\n tableName = index.data().replace(\" \", \"_\")\n query = QSqlQuery(inventoryDatabase)\n query.exec_(\"\"\"DELETE FROM '{}' WHERE name = '{}'\"\"\".format(tableName, text))\n self.inventoryItemsModel.select()\n\n def onInventoryCategoryChanged(self, index):\n \"\"\"Update inventory items table when inventory category is changed\n\n Args:\n :param index: Current selected inventory category row (QModelIndex)\n \"\"\"\n tableName = index.data().replace(\" \", \"_\")\n self.inventoryItemsModel.setTable(tableName)\n self.inventoryItemsModel.setHeaderData(0, Qt.Horizontal, \"Name\")\n self.inventoryItemsModel.select()","sub_path":"ui/InventoryOverview.py","file_name":"InventoryOverview.py","file_ext":"py","file_size_in_byte":6703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"387341171","text":"import io\nfrom os.path import join\nimport pkg_resources\n\nimport pandas as pd\n\n\ndef load_dataset(dataset, name):\n \"\"\" load example dataset or load from user supplied path \"\"\"\n if dataset == 'example':\n path = 'experiments/datasets/example/{}.csv'.format(name)\n data = pkg_resources.resource_string('energypy', path)\n\n return pd.read_csv(\n io.BytesIO(data), index_col=0, parse_dates=True\n )\n\n else:\n return pd.read_csv(\n join(dataset, name + '.csv'),\n index_col=0,\n parse_dates=True\n )\n","sub_path":"energypy/experiments/load_dataset.py","file_name":"load_dataset.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"147036346","text":"import random\npossibilities = [' ', '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\n\ndef random_solution(length):\n solution = []\n for i in range(length):\n solution.append(possibilities[random.randint(0, len(possibilities) - 1)])\n\n return solution\n\n\ndef pick_parent(generation):\n\n # pick two parents\n parent_genome_1 = generation.genomes[random.randint(0, len(generation.genomes) - 1)]\n parent_genome_2 = generation.genomes[random.randint(0, len(generation.genomes) - 1)]\n\n # compare their fitness and return the highest\n if parent_genome_1.fitness > parent_genome_2.fitness:\n return parent_genome_1\n else:\n return parent_genome_2\n\n\ndef max_member(data):\n max_index = 0\n max_number = data[max_index].fitness\n\n for i in range(1, len(data)):\n if data[i].fitness > max_number:\n max_index = i\n max_number = data[i].fitness\n return max_index\n\n\ndef crossover(p1, p2):\n new_solution = []\n mid_point = random.randint(0, len(p1.solution) - 1)\n\n for i in range(len(p1.solution)):\n if i < mid_point:\n new_solution.append(p1.solution[i])\n else:\n new_solution.append(p2.solution[i])\n\n return new_solution\n\n\ndef mutate(solution, mutation_rate):\n for i in range(len(solution)):\n random_number = random.random()\n\n if random_number < mutation_rate:\n solution[i] = possibilities[random.randint(0, len(possibilities) - 1)]\n\n return solution\n\n","sub_path":"GA-string matching/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"227523709","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ntest_stemmer\n----------------------------------\n\nTests for `stemmer` module.\n\"\"\"\n\nimport unittest\n\nimport prog.stemmer as stem\n\n\nclass TestStemmer(unittest.TestCase):\n def test_000_english_stemmer_positive(self):\n test = ['worked','wishes', 'hopefully']\n res = ['work', 'wish', 'hope']\n\n stemmer = stem.EnglishStemmer()\n test = stemmer.stem_word_list(test)\n self.assertEqual(res, test)\n\n def test_001_english_stemmer_negative(self):\n test = ['beautiful', 'does']\n res = ['beauti', 'doe']\n\n stemmer = stem.EnglishStemmer()\n test = stemmer.stem_word_list(test)\n self.assertEqual(res, test)\n\n\nif __name__ == '__main__':\n import sys\n\n sys.exit(unittest.main())\n","sub_path":"tests/test_stemmer.py","file_name":"test_stemmer.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"333551422","text":"import json\nfrom neopython_ext_rpc_server.ExtRpcTestCase import ExtendedJsonRpcApiTestCase, mock_get_request, mock_post_request\nfrom klein.test.test_resource import requestMock\n\n\"\"\"\nSpecial thanks to @jseagrave21 for writing most of the original tests\n\"\"\"\n\n\nclass TestServer(ExtendedJsonRpcApiTestCase):\n def setUp(self):\n super().setUp()\n\n def test_HTTP_OPTIONS_request(self):\n mock_req = mock_get_request(b'/?test', b\"OPTIONS\")\n res = json.loads(self.app.home(mock_req))\n\n self.assertTrue(\"GET\" in res['supported HTTP methods'])\n self.assertTrue(\"POST\" in res['supported HTTP methods'])\n self.assertTrue(\"extended-rpc\" in res['JSON-RPC server type'])\n\n def test_invalid_request_method(self):\n # test HEAD method\n mock_req = mock_get_request(b'/?test', b\"HEAD\")\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32600)\n self.assertEqual(res[\"error\"][\"message\"], 'HEAD is not a supported HTTP method')\n\n def test_invalid_json_payload(self):\n # test POST requests\n mock_req = mock_post_request(b\"{ invalid\")\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32700)\n\n mock_req = mock_post_request(json.dumps({\"some\": \"stuff\"}).encode(\"utf-8\"))\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32600)\n\n # test GET requests\n mock_req = mock_get_request(b\"/?%20invalid\") # equivalent to \"/? invalid\"\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32600)\n\n mock_req = mock_get_request(b\"/?some=stuff\")\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32600)\n\n def test_missing_fields(self):\n # test POST requests\n req = self._gen_post_rpc_req(\"foo\")\n del req[\"jsonrpc\"]\n mock_req = mock_post_request(json.dumps(req).encode(\"utf-8\"))\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32600)\n self.assertEqual(res[\"error\"][\"message\"], \"Invalid value for 'jsonrpc'\")\n\n req = self._gen_post_rpc_req(\"foo\")\n del req[\"id\"]\n mock_req = mock_post_request(json.dumps(req).encode(\"utf-8\"))\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32600)\n self.assertEqual(res[\"error\"][\"message\"], \"Field 'id' is missing\")\n\n req = self._gen_post_rpc_req(\"foo\")\n del req[\"method\"]\n mock_req = mock_post_request(json.dumps(req).encode(\"utf-8\"))\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32600)\n self.assertEqual(res[\"error\"][\"message\"], \"Field 'method' is missing\")\n\n # test GET requests\n mock_req = mock_get_request(b\"/?method=foo&id=2\")\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32600)\n self.assertEqual(res[\"error\"][\"message\"], \"Invalid value for 'jsonrpc'\")\n\n mock_req = mock_get_request(b\"/?jsonrpc=2.0&method=foo\")\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32600)\n self.assertEqual(res[\"error\"][\"message\"], \"Field 'id' is missing\")\n\n mock_req = mock_get_request(b\"/?jsonrpc=2.0&id=2\")\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32600)\n self.assertEqual(res[\"error\"][\"message\"], \"Field 'method' is missing\")\n\n def test_invalid_method(self):\n # test POST requests\n req = self._gen_post_rpc_req(\"invalid\", request_id=\"42\")\n mock_req = mock_post_request(json.dumps(req).encode(\"utf-8\"))\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"id\"], \"42\")\n self.assertEqual(res[\"error\"][\"code\"], -32601)\n self.assertEqual(res[\"error\"][\"message\"], \"Method not found\")\n\n # test GET requests\n req = self._gen_get_rpc_req(\"invalid\")\n mock_req = mock_get_request(req)\n res = json.loads(self.app.home(mock_req))\n self.assertEqual(res[\"error\"][\"code\"], -32601)\n self.assertEqual(res[\"error\"][\"message\"], \"Method not found\")\n\n def test_gzip_compression(self):\n req = self._gen_post_rpc_req(\"getblock\", params=['307ed2cf8b8935dd38c534b10dceac55fcd0f60c68bf409627f6c155f8143b31', 1])\n body = json.dumps(req).encode(\"utf-8\")\n\n # first validate that we get a gzip response if we accept gzip encoding\n mock_req = requestMock(path=b'/', method=b\"POST\", body=body, headers={'Accept-Encoding': ['deflate', 'gzip;q=1.0', '*;q=0.5']})\n res = self.app.home(mock_req)\n\n GZIP_MAGIC = b'\\x1f\\x8b'\n self.assertIsInstance(res, bytes)\n self.assertTrue(res.startswith(GZIP_MAGIC))\n\n # then validate that we don't get a gzip response if we don't accept gzip encoding\n mock_req = requestMock(path=b'/', method=b\"POST\", body=body, headers={})\n res = self.app.home(mock_req)\n\n self.assertIsInstance(res, str)\n\n try:\n json.loads(res)\n valid_json = True\n except ValueError:\n valid_json = False\n self.assertTrue(valid_json)\n","sub_path":"tests/test_rpc_server.py","file_name":"test_rpc_server.py","file_ext":"py","file_size_in_byte":5336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"366602344","text":"import pandas as pd\nimport os\nimport csv\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\n\n'''TAKES A GB GENOME FILE AND A CSV LIST OF LOCUS IDS TO AVOID. OUTPUT A FASTA FILE WITH ALL OTHER CDS'''\n\ngb = 'FM162591'\nfilename = gb + \"_negative.fasta\"\ngenbank_location = \"/Users/desho/Desktop/photorhabdus_svm/negatives/genbank/\" + gb + \".gb\"\navoid_positive = \"/Users/desho/Desktop/photorhabdus_svm/negatives/avoid/\" + gb + \".csv\"\n\ndef get_negatives(gb, avoid_locus):\n all_genes = []\n seq_record = SeqIO.parse(genbank_location, \"genbank\")\n for record in seq_record:\n for feature in record.features:\n if feature.type == 'CDS':\n try:\n translation = feature.qualifiers['translation']\n except:\n translation = None\n locus = feature.qualifiers['locus_tag']\n if translation and locus:\n if locus[0] in avoid_locus:\n print(locus[0])\n else:\n try:\n desc = feature.qualifiers['product'][0]\n except:\n desc = ''\n new_seqrecord = SeqRecord(\n Seq(translation[0]),\n id = locus[0],\n name = feature.qualifiers['protein_id'][0],\n description = desc,\n )\n all_genes.append(new_seqrecord)\n \n\n \n with open(filename, \"a\") as handle:\n SeqIO.write(all_genes, handle, \"fasta\")\n # #list of SeqRecord objects\n # #add locus tag to SeqRecord description\n # #SeqIO.write(record, handle, \"fasta\")\n\navoid_locus = []\n\nwith open(avoid_positive) as csvfile:\n avoid = csv.reader(csvfile)\n for row in avoid:\n avoid_locus += row\n\nget_negatives(genbank_location, avoid_locus)","sub_path":"photorhabdus_svm/py_scripts/extract_gene.py","file_name":"extract_gene.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"477762658","text":"import socket\nimport sys\n# Directly reference the os module\nsys.path.append(r\"C:\\Program Files (x86)\\IronPython 2.7\\Lib\")\nimport os\nimport codecs\nfrom threading import Thread\n\n\ndef Start(ip_address, server_name, server_password,server_port_number,server_backlog, res_folder_path):\n \n # start of by converting the numeric arguments into integers\n server_port_number = int(server_port_number)\n server_backlog = int(server_backlog)\n \n print(\"started {0} file server under port {1}\".format(server_name, server_port_number))\n\n # create, bind and listen based on server settings\n listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n listener.bind((ip_address,server_port_number))\n listener.listen(server_backlog)\n\n while True:\n handler, address = listener.accept() # handler = handle requests , address = the remote end point\n\n print(\"{0} has connected.\".format(address[0]))\n \n while(True):\n \n l = handler.recv(4096) # buffer to hold what command we are\n \n if l == b\"PUT\":\n do_put(handler,res_folder_path) # PUT command\n if l == b\"GET\":\n do_get(handler,res_folder_path)\n if l == \"LIST\":\n do_list(handler,res_folder_path)\n \n \n \n handler.close()\n\n listener.close()\n\n\ndef do_put(handler, res_folder_path):\n stop_code = str(300)\n buff = \"\" # used when writting to the file literally not sure why this works\n\n # the first information we are getting is the name of the file and its extension\n l = handler.recv(4096) # I doubt it wont be very big so I dont think we'll need to loop to parse this\n file_name, file_exten = get_file_name_exten(str(l))\n \n f = open(res_folder_path + \"\\\\\" + file_name + '.' + file_exten, 'wb') # create a new file\n \n l = handler.recv(4096)\n while(l):\n print(\"recieving {0}\".format(l))\n\n buff = buff + l # append data and recieve more\n buff = buff.strip(str(300)) # hack to remove the stop code\n if stop_code in l:\n break\n \n l = handler.recv(4096)\n \n if not l: break\n \n f.write(buff) # write the contents of the file\n f.close()\n print(\"done writing new file.\")\n return None\n\ndef do_get(handler,res_folder_path):\n stop_code = 300\n\n filename = handler.recv(4096) # first were going to get the name of the file\n filename = filename.decode('utf-8')\n # search the file list to see if that file exists.\n if filename in os.listdir(res_folder_path):\n # send the file that were looking for\n \n f = codecs.open(res_folder_path + '\\\\' + filename, 'r', encoding='utf8',errors='replace')\n line = f.read(4096) \n while(line):\n handler.send(bytes(line,'utf8')) \n line = f.readline(4096)\n \n handler.send(bytes(str(stop_code), 'utf8'))\n \n return None\n \n \ndef do_list(handler,res_folder_path):\n file_list = os.listdir(res_folder_path)\n\n # build a string with the list, delimiting the list using a new line\n send_str = \"\"\n for fna36me in file_list:\n send_str = send_str + fname + '\\n'\n\n handler.send(send_str)\n \ndef get_file_name_exten(filename):\n # simply split by the perion\n name, exten = filename.split('.')\n return name, exten\n\n# for testing compliation, this program is invoked through IronPython in Visual Studio\nif __name__ == '__main__':\n Start(\"192.168.1.10\",\"car\",\"it\",7777,10,r\"..\\res\")\n","sub_path":"FileClientSever/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"362616216","text":"'''\nUrban-PLUMBER processing code\nAssociated with the manuscript: Harmonized, gap-filled dataset from 20 urban flux tower sites\n\nCopyright (c) 2022 Mathew Lipson\n\nLicensed under the Apache License, Version 2.0 (the \"License\").\nYou may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0\n'''\n\n__title__ = \"site-specific processing wrapper\"\n__version__ = \"2022-09-15\"\n__author__ = \"Mathew Lipson\"\n__email__ = \"m.lipson@unsw.edu.au\"\n__description__ = 'Wrapper for processing individual sites. Includes setting site-specific information, importing raw site data, calling pipeline functions, creating site plots and webpages etc.'\n\nimport numpy as np\nimport xarray as xr\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport os\nimport sys\nimport argparse\nimport importlib\n\n# paths\noshome=os.getenv('HOME')\nprojpath = f'{oshome}/git/urban-plumber_pipeline' # root of repository\ndatapath = f'{oshome}/git/urban-plumber_pipeline/input_data' # raw data path (site data, global data)\n\nsys.path.append(projpath)\nimport pipeline_functions\nimportlib.reload(pipeline_functions)\n\n##########################################################################\n# MANUAL USER INPUTS\n##########################################################################\n# these are overridden with --existing flag (i.e. python create_dataset_XX.py --existing)\n\ncreate_raw_obs_nc = True # create obs nc from original format\ncreate_rain_file = True # find and load nearest GHCND\nqcplotdetail = True # plot quality control diurnal and timeseries\nforcingplots = True # plot forcing and analysis period obs and gap-filling\ncreate_outofsample_obs = True # for testing bias-correction on half of available obs\nfullpipeline = True # undertake full pipeline e.g. cleaning, bias correction, data creation\n\n##########################################################################\n# COMMAND LINE ARGUMENT PARSING\n##########################################################################\n\n# Initiate the parser\nparser = argparse.ArgumentParser()\nparser.add_argument('--log', help='log print statements to file', action='store_true')\nparser.add_argument('--projpath', help='replaces projpath with new path')\nparser.add_argument('--datapath', help='replaces datapath with new path')\nparser.add_argument('--existing', help='use existing outputs (processing already run)', action='store_true')\nparser.add_argument('--globaldata',help='output site characteristics from global dataset (if available)', action='store_true')\n\nargs = parser.parse_args()\n\nlog_stout = False\nif args.log:\n log_stout = True\nif args.projpath:\n print(f'updating projpath to {projpath}')\n projpath = args.projpath\nif args.datapath:\n print(f'updating datapath to {datapath}')\n datapath = args.datapath\nif args.existing:\n print('using existing files')\n create_raw_obs_nc = False\n create_rain_file = False\n qcplotdetail = False\n forcingplots = False\n create_outofsample_obs = False\n fullpipeline = False\n\n##########################################################################\n# SITE SPECIFIC INFORMATION\n##########################################################################\n\nsitename = 'US-Minneapolis2'\nout_suffix = 'v1'\nsitedata_suffix = 'v1'\n\nlocal_utc_offset_hours = -6\nlong_sitename = 'KUOM Tall Tower, Minneapolis, Minnesota, United States'\nobs_contact = 'Joe McFadden (mcfadden@ucsb.edu) University of California, Santa Barbara'\nobs_reference = 'Peters, Hiller, McFadden (2011): https://doi.org/10.1029/2010JG001463; Menzer and McFadden (2017): https://doi.org/10.1016/j.atmosenv.2017.09.049'\nobs_comment = 'Recreational sectors (180°-270°) of Minneapolis KUOM tower only. Air pressure (PSurf) from Minneapolis-Saint Paul International Airport. Radiation components (SWdown,SWup,LWdown,LWup) measured at 2 m above ground level, not from tower as other variables. SoilTemp at 5cm depth. Tower fluxes from original dataset which are flagged 2 excluded.'\nphoto_source='J. McFadden'\nhistory = 'v0.9 (2021-09-08): beta issue; v1 (2022-09-15): with publication in ESSD'\n\n##########################################################################\n# MAIN\n##########################################################################\n\ndef main():\n\n sitepath = f'{projpath}/sites/{sitename}'\n\n print('preparing site data and attributes')\n sitedata, siteattrs = pipeline_functions.prep_site(\n sitename, sitepath, out_suffix, sitedata_suffix, long_sitename, \n local_utc_offset_hours, obs_contact, obs_reference, obs_comment,\n history, photo_source, args.globaldata, datapath)\n\n print('getting observation netcdf\\n')\n if create_raw_obs_nc:\n\n print(f'creating observational NetCDF in ALMA format\\n')\n raw_ds = import_obs(sitedata,siteattrs)\n raw_ds = pipeline_functions.set_raw_attributes(raw_ds, siteattrs)\n \n else:\n fpath = f'{sitepath}/timeseries/{sitename}_raw_observations_{siteattrs[\"out_suffix\"]}.nc'\n raw_ds = xr.open_dataset(fpath)\n\n if create_rain_file:\n\n syear, eyear = raw_ds.time.dt.year.values[0] - 10, raw_ds.time.dt.year.values[-1]\n\n nearest = pipeline_functions.find_ghcnd_closest_stations(syear,eyear,sitedata,datapath,nshow=6)\n print('nearest stations, see: https://www.ncdc.noaa.gov/cdo-web/search:\\n',nearest)\n\n rain_sites = ['USC00218450', # UNIVERSITY OF MN ST. PAUL, MN US 44.9903 -93.1800 \n 'USC00214884'] # LOWER ST. ANTHONY FALLS, MN US 44.9783 -93.2469\n\n rain_obs = pipeline_functions.get_ghcnd_precip(sitepath,datapath,syear,eyear,rain_sites)\n pipeline_functions.write_ghcnd_precip(sitepath,sitename,rain_obs)\n\n ############################################\n ############ pipeline MAIN call ############\n raw_ds, clean_ds, watch_ds, era_ds, corr_ds, lin_ds, forcing_ds = pipeline_functions.main(\n datapath = datapath,\n sitedata = sitedata,\n siteattrs = siteattrs,\n raw_ds = raw_ds,\n fullpipeline = fullpipeline,\n qcplotdetail = qcplotdetail)\n ############################################\n\n print('post processing, plotting and checking')\n pipeline_functions.post_process_site(sitedata,siteattrs,datapath,\n raw_ds,forcing_ds,clean_ds,era_ds,watch_ds,corr_ds,lin_ds,\n forcingplots,create_outofsample_obs)\n\n print(f'{sitename} done!')\n\n return raw_ds, clean_ds, watch_ds, era_ds, corr_ds, forcing_ds\n\n##########################################################################\n# specific functinos\n##########################################################################\n\ndef import_obs(sitedata,siteattrs):\n\n fpath_obs = f'{datapath}/US-Minneapolis/kuom_data_extract_20150930.txt'\n\n # read data csv\n print('reading raw data file')\n raw = pd.read_csv(fpath_obs, delim_whitespace=True, skipfooter=1378, engine='python')\n\n # get times from data and reindex\n times = pd.date_range(start='2005-11-27 00:00', end='2009-05-29 7:00', freq='30Min')\n raw.index = times\n\n # # gives RH>100\n # esat = pipeline_functions.calc_esat(\n # temp = raw['Tair_40m_kuom']+273.15,\n # pressure = raw['Pair_kuom']*1000.,\n # mode=0)\n # rh = 100 * (esat - raw['vpd_40m_kuom']*1000.)/esat\n\n # # LiDAR cloud of building heights\n # bh = pd.read_csv('raw_data/KUOM_lidar_building_height_above_ground_in_footprint.txt',\n # header=None,names=['height']).sort_values(by='height',ignore_index=True)\n\n rho_air = pipeline_functions.calc_density(\n temp=raw['Tair_40m_kuom']+273.15,\n pressure=raw['Pair_kuom']*1000.)\n\n qair = (raw['h2o_40m_kuom']/1000)/rho_air\n\n # create dataframe in ALMA format\n df = pd.DataFrame(index=times)\n df = df.assign(\n SWdown = raw['Rs_in_turf'], # measured at 2m agl\n LWdown = raw['RL_in_turf'], # measured at 2m agl\n Tair = raw['Tair_40m_kuom']+273.15,\n Qair = pipeline_functions.convert_rh_to_qair(\n rh=raw['rh_40m_kuom'],\n temp=raw['Tair_40m_kuom']+273.15,\n pressure=raw['Pair_kuom']*1000.).where(raw['rh_40m_kuom']<=100),\n # Qair = (raw['h2o_40m_kuom']/1000)/rho_air, # wv concentration / air density\n PSurf = raw['Pair_kuom']*1000.,\n Rainf = raw['precip_turf']/1800.,\n Snowf = np.nan,\n Wind_N = pipeline_functions.convert_wdir_to_uv(\n speed=raw['ws_40m_kuom'],\n wind_dir_from=raw['wd_40m_kuom'], \n )[1],\n Wind_E = pipeline_functions.convert_wdir_to_uv(\n speed=raw['ws_40m_kuom'],\n wind_dir_from=raw['wd_40m_kuom'],\n )[0],\n SWup = raw['Rs_out_turf'], # measured at 2m agl\n LWup = raw['RL_out_turf'], # measured at 2m agl\n Qle = raw['LE_40m_kuom'].where(raw['qaqc_wh2o_40m_kuom']!=2), # remove data flagged 2\n Qh = raw['H_40m_kuom'].where(raw['qaqc_wTs_40m_kuom']!=2), # remove data flagged 2\n #######\n Qg = raw['G_turf'], # Ground heat flux in non-irrigated open turfgrass\n Qtau = pipeline_functions.convert_ustar_to_qtau(\n ustar=raw['ustar_40m_kuom'],\n temp=raw['Tair_40m_kuom']+273.15,\n pressure=raw['Pair_kuom']*1000.,\n air_density=rho_air).where(raw['qaqc_uw_40m_kuom']!=2), # remove data flagged 2\n # Tair2m=raw['Tair_135cm_turf']+273.15,\n SoilTemp=raw['Tsoil_5cm_gf_turf']+273.15 # 5cm below ground\n )\n\n '''\n From Menzer et al. 2017\n The residential sector was defined to include observations to the northeast (wind direction between 0+ and 75+) and to the northwest of the tower (wind direction between 285+ and 360+). \n The recreational sector included observations from the southwest over the nearby golf course, spanning wind directions from 195 to 270 .\n '''\n\n analysis_fluxes = ['Qh','Qle','Qtau']\n wind_dir = pd.Series(data=raw['wd_40m_kuom'],index=times)\n # remove residential wind sectors\n df[analysis_fluxes] = df[analysis_fluxes].where(~wind_dir.between(0,180))\n df[analysis_fluxes] = df[analysis_fluxes].where(~wind_dir.between(270,360))\n\n # reweight surface cover fractions to golf course\n wd = raw.where(wind_dir.between(180,270))\n\n weights = ['fp_K2d_frac_tree_dec','fp_K2d_frac_tree_eg','fp_K2d_frac_grass_irr','fp_K2d_frac_grass_nirr','fp_K2d_frac_impervious','fp_K2d_frac_water_pool','fp_K2d_frac_water_open','fp_K2d_frac_outside']\n print(wd[weights].describe())\n\n wd['trees'] = (wd['fp_K2d_frac_tree_dec'] + wd['fp_K2d_frac_tree_eg'])\n wd['grass'] = (wd['fp_K2d_frac_grass_irr'] + wd['fp_K2d_frac_grass_nirr']) \n wd['water'] = (wd['fp_K2d_frac_water_pool'] + wd['fp_K2d_frac_water_open']) \n wd['impervious'] = wd['fp_K2d_frac_impervious']\n\n fractions = wd[['trees','grass','water','impervious']].copy()\n\n fractions = fractions.divide(fractions.sum(axis=1),axis=0)\n\n print(fractions.mean().round(2))\n\n # remove early subset without radiation obs\n df = df.loc['2006-06-01 12:00':]\n\n # create qc flags, with 0=observed, 1=gap-filled by obsevations, 2=gap-filled by era-derived, 3=missing\n for key in df.columns:\n df[f'{key}_qc'] = np.where(df[key].isna(), 3, 0)\n\n df[f'PSurf_qc'] = np.where(df[f'PSurf_qc'].isna(), 3, 1)\n\n # convert times\n offset_from_utc = siteattrs['local_utc_offset_hours']\n df = pipeline_functions.convert_local_to_utc(df,offset_from_utc)\n\n # convert pandas dataframe to xarray dataset\n df.index.name='time'\n obs_ds = df.to_xarray()\n\n return obs_ds\n\n################################################################################\n\nif __name__ == \"__main__\":\n\n if log_stout:\n fname = f'log_processing_{sitename}_{out_suffix}.txt'\n print(f'logging print statements to {fname}')\n\n orig_stdout = sys.stdout\n f = open(f'{projpath}/sites/{sitename}/{fname}', 'w')\n sys.stdout = f\n\n raw_ds, clean_ds, watch_ds, era_ds, corr_ds, forcing_ds = main()\n\n if log_stout:\n sys.stdout = orig_stdout\n f.close()\n\n print('done!')\n","sub_path":"sites/US-Minneapolis2/create_dataset_US-Minneapolis2.py","file_name":"create_dataset_US-Minneapolis2.py","file_ext":"py","file_size_in_byte":12459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"231192012","text":"##################################################################################\n# #\n# Copyright (c) 2020 AECgeeks #\n# #\n# Permission is hereby granted, free of charge, to any person obtaining a copy #\n# of this software and associated documentation files (the \"Software\"), to deal #\n# in the Software without restriction, including without limitation the rights #\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #\n# copies of the Software, and to permit persons to whom the Software is #\n# furnished to do so, subject to the following conditions: #\n# #\n# The above copyright notice and this permission notice shall be included in all #\n# copies or substantial portions of the Software. #\n# #\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #\n# SOFTWARE. #\n# #\n##################################################################################\n\nfrom __future__ import print_function\n\nimport os\nimport json\nimport threading\n\nfrom collections import defaultdict, namedtuple\nfrom flask_dropzone import Dropzone\n\nfrom werkzeug.middleware.proxy_fix import ProxyFix\nfrom flask import Flask, request, send_file, render_template, abort, jsonify, redirect, url_for, make_response\nfrom flask_cors import CORS\nfrom flask_basicauth import BasicAuth\nfrom flasgger import Swagger\n\nimport utils\nimport worker\nimport database\n\napplication = Flask(__name__)\ndropzone = Dropzone(application)\n\n# application.config['DROPZONE_UPLOAD_MULTIPLE'] = True\n# application.config['DROPZONE_PARALLEL_UPLOADS'] = 3\n\nDEVELOPMENT = os.environ.get('environment', 'production').lower() == 'development'\n\n\nif not DEVELOPMENT and os.path.exists(\"/version\"):\n PIPELINE_POSTFIX = \".\" + open(\"/version\").read().strip()\nelse:\n PIPELINE_POSTFIX = \"\"\n\n\nif not DEVELOPMENT:\n # In some setups this proved to be necessary for url_for() to pick up HTTPS\n application.wsgi_app = ProxyFix(application.wsgi_app, x_proto=1)\n\nCORS(application)\napplication.config['SWAGGER'] = {\n 'title': os.environ.get('APP_NAME', 'ifc-pipeline request API'),\n 'openapi': '3.0.2',\n \"specs\": [\n {\n \"version\": \"0.1\",\n \"title\": os.environ.get('APP_NAME', 'ifc-pipeline request API'),\n \"description\": os.environ.get('APP_NAME', 'ifc-pipeline request API'),\n \"endpoint\": \"spec\",\n \"route\": \"/apispec\",\n },\n ]\n}\nswagger = Swagger(application)\n\nif not DEVELOPMENT:\n from redis import Redis\n from rq import Queue\n\n q = Queue(connection=Redis(host=os.environ.get(\"REDIS_HOST\", \"localhost\")), default_timeout=3600)\n\n\n@application.route('/', methods=['GET'])\ndef get_main():\n return render_template('index.html')\n\n\n\ndef process_upload(filewriter, callback_url=None):\n id = utils.generate_id()\n d = utils.storage_dir_for_id(id)\n os.makedirs(d)\n \n filewriter(os.path.join(d, id+\".ifc\"))\n \n session = database.Session()\n session.add(database.model(id, ''))\n session.commit()\n session.close()\n \n if DEVELOPMENT:\n t = threading.Thread(target=lambda: worker.process(id, callback_url))\n t.start()\n\n \n else:\n q.enqueue(worker.process, id, callback_url)\n\n return id\n \n\n\ndef process_upload_multiple(files, callback_url=None):\n id = utils.generate_id()\n d = utils.storage_dir_for_id(id)\n os.makedirs(d)\n \n file_id = 0\n session = database.Session()\n m = database.model(id, '') \n session.add(m)\n \n for file in files:\n fn = file.filename\n filewriter = lambda fn: file.save(fn)\n filewriter(os.path.join(d, id+\"_\"+str(file_id)+\".ifc\"))\n file_id += 1\n m.files.append(database.file(id, ''))\n \n session.commit()\n session.close()\n \n if DEVELOPMENT:\n t = threading.Thread(target=lambda: worker.process(id, callback_url))\n t.start() \n else:\n q.enqueue(worker.process, id, callback_url)\n\n return id\n\n\n\n@application.route('/', methods=['POST'])\ndef put_main():\n \"\"\"\n Upload model\n ---\n requestBody:\n content:\n multipart/form-data:\n schema:\n type: object\n properties:\n ifc:\n type: string\n format: binary\n responses:\n '200':\n description: redirect\n \"\"\"\n ids = []\n \n files = []\n for key, f in request.files.items():\n if key.startswith('file'):\n file = f\n files.append(file) \n\n \n id = process_upload_multiple(files)\n url = url_for('check_viewer', id=id) \n\n if request.accept_mimetypes.accept_json:\n return jsonify({\"url\":url})\n else:\n return redirect(url)\n\n\n@application.route('/p/', methods=['GET'])\ndef check_viewer(id):\n if not utils.validate_id(id):\n abort(404)\n return render_template('progress.html', id=id) \n \n \n@application.route('/pp/', methods=['GET'])\ndef get_progress(id):\n if not utils.validate_id(id):\n abort(404)\n session = database.Session()\n model = session.query(database.model).filter(database.model.code == id).all()[0]\n session.close()\n return jsonify({\"progress\": model.progress})\n\n\n@application.route('/log/.', methods=['GET'])\ndef get_log(id, ext):\n log_entry_type = namedtuple('log_entry_type', (\"level\", \"message\", \"instance\", \"product\"))\n \n if ext not in {'html', 'json'}:\n abort(404)\n \n if not utils.validate_id(id):\n abort(404)\n logfn = os.path.join(utils.storage_dir_for_id(id), \"log.json\")\n if not os.path.exists(logfn):\n abort(404)\n \n if ext == 'html':\n log = []\n for ln in open(logfn):\n l = ln.strip()\n if l:\n log.append(json.loads(l, object_hook=lambda d: log_entry_type(*(d.get(k, '') for k in log_entry_type._fields))))\n return render_template('log.html', id=id, log=log)\n else:\n return send_file(logfn, mimetype='text/plain')\n\n\n@application.route('/v/', methods=['GET'])\ndef get_viewer(id):\n if not utils.validate_id(id):\n abort(404)\n d = utils.storage_dir_for_id(id)\n \n ifc_files = [os.path.join(d, name) for name in os.listdir(d) if os.path.isfile(os.path.join(d, name)) and name.endswith('.ifc')]\n \n if len(ifc_files) == 0:\n abort(404)\n \n failedfn = os.path.join(utils.storage_dir_for_id(id), \"failed\")\n if os.path.exists(failedfn):\n return render_template('error.html', id=id)\n\n for ifc_fn in ifc_files:\n glbfn = ifc_fn.replace(\".ifc\", \".glb\")\n if not os.path.exists(glbfn):\n abort(404)\n \n n_files = len(ifc_files) if \"_\" in ifc_files[0] else None\n \n return render_template(\n 'viewer.html',\n id=id,\n n_files=n_files,\n postfix=PIPELINE_POSTFIX\n )\n\n\n@application.route('/m/', methods=['GET'])\ndef get_model(fn):\n \"\"\"\n Get model component\n ---\n parameters:\n - in: path\n name: fn\n required: true\n schema:\n type: string\n description: Model id and part extension\n example: BSESzzACOXGTedPLzNiNklHZjdJAxTGT.glb\n \"\"\"\n \n \n id, ext = fn.split('.', 1)\n \n if not utils.validate_id(id):\n abort(404)\n \n if ext not in {\"xml\", \"svg\", \"glb\", \"unoptimized.glb\"}:\n abort(404)\n \n path = utils.storage_file_for_id(id, ext) \n\n if not os.path.exists(path):\n abort(404)\n \n if os.path.exists(path + \".gz\"):\n import mimetypes\n response = make_response(\n send_file(path + \".gz\", \n mimetype=mimetypes.guess_type(fn, strict=False)[0])\n )\n response.headers['Content-Encoding'] = 'gzip'\n return response\n else:\n return send_file(path)\n\n\"\"\"\n# Create a file called routes.py with the following\n# example content to add application-specific routes\n\nfrom main import application\n\n@application.route('/test', methods=['GET'])\ndef test_hello_world():\n return 'Hello world'\n\"\"\"\ntry:\n import routes\nexcept ImportError as e:\n pass\n","sub_path":"application/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"381773923","text":"import json\n\nfrom flask import abort, flash, redirect, render_template, url_for, request, jsonify\nfrom flask_login import current_user, login_required\nfrom datetime import datetime\n\nfrom . import admin\nfrom .. import db\nfrom ..models import User, Role, MeterReading, Timetable, Preferences, Room, Building, Booking\nfrom .forms import UserAssignForm, RoleForm, UserForm, RoomForm, BuildingForm\nfrom app.home.views import get_logins\n\nfrom datetime import timedelta, datetime, date\n\n\ndef check_admin():\n \"\"\"\n Prevent non-admins from accessing the page\n \"\"\"\n if not current_user.is_admin:\n abort(403)\n\n\n@admin.route('/roles')\n@login_required\ndef list_roles():\n check_admin()\n \"\"\"\n List all roles\n \"\"\"\n roles = Role.query.all()\n return render_template('admin/roles/roles.html',\n roles=roles, title='Roles')\n\n@admin.route('/buildings')\n@login_required\ndef list_buildings():\n check_admin()\n \"\"\"\n List all buildings\n \"\"\"\n buildings = Building.query.all()\n return render_template('admin/buildings/buildings.html',\n buildings=buildings, title='Buildings')\n\n\n@admin.route('/rooms/')\n@login_required\ndef list_rooms(building_id):\n \"\"\"\n Return a list of all rooms within the system\n :return:\n \"\"\"\n check_admin()\n\n rooms = Room.query.filter_by(building_id=building_id).all()\n\n return render_template('admin/rooms/rooms.html', rooms=rooms, title='Rooms', building_id=building_id)\n\n\n@admin.route('/buildings/add/', methods=['GET', 'POST'])\n@login_required\ndef add_building():\n check_admin()\n\n form = BuildingForm()\n if form.validate_on_submit():\n building = Building(name=form.name.data)\n\n try:\n # add building to the database\n db.session.add(building)\n db.session.commit()\n\n flash('You have successfully added a new building.')\n except:\n # in case role name already exists\n flash('Error: building name already exists.')\n\n # redirect to the roles page\n return redirect(url_for('admin.list_buildings'))\n\n\n return render_template('admin/buildings/add_building.html', form=form, title='Add Building')\n\n\n@admin.route('/rooms/add/', methods=['GET', 'POST'])\n@login_required\ndef add_room(building_id):\n check_admin()\n\n form = RoomForm()\n if form.validate_on_submit():\n room = Room(name=form.name.data, floor_level=form.level.data, capacity=form.capacity.data, building_id=building_id)\n\n try:\n # add room to the database\n db.session.add(room)\n db.session.commit()\n\n flash('You have successfully added a new room.')\n except:\n # in case role name already exists\n flash('Error: room name already exists.')\n\n # redirect to the roles page\n return redirect(url_for('admin.list_rooms', building_id=building_id))\n\n return render_template('admin/rooms/add_room.html', form=form, title='Add Room')\n\n\n@admin.route('/bookings', methods=['GET', 'POST'])\n@login_required\ndef list_bookings():\n check_admin()\n\n # year = datetime.today().strftime('%Y')\n # month = datetime.today().strftime('%m')\n # day = datetime.today().strftime('%d')\n #\n # print(year)\n # print(month)\n # print(day)\n\n # from sqlalchemy import extract\n # # bookings = Booking.query.filter(extract('year', Booking.datetime) == year).filter(extract('month', Booking.datetime) == month).filter(extract('day', Booking.datetime) == day)\n # bookings = Booking.query.filter(extract('year', Booking.datetime) == year)\n # print(bookings)\n\n # current_date = date(year=datetime.today().year, month=datetime.today().month, day=datetime.today().day)\n # bookings = Booking.query.filter(Booking.datetime >= current_date).all()\n # print(bookings)\n\n current_date = datetime.today()\n year = current_date.year\n month = current_date.month\n day = current_date.day\n date_string = '{}/{}/{}'.format(day, month, year)\n\n current_date_start = datetime(year=year, month=month, day=day)\n current_date_end = datetime(year=year, month=month, day=day, hour=23, minute=59)\n\n from sqlalchemy import and_\n bookings = Booking.query.filter(and_(Booking.datetime >= current_date_start, Booking.datetime <= current_date_end)).all()\n\n return render_template('admin/bookings/bookings.html', title=\"Today's Bookings\", bookings=bookings, date=date_string)\n\n\n@admin.route('/roles/add', methods=['GET', 'POST'])\n@login_required\ndef add_role():\n \"\"\"\n Add a role to the database\n \"\"\"\n check_admin()\n\n add_role = True\n\n form = RoleForm()\n if form.validate_on_submit():\n role = Role(name=form.name.data,\n description=form.description.data)\n\n try:\n # add role to the database\n db.session.add(role)\n db.session.commit()\n flash('You have successfully added a new role.')\n except:\n # in case role name already exists\n flash('Error: role name already exists.')\n\n # redirect to the roles page\n return redirect(url_for('admin.list_roles'))\n\n # load role template\n return render_template('admin/roles/role.html', add_role=add_role,\n form=form, title='Add Role')\n\n\n@admin.route('/users/add', methods=['GET', 'POST'])\n@login_required\ndef add_user():\n \"\"\"\n Add a user to the database\n \"\"\"\n check_admin()\n\n form = UserForm()\n\n if form.validate_on_submit():\n user = User(email=form.data['email'],\n password=form.data['password'],\n username=form.data['username'],\n first_name=form.data['first_name'],\n last_name=form.data['last_name'])\n\n user.preferences = Preferences(number_of_people=2,\n has_pc=False,\n is_quiet=False)\n\n db.session.add(user)\n db.session.commit()\n flash('You have successfully added a new user')\n\n return redirect(url_for('admin.list_users'))\n\n return render_template('admin/users/add_user.html', form=form, title='Add User')\n\n\n@admin.route('/roles/edit/', methods=['GET', 'POST'])\n@login_required\ndef edit_role(id):\n \"\"\"\n Edit a role\n \"\"\"\n check_admin()\n\n add_role = False\n\n role = Role.query.get_or_404(id)\n form = RoleForm(obj=role)\n if form.validate_on_submit():\n role.name = form.name.data\n role.description = form.description.data\n db.session.add(role)\n db.session.commit()\n flash('You have successfully edited the role.')\n\n # redirect to the roles page\n return redirect(url_for('admin.list_roles'))\n\n form.description.data = role.description\n form.name.data = role.name\n return render_template('admin/roles/role.html', add_role=add_role,\n form=form, title=\"Edit Role\")\n\n\n@admin.route('/roles/delete/', methods=['GET', 'POST'])\n@login_required\ndef delete_role(id):\n \"\"\"\n Delete a role from the database\n \"\"\"\n check_admin()\n\n role = Role.query.get_or_404(id)\n db.session.delete(role)\n db.session.commit()\n flash('You have successfully deleted the role.')\n\n # redirect to the roles page\n return redirect(url_for('admin.list_roles'))\n\n\n@admin.route('/users')\n@login_required\ndef list_users():\n \"\"\"\n List all users\n \"\"\"\n check_admin()\n\n users = User.query.all()\n return render_template('admin/users/users.html',\n users=users, title='Users')\n\n\n@admin.route('/users/assign/', methods=['GET', 'POST'])\n@login_required\ndef assign_user(id):\n \"\"\"\n Assign a department and a role to an user\n \"\"\"\n check_admin()\n\n user = User.query.get_or_404(id)\n\n # # prevent admin from being assigned a department or role\n # if user.is_admin:\n # abort(403)\n\n form = UserAssignForm(obj=user)\n\n if form.validate_on_submit():\n user.role = form.data['role']\n user.is_admin = True if form.data['is_admin'] == 'YES' else False\n\n db.session.add(user)\n db.session.commit()\n flash('You have successfully assigned admin privileges and role.')\n\n # redirect to the roles page\n return redirect(url_for('admin.list_users'))\n else:\n form.is_admin.default = 'YES' if user.is_admin else 'NO'\n form.process()\n\n return render_template('admin/users/user.html',\n user=user, form=form,\n title='Assign User')\n\n\n@admin.route('/users/delete/', methods=['GET', 'POST'])\n@login_required\ndef delete_user(id):\n \"\"\"\n Admin: Remove a user\n \"\"\"\n check_admin()\n\n user = User.query.get(id)\n if user:\n username = user.username\n\n db.session.delete(user)\n db.session.commit()\n\n flash('You have successfully removed user {} from the system.'.format(username))\n else:\n flash('User does not exist.', 'error')\n\n return redirect(url_for('admin.list_users'))\n\n\n@admin.route('/efficiency', methods=['POST'])\n@login_required\ndef get_efficiency():\n data = json.loads(request.data)\n meter = data.get('meter')\n date = data.get('date').split('-')\n\n start = datetime(year=int(date[0]),\n month=int(date[1]),\n day=int(date[2]))\n\n meter_reading = MeterReading.query.filter_by(\n meter_reading_date=start,\n meter_id=int(meter)\n ).first()\n\n if meter_reading:\n return jsonify(meter_reading=meter_reading.to_dict())\n\n flash('No meter readings for that meter or date.', 'error')\n\n return abort(404)\n\n\n@admin.route('/timetable', methods=['GET', 'POST'])\n@login_required\ndef get_timetable():\n data = json.loads(request.data)\n year_group = data.get('year')\n\n timetable = Timetable.query.get(year_group)\n\n if timetable:\n return jsonify(timetable=timetable.to_dict())\n\n flash('No timetables available.', 'error')\n\n return abort(404)\n","sub_path":"app/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"180404382","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'vardb'\nurlpatterns = [\n path('variant/', views.variant, name='variant_view'),\n path('variant_collection/', views.variant_collection, name='variant_collection_view'),\n path('collection_set/', views.collection_set, name='collection_set_view'),\n\n\n\n]","sub_path":"vardb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"387338786","text":"# pylint: disable=missing-docstring\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport tarfile\n\nfrom six.moves import urllib\nimport tensorflow as tf\n\nimport cifar10_input\n\nIMAGE_SIZE = 32\nNUM_CLASSES = 10\nNUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 50000\nNUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 10000\n\n\n\n#从网址下载数据集存放到data_dir指定的目录中\ndef maybe_download_and_extract(data_dir):\n \"\"\"下载并解压缩数据集 from Alex's website.\"\"\"\n dest_directory = data_dir\n DATA_URL = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'\n if not os.path.exists(dest_directory):\n os.makedirs(dest_directory)\n filename = DATA_URL.split('/')[-1] #'cifar-10-binary.tar.gz'\n filepath = os.path.join(dest_directory, filename)#'../CIFAR10_dataset\\\\cifar-10-binary.tar.gz'\n if not os.path.exists(filepath):\n def _progress(count, block_size, total_size):\n sys.stdout.write('\\r>> Downloading %s %.1f%%' % (filename,\n float(count * block_size) / float(total_size) * 100.0))\n sys.stdout.flush()\n filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)\n print()\n statinfo = os.stat(filepath)\n print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')\n\n extracted_dir_path = os.path.join(dest_directory, 'cifar-10-batches-bin')#'../CIFAR10_dataset\\\\cifar-10-batches-bin'\n if not os.path.exists(extracted_dir_path):\n tarfile.open(filepath, 'r:gz').extractall(dest_directory)\n\ndef get_distorted_train_batch(data_dir,batch_size):\n \"\"\"Construct distorted input for CIFAR training using the Reader ops.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.\n\n Raises:\n ValueError: If no data_dir\n \"\"\"\n if not data_dir:\n raise ValueError('Please supply a data_dir')\n data_dir = os.path.join(data_dir, 'cifar-10-batches-bin')\n images, labels = cifar10_input.distorted_inputs(data_dir=data_dir,batch_size=batch_size)\n return images,labels\n\ndef get_undistorted_eval_batch(data_dir, batch_size, eval_data=True):\n \"\"\"Construct input for CIFAR evaluation using the Reader ops.\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.\n Raises:\n ValueError: If no data_dir\n \"\"\"\n if not data_dir:\n raise ValueError('Please supply a data_dir')\n data_dir = os.path.join(data_dir, 'cifar-10-batches-bin')\n images, labels = cifar10_input.inputs(eval_data=eval_data,data_dir=data_dir,batch_size=batch_size)\n return images,labels","sub_path":"model/cnn/vggnet/vgg16/cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"115908942","text":"from Pages.MediaPages.CtaButtonMedia import CtaButtonMedia\nimport pytest\n\n\n@pytest.allure.feature('Media')\n@pytest.allure.story('CTA media button')\n@pytest.mark.usefixtures('init_media_page')\nclass TestCtaButtonMedia:\n\n @pytest.allure.title('VDM-??? CTA media button - creating')\n def test_cta_button_adding(self):\n self.media_page.open_page('call_to_action')\n cta_button = CtaButtonMedia(self.driver)\n cta_button.fill_cta_mandatory()\n url = self.driver.current_url\n self.media_page.save_media()\n assert self.driver.current_url != url\n assert cta_button.get_cta_button().is_displayed()\n assert cta_button.get_cta_default_theme().is_displayed()\n self.media_page.delete_media()\n\n @pytest.allure.title('VDM-??? CTA media button - creating with all fields')\n def test_cta_button_adding_all_fields(self):\n self.media_page.open_page('call_to_action')\n cta_button = CtaButtonMedia(self.driver)\n cta_button.fill_cta_all_fields()\n url = self.driver.current_url\n self.media_page.save_media()\n assert self.driver.current_url != url\n assert cta_button.get_cta_button().is_displayed()\n assert cta_button.get_cta_custom_theme().is_displayed()\n assert cta_button.cta_data['link_url'] in cta_button.get_cta_button().get_attribute('href')\n assert cta_button.get_cta_button().get_attribute('target') == cta_button.cta_data['target']\n assert cta_button.get_cta_button().get_attribute('rel') == cta_button.cta_data['link_rel']\n assert cta_button.get_cta_button().text.lower() == cta_button.cta_data['link_text'].lower()\n self.media_page.delete_media()\n\n @pytest.allure.title('VDM-??? CTA media button - empty fields validation')\n def test_cta_button_empty_fields(self):\n self.media_page.open_page('call_to_action')\n cta_button = CtaButtonMedia(self.driver)\n url = self.driver.current_url\n cta_button.get_link_url()\n self.media_page.save_media()\n assert self.driver.current_url == url\n\n @pytest.allure.title('VDM-??? CTA media button - check fields existing')\n def test_cta_button_check_fields(self):\n self.media_page.open_page('call_to_action')\n cta_button = CtaButtonMedia(self.driver)\n assert cta_button.get_name().is_displayed()\n assert cta_button.get_link_url().is_displayed()\n assert cta_button.get_link_text().is_displayed()\n assert cta_button.get_attributes_tab().is_displayed()\n assert cta_button.get_colour_dropdown().first_selected_option","sub_path":"test_media/test_cta_button.py","file_name":"test_cta_button.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"134283843","text":"'''\r\nSphere Booking and Check-in\r\n260CT\r\nprototype\r\nSalah Abdo\r\nPython 3\r\n'''\r\nfrom Main import *\r\n\r\nclass updateMember():\r\n\r\n def __init__(self,master,mainwnd):\r\n\r\n self.mainwnd= mainwnd # store the 'self.master` of the main window\r\n self.master = master\r\n \r\n self.master= master\r\n self.master.geometry(\"1080x800+200+200\")\r\n self.master.title(\"Sphere Booking and Check-in\")\r\n\r\n self.conn = sqlite3.connect('Database.db')\r\n self.c = self.conn.cursor()\r\n\r\n Label(self.master, text=\"Sphere Booking and Check-in\",fg=\"black\",font=(\"Helvetica\",25)).grid(row=0,column=2)\r\n Label(self.master, text=\" \").grid(row=1)\r\n Label(self.master, text=\"First Name\").grid(row=2)\r\n Label(self.master, text=\" \").grid(row=3)\r\n Label(self.master, text=\"Surname\").grid(row=4)\r\n Label(self.master, text=\" \").grid(row=5)\r\n Label(self.master, text=\"Date of birth\").grid(row=6)\r\n Label(self.master, text=\" \").grid(row=7)\r\n\r\n\r\n self.e1 = Entry(self.master)\r\n self.e2 = Entry(self.master)\r\n self.e3 = Entry(self.master)\r\n\r\n self.e1.grid(row=2, column=1)\r\n self.e2.grid(row=4, column=1)\r\n self.e3.grid(row=6, column=1)\r\n\r\n\r\n Button(self.master, text='Update', command=self.checkValue, font=(\"Helvetica\",15, \"bold italic\")).grid(row=11, column=2, sticky=W, pady=4)\r\n Button(self.master, text='Home', command=self.goHome, font=(\"Helvetica\",15, \"bold italic\")).grid(row=12, column=2, sticky=W, pady=4)\r\n\r\n def goHome(self):\r\n self.master.destroy() # close the current Member window\r\n self.mainwnd.update() # update the home window\r\n self.mainwnd.deiconify() # un-minimize the home window\r\n\r\n def closeDB(self):\r\n self.c.close()\r\n self.conn.close()\r\n\r\n def updateMember(self):\r\n customerID = self.customer\r\n sessionNum = self.sessionNum\r\n loyalty = \"loyalty\"\r\n\r\n if sessionNum > 10: # check to see if the user meets the requirements to upgrade their membership\r\n self.c.execute(\"UPDATE Member SET Membership_Type = (?) WHERE Customer_ID = (?) \", # find the customer in the database and updates his membership status\r\n (loyalty, customerID))\r\n self.conn.commit()\r\n self.closeDB()\r\n else:\r\n print(\"user does not have more than 10 sessions\")\r\n print(sessionNum)\r\n \r\n \r\n def checkValue(self):\r\n\r\n firstName = self.e1.get()\r\n surname = self.e2.get()\r\n dob = self.e3.get()\r\n \r\n self.c.execute(\"SELECT CustomerID FROM Customer WHERE FirstName = ? AND surname = ? AND date_of_birth = ?\",\r\n (firstName, surname, dob))\r\n self.ID = self.c.fetchone()\r\n self.customer = str(self.ID[0])\r\n\r\n self.c.execute(\"SELECT number_of_sessions FROM Customer WHERE FirstName = ? AND surname = ? AND date_of_birth = ?\",\r\n (firstName, surname, dob))\r\n\r\n session = self.c.fetchone()\r\n self.sessionNum = int(session[0])\r\n \r\n self.updateMember() \r\n \r\n\r\nclass regMember():\r\n\r\n def __init__(self,master,mainwnd):\r\n\r\n self.mainwnd= mainwnd # store the 'self.master` of the main window\r\n self.master = master\r\n \r\n self.master.geometry(\"1080x800+200+200\")\r\n self.master.title(\"Sphere Booking and Check-in\")\r\n\r\n self.conn = sqlite3.connect('Database.db')\r\n self.c = self.conn.cursor()\r\n\r\n Label(self.master, text=\"Sphere Booking and Check-in\",fg=\"black\",font=(\"Helvetica\",25)).grid(row=0,column=2)\r\n Label(self.master, text=\" \").grid(row=1)\r\n Label(self.master, text=\"First Name\").grid(row=2)\r\n Label(self.master, text=\" \").grid(row=3)\r\n Label(self.master, text=\"Surname\").grid(row=4)\r\n Label(self.master, text=\" \").grid(row=5)\r\n Label(self.master, text=\"Date of birth\").grid(row=6)\r\n Label(self.master, text=\" \").grid(row=7)\r\n Label(self.master, text=\"Date\").grid(row=2,column=2)\r\n Label(self.master, text=\" \").grid(row=3)\r\n\r\n self.MFname = Entry(self.master)\r\n self.MSname = Entry(self.master)\r\n self.Mdob = Entry(self.master)\r\n self.Mdate = Entry(self.master)\r\n\r\n self.MFname.grid(row=2, column=1)\r\n self.MSname.grid(row=4, column=1)\r\n self.Mdob.grid(row=6, column=1)\r\n self.Mdate.grid(row=2, column=3)\r\n\r\n Button(self.master, text='Create membership', command=self.checkValue, font=(\"Helvetica\",15, \"bold italic\")).grid(row=11, column=4, sticky=W, pady=4)\r\n Button(self.master, text='Home', command=self.goHome, font=(\"Helvetica\",15, \"bold italic\")).grid(row=12, column=4, sticky=W, pady=4)\r\n\r\n def goHome(self):\r\n self.master.destroy() # close the current Member window\r\n self.mainwnd.update() # update the home window\r\n self.mainwnd.deiconify() # un-minimize the home window\r\n\r\n def closeDB(self):\r\n self.c.close()\r\n self.conn.close()\r\n self.goHome()\r\n \r\n def insertMember(self):\r\n customerID = int(self.customerID)\r\n date = self.Mdate.get()\r\n membershipType = \"standard\"\r\n membership = self.memID \r\n \r\n self.c.execute(\"INSERT INTO Member ( Membership_ID, Customer_ID, Membership_Type, Join_Date) VALUES (?, ?, ?, ?)\",\r\n (membership, customerID, membershipType, date,))\r\n self.conn.commit()\r\n\r\n self.closeDB()\r\n \r\n def randomMemberID(self):\r\n range_start = 10**(10-1)\r\n range_end = (10**10)-1\r\n self.memID = randint(range_start, range_end)\r\n \r\n self.insertMember()\r\n \r\n def checkValue(self):\r\n\r\n firstName = self.MFname.get()\r\n surname = self.MSname.get()\r\n dob = self.Mdob.get()\r\n \r\n self.c.execute(\"SELECT CustomerID FROM Customer WHERE FirstName = ? AND surname = ? AND date_of_birth = ?\",\r\n (firstName, surname, dob))\r\n self.ID = self.c.fetchone()\r\n \r\n self.customerID = self.ID[0]\r\n \r\n self.randomMemberID() \r\n \r\n","sub_path":"260CT/260CT-Group-master/Prototype1/member.py","file_name":"member.py","file_ext":"py","file_size_in_byte":6244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"326581820","text":"__author__ = 'Hao'\n\n\nclass State:\n\n state_id_num = 1\n\n def __init__(self):\n self.state_id = State.state_id_num\n self.is_accepting_state = False\n self.transitions = dict()\n State.state_id_num += 1\n\n def __hash__(self):\n return hash(self.state_id)\n\n # generate a new nfa state\n @classmethod\n def gen_nfa_state(cls):\n nfa_state = cls()\n return nfa_state\n\n # generate a new dfa state from a set of nfa states\n @classmethod\n def gen_dfa_state(cls, nfa_states):\n dfa_state = cls()\n dfa_state.nfa_states = nfa_states\n for nfa_state in nfa_states:\n if nfa_state.is_accepting_state:\n dfa_state.is_accepting_state = True\n break\n return dfa_state\n\n # add a transition, from self_state to to_state, char_input is the input consumed\n def add_transition(self, char_input, to_state):\n if char_input not in self.transitions.keys():\n self.transitions[char_input] = list()\n self.transitions[char_input].append(to_state)\n\n # get a dfa state which can be reached by consuming char_input\n def get_to_state(self, char_input):\n if not hasattr(self, \"nfa_states\"):\n return None\n if self.transitions.get(char_input) == None:\n return None\n else:\n return self.transitions[char_input][0]\n\n # get a set of states which can be reached by consuming char_input\n def move(self, char_input):\n to_state_set = set()\n if hasattr(self, \"nfa_states\"): # for dfa state\n for nfa_state in self.nfa_states:\n to_state_set.update(nfa_state.transitions.get(char_input, []))\n else: # for nfa state\n to_state_set.update(self.transitions.get(char_input, []))\n return to_state_set\n\n # display NFA/DFA info\n def print_all_transitions(self):\n for char_input in self.transitions.keys():\n for to_state in self.transitions.get(char_input):\n print(\"from: \" + str(self.state_id) + \" througn: \" + char_input + \" to: \"\n + str(to_state.state_id))\n if self.is_accepting_state:\n print(str(self.state_id) + \" is accepting state!\")\n\n\n\n","sub_path":"state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"164172033","text":"from conditional import Conditional\n\n# On the roll of two independent dice, if at least one face is known to be\n# an even number, what is the probability of a total of 8?\n\nDIE_ELEM_EVENTS = [1, 2, 3, 4, 5, 6]\nTOTAL_DICE = 2\n\n\ndef is_odd(num):\n return int(num) % 2 == 1\n\n\ndef calc_prob(elem_events, total_items):\n die_conditional = Conditional(elem_events)\n die_init_arrangements = die_conditional.arrange_items(total_items)\n\n # Excludes the case where both dice are odd\n arrangements = [arr for arr in die_init_arrangements if not (is_odd(arr[0]) and is_odd(arr[1]))]\n\n # Cases where total of 2 dice is 8\n total_8 = [arr for arr in arrangements if int(arr[0]) + int(arr[1]) == 8]\n\n print(f\"{len(total_8)}/{len(arrangements)}\")\n return len(total_8) / len(arrangements)\n\n\ndef main():\n probability = calc_prob(DIE_ELEM_EVENTS, TOTAL_DICE)\n print(probability)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"conditional/ex1.8-2.py","file_name":"ex1.8-2.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"370644758","text":"class Solution:\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n numa = int(a, base=2)\n numb = int(b, base=2)\n nsum = numa + numb\n ssum = \"{0:b}\".format(nsum)\n return ssum\n","sub_path":"string/67_e_addbinary.py","file_name":"67_e_addbinary.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"383892578","text":"from flask import Flask, render_template, request\r\nimport joblib\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nimport pandas as pd\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/')\r\ndef cosine_input():\r\n return render_template('cosine.html')\r\n\r\n@app.route('/cosine' , methods = ['post'])\r\ndef cosine():\r\n count_vector_data = CountVectorizer(stop_words='english')\r\n text1 = request.form.get('text1')\r\n text2 = request.form.get('text2')\r\n\r\n document = [text1,text2]\r\n\r\n sparse_matrix = count_vector_data.fit_transform(document)\r\n\r\n df= pd.DataFrame(sparse_matrix.todense(), columns=count_vector_data.get_feature_names(),\r\n index=['text1','text2'])\r\n\r\n output = cosine_similarity(df,df)\r\n print(output)\r\n if output[0][1]>=0.8:\r\n ans = 'Similar'\r\n else:\r\n ans = 'not similar'\r\n return render_template('cosine_op.html', cosine_op= f'the word is {ans}' )\r\n\r\n\r\n\r\nif __name__ == '__main__': \r\n app.run(host='0.0.0.0', port=8080)","sub_path":"cosine_app.py","file_name":"cosine_app.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"614351150","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[358]:\n\n\nimport json\nimport requests\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport datetime\nimport tweepy\nimport datetime as dt\nimport numpy as np\nimport array as arr\n\n\n#how many days back?\ndays = 500\n\n\ndef getData (coin, currency, daysback):\n \"\"\"API call to coingecko for historical coin prices\"\"\"\n api_url = ('https://api.coingecko.com/api/v3/coins/' + str(coin) +\n '/market_chart?vs_currency=' + str(currency) +\n '&days=' + str(daysback))\n\n response = requests.get(api_url).text\n return json.loads(response)\n\n# Get coin data\ndata = getData('bitcoin', 'eur', days)\n\n# initialise variables\ntime = []\nprice = []\ntrend = []\n\n#reading in csv\ntrends_df = pd.read_csv(\"googleTrends5y.csv\", header = 0)\n\n# format data to usable lists\nfor day in data['prices']:\n # cuts ms\n date_time = datetime.date.fromtimestamp(int(day[0] / 1000)).strftime(\"%Y-%m-%d\")\n if date_time <= trends_df[\"Week\"].max():\n time.append(datetime.datetime.fromtimestamp(int(day[0] / 1000)))\n price.append(day[1])\n\n #be wary of list length so only add trend for entire week in a loop(to avoid index errors)\n if date_time in trends_df.values:\n current_trend = trends_df.loc[trends_df['Week'] == date_time, 'bitcoin: (Worldwide)'].iloc[0]\n for i in range(7):\n trend.append(current_trend)\n\n\n#remove extra list entries from \"trend\" so lists have same length for DF\ndifference = len(trend) - len(time)\ntrend = trend[:len(trend)-difference]\n#do the same for other two lists if they're the bigger ones (delete first entries instead)\nif difference < 0:\n difference = len(time) - len(trend)\n del time[:difference]\n del price[:difference]\n\n# feed data lists into pandas dataframe\ndf = pd.DataFrame({\n 'time':time,\n 'price':price,\n 'trend':trend\n})\n\n#save it as a csv file\ndf.to_csv('./new.csv', index = False)\n\n\n##plot\n\n\nprint(\"As per google: Numbers represent search interest relative to the highest point on the chart for the given region and time. A value of 100 is the peak popularity for the term. A value of 50 means that the term is half as popular. A score of 0 means there was not enough data for this term.\")\n##subplots\nfig, ax1 = plt.subplots()\n\ncolor = 'tab:red'\nax1.set_xlabel('time')\nax1.set_ylabel('bitcoin price', color=color)\nax1.plot(df.time, df.price, color=color)\nax1.tick_params(axis='y', labelcolor=color)\n\nax2 = ax1.twinx() #2nd axis\n\ncolor = 'tab:blue'\nax2.set_ylabel('google trend %', color=color)\nax2.plot(df.time, df.trend, color=color)\nax2.tick_params(axis='y', labelcolor=color)\nfig.autofmt_xdate()\nfig.tight_layout()\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n","sub_path":"finsightTrends.py","file_name":"finsightTrends.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"15516297","text":"import json\nimport os\nimport yaml\n\napi_group = os.getenv(\"CRD_API_GROUP\", \"amalthea.dev\")\napi_version = os.getenv(\"CRD_API_VERSION\", \"v1alpha1\")\ncustom_resource_name = os.getenv(\"CRD_NAME\", \"JupyterServer\")\n\n\ntry:\n with open(\"/app/config/kopf-operator-settings.yaml\", \"r\") as f:\n kopf_operator_settings = yaml.safe_load(f.read())\nexcept FileNotFoundError:\n kopf_operator_settings = {}\n\namalthea_selector_labels = yaml.safe_load(os.getenv(\"AMALTHEA_SELECTOR_LABELS\", \"{}\"))\n\n\n# Allowed child resources / groups that we need per default\nCHILD_RESOURCES = [\n {\"name\": \"statefulsets\", \"group\": \"apps\"},\n {\"name\": \"pods\", \"group\": \"\"},\n {\"name\": \"ingresses\", \"group\": \"networking.k8s.io\"},\n {\"name\": \"secrets\", \"group\": \"\"},\n {\"name\": \"configmaps\", \"group\": \"\"},\n {\"name\": \"services\", \"group\": \"\"},\n {\"name\": \"persistentvolumeclaims\", \"group\": \"\"},\n]\n\nCHILD_RESOURCES += json.loads(os.getenv(\"EXTRA_CHILD_RESOURCES\", \"[]\"))\n\nKOPF_CREATE_TIMEOUT = (\n None\n if os.getenv(\"KOPF_CREATE_TIMEOUT\", \"\") == \"\"\n else float(os.getenv(\"KOPF_CREATE_TIMEOUT\"))\n)\nKOPF_CREATE_BACKOFF = (\n None\n if os.getenv(\"KOPF_CREATE_BACKOFF\", \"\") == \"\"\n else float(os.getenv(\"KOPF_CREATE_BACKOFF\"))\n)\nKOPF_CREATE_RETRIES = (\n None\n if os.getenv(\"KOPF_CREATE_RETRIES\", \"\") == \"\"\n else int(os.getenv(\"KOPF_CREATE_RETRIES\"))\n)\n\nJUPYTER_SERVER_IDLE_CHECK_INTERVAL_SECONDS = int(\n os.getenv(\"JUPYTER_SERVER_IDLE_CHECK_INTERVAL_SECONDS\", 300)\n)\nCPU_USAGE_MILLICORES_IDLE_THRESHOLD = int(\n os.getenv(\"CPU_USAGE_MILLICORES_IDLE_THRESHOLD\", 200)\n)\n","sub_path":"controller/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"78960096","text":"#!/usr/bin/python\n\"\"\"\nThis script will aid in running the examples and \"integration\" tests included\nwith furious.\n\nTo run:\n\n python example/runner.py workflow\n\nThis will hit the /workflow url, causing the \"workflow\" example to run.\n\"\"\"\n\nimport argparse\nimport sys\n\n\ndef args():\n \"\"\"Add and parse the arguments for the script.\n\n url: the url of the example to run\n gae-sdk-path: this allows a user to point the script to their GAE SDK\n if it's not in /usr/local/google_appengine.\n \"\"\"\n parser = argparse.ArgumentParser(description='Run the Furious Examples.')\n\n parser.add_argument('--gae-sdk-path', metavar='S', dest=\"gae_lib_path\",\n default=\"/usr/local/google_appengine\",\n help='path to the GAE SDK')\n\n parser.add_argument('url', metavar='U', default=\"\", nargs=1,\n help=\"the endpoint to run\")\n\n return parser.parse_args()\n\n\ndef setup(options):\n \"\"\"Grabs the gae_lib_path from the options and inserts it into the first\n index of the sys.path. Then calls GAE's fix_sys_path to get all the proper\n GAE paths included.\n\n :param options:\n \"\"\"\n sys.path.insert(0, options.gae_lib_path)\n\n from dev_appserver import fix_sys_path\n fix_sys_path()\n\n\ndef run(options):\n \"\"\"Run the passed in url of the example using GAE's rpc runner.\n\n Uses appengine_rpc.HttpRpcServer to send a request to the url passed in\n via the options.\n\n :param options:\n \"\"\"\n from google.appengine.tools import appengine_rpc\n from google.appengine.tools import appcfg\n\n source = 'furious'\n\n # use the same user agent that GAE uses in appcfg\n user_agent = appcfg.GetUserAgent()\n\n # Since we're only using the dev server for now we can hard code these\n # values. This will need to change and accept these values as variables\n # when this is wired up to hit appspots.\n server = appengine_rpc.HttpRpcServer(\n 'localhost:8080', lambda: ('test@example.com', 'password'), user_agent,\n source, secure=False)\n\n # if no url is passed in just use the top level.\n url = \"/\"\n if options.url:\n url += options.url[0]\n\n # use the dev server authentication for now.\n server._DevAppServerAuthenticate()\n\n # send a simple GET request to the url\n server.Send(url, content_type=\"text/html; charset=utf-8\",\n payload=None)\n\n\ndef main():\n \"\"\"Send a request to the url passed in via the options using GAE's rpc\n server.\n \"\"\"\n options = args()\n\n setup(options)\n\n run(options)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"example/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"318076378","text":"SERVER_ICON = u'\\uf0ae'\n# This is a nucleus specific development version with pretty icons and a much shoortened dev hostname\ndef add_hostname_nucleus_segment(powerline):\n import os\n if powerline.args.colorize_hostname:\n from lib.color_compliment import stringToHashToColorAndOpposite\n from lib.colortrans import rgb2short\n # this is not the recommended way to get hostname but it is faster and this is a very specific case\n hostname = os.getenv('HOST').upper()\n if hostname.startswith(\"DEV-DUTCH-\"):\n host_prompt = ' %s %s' % (SERVER_ICON, hostname[10:12])\n else:\n host_prompt = ' %s %s' % (SERVER_ICON, '%m')\n FG, BG = stringToHashToColorAndOpposite(hostname)\n FG, BG = (rgb2short(*color) for color in [FG, BG])\n\n powerline.append(host_prompt, FG, BG)\n else:\n # this is not the recommended way to get hostname but it is faster and this is a very specific case\n hostname = os.getenv('HOST').upper()\n if hostname.startswith(\"DEV-DUTCH-\"):\n host_prompt = ' %s %s' % (SERVER_ICON, hostname[10:12])\n BG = Color.HOSTNAME_BG\n else:\n host_prompt = ' %s %s' % (SERVER_ICON, '%m')\n BG = Color.USERNAME_ROOT_BG\n\n powerline.append(host_prompt, Color.HOSTNAME_FG, BG)","sub_path":"segments/hostname_nucleus.py","file_name":"hostname_nucleus.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"207994746","text":"# Do not have to count digits for every term in the sequence.\r\n# store each two terms in the sequence and if their sum exceeds a factor of 10, then increment\r\n# number of digits by 1\r\ndigit_lim = 1000\r\ndigit_number = 1\r\na = 1\r\nb = 1\r\nindex = 2 # start from second term F_2\r\n\r\nwhile digit_number < digit_lim:\r\n temp = a + b\r\n a = b\r\n b = temp\r\n index += 1\r\n if b > 10**digit_number:\r\n digit_number += 1\r\n\r\nprint(index)\r\n\r\n\r\n","sub_path":"problem_25.py","file_name":"problem_25.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"592832599","text":"#!/usr/bin/env python3\nimport sys\nfrom random import randrange\nfrom random import sample\n\n\nclass FileWordReader:\n def read_words(self, filename):\n with open(filename, 'r') as f:\n lines = f.read().splitlines()\n\n words = set()\n for line in lines:\n line_words = line.split(',')\n words.update(line_words)\n\n return words\n\n\nclass EssayMonkey:\n \"\"\"A class that writes essays of variable sentence and paragraph count. Pool of words comes\n from external files\"\"\"\n def __init__(self, paragraph_count, sentence_count, *files, word_reader=FileWordReader()):\n if not isinstance(paragraph_count, int):\n raise ValueError(\"paragraph_count input '{}' is not an integer\".format(paragraph_count))\n\n if not isinstance(sentence_count, int):\n raise ValueError(\"sentence_count input '{}' is not an integer\".format(sentence_count))\n\n if len(files) < 1:\n raise ValueError(\"No word files were provided\")\n\n self._paragraph_count = paragraph_count\n self._sentence_count = sentence_count\n\n words = set()\n for file in files:\n words.update(word_reader.read_words(file))\n\n self._words = words\n\n def write_essay(self):\n \"\"\"Produces an essay based on the current paragraph and sentence counts, using the words\n provided when the object was created\"\"\"\n words_range = len(self._words) + 1\n\n paragraphs = []\n for _ in range(self._paragraph_count):\n sentences = []\n for _ in range(self._sentence_count):\n sentence_length = randrange(4, 33)\n words = [sample(self._words, 1)[0] for _ in range(sentence_length)]\n sentence = ' '.join(words)\n cap_sentence = \"{}{}\".format(sentence[0].upper(), sentence[1:])\n sentences.append(cap_sentence)\n\n paragraph = \"{}{}\".format(\". \".join(sentences), '.')\n paragraphs.append(paragraph)\n\n essay = \"{}{}\".format(\"\\t\", \"\\n\\t\".join(paragraphs))\n\n return essay\n\n def set_paragraph_count(self, paragraph_count):\n self._paragraph_count = paragraph_count\n\n def set_sentence_count(self, sentence_count):\n self._sentence_count = sentence_count\n\n\ndef main(paragraph_count, sentence_count, *files):\n monkey = EssayMonkey(paragraph_count, sentence_count, *files)\n result = monkey.write_essay()\n print(result)\n\n\nif __name__ == '__main__':\n file_names = sys.argv[3:len(sys.argv) + 1]\n file_name_tuple = tuple(file_names)\n main(int(sys.argv[1]), int(sys.argv[2]), *file_name_tuple)\n","sub_path":"solutions/essay_monkey.py","file_name":"essay_monkey.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"275767761","text":"#!/usr/bin/python\nimport RPi.GPIO as GPIO\nimport platform\nimport sys\nimport datetime\nimport json\nimport platform\nimport random\nimport pymongo\nimport socket\nimport time\nimport picamera\nimport time\nfrom pymongo import MongoClient\n\ntime.sleep(60) # 1 minute to boot up\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(7, GPIO.IN) #Read output from PIR motion sensor\nGPIO.setup(11, GPIO.OUT) #LED output pin\n\ncolors = [0xFF00, 0x00FF]\npins = {'pin_R':10, 'pin_G':11} # pins is a dict\n\nGPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location\nfor i in pins:\n\tGPIO.setup(pins[i], GPIO.OUT) # Set pins' mode is output\n\n\np_R = GPIO.PWM(pins['pin_R'], 2000) # set Frequece to 2KHz\np_G = GPIO.PWM(pins['pin_G'], 2000)\n\np_R.start(0) # Initial duty Cycle = 0(leds off)\np_G.start(0)\n\ndef map(x, in_min, in_max, out_min, out_max):\n\treturn (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min\n\n\ndef setColor(col):\n\tR_val = (col & 0xFF00) >> 8\n\tG_val = (col & 0x00FF) >> 0\n\t\n\tR_val = map(R_val, 0, 255, 0, 100)\n\tG_val = map(G_val, 0, 255, 0, 100)\n\t\n\tp_R.ChangeDutyCycle(R_val) # Change duty cycle\n\tp_G.ChangeDutyCycle(G_val)\n\ntry:\n while True:\n #k=0\n i=GPIO.input(7)\n if i==0: #When output from motion sensor is LOW\n print( \"No intruders\",i)\n setColor(0x00FF)\n GPIO.output(11, 1) #Turn ON LED - GREEN - all good\n elif i==1: \n #k=1 #When output from motion sensor is HIGH\n print (\"Intruder detected\",i)\n setColor(0xFF00)\n GPIO.output(11, 1) #Turn ON LED - RED - intruder\n #from picamera import PiCamera from time import sleep \n camera = picamera.PiCamera() \n #camera.start_preview() \n picpath = '/home/pi/Desktop/'+str(datetime.datetime.now())+'.jpg'\n camera.capture(picpath) \n time.sleep(2)\n #camera.stop_preview() \n camera.close() \n time.sleep(3) # wait for 10 seconds before trying again on \nexcept KeyboardInterrupt:\n p_R.stop()\n p_G.stop()\n for i in pins:\n GPIO.output(pins[i], GPIO.HIGH) # Turn off all leds\n GPIO.cleanup()\n","sub_path":"pir2.py","file_name":"pir2.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"627700008","text":"import os\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom xgboost import XGBRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score, median_absolute_error\n\nPKG_DIR = os.path.dirname(os.path.abspath(__file__))\nDATA_DIR = os.path.join(PKG_DIR, \"data\")\nTRAIN_FILEPATH = os.path.join(DATA_DIR, \"train.csv\")\nTEST_FILEPATH = os.path.join(DATA_DIR, \"test.csv\")\nSUBMISSION_FILEPATH = os.path.join(DATA_DIR, \"submission.csv\")\n\ntrain_df = pd.read_csv(TRAIN_FILEPATH)\ntrain_df[\"AgeWhenSold\"] = train_df.YrSold - train_df.YearBuilt\n\nfeatures = [\"LotArea\", \"OverallCond\", \"OverallQual\", \"GarageCars\", \"GrLivArea\", \"FullBath\", \"HalfBath\", \"AgeWhenSold\"]\ntarget = [\"SalePrice\"]\n\nmodel_df = train_df[features + target]\n\nx_train, x_test, y_train, y_test = train_test_split(model_df[features], model_df[target])\nprint(model_df.corr())\n\nmodel = XGBRegressor(n_estimators=100, n_jobs=3)\nmodel.fit(x_train, y_train)\ny_pred = model.predict(x_test)\n\nr2 = r2_score(y_test, y_pred)\nerr = median_absolute_error(y_test, y_pred)\n\nprint(r2, err)\n\nplt.figure()\nplt.scatter([y[0] for y in y_test.values], [y for y in y_pred])\nplt.plot([x for x in range(400000)], [y for y in range(400000)], \"r\")\nplt.xlabel(\"True value for sales price\")\nplt.ylabel(\"Predicted value for sales price\")\n\ntest_df = pd.read_csv(TEST_FILEPATH)\ntest_df[\"AgeWhenSold\"] = test_df.YrSold - test_df.YearBuilt\ntest_df = test_df[[\"Id\"] + features]\ntest_df = test_df.fillna(0)\npred = model.predict(test_df[features])\n\npred = [p for p in pred]\nids = [id_ for id_ in test_df.Id]\ndata = [(id_, pred) for id_, pred in zip(ids, pred)]\n\nsubmission_df = pd.DataFrame(data=data, columns=[\"Id\", \"SalePrice\"])\nsubmission_df.to_csv(SUBMISSION_FILEPATH, index=False)\n\nplt.show()\n","sub_path":"house_prices/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"477388735","text":"#!/usr/bin/env python3\n# 2019-11, Bruno Grossniklaus, https://github.com/it-gro\n\nimport pymysql as mariadb\n\nmariadb_connection = mariadb.connect(\n host='localhost', database='BenBrumm',\n user='myAdmin', password='myAdmin')\ncursor = mariadb_connection.cursor()\n\nprint(\"1)\", \"~\" * 50)\nsql = (\n \"SELECT first_name, last_name \"\n \"FROM employee \"\n \"WHERE first_name LIKE %s \"\n)\n\nprint(sql)\n\nfirst_name_filter = 'Ba%'\ncursor.execute(sql, (first_name_filter, ))\n\nfor row in cursor:\n print(row)\n\nprint(\"2)\", \"~\" * 50)\nfirst_name_filter = 'Ch%'\ncursor.execute(sql, (first_name_filter, ))\n\nfor (f, l) in cursor:\n print(f, l, sep=\"/\")\n","sub_path":"SW_02_09/Pycharm/SW_02_09/demo/mariadb/pymysql/100_pymysql_cursor_benbrumm.py","file_name":"100_pymysql_cursor_benbrumm.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"527831172","text":"# coding=utf-8\n'''\nКласс автоматически формирующий модели\n@TODO: при создании тестов на лету лучше добавить полное логгирование\n'''\nfrom django.test import TestCase\nfrom datetime import date\nimport models\nfrom forms import forms_classes\nfrom yaml_config import TabelsConfig\n# структура таблиц\nstructure = TabelsConfig.get_config()\n#модели таблиц\nmodels_classes = models.models_classes\n\ntest_classes = {}\n# верные и неверные тестовые примеры\ncorrect_test_data = {'char':['', u'Иван', u'Иван да марья', u'Ivan'],\n 'int':[0, 1, -5, 169],\n 'date':[date(2012,2,2), date(2015,3,12)]}\n\ncorrect_form_data = {'char': [u'Иван', u'1234 fwfwe ', u'ffefef!ауцацуа'],\n 'int': [0, 1, -5, 169],\n 'date':['01.02.2001','31.01.2014', '29.02.2012']}\n\n\nincorrect_form_data = {'char':[u'qweifhvowueigfbwvuegfuwgevfuqwgefuyqgwveufyguiqwegfvgweuigfvuiwgefyqvwiuef'],\n 'int':[2.34, 'uobgfwehbfh'],\n 'date':['123', 'fwfwef', '01.13.2001', '32.02.2004', '30.02.2009', '29.02.2013']}\n\n# эти функции возвращают тест функции, каждая из которых проверяет свое значение\ndef incorrect_form_test(field_name, value):\n def do_test(self):\n form = self.form_class({field_name:value})\n self.assertFalse(form.is_valid())\n return do_test\n\ndef correct_form_test(field_name, value):\n def do_test(self):\n form = self.form_class({field_name:value})\n self.assertTrue(form.is_valid())\n return do_test\n\ndef correct_data_test(field_name, obj_id, value):\n def do_test(self):\n test_obj = self.model_class.objects.get(pk=obj_id)\n print(getattr(test_obj, field_name),value)\n self.assertEqual(getattr(test_obj, field_name), value)\n return do_test\n\n# общая для всех инициализация\n# создает для тестирования моделей по одному объекту на каддый случай\ndef setUp(self):\n for counter, field in enumerate(self.data_inf):\n self.model_class(**{'id':field['obj_id'], field['field_name']:field['value']}).save()\n\n# для всех возможных моделей и их форм и всех возможных их полей переберем все тестовые случаи\nfor model_name, model_class in models_classes.iteritems():\n obj_id = 1\n correct_data_test_name = '%s_models_correct_data' % model_name\n correct_data_attrs = {'setUp':setUp, 'model_class':model_class, '__module__':'YAML_data.test'}\n correct_model_data_inf = []\n \n correct_form_test_name = '%s_models_correct_form' % model_name\n correct_form_attrs = {'form_class':forms_classes[model_name], '__module__':'YAML_data.test'}\n \n incorrect_form_test_name = '%s_models_incorrect_form' % model_name\n incorrect_form_attrs = {'form_class':forms_classes[model_name], '__module__':'YAML_data.test'}\n \n for counter, field in enumerate(structure[model_name]['fields']):\n val_count = 1\n for val in correct_test_data[field['type']]:\n # каждый элемент содержит название поля, его значение и id объекта в которое это будет записано\n # потом этот объект будет прочитан и нужно его поле будет сверено с эталоном\n correct_model_data_inf.append({'field_name': field['id'], 'value': val, 'obj_id':obj_id})\n correct_data_attrs['test_%s_%d'% (field['id'], val_count)] = correct_data_test(field['id'], obj_id, val)\n obj_id += 1\n val_count +=1\n \n val_count = 1\n for val in correct_form_data[field['type']]:\n val_count = 1\n #форме модели будут поочередно предъявлены словари с одним заполненным полем\n # и будет проверен результат валидации\n correct_form_attrs['test_%s_%d'% (field['id'], val_count)] = correct_form_test(field['id'], val)\n val_count +=1\n \n val_count = 1\n for val in incorrect_form_data[field['type']]:\n val_count = 1\n #форме модели будут поочередно предъявлены словари с одним заполненным полем\n # и будет проверен результат валидации\n incorrect_form_attrs['test_%s_%d'% (field['id'], val_count)] = incorrect_form_test(field['id'], val)\n val_count +=1\n\n correct_data_attrs['data_inf'] = correct_model_data_inf\n correct_form_attrs['data_inf'] = correct_model_data_inf\n incorrect_form_attrs['data_inf'] = correct_model_data_inf\n\n\n test_classes[correct_data_test_name] = type(correct_data_test_name, (TestCase, ), correct_data_attrs)\n test_classes[correct_form_test_name] = type(correct_form_test_name, (TestCase, ), correct_form_attrs)\n test_classes[incorrect_form_test_name] = type(incorrect_form_test_name, (TestCase, ), incorrect_form_attrs)\n\n globals()[correct_data_test_name] = test_classes[correct_data_test_name]\n globals()[correct_form_test_name] = test_classes[correct_form_test_name]\n globals()[incorrect_form_test_name] = test_classes[incorrect_form_test_name]","sub_path":"YAML_data/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"553827382","text":"import pygame\nimport requests\n\n\ndef HowTheOblast(req):\n title = 'https://geocode-maps.yandex.ru/1.x/'\n geocode = 'geocode=' + req\n apikey = 'apikey=' + '40d1649f-0493-4b70-98ba-98533de7710b'\n format = 'format=' + 'json'\n a = '&'.join([geocode, apikey, format])\n b = '?'.join([title, a])\n result = requests.get(b)\n js = result.json()\n oblast = js['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']\n ll = 'll=' + oblast\n spn = 'spn=0.016457,0.00619'\n return oblast\n\n\nprint(HowTheOblast('Австралия'))","sub_path":"we_need_pygame.py","file_name":"we_need_pygame.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"330060971","text":"from unittest.mock import patch\n\nimport pytest\n\nfrom rocketpy import Environment, SolidMotor, Rocket, Flight\n\n\n@patch(\"matplotlib.pyplot.show\")\ndef test_motor(mock_show):\n example_motor = SolidMotor(\n thrustSource=\"data/motors/Cesaroni_M1670.eng\",\n burnOut=3.9,\n grainNumber=5,\n grainSeparation=5 / 1000,\n grainDensity=1815,\n grainOuterRadius=33 / 1000,\n grainInitialInnerRadius=15 / 1000,\n grainInitialHeight=120 / 1000,\n nozzleRadius=33 / 1000,\n throatRadius=11 / 1000,\n interpolationMethod=\"linear\",\n )\n\n assert example_motor.allInfo() == None\n","sub_path":"tests/test_solidmotor.py","file_name":"test_solidmotor.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"432995575","text":"# coding=utf-8\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport requests\nimport re\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport calendar\nimport sys\nimport time\n\n\ndef add_months(dt,months):\n month = dt.month - 1 + months\n year = dt.year + int(month / 12)\n month = month % 12 + 1\n day = min(dt.day, calendar.monthrange(year, month)[1])\n return dt.replace(year=year, month=month, day=day)\n\ntoday = datetime.now().date()\ntoday=today.replace(year=2013,month=12,day=1)\nprint('start month'+str(today))\n\ndriver=webdriver.Chrome()\nwith open('WenZhou_air_.csv', 'w+', encoding='utf-8') as f:\n detail=today.strftime('%Y%m')\n while detail<='201902':\n driver.get(\n 'https://www.aqistudy.cn/historydata/daydata.php?city=温州&month='+detail)\n time.sleep(3)\n elements = driver.find_elements_by_class_name(\"table\")\n ele=elements[0].text.split('\\n')\n print(ele[1])\n month_sum=[]\n s=[]\n for n, i in enumerate(ele):\n if n != 0:\n s.append(i)\n # s.append(re.sub('[\\t\\n\\r]','',item.string))\n if n%3==0:\n s+='\\n'\n month_sum.append(' '.join(s))\n s=[]\n # month_sum=month_sum[::-1]\n for m in month_sum:\n f.writelines(m)\n \n today=add_months(today,1)\n detail=today.strftime('%Y%m')\n print(detail)\n\n","sub_path":"scrach_air.py","file_name":"scrach_air.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"610681034","text":"import os\nimport time\nfrom slackclient import SlackClient\nimport bot\n\n# starterbot's ID as an environment variable\nBOT_ID = os.environ.get(\"BOT_ID\")\n\n# instantiate Slack & Twilio clients\nslack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))\n\nif __name__ == \"__main__\":\n READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose\n if slack_client.rtm_connect():\n print(\"ayerslab_bot connected and running!\")\n ayersbot = bot.brain.Brain(BOT_ID, slack_client)\n while True:\n command, channel = ayersbot.listen(slack_client.rtm_read())\n if command and channel:\n ayersbot.process(command, channel)\n time.sleep(READ_WEBSOCKET_DELAY)\n else:\n print(\"Connection failed. Invalid Slack token or bot ID?\")\n","sub_path":"live.py","file_name":"live.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"329334683","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom knn import KNN\nknn = KNN()\n\nknn.Load_Dataset('iris.csv')\n\nknn.data = np.array(knn.data)\nknn.target = np.array(knn.target)\n# First feature\n#x = knn.data[:,0:1]\n# Second feature\n#y = knn.data[:,1:2]\n\n# Reshape the values\ntargetnum = knn.target\nreshape = np.reshape(targetnum, (150,1))\n\n#print(np.shape(x))\n#print(np.shape(y))\n\ntrainX = knn.data[::2,1:3]\ntrainy = knn.target[::2]\n\nx = trainX[:,0:1]\ny = trainX[:,1:2]\n\ntrainy = np.reshape(trainy, (75,1))\n# print(np.shape(x))\n# print(np.shape(y))\n# print(np.shape(trainy))\n\ntestX = knn.data[1::2,1:3]\ntesty = knn.target[1::2]\n\nxT = testX[:,0:1]\nyT = testX[:,1:2]\n\ntesty = np.reshape(testy, (75,1))\n\n# 5, 7,9 give 98.66667%\nknn.Use_K_Of(15)\nknn.Fit(trainX,trainy)\nfor i in range(0,75):\n actualClass = testy[i]\n prediction = knn.Predict(testX[i,0:2])\n #print(actualClass, prediction)\n\n\n\n\ncolors = np.zeros((3,3), dtype='f')\ncolors[0,:] = [1,0.5,0.5]\ncolors[1,:] = [0.5,1,0.5]\ncolors[2,:] = [0.5,0.5,1]\n\nplt.figure()\n\n[numItems,numFeatures] = knn.data.shape\nfor i in range(0,numItems/2):\n itemClass = int(trainy[i])\n currColor = colors[itemClass,:]\n plt.scatter(trainX[i, 0], trainX[i, 1], edgecolor='black', facecolor=currColor, s=50, lw=2)\n\n\nnumCorr = 0\nfor i in range(0, numItems/2):\n itemClass = int(testy[i])\n currColor = colors[itemClass, :]\n prediction = int(knn.Predict(testX[i, :]))\n if prediction == itemClass:\n numCorr += 1\n edgeColor = colors[prediction,:]\n plt.scatter(testX[i, 0], testX[i, 1], edgecolor=edgeColor, facecolor=currColor, s=50, lw=2)\nprint(numCorr)\n\ntestItems = float(len(testX))\npct = float(numCorr/testItems) * 100\nprint(str(pct)+\"%\")\n\n\n# plot original data\n#plt.scatter(x, y, c=trainy)\n\n# plot new data\n#plt.scatter(xT, yT, c=testy)\n\nplt.show()\n","sub_path":"Predict.py","file_name":"Predict.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"412976440","text":"# This script replaces the rates for crimes against women\n# using population of women. This is ONLY for the year 2011\n\nimport csv\nfrom os.path import join\n\nDATADIR = '../static/data'\npop_file = 'female-2011.csv'\ndata_file = 'data-v5.csv'\nyear = '2011'\nf_crimes = ['Cruelty by husband or his relatives', 'Custodial rape', 'Dowry deaths', 'Kidnapping & abduction of women and girls', 'Molestation', 'Other rape', 'Rape', 'Sexual harassment']\n\n# Read in female populations\nwith open(join(DATADIR, pop_file), 'r') as pop:\n cp = list(csv.DictReader(pop))\n\n# Make a lookup dict of female pops in each city\ncity_pop = {}\nfor c in cp:\n if not city_pop.get(c['city']):\n city_pop[c['city']] = int(c['f_pop'])\n\n# Read in the data file\nwith open(join(DATADIR, data_file), 'r') as data:\n datarows = list(csv.DictReader(data))\n # datarows = [d for d in datarows if d['year'] == year]\n\n# Change rate of female crimes in 2010 in each city's row\nfor row in datarows:\n if row['year'] == year and row['crime_name'] in f_crimes:\n temp = float(100000 * int(row['incidences']) / int(city_pop[row['city']]))\n row['rate'] = round(temp, 1)\n\n# Write a new csv\nheaders = ['city','year','crime_name','incidences','rate']\n\nwith open(join(DATADIR,'data-v6.csv'), 'w') as f:\n writer = csv.DictWriter(f, headers)\n writer.writeheader()\n writer.writerows(datarows)","sub_path":"scripts/female-2011.py","file_name":"female-2011.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"461133533","text":"#!/usr/bin/env python3\n\nimport argparse\nimport itertools\nimport pandas as pd\nimport pickle\n\n\ndef heatmap_from_dataframe(dataframe, filename='heatmap.png'):\n import seaborn\n heatmap = seaborn.heatmap(dataframe, center=0)\n figure = heatmap.get_figure()\n figure.savefig(filename, dpi=300)\n\n\ndef fitness_dict_from_text_file(fitness_text_file):\n \"\"\"parses text file of one tuple and one float per line into a dictionary\n\n Args:\n fitness_text_file: txt file with each line formatted as follows\n (integer, 'Capital single character amino acid'),fitness_value\n\n Returns:\n A dict with keys of tuples (position, amino acid char) and values of variant fitness floats\n\n Raises:\n\n \"\"\"\n fitness_dict = {}\n with open(fitness_text_file, 'r') as f:\n for line in f:\n position, amino_acid, fitness = line.rstrip().split(',')\n position = int(position.split('(')[-1])\n amino_acid = amino_acid.split(\"'\")[1]\n fitness = float(fitness)\n fitness_dict[(position, amino_acid)] = fitness\n return fitness_dict\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"\"\"script which returns some preliminary stats on mapping randomized \n barcodes to expected library sequences\"\"\")\n parser.add_argument('-r', '--position_range',\n help='range of positions to be plotted in heatmap. first and last position separated by dash')\n parser.add_argument('-n', '--name', help='name of heatmap image')\n\n required = parser.add_argument_group('required')\n required.add_argument(\"-p\", \"--pickle_file\", required=True,\n help=\"input pickle dictionary with keys as tuple of postion, amino acid and values \"\n \"as fitness floats\")\n wt_seq = 'MDVFMKGLSKAKEGVVAAAEKTKQGVAEAAGKTKEGVLYVGSKTKEGVVHGVATVAEKTKEQVTNVGGAVV' \\\n 'TGVTAVAQKTVEGAGSIAAATGFVKKDQLGKNEEGAPQEGILEDMPVDPDNEAYEMPSEEGYQDYEPEA'\n args = parser.parse_args()\n if args.pickle_file.endswith('.pkl'):\n with open(args.pickle_file, 'rb') as f:\n variant_fitness_dict = pickle.load(f)\n elif args.pickle_file.endswith('.txt'):\n variant_fitness_dict = fitness_dict_from_text_file(args.pickle_file)\n else:\n raise IOError('Please give fitness dictionary as a pickle file')\n\n if args.position_range:\n first_position, last_position = map(int, args.position_range.split('-'))\n else:\n first_position = 1\n last_position = 140\n position_range = range(first_position, last_position + 1)\n fitness_df = pd.DataFrame(0, index=position_range, columns=list('AVILMFYWSTNQHKRDECGP'))\n\n # Using Robert's fitness dictionary, which does not normalize to wt fitness\n wt_fitness = variant_fitness_dict[(0, 'WT')]\n for position, amino_acid in itertools.product(position_range, list('AVILMFYWSTNQHKRDECGP')):\n if (position, amino_acid) in variant_fitness_dict.keys():\n fitness = variant_fitness_dict[(position, amino_acid)] - wt_fitness\n elif amino_acid != wt_seq[position - 1]:\n fitness = float('NaN')\n else:\n fitness = 0\n fitness_df.loc[position, amino_acid] = fitness\n\n heatmap_from_dataframe(fitness_df.T, args.name)\n","sub_path":"fitness_heatmap.py","file_name":"fitness_heatmap.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"369496649","text":"import math\nimport true_dip_with_vertical_exaggeration as TD\nimport Df_Te_alpha as DfTe\ndef main():\n Depth = float(input(\"enter the depth (Ws(X0)) in [km]: \"))\n dip = TD.true_dip()\n alpha = 2 * (Depth / math.tan(math.radians(dip)))\n alpha = alpha * 1000\n \n kappa = DfTe.Df_Te()\n Te = (alpha / kappa)**(4.0/3.0) #[m]\n print (\"Depth is:\", Depth, \"[m]\", \"dip angle is:\", dip, \"[m]\", \"and Te_ratio is:\", Te, \"[m]\", \"alpha_ratio is \", alpha, \"[m]\")\n print (\"__________________\")\n print (\"Results from ratio estimation\")\n triangle_x = float(input(\"enter the triangle x in [km]: \")) \n v1 = 3.5; v2 = 5.; # V1 is the sediment velocity and V2 is the lava velocity \n t_s = float(input(\"enter the sediment thickness in TWTT in sec: \")) \n t_o = float(input(\"enter the T_o in TWTT in sec: \"))\n t_1 = float(input(\"enter the T_1 in TWTT in sec: \")) \n \n alpha_ratio = (ts * 2. / (t_1 - t_o)) * (v1 / v2) * triangle_x + ((t_o + t_1 - 2*t_s)* triangle_x / 2.) / ((t_1 - t_o) / 2)\n \n Te_ratio = (alpha_ratio / kappa)**(4.0/3.0) #[m]\n print (alpha_ratio, Te_ratio) \nmain()\n","sub_path":"JGR_SDR_2019/1Codes/GMT_SDR/Te_calc_tools/TWTT_estimation.py","file_name":"TWTT_estimation.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"341047262","text":"\"\"\"Azure Blob Storage handling\n\"\"\"\n\n__author__ = \"Sebastian Kurscheid\"\n__copyright__ = \"Copyright 2022, Sebastian Kurscheid\"\n__email__ = \"sebastian.kurscheid@anu.edu.au\"\n__license__ = \"MIT\"\n\n# built-ins\nimport os\nimport re\n\n# snakemake specific\n# /\n\n# module specific\nfrom snakemake.exceptions import WorkflowError, AzureFileException\nfrom snakemake.remote import (\n AbstractRemoteProvider,\n AbstractRemoteRetryObject,\n)\n\n# service provider support\ntry:\n from azure.storage.blob import BlobServiceClient\n import azure.core.exceptions\nexcept ImportError as e:\n raise WorkflowError(\n \"The Python 3 package 'azure-storage-blob' \"\n \"need to be installed to use Azure Storage remote() file functionality. %s\"\n % e.msg\n )\n\n\nclass RemoteProvider(AbstractRemoteProvider):\n supports_default = True\n\n def __init__(\n self, *args, keep_local=False, stay_on_remote=False, is_default=False, **kwargs\n ):\n super(RemoteProvider, self).__init__(\n *args,\n keep_local=keep_local,\n stay_on_remote=stay_on_remote,\n is_default=is_default,\n **kwargs\n )\n\n self._as = AzureStorageHelper(*args, **kwargs)\n\n def remote_interface(self):\n return self._as\n\n @property\n def default_protocol(self):\n \"\"\"The protocol that is prepended to the path when no protocol is specified.\"\"\"\n return \"ab://\"\n\n @property\n def available_protocols(self):\n \"\"\"List of valid protocols for this remote provider.\"\"\"\n return [\"ab://\"]\n\n\nclass RemoteObject(AbstractRemoteRetryObject):\n def __init__(self, *args, keep_local=False, provider=None, **kwargs):\n super(RemoteObject, self).__init__(\n *args, keep_local=keep_local, provider=provider, **kwargs\n )\n\n if provider:\n self._as = provider.remote_interface()\n else:\n self._as = AzureStorageHelper(*args, **kwargs)\n\n # === Implementations of abstract class members ===\n def exists(self):\n if self._matched_as_path:\n return self._as.exists_in_container(self.container_name, self.blob_name)\n raise AzureFileException(\n \"The file cannot be parsed as an Azure Blob path in form 'container/blob': %s\"\n % self.local_file()\n )\n\n def mtime(self):\n if self.exists():\n # b = self.blob_service_client.get_blob_client(self.container_name, self.blob_name)\n # return b.get_blob_properties().last_modified\n t = self._as.blob_last_modified(self.container_name, self.blob_name)\n return t\n raise AzureFileException(\n \"The file does not seem to exist remotely: %s\" % self.local_file()\n )\n\n def size(self):\n if self.exists():\n return self._as.blob_size(self.container_name, self.blob_name)\n return self._iofile.size_local\n\n def _download(self):\n if self.exists():\n os.makedirs(os.path.dirname(self.local_file()), exist_ok=True)\n self._as.download_from_azure_storage(\n self.container_name, self.blob_name, destination_path=self.local_file()\n )\n os.sync()\n return self.local_file()\n return None\n\n def _upload(self):\n self._as.upload_to_azure_storage(\n container_name=self.container_name,\n blob_name=self.blob_name,\n file_path=self.local_file(),\n )\n\n @property\n def list(self):\n return self._as.list_blobs(self.container_name)\n\n # # === Related methods ===\n @property\n def _matched_as_path(self):\n return re.search(\n \"(?P[^/]*)/(?P.*)\", self.local_file()\n )\n\n def as_create_stub(self):\n if self._matched_as_path:\n if not self.exists:\n self._as.download_from_azure_storage(\n self.container_name,\n self.blob_name,\n self.file,\n create_stub_only=True,\n )\n else:\n raise AzureFileException(\n \"The file to be downloaded cannot be parsed as an Azure Storage path in form 'container/blob': %s\"\n % self.local_file()\n )\n\n @property\n def container_name(self):\n \"return container name component of the path\"\n if len(self._matched_as_path.groups()) == 2:\n return self._matched_as_path.group(\"container_name\")\n return None\n\n @property\n def name(self):\n return self.blob_name\n\n @property\n def blob_name(self):\n \"return the blob name component of the path\"\n if len(self._matched_as_path.groups()) == 2:\n return self._matched_as_path.group(\"blob_name\")\n return None\n\n\n# Actual Azure specific functions, adapted from S3.py\n\n\nclass AzureStorageHelper(object):\n def __init__(self, *args, **kwargs):\n if \"stay_on_remote\" in kwargs:\n del kwargs[\"stay_on_remote\"]\n\n # if not handed down explicitly, try to read credentials from\n # environment variables.\n for csavar, envvar in [\n (\"account_url\", \"AZ_BLOB_ACCOUNT_URL\"),\n (\"credential\", \"AZ_BLOB_CREDENTIAL\"),\n ]:\n if csavar not in kwargs and envvar in os.environ:\n kwargs[csavar] = os.environ.get(envvar)\n assert (\n \"account_url\" in kwargs\n ), \"Missing AZ_BLOB_ACCOUNT_URL env var (and possibly AZ_BLOB_CREDENTIAL)\"\n # remove leading '?' from SAS if needed\n # if kwargs.get(\"sas_token\", \"\").startswith(\"?\"):\n # kwargs[\"sas_token\"] = kwargs[\"sas_token\"][1:]\n if kwargs[\"account_url\"] == \"\" or kwargs[\"account_url\"] is None:\n raise ValueError(\"Blob Account URL is None or empty string\")\n\n if not self.is_valid_azure_storage_account_url(kwargs[\"account_url\"]):\n raise ValueError(\n \"Blob Account URL does not match azure storage blob account url pattern.\"\n )\n\n # by right only account_key or sas_token should be set, but we let\n # BlobServiceClient deal with the ambiguity\n self.blob_service_client = BlobServiceClient(**kwargs)\n\n @staticmethod\n def is_valid_azure_storage_account_url(blob_account_url: str) -> bool:\n \"\"\"\n Validates if the blob account url is a valid Azure Storage Account URL.\n\n Args:\n blob_account_url (str): The name of the environment variable.\n\n Returns:\n bool: True if the environment variable is a valid Azure Storage Account URL, False otherwise.\n \"\"\"\n url_pattern = re.compile(\n r\"^https:\\/\\/[a-z0-9]+(\\.[a-z0-9]+)*\\.blob\\.core\\.windows\\.net\\/?(.+)?$\"\n )\n\n return bool(url_pattern.match(blob_account_url))\n\n def container_exists(self, container_name):\n return any(\n True for _ in self.blob_service_client.list_containers(container_name)\n )\n\n def upload_to_azure_storage(\n self,\n container_name,\n file_path,\n blob_name=None,\n use_relative_path_for_blob_name=True,\n relative_start_dir=None,\n extra_args=None,\n ):\n \"\"\"Upload a file to Azure Storage\n This function uploads a file to an Azure Storage Container as a blob.\n Args:\n container_name: the name of the Azure container to use\n file_path: The path to the file to upload.\n blob_name: The name to set for the blob on Azure. If not specified, this will default to the\n name of the file.\n Returns: The blob_name of the file on Azure if written, None otherwise\n \"\"\"\n file_path = os.path.realpath(os.path.expanduser(file_path))\n\n assert container_name, \"container_name must be specified\"\n assert os.path.exists(file_path), (\n \"The file path specified does not exist: %s\" % file_path\n )\n assert os.path.isfile(file_path), (\n \"The file path specified does not appear to be a file: %s\" % file_path\n )\n\n container_client = self.blob_service_client.get_container_client(container_name)\n\n # create container if it doesn't exist.\n # for sas token created in the level of container, the exists method will fail with error code 403.\n # therefore the exception is passed to cover this type of sas tokens.\n\n try:\n if not container_client.exists():\n container_client.create_container()\n except Exception as e:\n if e.status_code == 403:\n pass\n\n if not blob_name:\n if use_relative_path_for_blob_name:\n if relative_start_dir:\n path_blob_name = os.path.relpath(file_path, relative_start_dir)\n else:\n path_blob_name = os.path.relpath(file_path)\n else:\n path_blob_name = os.path.basename(file_path)\n blob_name = path_blob_name\n blob_client = container_client.get_blob_client(blob_name)\n\n # upload_blob fails, if blob exists\n if self.exists_in_container(container_name, blob_name):\n blob_client.delete_blob()\n try:\n with open(file_path, \"rb\") as data:\n blob_client.upload_blob(data, blob_type=\"BlockBlob\")\n return blob_client\n except Exception as e:\n raise WorkflowError(\"Error in creating blob. %s\" % str(e))\n # return None\n\n def download_from_azure_storage(\n self,\n container_name,\n blob_name,\n destination_path=None,\n expandBlobNameIntoDirs=True,\n make_dest_dirs=True,\n create_stub_only=False,\n ):\n \"\"\"Download a file from Azure Storage\n This function downloads an object from a specified Azure Storage container.\n Args:\n container_name: the name of the Azure Storage container to use (container name only)\n destination_path: If specified, the file will be saved to this path, otherwise cwd.\n expandBlobNameIntoDirs: Since Azure blob names can include slashes, if this is True (defult)\n then Azure blob names with slashes are expanded into directories on the receiving end.\n If it is False, the blob name is passed to os.path.basename() to get the substring\n following the last slash.\n make_dest_dirs: If this is True (default) and the destination path includes directories\n that do not exist, they will be created.\n Returns:\n The destination path of the downloaded file on the receiving end, or None if the destination_path\n could not be downloaded\n \"\"\"\n assert container_name, \"container_name must be specified\"\n assert blob_name, \"blob_name must be specified\"\n if destination_path:\n destination_path = os.path.realpath(os.path.expanduser(destination_path))\n else:\n if expandBlobNameIntoDirs:\n destination_path = os.path.join(os.getcwd(), blob_name)\n else:\n destination_path = os.path.join(\n os.getcwd(), os.path.basename(blob_name)\n )\n # if the destination path does not exist\n if make_dest_dirs:\n os.makedirs(os.path.dirname(destination_path), exist_ok=True)\n b = self.blob_service_client.get_blob_client(container_name, blob_name)\n if not create_stub_only:\n with open(destination_path, \"wb\") as my_blob:\n blob_data = b.download_blob()\n blob_data.readinto(my_blob)\n else:\n # just create an empty file with the right timestamps\n ts = b.get_blob_properties().last_modified.timestamp()\n with open(destination_path, \"wb\") as fp:\n os.utime(fp.name, (ts, ts))\n return destination_path\n\n def delete_from_container(self, container_name, blob_name):\n \"\"\"Delete a file from Azure Storage container\n\n This function deletes an object from a specified Azure Storage container.\n\n Args:\n container_name: the name of the Azure Storage container to use (container name only, not endpoint)\n blob_name: the name of the blob to delete from the container\n\n Returns:\n nothing\n \"\"\"\n assert container_name, \"container_name must be specified\"\n assert blob_name, \"blob_name must be specified\"\n b = self.blob_service_client.get_blob_client(container_name, blob_name)\n b.delete_blob()\n\n def exists_in_container(self, container_name, blob_name):\n \"\"\"Returns whether the blob exists in the container\n\n Args:\n container_name: the name of the Azure Storage container (container name only, not endpoint)\n blob_name: the blob_name of the object to delete from the container\n\n Returns:\n True | False\n \"\"\"\n\n assert (\n container_name\n ), 'container_name must be specified (did you try to write to \"root\" or forgot to set --default-remote-prefix?)'\n assert blob_name, \"blob_name must be specified\"\n cc = self.blob_service_client.get_container_client(container_name)\n return any(True for _ in cc.list_blobs(name_starts_with=blob_name))\n\n def blob_size(self, container_name, blob_name):\n \"\"\"Returns the size of a blob\n\n Args:\n container_name: the name of the Azure Storage container (container name only, not endpoint)\n blob_name: the blob_name of the object to delete from the container\n\n Returns:\n Size in kb\n \"\"\"\n assert container_name, \"container_name must be specified\"\n assert blob_name, \"blob_name must be specified\"\n\n b = self.blob_service_client.get_blob_client(container_name, blob_name)\n return b.get_blob_properties().size // 1024\n\n def blob_last_modified(self, container_name, blob_name):\n \"\"\"Returns a timestamp of a blob\n\n Args:\n container_name: the name of the Azure Storage container (container name only, not endpoint)\n blob_name: the blob_name of the object to delete from the container\n\n Returns:\n timestamp\n \"\"\"\n assert container_name, \"container_name must be specified\"\n assert blob_name, \"blob_name must be specified\"\n b = self.blob_service_client.get_blob_client(container_name, blob_name)\n return b.get_blob_properties().last_modified.timestamp()\n\n def list_blobs(self, container_name):\n \"\"\"Returns a list of blobs from the container\n\n Args:\n container_name: the name of the Azure Storage container (container name only, not endpoint)\n\n Returns:\n list of blobs\n \"\"\"\n assert container_name, \"container_name must be specified\"\n c = self.blob_service_client.get_container_client(container_name)\n return [b.name for b in c.list_blobs()]\n","sub_path":"snakemake/remote/AzBlob.py","file_name":"AzBlob.py","file_ext":"py","file_size_in_byte":15093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"394183598","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nUniversidade de Lisboa\nFaculdade de Ciências\nDepartamento de Informática\nLicenciatura em Tecnologias da Informação\n2015/2016\n\nProgramação II\n\nProjeto de programação:\nCrime numa grande cidade\n\"\"\"\n\n__author__ = \"Bruno Matos, 47154; Pedro Gritter, 44964\"\n\nimport csv\nfrom math import radians, cos, sin, asin, sqrt\nimport math\nimport time\nfrom datetime import *\nimport pylab as pl\nimport numpy as np\nimport re\n\ndef crimes(nome_ficheiro):\n \"\"\"\n Esta função recebe o nome de um ficheiro como parâmetro, e traça uma figura\n com quatro gráficos.\n\n Requires: Um ficheiro csv.\n Ensures: Figura com quatro gráficos.\n \"\"\"\n pl.figure(1)\n pl.suptitle('O crime na cidade de Baltimore')\n traca_crimes_por_data(crimes_por_data(ler_tabela_de_csv(nome_ficheiro)))\n traca_crimes_por_hora(crimes_por_hora(ler_tabela_de_csv(nome_ficheiro)))\n traca_crimes_por_tipo(crimes_por_tipo(ler_tabela_de_csv(nome_ficheiro)))\n traca_crimes_por_distancia(crimes_por_distancia(ler_tabela_de_csv(nome_ficheiro)),100)\n pl.show()\n\ndef traca_crimes_por_data(grafico):\n \"\"\"\n Esta função traça o gráfico de crimes por data.\n\n Requires: duas listas: uma com as abcissas, outra com as ordenadas.\n Ensures: o gráfico dos crimes por data.\n \"\"\"\n contador1 = 1\n x_axis_label = []\n x_axis_location = []\n \n for x in grafico[0]:\n if x[4:] == '0101':\n x_axis_label.append(x[0:4])\n x_axis_location.append(contador1)\n contador1 += 1\n \n pl.subplot(2,2,1)\n pl.title('Numero de crimes por dia')\n x_axis = grafico[0]\n y_axis = grafico[1]\n pl.xlabel('Anos')\n pl.ylabel('#Crimes')\n x_show = [x for x in range(len(x_axis))]\n pl.xticks(x_axis_location, x_axis_label)\n pl.plot(x_show,y_axis)\n\ndef traca_crimes_por_hora(grafico):\n \"\"\"\n Esta função traça o gráfico de crimes por hora.\n\n Requires: duas listas: uma com as abcissas, outra com as ordenadas.\n Ensures: o gráfico dos crimes por hora.\n \"\"\"\n\n pl.subplot(2,2,2)\n pl.title('Numero de crimes por hora')\n x = grafico[0]\n y = grafico[1]\n pl.xlabel('Horas')\n pl.ylabel('#Crimes')\n x_show = [x for x in range(len(x))]\n pl.xlim(-0.5,23.5)\n pl.bar(x_show, y, align=\"center\", width=1)\n pl.xticks([x for x in range(24)])\n\n\ndef traca_crimes_por_tipo(grafico):\n \"\"\"\n Esta função traça o gráfico de crimes por tipo.\n\n Requires: duas listas: uma com as abcissas, outra com as ordenadas.\n Ensures: o gráfico dos crimes por tipo.\n \"\"\"\n pl.subplot(2,2,3)\n pl.title('Numero de crimes por tipo')\n x_axis = grafico[0]\n y_axis = grafico[1]\n pl.ylabel('#Crimes')\n ind = np.arange(len(x_axis))\n pl.bar(ind,y_axis, align=\"center\", width = 1)\n pl.xticks(ind,grafico[0],rotation='vertical')\n pl.xlim(-0.5, float(max(ind) + 0.5))\n \n \ndef traca_crimes_por_distancia(grafico, distancia_maxima):\n \"\"\"\n Esta função traça o gráfico de crimes por distâncias.\n\n Requires: duas listas: uma com as abcissas, outra com as ordenadas.\n Ensures: o gráfico dos crimes por distâncias.\n \"\"\"\n pl.subplot(2,2,4)\n pl.title('Numero de crimes por distancia ao centro')\n x = grafico[0]\n y = grafico[1]\n pl.xlabel('Distancia (x 100m)')\n pl.ylabel('#Crimes por km2')\n pl.xlim(0,distancia_maxima)\n \n pl.plot(x,y)\n \n\ndef crimes_por_data(tabela):\n \"\"\"\n Esta função recebe uma lista de dicionários e devolve um par de listas:\n abcissas e ordenadas. As abcissas contêm as datas dos crimes por ordem\n crescente; as ordenadas contêm o número de crimes que ocorreram em cada\n data. As datas tomam o formato \"AAAAMMDD\" , por exemplo, \"20160529\" . Tome atenção que na\n visualização do gráfico deverá apresentar a informação organizada\n pelos anos para os quais existem registos no CSV, sendo que a largura de\n cada ano no eixo dos X corresponderá ao total de dias deste (365 ou 366\n dias), mesmo que para alguns dias não existam registos no ficheiro CSV.\n\n Requires: uma lista de dicionários.\n Ensures: um par de listas.\n \"\"\"\n x = []\n y = []\n contador = 0\n\n tabela = map(format_date, tabela)\n table = sorted(tabela, key=lambda k: k['CrimeDate'])\n var = (table[0])['CrimeDate']\n x.append(var)\n \n for i in table:\n if i['CrimeDate'] == var:\n contador +=1\n else:\n x.append(i['CrimeDate'])\n y.append(contador)\n contador = 1\n var = i['CrimeDate']\n\n y.append(contador)\n\n return x, y\n\n\ndef crimes_por_hora(tabela):\n \"\"\"\n A função recebe uma lista de dicionários e devolve um par de listas: abcissas e ordenadas.\n As abcissas contêm uma lista ordenada de horas entre 0 e 23 ; as ordenadas contêm o\n total de crimes, independentemente da data de ocorrência destes, nas\n horas correspondentes na lista das abcissas. Considere crimes registados\n às 24 horas como tendo ocorrido às 0 horas. Tome atenção que na\n visualização do gráfico deverá apresentar todas as horas, mesmo\n aquelas para as quais não existem registos de crime.\n\n Requires: uma lista de dicionários.\n Ensures: um par de listas.\n \"\"\"\n\n x = [x for x in range(24)]\n y = []\n time_data = []\n\n sorted(tabela, key=lambda x: x['CrimeTime'])\n \n for item in tabela:\n hour = item['CrimeTime'].split(':')\n hour = hour[0]\n if hour == '24' or hour == '00':\n time_data.append(0)\n elif hour[0] == '0':\n time_data.append(int(hour[1]))\n else:\n time_data.append(int(hour))\n\n time_data = sorted(time_data)\n \n for hour in x:\n crimes = time_data.count(hour)\n y.append(crimes)\n\n return x,y\n \n\ndef crimes_por_tipo(tabela):\n \"\"\"\n A função recebe uma lista de dicionários e devolve um par de listas: abcissas e ordenadas.\n As abcissas contêm o tipo do crime, dado por um valor do tipo string constante no\n campo Description do ficheiro CSV. As ordenadas contêm o número de\n crimes que ocorreram para o tipo correspondente.\n\n Requires: uma lista de dicionários.\n Ensures: um par de listas.\n \"\"\"\n x = []\n y = []\n contador = 0\n table = sorted(tabela, key=lambda k: k['Description'])\n var = (table[0])['Description']\n x.append(var)\n \n for i in table:\n tipo = i['Description']\n if tipo == var:\n contador += 1\n else:\n x.append(tipo)\n y.append(contador)\n contador = 1\n var = tipo\n y.append(contador)\n \n return x, y\n\ndef crimes_por_distancia(tabela):\n \"\"\"\n Esta função recebe uma lista de dicionários e devolve um par de listas: abcissas e ordenadas.\n As abcissas contêm distâncias múltiplos de 100m ao centro da cidade, i.e.\n [0,1,2,...] , sendo que a primeira representa a coroa circular dos 0m\n (inclusivé) aos 100m (exclusivé), a segunda representa a coroa circular\n dos 100m (inclusivé) aos 200m (exclusivé), e assim sucessivamente. As\n ordenadas contêm a densidade dos crimes em cada coroa circular, i.e., o\n número de crimes por quilómetro quadrado, pela ordem correspondente da\n lista das abcissas. Por exemplo, se n for o número de crimes ocorridos\n dentro da terceira coroa, i.e., entre os 200m (inclusivé) e os 300m\n (exclusivé), a respetiva densidade de crimes será calculada dividindo n\n pela área desta coroa em quilómetros quadrados, sendo esta última\n dada pela fórmula π × 0.3 2 − π × 0.2 2 , e arredondando o resultado para\n o inteiro mais próximo.\n \n Requires: uma lista de dicionários.\n Ensures: um par de listas.\n \"\"\"\n \n x = []\n y = []\n orlas = {}\n \n for item in tabela:\n if 'Location 1' in item.keys() and item['Location 1'] != '':\n gps = re.sub('[() ]', '', item['Location 1']).split(',')\n distancia_centro = int(haversine(39.289444, -76.616667, float(gps[0]), float(gps[1]))/100)\n \n if distancia_centro in orlas.keys():\n orlas[distancia_centro] += 1\n else:\n orlas[distancia_centro] = 1\n pi = math.pi\n \n for orla in orlas: \n\n a_orla = (pi*(float(orla + 1)/10)**2) - (pi*(float(orla)/10)**2)\n densidade = float(orlas[orla])/a_orla\n\n x.append(orla)\n y.append(int(round(densidade)))\n \n return x, y\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n \"\"\"\n Returns the great circle distance between two GPS points given in degrees.\n See:\n http://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points\n http://www.movable-type.co.uk/scripts/latlong.html\n \"\"\"\n lat1, lat2, dlat, dlon = map(radians, [lat1, lat2, lat2 - lat1, lon2 - lon1])\n a = sin(dlat / 2.0) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2.0) ** 2\n c = 2 * asin(sqrt(a))\n raio_da_terra_em_metros = 6371000\n return c * raio_da_terra_em_metros\n\n\ndef ler_tabela_de_csv(nome_ficheiro_csv):\n \"\"\"\n Esta função lê o ficheiro CSV.\n Requires: o nome de um ficheiro CSV com cabeçalho na primeira linha.\n Ensures: retorna uma tabela no formato de lista de dicionários.\n \"\"\"\n with open(nome_ficheiro_csv, 'rU') as ficheiro_csv:\n leitor = csv.DictReader(ficheiro_csv, delimiter=',')\n return [linha for linha in leitor]\n\ndef format_date(crime):\n \"\"\"\n Esta função transforma uma data no formato AAAAMMDD. \n Requires: um registo com a data no formato MMDDAAAA.\n Ensures: retorna uma data no formato AAAAMMDD.\n \"\"\"\n \n crime['CrimeDate'] = datetime.strptime(crime['CrimeDate'], '%m/%d/%Y').strftime('%Y%m%d')\n\n return crime\n\n\n### Verificando o tempo que leva a construir os dados dos gráficos\n\nfrom timeit import timeit\n\n# Uma string representando o nome do ficheiro CSV contendo os dados de\n# interesse para o trabalho. Coloquem aqui o nome do vosso ficheiro.\nficheiro_dados_crimes = \"BPD_Part_1_Victim_Based_Crime_Data.csv\"\n\ndef go_time():\n \"\"\"Ensures: Devolve o tempo de execução da função dados_crimes()\n quando aplicada ao ficheiro ficheiro_dados_crimes.\n \"\"\"\n return timeit(\"dados_crimes(ficheiro_dados_crimes)\",\n \"from PRJ_47154 import dados_crimes, ficheiro_dados_crimes\", number = 1)\n\ndef dados_crimes(nome_ficheiro):\n \"\"\"Esta função não deve levar mais do que um determinado tempo\n quando executada numa máquina do laboratório do Departamento de\n Informática. O tempo em questão será anunciado na semana 9 de maio\n de 2016.\n\n Requires: nome_ficheiro é uma string representando o nome de um\n ficheiro CSV com dados sobre crimes.\n \n Ensures: Devolve um quadrúplo com os dados referentes a cada um dos\n quatro gráficos, de acordo com o enunciado do projeto.\n \"\"\"\n t = ler_tabela_de_csv(nome_ficheiro)\n return crimes_por_data(t), crimes_por_hora(t), \\\n crimes_por_tipo(t), crimes_por_distancia(t)\n","sub_path":"PRJ_47154.py","file_name":"PRJ_47154.py","file_ext":"py","file_size_in_byte":11109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"}