id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
11329009
<reponame>d-asnaghi/bazel-rust-embedded """ Transitive dependencies for Rust Embedded Tools """ load("@rust_embedded//crates:crates.bzl", "raze_fetch_remote_crates") load("@rules_rust//rust:repositories.bzl", "rust_repositories") load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace") def rust_embedded_deps(): """Runs dependency rules for third party dependencies""" bazel_skylib_workspace() rust_repositories() raze_fetch_remote_crates()
StarcoderdataPython
8112102
<filename>amp_app/app_config.py import os from dotenv import load_dotenv # Load the values from .env file dotenv_path = os.path.join(os.path.dirname(__file__), '.env') # Path to .env file load_dotenv(dotenv_path) # Our Quickstart uses this placeholder # In your production app, we recommend you to use other ways to store your secret, # such as KeyVault, or environment variable as described in Flask's documentation here # https://flask.palletsprojects.com/en/1.1.x/config/#configuring-from-environment-variables # https://pypi.org/project/python-dotenv/#usages # CLIENT_SECRET = os.getenv("CLIENT_SECRET") # if not CLIENT_SECRET: # raise ValueError("Need to define CLIENT_SECRET environment variable") # Application login TENANT_ID = os.getenv('TENANT_ID') if not TENANT_ID: raise ValueError("Need to define TENANT_ID environment variable") CLIENT_ID = os.getenv('CLIENT_ID') if not CLIENT_ID: raise ValueError("Need to define CLIENT_ID environment variable") CLIENT_SECRET = os.getenv('CLIENT_SECRET') if not CLIENT_SECRET: raise ValueError("Need to define CLIENT_SECRET environment variable") # For calling the market place api MARKETPLACEAPI_TENANTID = os.getenv('MARKETPLACEAPI_TENANTID') if not MARKETPLACEAPI_TENANTID: raise ValueError("Need to define MARKETPLACEAPI_TENANTID environment variable") MARKETPLACEAPI_CLIENT_ID = os.getenv('MARKETPLACEAPI_CLIENT_ID') if not MARKETPLACEAPI_CLIENT_ID: raise ValueError("Need to define MARKETPLACEAPI_CLIENT_ID environment variable") MARKETPLACEAPI_CLIENT_SECRET = os.getenv('MARKETPLACEAPI_CLIENT_SECRET') if not MARKETPLACEAPI_CLIENT_SECRET: raise ValueError("Need to define MARKETPLACEAPI_CLIENT_SECRET environment variable") MARKETPLACEAPI_API_VERSION = os.getenv('MARKETPLACEAPI_API_VERSION') if not MARKETPLACEAPI_API_VERSION: raise ValueError("Need to define MARKETPLACEAPI_API_VERSION environment variable") HTTP_SCHEME = os.getenv('HTTP_SCHEME') if not HTTP_SCHEME: raise ValueError("Need to define HTTP_SCHEME environment variable") SENDGRID_APIKEY = os.getenv('SENDGRID_APIKEY') if not SENDGRID_APIKEY: raise ValueError("Need to define SENDGRID_APIKEY environment variable") SENDGRID_FROM_EMAIL = os.getenv('SENDGRID_FROM_EMAIL') if not SENDGRID_FROM_EMAIL: raise ValueError("Need to define SENDGRID_FROM_EMAIL environment variable") SENDGRID_TO_EMAIL = os.getenv('SENDGRID_TO_EMAIL') if not SENDGRID_TO_EMAIL: raise ValueError("Need to define SENDGRID_TO_EMAIL environment variable") REDIRECT_PATH = '/getAToken' SESSION_TYPE = "filesystem" # So token cache will be stored in server-side session SCOPE = [""] AUTHORITY = "https://login.microsoftonline.com/" MARKETPLACEAPI_ENDPOINT = 'https://marketplaceapi.microsoft.com/api/saas/subscriptions/' MARKETPLACEAPI_RESOURCE = "62d94f6c-d599-489b-a797-3e10e42fbe22"
StarcoderdataPython
6625911
import os import time # Deploy environmet for i in range(10): print(f"[+] Deploy test{i}") os.system(f"tk apply environments/consensus --dangerous-auto-approve --name=test{i}") print("[+] Wait for pods to be up") os.system("kubectl wait -n default --for=condition=Ready pod --all") print("[+] Wait 30s") time.sleep(30) os.system("sh start-consensus-parallel.sh") # print("[+] Wait 30s") # time.sleep(30) # print("[+] Teardown") # os.system("kubectl delete -n default pod --all --grace-period=0")
StarcoderdataPython
6651222
<gh_stars>1-10 #coding=utf-8 #使用OrderedDict P160 2017.4.20 from collections import OrderedDict languages = OrderedDict() languages['jen'] = 'python' languages['sarah'] = 'c' languages['edward'] = 'ruby' languages['phil'] = 'c++' for name,language in languages.items(): print(name.title()+"--"+language.title()) xyz = { 'a':'a', 'b':'b', 'c':'c', } xyz['d']='d' for key,value in xyz.items(): print(key+"--"+value)
StarcoderdataPython
388478
<reponame>ancow/snakemq # -*- coding: utf-8 -*- """ :author: <NAME> (<EMAIL>) :license: MIT License (see LICENSE.txt or U{http://www.opensource.org/licenses/mit-license.php}) """ import threading from collections import deque # TODO utilize io module ############################################################################ ############################################################################ MAX_BUF_CHUNK_SIZE = 64 * 1024 ############################################################################ ############################################################################ class BufferException(Exception): pass class BufferTimeout(BufferException): pass class BufferTooLarge(BufferException): """ Raised when you want to put larger piece then the buffer max size. """ pass ############################################################################ ############################################################################ class StreamBuffer(object): def __init__(self): self.size = 0 #: current size of the buffer self.max_size = None self.queue = deque() self.not_full_cond = threading.Condition() ############################################################ def __del__(self): self.clear() ############################################################ def clear(self): with self.not_full_cond: self.queue.clear() self.size = 0 self.not_full_cond.notify() ############################################################ def set_max_size(self, max_size): """ :param max_size: None or number of bytes: L{StreamBuffer.put} will block if the content will be bigger then C{max_size}. WARNING: there must be only one thread inserting data at a time """ assert (max_size is None) or (max_size > 0) self.max_size = max_size ############################################################ def put(self, data, timeout=None): """ Add to the right side. It will block if the buffer will exceed C{max_size}. If C{max_size} is set then C{len(data)} must not be longer then the maximal size. """ assert type(data) == bytes if not data: # do not insert an empty string return data_len = len(data) if self.max_size and (data_len > self.max_size): raise BufferTooLarge("len(data)=%i > max_size=%i" % (data_len, self.max_size)) with self.not_full_cond: if self.max_size and (self.size + data_len > self.max_size): self.not_full_cond.wait(timeout) if self.size + data_len > self.max_size: raise BufferTimeout self.size += data_len for i in range(len(data) // MAX_BUF_CHUNK_SIZE + 1): chunk = data[i * MAX_BUF_CHUNK_SIZE:(i + 1) * MAX_BUF_CHUNK_SIZE] if not chunk: break self.queue.append(chunk) del chunk del data ############################################################ def get(self, size, cut=True): """ Get from the left side. :param cut: True = remove returned data from buffer :return: max N-bytes from the buffer. """ assert (((self.size > 0) and (len(self.queue) > 0)) or ((self.size == 0) and (len(self.queue) == 0))) retbuf = [] i = 0 with self.not_full_cond: orig_size = self.size while size and self.queue: if cut: fragment = self.queue.popleft() else: fragment = self.queue[i] if len(fragment) > size: if cut: # paste back the rest self.queue.appendleft(fragment[size:]) # get only needed fragment = fragment[:size] frag_len = size else: frag_len = len(fragment) retbuf.append(fragment) del fragment size -= frag_len if cut: self.size -= frag_len else: i += 1 if i == len(self.queue): break if (self.max_size and (orig_size >= self.max_size) and (self.size < self.max_size)): self.not_full_cond.notify() return b"".join(retbuf) ############################################################ def cut(self, size): """ More efficient version of get(cut=True) and no data will be returned. """ assert (((self.size > 0) and (len(self.queue) > 0)) or ((self.size == 0) and (len(self.queue) == 0))) with self.not_full_cond: orig_size = self.size while size and self.queue: fragment = self.queue.popleft() if len(fragment) > size: # paste back the rest self.queue.appendleft(fragment[size:]) frag_len = size else: frag_len = len(fragment) del fragment size -= frag_len self.size -= frag_len if (self.max_size and (orig_size >= self.max_size) and (self.size < self.max_size)): self.not_full_cond.notify() ############################################################ def __len__(self): assert sum([len(item) for item in self.queue]) == self.size return self.size
StarcoderdataPython
3315748
<filename>ex038.py v1 = int(input('Digite um valor: ')) v2 = int(input('Digite outro valor: ')) if v1 > v2: print('O primeiro valor {} é o maior'.format(v1)) elif v2 > v1: print('O segundo valor {} é o maior'.format(v2)) else: print('NÃO EXISTE um valor maior, os dois são iguais')
StarcoderdataPython
11378621
'''Sudoku Solver Main Module''' import tkinter from tkinter import ttk # Used for scrollbar from tkinter import messagebox # Used for message boxes from tkinter import filedialog # Used for opening the file dialog box import copy # Used for creating copies of variables instead of instances import threading # Multithreading module import time # Time module for delays import os # Module for opening system files from sys import exit # Prevents .exe from crashing when exit function is used import json # Module for opening json files class GraphicalInterface: 'Creates the entire GUI' def __init__(self, parent): # Parent is the main window self.parent = parent # Parent root frame self.solutions = [] # Stores all solved grids self.empty_grid = [ # Empty grid used for resetting [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0] ] self.running = False # Sets the flag indicating whether the solver thread is running; needed for solver thread self.modify = True # Sets the flag indicating whether the grid is allowed to be modified self.autosave = tkinter.IntVar() # Sets value indicating whether to save grid automatically (1 or 0) self.delay = tkinter.IntVar() # Sets value indicating whether to delay grid animation (1 or 0) self.margin = 10 # Margin size of the sudoku board self.side = 40 # Side length of each square in the grid self.width = self.height = (self.margin*2) + (self.side*9) # Defines the width and height of the canvas self.buttonfont = ('Helvetica', 7) # Font type of buttons self.statusfont = ('Helvetica', 7) # Font type for the status bar self.gridfont = ('Helvetica', 10, 'bold') # Font type of sudoku grid self.row = None # Currently selected cell row and column self.col = None self.__widgets() # Initiates other widgets self.__load_settings() # Loads old settings ### PACKING WIDGETS def __widgets(self): 'Initiates the widgets' ### MENUBAR self.menubar = tkinter.Menu(root) # Creates the menubar object root.config(menu=self.menubar) # Sets menubar object in root self.file_submenu = tkinter.Menu(self.menubar, tearoff=0) # Creates file submenu self.menubar.add_cascade(label='File', menu=self.file_submenu) # Places submenu inside menubar self.file_submenu.add_command(label='Load...', command=self.__load) # Adds load button self.file_submenu.add_separator() # Adds a line separator self.file_submenu.add_command(label='Save As...', state=tkinter.DISABLED, command=self.__save) # Adds save button which is disabled at the start self.file_submenu.add_checkbutton(label='Auto Save', variable=self.autosave, command=self.__save_settings) # Adds a checkbutton for autosave functionality binded to self.autosave self.file_submenu.add_separator() # Adds a line separator self.file_submenu.add_command(label='Exit', command=exit) # Adds exit button self.option_submenu = tkinter.Menu(self.menubar, tearoff=0) # Creates options submenu self.menubar.add_cascade(label='Options', menu=self.option_submenu) # Places the submenu inside the menubar self.option_submenu.add_checkbutton(label='Delay Animations', variable=self.delay, command=self.__save_settings) # Adds a checkbutton for delaying animations functionality binded to self.delay self.help_submenu = tkinter.Menu(self.menubar, tearoff=0) # Creates help submenu self.menubar.add_cascade(label='Help', menu=self.help_submenu) # Places the submenu inside the menubar self.help_submenu.add_command(label='About Sudoku Solver', command=self.__about) # About button that opens README.md self.help_submenu.add_separator() # Adds a line separator self.help_submenu.add_command(label='Licence', command=self.__licence) # Licence button that opens LICENCE.md ### SCROLLBAR & STATUS BAR self.scrollbar = tkinter.Scrollbar(root) # Scrollbar for the text widget self.scrollbar.grid(row=0, column=2, sticky=tkinter.NS) # sticky parameter makes scrollbar stretch from top to bottom; added on right side of GUI self.status_bar = tkinter.Label(root, text='Awaiting commands.', font=self.statusfont, bg='#171717', fg='white', anchor=tkinter.E) # Status bar for displaying various status updates self.status_bar.grid(row=1, column=0, columnspan=3, sticky=tkinter.EW) # sticky parameter makes the label stretch from left to right; added at the bottom of the GUI ### LEFT FRAME (Contains Sudoku Grid) self.left_frame = tkinter.Frame(self.parent, bg='#212121') # Left frame placed inside the root widget self.canvas = tkinter.Canvas(self.left_frame, bg='#212121', width=self.width, height=self.height) # Sudoku grid canvas self.left_frame.grid(row=0, column=0) # Positions the frame on the left of the GUI self.canvas.grid(padx=(10,0)) ### RIGHT FRAME (Contains solutions display grid and execution buttons) self.right_frame = tkinter.Frame(self.parent, bg='#212121') # Right frame placed inside the root widget self.solved_grids_display = tkinter.Text(self.right_frame, bg='#212121', height=21, width=30, state=tkinter.DISABLED, yscrollcommand=self.scrollbar.set) # Text widget displaying all the solved solutions self.right_frame.grid(row=0, column=1) # Positions the frame on the right of the GUI self.solved_grids_display.grid(row=0, column=0, padx=10, pady=(20,0)) ###### RIGHT FRAME BUTTONS LABEL FRAME (Contains execution buttons) self.buttons_label_frame = tkinter.LabelFrame(self.right_frame, text='Configure', font=self.statusfont, bg='#212121', fg='white') # Buttons sub frame inside right frame self.start_btn = tkinter.Button(self.buttons_label_frame, text='Start', font=self.buttonfont, bg='#212121', fg='white', command=self.__start) # Start button self.stop_btn = tkinter.Button(self.buttons_label_frame, text='Stop', font=self.buttonfont, bg='#212121', fg='white', state=tkinter.DISABLED, command=self.__stop) # Stop button self.reset_btn = tkinter.Button(self.buttons_label_frame, text='Reset', font=self.buttonfont, bg='#212121', fg='white', state=tkinter.DISABLED, command=self.__reset) # Reset button self.loading_bar = ttk.Progressbar(self.buttons_label_frame, orient=tkinter.HORIZONTAL, mode='indeterminate', maximum='20', length=150) # Indeterminate loading bar does not fill gradually but rather sweeps across self.buttons_label_frame.grid(row=1, column=0, columnspan=2, pady=(0,10)) # Places label frame inside the right frame self.start_btn.grid(row=1, column=0) self.stop_btn.grid(row=1, column=1) self.reset_btn.grid(row=1, column=2) self.loading_bar.grid(row=1, column=3, sticky=tkinter.EW) # sticky parameter makes loading bar stretch from left to right ### WIDGET CONFIGURATION self.scrollbar.config(command=self.solved_grids_display.yview) # Configures the scrolling of the text widget self.solved_grids_display.tag_configure('header', font=('Helvetica', 10, 'bold'), foreground='#FC5F17', justify=tkinter.CENTER) # Configures the header font properties of the text widget self.solved_grids_display.tag_configure('subheader', font=('Helvetica', 7, 'bold italic'), foreground='#FC5F17', justify=tkinter.CENTER) # Configures the subheader font properties of the text widget self.solved_grids_display.tag_configure('solutions', font=('Helvetica', 14, 'bold'), foreground='#FC5F17', justify=tkinter.CENTER) # Configures the solution grids font properties of the text widget ### BINDING MOUSE AND KEYBOARD EVENTS self.__draw_grid() # Draws the empty grid self.canvas.bind('<Button-1>', self.__cell_clicked) # Binds left click to selecting a cell self.parent.bind('<Key>', self.__key_pressed) # Binds key pressed to entering a key; must be binded to root def __draw_grid(self): 'Draws the Sudoku grid' for i in range(10): if i % 3 == 0: # Every 3 lines switches to black color = 'white' else: color = 'grey' # Vertical lines x0 = self.margin + (i*self.side) y0 = self.margin x1 = self.margin + (i*self.side) y1 = self.height - self.margin self.canvas.create_line(x0,y0,x1,y1, fill=color) # Horizontal lines x0 = self.margin y0 = self.margin + (i*self.side) x1 = self.height - self.margin y1 = self.margin + (i*self.side) self.canvas.create_line(x0,y0,x1,y1, fill=color) ### MOUSE AND KEYBOARD INPUT HANDLING def __cell_clicked(self, event): '''Handles mouse clicks Takes event as argument. Creates indicator only if self.modify is True''' x, y = event.x, event.y # Finds the x and y coordinate of the click if self.modify: # Box selection functionality only available if modify variable is True if (self.margin < x < self.width - self.margin) and (self.margin < y < self.height - self.margin): # Checks that the click is inside the grid row, col = (y-self.margin)//self.side, (x-self.margin)//self.side # Calculates what row and column the cursor is in if (row, col) == (self.row, self.col): # If cell is already selected, deselect it self.row, self.col = None, None else: # If it is not selected, select it self.row, self.col = row, col self.__draw_border() # Handles the box selection else: # If the user clicks outside the canvas self.row, self.col = None, None # Resets the currently selected cell row and column self.canvas.delete('cursor') # Deletes the previous cursor def __draw_border(self): 'Draws the border around the selected square' self.canvas.delete('cursor') # Deletes the previous cursor if (self.row, self.col) != (None, None): # Checks that a box has not been deselected x0 = self.margin + self.col*self.side # Defines the boundaries of the rectangle selection cursor y0 = self.margin + self.row*self.side x1 = self.margin + (self.col+1)*self.side y1 = self.margin + (self.row+1)*self.side self.canvas.create_rectangle(x0, y0, x1, y1, tags='cursor', outline='#03DAC6', width=2) # Creates the cursor def __key_pressed(self, event): '''Handles keyboard key press Takes event as argument''' if event.keysym == 'Return': # Return button used to start dynamic solving of the grid if self.start_btn.cget('state') == 'normal': # Start button is enabled (program is ok to run) self.__start() # Starts program execution elif event.keysym == 'Escape': # Escape button used to stop the dynamic solving of the grid if self.stop_btn.cget('state') == 'normal': # Stop button is enabled (program is ok to stop) self.__stop() # Stops program execution elif (self.row, self.col) != (None, None): # Checks that a square is selected if event.char.isnumeric(): # If entered key is a digit self.__display_number(self.row, self.col, event.char, color='#FC5F17') # Displays digit in canvas self.reset_btn.config(state=tkinter.NORMAL) # Enables the reset button if self.col == 8: # If selected cell is in the last column if self.row != 8: # If the selected cell is not in the last row self.row, self.col = self.row+1, 0 # Selects first cell of next row else: # If selected cell is not in the last column self.col += 1 # Selects next cell across self.__draw_border() elif event.keysym == 'BackSpace': # If backspace is pressed self.__display_number(self.row, self.col, None) # Resets the square ### START/STOP/RESET METHODS def __start(self): 'Begins the dynamic solving of the grid' self.row, self.col = None, None # Resets the currently selected cell row and column self.canvas.delete('cursor') # Deletes the previous cursor self.grid = [ # Makes a new empty 8x8 grid which will store the user-entered values [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0] ] # Stores each user-entered number in self.grid for ypos, row in enumerate(self.grid): # Goes through each row in the grid for xpos, _ in enumerate(row): # Goes through each position in the row grid_object = self.canvas.find_withtag((ypos,xpos),) # Gets the grid number object with tag at respective position (row, column) value = self.canvas.itemcget(grid_object, 'text') # Gets the value of the specific grid number; 'text' argument specifies we want to extract the text # Note that value could be None if value: # If the cell is filled in self.grid[ypos][xpos] = int(value) else: # If the cell is empty self.grid[ypos][xpos] = 0 if not self.__validate_selected_grid(): # If the grid is not valid in format return None # Returns early else: # Grid is valid in format; GRID MAY NOT HAVE ANY SOLUTIONS self.__update_grid(self.grid) # Displays the grid threading.Thread(target=self.__solver_thread).start() # Initiates the solver thread def __solver_thread(self): 'Main solver thread that solves self.grid' self.running = True # Allows the solver thread to run self.modify = False # Grid modification feature must be disabled when grid is solving self.file_submenu.entryconfig(0, state=tkinter.DISABLED) # Disables the load functionality when program is running self.file_submenu.entryconfig(2, state=tkinter.DISABLED) # Disables the save as functionality when program is running self.option_submenu.entryconfig(0, state=tkinter.DISABLED) # Disables animations delay setting self.start_btn.config(state=tkinter.DISABLED) # Disabled start button until execution is finished self.stop_btn.config(state=tkinter.NORMAL) # Enables the stop button until execution is finished self.reset_btn.config(state=tkinter.DISABLED) # Disables the reset button until execution is finished self.status_bar.config(text='Executing solve.', fg='white') # Updates status bar self.loading_bar.start() # Starts the loading bar animation self.interrupted = self.__solve_grid() # Solves the grid and returns True (was interrupted) or False (was not interrupted); used for displaying or auto saving self.running = False # Program is not running anymore if self.solutions: # If at least 1 solution has been found self.file_submenu.entryconfig(2, state=tkinter.NORMAL) # Re-enables the save as functionality else: # If no solutions have been found self.__update_solved_grids() # Updates the solved solutions text widget self.option_submenu.entryconfig(0, state=tkinter.NORMAL) # Enables animations delay setting self.stop_btn.config(state=tkinter.DISABLED) # Disables stop button at the end of execution self.reset_btn.config(state=tkinter.NORMAL) # Enables the reset button self.loading_bar.stop() # Stops the loading bar animation if not self.interrupted: # Displays all solutions only if it was not interrupted self.status_bar.config(text='Execution successful. Please reset grid.', fg='white') # Updates status bar if self.autosave.get() and self.solutions: # If autosave is on and at least 1 solution has been found self.__save() # Save the results else: # If program was interrupted self.status_bar.config(text='Execution interrupted. Please reset grid.', fg='white') # Updates status bar def __stop(self): 'Interrupts the dynamic solving of the grid' self.running = False # Disallowes the solver thread from running def __reset(self): 'Resets the graphical user interface to its initial state' self.file_submenu.entryconfig(0, state=tkinter.NORMAL) # Enables the load functionality when program is reset self.file_submenu.entryconfig(2, state=tkinter.DISABLED) # Disables the save as functionality when program is reset self.start_btn.config(state=tkinter.NORMAL) # Re-enables the start button self.reset_btn.config(state=tkinter.DISABLED) # Disables the reset ability self.solutions = [] # Resets all the found solutions self.loaded_grid = None # Forgets the loaded grid self.modify = True # Re-enables the modify flag to enable grid modification self.row, self.col = None, None # Resets the currently selected cell row and column self.canvas.delete('cursor') # Deletes the previous cursor self.solved_grids_display.config(state=tkinter.NORMAL) # Temporarily enables widget self.solved_grids_display.delete(1.0, 'end') # Clears the entire solved solutions text widget self.solved_grids_display.config(state=tkinter.DISABLED) # Disables widget again self.__update_grid(self.empty_grid) # Displays the empty grid self.status_bar.config(text='Reset complete.', fg='white') # Updates the status bar ### LOGIC HANDLING METHODS def __solve_grid(self): '''Solves the grid in self.grid and stores each solution as a list in self.solutions; displays each iteration of the solving algorithm Returns True if process was interrupted or False if process was not interrupted''' for ypos, row in enumerate(self.grid): # Goes through each row in the grid for xpos, position in enumerate(row): # Goes through each position in the row if position == 0: # Position must be empty for num in range(1,10): # Tries all numbers from 1 to 9 if self.delay.get(): # If animation is set to be delayed time.sleep(0.1) if not self.running: # If it was interrupted return True # Returns True; it was interrupted if self.__possible(xpos, ypos, num): # Check if the number is a possible self.grid[ypos][xpos] = num # Puts possible number in empty space self.__display_number(ypos, xpos, num) self.__solve_grid() # Keeps solving self.grid[ypos][xpos] = 0 # If program reaches here, no further numbers can be put into the grid and the square is reset self.__display_number(ypos, xpos, None) # Empties the sudoku square return False # No possible solution has been found for an empty position; Exits function by returning None as it was not interrupted # If program reaches this point, there are no more empty spaces in the grid and a solution has been found deepcopy_grid = copy.deepcopy(self.grid) # A copy of the original grid is made self.solutions.append(deepcopy_grid) # Solution added to list of solutions self.__update_solved_grids() # Updates the solved solutions text widget def __possible(self, x, y, n): '''Returns True or False if a number can fit in a specific position in self.grid Takes x position, y position, and value of a possible number as arguments''' # Checks row for position in self.grid[y]: if position == n: return False # Checks column for row in self.grid: if row[x] == n: return False # Checks square ranges = [range(0,3), range(3,6), range(6,9)] # Possible grid ranges xrange = None # Stores the ranges that x and y are in yrange = None for possible_range in ranges: if x in possible_range: xrange = possible_range # If x fits in the range, the range is stored if y in possible_range: yrange = possible_range # If y fits in the range, the range is stored for row in self.grid[yrange[0]:yrange[-1]+1]: for position in row[xrange[0]:xrange[-1]+1]: if position == n: # Checks every position in the square return False return True # No doubles detected ### VALIDATION METHODS def __validate_selected_grid(self): 'Validates self.grid by making sure the value placement is correct and that at least 17 values have been entered; returns True or False if grid is valid' count = 0 # Stores the valid grid clue count for ypos, row in enumerate(self.grid): # Goes through each row in the grid for xpos, position in enumerate(row): # Goes through each position in the row if position: # If the number is not 0 self.grid[ypos][xpos] = 0 # Sets the number to 0 temporarily so that self.__possible works if not self.__possible(xpos, ypos, position): # If number cannot be placed in that position # Note that number is not reset in the grid if it is invalid. Grid must be reset self.status_bar.config(text=f'Conflict in clue positioning (Row:{ypos+1},Column:{xpos+1}). Invalid grid.', fg='#CF6679') # Updates status bar with dark red color return False # Grid is invalid self.grid[ypos][xpos] = position # Resets number in the grid after using __possible method count += 1 # Number is valid if count < 17: # If there are less than 17 clues self.status_bar.config(text=f'Please enter at least 17 clues. ({17-count} remaining)', fg='#CF6679') # Updates status bar with dark red color return False # Grid is invalid return True # Grid is valid def __validate_loaded_grid(self, grid): # Used for validating an imported grid '''Validates the format of a LOADED grid by making sure only integer values between 0 to 9 are entered and that grid is of list type; returns True or False if grid format is valid Takes grid as argument''' if not isinstance(grid, list): # Checks that the grid is of type grid return False # Grid is not valid for row in grid: # For each row in the grid if len(row) != 9: # If exactly 9 items are not present in each row return False # Grid is not valid for position in row: # For each number in the grid if position not in range(0, 10): # Number must be in range [0,10) return False # Grid is invalid return True # Grid is valid ### DISPLAYER METHODS def __update_grid(self, grid): '''Displays a grid in the Sudoku canvas Takes grid as argument''' for ypos, row in enumerate(grid): # Goes through each row in the grid for xpos, position in enumerate(row): # Goes through each position in the row if position: # If the number does not equal to 0 self.__display_number(ypos, xpos, position, color='#FC5F17') # Displays the number else: # If the number is 0, square is supposed to be empty self.__display_number(ypos, xpos, None) # Empties square def __update_solved_grids(self): 'Updates solved grids text widget by displaying all the found solutions from self.solutions' self.solved_grids_display.config(state=tkinter.NORMAL) # Temporarily activates the text widget self.solved_grids_display.delete(1.0, 'end') # Clears entire widget self.solved_grids_display.insert('end', f'{len(self.solutions)} Solution(s) Found\n', 'header') # Adds header with header tag if len(self.solutions) == 1: # If only 1 solution has been found self.solved_grids_display.insert('end', f'(True Sudoku Grid)\n', 'subheader') # True Sudoku grid by definition else: # If more than 1 solutions are found self.solved_grids_display.insert('end', f'(False Sudoku Grid)\n', 'subheader') # False Sudoku grid by definition for grid in self.solutions: # For each solution self.solved_grids_display.insert('end', '\n') # Adds a separator between the solutions for row in grid: # For each row in the solution grid self.solved_grids_display.insert('end', f'{row}\n', 'solutions') # Appends the row to the text widget with solutions tag self.solved_grids_display.see('end') # Automatically scrolls to the end of the widget self.solved_grids_display.config(state=tkinter.DISABLED) # Deactivates the text widget def __display_number(self, row, column, n, color='white'): '''Displays a given digit on the Sudoku canvas Takes the row number, column number, value of the number to display, and optional font color as arguments''' x = round(self.margin + self.side*column + self.side/2) # Finds x and y coords of the centre of the selected square y = round(self.margin + self.side*row + self.side/2) # Coordinates are rounded to nearest integer tag = (row,column) # Create a tag from 00 to 88 representing the row and column the selected square is in self.canvas.delete(tag) # Deletes previous self.canvas.create_text(x, y, text=n, tags=(tag,), fill=color, font=self.gridfont) # Places a number on the screen with tagged position # tags argument should be a tuple or string def __solutions_formatter(self): '''Manipulates the solutions in self.solutions into a printable format Returns formatted string''' formatted = f'-----------------------{len(self.solutions)} Solutions Found-----------------------\n' # String storing formatted solutions if len(self.solutions) == 1: # If only 1 solution has been found formatted += f'(True Sudoku Grid)' # True Sudoku grid by definition else: # If more than 1 solutions are found formatted += f'(False Sudoku Grid)' # True Sudoku grid by definition for grid in self.solutions: # For each solution formatted += '\n' # Adds empty line between each solution for row in grid: # For each row in the grid formatted += f'\n{row}' return formatted # Returns formatted solutions as a string ### MENUBAR SETTINGS METHODS def __load(self): 'Loads a grid from a chosen json file' try: filename = filedialog.askopenfilename(title='Select Load File', filetypes=(('Text Files', '*.json'),)) # Prompts user to select a load file (.json) if filename: # If a file has been chosen with open(filename, 'r') as f: # Opens the chosen file as read loaded_grid = json.load(f) # Deserialize json file contents if self.__validate_loaded_grid(loaded_grid): # If the grid is of valid format self.row, self.col = None, None # Resets the currently selected cell row and column self.canvas.delete('cursor') # Deletes the previous cursor self.reset_btn.config(state=tkinter.NORMAL) # Enabled reset button self.__update_grid(loaded_grid) # Displays the grid else: # If grid is invalid raise Exception('Incorrect grid format') # Raises exception else: # If program reaches this point, user has not chosen a file and has aborted load return None except Exception as e: messagebox.showerror(title='Fatal Error', message=f'An unexpected error has occurred: {e}') # Shows error self.status_bar.config(text=f'An error occurred. Load aborted.', fg='#CF6689') # Updates status bar else: messagebox.showinfo(title='File loaded successfully', message=f"Grid has been successfully loaded from '{filename}'") # Shows successful load info self.status_bar.config(text=f'Load successful.', fg='white') # Updates status bar def __save(self): 'Saves all found solutions in chosen text file' try: filename = filedialog.askopenfilename(title='Select Save File', filetypes=(('Text Files', '*.txt'),)) # Prompts user to select a save file (.txt) if filename: # If a file has been chosen with open(filename, 'w') as f: # Opens the chosen file f.write(self.__solutions_formatter()) # Writes solutions into file else: # If program reaches this point, user has not chosen a file and has aborted save return None except Exception as e: messagebox.showerror(title='Fatal Error', message=f'An unexpected error has occurred: {e}') # Shows error self.status_bar.config(text=f'An error occurred. Save aborted.', fg='#CF6689') # Updates status bar else: messagebox.showinfo(title='File saved successfully', message=f"Solutions have been successfully saved in '{filename}'") # Shows successful save info self.status_bar.config(text=f'Save successful.', fg='white') # Updates status bar def __save_settings(self): 'Updates settings in settings.json' try: with open(r'resources\settings.json', 'w') as f: # Opens the chosen file as read self.settings = {'Autosave': self.autosave.get(), 'AnimationDelay': self.delay.get()} # Stores all the loadable settings as a dictionary json.dump(self.settings, f) # Dumps the settings into json file except Exception as e: messagebox.showerror(title='Fatal Error', message=f'An unexpected error has occurred: {e}') # Shows error exit() # Exits program if an error occurs when saving def __load_settings(self): 'Loads the settings from settings.json' try: with open(r'resources\settings.json', 'r') as f: # Opens the chosen file as read self.settings = json.load(f) # Loads all the settings self.autosave.set(self.settings['Autosave']) self.delay.set(self.settings['AnimationDelay']) except Exception as e: messagebox.showerror(title='Fatal Error', message=f'An unexpected error has occurred: {e}') # Shows error exit() # Exits program if settings are not found def __about(self): 'Opens README.md' if os.path.isfile(r'README.md'): # If file has not been deleted os.system(r'README.md') # Opens README.md with an adequate program like notepad else: # If file has been deleted or cannot be found messagebox.showerror(title='Fatal Error', message=f"File 'README.MD' not found.") # Shows error def __licence(self): 'Opens the LICENCE.md' if os.path.isfile(r'LICENCE.md'): # If file has not been deleted os.system(r'LICENCE.md') # Opens README.md with an adequate program like notepad else: # If file has been deleted or cannot be found messagebox.showerror(title='Fatal Error', message=f"File 'LICENCE.MD' not found.") # Shows error root = tkinter.Tk() # Defines the main window root.title('Sudoku Solver') # Sets the title of the window root.iconbitmap(r'resources\sudoku_icon.ico') # Sets the icon for the window root.resizable('False', 'False') # Disables resizing root.config(bg='#212121') GraphicalInterface(root) # GUI instance is created root.mainloop()
StarcoderdataPython
3524060
<filename>src/the_tale/the_tale/game/heroes/admin.py<gh_stars>0 import smart_imports smart_imports.all() class HeroAdmin(django_admin.ModelAdmin): list_display = ('id', 'name', 'clan_id', 'is_alive', 'health', 'account') readonly_fields = ('created_at_turn', 'saved_at_turn', 'saved_at', 'account') def name(self, obj): from . import logic return logic.load_hero(hero_model=obj).name class HeroPreferencesAdmin(django_admin.ModelAdmin): list_display = ('id', 'hero', 'energy_regeneration_type', 'mob', 'place', 'friend', 'enemy', 'equipment_slot') django_admin.site.register(models.Hero, HeroAdmin) django_admin.site.register(models.HeroPreferences, HeroPreferencesAdmin)
StarcoderdataPython
1873590
<filename>vujade/vujade_yaml.py """ Dveloper: vujadeyoon E-mail: <EMAIL> Github: https://github.com/vujadeyoon/vujade Title: vujade_videocv.py Description: A module for yaml. """ import yaml class vujade_yaml(): def __init__(self, _path_filename): super(vujade_yaml, self).__init__() self.path_filename = _path_filename def read(self): with open(self.path_filename) as f: data = yaml.load(f, Loader=yaml.FullLoader) return data def write(self, _dict_data): with open(self.path_filename, 'w') as f: yaml.dump(_dict_data, f)
StarcoderdataPython
5147223
<reponame>aogunwoolu/HRDL<gh_stars>0 import numpy as np import matplotlib.pyplot as plt from matplotlib import style # changes the matplotlib's figure to black (optional) style.use('dark_background') class TradingGraph: def __init__(self, dfs, title=None): self.dfs = dfs # Needed to be able to iteratively update the figure plt.ion() # Define our subplots self.fig, self.axs = plt.subplots(2, 2) # Show the plots plt.show() def plot_candles(self, ax, ohlc, idx): # iterate over each ohlc value along with the index for row, ix in zip(ohlc, idx): if row[3] < row[0]: clr = "red" else: clr = "green" # plots a thin line to represent high and low values ax.plot([ix, ix], [row[1], row[2]], lw=1, color=clr) # plot a wider line to represent open and close ax.plot([ix, ix], [row[3], row[0]], lw=3, color=clr) def render_prices(self, current_step, lbw): for splot, df in zip(self.axs.flatten(), self.dfs): splot.clear() step_range = range(current_step - lbw, current_step) idx = np.array(step_range) # prepare a 3-d numpy array to be used by our plot_candles function candlesticks = zip(df['open'].values[step_range], df['high'].values[step_range], df['low'].values[step_range], df['close'].values[step_range]) # Plot price using candlestick graph self.plot_candles(splot, candlesticks, idx) def render_trades(self, current_step, lbw, trades): for splot, coin in zip(self.axs.flatten(), trades): for trade in coin: if current_step > trade[1] > current_step - lbw: # plot the point at which the trade happened if trade[0] == 'buy': clr = 'red' splot.plot(trade[1], trade[2], 'ro') else: clr = 'green' splot.plot(trade[1], trade[2], 'go') # the plotted dot won't appear after the look back window is passed so a horizontal line keeps tracks at any time splot.hlines(trade[2], current_step - lbw, current_step, linestyle='dashed', colors=[clr]) def render(self, current_step, window_size, trades): self.render_prices(current_step, window_size) self.render_trades(current_step, window_size, trades) # the draw function redraws the figure after all plots have been executed self.fig.canvas.draw() self.fig.canvas.flush_events() # the pause is necessary to view the frame and allow the live updating mechanism on our figure plt.pause(0.1) def close(self): plt.close()
StarcoderdataPython
11396644
#!/usr/bin/env python3 # <NAME> # based off of Tdulcet's 'mprime.exp' # Python3 exp.py <User ID> <Computer name> <Type of work> <idle time to run> # Note: * pexpect has quirks about nonempty ()s (e.g., (y)), *s, inline ''s, or +s. import sys from time import sleep import subprocess # Potentially installing dependency try: import pexpect except ImportError as error: print("Installing pexpect...") p = subprocess.run('pip install pexpect', shell=True) import pexpect # Prerequisites, gained from mprime.py USERID, COMPUTER, TYPE = sys.argv[1], sys.argv[2], sys.argv[3] child = pexpect.spawn('./mprime -m') # starts shell to interact with child.logfile = sys.stdout.buffer # enables output to screen (Python 3) expectDict = {"Join Gimps?": "y", "Use PrimeNet to get work and report results": "y", "Your user ID or": USERID, "Optional computer name": COMPUTER, "Type of work to get": TYPE, "Upload bandwidth limit in Mbps": "10000", "Skip advanced resource settings": "n", "Optional directory to hold": "", "Your choice:": 5, pexpect.TIMEOUT: "", # "Use the following values to select a work type:": "", "Done communicating with server.": "\x03", "Choose Test/Continue to restart.": "5"} expects = list(expectDict.keys()) responses = list(expectDict.values()) while True: try: sleep(2) index = child.expect(expects, timeout=2) child.sendline(str(responses[index])) except pexpect.exceptions.EOF: break
StarcoderdataPython
152533
<reponame>ergs/transmutagen try: from . import py_solve del py_solve except ImportError: raise ImportError("Run 'python -m transmutagen.gensolve --py-solve' and 'setup.py build_ext --inplace' to generate the module") from .py_solve import (N, NNZ, IJ, NUCS, NUCS_IDX, ROWS, COLS, ones, flatten_sparse_matrix, csr_from_flat, asflat, solve, diag_add, dot, scalar_times_vector) __all__ = ['N', 'NNZ', 'IJ', 'NUCS', 'NUCS_IDX', 'ROWS', 'COLS', 'ones', 'flatten_sparse_matrix', 'csr_from_flat', 'asflat', 'solve', 'diag_add', 'dot', 'scalar_times_vector']
StarcoderdataPython
9785893
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 img = cv2.imread(r'd:\flappybird\atlas.png') cv2.namedWindow('Image') cv2.imshow('Image',img) cv2.waitKey(0) cv2.destroyAllWindows()
StarcoderdataPython
5004481
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.exceptions import NotFound # from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated from .models import Stock from .serializers.common import StockSerializer from .serializers.populated import PopulatedStockSerializer from django.db.models import Max # Create your views here. class StockListView(APIView): # permission_classes = (IsAuthenticatedOrReadOnly,) def get(self, _request): stock_items = Stock.objects.all() serialized_stock_items = StockSerializer(stock_items, many=True) print("✅ all stock items found") return Response(serialized_stock_items.data, status=status.HTTP_200_OK) def post(self, request): stock_item_to_add = StockSerializer(data=request.data) if stock_item_to_add.is_valid(): stock_item_to_add.save() print("✅ stock item created") return Response(stock_item_to_add.data, status=status.HTTP_201_CREATED) return Response(stock_item_to_add.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY) class StockDetailView(APIView): # permission_classes = (IsAuthenticatedOrReadOnly,) def get_stock_item(self, pk): try: print(f"✅ stock item ({pk}) found") return Stock.objects.get(pk=pk) except Stock.DoesNotExist: print("🆘 stock item not found") raise NotFound(detail="🆘 stock item not found") def get(self, _request, pk): stock_item = self.get_stock_item(pk=pk) serialized_stock_item = PopulatedStockSerializer(stock_item) return Response(serialized_stock_item.data, status=status.HTTP_200_OK) def put(self, request, pk): stock_item_to_edit = self.get_stock_item(pk=pk) updated_stock_item = StockSerializer(stock_item_to_edit, data=request.data) if updated_stock_item.is_valid(): updated_stock_item.save() print(f"✅ stock item ({pk}) edited") return Response(updated_stock_item.data, status=status.HTTP_202_ACCEPTED) return Response(updated_stock_item.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY) def delete(self, _request, pk): stock_item_to_delete = self.get_stock_item(pk=pk) stock_item_to_delete.delete() print(f"✅ stock item ({pk}) deleted") return Response(status=status.HTTP_204_NO_CONTENT) class GenerateNewStockNumberIndex(APIView): def get(self, _request): highest_stock_num = Stock.objects.all().aggregate(Max('stock_num')) next_highest_index = highest_stock_num["stock_num__max"] + 1 print(f"✅ new stock number generated: {next_highest_index} ") return Response(next_highest_index, status=status.HTTP_200_OK)
StarcoderdataPython
1997979
<gh_stars>0 import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import os import random import datetime import re import math import logging from collections import OrderedDict import multiprocessing import numpy as np import tensorflow as tf import tensorflow.keras import tensorflow.keras.backend as K import tensorflow.keras.layers as KL # import tensorflow.keras.engine as KE import tensorflow.keras.models as KM import utils print(os.getcwd()) import sys sys.path.append('samples/coco/') sys.path.append('coco/PythonAPI') sys.path.append('.') import coco from mrcnn.my_model import conv_block from mrcnn.my_model import identity_block from mrcnn.my_model import BatchNorm input_image = np.zeros((10, 100, 100, 3)) input_image = tf.cast(input_image, tf.float32) architecture = "resnet50" stage5=False train_bn=True # identity_block test x = KL.ZeroPadding2D((3, 3))(input_image) x = KL.Conv2D(64, (7, 7), strides=(2, 2), name='conv1', use_bias=True)(x) x = BatchNorm(name='bn_conv1')(x, training=train_bn) x = KL.Activation('relu')(x) C1 = x = KL.MaxPooling2D((3, 3), strides=(2, 2), padding="same")(x) # Stage 2 x = conv_block(x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1), train_bn=train_bn) x = identity_block(x, 3, [64, 64, 256], stage=2, block='b', train_bn=train_bn) C2 = x = identity_block(x, 3, [64, 64, 256], stage=2, block='c', train_bn=train_bn) # Stage 3 x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', train_bn=train_bn) x = identity_block(x, 3, [128, 128, 512], stage=3, block='b', train_bn=train_bn) x = identity_block(x, 3, [128, 128, 512], stage=3, block='c', train_bn=train_bn) C3 = x = identity_block(x, 3, [128, 128, 512], stage=3, block='d', train_bn=train_bn) # Stage 4 x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', train_bn=train_bn) block_count = {"resnet50": 5, "resnet101": 22}[architecture] for i in range(block_count): x = identity_block(x, 3, [256, 256, 1024], stage=4, block=chr(98 + i), train_bn=train_bn) C4 = x # Stage 5 if stage5: x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', train_bn=train_bn) x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', train_bn=train_bn) C5 = x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', train_bn=train_bn) else: C5 = None [C1, C2, C3, C4, C5]
StarcoderdataPython
5032669
<filename>src/infi/asi/cdb/control.py from infi.instruct import * from infi.instruct.buffer import Buffer, bytes_ref, be_int_field # sam5r07: 5.2 (page 70) class Control(Struct): _fields_ = BitFields( BitPadding(2), # 0-1: obsolete BitField("naca", 1), BitPadding(3), # 3-5: reserved BitField("vendor_specific", 2), # 6-7: vendor specific ) DEFAULT_CONTROL = Control(vendor_specific=0, naca=0) class ControlBuffer(Buffer): naca = be_int_field(where=bytes_ref[0].bits[2:3]) vendor_specific = be_int_field(where=bytes_ref[0].bits[6:8]) DEFAULT_CONTROL_BUFFER = ControlBuffer(vendor_specific=0, naca=0)
StarcoderdataPython
8093276
<filename>01/01.py print('Hola, mundo!')
StarcoderdataPython
3593261
import pytest from unittest import mock from django.core.exceptions import ValidationError from awx.main.models import ( UnifiedJob, InventoryUpdate, InventorySource, ) def test_cancel(mocker): with mock.patch.object(UnifiedJob, 'cancel', return_value=True) as parent_cancel: iu = InventoryUpdate() iu.save = mocker.MagicMock() build_job_explanation_mock = mocker.MagicMock() iu._build_job_explanation = mocker.MagicMock(return_value=build_job_explanation_mock) iu.cancel() parent_cancel.assert_called_with(is_chain=False, job_explanation=None) def test__build_job_explanation(): iu = InventoryUpdate(id=3, name='I_am_an_Inventory_Update') job_explanation = iu._build_job_explanation() assert job_explanation == 'Previous Task Canceled: {"job_type": "%s", "job_name": "%s", "job_id": "%s"}' % ( 'inventory_update', 'I_am_an_Inventory_Update', 3, ) class TestControlledBySCM: def test_clean_source_path_valid(self): inv_src = InventorySource(source_path='/not_real/', source='scm') inv_src.clean_source_path() @pytest.mark.parametrize( 'source', [ 'ec2', 'manual', ], ) def test_clean_source_path_invalid(self, source): inv_src = InventorySource(source_path='/not_real/', source=source) with pytest.raises(ValidationError): inv_src.clean_source_path() def test_clean_update_on_launch_update_on_project_update(self): inv_src = InventorySource(update_on_project_update=True, update_on_launch=True, source='scm') with pytest.raises(ValidationError): inv_src.clean_update_on_launch()
StarcoderdataPython
392239
"""Contains classes and functions related to patterns/transformations. """ from __future__ import print_function import copy import dace import inspect from typing import Dict from dace.sdfg import SDFG, SDFGState from dace.sdfg import utils as sdutil, propagation from dace.sdfg.graph import SubgraphView from dace.properties import make_properties, Property, DictProperty from dace.registry import make_registry from dace.sdfg import graph as gr, nodes as nd from dace.dtypes import ScheduleType import networkx as nx from networkx.algorithms import isomorphism as iso from typing import Dict, List, Tuple, Type, Union @make_registry @make_properties class Transformation(object): """ Base class for transformations, as well as a static registry of transformations, where new transformations can be added in a decentralized manner. New transformations are registered with ``Transformation.register`` (or ``dace.registry.autoregister_params``) with two optional boolean keyword arguments: ``singlestate`` (default: False) and ``strict`` (default: False). If ``singlestate`` is True, the transformation operates on a single state; otherwise, it will be matched over an entire SDFG. If ``strict`` is True, this transformation will be considered strict (i.e., always important to perform) and will be performed automatically as part of SDFG strict transformations. """ # Properties sdfg_id = Property(dtype=int, category="(Debug)") state_id = Property(dtype=int, category="(Debug)") _subgraph = DictProperty(key_type=int, value_type=int, category="(Debug)") expr_index = Property(dtype=int, category="(Debug)") @staticmethod def annotates_memlets(): """ Indicates whether the transformation annotates the edges it creates or modifies with the appropriate memlets. This determines whether to apply memlet propagation after the transformation. """ return False @staticmethod def expressions(): """ Returns a list of Graph objects that will be matched in the subgraph isomorphism phase. Used as a pre-pass before calling `can_be_applied`. @see Transformation.can_be_applied """ raise NotImplementedError @staticmethod def can_be_applied(graph, candidate, expr_index, sdfg, strict=False): """ Returns True if this transformation can be applied on the candidate matched subgraph. :param graph: SDFGState object if this Transformation is single-state, or SDFG object otherwise. :param candidate: A mapping between node IDs returned from `Transformation.expressions` and the nodes in `graph`. :param expr_index: The list index from `Transformation.expressions` that was matched. :param sdfg: If `graph` is an SDFGState, its parent SDFG. Otherwise should be equal to `graph`. :param strict: Whether transformation should run in strict mode. :return: True if the transformation can be applied. """ raise NotImplementedError @staticmethod def match_to_str(graph, candidate): """ Returns a string representation of the pattern match on the candidate subgraph. Used when identifying matches in the console UI. """ raise NotImplementedError def __init__(self, sdfg_id, state_id, subgraph, expr_index): """ Initializes an instance of Transformation. :param sdfg_id: A unique ID of the SDFG. :param state_id: The node ID of the SDFG state, if applicable. :param subgraph: A mapping between node IDs returned from `Transformation.expressions` and the nodes in `graph`. :param expr_index: The list index from `Transformation.expressions` that was matched. :raise TypeError: When transformation is not subclass of Transformation. :raise TypeError: When state_id is not instance of int. :raise TypeError: When subgraph is not a dict of dace.sdfg.nodes.Node : int. """ self.sdfg_id = sdfg_id self.state_id = state_id for value in subgraph.values(): if not isinstance(value, int): raise TypeError('All values of ' 'subgraph' ' dictionary must be ' 'instances of int.') # Serializable subgraph with node IDs as keys expr = self.expressions()[expr_index] self._subgraph = {expr.node_id(k): v for k, v in subgraph.items()} self._subgraph_user = subgraph self.expr_index = expr_index @property def subgraph(self): return self._subgraph_user def __lt__(self, other): """ Comparing two transformations by their class name and node IDs in match. Used for ordering transformations consistently. """ if type(self) != type(other): return type(self).__name__ < type(other).__name__ self_ids = iter(self.subgraph.values()) other_ids = iter(self.subgraph.values()) try: self_id = next(self_ids) except StopIteration: return True try: other_id = next(other_ids) except StopIteration: return False self_end = False while self_id is not None and other_id is not None: if self_id != other_id: return self_id < other_id try: self_id = next(self_ids) except StopIteration: self_end = True try: other_id = next(other_ids) except StopIteration: if self_end: # Transformations are equal return False return False if self_end: return True def apply_pattern(self, sdfg): """ Applies this transformation on the given SDFG. """ self.apply(sdfg) if not self.annotates_memlets(): propagation.propagate_memlets_sdfg(sdfg) def __str__(self): return type(self).__name__ def modifies_graph(self): return True def print_match(self, sdfg): """ Returns a string representation of the pattern match on the given SDFG. Used for printing matches in the console UI. """ if not isinstance(sdfg, dace.SDFG): raise TypeError("Expected SDFG, got: {}".format( type(sdfg).__name__)) if self.state_id == -1: graph = sdfg else: graph = sdfg.nodes()[self.state_id] string = type(self).__name__ + ' in ' string += type(self).match_to_str(graph, self.subgraph) return string def to_json(self, parent=None): props = dace.serialize.all_properties_to_json(self) return { 'type': 'Transformation', 'transformation': type(self).__name__, **props } @staticmethod def from_json(json_obj, context=None): xform = next(ext for ext in Transformation.extensions().keys() if ext.__name__ == json_obj['transformation']) # Recreate subgraph expr = xform.expressions()[json_obj['expr_index']] subgraph = {expr.node(int(k)): int(v) for k, v in json_obj['_subgraph'].items()} # Reconstruct transformation ret = xform(json_obj['sdfg_id'], json_obj['state_id'], subgraph, json_obj['expr_index']) context = context or {} context['transformation'] = ret dace.serialize.set_properties_from_json( ret, json_obj, context=context, ignore_properties={'transformation', 'type'}) return ret class ExpandTransformation(Transformation): """Base class for transformations that simply expand a node into a subgraph, and thus needs only simple matching and replacement functionality. Subclasses only need to implement the method "expansion". """ @classmethod def expressions(clc): return [sdutil.node_path_graph(clc._match_node)] @staticmethod def can_be_applied(graph: dace.sdfg.graph.OrderedMultiDiConnectorGraph, candidate: Dict[dace.sdfg.nodes.Node, int], expr_index: int, sdfg, strict: bool = False): # All we need is the correct node return True @classmethod def match_to_str(clc, graph: dace.sdfg.graph.OrderedMultiDiConnectorGraph, candidate: Dict[dace.sdfg.nodes.Node, int]): node = graph.nodes()[candidate[clc._match_node]] return str(node) @staticmethod def expansion(node): raise NotImplementedError("Must be implemented by subclass") @staticmethod def postprocessing(sdfg, state, expansion): pass def apply(self, sdfg, *args, **kwargs): state = sdfg.nodes()[self.state_id] node = state.nodes()[self.subgraph[type(self)._match_node]] expansion = type(self).expansion(node, state, sdfg, *args, **kwargs) if isinstance(expansion, dace.SDFG): # Modify internal schedules according to node schedule if node.schedule != ScheduleType.Default: for nstate in expansion.nodes(): topnodes = nstate.scope_dict(node_to_children=True)[None] for topnode in topnodes: if isinstance(topnode, (nd.EntryNode, nd.LibraryNode)): topnode.schedule = node.schedule expansion = state.add_nested_sdfg(expansion, sdfg, node.in_connectors, node.out_connectors, name=node.name, debuginfo=node.debuginfo) elif isinstance(expansion, dace.sdfg.nodes.CodeNode): expansion.debuginfo = node.debuginfo else: raise TypeError("Node expansion must be a CodeNode or an SDFG") expansion.environments = copy.copy( set(map(lambda a: a.__name__, type(self).environments))) sdutil.change_edge_dest(state, node, expansion) sdutil.change_edge_src(state, node, expansion) state.remove_node(node) type(self).postprocessing(sdfg, state, expansion) @make_registry class SubgraphTransformation(object): """ Base class for transformations that apply on arbitrary subgraphs, rather than matching a specific pattern. Subclasses need to implement the `match` and `apply` operations. """ @staticmethod def match(sdfg: SDFG, subgraph: SubgraphView) -> bool: """ Tries to match the transformation on a given subgraph, returning True if this transformation can be applied. :param sdfg: The SDFG that includes the subgraph. :param subgraph: The SDFG or state subgraph to try to apply the transformation on. :return: True if the subgraph can be transformed, or False otherwise. """ pass def apply(self, sdfg: SDFG, subgraph: SubgraphView): """ Applies the transformation on the given subgraph. :param sdfg: The SDFG that includes the subgraph. :param subgraph: The SDFG or state subgraph to apply the transformation on. """ pass # Module functions ############################################################ def collapse_multigraph_to_nx( graph: Union[gr.MultiDiGraph, gr.OrderedMultiDiGraph]) -> nx.DiGraph: """ Collapses a directed multigraph into a networkx directed graph. In the output directed graph, each node is a number, which contains itself as node_data['node'], while each edge contains a list of the data from the original edges as its attribute (edge_data[0...N]). :param graph: Directed multigraph object to be collapsed. :return: Collapsed directed graph object. """ # Create the digraph nodes. digraph_nodes: List[Tuple[int, Dict[str, nd.Node]]] = ([None] * graph.number_of_nodes()) node_id = {} for i, node in enumerate(graph.nodes()): digraph_nodes[i] = (i, {'node': node}) node_id[node] = i # Create the digraph edges. digraph_edges = {} for edge in graph.edges(): src = node_id[edge.src] dest = node_id[edge.dst] if (src, dest) in digraph_edges: edge_num = len(digraph_edges[src, dest]) digraph_edges[src, dest].update({edge_num: edge.data}) else: digraph_edges[src, dest] = {0: edge.data} # Create the digraph result = nx.DiGraph() result.add_nodes_from(digraph_nodes) result.add_edges_from(digraph_edges) return result def type_match(node_a, node_b): """ Checks whether the node types of the inputs match. :param node_a: First node. :param node_b: Second node. :return: True if the object types of the nodes match, False otherwise. :raise TypeError: When at least one of the inputs is not a dictionary or does not have a 'node' attribute. :raise KeyError: When at least one of the inputs is a dictionary, but does not have a 'node' key. """ return isinstance(node_a['node'], type(node_b['node'])) def match_pattern(state: SDFGState, pattern: Type[Transformation], sdfg: SDFG, node_match=type_match, edge_match=None, strict=False): """ Returns a list of single-state Transformations of a certain class that match the input SDFG. :param state: An SDFGState object to match. :param pattern: Transformation type to match. :param sdfg: The SDFG to match in. :param node_match: Function for checking whether two nodes match. :param edge_match: Function for checking whether two edges match. :param strict: Only match transformation if strict (i.e., can only improve the performance/reduce complexity of the SDFG). :return: A list of Transformation objects that match. """ # Collapse multigraph into directed graph # Handling VF2 in networkx for now digraph = collapse_multigraph_to_nx(state) for idx, expression in enumerate(pattern.expressions()): cexpr = collapse_multigraph_to_nx(expression) graph_matcher = iso.DiGraphMatcher(digraph, cexpr, node_match=node_match, edge_match=edge_match) for subgraph in graph_matcher.subgraph_isomorphisms_iter(): subgraph = { cexpr.nodes[j]['node']: state.node_id(digraph.nodes[i]['node']) for (i, j) in subgraph.items() } try: match_found = pattern.can_be_applied(state, subgraph, idx, sdfg, strict=strict) except Exception as e: print('WARNING: {p}::can_be_applied triggered a {c} exception:' ' {e}'.format(p=pattern.__name__, c=e.__class__.__name__, e=e)) match_found = False if match_found: yield pattern(sdfg.sdfg_id, sdfg.node_id(state), subgraph, idx) # Recursive call for nested SDFGs for node in state.nodes(): if isinstance(node, nd.NestedSDFG): sub_sdfg = node.sdfg for sub_state in sub_sdfg.nodes(): yield from match_pattern(sub_state, pattern, sub_sdfg, strict=strict) def match_stateflow_pattern(sdfg, pattern, node_match=type_match, edge_match=None, strict=False): """ Returns a list of multi-state Transformations of a certain class that match the input SDFG. :param sdfg: The SDFG to match in. :param pattern: Transformation object to match. :param node_match: Function for checking whether two nodes match. :param edge_match: Function for checking whether two edges match. :param strict: Only match transformation if strict (i.e., can only improve the performance/reduce complexity of the SDFG). :return: A list of Transformation objects that match. """ # Collapse multigraph into directed graph # Handling VF2 in networkx for now digraph = collapse_multigraph_to_nx(sdfg) for idx, expression in enumerate(pattern.expressions()): cexpr = collapse_multigraph_to_nx(expression) graph_matcher = iso.DiGraphMatcher(digraph, cexpr, node_match=node_match, edge_match=edge_match) for subgraph in graph_matcher.subgraph_isomorphisms_iter(): subgraph = { cexpr.nodes[j]['node']: sdfg.node_id(digraph.nodes[i]['node']) for (i, j) in subgraph.items() } try: match_found = pattern.can_be_applied(sdfg, subgraph, idx, sdfg, strict) except Exception as e: print('WARNING: {p}::can_be_applied triggered a {c} exception:' ' {e}'.format(p=pattern.__name__, c=e.__class__.__name__, e=e)) match_found = False if match_found: yield pattern(sdfg.sdfg_id, -1, subgraph, idx) # Recursive call for nested SDFGs for state in sdfg.nodes(): for node in state.nodes(): if isinstance(node, nd.NestedSDFG): yield from match_stateflow_pattern(node.sdfg, pattern, strict=strict)
StarcoderdataPython
8163740
<reponame>dhruvmanila/remove-print-statements from pathlib import Path from click.testing import CliRunner from remove_print_statements import main def test_noop() -> None: runner = CliRunner() result = runner.invoke(main) assert result.exit_code == 0 assert not result.stdout_bytes assert not result.stderr_bytes def test_verbose_output(tmp_path: str) -> None: runner = CliRunner() newlines = 10 with runner.isolated_filesystem(tmp_path) as temp_dir: dir = Path(temp_dir) dir.joinpath("hello.py").write_text( 'print("hello")' + "\n" * newlines + 'print("world")' ) result = runner.invoke(main, ["hello.py", "--verbose"]) assert result.exit_code == 0 assert not result.stderr_bytes assert result.stdout_bytes assert 'hello.py\n 1 print("hello")\n 11 print("world")' in result.output def test_ignore_single_files(tmp_path: str) -> None: runner = CliRunner() filenames = ("hello1.py", "hello2.py", "hello3.py") content = "print('hello')\n" with runner.isolated_filesystem(tmp_path) as temp_dir: dir = Path(temp_dir) for filename in filenames: dir.joinpath(filename).write_text(content) result = runner.invoke(main, ["--ignore", "hello2.py", *filenames]) assert result.exit_code == 0 assert not result.stderr_bytes assert result.stdout_bytes assert "2 files transformed" in result.output assert "2 print statements removed" in result.output assert content in dir.joinpath(filenames[1]).read_text() def test_ignore_multiple_files(tmp_path: str) -> None: runner = CliRunner() filenames = ("hello1.py", "hello2.py", "hello3.py") content = "print('hello')\n" with runner.isolated_filesystem(tmp_path) as temp_dir: dir = Path(temp_dir) for filename in filenames: dir.joinpath(filename).write_text(content) result = runner.invoke( main, ["--ignore", "hello2.py", "--ignore", "hello3.py", *filenames] ) assert result.exit_code == 0 assert not result.stderr_bytes assert result.stdout_bytes assert "1 file transformed" in result.output assert "1 print statement removed" in result.output assert content in dir.joinpath(filenames[1]).read_text() assert content in dir.joinpath(filenames[2]).read_text() def test_no_print_statements(tmp_path: str) -> None: runner = CliRunner() filenames = ("hello1.py", "hello2.py", "hello3.py") content = "a = 5\n" with runner.isolated_filesystem(tmp_path) as temp_dir: dir = Path(temp_dir) for filename in filenames: dir.joinpath(filename).write_text(content) result = runner.invoke(main, filenames) assert result.exit_code == 0 assert not result.stderr_bytes assert result.stdout_bytes assert "No print statements found" in result.output def test_transform_failure(tmp_path: str) -> None: runner = CliRunner() with runner.isolated_filesystem(tmp_path) as temp_dir: dir = Path(temp_dir) dir.joinpath("hello.py").write_text('print("hello"\n') result = runner.invoke(main, ["hello.py"]) assert result.exit_code == 123 assert result.stdout_bytes assert "1 file failed to transform" in result.output
StarcoderdataPython
378154
<gh_stars>1-10 #!/usr/bin/env python3 class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ d = {} for w in sorted(strs): k = tuple(sorted(w)) d[k] = d.get(k, []) + [w] return list(d.values()) if __name__ == "__main__": print(Solution().groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
StarcoderdataPython
9690894
import cv2 import numpy as np cap = cv2.VideoCapture(0) while True: _, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) lower_red = np.array([150,150,50]) upper_red = np.array([180,255,150]) mask = cv2.inRange(hsv, lower_red, upper_red) res = cv2.bitwise_and(frame, frame, mask=mask) # smoothing kernel = np.ones((15,15), np.float32)/225 smoothed = cv2.filter2D(res, -1, kernel) # blurring gaus = cv2.GaussianBlur(res, (15,15), 0) median = cv2.medianBlur(res, 15) bilateral = cv2.bilateralFilter(res, 15, 75, 75) cv2.imshow('frame',frame) cv2.imshow('res',res) #cv2.imshow('smoothed',smoothed) # not so great #cv2.imshow('gaus',gaus) #cv2.imshow('median',median) cv2.imshow('bilateral',bilateral) if cv2.waitKey(5) == 27: break cv2.destroyAllWindows() cap.release()
StarcoderdataPython
38723
<reponame>M2I-HABET/ahac2020workshop import rot2proG import serial import math import time import requests from queue import Queue from threading import Thread def _parse_degrees(nmea_data): # Parse a NMEA lat/long data pair 'dddmm.mmmm' into a pure degrees value. # Where ddd is the degrees, mm.mmmm is the minutes. if nmea_data is None or len(nmea_data) < 3: return None raw = float(nmea_data) deg = raw // 100 minutes = raw % 100 return deg + minutes/60 def MainLoop(): flightID = "fa0b701b-e40a-4711-94c0-09fedd0b1cac" scriptID = "429c4f46-140b-4db4-8cf9-6acc88f5b018" postURL = "http://10.29.189.44/REST/V1/flight_location" postURLRaw = "http://10.29.189.44/REST/V1/flight_data_raw" run = True lora = serial.Serial(port="COM27", baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=2) lora.flushInput() lora.flushOutput() while run: line = "" invalid = True data = "" latB = '' lonB = '' alt = '' rssi = '' while invalid: # Or: while ser.inWaiting(): if lora.in_waiting: print("in wating: "+str(lora.in_waiting)) try: line = lora.readline().decode("utf-8") lineToSave = line if("rssi" in lineToSave): rssi = lineToSave.strip("rssi:").strip("\r\n") print(rssi) try: params = {'scriptID': scriptID, 'flightID': flightID, 'gps':lineToSave} r = requests.post(url = postURLRaw, data = params, timeout=5) print(r.text) except Exception as e: print(e) line =lineToSave.strip('\n').strip('\r') invalid = False except: invalid = True print("bad Unicode") continue #print(line) vals = line.split(',') time.sleep(.1) #print(line) if "GPGGA" not in line: continue try: data = [vals[0],_parse_degrees(vals[3]),vals[4],_parse_degrees(vals[5]),vals[6],vals[10]] except: continue if data[2] == "S": data[1] = -1* data[1] if data[4] == "W": data[3] = -1*data[3] print(data) try: latB = float(data[1])#43.02700680709 lonB = float(data[3])#-94.6533878648 alt = float(data[5]) if(latB == 0): invalid = True params = {'scriptID': scriptID, 'flightID': flightID, 'time': int(time.time()), 'lat': latB, 'lon': lonB, 'alt':alt, 'rssi': rssi} try: r = requests.post(url = postURL, data = params, timeout=5) print(r.text) except Exception as e: print(e) print("\n\n\n\n\n NOT SENT \n\n\n\n") invalid = False except Exception as e: print(e) print("bad String") if __name__ == "__main__": MainLoop()
StarcoderdataPython
5016202
<gh_stars>0 import csv import json import argparse import os.path from LogManager import logger, initConsoleLogging CSV_FIELD_MAP = [ ('IA #', 'number'), ('NAME', 'name'), ('TYPE', 'type'), ('DATE CREATED', 'date'), ('STATUS', 'status') ] """ This python module will convert ICR Json file into Csv for Visualization """ class ICRJsonToCsv (object): def __init__(self): pass def generateCsvByJson(self, inputJsonFile, outputCsvFile): with open(inputJsonFile, 'r') as inJson: icrJson = json.load(inJson) with open(outputCsvFile, 'w') as outCsv: csvWrt = csv.writer(outCsv, lineterminator="\n") csvWrt.writerow([x[1] for x in CSV_FIELD_MAP]) CSV_FIELD_NAME = [x[0] for x in CSV_FIELD_MAP] for icrItem in icrJson: curRow = [] isValidData = True for fld in CSV_FIELD_NAME: if fld in icrItem: curRow.append(icrItem[fld]) else: isValidData = False break if isValidData: csvWrt.writerow(curRow) def generatePackageDependencyJson(self, inputJsonFile, outputDepFile): outDep = {} with open(inputJsonFile, 'r') as inJson: icrJson = json.load(inJson) for icrItem in icrJson: curIaNum = icrItem['IA #'] if 'STATUS' not in icrItem or icrItem['STATUS'] != 'Active': continue if 'CUSTODIAL PACKAGE' in icrItem: curPkg = icrItem['CUSTODIAL PACKAGE'] outDep.setdefault(curPkg,{}) if 'SUBSCRIBING PACKAGE' in icrItem: for subPkg in icrItem['SUBSCRIBING PACKAGE']: if 'SUBSCRIBING PACKAGE' in subPkg: subPkgName = subPkg['SUBSCRIBING PACKAGE'] subDep = outDep.setdefault(subPkgName, {}).setdefault('dependencies',{}) subDep.setdefault(curPkg, []).append(curIaNum) curDep = outDep.setdefault(curPkg, {}).setdefault('dependents', {}) curDep.setdefault(subPkgName, []).append(curIaNum) with open(outputDepFile, 'w') as outJson: json.dump(outDep, outJson, indent=4) def createArgParser(): parser = argparse.ArgumentParser(description='Convert VistA ICR JSON to csv for Visualization') parser.add_argument('icrJsonFile', help='path to the VistA ICR JSON file') parser.add_argument('-csv', '--outCsvFile', help='path to the output csv file') parser.add_argument('-dep', '--pkgDepJsonFile', help='path to the output package dependency JSON file') return parser if __name__ == '__main__': parser = createArgParser() result = parser.parse_args() initConsoleLogging() # initConsoleLogging(logging.DEBUG) if result.icrJsonFile: icrJsonToHtml = ICRJsonToCsv() if result.outCsvFile: icrJsonToHtml.generateCsvByJson(result.icrJsonFile, result.outCsvFile) if result.pkgDepJsonFile: icrJsonToHtml.generatePackageDependencyJson(result.icrJsonFile, result.pkgDepJsonFile)
StarcoderdataPython
27270
from mbus.record import ValueRecord from machine import RTC import ubinascii import random import time import re class MBusDevice: """Class that encapulates/emulates a single MBus device""" def __init__(self, primary_address, secondary_address, manufacturer, meter_type): self._primary_address = primary_address self._secondary_address = secondary_address self._manufacturer = manufacturer self._type = meter_type self._access_number = random.randint(0,255) self._records = [] self._rsp_ud2 = [] self._selected = False self.rtc = RTC() def get_time(self): """Returns the current time, as known by this MBus device""" return "%02u:%02u:%02u (%d)" % self.rtc.datetime()[4:8] def select(self): """Puts this MBus device in the 'selected' state""" if not self._selected: self._selected = True self.log("device {} is now selected".format(self._secondary_address)) def deselect(self): """Puts this MBus device in an 'unselected' state""" if self._selected: self._selected = False self.log("device {} is now deselected".format(self._secondary_address)) def is_selected(self): """Returns the current selection state for this MBus device""" return self._selected def log(self, message): print("[{}][debug ] {}".format(self.get_time(),message)) def update(self): for record in self._records: record.update() self.log("Device with ID {} has updated its data".format(self._secondary_address)) self.seal() def add_record(self,record): self._records.append(record) def seal(self): self._rsp_ud2 = self.get_rsp_ud2() def get_primary_address(self): """Returns the primary address for this MBus device""" return self._primary_address def get_secondary_address(self): """Returns the secondary address for this MBus device""" return self._secondary_address def matches_secondary_address(self,search_string): """Returns true if the secondary address of this MBus device matches the provided search string""" pattern = re.compile(search_string.replace('f','[0-9]')) if pattern.match(self._secondary_address): return True return False def get_manufacturer_id(self): """Returns the manufacturer id for this MBus device""" return self._manufacturer def get_type(self): """Returns the MBus attribute 'type' for this MBus device""" return self._type def get_address_bytes(self): """Returns the secondary address for this MBus device, as a byte array""" resp_bytes = [] resp_bytes.append(self._secondary_address[6]) resp_bytes.append(self._secondary_address[7]) resp_bytes.append(self._secondary_address[4]) resp_bytes.append(self._secondary_address[5]) resp_bytes.append(self._secondary_address[2]) resp_bytes.append(self._secondary_address[3]) resp_bytes.append(self._secondary_address[0]) resp_bytes.append(self._secondary_address[1]) resp_str = [] resp_str.append(resp_bytes[0] + resp_bytes[1]) resp_str.append(resp_bytes[2] + resp_bytes[3]) resp_str.append(resp_bytes[4] + resp_bytes[5]) resp_str.append(resp_bytes[6] + resp_bytes[7]) ret = [x for x in resp_str] return ret def get_manufacturer_bytes(self): """Returns the manufacturer id for this MBus device, as a byte array""" manufacturer = self._manufacturer.upper() id = ((ord(manufacturer[0]) - 64) * 32 * 32 + (ord(manufacturer[1]) - 64) * 32 + (ord(manufacturer[2]) - 64)) if 0x0421 <= id <= 0x6b5a: return self.manufacturer_encode(id, 2) return False def manufacturer_encode(self, value, size): """Converts a manufacturer id to its byte equivalent""" if value is None or value == False: return None data = [] for i in range(0, size): data.append((value >> (i * 8)) & 0xFF) return data def calculate_checksum(self, message): """Calculates the checksum of the provided data""" return sum([int(x, 16) if type(x) == str else x for x in message]) & 0xFF def get_latest_values(self): return self._rsp_ud2 def get_rsp_ud2(self): """Generates a RSP_UD2 response message""" resp_bytes = [] resp_bytes.append(0x68) # start resp_bytes.append(0xFF) # length resp_bytes.append(0xFF) # length resp_bytes.append(0x68) # start resp_bytes.append(0x08) # C resp_bytes.append(self._primary_address) # A resp_bytes.append(0x72) # CI resp_bytes.extend(self.get_address_bytes()) resp_bytes.extend(self.get_manufacturer_bytes()) resp_bytes.append(0x01) # version resp_bytes.append(self._type) # medium (heat) resp_bytes.append(self._access_number) # access no resp_bytes.append(0x00) # status resp_bytes.append(0x00) # configuration 1 resp_bytes.append(0x00) # configuration 2 for record in self._records: resp_bytes.extend(record.get_bytes()) resp_bytes.append(self.calculate_checksum(resp_bytes[4:])) resp_bytes.append(0x16) # stop length = len(resp_bytes) - 9 + 3 resp_bytes[1] = length resp_bytes[2] = length ret = ["{:>2}".format(hex(x)[2:]).replace(' ', '0') if type(x) == int else x for x in resp_bytes] if self._access_number < 255: self._access_number = self._access_number + 1 else: self._access_number = 1 return ''.join(ret).upper()
StarcoderdataPython
9757495
import tensorflow as tf from tensorflow import DType NODE_FEATURES = 'node_features' EDGE_FEATURES = 'edge_features' def TensorGraph(node_features, edge_features): """Returns a tensor graph instance. This function simply returns a dictionary with the relevant structure to represent a graph of Tensorflow Tensors. Arguments: node_features: A tensor of node features. edge_features: A tensor of edge features. """ return { NODE_FEATURES: node_features, EDGE_FEATURES: edge_features } class TensorGraphShape: """Represents the shape of a TensorGraph. The shape of a TensorGraph encompases all the information that describes the graph's underlying tensors. This includes what tensors are specified, their dimensions, as well as how they are represented. Arguments: num_nodes: The number of nodes in the graph, or None if unknown. node_dims: The number of features assigned to each node. edge_dims: The number of features assigned to each edge. node_dtype: The TensorFlow datatype for the node features. edge_dtype: The TensorFlow datatype for the edge features. """ def __init__(self, num_nodes: int = None, node_dims: int = 1, edge_dims: int = 1, node_dtype: DType = tf.float32, edge_dtype: DType = tf.float32): self.num_nodes = num_nodes self.node_dims = node_dims self.edge_dims = edge_dims self.node_dtype = node_dtype self.edge_dtype = edge_dtype def get_padding_shapes(self): return { NODE_FEATURES: (self.num_nodes, self.node_dims), EDGE_FEATURES: (self.edge_dims, self.num_nodes, self.num_nodes) } def get_padding_values(self): return { 'node_features': 0.0, 'edge_features': 0.0 } def map_node_features(graph, map_fn): features_in = graph[NODE_FEATURES] features_out = map_fn(features_in) return {**graph, NODE_FEATURES: features_out} def map_edge_features(graph, map_fn): features_in = graph[EDGE_FEATURES] features_out = map_fn(features_in) return {**graph, EDGE_FEATURES: features_out}
StarcoderdataPython
9627366
<reponame>adamkrekorian/Patient-Monitoring-Station-BME547<filename>test_monitor_gui.py import pytest import base64 import io import os from matplotlib import pyplot as plt import matplotlib.image as mpimg import filecmp @pytest.mark.parametrize('filename', [ ("images/acl1.jpg"), ("images/acl2.jpg"), ("images/upj1.jpg"), ("images/upj1.jpg"), ]) def test_save_b64_image(filename): """ Tests image decoder function The test_save_b64_image() function tests the ability of the image decoder function to decode an an encoded string back into an image file Args: filename (str): filepath to test image """ from monitor_gui import save_b64_image from patient_gui import read_file_as_b64 b64str = read_file_as_b64(filename) out_file = save_b64_image(b64str) answer = filecmp.cmp(filename, out_file) os.remove(out_file) assert answer is True
StarcoderdataPython
8046223
<reponame>samwel-chege/Neighborhood # Generated by Django 3.2.7 on 2021-09-27 08:55 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('neighbourhood', '0002_auto_20210925_0016'), ] operations = [ migrations.RenameField( model_name='resident', old_name='neighborhood', new_name='neighbourhood', ), ]
StarcoderdataPython
3203918
class Lock: """ synchronous lock that does not block""" def __init__(self): self._locked = False def acquire(self): if self._locked: return False else: self._locked = True return True def locked(self): return self._locked def release(self): self._locked = False # not checking if it was locked return True
StarcoderdataPython
6555281
from facenet_pytorch import InceptionResnetV1 from torch.utils.data import Dataset from torch.utils.data import DataLoader import numpy as np import torch import natsort from PIL import Image from pathlib import Path import logging logger = logging.getLogger(__name__) from torchvision.transforms import functional as F # from: https://github.com/timesler/facenet-pytorch/blob/master/models/mtcnn.py def fixed_image_standardization(image_tensor): processed_tensor = (image_tensor - 127.5) / 128.0 return processed_tensor class InceptionDataSet(Dataset): def __init__(self, main_dir, all_imgs_paths, transform=None, process=True): self.main_dir = main_dir self.img_paths = all_imgs_paths self.transform = transform # self.total_imgs = natsort.natsorted(self.img_paths) self.process = process def __len__(self): return len(self.img_paths) def __getitem__(self, idx): img_loc = Path(self.main_dir) / Path(self.img_paths[idx]) # image = Image.open(str(img_loc)).convert("RGB") # tensor_image = F.to_tensor(np.float32(image)) tensor_image = F.to_tensor(np.float32(Image.open(img_loc))) if self.process: tensor_image = fixed_image_standardization(tensor_image) return tensor_image, str(self.img_paths[idx]) def create_dataset_inception(repo_path, image_paths, batch_size, transform=None, num_workers=0): dataset = InceptionDataSet(main_dir=repo_path, all_imgs_paths=image_paths, transform=transform) loader = DataLoader(dataset, num_workers=num_workers,batch_size=batch_size, shuffle=False) return dataset, loader def get_embeddings(repo_path, face_paths, batch_size): logger.info(f"starting to embed {len(face_paths)} faces") device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') dataset, loader = create_dataset_inception(repo_path, face_paths, batch_size) resnet = InceptionResnetV1(pretrained='vggface2').eval().to(device) embeddings = [] all_paths = [] for imgs, paths in loader: logger.info("ran 1 batch") with torch.no_grad(): embeddings.append(resnet(imgs)) all_paths.extend(paths) embeddings = [el for el in torch.cat(embeddings)] # assert all embeddings are 512 in size assert len(all_paths) == len(face_paths) assert len(embeddings) == len(all_paths) assert sum([el.numel() == 512 for el in embeddings]) == len(embeddings) return embeddings, all_paths
StarcoderdataPython
6499963
import logging from django.conf import settings from django.core.urlresolvers import reverse import httplib import urllib from eulfedora import models, server from eulxml.xmlmap.dc import DublinCore from pidservices.clients import parse_ark from pidservices.djangowrapper.shortcuts import DjangoPidmanRestClient from readux.utils import absolutize_url logger = logging.getLogger(__name__) # try to configure a pidman client to get pids. try: pidman = DjangoPidmanRestClient() except: # if we're in dev mode then we can fall back on the fedora default # pid allocator. in non-dev, though, we really need pidman if getattr(settings, 'DEV_ENV', False): logger.warn('Failed to configure PID manager client; default pid logic will be used') pidman = None else: raise class ManagementRepository(server.Repository): '''Convenience class to initialize an instance of :class:`eulfedora.server.Repository` with Fedora management/maintenance account credentials defined in Django settings. .. Note:: This :class:`~eulfedora.server.Repository` variant should *only* be used for maintainance tasks (e.g., scripts that ingest, modify, or otherwise manage content). It should **not** be used for general website views or access; those views should use the standard :class:`~eulfedora.server.Repository` which will pick up the default, non-privileged credentials intended for read and display access but not for modifying content in the repository. ''' default_pidspace = getattr(settings, 'FEDORA_PIDSPACE', None) # default pidspace is not automatically pulled from django conf # when user/password are specified, so explicitly set it here def __init__(self): # explicitly disabling other init args, so that anyone who tries to use # this as a regular repo will get errors rather than confusing behavior super(ManagementRepository, self).__init__(username=settings.FEDORA_MANAGEMENT_USER, password=settings.FEDORA_MANAGEMENT_PASSWORD) class DigitalObject(models.DigitalObject): """Readux base :class:`~eulfedora.models.DigitalObject` class with logic for setting and accessing pids based on PID manager ids.""" #: :class:`~eulfedora.models.XmlDatastream` for the required Fedora #: **DC** datastream; datastream content loaded as an instance #: of :class:`eulxml.xmlmap.dc.DublinCore`; overriding default #: declaration in eulfedora to configure as Managed instead of Inline XML dc = models.XmlDatastream("DC", "Dublin Core", DublinCore, defaults={ 'control_group': 'M', 'format': 'http://www.openarchives.org/OAI/2.0/oai_dc/', 'versionable': True }) # NOTE: we don't really need DC versioned, but there is a Fedora bug # that requires Managed DC be versioned #: :class:`~eulfedora.models.RdfDatastream` for the standard Fedora #: **RELS-EXT** datastream; overriding to configure as Managed instead #: of Inline XML rels_ext = models.RdfDatastream("RELS-EXT", "External Relations", defaults={ 'control_group': 'M', 'format': 'info:fedora/fedora-system:FedoraRELSExt-1.0', }) def __init__(self, *args, **kwargs): default_pidspace = getattr(settings, 'FEDORA_PIDSPACE', None) kwargs['default_pidspace'] = default_pidspace super(DigitalObject, self).__init__(*args, **kwargs) self._default_target_data = None @property def noid(self): pidspace, noid = self.pid.split(':') return noid @property def ark_uri(self): for dcid in self.dc.content.identifier_list: if 'ark:/' in dcid: return dcid #: special pid token that tells pid manager to put the newly minted # pid into the url PID_TOKEN = '{%PID%}' def get_default_pid(self): '''Default pid logic for DigitalObjects in :mod:`readux`. Mint a new ARK via the PID manager, store the ARK in the MODS metadata (if available) or Dublin Core, and use the noid portion of the ARK for a Fedora pid in the site-configured Fedora pidspace.''' global pidman if pidman is not None: # pidman wants a target for the new pid # generate a pidman-ready target for a named view # Use the object absolute url method # NOTE: this requires that all values used in a url be set # (i.e., page objects must have volume pid configured) self.pid = '%s:%s' % (self.default_pidspace, self.PID_TOKEN) target = self.get_absolute_url() # reverse() encodes the PID_TOKEN and the :, so just unquote the url # (shouldn't contain anything else that needs escaping) target = urllib.unquote(target) # reverse() returns a full path - absolutize so we get scheme & server also target = absolutize_url(target) # pid name is not required, but helpful for managing pids pid_name = self.label # ask pidman for a new ark in the configured pidman domain try: ark = pidman.create_ark(settings.PIDMAN_DOMAIN, target, name=pid_name) except httplib.BadStatusLine: logger.warn('Error creating ARK; re-initializing pidman client and trying again') pidman = DjangoPidmanRestClient() ark = pidman.create_ark(settings.PIDMAN_DOMAIN, target, name=pid_name) # pidman returns the full, resolvable ark # parse into dictionary with nma, naan, and noid parsed_ark = parse_ark(ark) noid = parsed_ark['noid'] # nice opaque identifier # Add full uri ARK to dc:identifier self.dc.content.identifier_list.append(ark) # use the noid to construct a pid in the configured pidspace return '%s:%s' % (self.default_pidspace, noid) else: # if pidmanager is not available, fall back to default pid behavior return super(DigitalObject, self).get_default_pid() def index_data_descriptive(self): '''Extend the default :meth:`eulfedora.models.DigitalObject.index_data` to do common clean up for all Readux indexing: - If there are multiple titles, choose the longest one. ''' data = super(DigitalObject, self).index_data_descriptive() # a few books have multiple titles; # if title is a list, choose the longest one if 'title' in data and isinstance(data['title'], list): title = '' for d in data['title']: if len(d) > len(title): title = d data['title'] = title return data
StarcoderdataPython
8111759
<filename>profiler/image_classification/models/layers.py # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch import torch.nn as nn import torchmodules.torchgraph as torchgraph class SeparableConv2d(nn.Sequential): def __init__(self, in_channels, out_channels, dw_kernel, dw_stride, dw_padding, bias=False): super(SeparableConv2d, self).__init__() self.depthwise_conv2d = nn.Conv2d(in_channels, in_channels, dw_kernel, stride=dw_stride, padding=dw_padding, bias=bias, groups=in_channels) self.pointwise_conv2d = nn.Conv2d(in_channels, out_channels, 1, stride=1, bias=bias) class BranchSeparables(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=False): super(BranchSeparables, self).__init__() self.relu = nn.ReLU() self.separable_1 = SeparableConv2d(in_channels, in_channels, kernel_size, stride, padding, bias=bias) self.bn_sep_1 = nn.BatchNorm2d(in_channels, eps=0.001, momentum=0.1, affine=True) self.relu1 = nn.ReLU() self.separable_2 = SeparableConv2d(in_channels, out_channels, kernel_size, 1, padding, bias=bias) self.bn_sep_2 = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1, affine=True) class BranchSeparablesStem(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=False): super(BranchSeparablesStem, self).__init__() self.relu = nn.ReLU() self.separable_1 = SeparableConv2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias) self.bn_sep_1 = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1, affine=True) self.relu1 = nn.ReLU() self.separable_2 = SeparableConv2d(out_channels, out_channels, kernel_size, 1, padding, bias=bias) self.bn_sep_2 = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1, affine=True) def ReductionCellBranchCombine(cell, x_left, x_right): x_comb_iter_0_left = cell.comb_iter_0_left(x_left) x_comb_iter_0_right = cell.comb_iter_0_right(x_right) x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right x_comb_iter_1_left = cell.comb_iter_1_left(x_left) x_comb_iter_1_right = cell.comb_iter_1_right(x_right) x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right x_comb_iter_2_left = cell.comb_iter_2_left(x_left) x_comb_iter_2_right = cell.comb_iter_2_right(x_right) x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right x_comb_iter_3_right = cell.comb_iter_3_right(x_comb_iter_0) x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1 x_comb_iter_4_left = cell.comb_iter_4_left(x_comb_iter_0) x_comb_iter_4_right = cell.comb_iter_4_right(x_left) x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right x_out = torchgraph.cat([x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1) return x_out class CellStem0(nn.Module): def __init__(self, in_channels, out_channels): super(CellStem0, self).__init__() self.conv_1x1 = nn.Sequential() self.conv_1x1.add_module('relu', nn.ReLU()) self.conv_1x1.add_module('conv', nn.Conv2d(in_channels, out_channels, 1, stride=1, bias=False)) self.conv_1x1.add_module('bn', nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1, affine=True)) self.comb_iter_0_left = BranchSeparables(out_channels, out_channels, 5, 2, 2, bias=False) self.comb_iter_0_right = BranchSeparablesStem(in_channels, out_channels, 7, 2, 3, bias=False) self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1) self.comb_iter_1_right = BranchSeparablesStem(in_channels, out_channels, 7, 2, 3, bias=False) self.comb_iter_2_left = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False) self.comb_iter_2_right = BranchSeparablesStem(in_channels, out_channels, 5, 2, 2, bias=False) self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False) self.comb_iter_4_left = BranchSeparables(out_channels, out_channels, 3, 1, 1, bias=False) self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1) def forward(self, x): x1 = self.conv_1x1(x) return ReductionCellBranchCombine(self, x1, x) class CellStem1(nn.Module): def __init__(self, in_channels_x, in_channels_h, out_channels): super(CellStem1, self).__init__() self.conv_1x1 = nn.Sequential() self.conv_1x1.add_module('relu', nn.ReLU()) self.conv_1x1.add_module('conv', nn.Conv2d(in_channels_x, out_channels, 1, stride=1, bias=False)) self.conv_1x1.add_module('bn', nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1, affine=True)) self.relu = nn.ReLU() self.path_1 = nn.Sequential() self.path_1.add_module('avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False)) self.path_1.add_module('conv', nn.Conv2d(in_channels_h, out_channels//2, 1, stride=1, bias=False)) self.path_2 = nn.Sequential() self.path_2.add_module('avgpool', nn.AvgPool2d(1, stride=2, ceil_mode=True, count_include_pad=False)) # ceil mode for padding self.path_2.add_module('conv', nn.Conv2d(in_channels_h, out_channels//2, 1, stride=1, bias=False)) self.final_path_bn = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1, affine=True) self.comb_iter_0_left = BranchSeparables(out_channels, out_channels, 5, 2, 2, bias=False) self.comb_iter_0_right = BranchSeparables(out_channels, out_channels, 7, 2, 3, bias=False) self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1) self.comb_iter_1_right = BranchSeparables(out_channels, out_channels, 7, 2, 3, bias=False) self.comb_iter_2_left = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False) self.comb_iter_2_right = BranchSeparables(out_channels, out_channels, 5, 2, 2, bias=False) self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False) self.comb_iter_4_left = BranchSeparables(out_channels, out_channels, 3, 1, 1, bias=False) self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1) def forward(self, x_conv0, x_stem_0): x_left = self.conv_1x1(x_stem_0) x_relu = self.relu(x_conv0) # path 1 x_path1 = self.path_1(x_relu) # path 2 x_path2 = self.path_2(x_relu[:, :, 1:, 1:]) # final path x_right = self.final_path_bn(torchgraph.cat([x_path1, x_path2], 1)) return ReductionCellBranchCombine(self, x_left, x_right) class ReductionCell(nn.Module): def __init__(self, in_channels_left, out_channels_left, in_channels_right, out_channels_right): super(ReductionCell, self).__init__() self.conv_prev_1x1 = nn.Sequential() self.conv_prev_1x1.add_module('relu', nn.ReLU()) self.conv_prev_1x1.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False)) self.conv_prev_1x1.add_module('bn', nn.BatchNorm2d(out_channels_left, eps=0.001, momentum=0.1, affine=True)) self.conv_1x1 = nn.Sequential() self.conv_1x1.add_module('relu', nn.ReLU()) self.conv_1x1.add_module('conv', nn.Conv2d(in_channels_right, out_channels_right, 1, stride=1, bias=False)) self.conv_1x1.add_module('bn', nn.BatchNorm2d(out_channels_right, eps=0.001, momentum=0.1, affine=True)) self.comb_iter_0_left = BranchSeparables(out_channels_right, out_channels_right, 5, 2, 2, bias=False) self.comb_iter_0_right = BranchSeparables(out_channels_right, out_channels_right, 7, 2, 3, bias=False) self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1) self.comb_iter_1_right = BranchSeparables(out_channels_right, out_channels_right, 7, 2, 3, bias=False) self.comb_iter_2_left = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False) self.comb_iter_2_right = BranchSeparables(out_channels_right, out_channels_right, 5, 2, 2, bias=False) self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False) self.comb_iter_4_left = BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False) self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1) def forward(self, x, x_prev): x_left = self.conv_1x1(x) x_right = self.conv_prev_1x1(x_prev) return ReductionCellBranchCombine(self, x_left, x_right) def NormalCellBranchCombine(cell, x_left, x_right): x_comb_iter_0_left = cell.comb_iter_0_left(x_right) x_comb_iter_0_right = cell.comb_iter_0_right(x_left) x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right x_comb_iter_1_left = cell.comb_iter_1_left(x_left) x_comb_iter_1_right = cell.comb_iter_1_right(x_left) x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right x_comb_iter_2_left = cell.comb_iter_2_left(x_right) x_comb_iter_2 = x_comb_iter_2_left + x_left x_comb_iter_3_left = cell.comb_iter_3_left(x_left) x_comb_iter_3_right = cell.comb_iter_3_right(x_left) x_comb_iter_3 = x_comb_iter_3_left + x_comb_iter_3_right x_comb_iter_4_left = cell.comb_iter_4_left(x_right) x_comb_iter_4 = x_comb_iter_4_left + x_right x_out = torchgraph.cat([x_left, x_comb_iter_0, x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1) return x_out class FirstCell(nn.Module): def __init__(self, in_channels_left, out_channels_left, in_channels_right, out_channels_right): super(FirstCell, self).__init__() self.conv_1x1 = nn.Sequential() self.conv_1x1.add_module('relu', nn.ReLU()) self.conv_1x1.add_module('conv', nn.Conv2d(in_channels_right, out_channels_right, 1, stride=1, bias=False)) self.conv_1x1.add_module('bn', nn.BatchNorm2d(out_channels_right, eps=0.001, momentum=0.1, affine=True)) self.relu = nn.ReLU() self.path_1 = nn.Sequential() self.path_1.add_module('avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False)) self.path_1.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False)) self.path_2 = nn.Sequential() self.path_2.add_module('avgpool', nn.AvgPool2d(1, stride=2, ceil_mode=True, count_include_pad=False)) self.path_2.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False)) self.final_path_bn = nn.BatchNorm2d(out_channels_left * 2, eps=0.001, momentum=0.1, affine=True) self.comb_iter_0_left = BranchSeparables(out_channels_right, out_channels_right, 5, 1, 2, bias=False) self.comb_iter_0_right = BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False) self.comb_iter_1_left = BranchSeparables(out_channels_right, out_channels_right, 5, 1, 2, bias=False) self.comb_iter_1_right = BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False) self.comb_iter_2_left = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False) self.comb_iter_3_left = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False) self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False) self.comb_iter_4_left = BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False) def forward(self, x, x_prev): x_relu = self.relu(x_prev) # path 1 x_path1 = self.path_1(x_relu) # path 2 x_path2 = self.path_2(x_relu[:, :, 1:, 1:]) # final path x_left = self.final_path_bn(torchgraph.cat([x_path1, x_path2], 1)) x_right = self.conv_1x1(x) return NormalCellBranchCombine(self, x_left, x_right) class NormalCell(nn.Module): def __init__(self, in_channels_left, out_channels_left, in_channels_right, out_channels_right): super(NormalCell, self).__init__() self.conv_prev_1x1 = nn.Sequential() self.conv_prev_1x1.add_module('relu', nn.ReLU()) self.conv_prev_1x1.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False)) self.conv_prev_1x1.add_module('bn', nn.BatchNorm2d(out_channels_left, eps=0.001, momentum=0.1, affine=True)) self.conv_1x1 = nn.Sequential() self.conv_1x1.add_module('relu', nn.ReLU()) self.conv_1x1.add_module('conv', nn.Conv2d(in_channels_right, out_channels_right, 1, stride=1, bias=False)) self.conv_1x1.add_module('bn', nn.BatchNorm2d(out_channels_right, eps=0.001, momentum=0.1, affine=True)) self.comb_iter_0_left = BranchSeparables(out_channels_right, out_channels_right, 5, 1, 2, bias=False) self.comb_iter_0_right = BranchSeparables(out_channels_left, out_channels_left, 3, 1, 1, bias=False) self.comb_iter_1_left = BranchSeparables(out_channels_left, out_channels_left, 5, 1, 2, bias=False) self.comb_iter_1_right = BranchSeparables(out_channels_left, out_channels_left, 3, 1, 1, bias=False) self.comb_iter_2_left = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False) self.comb_iter_3_left = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False) self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False) self.comb_iter_4_left = BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False) def forward(self, x, x_prev): x_left = self.conv_prev_1x1(x_prev) x_right = self.conv_1x1(x) return NormalCellBranchCombine(self, x_left, x_right)
StarcoderdataPython
11382917
<reponame>jejjohnson/pysim<filename>pysim/information/kde.py<gh_stars>1-10 from typing import Optional, Union, Dict, List import numpy as np import statsmodels.api as sm from sklearn.utils import check_array def kde_entropy_uni(X: np.ndarray, **kwargs): # check input array X = check_array(X, ensure_2d=True) # initialize KDE kde_density = sm.nonparametric.KDEUnivariate(X) kde_density.fit(**kwargs) return kde_density.entropy
StarcoderdataPython
9639213
<reponame>abraaogleiber/Python_Procedural_OrientadoO #__________________ Script Python - versão 3.8 _____________________# # Autor |> <NAME> # Data |> 18 de Março de 2021 # Paradigma |> Orientado à objetos # Objetivo |> Desenvolver um algoritmo que consiga calcular raízes # de equações do 2ºGrau #___________________________________________________________________# #----> Formula : Ax² + B + C = 0 # ---> Verificar possivel existência de uma raiz, dado os valores dos elementos da equação. # ----> r < 0 (negativo) Nenhuma raiz # ----> r = 0 (nulo) Uma raia # ----> r > 0 (positivo) Duas raiz class EquaRaiz: """ A classe disponibiliza uma maneira prática para encontrar raízes de equações do 2ºGrau. """ __slots__ = ('_a', '_b', '_c') _raiz_1 = None _raiz_2 = None def __init__(self, a=1, b=1 , c=1): try: if isinstance(a, int) and isinstance(b, int) and isinstance(c, int): self._a = a self._b = b self._c = c else: raise TypeError except TypeError: print('Impossivel continuar. Erro na atribuição de valores!.') exit() self.__calcular_descriminante() @property def a(self): return self._a @property def b(self): return self._b @property def c(self): return self._c def __calcular_descriminante(self): """ -------> O método realiza o calculo do delta, e o torna global, além de encerrar o programa caso o valor de "A" seja igual a zero(0). retorna: O delta para dentro do método que irá determinar a quantidade de raizes da equação. """ global descriminante if self._a == 0: print('A Equação não é do 2ºGrau!.') exit() descriminante = (self._b) ** 2 - (4 * self._a * self._c) return self.__validar_equacao(descriminante) def __validar_equacao(self, delta): """ -------> O método avalia o delta e define a quantidade de raízes da equação. parametro delta: Recebe o delta. retorna: A quantidade de raízes da equação para dentro do método responsável pelo calculo da raíz. """ if delta == 0: quant_raiz = 1 elif delta < 0: quant_raiz = 0 elif delta > 0: quant_raiz = 2 return self.__encontrando_raiz(quant_raiz) def __encontrando_raiz(self, q_raiz): """ -------> O método realiza o calculo da raíz(zes) da equação. parametro q_raiz: Recebe a quantidade de raízes da equação. retorna: O valor da(s) raíz(es) para dentro de um método que irá mostrar ao usuário. """ if q_raiz == 0: print('Esta Equação não possui raiz, já que seu delta é menor que zero(0) -- Negativo.') print('Valor do delta ---> {}'.format(descriminante)) exit() elif q_raiz == 2: EquaRaiz._raiz_1 = (self._b + descriminante) / (2 * self._a) EquaRaiz._raiz_2 = (self._b - descriminante) / (2 * self._a) return self.__raizes_encontradas(EquaRaiz._raiz_1, EquaRaiz._raiz_2) else: EquaRaiz._raiz_1 = (self._b ) / (2 * self._a) print(EquaRaiz._raiz_1) return self.__raizes_encontradas(EquaRaiz._raiz_1) def __raizes_encontradas(self, r1=None, r2=None): """ -------> O método mostra o valor da(s) raíz(es) da equação. parametro r1: Recebe a primeria raiz. parametro r2: Se houver, recebe a segunda raiz da equação. retorna: None """ if r2 == None: print(f'A raiz encontrada foi {r1}') else: print(f'As duas raízes encontradas foram --> Raiz(1) {r1}\n' f' Raiz(2) {r2}') if __name__ == '__main__': teste = EquaRaiz(a=3, b=5, c=6)
StarcoderdataPython
8109377
from FacebookWebBot import * import os, json, random, jsonpickle from Spam import spam from loginInfo import Info posts_=[] selfProfile = "https://mbasic.facebook.com/profile.php?fref=pb" grups = ["https://mbasic.facebook.com/groups/830198010427436", "https://m.facebook.com/groups/1660869834170435", "https://m.facebook.com/groups/100892180263901", "https://m.facebook.com/groups/1649744398596548", "https://m.facebook.com/groups/421300388054652", "https://m.facebook.com/groups/675838025866331", "https://m.facebook.com/groups/1433809846928404", "https://m.facebook.com/groups/1625415104400173", "https://m.facebook.com/groups/424478411092230", "https://m.facebook.com/groups/1056447484369528", "https://m.facebook.com/groups/1433809846928404", "https://m.facebook.com/groups/421300388054652", "https://m.facebook.com/groups/1649744398596548", "https://m.facebook.com/groups/751450114953723", "https://m.facebook.com/groups/943175872420249" ] postsList = list() peopleList = list() saluteText = "Buenos días usuarios, gracias por activar su unidad moderadora 3000\n" \ "\nPara información sobre su uso presione la tecla F1, para ayuda presione F2 \n" \ "Para otras instrucciones remitase al manual de usuario adjunto en el CD instalador" eula = """Unidad Moderadora 3000 0.69 Copyright (c) 2001 Unit0x78A *** END USER LICENSE AGREEMENT *** IMPORTANT: PLEASE READ THIS LICENSE CAREFULLY BEFORE USING THIS SOFTWARE. 1. LICENSE By receiving, opening the file package, and/or using Unidad Moderadora 3000 0.69("Software") containing this software, you agree that this End User User License Agreement(EULA) is a legally binding and valid contract and agree to be bound by it. You agree to abide by the intellectual property laws and all of the terms and conditions of this Agreement. Unless you have a different license agreement signed by Unit0x78A your use of Unidad Moderadora 3000 0.69 indicates your acceptance of this license agreement and warranty. Subject to the terms of this Agreement, Unit0x78A grants to you a limited, non-exclusive, non-transferable license, without right to sub-license, to use Unidad Moderadora 3000 0.69 in accordance with this Agreement and any other written agreement with Unit0x78A. Unit0x78A does not transfer the title of Unidad Moderadora 3000 0.69 to you; the license granted to you is not a sale. This agreement is a binding legal agreement between Unit0x78A and the purchasers or users of Unidad Moderadora 3000 0.69. If you do not agree to be bound by this agreement, remove Unidad Moderadora 3000 0.69 from your computer now and, if applicable, promptly return to Unit0x78A by mail any copies of Unidad Moderadora 3000 0.69 and related documentation and packaging in your possession. 2. DISTRIBUTION Unidad Moderadora 3000 0.69 and the license herein granted shall not be copied, shared, distributed, re-sold, offered for re-sale, transferred or sub-licensed in whole or in part except that you may make one copy for archive purposes only. For information about redistribution of Unidad Moderadora 3000 0.69 contact Unit0x78A. 3. USER AGREEMENT 3.1 Use Your license to use Unidad Moderadora 3000 0.69 is limited to the number of licenses purchased by you. You shall not allow others to use, copy or evaluate copies of Unidad Moderadora 3000 0.69. 3.2 Use Restrictions You shall use Unidad Moderadora 3000 0.69 in compliance with all applicable laws and not for any unlawful purpose. Without limiting the foregoing, use, display or distribution of Unidad Moderadora 3000 0.69 together with material that is pornographic, racist, vulgar, obscene, defamatory, libelous, abusive, promoting hatred, discriminating or displaying prejudice based on religion, ethnic heritage, race, sexual orientation or age is strictly prohibited. Each licensed copy of Unidad Moderadora 3000 0.69 may be used on one single computer location by one user. Use of Unidad Moderadora 3000 0.69 means that you have loaded, installed, or run Unidad Moderadora 3000 0.69 on a computer or similar device. If you install Unidad Moderadora 3000 0.69 onto a multi-user platform, server or network, each and every individual user of Unidad Moderadora 3000 0.69 must be licensed separately. You may make one copy of Unidad Moderadora 3000 0.69 for backup purposes, providing you only have one copy installed on one computer being used by one person. Other users may not use your copy of Unidad Moderadora 3000 0.69 . The assignment, sublicense, networking, sale, or distribution of copies of Unidad Moderadora 3000 0.69 are strictly forbidden without the prior written consent of Unit0x78A. It is a violation of this agreement to assign, sell, share, loan, rent, lease, borrow, network or transfer the use of Unidad Moderadora 3000 0.69. If any person other than yourself uses Unidad Moderadora 3000 0.69 registered in your name, regardless of whether it is at the same time or different times, then this agreement is being violated and you are responsible for that violation! 3.3 Copyright Restriction This Software contains copyrighted material, trade secrets and other proprietary material. You shall not, and shall not attempt to, modify, reverse engineer, disassemble or decompile Unidad Moderadora 3000 0.69. Nor can you create any derivative works or other works that are based upon or derived from Unidad Moderadora 3000 0.69 in whole or in part. Unit0x78A's name, logo and graphics file that represents Unidad Moderadora 3000 0.69 shall not be used in any way to promote products developed with Unidad Moderadora 3000 0.69 . Unit0x78A retains sole and exclusive ownership of all right, title and interest in and to Unidad Moderadora 3000 0.69 and all Intellectual Property rights relating thereto. Copyright law and international copyright treaty provisions protect all parts of Unidad Moderadora 3000 0.69, products and services. No program, code, part, image, audio sample, or text may be copied or used in any way by the user except as intended within the bounds of the single user program. All rights not expressly granted hereunder are reserved for Unit0x78A. 3.4 Limitation of Responsibility You will indemnify, hold harmless, and defend Unit0x78A , its employees, agents and distributors against any and all claims, proceedings, demand and costs resulting from or in any way connected with your use of Unit0x78A's Software. In no event (including, without limitation, in the event of negligence) will Unit0x78A , its employees, agents or distributors be liable for any consequential, incidental, indirect, special or punitive damages whatsoever (including, without limitation, damages for loss of profits, loss of use, business interruption, loss of information or data, or pecuniary loss), in connection with or arising out of or related to this Agreement, Unidad Moderadora 3000 0.69 or the use or inability to use Unidad Moderadora 3000 0.69 or the furnishing, performance or use of any other matters hereunder whether based upon contract, tort or any other theory including negligence. Unit0x78A's entire liability, without exception, is limited to the customers' reimbursement of the purchase price of the Software (maximum being the lesser of the amount paid by you and the suggested retail price as listed by Unit0x78A ) in exchange for the return of the product, all copies, registration papers and manuals, and all materials that constitute a transfer of license from the customer back to Unit0x78A. 3.5 Warranties Except as expressly stated in writing, Unit0x78A makes no representation or warranties in respect of this Software and expressly excludes all other warranties, expressed or implied, oral or written, including, without limitation, any implied warranties of merchantable quality or fitness for a particular purpose. 3.6 Governing Law This Agreement shall be governed by the law of the Afghanistan applicable therein. You hereby irrevocably attorn and submit to the non-exclusive jurisdiction of the courts of Afghanistan therefrom. If any provision shall be considered unlawful, void or otherwise unenforceable, then that provision shall be deemed severable from this License and not affect the validity and enforceability of any other provisions. 3.7 Termination Any failure to comply with the terms and conditions of this Agreement will result in automatic and immediate termination of this license. Upon termination of this license granted herein for any reason, you agree to immediately cease use of Unidad Moderadora 3000 0.69 and destroy all copies of Unidad Moderadora 3000 0.69 supplied under this Agreement. The financial obligations incurred by you shall survive the expiration or termination of this license. 4. DISCLAIMER OF WARRANTY THIS SOFTWARE AND THE ACCOMPANYING FILES ARE SOLD "AS IS" AND WITHOUT WARRANTIES AS TO PERFORMANCE OR MERCHANTABILITY OR ANY OTHER WARRANTIES WHETHER EXPRESSED OR IMPLIED. THIS DISCLAIMER CONCERNS ALL FILES GENERATED AND EDITED BY Unidad Moderadora 3000 0.69 AS WELL. 5. CONSENT OF USE OF DATA You agree that Unit0x78A may collect and use information gathered in any manner as part of the product support services provided to you, if any, related to Unidad Moderadora 3000 0.69.Unit0x78A may also use this information to provide notices to you which may be of use or interest to you.""" def getPost(): global postsList def saluteAll(): global grups, bot, saluteText for g in grups: try: bot.postInGroup(g, eula) print("DONE") except Exception: print("Fail") def getUsers(): global peopleList, grups, bot for g in grups: try: pg = bot.getGroupMembers(g, 1, random.randint(0, 20)) peopleList += pg print("DONE", len(pg)) except Exception: print("fail") print(len(peopleList)) def addAll(): global bot, grups, peopleList for p in peopleList: try: bot.sendFriendRequest(p.profileLink) print("Added: ", p.name) except Exception: print("Fail to add: ", p.name) def spam_group(): global bot, groups,posts_ for g in grups: try: posts_ += bot.getPostInGroup(g)[0] print("Number of posts: ", len(posts_)) except Exception: print("Fail get posts in :", bot.title) for p in posts_: try: n=bot.commentInPost(p.linkToComment, random.choice(spam)) bot.save_screenshot(n) print("Commenting in", bot.title) except Exception: print("Fail comment in ", bot.title) if __name__ == "__main__": bot = FacebookBot() bot.login(Info["email"], Info["pass"], False) bot.save_screenshot("debug.jpg") while True: try: saluteAll() spam_group() time.sleep(5*60) except Exception: print ("ERROR!!!")
StarcoderdataPython
1600518
<filename>getPrices.py ''' Created on Jun 2, 2014 @author: vidurjoshi ''' from pandas.io import parsers from datetime import datetime def make_url(ticker_symbol,start_date, end_date): print ticker_symbol base_url = "http://ichart.finance.yahoo.com/table.csv?s=" a = start_date b = end_date dt_url = '%s&a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&g=d&ignore=.csv'% (ticker_symbol, a.month-1, a.day, a.year, b.month-1, b.day,b.year) return base_url + dt_url def getPrices(symb, openD, closeD): url = make_url(symb,openD, closeD) print url e = parsers.read_csv(url) print e getPrices("GOOG", datetime(2000,1,1), datetime(2012,1,1))
StarcoderdataPython
8126611
import torch from torch import nn import torch.nn.functional as F from .pooling import ChannelPool class ChannelAttention(nn.Module): def __init__(self, in_planes, ratio=12): super().__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.max_pool = nn.AdaptiveMaxPool2d(1) self.fc1 = nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False) self.relu1 = nn.ReLU(inplace=True) self.fc2 = nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False) self.sigmoid = nn.Sigmoid() def forward(self, x): avg_out = self.fc2(self.relu1(self.fc1(self.avg_pool(x)))) max_out = self.fc2(self.relu1(self.fc1(self.max_pool(x)))) out = avg_out + max_out return self.sigmoid(out) class SpatialAttention(nn.Module): def __init__(self, kernel_size=7): super().__init__() self.pool = ChannelPool() self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=( kernel_size-1)//2, bias=False) self.sigmoid = nn.Sigmoid() def forward(self, x): x = self.conv1(self.pool(x)) return self.sigmoid(x) class CBAM2d(nn.Module): def __init__(self, in_planes, kernel_size=7, return_mask=False): super().__init__() self.ch_attn = ChannelAttention(in_planes) self.sp_attn = SpatialAttention(kernel_size) self.return_mask = return_mask def forward(self, x): # x: bs x ch x w x h x = self.ch_attn(x) * x sp_mask = self.sp_attn(x) x = sp_mask * x if self.return_mask: return sp_mask, x else: return x class MultiInstanceAttention(nn.Module): ''' Implementation of: Attention-based Multiple Instance Learning https://arxiv.org/abs/1802.04712 ''' def __init__(self, feature_size, instance_size, num_classes=1, hidden_size=512, gated_attention=False): super().__init__() self.gated = gated_attention self.attn_U = nn.Sequential( nn.Linear(feature_size, hidden_size), nn.Tanh() ) if self.gated: self.attn_V = nn.Sequential( nn.Linear(feature_size, hidden_size), nn.Sigmoid() ) self.attn_W = nn.Linear(hidden_size, num_classes) def forward(self, x): # x: bs x k x f # k: num of instance # f: feature dimension bs, k, f = x.shape x = x.view(bs*k, f) if self.gated: x = self.attn_W(self.attn_U(x) * self.attn_V(x)) else: x = self.attn_W(self.attn_U(x)) x = x.view(bs, k, self.attn_W.out_features) x = F.softmax(x.transpose(1, 2), dim=2) # Softmax over k return x # : bs x 1 x k
StarcoderdataPython
4952589
<reponame>rpitchumani/s-3500 """ Class to read exported Microtrac 3500 Particle Analysis CSV File 2022, <NAME> """ from typing import List, Dict, Any import pandas as pd import numpy as np class S3500: def __init__(self, path_csv: str): self.path_csv = path_csv self.df = pd.read_csv(path_csv, index_col=None, header=0, engine="python") self.df.columns = ["Column 1", "Column 2", "Column 3"] self.get_indices() self.get_sample_information() self.get_statistics() self.get_percentiles() def get_sample_information(self): filter_title = self.df[self.df["Column 1"].str.contains("Title", na=False)].reset_index() self.title = filter_title["Column 2"][0].strip() filter_id_1 = self.df[self.df["Column 1"].str.contains("ID 1:", na=False)].reset_index() # print("id1", filter_id_1) self.id_1 = filter_id_1["Column 2"][0].strip() filter_id_2 = self.df[self.df["Column 1"].str.contains("ID 2:", na=False)].reset_index() # print("id2", filter_id_2) self.id_2 = filter_id_2["Column 2"][0].strip() filter_date = self.df[self.df["Column 1"].str.contains("Date:", na=False)].reset_index() # print("date", filter_date) self.date = filter_date["Column 2"][0].strip() filter_time = self.df[self.df["Column 1"].str.contains("Time:", na=False)].reset_index() # print("time", filter_time) self.time = filter_time["Column 2"][0].strip() filter_db_rec = self.df[self.df["Column 1"].str.contains("Db Rec#:", na=False)].reset_index() # print("db rec", filter_db_rec) self.db_rec = filter_db_rec["Column 2"][0].strip() filter_db_name = self.df[self.df["Column 1"].str.contains("DB Name:", na=False)].reset_index() # print("db name", filter_db_name) self.db_name = filter_db_name["Column 2"][0].strip() def get_statistics(self): filter_mv = self.df[self.df["Column 2"].str.contains("MV\(um\):", na=False)].reset_index() self.mv = float(filter_mv["Column 3"][0]) filter_mn = self.df[self.df["Column 2"].str.contains("MN\(um\):", na=False)].reset_index() self.mn = float(filter_mn["Column 3"][0]) filter_ma = self.df[self.df["Column 2"].str.contains("MA\(um\):", na=False)].reset_index() self.ma = float(filter_ma["Column 3"][0]) filter_cs = self.df[self.df["Column 2"].str.contains("CS:", na=False)].reset_index() self.cs = float(filter_cs["Column 3"][0]) filter_sd = self.df[self.df["Column 2"].str.contains("SD:", na=False)].reset_index() self.sd = float(filter_sd["Column 3"][0]) filter_mz = self.df[self.df["Column 2"].str.contains("Mz:", na=False)].reset_index() self.mz = float(filter_mz["Column 3"][0]) filter_si = self.df[self.df["Column 2"].str.contains("si:", na=False)].reset_index() self.si = float(filter_si["Column 3"][0]) filter_ski = self.df[self.df["Column 2"].str.contains("Ski:", na=False)].reset_index() self.ski = float(filter_ski["Column 3"][0]) filter_kg = self.df[self.df["Column 2"].str.contains("Kg:", na=False)].reset_index() self.kg = float(filter_kg["Column 3"][0]) @property def percentiles(self): self.get_percentiles() return self.df_percentiles def get_percentiles(self): idx_start = self.df[self.df["Column 1"].str.contains("Percentiles", na=False)].index[0] idx_end = self.df[self.df["Column 1"].str.contains("Size Percent", na=False)].index[0] # print("idx", idx_start) # print("idx", idx_end) self.df_percentiles = self.df.iloc[idx_start+1:idx_end-1] self.df_percentiles.reset_index(drop=True, inplace=True) self.df_percentiles = self.df_percentiles.rename(columns=self.df_percentiles.iloc[0]) self.df_percentiles = self.df_percentiles[1:] self.df_percentiles.drop(columns=self.df_percentiles.columns[0], axis=1, inplace=True) self.df_percentiles.columns = ["%Tile", "Size(um)"] self.df_percentiles = self.df_percentiles.astype(float) @property def psd(self): self.get_psd() return self.df_psd def get_psd(self): idx_start = self.df[self.df["Column 1"].str.contains("Size\(um\)", na=False)].index[0] # print("idx", idx_start) self.df_psd = self.df.iloc[idx_start:self.df.shape[0]] self.df_psd.reset_index(drop=True, inplace=True) self.df_psd = self.df_psd.rename(columns=self.df_psd.iloc[0]) self.df_psd = self.df_psd[1:] self.df_psd.columns = ["Size(um)", "%Chan", "%Pass"] self.df_psd = self.df_psd.astype(float) def get_indices(self): find_strings = ["Summary Data", "User Defined Calculations", "Percentiles", "Peaks", "Size(um)"] self.dict_indices ={} for item in find_strings: self.dict_indices[item] = np.where(self.df == item)
StarcoderdataPython
1708723
<gh_stars>1-10 from pprint import pprint from random import randint tab1 = [[table * i for i in range(11)] for table in range(11)] #pprint(tab1) keno = [[5 * l + (i + 1) for i in range(5)] for l in range(14)] for _ in range(3): keno[randint(0, 13)][randint(0, 4)] = "X" pprint(keno)
StarcoderdataPython
11211452
# You have a number and you need to determine which digit in this number is the biggest. # # Input: A positive int. # # Output: An Int (0-9). # # Example: def max_digit(number: int) -> int: # your code here maxnumber = 0 for x in str(number): if int(x) > maxnumber: maxnumber = int(x) return maxnumber # return reduce(lambda x, y: x * int(y),(y for y in str(number) if int(y) != 0),1) if __name__ == '__main__': print("Example:") print(max_digit(0)) # These "asserts" are used for self-checking and not for an auto-testing assert max_digit(0) == 0 assert max_digit(52) == 5 assert max_digit(634) == 6 assert max_digit(1) == 1 assert max_digit(10000) == 1 # print("Coding complete? Click 'Check' to earn cool rewards!")
StarcoderdataPython
1854326
<gh_stars>0 import adventofcode def fuel_required(mass): """ >>> fuel_required(12) 2 >>> fuel_required(14) 2 >>> fuel_required(1969) 654 >>> fuel_required(100756) 33583 """ return mass // 3 - 2 def fuel_required_extra(mass): """ >>> fuel_required_extra(14) 2 >>> fuel_required_extra(1969) 966 >>> fuel_required_extra(100756) 50346 """ fuel = 0 next_fuel = mass while (next_fuel := fuel_required(next_fuel)) > 0: fuel += next_fuel return fuel def sum_of_fuel(puzzle_input, func): return sum(func(int(line)) for line in puzzle_input) def main(): puzzle_input = adventofcode.read_input(1) adventofcode.answer(1, 3154112, sum_of_fuel(puzzle_input, fuel_required)) adventofcode.answer(2, 4728317, sum_of_fuel(puzzle_input, fuel_required_extra)) if __name__ == "__main__": import doctest doctest.testmod() main()
StarcoderdataPython
1732723
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Supporting functions for scraping jaap.nl - get_max_page finds the number of summary pages to be scraped - read_summary_page reads the houses advertised on one page By dr.Pep, all rights reserved """ # Libs import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import re import ssl # import numpy as np import pandas as pd # import time import datetime #NEW import logging # Take a string, strip the non-numbers, convert to integer # Usable not just for prices, but also for other figures def char_as_int(price_as_string): price_temp = re.findall('[0-9]+',price_as_string) if len(price_temp)>0: house_price = int(''.join(price_temp)) else: house_price = None return house_price def get_max_page(url): ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # Scrape the page # Works for main page after a search on Jaap.nl html = urllib.request.urlopen(url,context=ctx).read() soup = BeautifulSoup(html,'html.parser') # Extract max page numebr from "Page 1 of [0-9]+" page_info = soup.find('span',class_ = 'page-info') max_page = int(re.findall('[0-9]+',page_info.get_text())[1]) # second numer is the last page return max_page # Read a given result page (number) def read_summary_page(url_mainpage,page_number): # construct page url url = url_mainpage + "p" + str(page_number) # logging.info('Scraping webpage '+str(url)) # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # get the html html = urllib.request.urlopen(url,context=ctx).read() soup = BeautifulSoup(html,'html.parser') # for id and link, the straightforward regular expression approach is easiest # as it gets rid of Ad boxes that otherwise get in the way id_html = re.findall(b'id="(house_result_.+)"',html) link_html = re.findall(b'<a class="property-inner" href="(.+?)\?',html) # for other fields, beautifulsoup is the easiest solution address_html = soup.find_all(class_ = 'property-address-street') PC_html = soup.find_all(class_ = 'property-address-zipcity') price_html = soup.find_all(class_ = 'property-price') pricetype_html = soup.find_all(class_ = 'pricetype') # test if all scraped lists have equal length if (len(id_html) != len(link_html) | len(id_html) != len(address_html) | len(id_html) != len(PC_html) | len(id_html) != len(price_html) | len(id_html) != len(pricetype_html)): # if lengths not equal: print error message and return None logging.error('ERROR: Not all scraped lists of equal length!') return {'id': len(id_html), 'link': len(link_html), 'address': len(address_html), 'PC': len(PC_html), 'price': len(price_html), 'pricetype': len(pricetype_html)} # clean scraped content house_id = [] for id in id_html: house_id.append(str(id.decode())) link = [] for lnk in link_html: link.append(str(lnk.decode())) address = [] for addr in address_html: if len(addr.contents)>0: address.append(str(addr.contents[0])) else: address.append(None) PC = [] for code in PC_html: if len(code.contents)>0: PC.append(str(code.contents[0])) else: PC.append(None) pricetype = [] for prct in pricetype_html: if len(prct.contents)>0: pricetype.append(str(prct.contents[0])) else: pricetype.append(None) # specific for price: get from string with € sign to integer price = [] for prc in price_html: if len(prc.contents)>0: price.append(char_as_int(prc.contents[0])) else: price.append(None) # put the cleaned lists into a data frame df_house_summary = pd.DataFrame({'id': house_id, 'link': link, 'address': address, 'PC': PC, 'pricetype': pricetype, 'price': price}) # return the data frame return df_house_summary # Give in url and pricetype to create dict with house details def read_house_detail_page(url_detail_page,pricetype,ID): # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # get the html try: html = urllib.request.urlopen(url_detail_page,context=ctx).read() soup = BeautifulSoup(html,'html.parser') except: return False # Get the basic info also from this page # Construct sub-tree of DOM to facilitate finding pricetype and sold detail_html = soup.find(class_ = 'detail-address') # characteristics stored in specific nodes; pricetype is empty # pricetype_html = detail_html.findChildren('span')[0] sold_html = detail_html.findChildren('span') # Produces error if not 'Verkocht (onder voorbehoud)' address_html = soup.find(class_ = 'detail-address-street') zip_html = soup.find(class_ = 'detail-address-zipcity') # price_html = soup.find(class_ = 'detail-address-price') short_descr_html = soup.find(class_ = 'short-description') long_descr_html = soup.find(class_ = 'description') broker_html = soup.find(class_ = 'broker-name') # list of characteristics and metrics in array characteristics_html = soup.find_all(class_ = 'no-dots') metrics_html = soup.find_all(class_ = 'value') # Need to restrict to first 27 (found by exploring all) n_char = 26 # Now there is some cleaning to do... # make characteristics and metrics into a dictionary house_char_names = [] for c in characteristics_html[0:n_char]: house_char_names.append(c.contents[0].replace(' ','_')) house_char_metrics = [] for m in metrics_html[0:n_char]: house_char_metrics.append(m.contents[0].strip()) house_characteristics = dict(zip(house_char_names,house_char_metrics)) # Clean dictionary contents house_characteristics['Bouwjaar'] = char_as_int(house_characteristics['Bouwjaar']) house_characteristics['Woonoppervlakte'] = char_as_int(house_characteristics['Woonoppervlakte']) house_characteristics['Inhoud'] = char_as_int(house_characteristics['Inhoud']) house_characteristics['Perceeloppervlakte'] = char_as_int(house_characteristics['Perceeloppervlakte']) house_characteristics['Kamers'] = char_as_int(house_characteristics['Kamers']) house_characteristics['Slaapkamers'] = char_as_int(house_characteristics['Slaapkamers']) house_characteristics['Aantal_keer_getoond'] = char_as_int(house_characteristics['Aantal_keer_getoond']) house_characteristics['Aantal_keer_getoond_gisteren'] = char_as_int(house_characteristics['Aantal_keer_getoond_gisteren']) house_characteristics['Huidige_vraagprijs'] = char_as_int(house_characteristics['Huidige_vraagprijs']) house_characteristics['Oorspronkelijke_vraagprijs'] = char_as_int(house_characteristics['Oorspronkelijke_vraagprijs']) house_characteristics['Geplaatst_op'] = datetime.datetime.strptime(house_characteristics['Geplaatst_op'], "%d-%m-%Y").date() # Add other data points # try-except for the ones that might be empty try: house_characteristics['Short_description'] = short_descr_html.get_text().strip().replace('\n', ' ').replace('\r', ' ') except: house_characteristics['Short_description'] = None try: house_characteristics['Long_description'] = long_descr_html.get_text().strip().replace('\n', ' ').replace('\r', ' ') except: house_characteristics['Long_description'] = None try: house_characteristics['Broker'] = broker_html.contents[0].strip() except: house_characteristics['Broker'] = None try: house_characteristics['Address'] = address_html.contents[0] except: house_characteristics['Address'] = None try: house_characteristics['Zip'] = zip_html.contents[0] except: house_characteristics['Zip'] = None # For sold we need to be careful because field is missing when not sold if len(sold_html) < 2: house_characteristics['Sold'] = 'Te koop' else: house_characteristics['Sold'] = detail_html.findChildren('span')[1].contents[0].strip() # pricetype is empty, so we get it from the summary page house_characteristics['Pricetype'] = pricetype # we drag along house id to have a key to the summary info house_characteristics['ID'] = ID # price is the same as Huidige_vraagprijs, so we omit it return pd.DataFrame([house_characteristics]) if __name__ == '__main__': print('This is a test of the function get_max_page...') # print(get_max_page('https://www.jaap.nl/koophuizen/zuid+holland/groot-rijnmond/rotterdam/50+-woonopp/')) # print('This is a test of the function read_summary_page...') # df_test = read_summary_page('https://www.jaap.nl/koophuizen/zuid+holland/groot-rijnmond/rotterdam/50+-woonopp/',20) # print(df_test) print('this is a test of the function that reads a detail page') df_detail_test = read_house_detail_page("https://www.jaap.nl/te-koop/zuid+holland/groot-rijnmond/rotterdam/3062zj/'s-gravenweg+34/7802327/overzicht","k.k.","house_result_7802327") print(df_detail_test.to_dict('series'))
StarcoderdataPython
203131
<gh_stars>1-10 """ all opcodes Python3.6.0 """ # general NOP = 9 POP_TOP = 1 ROT_TWO = 2 ROT_THREE = 3 DUP_TOP = 4 DUP_TOP_TWO = 5 # one operand UNARY_POSITIVE = 10 UNARY_NEGATIVE = 11 UNARY_NOT = 12 UNARY_INVERT = 15 GET_ITER = 68 GET_YIELD_FROM_ITER = 69 # two operand BINARY_POWER = 19 BINARY_MULTIPLY = 20 BINARY_MATRIX_MULTIPLY = 16 BINARY_FLOOR_DIVIDE = 26 BINARY_TRUE_DIVIDE = 27 BINARY_MODULO = 22 BINARY_ADD = 23 BINARY_SUBTRACT = 24 BINARY_SUBSCR = 25 BINARY_LSHIFT = 62 BINARY_RSHIFT = 63 BINARY_AND = 64 BINARY_XOR = 65 BINARY_OR = 66 # inplace INPLACE_POWER = 67 INPLACE_MULTIPLY = 57 INPLACE_MATRIX_MULTIPLY = 17 INPLACE_FLOOR_DIVIDE = 28 INPLACE_TRUE_DIVIDE = 29 INPLACE_MODULO = 59 INPLACE_ADD = 55 INPLACE_SUBTRACT = 56 STORE_SUBSCR = 60 DELETE_SUBSCR = 61 INPLACE_LSHIFT = 75 INPLACE_RSHIFT = 76 INPLACE_AND = 77 INPLACE_XOR = 78 INPLACE_OR = 79 # coroutine (not implemented) GET_AWAITABLE = 73 GET_AITER = 50 GET_ANEXT = 51 BEFORE_ASYNC_WITH = 52 SETUP_ASYNC_WITH = 154 # loop FOR_ITER = 93 SETUP_LOOP = 120 # Distance to target address BREAK_LOOP = 80 CONTINUE_LOOP = 119 # Target address # comprehension SET_ADD = 146 LIST_APPEND = 145 MAP_ADD = 147 # return RETURN_VALUE = 83 YIELD_VALUE = 86 YIELD_FROM = 72 SETUP_ANNOTATIONS = 85 # context SETUP_WITH = 143 WITH_CLEANUP_START = 81 WITH_CLEANUP_FINISH = 82 # import IMPORT_STAR = 84 IMPORT_NAME = 108 # Index in name list IMPORT_FROM = 109 # Index in name list # block stack POP_BLOCK = 87 SETUP_EXCEPT = 121 # "" SETUP_FINALLY = 122 # "" POP_EXCEPT = 89 END_FINALLY = 88 # variable STORE_NAME = 90 # Index in name list DELETE_NAME = 91 # "" UNPACK_SEQUENCE = 92 # Number of tuple items UNPACK_EX = 94 STORE_ATTR = 95 # Index in name list DELETE_ATTR = 96 # "" STORE_GLOBAL = 97 # "" DELETE_GLOBAL = 98 # "" # load LOAD_CONST = 100 # Index in const list LOAD_NAME = 101 # Index in name list LOAD_ATTR = 106 # Index in name list LOAD_GLOBAL = 116 # Index in name list LOAD_FAST = 124 # Local variable number STORE_FAST = 125 # Local variable number DELETE_FAST = 126 # Local variable number # build object BUILD_TUPLE = 102 # Number of tuple items BUILD_LIST = 103 # Number of list items BUILD_SET = 104 # Number of set items BUILD_MAP = 105 # Number of dict entries BUILD_CONST_KEY_MAP = 156 BUILD_STRING = 157 BUILD_TUPLE_UNPACK = 152 BUILD_LIST_UNPACK = 149 BUILD_MAP_UNPACK = 150 BUILD_SET_UNPACK = 153 BUILD_MAP_UNPACK_WITH_CALL = 151 BUILD_TUPLE_UNPACK_WITH_CALL = 158 # bool COMPARE_OP = 107 # Comparison operator # counter JUMP_FORWARD = 110 # Number of bytes to skip POP_JUMP_IF_TRUE = 115 # "" POP_JUMP_IF_FALSE = 114 # "" JUMP_IF_TRUE_OR_POP = 112 # "" JUMP_IF_FALSE_OR_POP = 111 # Target byte offset from beginning of code JUMP_ABSOLUTE = 113 # "" # exception RAISE_VARARGS = 130 # Number of raise arguments (1, 2, or 3) # function CALL_FUNCTION = 131 # #args MAKE_FUNCTION = 132 # Flags BUILD_SLICE = 133 # Number of items LOAD_CLOSURE = 135 LOAD_DEREF = 136 STORE_DEREF = 137 DELETE_DEREF = 138 CALL_FUNCTION_KW = 141 # #args + #kwargs CALL_FUNCTION_EX = 142 # Flags LOAD_CLASSDEREF = 148 # others PRINT_EXPR = 70 LOAD_BUILD_CLASS = 71 HAVE_ARGUMENT = 90 # Opcodes from here have an argument: EXTENDED_ARG = 144 FORMAT_VALUE = 155
StarcoderdataPython
6413693
<filename>PyBank.py #import modules import pandas as pd import numpy as np #save file path as variable budget1 = "budget_data_1.csv" budget2 = "budget_data_2.csv" #read in first file budget1_df = pd.read_csv(budget1) budget1_df.head() #read in second file budget2_df = pd.read_csv(budget2) budget2_df.head() #stack csv files together to create new DataFrame allData = pd.concat([budget1_df, budget2_df]) allData.head() #Count total months and sum revenue TotalMonths = allData["Date"].count() TotalRevenue = allData["Revenue"].sum() #Calculate monthly change in revenue returns = allData["Revenue"] - allData["Revenue"].shift(1) returns.head() #Add in monthly change column allData["Monthly Change"] = returns allData.head() #calculate average revenue change, greatest change and greatest decline avgChange = allData["Monthly Change"].mean() maxChange = allData["Monthly Change"].max() minChange = allData["Monthly Change"].min() #final output print (" Financial Analysis") print ("----------------------------") print("Total Months: " + str(TotalMonths)) print("Total Revenue: " + str(TotalRevenue)) print("Average Revenue Change: " + str(avgChange)) print("Greatest Increase in Revenue: " + str(maxChange)) print("Greatest Decrease in Revenue: " + str(minChange)) #trying to consolidate the months/dates so that I can accurately calculate the monthly changes, etc. #allData.set_index("Date", inplace=True) #allData["Date"] = pd.to_datetime(allData["Date"]) #allData["Date"].groupby(pd.TimeGrouper(freq='M')) #allData.head()
StarcoderdataPython
9649511
# -*- coding: utf-8 -*- """Community-developed Python SDK for the DNA Center APIs. Copyright (c) 2019-2020 Cisco and/or its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import logging from ._metadata import * from .api import DNACenterAPI from .exceptions import ( AccessTokenError, ApiError, dnacentersdkException, DownloadFailure, MalformedRequest, RateLimitError, RateLimitWarning, VersionError, ) from .models.mydict import mydict_data_factory # Initialize Package Logging logging.getLogger(__name__).addHandler(logging.NullHandler()) logger = logging.getLogger(__name__) from pkg_resources import get_distribution release = get_distribution('dnacentersdk').version __version__ = '.'.join(release.split('.')[:3])
StarcoderdataPython
8106845
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data generators for the CNN and Daily Mail datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import hashlib import io import os import tarfile import six from tensor2tensor.data_generators import generator_utils from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import text_encoder from tensor2tensor.data_generators import text_problems from tensor2tensor.utils import registry import tensorflow as tf # Links to data from http://cs.nyu.edu/~kcho/DMQA/ _CNN_STORIES_DRIVE_URL = "https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfTHk4NFg2SndKcjQ" _DAILYMAIL_STORIES_DRIVE_URL = "https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfM1BxdkxVaTY2bWs" # Note: using See et al. (2017) as reference for data generation # For more info, use the links below # Train/Dev/Test Splits for summarization data _TRAIN_URLS = "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_train.txt" _DEV_URLS = "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_val.txt" _TEST_URLS = "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_test.txt" # End-of-sentence marker. EOS = text_encoder.EOS_ID # Techniques for data prep from See et al. (2017) dm_single_close_quote = u"\u2019" # unicode dm_double_close_quote = u"\u201d" # Acceptable ways to end a sentence. END_TOKENS = [ u".", u"!", u"?", u"...", u"'", u"`", u"\"", dm_single_close_quote, dm_double_close_quote, u")" ] def _maybe_download_corpora(tmp_dir, is_training): """Download corpora if necessary and unzip them. Args: tmp_dir: directory containing dataset. is_training: whether we're in training mode or not. Returns: List of all files generated and path to file containing train/dev/mnist split info. """ cnn_filename = "cnn_stories.tgz" cnn_finalpath = os.path.join(tmp_dir, "cnn/stories/") dailymail_filename = "dailymail_stories.tgz" dailymail_finalpath = os.path.join(tmp_dir, "dailymail/stories/") if not tf.gfile.Exists(cnn_finalpath): cnn_file = generator_utils.maybe_download_from_drive( tmp_dir, cnn_filename, _CNN_STORIES_DRIVE_URL) with tarfile.open(cnn_file, "r:gz") as cnn_tar: cnn_tar.extractall(tmp_dir) if not tf.gfile.Exists(dailymail_finalpath): dailymail_file = generator_utils.maybe_download_from_drive( tmp_dir, dailymail_filename, _DAILYMAIL_STORIES_DRIVE_URL) with tarfile.open(dailymail_file, "r:gz") as dailymail_tar: dailymail_tar.extractall(tmp_dir) cnn_files = tf.gfile.Glob(cnn_finalpath + "*") dailymail_files = tf.gfile.Glob(dailymail_finalpath + "*") all_files = cnn_files + dailymail_files if is_training: urls_path = generator_utils.maybe_download(tmp_dir, "all_train.txt", _TRAIN_URLS) else: urls_path = generator_utils.maybe_download(tmp_dir, "all_val.txt", _DEV_URLS) return all_files, urls_path def example_splits(url_file, all_files): """Generate splits of the data.""" def generate_hash(inp): """Generate a sha1 hash to match the raw url to the filename extracted.""" h = hashlib.sha1() h.update(inp) return h.hexdigest() all_files_map = {f.split("/")[-1]: f for f in all_files} urls = [] for line in tf.gfile.Open(url_file): urls.append(line.strip().encode("utf-8")) filelist = [] for url in urls: url_hash = generate_hash(url) filename = url_hash + ".story" if filename not in all_files_map: tf.logging.info("Missing file: %s" % url) continue filelist.append(all_files_map[filename]) tf.logging.info("Found %d examples" % len(filelist)) return filelist def example_generator(all_files, urls_path, sum_token): """Generate examples.""" def fix_run_on_sents(line): if u"@highlight" in line: return line if not line: return line if line[-1] in END_TOKENS: return line return line + u"." filelist = example_splits(urls_path, all_files) story_summary_split_token = u" <summary> " if sum_token else " " for story_file in filelist: story = [] summary = [] reading_highlights = False for line in tf.gfile.Open(story_file, "rb"): if six.PY2: line = unicode(line.strip(), "utf-8") else: line = line.strip().decode("utf-8") line = fix_run_on_sents(line) if not line: continue elif line.startswith(u"@highlight"): if not story: break # No article text. reading_highlights = True elif reading_highlights: summary.append(line) else: story.append(line) if (not story) or not summary: continue yield " ".join(story) + story_summary_split_token + " ".join(summary) def _story_summary_split(story): split_str = u" <summary> " split_str_len = len(split_str) split_pos = story.find(split_str) return story[:split_pos], story[split_pos + split_str_len:] # story, summary def write_raw_text_to_files(all_files, urls_path, tmp_dir, is_training): """Write text to files.""" def write_to_file(all_files, urls_path, tmp_dir, filename): with io.open(os.path.join(tmp_dir, filename + ".source"), "w") as fstory: with io.open(os.path.join(tmp_dir, filename + ".target"), "w") as fsummary: for example in example_generator(all_files, urls_path, sum_token=True): story, summary = _story_summary_split(example) fstory.write(story + "\n") fsummary.write(summary + "\n") filename = "cnndm.train" if is_training else "cnndm.dev" tf.logging.info("Writing %s" % filename) write_to_file(all_files, urls_path, tmp_dir, filename) if not is_training: test_urls_path = generator_utils.maybe_download(tmp_dir, "all_test.txt", _TEST_URLS) filename = "cnndm.mnist" tf.logging.info("Writing %s" % filename) write_to_file(all_files, test_urls_path, tmp_dir, filename) @registry.register_problem class SummarizeCnnDailymail32k(text_problems.Text2TextProblem): """Summarize CNN and Daily Mail articles to their summary highlights.""" @property def vocab_filename(self): return "vocab.cnndailymail.%d" % self.approx_vocab_size def generate_text_for_vocab(self, data_dir, tmp_dir): del data_dir all_files, urls_path = _maybe_download_corpora(tmp_dir, True) return example_generator(all_files, urls_path, sum_token=False) def is_generate_per_split(self): return True def generate_samples(self, data_dir, tmp_dir, dataset_split): del data_dir is_training = dataset_split == problem.DatasetSplit.TRAIN all_files, urls_path = _maybe_download_corpora(tmp_dir, is_training) write_raw_text_to_files(all_files, urls_path, tmp_dir, is_training) for example in example_generator(all_files, urls_path, sum_token=True): story, summary = _story_summary_split(example) yield {"inputs": story, "targets": summary}
StarcoderdataPython
4884357
#!/usr/bin/env python import rospy import actionlib import math from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal from geometry_msgs.msg import PoseStamped, Pose, Point waypoints = [ [(6.5, 4.43, 0.0),(0.0, 0.0, -0.984047240305, 0.177907360295)], [(2.1, 2.2, 0.0), (0.0, 0.0, 0.0, 1.0)] ] g_point = Point(0, 0, 0) def feedback_cb(feedback): cur = feedback.base_position.pose.position distance = math.sqrt(math.pow(cur.x - g_point.x, 2.0) + math.pow(cur.y - g_point.y, 2.0) + math.pow(cur.z - g_point.z, 2.0)) print('[Feedback] (%f, %f, %f) dist: %f' % (cur.x, cur.y, cur.z, distance)) def goal_pose(pose): goal_pose = MoveBaseGoal() goal_pose.target_pose.header.frame_id = 'map' goal_pose.target_pose.pose.position.x = pose[0][0] goal_pose.target_pose.pose.position.y = pose[0][1] goal_pose.target_pose.pose.position.z = pose[0][2] goal_pose.target_pose.pose.orientation.x = pose[1][0] goal_pose.target_pose.pose.orientation.y = pose[1][1] goal_pose.target_pose.pose.orientation.z = pose[1][2] goal_pose.target_pose.pose.orientation.w = pose[1][3] return goal_pose if __name__ == '__main__': rospy.init_node('patrol') client = actionlib.SimpleActionClient('move_base', MoveBaseAction) client.wait_for_server() while not rospy.is_shutdown(): for pose in waypoints: goal = goal_pose(pose) g_point = goal.target_pose.pose.position print("going to goal: %f, %f, %f" % (g_point.x, g_point.y, g_point.z)) client.send_goal(goal, feedback_cb = feedback_cb) client.wait_for_result() print('[Result] State: %d' % (client.get_state())) print('[Result] Status: %s' % (client.get_goal_status_text()))
StarcoderdataPython
4905319
"""Testing nodes for unimpeded model development """ from typing import Any, Dict import logging import pandas as pd from mlflow import sklearn as mlf_sklearn from sklearn.pipeline import Pipeline as sklearn_Pipeline import random from copy import deepcopy
StarcoderdataPython
1631499
<gh_stars>1-10 import threading, queue import time lock = threading.Lock() q = queue.Queue() c = 0 def task(i): global c d = 0 for v in range(100000): d += 1 with lock: c += d print("Thread %s" % (i)) if __name__ == "__main__": tasks = [] for i in range(100): add_task = threading.Thread(target=task, args=(i,)) add_task.start() tasks.append(add_task) for task in tasks: task.join() print("Final result of 100 times 100000: %s" % c)
StarcoderdataPython
8159062
<gh_stars>0 """Find the parameters for a levels adjustment between two images.""" import concurrent.futures from PIL import Image import numpy as np from scipy.optimize import curve_fit from level import LevelsAdjustment, level_array def match_histogram(x: np.ndarray, y: np.ndarray, *, xtol: float = 1 / 1024, samples: int = 2048) -> LevelsAdjustment: """ Find the levels adjustments for arrays representing a single band by comparing quantiles of the image. This is roughly equivalent to the histogram plots provided in image editing software. For large images, this method can speed up the fit by reducing the size of the data significantly. Note that it does *not* take into account the position of pixels when calculating error. :param x: The array to be leveled, with values in the range [0, 255]. :param y: The array to match, with values in the range [0, 255]. :param xtol: The tolerance for the curve fit. :param samples: The number of quantiles to compare. :return: The levels adjustment for the array. """ # Take quantiles and scale to [0, 1] xdata = np.divide(np.quantile(x, np.linspace(0, 1, samples)), 255) ydata = np.divide(np.quantile(y, np.linspace(0, 1, samples)), 255) # Find the optimal values for the parameters popt, pcov = curve_fit(level_array, xdata, ydata, method='dogbox', xtol=xtol, p0=[0, 1, 0, 1, 1], bounds=([0, 0, 0, 0, 0], [1, 1, 1, 1, np.inf])) return LevelsAdjustment(*popt) def match_array(x: np.ndarray, y: np.ndarray, *, xtol: float = 1 / 1024, samples: int = 2048) -> LevelsAdjustment: """ Find the levels adjustments for arrays representing a single band by comparing pixels in the image. This is roughly equivalent to the histogram plots provided in image editing software. For large images, the data is sub-sampled using a histogram and fit to provide an improved initial guess. Note that this method *does* take into account the position of pixels when calculating error. :param x: The array to be leveled, with values in the range [0, 255]. :param y: The array to match, with values in the range [0, 255]. :param xtol: The tolerance for the curve fit. :param samples: The number of quantiles to compare. :return: The levels adjustment for the array. """ # If the image size is greater than the number of samples, # find an initial guess based on the sub-sampled histogram p0 = (match_histogram(x, y, xtol=1 / 256, samples=samples) if x.size > samples else [0, 1, 0, 1, 1]) # Scale to [0, 1] xdata = np.divide(x.ravel(), 255) ydata = np.divide(y.ravel(), 255) # Find the optimal values for the parameters popt, pcov = curve_fit(level_array, xdata, ydata, method='dogbox', xtol=xtol, p0=p0, bounds=([0, 0, 0, 0, 0], [1, 1, 1, 1, np.inf])) return LevelsAdjustment(*popt) def match_images(x: Image.Image, y: Image.Image, *, resample: int = Image.LANCZOS, histogram: bool = False) -> list[LevelsAdjustment]: """ Find the levels adjustments for each band from one image to another. :param x: The original image to be leveled. :param y: The leveled image to compare to. :param resample: Resampling filter to use when resizing images. :param histogram: Whether to level the image based on the histogram only. :return: A list of levels adjustments for each band. """ # If dimensions do not match, resize down to match if x.size != y.size: new_size = min(x.size[0], y.size[0]), min(x.size[1], y.size[1]) x = x.resize(new_size, resample=resample) y = y.resize(new_size, resample=resample) # Curve fit each band separately using multiprocessing with concurrent.futures.ThreadPoolExecutor() as executor: if not histogram: match = match_array else: match = match_histogram futures = [executor.submit(match, np.asarray(x), np.asarray(y)) for x, y in zip(x.split(), y.split())] # Print each result results = [future.result() for future in futures] for b, adj in zip(x.getbands(), results): t = tuple(list(np.multiply(adj, 255))[:4] + [adj[4]]) print(b + ":", t) # print the parameters for each band return results
StarcoderdataPython
4848015
import numpy as np import pandas as pd def generate_gbm_returns(mu, sigma, samples, scenarios, random_state=0): """ :param mu: vector of expected returns :param sigma: vector of variances - returns are assumed uncorrelated :param samples: number of samples in each scenario :param scenarios: number of scenarios :param random_state: random seed :return: a data frame of sample returns of shape (len(mu), samples, scenarios) """ #TODO pass # TODO: use random generator with seed def geometric_brownian_motion(mu, sigma, years, scenarios, initial_price=1.0, steps_per_year=12, prices=True): """ Evolution of stock price using a Geometric Brownian Motion model Generates an ensemble of time series of prices according to GBM :param mu: the mean drift :param sigma: the price volatility :param years: number of years to simulate :param steps_per_year: Number of periods per year :param scenarios: number of sample paths to simulate :param initial_price: initial price :param prices: return prices if True, returns if False :return: A data frame with all the price (or return) sample paths """ dt = 1 / steps_per_year n_steps = int(years * steps_per_year) rets_plus_1 = np.random.normal(size=(n_steps, scenarios), loc=1 + mu * dt, scale=sigma * np.sqrt(dt)) # fix the first row rets_plus_1[0] = 1 return initial_price * pd.DataFrame(rets_plus_1).cumprod() if prices else pd.DataFrame(rets_plus_1 - 1)
StarcoderdataPython
12836751
from django.contrib import admin from django.utils.translation import gettext_lazy as _ from django.forms import ModelForm from danceschool.core.admin import EventChildAdmin, EventOccurrenceInline from danceschool.core.models import Event from danceschool.core.forms import LocationWithDataWidget from .models import PrivateEvent, PrivateEventCategory, EventReminder class EventReminderInline(admin.StackedInline): model = EventReminder extra = 0 class PrivateEventAdminForm(ModelForm): ''' Custom form for private events is needed to include necessary Javascript for room selection, even though capacity is not an included field in this admin. ''' class Meta: model = PrivateEvent exclude = [ 'month', 'year', 'startTime', 'endTime', 'duration', 'submissionUser', 'registrationOpen', 'capacity', 'status' ] widgets = { 'location': LocationWithDataWidget, } class Media: js = ('js/serieslocation_capacity_change.js', 'js/location_related_objects_lookup.js') class PrivateEventAdmin(EventChildAdmin): base_model = PrivateEvent form = PrivateEventAdminForm show_in_index = True list_display = ('name', 'category', 'nextOccurrenceTime', 'firstOccurrenceTime', 'location_given', 'displayToGroup') list_filter = ('category', 'displayToGroup', 'location', 'locationString') search_fields = ('title', ) ordering = ('-endTime', ) inlines = [EventOccurrenceInline, EventReminderInline] fieldsets = ( (None, { 'fields': ('title', 'category', 'descriptionField', 'link') }), ('Location', { 'fields': (('location', 'room'), 'locationString') }), ('Visibility', { 'fields': ('displayToGroup', 'displayToUsers'), }) ) def location_given(self, obj): if obj.room and obj.location: return _('%s, %s' % (obj.room.name, obj.location.name)) if obj.location: return obj.location.name return obj.locationString def save_model(self, request, obj, form, change): obj.status = Event.RegStatus.disabled obj.submissionUser = request.user obj.save() admin.site.register(PrivateEvent, PrivateEventAdmin) admin.site.register(PrivateEventCategory)
StarcoderdataPython
6614660
<filename>Contents/Code/agents/ave.py # coding=utf-8 import datetime import re from bs4 import BeautifulSoup import requests from .base import Base class AVE(Base): name = "AVEntertainments" def get_results(self, media): rv = [] movie_id = self.get_local_id(media) if movie_id: if movie_id.lower().startswith("red-"): movie_id = movie_id.lower().replace("red-", "red") rv.extend(self.get_results_by_keyword(movie_id)) else: vol_ids = self.get_volumn_id(media) if vol_ids: for vol_id in vol_ids: rv.extend(self.get_results_by_keyword(vol_id)) rv.extend(self.get_results_by_keyword(media.name)) return rv def get_results_by_keyword(self, keyword): url = "https://www.aventertainments.com/search_Products.aspx" params = { "languageId": "2", "dept_id": "29", "keyword": keyword, "searchby": "keyword" } resp = requests.get(url, params=params) resp.raise_for_status() html = resp.content.decode("utf-8") soup = BeautifulSoup(html, "html.parser") wrap = soup.find("div", "shop-product-wrap") products = wrap.findAll("div", "grid-view-product") rv = [] for product in products: title_ele = product.find("p", "product-title").find("a") url = title_ele["href"] match = re.search("product_id=(\d+)", url) rv.append({ "id": self.name + "." + match.group(1), "name": title_ele.text.strip(), "lang": self.lang, "score": 100, "thumb": product.find("div", "single-slider-product__image").find("img")["src"] }) return rv def is_match(self, media): meta_id = getattr(media, "metadata_id", "") if meta_id: return meta_id.startswith(self.name + ".") else: return bool(self.get_local_id(media) or self.get_volumn_id(media)) def get_id(self, media, data=None): if data: return self.find_ele(data, "商品番号").text.strip() return self.get_local_id(media) def get_local_id(self, media): pattern = r"(?:^|\s|\[|\(|\.|\\|\/)([a-z\d]+[-][a-z\d]+)(?:$|\s|\]|\)|\.)" if hasattr(media, "name"): match = re.search(pattern, media.name, re.I) if match: return match.group(1) filename = media.items[0].parts[0].file.lower() match = re.search(pattern, filename) if match: return match.group(1) def get_volumn_id(self, media): filename = media.items[0].parts[0].file.lower() pattern = r"vol\s*\.?\s*(\d+)" match = re.search(pattern, filename) rv = [] if match: vol = int(match.group(1)) rv.append("Vol." + str(vol)) if vol < 100: rv.append("Vol.0" + str(vol)) return rv def get_title_sort(self, media, data): return self.get_title(media, data) def get_studio(self, media, data): return self.find_ele(data, "スタジオ").text.strip() def crawl(self, media): url = "https://www.aventertainments.com/product_lists.aspx" resp = requests.get(url, params={ "product_id": media.metadata_id.split(".")[1], "languageID": 2, "dept_id": "29" }) resp.raise_for_status() html = resp.content.decode("utf-8") return BeautifulSoup(html, "html.parser") def get_original_title(self, media, data): return "[{0}] {1}".format( self.get_id(media, data), data.find("div", "section-title").find("h3").text.strip() ) def get_originally_available_at(self, media, data): ele = self.find_ele(data, "発売日") if ele: dt_str = ele.text.strip() match = re.search("\d+/\d+/\d+", dt_str) try: if match: return datetime.datetime.strptime(match.group(0), "%m/%d/%Y") except ValueError: pass def get_roles(self, media, data): ele = self.find_ele(data, "主演女優") if ele: return [ item.text.strip() for item in ele.findAll("a") ] return [] def get_duration(self, media, data): ele = self.find_ele(data, "収録時間") if ele: match = re.search("\d+", ele.text) if match: return int(match.group(0))*60*1000 def get_collections(self, media, data): rv = [] studio = self.get_studio(media, data) if studio: rv.append(studio) series = self.find_ele(data, "シリーズ") if series: rv.append(series.text.strip()) return rv def get_genres(self, media, data): ele = self.find_ele(data, "カテゴリ") if ele: return [ele.text.strip() for ele in ele.findAll("a")] return [] def get_summary(self, media, data): ele = data.find("div", "product-description") if ele: return ele.text.strip() def get_posters(self, media, data): thumbs = self.get_thumbs(media, data) return [ thumb.replace("bigcover", "jacket_images") for thumb in thumbs ] def get_thumbs(self, media, data): ele = data.find("div", {"id": "PlayerCover"}) if ele: return [ ele.find("img")["src"] ] return [] def find_ele(self, data, title): single_infos = data.findAll("div", "single-info") for single_info in single_infos: if single_info.find("span", "title").text.strip() == title: return single_info.find("span", "title").findNext("span")
StarcoderdataPython
247583
# https://app.codility.com/demo/results/trainingUJUBFH-2H3/ def solution(X, A): """ DINAKAR Clue -> Find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X [1, 3, 1, 4, 2, 3, 5, 4] X = 5 ie. {1, 2, 3, 4, 5} here 1 to X/5 is completed so we return the index which is time """ positions = set() for index, item in enumerate(A): print("Current Time " + str(index)) print("Position " + str(item)) positions.add(item) print("Positions covered..." + str(positions)) if len(positions) == X: return index return -1 result = solution(5, [1, 3, 1, 4, 2, 3, 5, 4]) print("Sol " + str(result)) """ Current Time 0 Position 1 Positions covered...{1} Current Time 1 Position 3 Positions covered...{1, 3} Current Time 2 Position 1 Positions covered...{1, 3} Current Time 3 Position 4 Positions covered...{1, 3, 4} Current Time 4 Position 2 Positions covered...{1, 2, 3, 4} Current Time 5 Position 3 Positions covered...{1, 2, 3, 4} Current Time 6 Position 5 Positions covered...{1, 2, 3, 4, 5} Sol 6 """
StarcoderdataPython
4972811
from jadlog.calcula import peso_cubagem def test_peso_cubagem_expresso(): cubagens = peso_cubagem(72, 44, 62) peso_cubagem_expresso = cubagens['Cubagem Expresso'] assert peso_cubagem_expresso == 32.736 def test_peso_cubagem_rodoviario(): cubagens = peso_cubagem(72, 44, 62) peso_cubagem_rodoviario = cubagens['Cubagem Rodoviario'] assert peso_cubagem_rodoviario == 58.93069306930693 def test_peso_cubagem_expresso_round(): cubagens = peso_cubagem(72, 44, 62) peso_cub_exp = cubagens['Cubagem Expresso'] peso_cub_exp_round = round(peso_cub_exp, 2) assert peso_cub_exp_round == 32.74 def test_peso_cubagem_rodoviario_round(): cubagens = peso_cubagem(72, 44, 62) peso_cub_rod = cubagens['Cubagem Rodoviario'] peso_cub_rod_round = round(peso_cub_rod, 2) assert peso_cub_rod_round == 58.93 def test_peso_cubagem_geral(): cubagens = peso_cubagem(72, 42, 62) assert cubagens == {'Cubagem Expresso': 31.248, 'Cubagem Rodoviario': 56.25202520252025}
StarcoderdataPython
9742354
import csb.test as test from csb.bio.sequence import RichSequence, SequenceTypes from csb.bio.sequence.alignment import IdentityMatrix, SimilarityMatrix from csb.bio.sequence.alignment import GlobalAlignmentAlgorithm, LocalAlignmentAlgorithm, AlignmentResult @test.unit class TestIdentityMatrix(test.Case): def setUp(self): super(TestIdentityMatrix, self).setUp() self.matrix = IdentityMatrix(2, -3) def testScore(self): self.assertEqual(self.matrix.score("a", "a"), 2) self.assertEqual(self.matrix.score("a", "b"), -3) @test.unit class TestSimilarityMatrix(test.Case): def setUp(self): super(TestSimilarityMatrix, self).setUp() self.matrix = SimilarityMatrix(SimilarityMatrix.BLOSUM62) def testScore(self): self.assertEqual(self.matrix.score("A", "A"), 4) self.assertEqual(self.matrix.score("A", "R"), -1) self.assertEqual(self.matrix.score("R", "A"), -1) @test.unit class TestGlobalAlignmentAlgorithm(test.Case): def setUp(self): super(TestGlobalAlignmentAlgorithm, self).setUp() self.seq1 = RichSequence('s1', '', 'CCABBBCBBCABAABCCEAAAAAAAAAAAAFAA', SequenceTypes.Protein) self.seq2 = RichSequence('s1', '', 'AZCBBABAABCCEF', SequenceTypes.Protein) self.algorithm = GlobalAlignmentAlgorithm(scoring=IdentityMatrix(1, -1), gap=0) def testAlign(self): ali = self.algorithm.align(self.seq1, self.seq2) self.assertEqual(ali.query.sequence, "CCA-BBBCBBCABAABCCEAAAAAAAAAAAAFAA") self.assertEqual(ali.subject.sequence, "--AZ---CBB-ABAABCCE------------F--") self.assertEqual(ali.query.residues[3], self.seq1.residues[3]) self.assertTrue(ali.query.residues[3] is self.seq1.residues[3]) self.assertEqual(ali.qstart, 1) self.assertEqual(ali.qend, 33) self.assertEqual(ali.start, 1) self.assertEqual(ali.end, 14) self.assertEqual(ali.length, 34) self.assertEqual(ali.gaps, 21) self.assertEqual(ali.identicals, 13) self.assertEqual(ali.identity, 13 / 34.0 ) self.assertEqual(ali.score, 13) def testEmptyAlignment(self): seq1 = RichSequence('s1', '', 'AAAA', SequenceTypes.Protein) seq2 = RichSequence('s2', '', 'BBBB', SequenceTypes.Protein) ali = self.algorithm.align(seq1, seq2) self.assertTrue(ali.is_empty) @test.unit class TestLocalAlignmentAlgorithm(test.Case): def setUp(self): super(TestLocalAlignmentAlgorithm, self).setUp() self.seq1 = RichSequence('s1', '', 'CCABBBCBBCABAABCCEAAAAAAAAAAAAFAA', SequenceTypes.Protein) self.seq2 = RichSequence('s1', '', 'AZCBBABAACBCCEF', SequenceTypes.Protein) self.algorithm = LocalAlignmentAlgorithm(scoring=IdentityMatrix(1, -1), gap=-1) def testAlign(self): ali = self.algorithm.align(self.seq1, self.seq2) self.assertEqual(ali.query.sequence, "CBBCABAA-BCCE") self.assertEqual(ali.subject.sequence, "CBB-ABAACBCCE") self.assertEqual(ali.qstart, 7) self.assertEqual(ali.qend, 18) self.assertEqual(ali.start, 3) self.assertEqual(ali.end, 14) self.assertEqual(ali.length, 13) self.assertEqual(ali.gaps, 2) self.assertEqual(ali.identicals, 11) self.assertEqual(ali.identity, 11 / 13.0 ) self.assertEqual(ali.score, 9) def testEmptyAlignment(self): seq1 = RichSequence('s1', '', 'AAAA', SequenceTypes.Protein) seq2 = RichSequence('s2', '', 'BBBB', SequenceTypes.Protein) ali = self.algorithm.align(seq1, seq2) self.assertTrue(ali.is_empty) @test.unit class TestAlignmentResult(test.Case): def setUp(self): super(TestAlignmentResult, self).setUp() self.seq1 = RichSequence('s1', '', 'AB-D', SequenceTypes.Protein) self.seq2 = RichSequence('s2', '', 'A-CD', SequenceTypes.Protein) self.ali = AlignmentResult(5.5, self.seq1, self.seq2, 10, 12, 20, 22) self.es = RichSequence('s1', '', '') self.empty = AlignmentResult(0, self.es, self.es, 0, 0, 0, 0) def testConstructor(self): self.assertRaises(ValueError, AlignmentResult, 1, self.es, self.es, 0, 0, 0, 0) self.assertRaises(ValueError, AlignmentResult, 0, self.es, self.es, 1, 0, 0, 0) self.assertRaises(ValueError, AlignmentResult, 0, self.es, self.es, 0, 1, 0, 0) self.assertRaises(ValueError, AlignmentResult, 0, self.es, self.es, 0, 0, 1, 0) self.assertRaises(ValueError, AlignmentResult, 0, self.es, self.es, 0, 0, 0, 1) self.assertRaises(ValueError, AlignmentResult, 1, self.seq1, self.seq2, 0, 0, 0, 0) def testStr(self): string = r""" 10 AB-D 12 20 A-CD 22 """.strip("\r\n") self.assertEqual(string, str(self.ali)) def testAlignment(self): ali = self.ali.alignment() self.assertEqual(ali.rows[1].sequence, self.seq1.sequence) self.assertEqual(ali.rows[2].sequence, self.seq2.sequence) def testQuery(self): self.assertEqual(self.ali.query.sequence, self.seq1.sequence) self.assertEqual(self.ali.query.residues[2], self.seq1.residues[2]) self.assertTrue(self.ali.query.residues[2] is self.seq1.residues[2]) def testSubject(self): self.assertEqual(self.ali.subject.sequence, self.seq2.sequence) self.assertEqual(self.ali.subject.residues[3], self.seq2.residues[3]) self.assertTrue(self.ali.subject.residues[3] is self.seq2.residues[3]) def testQstart(self): self.assertEqual(self.ali.qstart, 10) def testQend(self): self.assertEqual(self.ali.qend, 12) def testStart(self): self.assertEqual(self.ali.start, 20) def testEnd(self): self.assertEqual(self.ali.end, 22) def testLength(self): self.assertEqual(self.ali.length, 4) def testScore(self): self.assertEqual(self.ali.score, 5.5) def testGaps(self): self.assertEqual(self.ali.gaps, 2) def testIdenticals(self): self.assertEqual(self.ali.identicals, 2) def testIdentity(self): self.assertEqual(self.ali.identity, 0.5) def testIsEmpty(self): self.assertFalse(self.ali.is_empty) es = RichSequence('s1', '', '') empty = AlignmentResult(0, es, es, 0, 0, 0, 0) self.assertTrue(empty.is_empty) if __name__ == '__main__': test.Console()
StarcoderdataPython
32838
<filename>organization/job_urls.py<gh_stars>0 from django.conf.urls import url, patterns urlpatterns = patterns('organization.views', url(r'^organization/(?P<organization_id>\d+)/job/create/$', 'job_create', name='job_create'), url(r'^job/create/$', 'job_create_standalone', name='job_create_standalone'), url(r'^job/(?P<job_id>\d+)/edit/$', 'job_edit', name='job_edit'), url(r'^job/(?P<job_id>\d+)/$', 'job_detail', name='job_detail'), url(r'^job/$', 'job_list', name='job_list'), )
StarcoderdataPython
6574424
class Solution: def exist(self, board, word): if not word: return True if not board: return False m=len(board) n=len(board[0]) w=len(word)-1 def dfs(i,j,k): if (i<0) or (i>=m) or (j<0) or (j>=n): return False if board[i][j] != word[k]: return False if board[i][j]=='#': return False if k==w: return True tmp = board[i][j] board[i][j]='#' k +=1 for x,y in ((+1,0),(-1,0),(0,-1),(0,+1)): if dfs(i+x,j+y,k): return True board[i][j]=tmp return False for i in range(m): for j in range(n): if dfs(i,j,0): return True return False
StarcoderdataPython
11235149
import compas_rhino from compas.datastructures import Mesh from compas.geometry import delaunay_from_points from compas.datastructures import trimesh_remesh from compas_rhino.artists import MeshArtist # get the boundary curve # and divide into segments of a specific length boundary = compas_rhino.rs.GetObject("Select Boundary Curve", 4) length = compas_rhino.rs.GetReal("Select Edge Target Length", 2.0) points = compas_rhino.rs.DivideCurve(boundary, compas_rhino.rs.CurveLength(boundary) / length) # generate a delaunay triangulation # from the points on the boundary faces = delaunay_from_points(points, boundary=points) mesh = Mesh.from_vertices_and_faces(points, faces) # run the remeshing algorithm # and draw the result trimesh_remesh( mesh, target=length, kmax=500, allow_boundary_split=True, allow_boundary_swap=True) artist = MeshArtist(mesh) artist.draw_faces(join_faces=True) artist.redraw()
StarcoderdataPython
39445
<reponame>EgorBlagov/l2address import re from abc import ABC, abstractmethod from .utils import parse_hex, per_join class Formatter(ABC): def _to_clean_str(self, value, max_value): value_str = str(hex(value))[2:] full_mac_str = '0' * (self._hex_digits_count(max_value) - len(value_str)) + value_str return full_mac_str def _hex_digits_count(self, value): return len(hex(value)[2:]) def _common_regex(self, max_value, delimeter, step): return "^" + per_join([r'[\da-fA-f]' for _ in range(self._hex_digits_count(max_value))], delimeter, step) + "$" @abstractmethod def format(self, value, max_value): pass def parse(self, _str, max_value): m = re.match(self._get_validator_regexp(_str, max_value), _str) if m is None: raise ValueError('Invalid MAC address format') else: return self._parse_value_from_str(_str) def _parse_value_from_str(self, _str): return parse_hex(_str) @abstractmethod def _get_validator_regexp(self, _str, max_value): pass class ColonFormatter(Formatter): def format(self, value, max_value): return per_join(self._to_clean_str(value, max_value), ':', 2) def _get_validator_regexp(self, _str, max_value): return self._common_regex(max_value, r'\:', 2) class PeriodFormatter(Formatter): def __init__(self, step=2): super().__init__() self.step = step def format(self, value, max_value): return per_join(self._to_clean_str(value, max_value), '.', self.step) def _get_validator_regexp(self, _str, max_value): return self._common_regex(max_value, r'\.', self.step) class HyphenFormatter(Formatter): def format(self, value, max_value): return per_join(self._to_clean_str(value, max_value), '-', 2) def _get_validator_regexp(self, _str, max_value): return self._common_regex(max_value, r'\-', 2) class CleanFormatter(Formatter): def format(self, value, max_value): return self._to_clean_str(value, max_value) def _get_validator_regexp(self, _str, max_value): return self._common_regex(max_value, '', 2) DEFAULT_FORMATTERS = [ ColonFormatter(), PeriodFormatter(2), PeriodFormatter(3), PeriodFormatter(4), HyphenFormatter(), CleanFormatter() ]
StarcoderdataPython
9756086
<gh_stars>0 from rubygems_utils import RubyGemsTestUtils class RubyGemsTestrubygems_tty_box(RubyGemsTestUtils): def test_gem_list_rubygems_tty_box(self): self.gem_is_installed("tty-box") def test_load_tty_box(self): self.gem_is_loadable("tty-box")
StarcoderdataPython
11208813
<reponame>Mithzyl/Master-college-selecting-api<filename>Favorites/migrations/0006_auto_20210208_0945.py # Generated by Django 3.1.5 on 2021-02-08 09:45 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('Majors', '0008_auto_20210207_0950'), ('Favorites', '0005_auto_20210208_0942'), ] operations = [ migrations.AlterField( model_name='favoritecolleges', name='add_time', field=models.DateTimeField(default=datetime.datetime(2021, 2, 8, 9, 45, 53, 702389, tzinfo=utc)), ), migrations.AlterField( model_name='favoritemajors', name='add_time', field=models.DateTimeField(default=datetime.datetime(2021, 2, 8, 9, 45, 53, 703109, tzinfo=utc)), ), migrations.AlterUniqueTogether( name='favoritemajors', unique_together={('base',)}, ), ]
StarcoderdataPython
8039229
from datetime import datetime from mongoengine import * from config import * class UserSettings(Document): email = EmailField(unique=True, required=True) location = PointField() # todo: make this required education_navigation = BooleanField() education_support = BooleanField() employment_navigation = BooleanField() employment_support = BooleanField() health_care_navigation = BooleanField() health_care_support = BooleanField() local_navigation = BooleanField() local_support = BooleanField() well_being_leisure = BooleanField() pick_up_and_delivery = BooleanField() pick_up_and_drop_off = BooleanField() homemaking_supports = BooleanField() request_type = StringField() class User(Document): email = EmailField(unique=True, required=True) date_created = DateTimeField(default=datetime.utcnow) meta = { "ordering": ["-date_created"] } class Profile(Document): email = EmailField(unique=True, required=True) first_name = StringField(required=True, max_length=NAME_MAX_LENGTH) last_name = StringField(required=True, max_length=NAME_MAX_LENGTH) date_of_birth = DateField(required=True) age = IntField(required=False) gender = StringField(required=True) image_url = StringField( required=True) # Google auth login will always provide one. description = StringField(required=True, max_length=DESCRIPTION_MAX_LENGTH) def json(self): return self.turn_to_dict() def turn_to_dict(self): return { "email": self.email, "first_name": self.first_name, "last_name": self.last_name, "date_of_birth": self.date_of_birth, "gender": self.gender, "image_url": self.image_url, "description": self.description } class UserOtherSettings(Document): email = EmailField(unique=True, required=True) location = PointField() location_enabled = BooleanField(default=True) monday = BooleanField(default=False) tuesday = BooleanField(default=False) wednesday = BooleanField(default=False) thursday = BooleanField(default=False) friday = BooleanField(default=False) saturday = BooleanField(default=False) sunday = BooleanField(default=False) morning = BooleanField(default=False) afternoon = BooleanField(default=False) evening = BooleanField(default=False) OPC = BooleanField(default=False) OQC = BooleanField(default=False) OQE = BooleanField(default=False)
StarcoderdataPython
4880842
"""visualization.py draw widgets on main frame """ import cv2 def open_window(window_name, width, height, title): """Open the display window.""" cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) cv2.resizeWindow(window_name, width, height) cv2.setWindowTitle(window_name, title) def show_fps(img, fps): """Draw fps number at top-left corner of the image.""" font = cv2.FONT_HERSHEY_SIMPLEX line = cv2.LINE_AA cv2.putText(img, "FPS: {:.1f}".format(fps), (11, 25), font, 0.5, (32, 32, 32), 4, line) cv2.putText(img, "FPS: {:.1f}".format(fps), (10, 25), font, 0.5, (240, 240, 240), 1, line) return img def record_time(a, b, c, d): time_stamp = { '_preprocess': a, '_postprocess': b, '_network': c, '_visualize': d, '_total': round((a + b + c + d), 4) } return time_stamp def show_runtime(time_stamp): print('[TRT] ', 'Timing Report') print('[TRT] ', '-' * 30) print('[TRT] ', 'Pre-Process ', 'CUDA ', str(round(time_stamp['_preprocess'], 5)) + 'ms') print('[TRT] ', 'Post-Process ', 'CUDA ', str(round(time_stamp['_postprocess'], 5)) + 'ms') print('[TRT] ', 'Network ', ' ' * 4, 'CUDA ', str(round(time_stamp['_network'], 5)) + 'ms') print('[TRT] ', 'Visualize', ' ' * 3, 'CUDA ', str(round(time_stamp['_visualize'], 5)) + 'ms') print('[TRT] ', 'Total', ' ' * 7, 'CUDA ', str(round(time_stamp['_total'], 5)) + 'ms') print('[TRT] ', '-' * 30, '\n')
StarcoderdataPython
6473794
<filename>keras/layers/custom.py from keras import backend as K from .core import Dense, Lambda from .embeddings import Embedding class SoftAttention(Dense): def call(self, x, mask=None): score = self.activation(K.dot(x, self.W) + self.b) return K.sum(x * K.dimshuffle(score, (0, 'x')), axis=1) class BitwiseEmbedding(Lambda): """ function for embedding with encoding """ def __init__(self, bit_info, *args, **kwargs): super(BitwiseEmbed, self).__init__(self.make(bit_info), *args, **kwargs) def make(self, bit_info): def func(layer_out): embeddings = [] sh = K.shape(layer_out) if K.ndim(layer_out) != 2: out_shape = sh[:-1] + (0,) faceflat = (reduce(mul, out_shape), sh[-1]) layer_out = K.reshape(layer_out, faceflat) else: out_shape = (sh[0], 0) for i, (in_dim, out_dim) in enumerate(bit_info): E = Embedding(input_dim=in_dim, output_dim=out_dim, mask_zero=True) embeddings.append(E(layer_out[:,i])) out_shape = out_shape[:-1] + (out_shape[-1]+out_dim,) merged = merge(embeddings, mode='concat') merged = K.reshape(merged, out_shape) return merged
StarcoderdataPython
8194973
<reponame>annihilatorrrr/pytgbot # -*- coding: utf-8 -*- """ A cli for bot api. Supported commands are all `Bot.*` commands. They need to be called with the parameter being json. For the command Custom commands to make stuff easier: `msg <peer> <text>` """ from itertools import chain import requests from DictObject import DictObject from luckydonaldUtils.exceptions import assert_type_or_raise from pytgbot.api_types.receivable.inline import InlineQuery from pytgbot.api_types.receivable.updates import Message, Update from pytgbot.api_types.receivable.peer import Peer, Chat, User from pytgbot.exceptions import TgApiException from pytgbot import Bot from luckydonaldUtils.logger import logging from luckydonaldUtils.interactions import input, answer from luckydonaldUtils.encoding import to_binary as b, to_native as n from inspect import getmembers, ismethod, getargspec, formatargspec from threading import Thread # cool input import readline # cool output # see iterm2_image module source, # at https://github.com/zakx/iterm2_image/blob/f1134a720c37a515c5b15c438ae7bca92d4d4c55/iterm2_image.py from io import BytesIO from base64 import b64encode import sys def read_file_to_buffer(filename): """ Reads a file to string buffer :param filename: :return: """ f = open(filename, "r") buf = BytesIO(f.read()) f.close() return buf # end def def iterm_show_file(filename, data=None, inline=True, width="auto", height="auto", preserve_aspect_ratio=True): """ https://iterm2.com/documentation-images.html :param filename: :param data: :param inline: :param width: :param height: :param preserve_aspect_ratio: Size: - N (Number only): N character cells. - Npx (Number + px): N pixels. - N% (Number + %): N percent of the session's width or height. - auto: The image's inherent size will be used to determine an appropriate dimension. :return: """ width = str(width) if width is not None else "auto" height = str(height) if height is not None else "auto" if data is None: data = read_file_to_buffer(filename) # end if data_bytes = data.getvalue() output = "\033]1337;File=" \ "name={filename};size={size};inline={inline};" \ "preserveAspectRatio={preserve};width={width};height={height}:{data}\a\n".format( filename=n(b64encode(b(filename))), size=len(data_bytes), inline=1 if inline else 0, width=width, height=height, preserve=1 if preserve_aspect_ratio else 0, data=n(b64encode(data_bytes)), ) #sys.stdout.write(output) return output # end if try: from somewhere import API_KEY # so I don't upload them to github :D except ImportError: API_KEY = None # end if __author__ = 'luckydonald' logger = logging.getLogger(__name__)# logging.add_colored_handler(level=logging.INFO) cached_chats = {} class Color(object): """ utility to return ansi colored text. just to store the colors next to the function. """ # Color codes: http://misc.flogisoft.com/bash/tip_colors_and_formatting def __init__(self): self.formatter = self.create_formatter() # end def RESET = 0 DEFAULT = 39 BLACK = 30 RED = 31 GREEN = 32 YELLOW = 33 BLUE = 34 MAGENTA = 35 CYAN = 36 WHITE = 37 GREY = 90 LIGHT_BLUE = 94 BG_RED = 41 BG_GREY = 100 BG_DEFAULT = 49 color_prefix = '\033[' def prepare_color(self, color_number): return '%s%dm' % (self.color_prefix, color_number) # end def def create_formatter(self): return DictObject.objectify(dict( color_black=self.prepare_color(self.BLACK), color_red=self.prepare_color(self.RED), color_green=self.prepare_color(self.GREEN), color_yellow=self.prepare_color(self.YELLOW), color_blue=self.prepare_color(self.BLUE), color_lightblue=self.prepare_color(self.LIGHT_BLUE), color_magenta=self.prepare_color(self.MAGENTA), color_cyan=self.prepare_color(self.CYAN), color_white=self.prepare_color(self.WHITE), color_grey=self.prepare_color(self.GREY), color_off=self.prepare_color(self.DEFAULT), # Default foreground color background_red=self.prepare_color(self.BG_RED), background_grey=self.prepare_color(self.BG_GREY), background_default=self.prepare_color(self.BG_DEFAULT), # turn of background background_off=self.prepare_color(self.BG_DEFAULT), # Default background color inverse_on=self.prepare_color(7), # Reverse (invert the foreground and background colors) inverse_off=self.prepare_color(27), # Reset reverse all_off=self.prepare_color(self.RESET), )) # end def def overwrite_color(self, string, color, prefix=False, reset=False): """ :param string: input :param color: new color :param prefix: if it also should start the color to at the beginning. :param reset: if it also should end the color at the ending. :type reset: bool | int | str :return: """ if isinstance(color, int): color = self.prepare_color(color) # end if prefix = color if prefix else "" if isinstance(reset, int): reset = self.prepare_color(reset) elif isinstance(reset, bool): reset = self.formatter.color_off if reset else "" # end if return ( prefix + string.replace(self.formatter.color_off, self.formatter.color_off+color).replace(self.formatter.all_off, self.formatter.all_off + color) + reset ) # end def # end class class CLI(object): METHOD_INCLUDES = {} # added to in the __init__ method. METHOD_EXCLUDES = ["do",] def __init__(self, API_KEY, debug=False): if API_KEY is None: API_KEY = self.ask_for_apikey() self._api_key = API_KEY self.bot = Bot(API_KEY, return_python_objects=True) self.me = self.bot.get_me() logger.info("Information about myself: {info}".format(info=self.me)) self.METHOD_INCLUDES.update({ "debug": self.cmd_debug, "help": self.cmd_help, }) self.color = Color() self.update_thread = self.create_update_thread() self.functions = {k: v for k, v in self.get_functions()} self.current_candidates = [] self.is_debug = debug self.query = "pytgbot> " # in front of the input. self.register_tab_completion() # end def def print(self, text): current_input = readline.get_line_buffer() delete_chars = len(self.query) + len(current_input) # remove the input: sys.stdout.flush() for i in range(delete_chars): sys.stdout.write("\b \b") # end for sys.stdout.write("\033[K") sys.stdout.flush() # actual output sys.stdout.write(str(text)) sys.stdout.write("\n") sys.stdout.flush() # load back the input sys.stdout.write(self.query) sys.stdout.flush() sys.stdout.write(current_input) sys.stdout.flush() readline.redisplay() # end def def ask_for_apikey(self): return answer("Input your bot API key.") # end def def register_tab_completion(self): # Register our completer function readline.parse_and_bind('tab: complete') readline.set_completer(self.complete) # Use the tab key for completion # end def def create_update_thread(self): tg_update_thread = Thread(target=self.get_updates, name="telegram update thread") tg_update_thread.daemon = True tg_update_thread.start() return tg_update_thread # end def def run(self): print("You can enter commands now.") while True: sys.stdout.write("\r") sys.stdout.flush() cmd = input(self.query) try: result_str = self.parse_input(cmd) if result_str: self.print(result_str) except Exception as e: logger.exception("Error.") self.print("{color_red}{error}{all_off}".format( error=e, **self.color.formatter )) # end try # end while # end def def update_callback(self, string): try: self.print_update(string) except AttributeError: self.print(string) raise # end try # end def def get_updates(self): last_update_id = 0 while True: # loop forever. for update in self.bot.get_updates( limit=100, offset=last_update_id + 1, poll_timeout=60, error_as_empty=True ): # for every new update last_update_id = update.update_id if self.is_debug: logger.info(repr(last_update_id)) # end if try: self.update_callback(update) except Exception: logger.exception("update_callback failed\nIncomming update: {u}".format(u=update)) # end def # end for # end while # end def def print_update(self, update): self.print(self.process_update(update)) # end def def process_update(self, update): assert_type_or_raise(update, Update, parameter_name="update") # is message if update.message: return self.process_message(update.message) elif update.channel_post: return self.process_message(update.channel_post) elif update.inline_query: qry = update.inline_query assert_type_or_raise(qry, InlineQuery, parameter_name="update.inline_query") qry_from_print = self.color.overwrite_color( self.print_peer(qry.from_peer, id_prefix=True), self.color.formatter.color_yellow, prefix=True, reset=self.color.formatter.color_white ) return "[query {id}] {from_print}:{all_off} {text}".format(from_print=qry_from_print, id=qry.id, text=qry.query, **self.color.formatter) else: return str(update) # end if # end def def process_message(self, msg): # prepare prefix with chat infos: assert_type_or_raise(msg, Message, parameter_name="msg") user_print=None if "from_peer" in msg and msg.from_peer: # 'channel' might have no `from_peer`. user_print = self.color.overwrite_color( self.print_peer(msg.from_peer, id_prefix="user"), self.color.formatter.color_yellow, prefix=True, reset=self.color.formatter.color_white ) if msg.chat.type == 'private': prefix = "{background_grey}{color_white}[msg {message_id}]{color_off} {color_yellow}{user}{color_white}: ".format( message_id=msg.message_id, user=user_print, **self.color.formatter ) elif msg.chat.type in ('group', 'supergroup'): group_print = self.color.overwrite_color( self.print_peer(msg.chat, id_prefix=True), self.color.formatter.color_yellow, prefix = True, reset = self.color.formatter.color_white ) prefix = "{background_grey}{color_white}[msg {message_id}]{color_off} {color_yellow}{user}{color_white} in {chat}: ".format( message_id=msg.message_id, user=user_print, chat=group_print, **self.color.formatter ) elif msg.chat.type == 'channel': group_print = self.color.overwrite_color( self.print_peer(msg.chat, id_prefix=True), self.color.formatter.color_yellow, prefix=True, reset=self.color.formatter.color_white ) prefix = "{background_grey}{color_white}[msg {message_id}]{color_off} {color_white}In {chat}: ".format( message_id=msg.message_id, user=user_print, chat=group_print, **self.color.formatter ) else: prefix = "{background_grey}{color_white}[msg {message_id}]{color_off} {color_red}UNKNOWN ORIGIN{color_white}: ".format( message_id=msg.message_id, **self.color.formatter ) # end if # now the message types if "text" in msg: return prefix + self.color.formatter.color_red + msg.text + self.color.formatter.all_off if "photo" in msg: photo = msg.photo[0] for p in msg.photo[1:]: if p.file_size > photo.file_size: photo = p # end if # end for return prefix + "\n" + self.process_file(photo, msg.caption, file_type="photo", height="10") + self.color.formatter.all_off if "sticker" in msg: return prefix + "\n" + self.process_file(msg.sticker, msg.caption, file_type="sticker", as_png=True, height="10") + self.color.formatter.all_off # end if # end def def process_file(self, file, caption, file_type="file", as_png=False, inline=True, height=None): file_object = self.bot.get_file(file.file_id) file_url = self.bot.get_download_url(file_object) file_content = get_file(file_url, as_png=as_png) file_name = file_url.split("/")[-1] if as_png: file_name = file_name + ".png" # end if save_file_name = str(file.file_id) + "__" + file_name return "[{type} {file_id}]\n{image}{color_red}{caption}{color_off}".format( file_id=file.file_id, caption=(" " + caption if caption else ""), image=iterm_show_file(save_file_name, data=file_content, inline=inline, height=height), type=file_type, file_name=save_file_name, **self.color.formatter ) # end def def parse_input(self, cmd): if " " not in cmd: # functions like get_me doesn't need params. command, args = cmd, None else: command, args = cmd.split(" ", maxsplit=1) if command == "msg": user, message = args.split(" ", maxsplit=1) try: user = cached_chats[user] except KeyError: return "{color_red}{inverse_on}[FAIL]{inverse_off} I don't have that peer cached.{all_off}".format( **self.color.formatter ) # TODO: accept anyway? So you can use a username or something? try: result = self.bot.send_msg(user, message) return "{color_green}{inverse_on}[ OK ]{inverse_off} {0}{all_off}".format(result, **self.color.formatter) except TgApiException as e: return "{color_red}{inverse_on}[FAIL]{inverse_off} {0}{all_off}".format(e, **self.color.formatter) # end try # end if if command not in self.functions: return '{color_red}{inverse_on}ERROR:{inverse_off} The function {0!r} was not found.{all_off}'.format( command, **self.color.formatter ) # end if cmd_func = self.functions[command] try: if args: parsed_args = parse_args(args) if not isinstance(parsed_args, (list, dict)): parsed_args = [str(parsed_args)] # end if not isinstance if isinstance(parsed_args, list): call_result = cmd_func(*parsed_args) else: assert isinstance(parsed_args, dict) call_result = cmd_func(**parsed_args) # end if isinstance else: call_result = cmd_func() # end if # end if return "{color_green}{inverse_on}[ OK ]{inverse_off} {result}{all_off}".format( result=call_result, **self.color.formatter ) except TgApiException as e: return "{color_red}{inverse_on}[FAIL]{inverse_off} {exception}{all_off}".format( exception=e, **self.color.formatter ) # end try # end def def cmd_debug(self): self.is_debug = not self.is_debug return "Turned {state} debug.".format(state="on" if self.is_debug else "off") # end if def cmd_help(self, *args, **kwargs): return self.get_help(*args, **kwargs) # end def def get_help(self, search="", return_string=True): strings = [] for name, func in self.functions.items(): if search and not name.startswith(search): continue func_str = "{func} - {doc}".format(func=self.get_func_str(func), doc=func.__doc__.strip().split("\n")[0]) if search and search == name: # perfect hit func_def = "{color_blue}def{color_off} ".format(**self.color.formatter) + self.get_func_str(func) + ":" seperator = ("-" * (len(func_def) - 1)) return func_def + "\n|>" + seperator + "\n| " + ( "\n| ".join(func.__doc__.strip().split("\n")) + "\n'>" + seperator) strings.append(func_str) # end if # end for return "\n".join(strings) # end def def get_func_str(self, func): from inspect import signature has_self = hasattr(func, "__self__") args = [] for i, param in enumerate(signature(func).parameters): if i == 0 and has_self: key = "{color_magenta}{text}{color_off}".format(text=param.name, **self.color.formatter) else: key = param.name # end if if param.default: arg = "{key}={default!r}".format(key=key, default=param.default) else: arg = arg # end if args.append(arg) # end for spec = "{name}({params})".format(name=func.__name__, params=", ".join(args)) return spec def get_functions(self): for name, func in chain(self.METHOD_INCLUDES.items(), getmembers(self.bot)): if name.startswith("_"): continue # end if if name in self.METHOD_EXCLUDES: continue # end if elif not ismethod(func): continue # end if yield name, func # end for # end def def complete(self, text, state): if state == 0: # first of list, prepare the list self.current_candidates = [cmd for cmd in list(self.functions.keys()) if cmd.startswith(text)] # end if try: return self.current_candidates[state] except IndexError: return None # end try if True: pass else: return None # This is the first time for this text, so build a match list. origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() logger.debug('origline=%s', repr(origline)) logger.debug('begin=%s', begin) logger.debug('end=%s', end) logger.debug('being_completed=%s', being_completed) logger.debug('words=%s', words) if not words: self.current_candidates = sorted(self.functions.keys()) else: try: if begin == 0: # first word candidates = self.functions.keys() else: # later word first = words[0] candidates = self.functions[first] if being_completed: # match options with portion of input # being completed self.current_candidates = [w for w in candidates if w.startswith(being_completed)] else: # matching empty string so use all candidates self.current_candidates = candidates logging.debug('candidates=%s', self.current_candidates) except (KeyError, IndexError) as err: logging.error('completion error: %s', err) self.current_candidates = [] try: response = self.current_candidates[state] except IndexError: response = None logging.debug('complete(%s, %s) => %s', repr(text), state, response) return response # end def def print_peer(self, peer, show_id=True, id_prefix="", reply=True): """ :param id_prefix: Prefix of the #id thing. Set a string, or true to have it generated. :type id_prefix: str|bool """ if isinstance(id_prefix, bool): if id_prefix: # True if isinstance(peer, User): id_prefix = "user" elif isinstance(peer, Chat): id_prefix = peer.type else: id_prefix = "unknown" # end if else: # False id_prefix = "" # end if # end if peer_string = self.peer_to_string(peer) if show_id and "id" in peer: peer_string += " ({color_lightblue}{id_prefix}#{id}{color_off})".format(id_prefix=id_prefix, id=peer.id, **self.color.formatter) return peer_string def peer_to_string(self, peer): assert_type_or_raise(peer, Peer, parameter_name="peer") if isinstance(peer, Chat): # chats return "{title}".format(title=peer.title) assert_type_or_raise(peer, User, parameter_name="peer") if peer.first_name: if peer.last_name: return "{first_name} {last_name}".format(first_name=peer.first_name, last_name=peer.last_name) # end if last_name return "{first_name}".format(first_name=peer.first_name) # not first_name elif peer.last_name: return "{last_name}".format(last_name=peer.last_name) elif peer.username: return "{}@{username}".format(username=peer.username) elif peer.id: return "#{id}".format(id=peer.id) # end if return "<UNKNOWN>" # end def # end class def get_file(file_url, as_png=True): r = requests.get(file_url) if r.status_code != 200: logger.error("Download returned: {}".format(r.content)) return None # end if fake_input = BytesIO(r.content) if not as_png: return fake_input # end if from PIL import Image # pip install Pillow im = Image.open(fake_input) del fake_input fake_output = BytesIO() im.save(fake_output, "PNG") del im fake_output.seek(0) return fake_output # end def def parse_call_result(call_result): if "ok" in call_result and "response" in call_result and "result" in call_result: result_str = "[{status}] {result}".format( status="OK " if call_result.ok else "FAIL", result=format_array(call_result.result, prefix=" ", prefix_count=7) ) return result_str # end if has 'ok', 'response' and 'result' return "'ok', 'response' or 'result' missing. Data: {data}".format(data=call_result) # end def def get_help(bot, search="", return_string=True): strings = [] for name, func in getmembers(bot): if name.startswith("_"): continue if name in CLI.METHOD_EXCLUDES: continue if search and not name.startswith(search): continue if ismethod(func): func_str = "{func} - {doc}".format(func=get_func_str(func), doc=func.__doc__.strip().split("\n")[0]) if search and search == name: # perfect hit func_def = "def " + get_func_str(func) + ":" seperator = ("-"*(len(func_def)-1)) return func_def + "\n|>" + seperator + "\n| " + ("\n| ".join(func.__doc__.strip().split("\n")) +"\n'>" + seperator) strings.append(func_str) # end if # end for return "\n".join(strings) # end def def get_func_str(func): spec = func.__name__ + formatargspec(*getargspec(func)) return spec ARRAY_ROW_FORMAT = "{prefix}{key}: {value}{postfix}" def format_array(array, prefix="", prefix_count=1): string_to_return = "" prefix_to_use = prefix * prefix_count for key in array.keys(): if string_to_return == "": string_to_return = ARRAY_ROW_FORMAT.format( prefix="", key=key, value=str(array[key]), postfix="\n" ) else: string_to_return += ARRAY_ROW_FORMAT.format( prefix=prefix_to_use, key=key, value=str(array[key]), postfix="\n" ) # end for return string_to_return # end def def peer_cache(peer, show_id=True, id_prefix="", reply=True): """ :param peer: :param show_id: :param id_prefix: Prefix of the #id thing. Set a string, or true to have it generated. :type id_prefix: str|bool :param reply: :return: """ if isinstance(id_prefix, bool): if id_prefix: # True if isinstance(peer, User): id_prefix = "user" elif isinstance(peer, Chat): id_prefix = peer.type else: id_prefix = "unknown" # end if else: # False id_prefix = "" # end if # end if peer_string = peer_to_string(peer) cached_chats[peer_string.strip()] = peer.id cached_chats[str(peer.id).strip()] = peer.id if reply: cached_chats["!"] = peer.id # end if peer_string = peer_to_string(peer) if show_id and "id" in peer: peer_string += " ({id_prefix}#{id})".format(id_prefix=id_prefix, id=peer.id) return peer_string def parse_args(string): """ `"yada hoa" yupi yeah 12 "" None "None"` -> `["yada hoa", "yupi", "yeah", 12, "", None, "None"]` :param str: :return: """ import ast is_quoted = False result_parts = [] current_str = "" while len(string) > 0: if string[0] == "\"": is_quoted = not is_quoted current_str += string[0] elif string[0].isspace(): if is_quoted: current_str += string[0] else: result_parts.append(current_str) current_str = "" # end if else: current_str += string[0] # end if string = string[1:] # end while if current_str: # last part of the array result_parts.append(current_str) # end if for i in range(len(result_parts)): # Will try for each element if it is something pythonic. Parsed type will replace original list element. try: part = ast.literal_eval(result_parts[i]) result_parts[i] = part # write it back. except ValueError: # could not parse -> is string pass # because already is str. # end try # end for return result_parts # end def parse_args if __name__ == '__main__': cli = CLI(API_KEY) cli.run() # end if # end file
StarcoderdataPython
79460
<filename>fdrtd/plugins/simon/accumulators/accumulator_statistics_bivariate.py import math as _math from fdrtd.plugins.simon.accumulators.accumulator import Accumulator from fdrtd.plugins.simon.accumulators.accumulator_statistics_univariate import AccumulatorStatisticsUnivariate class AccumulatorStatisticsBivariate(Accumulator): def __init__(self, _=None): self.accumulator_x = AccumulatorStatisticsUnivariate() self.accumulator_y = AccumulatorStatisticsUnivariate() self.accumulator_xy = AccumulatorStatisticsUnivariate() def serialize(self): return {'accumulator_x': self.accumulator_x.serialize(), 'accumulator_y': self.accumulator_y.serialize(), 'accumulator_xy': self.accumulator_xy.serialize()} @staticmethod def deserialize(dictionary): accumulator = AccumulatorStatisticsBivariate() accumulator.accumulator_x = AccumulatorStatisticsUnivariate.deserialize(dictionary['accumulator_x']) accumulator.accumulator_y = AccumulatorStatisticsUnivariate.deserialize(dictionary['accumulator_y']) accumulator.accumulator_xy = AccumulatorStatisticsUnivariate.deserialize(dictionary['accumulator_xy']) return accumulator def add(self, other): self.accumulator_x.add(other.accumulator_x) self.accumulator_y.add(other.accumulator_y) self.accumulator_xy.add(other.accumulator_xy) def update(self, data): (x, y) = data self.accumulator_x.update(x) self.accumulator_y.update(y) self.accumulator_xy.update(x*y) def finalize(self): self.accumulator_x.finalize() self.accumulator_y.finalize() self.accumulator_xy.finalize() def encrypt_data_for_upload(self, nonce): return {'accumulator_x': self.accumulator_x.encrypt_data_for_upload(nonce), 'accumulator_y': self.accumulator_y.encrypt_data_for_upload(nonce), 'accumulator_xy': self.accumulator_xy.encrypt_data_for_upload(nonce, power=2)} @staticmethod def decrypt_result_from_download(encrypted, nonce): decryption_powers = {'samples': 0, 'covariance_mle': 2, 'covariance': 2, 'correlation_coefficient': 0, 'regression_slope': 0, 'regression_interceipt': 1, 'regression_slope_only': 0} return nonce.decrypt_dictionary_numerical(encrypted, decryption_powers) def get_samples(self): return self.accumulator_xy.get_samples() def get_covariance_mle(self): return self.accumulator_xy.get_mean() - self.accumulator_x.get_mean() * self.accumulator_y.get_mean() def get_covariance(self): return self.get_covariance_mle() / (1.0 - 1.0 / self.accumulator_xy.get_samples()) def get_correlation_coefficient(self): return self.get_covariance() / _math.sqrt(self.accumulator_x.get_variance() * self.accumulator_y.get_variance()) def get_regression_slope(self): return self.get_covariance() / self.accumulator_x.get_variance() def get_regression_interceipt(self): return self.accumulator_y.get_mean() - self.get_regression_slope() * self.accumulator_x.get_mean() def get_regression_slope_only(self): return self.accumulator_xy.get_mean() / self.accumulator_x.calculate_raw_moment(2)
StarcoderdataPython
9628319
<filename>neuralocalize/utils/cifti_utils.py import itertools import warnings import cifti import nibabel as nib import numpy as np from . import constants, utils class BrainMap: """Represent a brain map object """ def __init__(self, brain_map_object): """ Initialize from a brain map object that was loaded from the nii files. """ self.brain_structure_name = brain_map_object.brain_structure self.data_indices = range( brain_map_object.index_offset, brain_map_object.index_offset + brain_map_object.index_count) if brain_map_object.vertex_indices is not None: self.surface_indices = brain_map_object.vertex_indices._indices else: self.surface_indices = [] def load_cifti_brain_data_from_file(nii_path): """ Convert dtseries.nii object into numpy matrix, and brain model meta data :param nii_path: A path to a nii file :return: numpy matrix containing the image data, brain models iterable """ print("Loading cifti file:", nii_path) nib_data = nib.load(nii_path) cifti_image = np.array(np.array(nib_data.dataobj), dtype=constants.DTYPE) brain_maps = [BrainMap(i) for i in nib_data.header.matrix.get_index_map(1).brain_models] return cifti_image, brain_maps def get_cortex_and_sub_cortex_indices(brain_maps): """Generate two list: The cortex indices and the sub-cortex indices. :param sample_file_path: the file path to load from the cortex indices. :return: (cortex indices list, sub-cortex indices list) """ ctx_inds = list(itertools.chain( brain_maps[0].data_indices, brain_maps[1].data_indices)) sub_ctx_inds = utils.remove_elements_from_list(range(91282), ctx_inds) return np.array(ctx_inds), np.array(sub_ctx_inds) def save_cifti(cifti_img, path, series=None, brain_maps=None, sample_file_path=constants.EXAMPLE_FILE_PATH): """Save the cifti image to path. :param cifti_img: [n_component, 91282] The cifti image to save. :param path: The file path to save the cifti image to. :param series: The time series to use when saving the file. If not provided, create default one which fit the size of the image. :param brain_maps: If provided add this as the BrainMap inside the cifti file. If not take default one from sample file name. :param sample_file_path: An example cifti file that is used to generate the default brain maps if needed. """ if not path.endswith('.dtseries.nii'): warnings.warn('Cifti files should be saved with ".dtseries.nii" file extension') if series is not None and series.size != cifti_img.shape[0]: warnings.warn( ("The series provided in save_cifti under utils.cifti_utils " + "does not match the cifti image size provided: " + "cifti image shape: {}, series size: {}").format(cifti_img.shape, series.size) ) series = None if series is None: series = cifti.Series(start=0.0, step=0.72, size=cifti_img.shape[0]) if brain_maps is None: _, axis = cifti.read(sample_file_path) brain_maps = axis[1] cifti.write(path, cifti_img, (series, brain_maps))
StarcoderdataPython
4917152
<reponame>JRC1995/Dynamic-Mem-Net-QA # coding: utf-8 # ### LOADING PREPROCESSED DATA # # Loading GloVe word embeddings. Building functions to convert words into their vector representations and vice versa. Loading babi induction task 10K dataset. # In[1]: import numpy as np from __future__ import division filename = 'glove.6B.100d.txt' def loadEmbeddings(filename): vocab = [] embd = [] file = open(filename,'r') for line in file.readlines(): row = line.strip().split(' ') vocab.append(row[0]) embd.append(row[1:]) print('Loaded!') file.close() return vocab,embd vocab,embd = loadEmbeddings(filename) word_vec_dim = len(embd[0]) vocab.append('<UNK>') embd.append(np.asarray(embd[vocab.index('unk')],np.float32)+0.01) vocab.append('<EOS>') embd.append(np.asarray(embd[vocab.index('eos')],np.float32)+0.01) vocab.append('<PAD>') embd.append(np.zeros((word_vec_dim),np.float32)) embedding = np.asarray(embd) embedding = embedding.astype(np.float32) def word2vec(word): # converts a given word into its vector representation if word in vocab: return embedding[vocab.index(word)] else: return embedding[vocab.index('<UNK>')] def most_similar_eucli(x): xminusy = np.subtract(embedding,x) sq_xminusy = np.square(xminusy) sum_sq_xminusy = np.sum(sq_xminusy,1) eucli_dists = np.sqrt(sum_sq_xminusy) return np.argsort(eucli_dists) def vec2word(vec): # converts a given vector representation into the represented word most_similars = most_similar_eucli(np.asarray(vec,np.float32)) return vocab[most_similars[0]] import pickle with open ('embeddingPICKLE', 'rb') as fp: processed_data = pickle.load(fp) fact_stories = processed_data[0] questions = processed_data[1] answers = np.reshape(processed_data[2],(len(processed_data[2]))) test_fact_stories = processed_data[3] test_questions = processed_data[4] test_answers = np.reshape(processed_data[5],(len(processed_data[5]))) # In[2]: import random print "EXAMPLE DATA:\n" sample = random.randint(0,len(fact_stories)) print "FACTS:\n" for i in xrange(len(fact_stories[sample])): print str(i+1)+") ", print map(vec2word,fact_stories[sample][i]) print "\nQUESTION:" print map(vec2word,questions[sample]) print "\nANSWER:" print vocab[answers[sample]] # ### CREATING TRAINING AND VALIDATION DATA # In[3]: from __future__ import division train_fact_stories = [] train_questions = [] train_answers = [] val_fact_stories = [] val_questions = [] val_answers = [] p=90 #(90% data used for training. Rest for validation) train_len = int((p/100)*len(fact_stories)) train_fact_stories = fact_stories[0:train_len] val_fact_stories = fact_stories[train_len:] train_questions = questions[0:train_len] val_questions = questions[train_len:] train_answers = answers[0:train_len] val_answers = answers[train_len:] # ### SENTENCE READING LAYER IMPLEMENTED BEFOREHAND # # Positionally encode the word vectors in each sentence, and combine all the words in the sentence to create a fixed sized vector representation for the sentence. # # "sentence embedding" # In[4]: # from __future__ import division def sentence_reader(fact_stories): #positional_encoder PAD_val = np.zeros((word_vec_dim),np.float32) pe_fact_stories = np.zeros((fact_stories.shape[0],fact_stories.shape[1],word_vec_dim),np.float32) for fact_story_index in xrange(0,len(fact_stories)): for fact_index in xrange(0,len(fact_stories[fact_story_index])): M = 0 # Code to ignore pads. for word_position in xrange(len(fact_stories[fact_story_index,fact_index])): if np.all(np.equal(PAD_val,fact_stories[fact_story_index,fact_index,word_position])): break else: M+=1 l = np.zeros((word_vec_dim),np.float32) # ljd = (1 − j/M) − (d/D)(1 − 2j/M), for word_position in xrange(0,M): for dimension in xrange(0,word_vec_dim): j = word_position + 1 # making position start from 1 instead of 0 d = dimension + 1 # making dimensions start from 1 isntead of 0 (1-100 instead of 0-99) l[dimension] = (1-(j/M)) - (d/word_vec_dim)*(1-2*(j/M)) pe_fact_stories[fact_story_index,fact_index] += np.multiply(l,fact_stories[fact_story_index,fact_index,word_position]) return pe_fact_stories train_fact_stories = sentence_reader(train_fact_stories) val_fact_stories = sentence_reader(val_fact_stories) test_fact_stories = sentence_reader(test_fact_stories) # ### Function to create randomized batches # In[5]: def create_batches(fact_stories,questions,answers,batch_size): shuffle = np.arange(len(questions)) np.random.shuffle(shuffle) batches_fact_stories = [] batches_questions = [] batches_answers = [] i=0 while i+batch_size<=len(questions): batch_fact_stories = [] batch_questions = [] batch_answers = [] for j in xrange(i,i+batch_size): batch_fact_stories.append(fact_stories[shuffle[j]]) batch_questions.append(questions[shuffle[j]]) batch_answers.append(answers[shuffle[j]]) batch_fact_stories = np.asarray(batch_fact_stories,np.float32) batch_fact_stories = np.transpose(batch_fact_stories,[1,0,2]) #result = number of facts x batch_size x fact sentence size x word vector size batch_questions = np.asarray(batch_questions,np.float32) batch_questions = np.transpose(batch_questions,[1,0,2]) #result = question_length x batch_size x fact sentence size x word vector size batches_fact_stories.append(batch_fact_stories) batches_questions.append(batch_questions) batches_answers.append(batch_answers) i+=batch_size batches_fact_stories = np.asarray(batches_fact_stories,np.float32) batches_questions = np.asarray(batches_questions,np.float32) batches_answers = np.asarray(batches_answers,np.int32) return batches_fact_stories,batches_questions,batches_answers # ### Hyperparameters # In[6]: import tensorflow as tf # Tensorflow placeholders tf_facts = tf.placeholder(tf.float32,[None,None,word_vec_dim]) tf_questions = tf.placeholder(tf.float32,[None,None,word_vec_dim]) tf_answers = tf.placeholder(tf.int32,[None]) training = tf.placeholder(tf.bool) #hyperparameters epochs = 256 learning_rate = 0.001 hidden_size = 100 passes = 3 dropout_rate = 0.1 beta = 0.0001 #l2 regularization scale regularizer = tf.contrib.layers.l2_regularizer(scale=beta) #l2 # ### All the trainable parameters initialized here # In[7]: # Parameters # FORWARD GRU PARAMETERS FOR INPUT MODULE wf = tf.get_variable("wf", shape=[3,word_vec_dim, hidden_size], initializer=tf.contrib.layers.xavier_initializer(), regularizer= regularizer) uf = tf.get_variable("uf", shape=[3,hidden_size, hidden_size], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) bf = tf.get_variable("bf", shape=[3,hidden_size],initializer=tf.zeros_initializer()) # BACKWARD GRU PARAMETERS FOR INPUT MODULE wb = tf.get_variable("wb", shape=[3,word_vec_dim, hidden_size], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) ub = tf.get_variable("ub", shape=[3,hidden_size, hidden_size], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) bb = tf.get_variable("bb", shape=[3,hidden_size],initializer=tf.zeros_initializer()) # GRU PARAMETERS FOR QUESTION MODULE (TO ENCODE THE QUESTIONS) wq = tf.get_variable("wq", shape=[3,word_vec_dim, hidden_size], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) uq = tf.get_variable("uq", shape=[3,hidden_size, hidden_size], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) bq = tf.get_variable("bq", shape=[3,hidden_size],initializer=tf.zeros_initializer()) # EPISODIC MEMORY # ATTENTION MECHANISM inter_neurons = hidden_size w1 = tf.get_variable("w1", shape=[hidden_size*4, inter_neurons], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) b1 = tf.get_variable("b1", shape=[inter_neurons], initializer=tf.zeros_initializer()) w2 = tf.get_variable("w2", shape=[inter_neurons,1], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) b2 = tf.get_variable("b2", shape=[1],initializer=tf.zeros_initializer()) # ATTENTION BASED GRU PARAMETERS watt = tf.get_variable("watt", shape=[2,hidden_size,hidden_size], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) uatt = tf.get_variable("uatt", shape=[2,hidden_size, hidden_size], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) batt = tf.get_variable("batt", shape=[2,hidden_size],initializer=tf.zeros_initializer()) # MEMORY UPDATE PARAMETERS # (UNTIED) wt = tf.get_variable("wt", shape=[passes,hidden_size*3,hidden_size], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) bt = tf.get_variable("bt", shape=[passes,hidden_size], initializer=tf.zeros_initializer()) # ANSWER MODULE PARAMETERS wa_pd = tf.get_variable("wa_pd", shape=[hidden_size*2,len(vocab)], initializer=tf.contrib.layers.xavier_initializer(), regularizer=regularizer) ba_pd = tf.get_variable("ba_pd", shape=[len(vocab)], initializer=tf.zeros_initializer()) # ### Layer Normalization # In[8]: def layer_norm(inputs,scope,scale=True,layer_norm=True,epsilon = 1e-5): if layer_norm == True: with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): if scale == False: scale = tf.ones([inputs.get_shape()[1]],tf.float32) else: scale = tf.get_variable("scale", shape=[inputs.get_shape()[1]], initializer=tf.ones_initializer()) ## ignored shift - bias will be externally added which can produce shift mean, var = tf.nn.moments(inputs, [1], keep_dims=True) LN = tf.multiply((scale / tf.sqrt(var + epsilon)),(inputs - mean)) return LN else: return inputs # ### GRU Function # # Returns a tensor of all the hidden states # In[9]: def GRU(inp,hidden, w,u,b, seq_len,scope): hidden_lists = tf.TensorArray(size=seq_len,dtype=tf.float32) i=0 def cond(i,hidden,hidden_lists): return i < seq_len def body(i,hidden,hidden_lists): x = inp[i] # GRU EQUATIONS: z = tf.sigmoid(layer_norm( tf.matmul(x,w[0]) + tf.matmul(hidden,u[0]) , scope+"_z")+ b[0]) r = tf.sigmoid(layer_norm( tf.matmul(x,w[1]) + tf.matmul(hidden,u[1]) , scope+"_r")+ b[1]) h_ = tf.tanh(layer_norm( tf.matmul(x,w[2]) + tf.multiply(r,tf.matmul(hidden,u[2])),scope+"_h") + b[2]) hidden = tf.multiply(z,h_) + tf.multiply((1-z),hidden) hidden_lists = hidden_lists.write(i,hidden) return i+1,hidden,hidden_lists _,_,hidden_lists = tf.while_loop(cond,body,[i,hidden,hidden_lists]) return hidden_lists.stack() # ### Attention based GRU # # Returns only the final hidden state. # In[10]: def attention_based_GRU(inp,hidden, w,u,b, g,seq_len,scope): i=0 def cond(i,hidden): return i < seq_len def body(i,hidden): x = inp[i] # GRU EQUATIONS: r = tf.sigmoid(layer_norm( tf.matmul(x,w[0]) + tf.matmul(hidden,u[0]), scope+"_r") + b[0]) h_ = tf.tanh(layer_norm( tf.matmul(x,w[1]) + tf.multiply(r,tf.matmul(hidden,u[1])),scope+"_h") + b[1]) hidden = tf.multiply(g[i],h_) + tf.multiply((1-g[i]),hidden) return i+1,hidden _,hidden = tf.while_loop(cond,body,[i,hidden]) return hidden # ### Dynamic Memory Network+ Model Definition # In[11]: def DMN_plus(tf_facts,tf_questions): facts_num = tf.shape(tf_facts)[0] tf_batch_size = tf.shape(tf_questions)[1] question_len = tf.shape(tf_questions)[0] hidden = tf.zeros([tf_batch_size,hidden_size],tf.float32) # Input Module # input fusion layer # bidirectional GRU forward = GRU(tf_facts,hidden, wf,uf,bf, facts_num,"Forward_GRU") backward = GRU(tf.reverse(tf_facts,[0]),hidden, wb,ub,bb, facts_num,"Backward_GRU") backward = tf.reverse(backward,[0]) encoded_input = tf.add(forward,backward) # encoded input now shape = facts_num x batch_size x hidden_size encoded_input = tf.layers.dropout(encoded_input,dropout_rate,training=training) # Question Module question_representation = GRU(tf_questions,hidden, wq,uq,bq, question_len,"Question_GRU") #question_representation's current shape = question len x batch size x hidden size question_representation = question_representation[question_len-1] #^we will only use the final hidden state. question_representation = tf.reshape(question_representation,[tf_batch_size,1,hidden_size]) # Episodic Memory Module episodic_memory = tf.identity(question_representation) encoded_input = tf.transpose(encoded_input,[1,0,2]) #now shape = batch_size x facts_num x hidden_size for i in xrange(passes): # Attention Mechanism Z1 = tf.multiply(encoded_input,question_representation) Z2 = tf.multiply(encoded_input,episodic_memory) Z3 = tf.abs(tf.subtract(encoded_input,question_representation)) Z4 = tf.abs(tf.subtract(encoded_input,episodic_memory)) Z = tf.concat([Z1,Z2,Z3,Z4],2) Z = tf.reshape(Z,[-1,4*hidden_size]) Z = tf.matmul( tf.tanh( layer_norm( tf.matmul(Z,w1), "Attention_Mechanism") + b1),w2 ) Z = layer_norm(Z,"Attention_Mechanism_2") + b2 Z = tf.reshape(Z,[tf_batch_size,1,facts_num]) g = tf.nn.softmax(Z) g = tf.transpose(g,[2,0,1]) context_vector = attention_based_GRU(tf.transpose(encoded_input,[1,0,2]), hidden, watt,uatt,batt, g,facts_num,"Attention_GRU") context_vector = tf.reshape(context_vector,[tf_batch_size,1,hidden_size]) # Episodic Memory Update concated = tf.concat([episodic_memory,context_vector,question_representation],2) concated = tf.reshape(concated,[-1,3*hidden_size]) episodic_memory = tf.nn.relu(layer_norm(tf.matmul(concated,wt[i]),"Memory_Update",scale=False) + bt[i]) episodic_memory = tf.reshape(episodic_memory,[tf_batch_size,1,hidden_size]) # Answer module # (single word answer prediction) episodic_memory = tf.reshape(episodic_memory,[tf_batch_size,hidden_size]) episodic_memory = tf.layers.dropout(episodic_memory,dropout_rate,training=training) question_representation = tf.reshape(question_representation,[tf_batch_size,hidden_size]) y_concat = tf.concat([question_representation,episodic_memory],1) # Convert to pre-softmax probability distribution y = tf.matmul(y_concat,wa_pd) + ba_pd return y # ### Cost function, Evaluation, Optimization function # In[12]: model_output = DMN_plus(tf_facts,tf_questions) # l2 regularization reg_variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) regularization = tf.contrib.layers.apply_regularization(regularizer, tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model_output, labels=tf_answers))+regularization optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) model_output = tf.nn.softmax(model_output) #Evaluate model correct_pred = tf.equal(tf.cast(tf.argmax(model_output,1),tf.int32),tf_answers) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # Initializing the variables init = tf.global_variables_initializer() # ### Training.... # In[13]: with tf.Session() as sess: # Start Tensorflow Session saver = tf.train.Saver() sess.run(init) #initialize all variables step = 1 loss_list=[] acc_list=[] val_loss_list=[] val_acc_list=[] best_val_acc=0 best_val_loss=2**30 prev_val_acc=0 patience = 20 impatience = 0 display_step = 20 min_epoch = 20 batch_size = 128 while step <= epochs: total_loss=0 total_acc=0 total_val_loss = 0 total_val_acc = 0 batches_train_fact_stories,batches_train_questions,batches_train_answers = create_batches(train_fact_stories,train_questions,train_answers,batch_size) for i in xrange(len(batches_train_questions)): # Run optimization operation (backpropagation) _,loss,acc = sess.run([optimizer,cost,accuracy], feed_dict={tf_facts: batches_train_fact_stories[i], tf_questions: batches_train_questions[i], tf_answers: batches_train_answers[i], training: True}) total_loss += loss total_acc += acc if i%display_step == 0: print "Iter "+str(i)+", Loss= "+ "{:.3f}".format(loss)+", Accuracy= "+ "{:.3f}".format(acc*100) avg_loss = total_loss/len(batches_train_questions) avg_acc = total_acc/len(batches_train_questions) loss_list.append(avg_loss) acc_list.append(avg_acc) val_batch_size = 100 #(should be able to divide total no. of validation samples without remainder) batches_val_fact_stories,batches_val_questions,batches_val_answers = create_batches(val_fact_stories,val_questions,val_answers,val_batch_size) for i in xrange(len(batches_val_questions)): val_loss, val_acc = sess.run([cost, accuracy], feed_dict={tf_facts: batches_val_fact_stories[i], tf_questions: batches_val_questions[i], tf_answers: batches_val_answers[i], training: False}) total_val_loss += val_loss total_val_acc += val_acc avg_val_loss = total_val_loss/len(batches_val_questions) avg_val_acc = total_val_acc/len(batches_val_questions) val_loss_list.append(avg_val_loss) val_acc_list.append(avg_val_acc) print "\nEpoch " + str(step) + ", Validation Loss= " + "{:.3f}".format(avg_val_loss) + ", validation Accuracy= " + "{:.3f}%".format(avg_val_acc*100)+"" print "Epoch " + str(step) + ", Average Training Loss= " + "{:.3f}".format(avg_loss) + ", Average Training Accuracy= " + "{:.3f}%".format(avg_acc*100)+"" impatience += 1 if avg_val_acc >= best_val_acc: best_val_acc = avg_val_acc saver.save(sess, 'DMN_Model_Backup/model.ckpt') print "Checkpoint created!" if avg_val_loss <= best_val_loss: impatience=0 best_val_loss = avg_val_loss if impatience > patience and step>min_epoch: print "\nEarly Stopping since best validation loss not decreasing for "+str(patience)+" epochs." break print "" step += 1 print "\nOptimization Finished!\n" print "Best Validation Accuracy: %.3f%%"%((best_val_acc*100)) # In[14]: #Saving logs about change of training and validation loss and accuracy over epochs in another file. import h5py file = h5py.File('Training_logs_DMN_plus.h5','w') file.create_dataset('val_acc', data=np.array(val_acc_list)) file.create_dataset('val_loss', data=np.array(val_loss_list)) file.create_dataset('acc', data=np.array(acc_list)) file.create_dataset('loss', data=np.array(loss_list)) file.close() # In[15]: import h5py import numpy as np import matplotlib.pyplot as plt get_ipython().magic(u'matplotlib inline') log = h5py.File('Training_logs_DMN_plus.h5','r+') # Loading logs about change of training and validation loss and accuracy over epochs y1 = log['val_acc'][...] y2 = log['acc'][...] x = np.arange(1,len(y1)+1,1) # (1 = starting epoch, len(y1) = no. of epochs, 1 = step) plt.plot(x,y1,'b',label='Validation Accuracy') plt.plot(x,y2,'r',label='Training Accuracy') plt.legend(loc='lower right') plt.xlabel('epoch') plt.show() y1 = log['val_loss'][...] y2 = log['loss'][...] plt.plot(x,y1,'b',label='Validation Loss') plt.plot(x,y2,'r',label='Training Loss') plt.legend(loc='upper right') plt.xlabel('epoch') plt.show() # In[16]: with tf.Session() as sess: # Begin session print 'Loading pre-trained weights for the model...' saver = tf.train.Saver() saver.restore(sess, 'DMN_Model_Backup/model.ckpt') sess.run(tf.global_variables()) print '\nRESTORATION COMPLETE\n' print 'Testing Model Performance...' total_test_loss = 0 total_test_acc = 0 test_batch_size = 100 #(should be able to divide total no. of test samples without remainder) batches_test_fact_stories,batches_test_questions,batches_test_answers = create_batches(test_fact_stories,test_questions,test_answers,test_batch_size) for i in xrange(len(batches_test_questions)): test_loss, test_acc = sess.run([cost, accuracy], feed_dict={tf_facts: batches_test_fact_stories[i], tf_questions: batches_test_questions[i], tf_answers: batches_test_answers[i], training: False}) total_test_loss += test_loss total_test_acc += test_acc avg_test_loss = total_test_loss/len(batches_test_questions) avg_test_acc = total_test_acc/len(batches_test_questions) print "\nTest Loss= " + "{:.3f}".format(avg_test_loss) + ", Test Accuracy= " + "{:.3f}%".format(avg_test_acc*100)+""
StarcoderdataPython
376379
from rest_framework.fields import SerializerMethodField from rest_framework.serializers import ModelSerializer from ..quips import models class CliqueSerializer(ModelSerializer): """Clique model serializer.""" class Meta: model = models.Clique fields = ["id", "slug"] class SpeakerSerializer(ModelSerializer): """Speaker model serializer.""" class Meta: model = models.Speaker fields = ["id", "name"] class SpeakerSerializerWithCliques(ModelSerializer): """Speaker model serializer with clique list.""" class Meta: model = models.Speaker fields = ["id", "name", "cliques"] cliques = CliqueSerializer(many=True) class CliqueSerializerWithSpeakers(ModelSerializer): """Clique model serializer with speaker list.""" class Meta: model = models.Clique fields = ["id", "slug", "speakers"] speakers = SerializerMethodField("speaker_list") def speaker_list(self, instance): serializer = SpeakerSerializer() speakers = instance.get_speakers() return [serializer.to_representation(speaker) for speaker in speakers]
StarcoderdataPython
9683316
import os import tempfile from click.testing import CliRunner import requests from filmcompress import main as conv def file2dir(dl_uri: str, path: str) -> str: """ Get file from URL and save it to file (basically wget) :param dl_uri: Download URL :return: HTTP request status code """ print("Saving from", dl_uri, "to", path) try: r = requests.get(dl_uri) with open(path, 'wb') as f: f.write(r.content) return path except Exception as e: print("Exception:", e) def test_1(): runner = CliRunner() with runner.isolated_filesystem(): with tempfile.TemporaryDirectory() as td: tf = td + os.sep + 'ForBiggerEscapes.mp4' file2dir('http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4', tf) with tempfile.TemporaryDirectory() as td2: result = runner.invoke(conv, [td, '--outdir', td2]) print(result.stdout) assert result.exit_code == 0 # def test_2(): # assert os.path.exists(tempdir + 'videosample1.mp4')
StarcoderdataPython
3402472
<reponame>ludwiglierhammer/pyremo<filename>tests/test_domain.py<gh_stars>0 # -*- coding: utf-8 -*- # flake8: noqa import pytest import pyremo as pr def test_domain_dataset(): eur11 = pr.remo_domain("EUR-11") eur22 = pr.remo_domain("EUR-22") eur44 = pr.remo_domain("EUR-44")
StarcoderdataPython
5093529
<reponame>MehmetErer/anima<filename>anima/env/equalizer/toolbox.py # -*- coding: utf-8 -*- """ import os import sys os.environ['STALKER_PATH'] = '/mnt/T/STALKER_CONFIG' sys.path.append("/home/eoyilmaz/Documents/development/anima/anima") sys.path.append("/home/eoyilmaz/Documents/development/anima/extra_libraries/py2") sys.path.append("/home/eoyilmaz/Documents/development/anima/extra_libraries/py2/__extras__") from anima.env.equalizer import toolbox toolbox.Toolbox.bake_3d_to_2d() """ class Toolbox(object): """toolbox for 3DEqualizer """ @classmethod def bake_3d_to_2d(cls): """bakes the selected points projected 3D position with distortion to the 2D space """ import tde4 camera_id = tde4.getCurrentCamera() pgroup_id = tde4.getCurrentPGroup() camera_name = tde4.getCameraName(camera_id) print("==========") print("Camera: %s" % camera_name) point_ids = tde4.getPointList(pgroup_id, True) calc_range = tde4.getCameraCalculationRange(camera_id) for point_id in point_ids: for frame in range(calc_range[0], calc_range[1] + 1): # tde4.setCurrentFrame(frame) # only apply when point position is valid in this frame is_point_pos_2d_valid = tde4.isPointPos2DValid(pgroup_id, point_id, camera_id, frame) if is_point_pos_2d_valid == 1: point_pos = tde4.calcPointBackProjection2D(pgroup_id, point_id, camera_id, frame, True) tde4.setPointPosition2D(pgroup_id, point_id, camera_id, frame, point_pos) print("Done!")
StarcoderdataPython
4870734
<gh_stars>0 """Feature -> (categories, ids) mappings.""" import csv import os import yaml from .config import get_config_path with open(os.path.join(get_config_path(), "mappings.yml"), "r") as f: mappings = yaml.load(f, Loader=yaml.SafeLoader) with open(os.path.join(get_config_path(), "value_sets.yml"), "r") as f: value_sets = yaml.load(f, Loader=yaml.SafeLoader) with open(os.path.join(get_config_path(), "correlations.csv"), "r") as f: correlations = list(csv.reader(f))
StarcoderdataPython
1813524
<reponame>saadaoui-salah/Daily-Coding-Problem<gh_stars>0 """This problem was asked by Square. A competitive runner would like to create a route that starts and ends at his house, with the condition that the route goes entirely uphill at first, and then entirely downhill. Given a dictionary of places of the form {location: elevation}, and a dictionary mapping paths between some of these locations to their corresponding distances, find the length of the shortest route satisfying the condition above. Assume the runner's home is location 0. For example, suppose you are given the following input: elevations = {0: 5, 1: 25, 2: 15, 3: 20, 4: 10} paths = { (0, 1): 10, (0, 2): 8, (0, 3): 15, (1, 3): 12, (2, 4): 10, (3, 4): 5, (3, 0): 17, (4, 0): 10 } In this case, the shortest valid path would be 0 -> 2 -> 4 -> 0, with a distance of 28. """
StarcoderdataPython
11242952
# 12 - Tendo como dados de entrada a altura de uma pessoa. # Construa um algoritmo que calcule seu peso ideal, usando a seguinte fórmula: (72.7*altura) - 58. altura = float(input('Digite sua altura: ')) conversor = (72.7 * altura) - 58 print(f'De acordo com sua altura: {altura:.2f}m . ') print(f'Seu peso ideal é: {conversor:.2f}. ')
StarcoderdataPython
9770273
import argparse import random import time import logging import pymongo import requests from gumjabi import queue from gumjabi.util.config import ( collections, ) from gumjabi.util import mongo log = logging.getLogger(__name__) # Disable annoying "HTTP connection" log lines from the requests module requests_log = logging.getLogger("requests") requests_log.setLevel(logging.WARNING) def main(): parser = argparse.ArgumentParser( description='Start the Glue API', ) parser.add_argument( '-v', '--verbose', action='store_true', default=False, help='output DEBUG logging statements (default: %(default)s)', ) parser.add_argument( '--db-config', help=('path to the file with information on how to ' 'retrieve and store data in the database' ), required=True, metavar='PATH', type=str, ) args = parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.verbose else logging.INFO, format='%(asctime)s.%(msecs)03d %(name)s: %(levelname)s: %(message)s', datefmt='%Y-%m-%dT%H:%M:%S', ) colls = collections( config=args.db_config, ) indices = [ {'meta.requested_on': pymongo.ASCENDING}, ] mongo.create_indices( collection=colls['kajabi-queue'], indices=indices, ) session = requests.session() if not queue.create_accts(colls, session): delay = random.randint(5, 10) log.debug('No work, sleeping %d seconds...', delay) time.sleep(delay)
StarcoderdataPython
6514962
#!/usr/bin/env python3 # Developed by <NAME> and <NAME> # This file is covered by the LICENSE file in the root of this project. # Brief: This demo shows how to generate the overlap and yaw ground truth files for training and testing. import yaml import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '../src/utils')) from utils import * from com_function_angle import com_function_angle, read_function_angle_com_yaw from normalize_data import normalize_data from split_train_val import split_train_val import matplotlib.pyplot as plt import matplotlib import matplotlib.cm as cm def vis_gt(xys, ground_truth_mapping): """Visualize the overlap value on trajectory""" # set up plot fig, ax = plt.subplots() norm = matplotlib.colors.Normalize(vmin=0, vmax=1, clip=True) mapper = cm.ScalarMappable(norm=norm) # cmap="magma" mapper.set_array(ground_truth_mapping[:, 2]) colors = np.array([mapper.to_rgba(a) for a in ground_truth_mapping[:, 2]]) # sort according to overlap indices = np.argsort(ground_truth_mapping[:, 2]) xys = xys[indices] ax.scatter(xys[:, 0], xys[:, 1], c=colors[indices], s=10) ax.axis('square') ax.set_xlabel('X [m]') ax.set_ylabel('Y [m]') ax.set_title('Demo 4: Generate ground truth for training') cbar = fig.colorbar(mapper, ax=ax) cbar.set_label('cos(function angle)', rotation=270, weight='bold') plt.show() if __name__ == '__main__': config_filename = 'config/demo.yml' if len(sys.argv) > 1: config_filename = sys.argv[1] # load the configuration file config = yaml.load(open(config_filename)) # set the related parameters poses_file = config['Demo4']['poses_file'] calib_file = config['Demo4']['calib_file'] scan_folder = config['Demo4']['scan_folder'] dst_folder = config['Demo4']['dst_folder'] # load scan paths scan_paths = load_files(scan_folder) # load calibrations T_cam_velo = load_calib(calib_file) T_cam_velo = np.asarray(T_cam_velo).reshape((4, 4)) T_velo_cam = np.linalg.inv(T_cam_velo) # load poses poses = load_poses(poses_file) pose0_inv = np.linalg.inv(poses[0]) # for KITTI dataset, we need to convert the provided poses # from the camera coordinate system into the LiDAR coordinate system poses_new = [] for pose in poses: poses_new.append(T_velo_cam.dot(pose0_inv).dot(pose).dot(T_cam_velo)) poses = np.array(poses_new) # generate overlap and yaw ground truth array # ground_truth_mapping = com_function_angle(scan_paths, poses, frame_idx=0) funcangle_file = '/home/cel/CURLY/code/DockerFolder/data/kitti/sequences/07_overlap/preprocess_data_demo/07_all.csv' ground_truth_mapping = read_function_angle_com_yaw(scan_paths, poses, funcangle_file) # normalize the distribution of ground truth data dist_norm_data = normalize_data(ground_truth_mapping) # split ground truth for training and validation train_data, validation_data = split_train_val(dist_norm_data) # add sequence label to the data and save them as npz files seq_idx = '07' # specify the goal folder dst_folder = os.path.join(dst_folder, 'ground_truth_2') try: os.stat(dst_folder) print('generating depth data in: ', dst_folder) except: print('creating new depth folder: ', dst_folder) os.mkdir(dst_folder) # training data train_seq = np.empty((train_data.shape[0], 2), dtype=object) train_seq[:] = seq_idx np.savez_compressed(dst_folder + '/train_set_2', overlaps=train_data, seq=train_seq) # validation data validation_seq = np.empty((validation_data.shape[0], 2), dtype=object) validation_seq[:] = seq_idx np.savez_compressed(dst_folder + '/validation_set_2', overlaps=validation_data, seq=validation_seq) # raw ground truth data, fully mapping, could be used for testing ground_truth_seq = np.empty((ground_truth_mapping.shape[0], 2), dtype=object) ground_truth_seq[:] = seq_idx np.savez_compressed(dst_folder + '/ground_truth_overlap_yaw_2', overlaps=ground_truth_mapping, seq=ground_truth_seq) print('Finish saving the ground truth data for training and testing at: ', dst_folder) # visualize the raw ground truth mapping vis_gt(poses[:, :2, 3], ground_truth_mapping)
StarcoderdataPython
1897076
<reponame>Allen7D/mini-shop-server # _*_ coding: utf-8 _*_ """ Created by Allen7D on 2018/6/16. ↓↓↓ Banner接口 ↓↓↓ """ from app.extensions.api_docs.redprint import Redprint from app.extensions.api_docs.v1 import banner as api_doc from app.models.banner import Banner from app.libs.error_code import Success, BannerException __author__ = 'Allen7D' api = Redprint(name='banner', module='首页轮播图', api_doc=api_doc) @api.route('/<int:id>', methods=['GET']) @api.doc(args=['g.path.banner_id']) def get_banner(id): '''查询首页轮播图''' banner = Banner.query.filter_by(id=id).first_or_404(e=BannerException) return Success(banner)
StarcoderdataPython
357697
#!/usr/bin/python3 # Polyglot Node Server for EnvisaLink EVL 3/4 Device (DSC) import sys import envisalinktpi as EVL import polyinterface # TODO: Test Fire zone and reporitng functionality # TODO: Add heartbeat from nodeserver # TODO: Add shortcut arming (with #) # TODO: Process CID events for more information # contstants for ISY Nodeserver interface _ISY_BOOL_UOM = 2 # Used for reporting status values for Controller node _ISY_INDEX_UOM = 25 # Index UOM for custom states (must match editor/NLS in profile): _ISY_USER_NUM_UOM = 70 # User Number UOM for reporting last user number _ISY_SECONDS_UOM = 58 # used for reporting duration in seconds _LOGGER = polyinterface.LOGGER _PART_ADDR_FORMAT_STRING = "partition%1d" _ZONE_ADDR_FORMAT_STRING = "zone%02d" _PARM_IP_ADDRESS_NAME = "ipaddress" _PARM_PASSWORD_NAME = "password" _PARM_USER_CODE_NAME = "usercode" _PARM_NUM_PARTITIONS_NAME = "numpartitions" _PARM_NUM_ZONES_NAME = "numzones" _PARM_DISABLE_WATCHDOG_TIMER = "disablewatchdog" _PARM_SMART_ZONE_TRACKING = "smartzonetracking" _DEFAULT_IP_ADDRESS = "0.0.0.0" _DEFAULT_PASSWORD = "<PASSWORD>" _DEFAULT_USER_CODE = "5555" _DEFAULT_NUM_ZONES = 8 # values for zonetimerdumpflag in custom configuration' _PARM_ZONE_TIMER_DUMP_FLAG = "zonetimerdumpflag" _ZONE_TIMER_DUMP_DISABLED = 0 _ZONE_TIMER_DUMP_SHORTPOLL = 1 _ZONE_TIMER_DUMP_LONGPOLL = 2 _DEFAULT_ZONE_TIMER_DUMP_FLAG = _ZONE_TIMER_DUMP_SHORTPOLL # constants from nodeserver profile _IX_PARTITION_STATE_READY = 0 _IX_PARTITION_STATE_NOT_READY = 1 _IX_PARTITION_STATE_ARMED_AWAY = 2 _IX_PARTITION_STATE_ARMED_STAY = 3 _IX_PARTITION_STATE_ARMED_AWAY_ZE = 4 _IX_PARTITION_STATE_ARMED_STAY_ZE = 5 _IX_PARTITION_STATE_ALARMING = 6 _IX_PARTITION_STATE_DELAY_EXIT = 7 _IX_PARTITION_STATE_ALARM_IN_MEMORY = 8 _IX_PARTITION_DOES_NOT_EXIST = 10 _IX_ZONE_STATE_CLOSED = 0 _IX_ZONE_STATE_OPEN = 1 _IX_ZONE_STATE_ALARMING = 2 _IX_ZONE_STATE_UNKNOWN = 3 # Node class for partitions class Partition(polyinterface.Node): id = "PARTITION" # Override init to handle partition number def __init__(self, controller, primary, partNum): super(Partition, self).__init__(controller, primary, _PART_ADDR_FORMAT_STRING % partNum, "Partition %1d" % partNum) self.partitionNum = partNum self.initialBypassZoneDump = False self.alarming = False # Update the driver values based on the partition state received from the EnvisaLink for the partition def set_state(self, state): if state == EVL.PARTITION_STATE_ALARMING: # send a DON commmand when the partition goes to an alarming state self.reportCmd("DON") self.alarming = True # set the status to Alarming self.setDriver("ST", _IX_PARTITION_STATE_ALARMING) return else: # if partition was previously set to an alarming state, clear the state if self.alarming: # send a DOF commmand when the partition goes to an alarming state self.reportCmd("DOF") self.alarming = False if state in (EVL.PARTITION_STATE_READY, EVL.PARTITION_STATE_READY_ZONES_BYPASSED): self.setDriver("ST", _IX_PARTITION_STATE_READY) # Ready # Note "Zones Bypassed" driver GV1 is handled in LED statusBits processing # if SmartZoneTracking is enabled, spin through the zones for the partition # and manage the state and bypass flags if self.controller.smartZoneTracking: for addr in self.controller.nodes: node = self.controller.nodes[addr] if node.id == Zone.id and node.partitionNum == self.partitionNum: # if bypassed zones are indicated, then set all non-bypassed zones to closed if state == EVL.PARTITION_STATE_READY_ZONES_BYPASSED: if not node.bypass: node.set_state(_IX_ZONE_STATE_CLOSED) # Otherwise set the state of all zones to closed and clear the bypass flags else: node.set_bypass(False) node.set_state(_IX_ZONE_STATE_CLOSED) elif state == EVL.PARTITION_STATE_NOT_READY: self.setDriver("ST", _IX_PARTITION_STATE_NOT_READY) # Not Ready elif state == EVL.PARTITION_STATE_ARMED_STAY: self.setDriver("ST", _IX_PARTITION_STATE_ARMED_STAY) elif state == EVL.PARTITION_STATE_ARMED_AWAY: self.setDriver("ST", _IX_PARTITION_STATE_ARMED_AWAY) elif state == EVL.PARTITION_STATE_ARMED_STAY_ZE: self.setDriver("ST", _IX_PARTITION_STATE_ARMED_STAY_ZE) elif state == EVL.PARTITION_STATE_ARMED_AWAY_ZE: self.setDriver("ST", _IX_PARTITION_STATE_ARMED_AWAY_ZE) elif state == EVL.PARTITION_STATE_EXIT_DELAY: self.setDriver("ST", _IX_PARTITION_STATE_DELAY_EXIT) elif state == EVL.PARTITION_STATE_ALARM_IN_MEMORY: self.setDriver("ST", _IX_PARTITION_STATE_ALARM_IN_MEMORY) elif state == EVL.PARTITION_STATE_DOES_NOT_EXIST: self.setDriver("ST", _IX_PARTITION_DOES_NOT_EXIST) # does not exist # Update the driver values based on the statusBits received from the EnvisaLink for keypad updates for partition def set_statuses(self, statusBits): # update the partition flags from the status bits self.setDriver("GV0", int((statusBits & EVL.LED_MASK_CHIME) > 0)) # Chime self.setDriver("GV1", int((statusBits & EVL.LED_MASK_BYPASS) > 0)) # Zone Bypassed self.setDriver("GV2", int((statusBits & EVL.LED_MASK_ALARM_FIRE) > 0)) # Fire Alarm self.setDriver("GV5", int((statusBits & EVL.LED_MASK_LOW_BATTERY) > 0)) # Low Battery self.setDriver("GV6", int((statusBits & EVL.LED_MASK_AC_PRESENT) == 0)) # AC Trouble self.setDriver("GV7", int((statusBits & EVL.LED_MASK_SYS_TROUBLE) > 0)) # System Trouble # dump bypass zones for the partition def dump_bypass_zones(self): # send keys to dump bypass zones if self.controller.envisalink.sendKeys(self.partitionNum, EVL.KEYS_DUMP_BYPASS_ZONES.format(code=self.controller.userCode)): # if this is the initial dump of the bypass zones, then spin through and set all the zones for this partition # initially to false and allow the messages from the alarm panel to set the zones back if not self.initialBypassZoneDump: for addr in self.controller.nodes: node = self.controller.nodes[addr] if node.id == Zone.id and node.partitionNum == self.partitionNum: # clear the bypass state for the zone node.set_bypass(False) self.initialBypassZoneDump = True else: _LOGGER.warning("Call to EnvisaLink to dump bypass zones failed for node %s.", self.address) # Arm the partition in Away mode (the listener thread will update the corresponding driver values) def arm_away(self, command): _LOGGER.info("Arming partition %d in away mode in arm_away()...", self.partitionNum) # send keys to arm away if self.controller.envisalink.sendKeys(self.partitionNum, EVL.KEYS_ARM_AWAY.format(code=self.controller.userCode)): pass else: _LOGGER.warning("Call to EnvisaLink to arm partition failed for node %s.", self.address) # Arm the partition in Stay mode (the listener thread will update the corresponding driver values) def arm_stay(self, command): _LOGGER.info("Arming partition %d in stay mode in arm_stay()...", self.partitionNum) # send keys to arm stay if self.controller.envisalink.sendKeys(self.partitionNum, EVL.KEYS_ARM_STAY.format(code=self.controller.userCode)): pass else: _LOGGER.warning("Call to EnvisaLink to arm partition failed for node %s.", self.address) # Arm the partition in Zero Entry mode (the listener thread will update the corresponding driver values) def arm_zero_entry(self, command): _LOGGER.info("Arming partition %d in zero_entry mode in arm_zero_entry()...", self.partitionNum) # send keys to arm instant if self.controller.envisalink.sendKeys(self.partitionNum, EVL.KEYS_ARM_INSTANT.format(code=self.controller.userCode)): pass else: _LOGGER.warning("Call to EnvisaLink to arm partition failed for node %s.", self.address) # Disarm the partition (the listener thread will update the corresponding driver values) def disarm(self, command): _LOGGER.info("Disarming partition %d in disarm()...", self.partitionNum) # send keys to disarm if self.controller.envisalink.sendKeys(self.partitionNum, EVL.KEYS_DISARM.format(code=self.controller.userCode)): pass else: _LOGGER.warning("Call to EnvisaLink to disarm partition failed for node %s.", self.address) # Toggle the door chime for the partition (the listener thread will update the corresponding driver values) def toggle_chime(self, command): _LOGGER.info("Toggling door chime for partition %d in toggle_chime()...", self.partitionNum) # send door chime toggle keystrokes to EnvisaLink device for the partition numner if self.controller.envisalink.sendKeys(self.partitionNum, EVL.KEYS_TOGGLE_DOOR_CHIME.format(code=self.controller.userCode)): pass else: _LOGGER.warning("Call to EnvisaLink to toggle door chime failed for node %s.", self.address) drivers = [ {"driver": "ST", "value": 0, "uom": _ISY_INDEX_UOM}, {"driver": "GV0", "value": 0, "uom": _ISY_BOOL_UOM}, {"driver": "GV1", "value": 0, "uom": _ISY_BOOL_UOM}, {"driver": "GV2", "value": 0, "uom": _ISY_BOOL_UOM}, {"driver": "GV5", "value": 0, "uom": _ISY_BOOL_UOM}, {"driver": "GV6", "value": 0, "uom": _ISY_BOOL_UOM}, {"driver": "GV7", "value": 0, "uom": _ISY_BOOL_UOM}, ] commands = { "DISARM": disarm, "ARM_AWAY": arm_away, "ARM_STAY": arm_stay, "ARM_ZEROENTRY": arm_zero_entry, "TOGGLE_CHIME": toggle_chime } # Node class for zones class Zone(polyinterface.Node): id = "ZONE" # Override init to handle partition number def __init__(self, controller, primary, zoneNum): super(Zone, self).__init__(controller, primary, _ZONE_ADDR_FORMAT_STRING % zoneNum, "Zone %02d" % zoneNum) self.zoneNum = zoneNum self.partitionNum = 1 # default to partition 1 - only one partition currently supported self.bypass = False # default to false - updates with initial bypass zone dump # Set the zone state value def set_state(self, state): self.setDriver("ST", state) # Set the bypass driver value from the parameter def set_bypass(self, bypass): self.bypass = bypass self.setDriver("GV0", int(self.bypass)) # if SmartZoneTracking is enabled, then set state of bypassed zone to unknown if bypass and self.controller.smartZoneTracking: self.setDriver("ST", _IX_ZONE_STATE_UNKNOWN) # Set the zone timer driver value def set_timer(self, time): self.setDriver("GV1", time) # Bypass the zone (assuming partition 1) # Note: this is not a toggle, cleared by disarming partition def bypass_zone(self, command): _LOGGER.info("Bypassing zone %d in bypass_zone()...", self.zoneNum) # send bypass zone keystrokesdoor chime toggle keystrokes to EnvisaLink device for the partition numner if self.controller.envisalink.sendKeys(self.partitionNum, EVL.KEYS_BYPASS_ZONE.format(code=self.controller.userCode, zone=self.zoneNum)): self.set_bypass(True) else: _LOGGER.warning("Call to EnvisaLink to toggle door chime failed for node %s.", self.address) drivers = [ {"driver": "ST", "value": 0, "uom": _ISY_INDEX_UOM}, {"driver": "GV0", "value": 0, "uom": _ISY_BOOL_UOM}, {"driver": "GV1", "value": 327675, "uom": _ISY_SECONDS_UOM}, ] commands = { "BYPASS_ZONE": bypass_zone, } # Node class for controller class Controller(polyinterface.Controller): id = "CONTROLLER" def __init__(self, poly): super(Controller, self).__init__(poly) self.ip = "" self.password = "" self.name = "EnvisaLink-Vista Nodeserver" self.envisalink = None self.userCode = "" self.numPartitions = 0 self.smartZoneTracking = False # Update the profile on the ISY def cmd_updateProfile(self, command): _LOGGER.info("Installing profile in cmd_updateProfile()...") self.poly.installprofile() # Update the profile on the ISY def cmd_setLogLevel(self, command): _LOGGER.info("Setting logging level in cmd_setLogLevel(): %s", str(command)) # retrieve the parameter value for the command value = int(command.get("value")) # set the current logging level _LOGGER.setLevel(value) # store the new loger level in custom data self.addCustomData("loggerlevel", value) self.saveCustomData(self._customData) # update the state driver to the level set self.setDriver("GV20", value) def cmd_query(self): # Force EnvisaLink to report all statuses available for reporting # check for existing EnvisaLink connection if self.envisalink is None or not self.envisalink.connected(): # Update the alarm panel connected status self.setDriver("GV1", 1, True, True) # send the status polling command to the EnvisaLink device # What can we send to the Honeywell panel to force reporting of statuses? #self.envisalink.sendCommand(EVL.CMD_STATUS_REPORT) else: # Update the alarm panel connected status self.setDriver("GV1", 0, True, True) # Start the nodeserver def start(self): _LOGGER.info("Starting envisaink Nodeserver...") # remove all notices from ISY Admin Console self.removeNoticesAll() # load custom data from polyglot self._customData = self.polyConfig["customData"] # If a logger level was stored for the controller, then use to set the logger level level = self.getCustomData("loggerlevel") if level is not None: _LOGGER.setLevel(int(level)) # get custom configuration parameters configComplete = self.getCustomParams() # if the configuration is not complete, stop the nodeserver if not configComplete: self.poly.stop() # don't think this is working return else: # setup the nodes based on the counts of zones and partition in the configuration parameters self.build_nodes(self.numPartitions, self.numZones) # setting up the interface moved to shortpoll so that it is retried if initial attempt to connection fails # NOTE: this is for, e.g., startup after power failure where Polyglot may restart faster than network or # EnvisaLink # Set the nodeserver status flag to indicate nodeserver is running self.setDriver("ST", 1, True, True) # Report initial alarm panel connection status self.setDriver("GV1", 0, True, True) # Report the logger level to the ISY self.setDriver("GV20", _LOGGER.level, True, True) # Called when the nodeserver is stopped def stop(self): # shudtown the connection to the EnvisaLink device if not self.envisalink is None: self.envisalink.shutdown() # Update the alarm panel connected status # Note: this is currently not effective because the polyinterface won't accept # any more status changes from the nodeserver self.setDriver("GV1", 0, True, True) # Set the nodeserver status flag to indicate nodeserver is stopped # self.setDriver("ST", 0) # Get custom configuration parameter values def getCustomParams(self): customParams = self.poly.config["customParams"] complete = True # get IP address of the EnvisaLink device from custom parameters try: self.ip = customParams[_PARM_IP_ADDRESS_NAME] except KeyError: _LOGGER.error("Missing IP address for EnvisaLink device in configuration.") # add a notification to the nodeserver's notification area in the Polyglot dashboard self.addNotice({"missing_ip": "Please update the '%s' parameter value in the nodeserver custom parameters and restart the nodeserver." % _PARM_IP_ADDRESS_NAME}) # put a place holder parameter in the configuration with a default value customParams.update({_PARM_IP_ADDRESS_NAME: _DEFAULT_IP_ADDRESS}) complete = False # get the password of the EnvisaLink device from custom parameters try: self.password = customParams[_PARM_PASSWORD_NAME] except KeyError: _LOGGER.error("Missing password for EnvisaLink device in configuration.") # add a notification to the nodeserver's notification area in the Polyglot dashboard self.addNotice({"missing_pwd": "Please update the '%s' parameter value in the nodeserver custom parameters and restart the nodeserver." % _PARM_PASSWORD_NAME}) # put a place holder parameter in the configuration with a default value customParams.update({_PARM_PASSWORD_NAME: _DEFAULT_PASSWORD}) complete = False # get the user code for the DSC panel from custom parameters try: self.userCode = customParams[_PARM_USER_CODE_NAME] except KeyError: _LOGGER.error("Missing user code for DSC panel in configuration.") # add a notification to the nodeserver's notification area in the Polyglot dashboard self.addNotice({"missing_code": "Please update the '%s' custom configuration parameter value in the nodeserver configuration and restart the nodeserver." % _PARM_USER_CODE_NAME}) # put a place holder parameter in the configuration with a default value customParams.update({_PARM_USER_CODE_NAME: _DEFAULT_USER_CODE}) complete = False # get the optional number of partitions and zones to create nodes for try: self.numPartitions = int(customParams[_PARM_NUM_PARTITIONS_NAME]) except (KeyError, ValueError, TypeError): self.numPartitions = 1 # default to single partition try: self.numZones = int(customParams[_PARM_NUM_ZONES_NAME]) except (KeyError, ValueError, TypeError): self.numZones = _DEFAULT_NUM_ZONES # get optional setting for watchdog timer try: self.disableWDTimer = (int(customParams[_PARM_DISABLE_WATCHDOG_TIMER]) == 1) except (KeyError, ValueError, TypeError): self.disableWDTimer = False # default to enabled # get optional setting for zone timer dump frequency try: self.zoneTimerDumpFlag = int(customParams[_PARM_ZONE_TIMER_DUMP_FLAG]) except (KeyError, ValueError, TypeError): self.zoneTimerDumpFlag = _DEFAULT_ZONE_TIMER_DUMP_FLAG # get optional setting for smart zone tracking try: self.smartZoneTracking = bool(int(customParams[_PARM_SMART_ZONE_TRACKING])) except (KeyError, ValueError, TypeError): self.smartZoneTracking = False # default disabled self.poly.saveCustomParams(customParams) return complete # Create nodes for zones, partitions, and command outputs as specified by the parameters def build_nodes(self, numPartitions, numZones): # create partition nodes for the number of partitions specified for i in range(numPartitions): # create a partition node and add it to the node list self.addNode(Partition(self, self.address, i+1)) # create zone nodes for the number of partitions specified for i in range(numZones): # create a partition node and add it to the node list self.addNode(Zone(self, self.address, i+1)) self.setDriver("ST", 0, True, True) # called every short_poll seconds def shortPoll(self): # check for existing EnvisaLink connection if self.envisalink is None or not self.envisalink.connected(): # Setup the interface to the EnvisaLink device and connect (starts the listener thread) self.envisalink = EVL.EnvisaLinkInterface(_LOGGER) _LOGGER.info("Establishing connection to EnvisaLink device...") if self.envisalink.connect(self.ip, self.password, self.process_command): # clear any prior connection failure notices self.removeNotice("no_connect") # set alarm panel connected status self.setDriver("GV1", 1, True, True) else: # set alarm panel connected status self.setDriver("GV1", 0, True, True) # Format errors _LOGGER.warning("Could not connect to EnvisaLink device at %s.", self.ip) self.addNotice({"no_connect": "Could not connect to EnvisaLink device. Please check the network and configuration parameters and restart the nodeserver."}) self.envisalink = None else: # perform the bypassed zones dump for each partition on subsequent shortpolls # until they have all been performed skipTimerDump = False for n in range(self.numPartitions): addr = _PART_ADDR_FORMAT_STRING % (n+1) if addr in self.nodes: part = self.nodes[addr] if not part.initialBypassZoneDump: _LOGGER.debug("Dumping bypassed zones for partition %s", addr) part.dump_bypass_zones() skipTimerDump = True # don't dump timers if a bypass zone dump was performed break # Check zone timer dump flag and force a zone timer dump if not skipTimerDump and self.zoneTimerDumpFlag == _ZONE_TIMER_DUMP_SHORTPOLL: self.envisalink.sendCommand(EVL.CMD_DUMP_ZONE_TIMERS) # called every long_poll seconds def longPoll(self): # check for EVL connection if self.envisalink is not None and self.envisalink.connected(): # if the EVL's watchdog timer is to be disabled, send a poll command to reset the timer # NOTE: this prevents the EnvisaLink from resetting the connection if it can't communicate with EyezON service if self.disableWDTimer: self.envisalink.sendCommand(EVL.CMD_POLL) # Check zone timer dump flag and force a zone timer dump if self.zoneTimerDumpFlag == _ZONE_TIMER_DUMP_LONGPOLL: self.envisalink.sendCommand(EVL.CMD_DUMP_ZONE_TIMERS) # Callback function for listener thread # Note: called with data parsed from the EnvisaLink command. def process_command(self, cmd, data): # update the state values from the keypad updates # Note: This is rather chatty at one message every 4 seconds if cmd == EVL.CMD_KEYPAD_UPDATE: # parse the command parameters from the data # Partition, LED/Icon Bitfield, User/Zone, Beep, Alphanumeric parms = data.split(",") partNum = int(parms[0]) # Partition statusBits = int(parms[1], base=16) # LED/Icon Bitfield zoneNum = int(parms[2]) if parms[2].isdigit() else 0 text1 = parms[4][:16] # First Alphanumeric Line text2 = parms[4][16:] # First Alphanumeric Line # if the report is not zone oriented, process status for the partition if (statusBits & EVL.LED_MASK_PARTITION_FLAG) > 0: # check if node for partition exists addr = _PART_ADDR_FORMAT_STRING % partNum if addr in self.nodes: partition = self.nodes[addr] # update the partition state (ST driver) # this is duplicate of statuses reported in CMD_PARTITION_STATE_CHANGE # so whichever is the most reliable should be used partition.set_statuses(statusBits) # otherwise process zone based information else: # look at text1 to determine meaning of update, e.g. "BYPAS ZZ", "ALARM ZZ", "FAULT ZZ" status = text1[:5] if status in (EVL.ZONE_STATUS_UPDATE_ALARM, EVL.ZONE_STATUS_UPDATE_BYPASS, EVL.ZONE_STATUS_UPDATE_FAULT): # get the zone node for the indicated zone addr = _ZONE_ADDR_FORMAT_STRING % zoneNum if addr in self.nodes: zone = self.nodes[addr] # update the zone state based on the flag if status == EVL.ZONE_STATUS_UPDATE_ALARM: zone.set_state(_IX_ZONE_STATE_ALARMING) # use the fault message to update the zone state if SmartZoneTracking is enabled elif status == EVL.ZONE_STATUS_UPDATE_FAULT and self.smartZoneTracking: zone.set_state(_IX_ZONE_STATE_OPEN) elif EVL.ZONE_STATUS_UPDATE_BYPASS: zone.set_bypass(True) # process the partition statuses on status change elif cmd == EVL.CMD_PARTITION_STATE_CHANGE: # spilt the 16 characters of data into 8 individual 2-character hex strings partStates = [data[i:i+2] for i in range(0, len(data), 2)] # iterate through the partitions nodes and update the state from the corresponding status value for addr in self.nodes: node = self.nodes[addr] if node.id == Partition.id: node.set_state(partStates[node.partitionNum - 1]) # process the zone statuses on status change # Note: this pretty much only works for open state # Note: this is only if SmartZoneTracking is disabled elif cmd == EVL.CMD_ZONE_STATE_CHANGE: # spilt the 16/32 characters of data into 8/16 individual 2-character hex strings zoneStateBytes = [data[i:i+2] for i in range(0, len(data), 2)] # convert the 2-character hex strings into a list of 64/128 integer zone states (0, 1) zoneStates = [] for byte in zoneStateBytes: bits = int(byte, base=16) for i in range(8): zoneStates.append(int((bits & (1 << i)) > 0)) # iterate through the zone nodes and set the state value the state list for addr in self.nodes: node = self.nodes[addr] if node.id == Zone.id: node.set_state(zoneStates[node.zoneNum - 1]) # if a CID event is sent, log it so that we can add functionality elif cmd == EVL.CMD_CID_EVENT: # parse the CID parameters from the data # QXXXPPZZZ0 where: # Q = Qualifier. 1 = Event, 3 = Restoral # XXX = 3 digit CID code # PP = 2 digit Partition # ZZZ = Zone or User (depends on CID code) # 0 = Always 0 (padding) isRestoral = (data[0:1] == "3") # Qaulifier code = int(data[1:4]) # CID code partNum = int(data[4:6]) # Partition zoneNum = int(data[6:9]) # Zone/User Num # log the CID code for future functionality _LOGGER.info("CID event received from Alarm Panel. Code: %d, Qualifier: %s, Partition: %d, Zone/User: %d", code, data[0:1], partNum, zoneNum) # handle zone timer dump elif cmd == EVL.CMD_ZONE_TIMER_DUMP: # spilt the 256/512 bytes of data into 64/128 individual 4-byte hex values zoneTimerHexValues = [data[i:i+4] for i in range(0, len(data), 4)] # convert the 4-byte hex values to a list of integer zone timers # Note: Each 4-byte hex value is a little-endian countdown of 5-second # intervals, i.e. FFFF = 0, FEFF = 5, FDFF = 10, etc. zoneTimers = [] for leHexString in zoneTimerHexValues: beHexString = leHexString[2:] + leHexString[:2] time = (int(beHexString, base=16) ^ 0xFFFF) * 5 zoneTimers.append(time) # iterate through the zone nodes and set the time value from the bitfield for addr in self.nodes: node = self.nodes[addr] if node.id == "ZONE": node.set_timer(zoneTimers[node.zoneNum - 1]) else: _LOGGER.info("Unhandled command received from EnvisaLink. Command: %s, Data: %s", cmd.decode("ascii"), data) # helper method for storing custom data def addCustomData(self, key, data): # add specififed data to custom data for specified key self._customData.update({key: data}) # helper method for retrieve custom data def getCustomData(self, key): # return data from custom data for key return self._customData.get(key) drivers = [ {"driver": "ST", "value": 0, "uom": _ISY_BOOL_UOM}, {"driver": "GV1", "value": 0, "uom": _ISY_BOOL_UOM}, {"driver": "GV20", "value": 0, "uom": _ISY_INDEX_UOM} ] commands = { "QUERY": cmd_query, "UPDATE_PROFILE" : cmd_updateProfile, "SET_LOGLEVEL": cmd_setLogLevel } # Main function to establish Polyglot connection if __name__ == "__main__": try: poly = polyinterface.Interface() poly.start() controller = Controller(poly) controller.runForever() except (KeyboardInterrupt, SystemExit): sys.exit(0)
StarcoderdataPython
3355499
<gh_stars>0 import time import mock import pytest import random from etcd3.client import Client from tests.docker_cli import docker_run_etcd_main from .envs import protocol, host from .etcd_go_cli import NO_ETCD_SERVICE, etcdctl @pytest.fixture(scope='module') def client(): """ init Etcd3Client, close its connection-pool when teardown """ _, p, _ = docker_run_etcd_main() c = Client(host, p, protocol) yield c c.close() @pytest.mark.skipif(NO_ETCD_SERVICE, reason="no etcd service available") def test_lease_util(client): ID = random.randint(10000, 100000) TTL = 2 # min is 2sec lease = client.Lease(ttl=TTL, ID=ID) with lease: hexid = hex(ID)[2:] etcdctl('put --lease=%s foo bar' % hexid) etcdctl('put --lease=%s fizz buzz' % hexid) time.sleep(TTL) r = lease.time_to_live(keys=True) assert r.ID == ID assert r.grantedTTL == TTL assert r.TTL <= TTL assert set(r.keys) == {b'foo', b'fizz'} # time.sleep(100) assert lease.keeping assert lease.alive() assert not lease.jammed() assert lease._thread.is_alive() assert not lease.alive() assert not lease.keeping assert not lease._thread.is_alive() ID = random.randint(10000, 100000) TTL = 5 # min is 2sec keep_cb = mock.Mock() cancel_cb = mock.Mock() lease = client.Lease(ttl=TTL, ID=ID) lease.grant() lease.keepalive(keep_cb=keep_cb, cancel_cb=cancel_cb) lease.cancel_keepalive() assert keep_cb.called assert cancel_cb.called lease.keepalive_once() lease = client.Lease(ttl=TTL, ID=ID, new=False) lease.grant() assert lease.alive() lease.revoke() lease = client.Lease(ttl=TTL) lease.grant() assert lease.alive() lease.revoke()
StarcoderdataPython
4940375
import argparse import cv2 import numpy as np from tqdm import tqdm def get_args(): """Gets the arguments from the command line.""" parser = argparse.ArgumentParser("Handle an input stream") # -- Create the descriptions for the commands i_desc = "The location of the input file" # -- Create the arguments parser.add_argument("-i", help=i_desc) args = parser.parse_args() return args def capture_stream(args): ### TODO: Handle image, video or webcam image_flag = False if args.i == "CAM": args.i = 0 elif args.i.endswith((".jpg", "png", ".bmp")): image_flag = True ### TODO: Get and open video capture stream_capture = cv2.VideoCapture(args.i) stream_capture.open(args.i) new_width, new_height = 100, 100 # width, height = stream_capture.get(3), stream_capture.get(4) out = None if not image_flag: # To write to mp4 you would need to used MP4 Codecs # See: https://stackoverflow.com/questions/30103077/what-is-the-codec-for-mp4-videos-in-python-opencv # https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html#saving-a-video fourcc = cv2.VideoWriter_fourcc(*"mp4v") out = cv2.VideoWriter("out.mp4", fourcc, 30, (new_width, new_height)) length = stream_capture.get(cv2.CAP_PROP_FRAME_COUNT) fps = stream_capture.get(cv2.CAP_PROP_FPS) pbar = tqdm(total=int(length - fps + 1)) while stream_capture.isOpened(): pbar.update(1) flag, frame = stream_capture.read() if not flag: break # Easily exit from opencv key_pressed = cv2.waitKey(60) ### TODO: Re-size the frame to 100x100 frame = cv2.resize(frame, (new_width, new_height)) ### TODO: Add Canny Edge Detection to the frame, ### with min & max values of 100 and 200 frame = cv2.Canny(frame, 100, 200) ### Make sure to use np.dstack after to make a 3-channel image frame = np.dstack((frame,) * 3) ### TODO: Write out the frame, depending on image or video if image_flag: cv2.imwrite("output_image.jpg", frame) else: out.write(frame) if key_pressed == 27: break ### TODO: Close the stream and any windows at the end of the application pbar.close() if not image_flag: out.release() stream_capture.release() cv2.destroyAllWindows() def main(): args = get_args() capture_stream(args) if __name__ == "__main__": main()
StarcoderdataPython
286708
<gh_stars>10-100 # # Copyright 2012-2015 <NAME>, Inc. and contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import unicode_literals from builtins import str import logging import re import sys class StringBuilder(list): def build(self): return str(self) def __str__(self): return ''.join(self) class Directive(object): def __init__(self, type, argument=''): self.type = type self.argument = argument self.options = [] self.content = [] def add_option(self, name, value=''): self.options.append((name, value)) def add_content(self, o): assert o is not None self.content.append(o) def build(self): doc = Document() doc.add_line('.. %s:: %s' % (self.type, self.argument)) for name, value in self.options: doc.add_line(' :%s: %s\n' % (name, value)) content = Document() for obj in self.content: content.add_object(obj) doc.clear() for line in content.build().splitlines(): doc.add_line(' ' + line) doc.clear() return doc.build() class Document(object): remove_trailing_whitespace_re = re.compile('[ \t]+$', re.MULTILINE) collapse_empty_lines_re = re.compile('\n' + '{3,}', re.DOTALL) def __init__(self): self.content = [] def add_object(self, o): assert o is not None self.content.append(o) def add(self, s): self.add_object(s) def add_line(self, s): self.add(s) self.add('\n') def add_heading(self, s, t='-'): self.add_line(s) self.add_line(t * len(s)) def clear(self): self.add('\n\n') def build(self): output = StringBuilder() for obj in self.content: if isinstance(obj, Directive): output.append('\n\n') output.append(obj.build()) output.append('\n\n') elif isinstance(obj, Document): output.append(obj.build()) else: output.append(str(obj)) output.append('\n\n') output = str(output) output = self.remove_trailing_whitespace_re.sub('', output) output = self.collapse_empty_lines_re.sub('\n\n', output) return output def error(s, *args, **kwargs): logging.error(s, *args, **kwargs) sys.exit(1) def unexpected(s, *args, **kwargs): logging.exception(s, *args, **kwargs) sys.exit(1)
StarcoderdataPython
6455934
# coding: utf-8 from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class MeetingsConfig(AppConfig): name = 'value.deliverables.meetings' verbose_name = _('meetings') def ready(self): import value.deliverables.meetings.signals.handlers # noqa
StarcoderdataPython
238043
import numpy as np import matplotlib.pyplot as plt from matplotlib import animation import matplotlib.patches as patches import cv2 # write your script here, we recommend the above libraries for making your animation from LucasKanadeBasis import LucasKanadeBasis from LucasKanade import LucasKanade # write your script here, we recommend the above libraries for making your animation frames = np.load('../data/sylvseq.npy') bases = np.load('../data/sylvbases.npy') H, W, T = frames.shape rect1 = np.array([101, 61, 155, 107]).T rect2 = np.array([101, 61, 155, 107]).T for i in range(1, T): p1 = LucasKanadeBasis(frames[:, :, i-1], frames[:, :, i], rect1, bases) p2 = LucasKanade(frames[:, :, i-1], frames[:, :, i], rect2) print('frame: ', i) rect1[0] = rect1[0] + p1[1] rect1[1] = rect1[1] + p1[0] rect1[2] = rect1[2] + p1[1] rect1[3] = rect1[3] + p1[0] rect2[0] = rect2[0] + p2[1] rect2[1] = rect2[1] + p2[0] rect2[2] = rect2[2] + p2[1] rect2[3] = rect2[3] + p2[0] frame = frames[:, :, i].copy() cv2.rectangle(frame, (int(rect1[0]),int(rect1[1])), (int(rect1[2]),int(rect1[3])),(255), 1) cv2.rectangle(frame, (int(rect2[0]),int(rect2[1])), (int(rect2[2]),int(rect2[3])),(0), 1) #if i in [2, 100, 200, 300, 400]: # cv2.imwrite('frame_'+str(i) + '.jpg', frame.astype('uint8')) #break cv2.imshow('input', frame) print('frame: ', i) if cv2.waitKey(10) == ord('q'): break cv2.destroyAllWindows()
StarcoderdataPython
6657017
<filename>Back/userprofile/urls.py from django.urls import path from . import views urlpatterns = [ path("showpersonalinfo/", views.show_personal_info, name="showpersonalinfo"), path("getpersonalinfo/", views.get_personal_info, name="getpersonalinfo"), path("editprofilepicture/", views.edit_profile_picture, name="editprofilepicture"), path("editinterest/", views.edit_interests, name="editinterest"), path("show_profile_picture/", views.show_profile_picture, name="show_profile_picture"), path("show_interests/", views.show_interests, name="show_interests"), ]
StarcoderdataPython
1833645
<reponame>Khan/pyobjc-framework-Cocoa # # __main__.py # TableModel # # Created by <NAME> on Sun Apr 04 2004. # Copyright (c) 2004 <NAME>. All rights reserved. # from PyObjCTools import AppHelper # import classes required to start application import TableModelAppDelegate # start the event loop AppHelper.runEventLoop(argv=[])
StarcoderdataPython
6548814
import factory from wagtail.core.models import Site, Page from wagtail_factories import PageFactory from .pages.base import BasePage class BasePageFactory(PageFactory): class Meta: model = BasePage
StarcoderdataPython
9647733
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import copy, warnings from os import path from collections import OrderedDict import itertools import numpy as np from scipy import stats, signal, interpolate import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from . import six, afni, io, utils, dicom, math def convolve_HRF(starts, lens, TR=2, scan_time=None, HRF=None): if np.isscalar(lens): lens = lens * np.ones(len(starts)) numout_cmd = '' if scan_time is None else f"-numout {np.ceil(scan_time/TR)}" HRF_cmd = '-GAM' if HRF is None else HRF res = utils.run(f"waver -TR {TR} {numout_cmd} {HRF_cmd} -tstim {' '.join([f'{t:g}%{l:g}' for t, l in zip(starts, lens)])}", verbose=0) return np.float_(afni.filter_output(res['output'], ex_tags=['++'])) def create_ideal(stimuli, lens, **kwargs): ''' Parameters ---------- stimuli : list of fname ''' starts = [io.read_stim(fname) for fname in stimuli] n_stims = len(starts) n_runs = len(starts[0]) assert(np.all(np.array([len(runs) for runs in starts]) == n_runs)) if lens == 'alterating': lens = [[[] for run in range(n_runs)] for stim in range(n_stims)] for run in range(n_runs): curr_state, curr_time = -1, np.nan n_events = np.array([len(starts[stim][run]) for stim in range(n_stims)]) ids = np.zeros(n_stims, dtype=int) while np.any(ids < n_events): wavefront = [(starts[stim][run][ids[stim]] if ids[stim] < n_events[stim] else np.inf) for stim in range(n_stims)] next_state, next_time = np.argmin(wavefront), np.min(wavefront) if next_state != curr_state: if curr_state != -1: lens[curr_state][run].append(next_time - curr_time) curr_state, curr_time = next_state, next_time ids[curr_state] += 1 elif np.isscalar(lens): lens = [[[lens]*len(starts[stim][run]) for run in range(n_runs)] for stim in range(n_stims)] ideal = [[convolve_HRF(starts[stim][run], lens[stim][run], **kwargs) for run in range(n_runs)] for stim in range(n_stims)] return ideal def create_times(tmin, tmax, dt): if tmin < 0 and tmax > 0: times = np.r_[np.arange(-dt, tmin-dt/2, -dt)[::-1], np.arange(0, tmax+dt/2, dt)] else: times = np.arange(tmin, tmax+dt/2, dt) return times def create_ERP(t, x, events, tmin=-8, tmax=16, dt=0.1, baseline=[-2,0], interp='linear'): ''' t : time for each data point (can be non-contiguous) x : [event, feature, time] events : event onset time (can be on non-integer time point) ''' times = create_times(tmin, tmax, dt) f = interpolate.interp1d(t, x, axis=-1, kind=interp, fill_value=np.nan, bounds_error=False) base_corr = create_base_corr_func(times, baseline=baseline) ERP = np.zeros(np.r_[len(events), x.shape[1:-1], len(times)].astype(int), dtype=x.dtype) for k, t in enumerate(events): ERP[k] = base_corr(f(np.arange(t+tmin, t+tmax+dt/2, dt))) return ERP, times class Attributes(object): def __init__(self, shape): super().__setattr__('attributes', {}) self.shape = shape shape = property(lambda self: self._shape, lambda self, x: setattr(self, '_shape', np.array(x))) def add(self, name, value, axis): assert(len(value) == self.shape[axis]) self.attributes[name] = {'axis': axis, 'value': np.array(value)} def drop(self, name): self.attributes.pop(name) def drop_all_with_axis(self, axis): axes = axis if np.iterable(axis) else [axis] for axis in axes: for name in self.names_with_axis(axis): self.drop(name) def __getattr__(self, name): return self.attributes[name]['value'] def __setattr__(self, name, value): if name in self.attributes: assert(len(value) == self.shape[self.attributes[name]['axis']]) self.attributes[name]['value'] = np.array(value) else: # If the attribute is not added before, it will become a instance attribute super().__setattr__(name, value) def names_with_axis(self, axis): return [name for name, attr in self.attributes.items() if attr['axis']==axis] def __repr__(self): names = '\n'.join([f" axis={axis} ({self.shape[axis]}) | {', '.join(self.names_with_axis(axis))}" for axis in range(len(self.shape))]) return f"<Attributes | shape = {self.shape}\n" + names def __copy__(self): inst = type(self)(self.shape) inst.attributes = copy.deepcopy(self.attributes) return inst def pick(self, index, axis): inst = copy.copy(self) if np.iterable(axis): indices, axes = index, axis else: indices, axes = [index], [axis] for index, axis in zip(indices, axes): # Update shape first via a virtual attribute (in case there is not attribute at all) inst.shape[axis] = len(np.arange(inst.shape[axis])[index]) # Update attributes belonging to the axis for name in inst.names_with_axis(axis): attr = inst.attributes[name] attr['value'] = attr['value'][index] return inst @classmethod def concatinate(cls, attributes_list, axis): # Concat shape along axis, and check shape compatibility along other axis inst = attributes_list[0] self = cls(inst.shape) self.shape[axis] = np.sum([attributes.shape[axis] for attributes in attributes_list]) other_axes = np.r_[0:axis, axis+1:len(self.shape)] for attributes in attributes_list[1:]: assert(np.all(attributes.shape[other_axes] == self.shape[other_axes])) # Concat attributes along axis, and check attributes compatibility (identity) along other axis for name, attr in inst.attributes.items(): if attr['axis'] == axis: value = np.concatenate([attributes.attributes[name]['value'] for attributes in attributes_list]) else: value = attr['value'] for attributes in attributes_list[1:]: assert(np.all(attributes.attributes[name]['value'] == value)) self.add(name, value, axis) return self def to_dict(self): return dict(attributes=self.attributes, shape=self.shape) @classmethod def from_dict(cls, d): self = cls(None) for k, v in d.items(): setattr(self, k, v) return self class Raw(utils.Savable, object): def __init__(self, fname, mask=None, TR=None): if fname is None: return # Skip __init__(), create an empty Raw object, and manually initialize it later. if mask is not None: self.mask = mask if isinstance(mask, io.Mask) else io.Mask(mask) self.data = self.mask.dump(fname) else: self.mask = None self.data = io.read_vol(fname) self.info = {} self.info['sfreq'] = 1 / (afni.get_TR(fname) if TR is None else TR) self.info['feature_name'] = 'voxel' self.info['value_name'] = 'value' self.times = np.arange(self.n_times) * self.TR shape = property(lambda self: self.data.shape) n_features = property(lambda self: self.data.shape[0]) n_times = property(lambda self: self.data.shape[1]) TR = property(lambda self: 1 / self.info['sfreq']) @classmethod def from_array(cls, data, TR): ''' data : 2D array, [n_features, n_times] TR : in sec ''' self = cls(None) self.mask = None self.data = np.array(data, copy=False) self.info = dict(sfreq=1/TR, feature_name='voxel', value_name='value') self.times = np.arange(self.n_times) * self.TR return self def __repr__(self): # return f"<Raw | {self.n_features} {self.info['feature_name']}s, {self.times[0]:.3f} - {self.times[-1]:.3f} sec, TR = {self.TR} sec, {self.n_times} TRs>" return f"<Raw | {self.n_features} {self.info['feature_name']}s, {self.times[0]:.3f} - {self.times[-1]+self.TR:.3f} sec, TR = {self.TR} sec, {self.n_times} TRs>" def copy(self): return _copy(self) def plot(self, events=None, event_id=None, color=None, palette=None, figsize=None, event_kws=None, **kwargs): # Plot mean time course data = np.mean(self.data, axis=0) if events is not None: # If going to plot events, plot data in black by default color = 'k' if color is None else color if figsize is not None: plt.gcf().set_figwidth(figsize[0]) plt.gcf().set_figheight(figsize[1]) plt.plot(self.times, data, color=color, **kwargs) plt.xlabel('Time (s)') plt.ylabel('Signal change (%)') # Plot events if events is not None: if event_id is None: event_id = _default_event_id(events) if palette is None: # A palette is eventually a list of colors palette = plt.rcParams['axes.prop_cycle'].by_key()['color'] id2ev = {id: [eid, ev, None] for eid, (ev, id) in enumerate(event_id.items())} event_kws = dict(dict(), **(event_kws if event_kws is not None else {})) for event in events: t, id = event[0], event[-1] id2ev[id][2] = plt.axvline(t, color=palette[id2ev[id][0]], **event_kws) plt.legend(*zip(*[(h, ev) for eid, ev, h in id2ev.values()])) def to_dict(self): return dict(info=self.info, data=self.data, mask=self.mask.to_dict(), times=self.times) @classmethod def from_dict(cls, d): self = cls(None) for k, v in d.items(): setattr(self, k, v) self.mask = io.Mask.from_dict(self.mask) return self def _copy(self): '''Copy all object attributes other than `data`, which is simply referred to.''' # TODO: .info and events etc. should be deep copied data = self.data del self.data inst = copy.copy(self) inst.data = self.data = data return inst class RawCache(utils.Savable, object): def __init__(self, fnames, mask, TR=None, cache_file=None, force_redo=False): if fnames is None: return # Skip __init__(), create an empty RawCache object, and manually initialize it later. if cache_file is None or not utils.exists(cache_file, force_redo=force_redo): self.mask = mask if isinstance(mask, io.Mask) else io.Mask(mask) self.raws = [Raw(fname, mask=self.mask, TR=TR) for fname in fnames] if cache_file is not None: self.save(cache_file) else: inst = self.load(cache_file) self.mask = inst.mask self.raws = inst.raws n_runs = property(lambda self: len(self.raws)) def subset(self, mask, cache_file=None): inst = type(self)(None, None) inst.mask = mask if isinstance(mask, io.Mask) else io.Mask(mask) inst.raws = self.get_raws(mask) # TODO: copy??? if cache_file is not None: inst.save(cache_file) return inst def get_raws(self, mask, ids=None): return_scalar = False if ids is None: ids = range(self.n_runs) elif not utils.iterable(ids): return_scalar = True ids = [ids] if isinstance(mask, six.string_types): mask = io.Mask(mask) selector = self.mask.infer_selector(mask) elif isinstance(mask, io.Mask): selector = self.mask.infer_selector(mask) else: # boolean index selector = mask mask = self.mask.pick(selector) raws = [] for idx in ids: raw = self.raws[idx].copy() raw.data = raw.data[selector] raw.mask = mask raws.append(raw) return raws[0] if return_scalar else raws def get_epochs(self, mask, events, event_id, ids=None, cache_file=None, **kwargs): assert(len(events) == self.n_runs or len(events) == len(ids)) if cache_file is None or not utils.exists(cache_file): epochs = [Epochs(raw, events[idx], event_id=event_id, **kwargs) for idx, raw in enumerate(self.get_raws(mask, ids=ids))] epochs = concatinate_epochs(epochs) if cache_file is not None: epochs.save(cache_file) else: epochs = Epochs.load(cache_file) return epochs def to_dict(self): return dict(raws=[raw.to_dict() for raw in self.raws], mask=self.mask.to_dict()) @classmethod def from_dict(cls, d): self = cls(None, None) for k, v in d.items(): setattr(self, k, v) self.raws = [Raw.from_dict(raw) for raw in self.raws] self.mask = io.Mask.from_dict(self.mask) return self def read_events(event_files): ''' Read events from AFNI style (each row is a run, and each element is an occurance) stimulus timing files. Parameters ---------- event_files : dict e.g., OrderedDict(('Physical/Left', '../stimuli/phy_left.txt'), ('Physical/Right', '../stimuli/phy_right.txt'), ...) Returns ------- events_list : list of n_events-by-3 arrays The three columns are [start_time(sec), reserved, event_id(int)] event_id : dict ''' if not isinstance(event_files, dict): event_files = OrderedDict((path.splitext(path.basename(f))[0], f) for f in event_files) t = [] e = [] event_id = OrderedDict() for k, (event, event_file) in enumerate(event_files.items()): if isinstance(event_file, str): eid = k + 1 else: event_file, eid = event_file with open(event_file, 'r') as fi: for rid, line in enumerate(fi): line = line.strip() if not line: continue if k == 0: t.append([]) e.append([]) if not line.startswith('*'): t_run = np.float_(line.split()) t[rid].extend(t_run) e[rid].extend(np.ones_like(t_run)*(eid)) event_id[event] = eid events_list = [] for rid in range(len(t)): events_run = np.c_[t[rid], np.zeros_like(t[rid]), e[rid]] sorter = np.argsort(events_run[:,0]) events_list.append(events_run[sorter,:]) return events_list, event_id def events_from_dataframe(df, time, conditions, duration=None, run=None, event_id=None): ''' Parameters ---------- df : dataframe time : str conditions : list (names) or OrderedDict (name->levels) duration : str run : str event_id : dict (name->index) Returns ------- events : array event_id : dict (name->index) ''' if not isinstance(conditions, dict): conditions = OrderedDict([(condition, sorted(df[condition].unique())) for condition in conditions]) if event_id is None: levels = itertools.product(*list(conditions.values())) event_id = OrderedDict([('/'.join(level), k+1) for k, level in enumerate(levels)]) get_event_id = lambda trial: event_id['/'.join([getattr(trial, condition) for condition in conditions])] get_duration = lambda trial: 0 if duration is None else getattr(trial, duration) if run is not None: events = [] for r in sorted(df[run].unique()): # Uniques are returned in order of appearance (NOT sorted). events.append(np.array([[getattr(trial, time), get_duration(trial), get_event_id(trial)] for trial in df[df[run]==r].itertuples()])) else: events = np.array([[getattr(trial, time), get_duration(trial), get_event_id(trial)] for trial in df.itertuples()]) return events, event_id def events_to_dataframe(events_list, event_id, conditions): id2event = {eid: event.split('/') for event, eid in event_id.items()} trials = [] for rid, events in enumerate(events_list): for tid in range(len(events)): trials.append(OrderedDict([('run', rid+1), ('trial', tid+1), ('time', events[tid,0])] \ + list(zip(conditions, id2event[events[tid,2]])))) return pd.DataFrame(trials) def _default_event_id(events): return {f"{id:g}": id for id in np.unique(events[:,2])} def create_base_corr_func(times, baseline=None, method=None): ''' Parameters ---------- time : array-like Sampling time for your data. baseline : 'none', 'all', or (tmin, tmax) Baseline time interval. ''' if baseline is None: baseline = 'none' if method is None: method = np.nanmean if isinstance(baseline, str): if baseline.lower() == 'none': return lambda x: x elif baseline.lower() == 'all': return lambda x: x - np.nanmean(x, axis=-1, keepdims=True) else: # `baseline` is like (tmin, tmax) tmin = times[0] if baseline[0] is None else baseline[0] tmax = times[-1] if baseline[1] is None else baseline[1] times = np.array(times) time_sel = (tmin<=times) & (times<=tmax) if method in [np.nanmean, np.nanmedian]: def base_corr(x): with warnings.catch_warnings(): warnings.simplefilter('ignore', category=RuntimeWarning) return x - method(x[...,time_sel], axis=-1, keepdims=True) return base_corr else: return lambda x: x - method(x[...,time_sel], axis=-1, keepdims=True) class Epochs(utils.Savable, object): def __init__(self, raw, events, event_id=None, tmin=-5, tmax=15, baseline=(-2,0), dt=0.1, interp='linear', hamm=None, conditions=None): if raw is None: return # Skip __init__(), create an empty Epochs object, and manually initialize it later. self.events = events self.event_id = _default_event_id(events) if event_id is None else event_id self.info = raw.info.copy() # Caution: container datatype is assigned by reference by default self.info['sfreq'] = 1 / dt self.info['tmin'] = tmin self.info['tmax'] = tmax self.info['baseline'] = baseline self.info['interp'] = interp self.info['hamm'] = hamm if isinstance(conditions, six.string_types): conditions = conditions.split('/') self.info['conditions'] = conditions self.info['condition'] = None self.times = create_times(tmin, tmax, dt) x = raw.data if hamm is not None: h = signal.hamming(hamm) h = h/np.sum(h) x = signal.filtfilt(h, [1], x, axis=-1) f = interpolate.interp1d(raw.times, x, axis=-1, kind=interp, fill_value=np.nan, bounds_error=False) base_corr = create_base_corr_func(self.times, baseline=baseline) self.data = np.zeros([events.shape[0], raw.n_features, len(self.times)], dtype=raw.data.dtype) for k, t in enumerate(events[:,0]): self.data[k] = base_corr(f(np.arange(t+tmin, t+tmax+dt/2, dt))) self.attr = Attributes(shape=self.shape) shape = property(lambda self: self.data.shape) n_events = property(lambda self: self.data.shape[0]) n_features = property(lambda self: self.data.shape[1]) n_times = property(lambda self: self.data.shape[2]) @classmethod def from_array(cls, data, TR=None, tmin=None, baseline=(-2,0), events=None, event_id=None, conditions=None): self = cls(None, None) self.data = np.array(data, copy=False) assert(self.data.ndim == 3) # n_events x n_features x n_times self.info = {} self.info['sfreq'] = 1 if TR is None else 1/TR self.info['feature_name'] = 'voxel' self.info['value_name'] = 'value' self.info['tmin'] = 0 if tmin is None else tmin self.times = self.info['tmin'] + np.arange(self.data.shape[-1])/self.info['sfreq'] self.info['tmax'] = self.times[-1] self.info['baseline'] = baseline self.info['interp'] = None self.info['hamm'] = None self.info['conditions'] = conditions self.info['condition'] = None if events is not None: assert(self.data.shape[0] == events.shape[0]) self.events = events else: self.events = np.zeros([self.data.shape[0], 3]) if event_id is None: self.event_id = {'Event': 0} if events is None else _default_event_id(self.events) else: assert(np.all(np.in1d(self.events[:,2], list(event_id.values())))) self.event_id = event_id base_corr = create_base_corr_func(self.times, baseline=baseline) self.data = base_corr(self.data) self.attr = Attributes(shape=self.shape) return self def __repr__(self): event_str = '\n '.join(f"'{ev}': {np.sum(self.events[:,2]==id)}" for ev, id in self.event_id.items()) return f"<Epochs | {self.n_events:4d} events, {self.n_features} {self.info['feature_name']}s, {self.times[0]:.3f} - {self.times[-1]:.3f} sec, baseline {self.info['baseline']}, hamm = {self.info['hamm']},\n {event_str}>" # https://github.com/mne-tools/mne-python/blob/master/mne/utils/mixin.py def __getitem__(self, item): if isinstance(item, tuple): return self.pick(*item) else: return self.pick(event=item) def add_event_attr(self, name, value): self.attr.add(name, value, axis=0) def add_feature_attr(self, name, value): self.attr.add(name, value, axis=1) def pick(self, event=None, feature=None, time=None): inst = self.copy() # Select event if event is None: sel_event = slice(None) elif isinstance(event, six.string_types) or (utils.iterable(event) and isinstance(event[0], six.string_types)): # e.g., 'Physical/Left' sel_event = self._partial_match_event(event) self.info['condition'] = event if isinstance(event, six.string_types) else ' | '.join(event) else: sel_event = event inst.events = inst.events[sel_event] inst.event_id = {ev: id for ev, id in inst.event_id.items() if id in inst.events[:,2]} # Select feature if feature is None: sel_feature = slice(None) else: sel_feature = feature # Select time if time is None: sel_time = slice(None) elif utils.iterable(time) and len(time) == 2: sel_time = (time[0] <= self.times) & (self.times <= time[1]) else: sel_time = time inst.times = inst.times[sel_time] inst.info['tmin'] = inst.times[0] inst.info['tmax'] = inst.times[-1] # inst.info['sfreq'] = ? # Make 3D selection inst.data = inst.data[sel_event][:,sel_feature][...,sel_time] inst.attr = inst.attr.pick([sel_event, sel_feature, sel_time], axis=[0, 1, 2]) return inst def copy(self): inst = _copy(self) inst.attr = copy.copy(self.attr) return inst def drop_events(self, ids): inst = self.copy() inst.data = np.delete(inst.data, ids, axis=0) inst.events = np.delete(inst.events, ids, axis=0) inst.event_id = {ev: id for ev, id in inst.event_id.items() if id in inst.events[:,2]} # TODO: Need refactor inst.attr.pick(np.delete(np.arange(self.n_events), ids), axis=0) return inst def _partial_match_event(self, keys): if isinstance(keys, six.string_types): keys = [keys] matched = [] for key in keys: key_set = set(key.split('/')) matched_id = [id for ev, id in self.event_id.items() if key_set.issubset(ev.split('/'))] matched.append(np.atleast_2d(np.in1d(self.events[:,2], matched_id))) return np.any(np.vstack(matched), axis=0) def apply_baseline(self, baseline): base_corr = create_base_corr_func(self.times, baseline=baseline) inst = self.copy() inst.data = base_corr(inst.data) inst.info['baseline'] = baseline return inst def aggregate(self, event=True, feature=False, time=False, method=np.nanmean, keepdims=np._globals._NoValue, return_index=False): axes = ((0,) if event else ()) + ((1,) if feature else ()) + ((2,) if time else ()) values = method(self.data, axis=axes, keepdims=keepdims) events = self.events[:,2] if not event else None features = np.arange(self.n_features) if not feature else -1 times = self.times if not time else np.mean(self.times) return (values, events, features, times) if return_index else values def average(self, feature=True, time=False, method=np.nanmean, error='bootstrap', ci=95, n_boot=1000, condition=None): ''' Average data over event (and optionally feature and/or time) dimensions, and return an Evoked object. ''' x, _, _, times = self.aggregate(event=False, feature=feature, time=time, method=method, return_index=True) data = method(x, axis=0) nave = x.shape[0] if error == 'bootstrap': error_type = (error, ci) boot_dist = method(x[np.random.randint(nave, size=[nave, n_boot]),...], axis=0) error = np.percentile(boot_dist, [50-ci/2, 50+ci/2], axis=0) - data elif error == 'instance': error_type = (error, None) error = x - data if condition is None: condition = self.info['condition'] evoked = Evoked(self.info, data, nave, times, error=error, error_type=error_type, condition=condition) return evoked # def running_average(self, win_size, overlap=0.5, time=False, method=np.nanmean): # data = [] # for start in range(0, self.n_events, int(win_size*overlap)): # x, _, _, times = self.pick(event=slice(start, start+win_size)).aggregate(feature=True, time=time, method=method, return_index=True) # data.append(x) # evoked = Evoked2D(self.info, np.array(data), win_size, features, times) def transform(self, feature_name, feature_values, transformer): ''' Transform the data into a new Epochs object. E.g., epochs.transform('depth', depth, tc.wcutter(depth, linspace(0, 1, 20), win_size=0.2, win_func='gaussian', exclude_outer=True)) ''' assert(len(feature_values)==self.n_features) inst = self.copy() inst.info['feature_name'] = feature_name inst.info['feature_values'] = feature_values inst.data = transform(inst.data, *transformer, axis=1) # TODO: update inst.attr return inst def summary(self, event=False, feature=True, time=False, method=np.nanmean, attributes=None): ''' Summary data as a pandas DataFrame. ''' assert(self.info['conditions'] is not None) dfs = [] for ev in self.event_id: # import pdb; pdb.set_trace() x, _, features, times = self.pick(ev).aggregate(event=event, feature=feature, time=time, method=method, keepdims=True, return_index=True) events = ev.split('/') df = OrderedDict() for k, condition in enumerate(self.info['conditions']): df[condition] = events[k] df[self.info['feature_name']] = np.tile(np.repeat(features, x.shape[2]), x.shape[0]) df['time'] = np.tile(times, np.prod(x.shape[:2])) df[self.info['value_name']] = x.ravel() dfs.append(pd.DataFrame(df)) df = pd.concat(dfs, ignore_index=True) if attributes is not None: for name, value in attributes.items(): df[name] = value return df def plot(self, hue=None, style=None, row=None, col=None, hue_order=None, style_order=None, row_order=None, col_order=None, palette=None, dashes=None, figsize=None, legend=True, bbox_to_anchor=None, subplots_kws=None, average_kws=None, axs=None, **kwargs): assert(self.info['conditions'] is not None) conditions = OrderedDict([(condition, np.unique(levels)) for condition, levels in zip(self.info['conditions'], np.array([ev.split('/') for ev in self.event_id]).T)]) con_sel = [[hue, style, row, col].index(condition) for condition in conditions] n_rows = 1 if row is None else len(conditions[row]) n_cols = 1 if col is None else len(conditions[col]) if axs is None: subplots_kws = dict(dict(sharex=True, sharey=True, figsize=figsize, constrained_layout=True), **({} if subplots_kws is None else subplots_kws)) fig, axs = plt.subplots(n_rows, n_cols, squeeze=False, **subplots_kws) row_order = [None] if row is None else (conditions[row] if row_order is None else row_order) col_order = [None] if col is None else (conditions[col] if col_order is None else col_order) hue_order = [None] if hue is None else (conditions[hue] if hue_order is None else hue_order) style_order = [None] if style is None else (conditions[style] if style_order is None else style_order) if palette is None: palette = plt.rcParams['axes.prop_cycle'].by_key()['color'] elif isinstance(palette, str): palette = sns.color_palette(palette) if dashes is None: dashes = ['-', '--', ':', '-.'] average_kws = dict(dict(), **({} if average_kws is None else average_kws)) for rid, row_val in enumerate(row_order): for cid, col_val in enumerate(col_order): plt.sca(axs[rid,cid]) show_info = True for hid, hue_val in enumerate(hue_order): for sid, style_val in enumerate(style_order): event = '/'.join(np.array([hue_val, style_val, row_val, col_val])[con_sel]) label = '/'.join([s for s in [hue_val, style_val] if s is not None]) event_sel = self._partial_match_event(event) kwargs = dict(dict(show_n='label' if label else 'info', info=show_info), **kwargs) self[event_sel].average(**average_kws).plot(color=palette[hid], ls=dashes[sid], label=label, **kwargs) show_info = False plt.axhline(0, color='gray', ls='--') plt.title('/'.join([s for s in [row_val, col_val] if s is not None])) if rid < n_rows-1: plt.xlabel('') if cid > 0: plt.ylabel('') if legend and label: plt.legend(bbox_to_anchor=bbox_to_anchor, loc=None if bbox_to_anchor is None else 'center left') sns.despine() def to_dict(self): return dict(info=self.info, data=self.data, events=self.events, event_id=self.event_id, times=self.times, attr=self.attr.to_dict()) @classmethod def from_dict(cls, d): self = cls(None, None) for k, v in d.items(): setattr(self, k, v) self.attr = Attributes.from_dict(self.attr) return self def concatinate_epochs(epochs_list, axis=0): inst = epochs_list[0].copy() inst.data = np.concatenate([epochs.data for epochs in epochs_list], axis=axis) inst.attr = Attributes.concatinate([epochs.attr for epochs in epochs_list], axis=axis) if axis == 0: # Concat events inst.events = np.concatenate([epochs.events for epochs in epochs_list], axis=0) inst.event_id = {k: v for epochs in epochs_list for k, v in epochs.event_id.items()} elif axis == 1: # Concat voxels assert(np.all([np.all(epochs.events == epochs_list[0].events) for epochs in epochs_list[1:]])) assert(np.all([(epochs.event_id == epochs_list[0].event_id) for epochs in epochs_list[1:]])) return inst def group_epochs(epochs_list): inst = epochs_list[0].copy() inst.data = np.concatenate([epochs[event].aggregate(event=True, feature=True, keepdims=True) for epochs in epochs_list for event in inst.event_id], axis=0) inst.events = np.array(list(inst.event_id.values())*len(epochs_list)) inst.events = np.c_[np.zeros((len(inst.events),2)), inst.events] inst.attr = Attributes(shape=inst.shape) return inst # def transform(data, idx_gen, weight_gen=None, agg_func=None, axis=0): # if agg_func is None: # agg_func = np.nanmean if np.any(np.isnan(data)) else np.mean # if weight_gen is None: # ##### BUG!!! # return np.concatenate([agg_func(data[idx,...], axis=axis, keepdims=True) for idx in idx_gen], axis=axis) # else: # return np.concatenate([agg_func(data[idx,...]*weight, axis=axis, keepdims=True) # for idx, weight in zip(idx_gen, weight_gen)], axis=axis) def cut(data, val, bins, **kwargs): return transform(data, *cutter(val, bins), **kwargs) def cutter(val, bins): idx_gen = ((bins[k]<val)&(val<=bins[k+1]) for k in range(len(bins)-1)) return idx_gen, None def qcut(data, val, q, **kwargs): return transform(data, *qcutter(val, q), **kwargs) def qcutter(val, q): bins = np.percentile(val, q) idx_gen = ((bins[k]<val)&(val<=bins[k+1]) for k in range(len(bins)-1)) return idx_gen, None def wcut(data, val, v, win_size, win_func=None, exclude_outer=False, **kwargs): return transform(data, *wcutter(val, v, win_size, win_func=win_func, exclude_outer=exclude_outer), **kwargs) def wcutter(val, v, win_size, win_func=None, exclude_outer=False): r = win_size/2 if win_func == 'gaussian': sigma = win_size/4 win_func = lambda c, x: np.exp(-(x-c)**2/sigma**2) if exclude_outer: bins = [[max(v[0], vv-r), min(v[-1], vv+r)] for vv in v] else: bins = [[vv-r, vv+r] for vv in v] idx_gen = ((lower<val)&(val<=upper) for lower, upper in bins) if win_func is not None: weight_gen = (win_func(vv, val[(lower<val)&(val<=upper)]) for vv, (lower, upper) in zip(v, bins)) else: weigth_gen = None return idx_gen, weight_gen class Evoked(object): def __init__(self, info, data, nave, times, error=None, error_type=None, condition=None): ''' This class is intended for representing only a single subject and a single condition. Group data with multiple conditions together could be flexibly handled by `pd.DataFrame`. For the later purpose, instead of Epochs.average() -> Evoked, consider using Epochs.summary() -> pd.DataFrame. ''' self.info = info self.times = times self.data = data self.info['nave'] = nave self.error = error self.info['error_type'] = error_type self.info['condition'] = condition shape = property(lambda self: self.data.shape) def plot(self, color=None, error=True, info=True, error_kws=None, show_n='info', **kwargs): n_str = rf"$n={self.info['nave']}$" label = kwargs.pop('label') if 'label' in kwargs else self.info['condition'] if show_n == 'label': label += rf" ({n_str})" line = plt.plot(self.times, self.data, color=color, label=label, **kwargs)[0] if color is None: color = line.get_color() if error: if self.info['error_type'][0] == 'instance': error_kws = dict(dict(alpha=0.3, lw=0.3), **(error_kws if error_kws is not None else {})) plt.plot(self.times, (self.data+self.error).T, color=color, **error_kws) else: error_kws = dict(dict(alpha=0.3), **(error_kws if error_kws is not None else {})) plt.fill_between(self.times, self.data+self.error[0], self.data+self.error[1], color=color, **error_kws) plt.xlabel('Time (s)') plt.ylabel('Signal change (%)') if info: ci = self.info['error_type'][1] err_str = r'$\pm SEM$' if ci == 68 else rf'${ci}\%\ CI$' s = rf"{n_str}$\quad${err_str}" if show_n == 'info' else err_str plt.text(0.95, 0.05, s, ha='right', transform=plt.gca().transAxes) # class Evoked2D(object): # def __init__(self, info, data, nave, features, times): # self.info = info # self.features = features # self.times = times # self.data = data # self.info['nave'] = nave # @classmethod # def from_evoked_list(cls, evoked_list, features): # evoked = evoked_list[0] # data = np.array([evoked.data for evoked in evoked_list]) # return cls(evoked.info, data, evoked.info['nave'], features, evoked.times) if __name__ == '__main__': pass # stim_dir = '/Volumes/raid78/ccqian/LaminarRivalry2/LGN/S01/stimuli' # stim_files = [f"{stim_dir}/L_replay.txt", f"{stim_dir}/R_replay.txt"] # tc.create_ideal(stim_files, 'alterating')
StarcoderdataPython
962
<gh_stars>1000+ # Copyright 2019 Atalaya Tech, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import io import os import sys import tarfile import logging import tempfile import shutil from functools import wraps from contextlib import contextmanager from urllib.parse import urlparse from typing import TYPE_CHECKING from pathlib import PureWindowsPath, PurePosixPath from bentoml.utils.s3 import is_s3_url from bentoml.utils.gcs import is_gcs_url from bentoml.exceptions import BentoMLException from bentoml.saved_bundle.config import SavedBundleConfig from bentoml.saved_bundle.pip_pkg import ZIPIMPORT_DIR if TYPE_CHECKING: from bentoml.yatai.proto.repository_pb2 import BentoServiceMetadata logger = logging.getLogger(__name__) def _is_http_url(bundle_path) -> bool: try: return urlparse(bundle_path).scheme in ["http", "https"] except ValueError: return False def _is_remote_path(bundle_path) -> bool: return isinstance(bundle_path, str) and ( is_s3_url(bundle_path) or is_gcs_url(bundle_path) or _is_http_url(bundle_path) ) @contextmanager def _resolve_remote_bundle_path(bundle_path): if is_s3_url(bundle_path): import boto3 parsed_url = urlparse(bundle_path) bucket_name = parsed_url.netloc object_name = parsed_url.path.lstrip('/') s3 = boto3.client('s3') fileobj = io.BytesIO() s3.download_fileobj(bucket_name, object_name, fileobj) fileobj.seek(0, 0) elif is_gcs_url(bundle_path): try: from google.cloud import storage except ImportError: raise BentoMLException( '"google-cloud-storage" package is required. You can install it with ' 'pip: "pip install google-cloud-storage"' ) gcs = storage.Client() fileobj = io.BytesIO() gcs.download_blob_to_file(bundle_path, fileobj) fileobj.seek(0, 0) elif _is_http_url(bundle_path): import requests response = requests.get(bundle_path) if response.status_code != 200: raise BentoMLException( f"Error retrieving BentoService bundle. " f"{response.status_code}: {response.text}" ) fileobj = io.BytesIO() fileobj.write(response.content) fileobj.seek(0, 0) else: raise BentoMLException(f"Saved bundle path: '{bundle_path}' is not supported") with tarfile.open(mode="r:gz", fileobj=fileobj) as tar: with tempfile.TemporaryDirectory() as tmpdir: filename = tar.getmembers()[0].name tar.extractall(path=tmpdir) yield os.path.join(tmpdir, filename) def resolve_remote_bundle(func): """Decorate a function to handle remote bundles.""" @wraps(func) def wrapper(bundle_path, *args): if _is_remote_path(bundle_path): with _resolve_remote_bundle_path(bundle_path) as local_bundle_path: return func(local_bundle_path, *args) return func(bundle_path, *args) return wrapper @resolve_remote_bundle def load_saved_bundle_config(bundle_path) -> "SavedBundleConfig": try: return SavedBundleConfig.load(os.path.join(bundle_path, "bentoml.yml")) except FileNotFoundError: raise BentoMLException( "BentoML can't locate config file 'bentoml.yml'" " in saved bundle in path: {}".format(bundle_path) ) def load_bento_service_metadata(bundle_path: str) -> "BentoServiceMetadata": return load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb() def _find_module_file(bundle_path, service_name, module_file): # Simply join full path when module_file is just a file name, # e.g. module_file=="iris_classifier.py" module_file_path = os.path.join(bundle_path, service_name, module_file) if not os.path.isfile(module_file_path): # Try loading without service_name prefix, for loading from a installed PyPi module_file_path = os.path.join(bundle_path, module_file) # When module_file is located in sub directory # e.g. module_file=="foo/bar/iris_classifier.py" # This needs to handle the path differences between posix and windows platform: if not os.path.isfile(module_file_path): if sys.platform == "win32": # Try load a saved bundle created from posix platform on windows module_file_path = os.path.join( bundle_path, service_name, str(PurePosixPath(module_file)) ) if not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, str(PurePosixPath(module_file)) ) else: # Try load a saved bundle created from windows platform on posix module_file_path = os.path.join( bundle_path, service_name, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): raise BentoMLException( "Can not locate module_file {} in saved bundle {}".format( module_file, bundle_path ) ) return module_file_path @resolve_remote_bundle def load_bento_service_class(bundle_path): """ Load a BentoService class from saved bundle in given path :param bundle_path: A path to Bento files generated from BentoService#save, #save_to_dir, or the path to pip installed BentoService directory :return: BentoService class """ config = load_saved_bundle_config(bundle_path) metadata = config["metadata"] # Find and load target module containing BentoService class from given path module_file_path = _find_module_file( bundle_path, metadata["service_name"], metadata["module_file"] ) # Prepend bundle_path to sys.path for loading extra python dependencies sys.path.insert(0, bundle_path) sys.path.insert(0, os.path.join(bundle_path, metadata["service_name"])) # Include zipimport modules zipimport_dir = os.path.join(bundle_path, metadata["service_name"], ZIPIMPORT_DIR) if os.path.exists(zipimport_dir): for p in os.listdir(zipimport_dir): logger.debug('adding %s to sys.path', p) sys.path.insert(0, os.path.join(zipimport_dir, p)) module_name = metadata["module_name"] if module_name in sys.modules: logger.warning( "Module `%s` already loaded, using existing imported module.", module_name ) module = sys.modules[module_name] elif sys.version_info >= (3, 5): import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info >= (3, 3): from importlib.machinery import SourceFileLoader # pylint:disable=deprecated-method module = SourceFileLoader(module_name, module_file_path).load_module( module_name ) # pylint:enable=deprecated-method else: raise BentoMLException("BentoML requires Python 3.4 and above") # Remove bundle_path from sys.path to avoid import naming conflicts sys.path.remove(bundle_path) model_service_class = module.__getattribute__(metadata["service_name"]) # Set _bento_service_bundle_path, where BentoService will load its artifacts model_service_class._bento_service_bundle_path = bundle_path # Set cls._version, service instance can access it via svc.version model_service_class._bento_service_bundle_version = metadata["service_version"] if ( model_service_class._env and model_service_class._env._requirements_txt_file is not None ): # Load `requirement.txt` from bundle directory instead of the user-provided # file path, which may only available during the bundle save process model_service_class._env._requirements_txt_file = os.path.join( bundle_path, "requirements.txt" ) return model_service_class @resolve_remote_bundle def safe_retrieve(bundle_path: str, target_dir: str): """Safely retrieve bento service to local path Args: bundle_path (:obj:`str`): The path that contains saved BentoService bundle, supporting both local file path and s3 path target_dir (:obj:`str`): Where the service contents should end up. Returns: :obj:`str`: location of safe local path """ shutil.copytree(bundle_path, target_dir) @resolve_remote_bundle def load_from_dir(bundle_path): """Load bento service from local file path or s3 path Args: bundle_path (str): The path that contains saved BentoService bundle, supporting both local file path and s3 path Returns: bentoml.service.BentoService: a loaded BentoService instance """ svc_cls = load_bento_service_class(bundle_path) return svc_cls() @resolve_remote_bundle def load_bento_service_api(bundle_path, api_name=None): bento_service = load_from_dir(bundle_path) return bento_service.get_inference_api(api_name)
StarcoderdataPython
6429119
from .LoggingManager import LoggingManager
StarcoderdataPython
6528672
# -*- coding: utf-8 -*- from andip.default import DefaultProvider from ZODB.FileStorage import FileStorage from ZODB.DB import DB from persistent.mapping import PersistentMapping import transaction class DatabaseProvider(DefaultProvider): def __init__(self, path, backoff = None): """ Initializes DatabaseProvider. This provider requires closing database after using (call close function). :param path: path to a database file :type path: str :param backoff: (optional) backoff provider """ DefaultProvider.__init__(self, backoff) self.storage = FileStorage(path + '.fs') self.db = DB(self.storage) self.connection = self.db.open() self.root = self.connection.root() if not self.root: self.__dictionary_init() def __check_connection(self): if self.root == None: raise LookupError("Database connection is closed!") def close(self): """ Function close connection to database. Call this before destroying DatabaseProvider object to avoid issues with database file access. """ self.connection.close() self.db.close() self.storage.close() self.root = None def save_model(self, conf): """ Inserts new data into database. Get new data using WikiProvider and get it using get_model method. :param conf: new data returned by WikiProvider get_model method """ self.__check_connection(); for type in conf: for baseword in conf[type]: self.__save(conf[type][baseword], baseword, type) def _get_word(self, conf): ''' Returns word or throw KeyError, if there is no information about word in database ''' self.__check_connection(); return self.__get_word(conf[2], conf[1]) def _get_conf(self, word): ''' Returns word configuration or KeyError, if there is no information about word in database ''' self.__check_connection(); return self.__get_conf_preview(word) def __dictionary_init(self): ''' Initialization of database dictionaries. ''' self.root['przymiotnik'] = PersistentMapping() self.root['rzeczownik'] = PersistentMapping() self.root['czasownik'] = PersistentMapping() self.root['czasownik']['word'] = PersistentMapping() self.root['przymiotnik']['word'] = PersistentMapping() self.root['rzeczownik']['word'] = PersistentMapping() transaction.commit() def __save(self, dict, base_word, type): ''' Save object to database in Bartosz Alchimowicz convention ''' self.root[type]['word'][base_word] = dict transaction.commit() def __get_conf(self, base_word): ''' Get configuration of word whic is in database ''' for word_type in ['rzeczownik', 'czasownik', 'przymiotnik']: for word in self.root[word_type]['word'].keys(): if word == base_word: return self.root[word_type]['word'][word] raise KeyError("There is no such a word in Database") def __get_conf_preview(self, word): # rzeczownik dictionary = self.root['rzeczownik']['word'] for base_word in dictionary.keys(): for przypadek in dictionary[base_word]['przypadek'].keys(): for liczba in dictionary[base_word]['przypadek'][przypadek]['liczba'].keys(): if dictionary[base_word]['przypadek'][przypadek]['liczba'][liczba] == word: return [('rzeczownik', base_word, {'przypadek' : przypadek, 'liczba' : liczba })] # przymiotnik dictionary = self.root['przymiotnik']['word'] for base_word in dictionary.keys(): for stopien in dictionary[base_word]['stopień'].keys(): for przypadek in dictionary[base_word]['stopień'][stopien]['przypadek'].keys(): for liczba in dictionary[base_word]['stopień'][stopien]['przypadek'][przypadek]['liczba'].keys(): for rodzaj in dictionary[base_word]['stopień'][stopien]['przypadek'][przypadek]['liczba'][liczba]['rodzaj'].keys(): if dictionary[base_word]['stopień'][stopien]['przypadek'][przypadek]['liczba'][liczba]['rodzaj'][rodzaj] == word: return [('przymiotnik', base_word, {'stopień' : stopien, 'liczba' : liczba, 'rodzaj' : rodzaj})] # czasownik dictionary = self.root['czasownik']['word'] for base_word in dictionary.keys(): for aspekt in dictionary[base_word]['aspekt'].keys(): for forma in dictionary[base_word]['aspekt'][aspekt]['forma'].keys(): for liczba in dictionary[base_word]['aspekt'][aspekt]['forma'][forma]['liczba'].keys(): for osoba in dictionary[base_word]['aspekt'][aspekt]['forma'][forma]['liczba'][liczba]['osoba'].keys(): if forma == 'czas przeszły': for rodzaj in dictionary[base_word]['aspekt'][aspekt]['forma'][forma]['liczba'][liczba]['osoba'][osoba]['rodzaj'].keys(): if dictionary[base_word]['aspekt'][aspekt]['forma'][forma]['liczba'][liczba]['osoba'][osoba]['rodzaj'][rodzaj] == word: return [('czasownik', base_word, {'aspekt' : aspekt, 'forma' : forma, 'liczba' : liczba, 'osoba' : osoba, 'rodzaj' : rodzaj})] else: if dictionary[base_word]['aspekt'][aspekt]['forma'][forma]['liczba'][liczba]['osoba'][osoba] == word: return [('czasownik', base_word, {'aspekt' : aspekt, 'forma' : forma, 'liczba' : liczba, 'osoba' : osoba})] raise LookupError("configuration not found") def __get_word(self, conf, base_word): ''' Search all database and get word ''' try: return self.root['rzeczownik']['word'][base_word]['przypadek'][conf['przypadek']]['liczba'][conf['liczba']] except KeyError: try: return self.root['przymiotnik']['word'][base_word]['stopień'][conf['stopień']]['przypadek'][conf['przypadek']]['liczba'][conf['liczba']]['rodzaj'][conf['rodzaj']] except KeyError: try: if conf['forma'] == 'czas teraźniejszy': return self.root['czasownik']['word'][base_word]['aspekt'][conf['aspekt']]['forma'][conf['forma']]['liczba'][conf['liczba']]['osoba'][conf['osoba']] else: return self.root['czasownik']['word'][base_word]['aspekt'][conf['aspekt']]['forma'][conf['forma']]['liczba'][conf['liczba']]['osoba'][conf['osoba']]['rodzaj'][conf['rodzaj']] except KeyError: raise KeyError("There is no such word in Database")
StarcoderdataPython
11321227
<reponame>jgori-ouistiti/CoopIHC import pytest def test_basic_examples(): import coopihc.examples.basic_examples.space_examples import coopihc.examples.basic_examples.stateelement_examples import coopihc.examples.basic_examples.state_examples import coopihc.examples.basic_examples.observation_examples import coopihc.examples.basic_examples.policy_examples import coopihc.examples.basic_examples.agents_examples import coopihc.examples.basic_examples.interactiontask_examples def test_simple_examples(): import coopihc.examples.simple_examples.lqr_example import coopihc.examples.simple_examples.lqg_example import coopihc.examples.simple_examples.assistant_has_user_model import coopihc.examples.simple_examples.rl_sb3 import coopihc.examples.simple_examples.exploit_rlnet @pytest.mark.timeout(3) def test_bundle_examples(): import coopihc.examples.basic_examples.bundle_examples def test_all_examples(): test_basic_examples() test_simple_examples() test_bundle_examples() if __name__ == "__main__": test_all_examples()
StarcoderdataPython
5036215
from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import ObjectDoesNotExist from django.db import transaction from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.urls import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views import generic from rules.contrib.views import PermissionRequiredMixin from ...discord.models import CommunityDiscordLink, DiscordServer, DiscordServerMembership, GamerDiscordLink from ..forms import CommunityDiscordForm from ..models import GamerCommunity class CommunityDiscordLinkView( LoginRequiredMixin, PermissionRequiredMixin, generic.edit.UpdateView ): """ A view designed to allow a user to connect a community to a given discord server. """ model = CommunityDiscordLink slug_url_kwarg = "community" slug_field = "slug" permission_required = "community.edit_community" template_name = "gamer_profiles/community_discord_link.html" context_object_name = "community_discord_link" form_class = CommunityDiscordForm def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: self.community = get_object_or_404(GamerCommunity, slug=kwargs["community"]) if self.community.linked_with_discord: messages.info( request, _("This community is already linked to a discord server.") ) # Find the social app connection. try: self.discord_link = GamerDiscordLink.objects.get( gamer=request.user.gamerprofile ) self.linkable_servers = DiscordServerMembership.objects.filter( gamer_link=self.discord_link, server_role="admin" ) if self.linkable_servers.count() == 0: messages.info( request, _( "No linkable Discord servers have been synced with your account yet. You must be an admin for the Discord server in order to link it to a community on this site." ), ) except ObjectDoesNotExist: messages.info( request, _( "In order to manage Discord links for this community, you must first authenticate with Discord to prove you have the ability to do so." ), ) return HttpResponseRedirect(reverse_lazy("socialaccount_connections")) return super().dispatch(request, *args, **kwargs) def get_object(self): self.community_discord_link, created = CommunityDiscordLink.objects.get_or_create( community=self.community ) return self.community_discord_link def get_permission_object(self): return self.get_object().community def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["community"] = self.community context["discord_gamer_link"] = self.discord_link context["linkable_servers"] = self.linkable_servers return context def get_form_kwargs(self, **kwargs): form_kwargs = super().get_form_kwargs(**kwargs) form_kwargs["linkable_servers_queryset"] = self.linkable_servers return form_kwargs def form_valid(self, form): with transaction.atomic(): immutable_servers = list( self.community_discord_link.servers.exclude( id__in=[s.server.id for s in self.linkable_servers.all()] ) ) temp_obj = form.save(commit=False) new_list = ( list( DiscordServer.objects.filter( id__in=[s.id for s in temp_obj.servers.all()] ) ) + immutable_servers ) if len(new_list) > 0: if not self.community.linked_with_discord: self.community.linked_with_discord = True self.community.save() self.community_discord_link.servers.set(*new_list) else: if self.community.linked_with_discord: self.community.linked_with_discord = False self.community.save() self.community_discord_link.servers.clear() messages.success(self.request, _("Changes have been successfully saved!")) return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return self.community.get_absolute_url()
StarcoderdataPython
11343104
class Solution: def minWindow(self, s: str, t: str) -> str: d = collections.Counter(t) l0,r0,l,cnt = 0,-1,0,len(t) for r,c in enumerate(s): if c in d: cnt -= d[c]>0 d[c] -= 1 while not cnt: if r0 < 0 or r-l <r0-l0: r0,l0 = r,l if s[l] in d: d[s[l]] += 1 cnt += d[s[l]]>0 l += 1 return s[l0:r0+1]
StarcoderdataPython
6481930
from rest_framework.serializers import SerializerMetaclass from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,permissions from rest_framework.parsers import FileUploadParser from .cosmosdb import CosmosDB from .blobdb import BlobDB collection = 'models' class RegModel(APIView): # auth_class = [authentication.TokenAuthentication] # permission_class = [permissions.IsAuthenticated] def get(self,**kwargs): pass def post(self,request): data = request.data id = data['id'] cdb = CosmosDB(collection) cdb.insert(data) return Response(f"{cdb.find_by_id(id)}") class GetModel(APIView): def get(self,**kwargs): pass def post(self,request): data = request.data id = data['id'] cdb = CosmosDB(collection) result = cdb.find_by_id(id) return Response(f"{result}") class SaveModelFile(APIView): # parser_classes = [FileUploadParser] def post(self,request): file = request.data['file'] filename = file.name blobDB = BlobDB('containertest') re = blobDB.create(id='testtest.rar',file=file) print(re) print(re.items()) return Response(f'{filename}upload completed\n{re.items()}')
StarcoderdataPython
9788734
#!/usr/bin/env python # encoding: utf-8 # Copyright (c) 2016, <NAME> (www.karlsruhe.de) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import io import os.path import re import sys from setuptools import find_packages, setup HERE = os.path.dirname(__file__) SOURCE_FILE = os.path.join(HERE, 'svg2imgmap', '__init__.py') REQUIREMENTS_FILE = os.path.join(HERE, 'requirements.txt') version = None with io.open(SOURCE_FILE, encoding='utf8') as f: for line in f: s = line.strip() m = re.match(r"""__version__\s*=\s*['"](.*)['"]""", line) if m: version = m.groups()[0] break if not version: raise RuntimeError('Could not extract version from "%s".' % SOURCE_FILE) with io.open(REQUIREMENTS_FILE, encoding='utf8') as f: requirements = f.readlines() long_description = """ A small command line utility to generate source code for HTML image maps from SVG images. """.strip() setup( name='svg2imgmap', description='Generate HTML image maps from SVG images', long_description=long_description, url='https://github.com/stadt-karlsruhe/svg2imgmap', version=version, license='MIT', keywords=['svg', 'html', 'image map'], classifiers=[ # Reference: http://pypi.python.org/pypi?%3Aaction=list_classifiers "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Environment :: Console", "Topic :: Multimedia :: Graphics", "Topic :: Text Processing :: Markup :: HTML", ], author='<NAME>', author_email='<EMAIL>', packages=find_packages(), install_requires=requirements, entry_points={ 'console_scripts': [ 'svg2imgmap = svg2imgmap.__main__:main', ], }, )
StarcoderdataPython
9713555
<gh_stars>1-10 import sys import time import numpy as np import matplotlib.pyplot as plt from multiprocessing import Pool # if len(sys.argv) < 3: # print('ERROR Args number. Needed: \n[1]In Path(with file.npy) -- prepros file \n[2]Out Path(with .json)') # sys.exit() # # # in_path = str(sys.argv[1]) # out_path = str(sys.argv[2]) in_path = '/Users/Juan/django_projects/adaptive-boxes/data_binary/squares.binary' out_path = '' data_matrix = np.loadtxt(in_path, delimiter=",") data_matrix[:,0] = 1 # Plot fig = plt.figure(figsize=(6, 3.2)) ax = fig.add_subplot(111) plt.imshow(data_matrix) ax.set_aspect('equal') # Flatten Matrix data_matrix_f = data_matrix.flatten() # Kernel Data dim3_block_x = data_matrix.shape[1] dim3_block_y = data_matrix.shape[0] block_dim_y = dim3_block_y block_dim_x = dim3_block_x # KERNEL # Kernel non-editable - they go in for-loop block_idx_x = 0 block_idx_y = 0 thread_idx_x = 0 thread_idx_y = 0 # Kernel editable # Params distances = np.zeros(shape=[data_matrix_f.shape[0]]) # Could be stored in Cache- Shared Memory idx_i = 7 # y rand point idx_j = 13 # x rand point plt.scatter(idx_j, idx_i, c='r') m = data_matrix.shape[0] n = data_matrix.shape[1] # br ---- for i in range(idx_i, m): temp_value = data_matrix_f[i * n + idx_j] if temp_value == 0: i = i - 1 break else: plt.scatter(idx_j, i, c='g', marker='x') d0 = i for j in range(idx_j + 1, n): for i in range(idx_i, d0 + 1): # print(str(j) + ' ' + str(i)) temp_value = data_matrix_f[i * n + j] if temp_value == 0: i = i - 1 break else: plt.scatter(j, i, c='b', marker='x') if i < d0: j = j - 1 break # bl ---- for i in range(idx_i, m): temp_value = data_matrix_f[i * n + idx_j] if temp_value == 0: i = i - 1 break else: plt.scatter(idx_j, i, c='g', marker='x') d0 = i for j in range(idx_j - 1, -1, -1): for i in range(idx_i, d0 + 1): # print(str(j) + ' ' + str(i)) temp_value = data_matrix_f[i * n + j] if temp_value == 0: i = i - 1 break else: plt.scatter(j, i, c='b', marker='x') if i < d0: j = j + 1 break # tl ---- for i in range(idx_i, -1, -1): temp_value = data_matrix_f[i * n + idx_j] if temp_value == 0: i = i + 1 break else: plt.scatter(idx_j, i, c='g', marker='x') d0 = i for j in range(idx_j - 1, -1, -1): for i in range(idx_i, d0 - 1, -1): # print(str(j) + ' ' + str(i)) temp_value = data_matrix_f[i * n + j] if temp_value == 0: i = i + 1 break else: plt.scatter(j, i, c='b', marker='x') if i > d0: j = j + 1 break # tr ---- for i in range(idx_i, -1, -1): temp_value = data_matrix_f[i * n + idx_j] if temp_value == 0: i = i + 1 break else: plt.scatter(idx_j, i, c='g', marker='x') d0 = i for j in range(idx_j + 1, n): for i in range(idx_i, d0 -1, - 1): # print(str(j) + ' ' + str(i)) temp_value = data_matrix_f[i * n + j] if temp_value == 0: i = i + 1 break else: plt.scatter(j, i, c='b', marker='x') if i > d0: j = j - 1 break # plt.scatter(j, idx_i_arg, c='g', marker='x') # plt.scatter(j, idx_i_arg + first_step_i - 1, c='g', marker='x') # Run Kernel for thread_idx_y in range(block_dim_y): for thread_idx_x in range(block_dim_x): # print('running threadId.x: ' + str(thread_idx_x) + ' threadId.y: ' + str(thread_idx_y)) i = thread_idx_y j = thread_idx_x g_i = block_dim_y * block_idx_y + i g_j = block_dim_x * block_idx_x + j m = block_dim_y n = block_dim_x plt.scatter(j, i, c='b', marker='x') val_in_b = data_matrix_f[n * i + j] val_in_a = data_matrix_f[n * i + idx_j] distance_j = (j - idx_j) * val_in_b * val_in_a distance_i = (i - idx_i) * val_in_b * val_in_a print('i: ' + str(i) + ' j: ' + str(j) + ' distance ' + str(distance_j)) # if distance_j > 0: distances[i * n + j] = distance_j # distances[i * n + j] = distance_j # if j == idx_j: # distances[i * n + j] = distance_j + distance_i print(distances.reshape([m, n])) distances_matrix = distances.reshape([m, n]) # Break # Get min distance in left - Atomic can be used(In this case: min() function) distances_matrix = distances.reshape([m, n]) idx_d = 1 distances_matrix[idx_d, :].max() distances_matrix[idx_d, :].min() for thread_idx_y in range(block_dim_y): for thread_idx_x in range(block_dim_x): # print('running threadId.x: ' + str(thread_idx_x) + ' threadId.y: ' + str(thread_idx_y)) i = thread_idx_y j = thread_idx_x g_i = block_dim_y * block_idx_y + i g_j = block_dim_x * block_idx_x + j m = block_dim_y n = block_dim_x if (j == 0): distances[i * n + 0: i * n + m] def get_right_bottom_rectangle(idx_i_arg, idx_j_arg): step_j = 0 first_step_i = 0 while True: i = idx_i_arg j = idx_j_arg + step_j if j == n: break temp_val = data_matrix[i, j] if temp_val == 0: break step_i = 0 while True: i = idx_i_arg + step_i if i == m: break # print(i) temp_val = data_matrix[i, j] # print(temp_val) # plt.scatter(j, i, c='g', marker='x') if temp_val == 0: break step_i += 1 if step_j == 0: first_step_i = step_i else: if step_i < first_step_i: break plt.scatter(j, idx_i_arg, c='g', marker='x') plt.scatter(j, idx_i_arg + first_step_i - 1, c='g', marker='x') x1_val = idx_j_arg y1_val = idx_i_arg x2_val = idx_j_arg + step_j - 1 y2_val = idx_i_arg + first_step_i - 1 return x1_val, x2_val, y1_val, y2_val def get_left_bottom_rectangle(idx_i_arg, idx_j_arg): step_j = 0 first_step_i = 0 while True: i = idx_i_arg j = idx_j_arg - step_j if j == -1: break temp_val = data_matrix[i, j] if temp_val == 0: break step_i = 0 while True: i = idx_i_arg + step_i if i == m: break # print(i) temp_val = data_matrix[i, j] # print(temp_val) # plt.scatter(j, i, c='g', marker='x') if temp_val == 0: break step_i += 1 if step_j == 0: first_step_i = step_i else: if step_i < first_step_i: break plt.scatter(j, idx_i_arg, c='g', marker='x') plt.scatter(j, idx_i_arg + first_step_i - 1, c='b', marker='x') step_j += 1 x1_val = idx_j_arg y1_val = idx_i_arg x2_val = idx_j_arg - step_j + 1 y2_val = idx_i_arg + first_step_i - 1 return x1_val, x2_val, y1_val, y2_val def get_left_top_rectangle(idx_i_arg, idx_j_arg): step_j = 0 first_step_i = 0 while True: i = idx_i_arg j = idx_j_arg - step_j if j == -1: break temp_val = data_matrix[i, j] if temp_val == 0: break step_i = 0 while True: i = idx_i_arg - step_i if i == -1: break # print(i) temp_val = data_matrix[i, j] # print(temp_val) # plt.scatter(j, i, c='g', marker='x') if temp_val == 0: break step_i += 1 if step_j == 0: first_step_i = step_i else: if step_i < first_step_i: break plt.scatter(j, idx_i_arg, c='g', marker='x') plt.scatter(j, idx_i_arg - first_step_i + 1, c='b', marker='x') step_j += 1 x1_val = idx_j_arg y1_val = idx_i_arg x2_val = idx_j_arg - step_j + 1 y2_val = idx_i_arg - first_step_i + 1 return x1_val, x2_val, y1_val, y2_val def get_right_top_rectangle(idx_i_arg, idx_j_arg): step_j = 0 first_step_i = 0 while True: i = idx_i_arg j = idx_j_arg + step_j if j == n: break temp_val = data_matrix[i, j] if temp_val == 0: break step_i = 0 while True: i = idx_i_arg - step_i if i == -1: break # print(i) temp_val = data_matrix[i, j] # print(temp_val) # plt.scatter(j, i, c='g', marker='x') if temp_val == 0: break step_i += 1 if step_j == 0: first_step_i = step_i else: if step_i < first_step_i: break plt.scatter(j, idx_i_arg, c='g', marker='x') plt.scatter(j, idx_i_arg - first_step_i + 1, c='g', marker='x') step_j += 1 x1_val = idx_j_arg y1_val = idx_i_arg x2_val = idx_j_arg + step_j - 1 y2_val = idx_i_arg - first_step_i + 1 return x1_val, x2_val, y1_val, y2_val # Plot fig = plt.figure(figsize=(6, 3.2)) ax = fig.add_subplot(111) plt.imshow(data_matrix) ax.set_aspect('equal') m = data_matrix.shape[0] # for i n = data_matrix.shape[1] # for j for i_n in range(m): for j_n in range(n): if data_matrix[i_n, j_n] == 1: plt.scatter(j_n, i_n, c='w', marker='.') idx_i = 10 # y rand point idx_j = 1 # x rand point plt.scatter(idx_j, idx_i, c='r') coords = np.zeros(shape=[4, 4]) # 4 threads: [right-bottom right_top , left-bt, left-tp], 4 coords: [x1 x2 y1 y2] x1, x2, y1, y2 = get_right_bottom_rectangle(idx_i, idx_j) coords[0, :] = np.array([x1, x2, y1, y2]) p1 = np.array([x1, y1]) p2 = np.array([x1, y2]) p3 = np.array([x2, y1]) p4 = np.array([x2, y2]) ps = np.array([p1, p2, p4, p3, p1]) plt.plot(ps[:, 0], ps[:, 1], c='w') x1, x2, y1, y2 = get_right_top_rectangle(idx_i, idx_j) coords[1, :] = np.array([x1, x2, y1, y2]) p1 = np.array([x1, y1]) p2 = np.array([x1, y2]) p3 = np.array([x2, y1]) p4 = np.array([x2, y2]) ps = np.array([p1, p2, p4, p3, p1]) plt.plot(ps[:, 0], ps[:, 1], c='w') x1, x2, y1, y2 = get_left_bottom_rectangle(idx_i, idx_j) coords[2, :] = np.array([x1, x2, y1, y2]) p1 = np.array([x1, y1]) p2 = np.array([x1, y2]) p3 = np.array([x2, y1]) p4 = np.array([x2, y2]) ps = np.array([p1, p2, p4, p3, p1]) plt.plot(ps[:, 0], ps[:, 1], c='w') x1, x2, y1, y2 = get_left_top_rectangle(idx_i, idx_j) coords[3, :] = np.array([x1, x2, y1, y2]) p1 = np.array([x1, y1]) p2 = np.array([x1, y2]) p3 = np.array([x2, y1]) p4 = np.array([x2, y2]) ps = np.array([p1, p2, p4, p3, p1]) plt.plot(ps[:, 0], ps[:, 1], c='w') # coords[] pr = coords[[0, 1], 1].min() pl = coords[[2, 3], 1].max() pb = coords[[0, 2], 3].min() pt = coords[[1, 3], 3].max() # final x1x2 and y1y2 x1 = pl x2 = pr y1 = pt y2 = pb plt.scatter(x1, y1, c='r') plt.scatter(x2, y2, c='b') p1 = np.array([x1, y1]) p2 = np.array([x1, y2]) p3 = np.array([x2, y1]) p4 = np.array([x2, y2]) ps = np.array([p1, p2, p4, p3, p1]) plt.plot(ps[:, 0], ps[:, 1], c='r') data_matrix[y1:y2 + 1, x1:x2 + 1] = 0
StarcoderdataPython
1779423
<filename>dynamics.py import numpy as np from matplotlib import pyplot as plt class Enum(object): def __init__(self, _list): self._list = _list def __getitem__(self, key): if key in self._list: return self._list.index(key) else: raise(KeyError("{} not in enum".format(key))) def __getattr__(self, key): return self[key] state_names = [ 'posx', 'posy', 'velx', 'vely', ] control_names = [ 'forcex', 'forcey', ] States = Enum(state_names) Controls = Enum(control_names) real_m = 0.9 def dynamics(x, u, dt=0.1): m = real_m x_new = np.zeros(4) dt2 = 0.5 * dt * dt x_new[States.posx] = x[States.posx] + (x[States.velx] * dt) + (u[Controls.forcex] * dt2 / m) x_new[States.posy] = x[States.posy] + (x[States.vely] * dt) + (u[Controls.forcey] * dt2 / m) x_new[States.velx] = x[States.velx] + (u[Controls.forcex] * dt / m) x_new[States.vely] = x[States.vely] + (u[Controls.forcey] * dt / m) return x_new if __name__ == '__main__': sim_x = np.array([1.0, 2.0, 3.0, 4.0]) sim_u = np.array([0.0, 0.9]) xl = [] for k in range(20): sim_x = dynamics(sim_x, sim_u) xl.append(sim_x) xl = np.array(xl) # plt.plot(xl[:, 0], xl[:, 1]) # plt.show()
StarcoderdataPython
6447370
<filename>napari/components/tests/test_multichannel.py import numpy as np from napari.components import ViewerModel base_colormaps = ['cyan', 'yellow', 'magenta', 'red', 'green', 'blue'] def test_multichannel(): """Test adding multichannel image.""" viewer = ViewerModel() np.random.seed(0) data = np.random.random((15, 10, 5)) viewer.add_multichannel(data) assert len(viewer.layers) == data.shape[-1] for i in range(data.shape[-1]): assert np.all(viewer.layers[i].data == data.take(i, axis=-1)) assert viewer.layers[i].colormap[0] == base_colormaps[i] def test_specified_multichannel(): """Test adding multichannel image with color channel set.""" viewer = ViewerModel() np.random.seed(0) data = np.random.random((5, 10, 15)) viewer.add_multichannel(data, axis=0) assert len(viewer.layers) == data.shape[0] for i in range(data.shape[0]): assert np.all(viewer.layers[i].data == data.take(i, axis=0)) def test_names(): """Test adding multichannel image with custom names.""" viewer = ViewerModel() np.random.seed(0) data = np.random.random((15, 10, 5)) names = ['multi ' + str(i + 3) for i in range(data.shape[-1])] viewer.add_multichannel(data, name=names) assert len(viewer.layers) == data.shape[-1] for i in range(data.shape[-1]): assert viewer.layers[i].name == names[i] viewer = ViewerModel() name = 'example' names = [name] + [name + f' [{i + 1}]' for i in range(data.shape[-1] - 1)] viewer.add_multichannel(data, name=name) assert len(viewer.layers) == data.shape[-1] for i in range(data.shape[-1]): assert viewer.layers[i].name == names[i] def test_colormaps(): """Test adding multichannel image with custom colormaps.""" viewer = ViewerModel() np.random.seed(0) data = np.random.random((15, 10, 5)) colormap = 'gray' viewer.add_multichannel(data, colormap=colormap) assert len(viewer.layers) == data.shape[-1] for i in range(data.shape[-1]): assert viewer.layers[i].colormap[0] == colormap viewer = ViewerModel() colormaps = ['gray', 'blue', 'red', 'green', 'yellow'] viewer.add_multichannel(data, colormap=colormaps) assert len(viewer.layers) == data.shape[-1] for i in range(data.shape[-1]): assert viewer.layers[i].colormap[0] == colormaps[i] def test_contrast_limits(): """Test adding multichannel image with custom contrast limits.""" viewer = ViewerModel() np.random.seed(0) data = np.random.random((15, 10, 5)) clims = [0.3, 0.7] viewer.add_multichannel(data, contrast_limits=clims) assert len(viewer.layers) == data.shape[-1] for i in range(data.shape[-1]): assert viewer.layers[i].contrast_limits == clims viewer = ViewerModel() clims = [[0.3, 0.7], [0.1, 0.9], [0.3, 0.9], [0.4, 0.9], [0.2, 0.9]] viewer.add_multichannel(data, contrast_limits=clims) assert len(viewer.layers) == data.shape[-1] for i in range(data.shape[-1]): assert viewer.layers[i].contrast_limits == clims[i] def test_gamma(): """Test adding multichannel image with custom gamma.""" viewer = ViewerModel() np.random.seed(0) data = np.random.random((15, 10, 5)) gamma = 0.7 viewer.add_multichannel(data, gamma=gamma) assert len(viewer.layers) == data.shape[-1] for i in range(data.shape[-1]): assert viewer.layers[i].gamma == gamma viewer = ViewerModel() gammas = [0.3, 0.4, 0.5, 0.6, 0.7] viewer.add_multichannel(data, gamma=gammas) assert len(viewer.layers) == data.shape[-1] for i in range(data.shape[-1]): assert viewer.layers[i].gamma == gammas[i]
StarcoderdataPython