dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def setWaveformSource(self, channel:RigolWaveformSources):
if self.checkValidChannel(RigolWaveformSources.getChannelNumber(channel)):
return self.writeCmd(f":WAVeform:SOURce {channel.value}")
def getWaveformSource(self):
data = self.readCmd(":WAVeform:SOURce?")
wavSource = RigolWavef... | This function configures a waveform source, mode, and format on a device, verifies the settings were applied successfully, and retrieves the waveform data. It raises exceptions if any configuration step fails, ensuring correct setup before returning the acquired waveform data. | def getWaveformFromChannel(self, channel:RigolWaveformSources,
mode:RigolWaveformModes,
format:RigolWaveformFormats):
self.setWaveformSource(channel)
if channel != self.getWaveformSource():
raise RuntimeError("Waveform source no... |
def http_get(self,uri):
print("trying to get data from", self.address)
try:
r = requests.get("http://"+str(self.address)+"/"+uri,timeout=3)
self.reachable=True
except:
self.reachable=False
if self.reachable:
if r.status_code==200:
... | This code manages a charging system's state transitions, including initialization, vehicle detection, phase switching, current adjustment, and charging state handling based on power levels, configurations, and hardware capabilities. It ensures proper charger operation by adapting to detected phases, applying correction... | def statemachine(self):
if self.plug_state==Plug_states.INITIALIZE_CHARGER:
self.reachable=False
# older chargers tend to measure a too low volate
# as power is measured voltage*current, power needs same correction
self.correction_factor=1.05
self.cap... |
def http_get(self,uri):
print("trying to get data from", self.address)
try:
r = requests.get("http://"+str(self.address)+"/"+uri,timeout=3)
self.reachable=True
except:
self.reachable=False
if self.reachable:
if r.status_code==200:
... | The code's main task is to periodically trigger an update by checking the elapsed time, fetch device status data via HTTP, update internal state variables, process the received data, and advance a state machine. It also logs the object's name and state. | def update(self):
if self.nexttick<time.time():
self.nextinterval()
# if self.plug_state!=Plug_states.INITIALIZE_CHARGER:
data=self.http_get("status")
if not data is None:
self.data=data
self.read_data()
self.statemac... |
def is_dirty(self) -> bool:
"""
Check If Current Tile Is Clean or Not
:return: True | False
"""
if self.get_position_val() is 1:
return True
else:
return False
def clean(self) -> str:
"""
Clean Dirty Tiles By Just Setting Dirty Tile Value To 0
Increment Tiles Cleaned
Call calculate_distance
... | The code determines the vacuum's action: if the current tile is dirty, it cleans it; otherwise, it moves horizontally or vertically. | def action(self) -> str:
"""
:return: Returns An Action Done By The Vacuum
"""
if self.is_dirty(): # Check For Dirtiness
return self.clean() # Clean The Tile
else:
return self.move_horizontal_and_vertical() |
def show_pos(self, where) -> None:
"""
:param where: name of method that called this method, its for debuggin purposes
:return: None
"""
print("{} :=> (x = {}, y = {})".format(where, self.N_POS_X, self.N_POS_Y))
def is_dirty(self) -> bool:
"""
Check If Current Tile Is Clean or Not
:return: True | Fals... | The main task of the code is to systematically clean a grid-based room by iterating through each cell in a nested loop, checking for dirt, cleaning dirty tiles, and updating the environment. It records start/end times, tracks coordinates, and applies horizontal/vertical movement logic to navigate the grid, ensuring the... | def move(self, env: Environment) -> None:
"""
:param env: The Environment the Vacuum Will be Working in
:return: None
"""
self.ROOM_GRID = env.get_room() # Set Room To This Class Level Var
"""
Since This Is An N*M Matrix, we implement a nested for loop
to traverse trough all indexes.
Also he... |
def get_new_archive_dir(self, cbm_nr = 0):
return os.path.join(self.get_cbm_archive_path(), self.get_cbm_dir(cbm_nr))
def get_new_import_dir(self, cbm_nr = 0):
return os.path.join(self.get_cbm_import_path(), self.get_cbm_dir(cbm_nr))
def set_dir_to_777(self, dir):
mode = 0o777
os.chmod(d... | This function copies files from an archive directory to an import directory, sets permissions, and performs cleanup by retaining files matching a specific pattern while removing others based on predefined deletion patterns. | def copy_to_import(self, cbm_nr = 0):
source = self.get_new_archive_dir(cbm_nr)
destination = self.get_new_import_dir(cbm_nr)
shutil.copytree(source, destination)
self.set_dir_to_777(destination)
self.walk_directory_and_cleanup(destination, self.get_cbm_pattern(cbm_nr), keep = Tr... |
def testfile_exists(self):
return os.path.exists(self.get_test_filename())
def get_cdrom_path(self):
return self.config_data["PATH"]["CDROM"]
def get_new_archive_dir(self, cbm_nr = 0):
return os.path.join(self.get_cbm_archive_path(), self.get_cbm_dir(cbm_nr))
def set_dir_to_777(self, dir):
... | The main task of the code is to copy a CD-ROM directory to a new archive location, set permissions, remove files matching specified patterns, and initiate an import process. It checks for a test file's existence, copies the source directory, adjusts permissions, cleans up designated files, and triggers the import funct... | def copy_cbm(self):
if self.testfile_exists():
source = self.get_cdrom_path()
destination = self.get_new_archive_dir()
shutil.copytree(source, destination)
self.set_dir_to_777(destination)
for pattern in self.config_data["DEL_PATTERN"]["ARCHIVE"]:
... |
def rbf_kernel(X_p,X_q):
X_p = np.reshape(X_p,(-1,1))
X_q = np.reshape(X_q, (-1, 1))
K = -2 * np.matmul(X_p,X_q.T)
K += X_p * X_p
K += X_q.T * X_q.T
K = K * (-1/2)
K = np.exp(K)
return K
def matern_kernel(X_p,X_q):
X_p = np.reshape(X_p, (-1, 1))
X_q = np.reshape(X_q, (-1, 1))
... | The code implements the Gaussian Process Upper Confidence Bound (GP-UCB) algorithm for multi-armed bandit problems. It samples a function from a kernel-based prior (RBF, Matern, or linear), iteratively selects actions using UCB values, updates Bayesian posteriors, and evaluates cumulative regret against theoretical bou... | def GP_UCB(D, sigma,T,delta,k):
# Range of X
x = np.linspace(0,5,D)
# Sample f from RBF prior
X_star = np.reshape(x,(-1,1))
mu_p = np.zeros(X_star.shape[0])
if(k == 1):
sigma_p = rbf_kernel(X_star,X_star)
elif(k == 2):
sigma_p = matern_kernel(X_star, X_star)
else:
... |
def greeting(intent_request):
return {
'sessionState': {
'dialogAction': {
'type': 'ElicitIntent'
}
},
"messages": [
{
"contentType": "PlainText",
"content": "Hi, How can I help you??",
}
],
}
def tha... | The code defines a `dispatch` function that routes incoming intent requests to corresponding handler functions based on the intent name. It checks the intent type (e.g., 'GreetingIntent', 'ThankYouIntent', 'DiningSuggestionsIntent') and invokes the matching function. If the intent is unsupported, it raises an exception... | def dispatch(intent_request):
intent_name = intent_request['sessionState']['intent']['name']
if intent_name == 'GreetingIntent':
return greeting(intent_request)
elif intent_name == 'ThankYouIntent':
return thankyou(intent_request)
elif intent_name == 'DiningSuggestionsIntent':
... |
def check_for_existing_output(self):
return os.path.isfile(self.processed_data_loc)
def log_skip_message(self):
print("Output file already exists. Skipping wl:" + str(self.window_length) + " sl_pair: " +
str(self.target_pips) + "_" + str(self.stop_pips))
def log_pre_processing_message(self... | The main task of the code is to build target data by processing tick data. It checks for existing output, logs pre-processing, initializes TickFeed and TickWindow abstractions, iterates through tick data to populate the window, saves the processed outcome, and logs post-processing. The function orchestrates data flow f... | def build_targets(self):
if self.check_for_existing_output():
self.log_skip_message()
else:
self.log_pre_processing_message()
# abstraction of tick feed with its own class
tick_feed = TickFeed(self)
# abstraction of tick window with its own cla... |
def printmenu():
print(rand[0].capitalize())
print(recr[0].capitalize())
print(togg[0].capitalize())
print(leav[0].capitalize())
print()
def queryInput():
return input('> ')
def execute(roster, userinput):
(command, args) = (userinput + ' ').split(' ', 1)
command = command.lower()
ar... | The code defines a function `start` that initializes a menu-driven interface for interacting with a `roster` data structure. It continuously displays a menu, captures user input, and executes corresponding actions using the `execute` function, looping until terminated. The main task is to manage user interactions for p... | def start(roster):
print('Welcome to the deck of many heroes!')
print()
while(True):
printmenu()
userinput = queryInput()
execute(roster, userinput) |
def __jsonpath():
return fileroot + '\\' + filename + '.json'
def parsejson(path):
file = open(path, 'r')
roster = []
for obj in json.load(file):
hero = Hero(obj['name'], obj['enabled'], obj['combatant'], obj['recruited'])
roster.append(hero)
# print(hero)
return ro... | The main task of the code is to retrieve and parse roster data from a file (either JSON or text) based on the provided path. It sets a global file root, checks for the existence of a JSON file first, then a text file, parses and returns the data if found, or exits with an error if neither file exists. | def get(path):
global fileroot
fileroot = path
if os.path.isfile(__jsonpath()):
return parsejson(__jsonpath())
elif os.path.isfile(__txtpath()):
return parsetxt(__txtpath())
else:
sys.exit("Roster data not found") |
def _check_fleet_edges(self):
"""react if alien get edge of screen"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
"""react to touch this ship"""
if self.stats.ships_left > 0:
#to reduce ships
self.stats.ships_left -= 1
... | This method updates alien positions, checks if the alien fleet is at screen edges, detects collisions between bullets/aliens, triggers ship hit response if collided, and checks if aliens have reached the bottom of the screen to handle game-ending conditions. | def _update_aliens(self):
"""check if fleet on the edge then update all aliens"""
self._check_fleet_edges()
self.aliens.update()
#find colision bullet and aliens
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom() |
def _check_keydown_events(self,event):
"""React the key is press"""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
self.sb.save_high_score()
sys.exit()
elif event.key == pygame.K_SPACE:
se... | The main task of the code is to handle user input events in a Pygame application by checking for keyboard presses, releases, mouse clicks, and quit signals. It triggers game exit, saves high scores, and delegates key/mouse actions to specialized methods for gameplay control and interaction. | def _check_events(self):
#to follow for the mouse and the keyboard
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.sb.save_high_score()
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_even... |
def _check_events(self):
#to follow for the mouse and the keyboard
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.sb.save_high_score()
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_even... | The code runs the game loop, continuously checking for events, updating game elements (ship, bullets, aliens) if the game is active, and rendering the screen to create an interactive gameplay experience. | def run_game(self):
"""Start new cycle of the game"""
while True:
self._check_events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
#Show the last displayed screen
self._update_screen() |
def succ(self, state, piece):
l = list()
drop_phase = True
c = 0
for i in state:
for j in i:
if j != " ":
c += 1
if c == 8:
drop_phase = False
if not drop_phase:
for i in range(5):
for... | The main task of the code is to implement a minimax algorithm with heuristic evaluation for a Teeko game AI. It selects the optimal move by evaluating all possible successor states, prioritizing immediate wins (heuristic value of 1), and using minimax for deeper analysis. The function returns a move tuple (or relocatio... | def make_move(self, state):
# self.printb(state)
# print(self.heuristic_game_value(state))
# TeekoPlayer.printb(self, TeekoPlayer.succ(self, state))
""" Selects a (row, col) space for the next move. You may assume that whenever
this function is called, it is this player's turn to... |
def succ(self, state, piece):
self.game_value(state)
succ = []
drop_phase = True
count = 0
for i in range(len(state)):
for j in range(len(state)):
if state[i][j] != ' ':
count += 1
if count == 8:
drop_phase = F... | The code implements a minimax algorithm for a Teeko AI to select the optimal move. It evaluates successor states using a heuristic, prioritizing moves with immediate wins (heuristic value 1). If none are found, it recursively explores deeper states to minimize the opponent's best outcome, updating the best move based o... | def make_move(self, state):
""" Selects a (row, col) space for the next move. You may assume that whenever
this function is called, it is this player's turn to move.
Args:
state (list of lists): should be the current state of the game as saved in
this TeekoPlayer obj... |
def _find_new_resolution(TR,res):
n = TR*1000.
# find divisors of TR*1000
large_divisors = []
for i in range(1, int(math.sqrt(n) + 1)):
if n % i == 0:
large_divisors.append(i)
if i*i != n:
large_divisors.append(int(n / i))
sorted = np.sort(large_diviso... | This code initializes a class to model experimental stimuli with parameters like TR (time resolution), stimulus duration, constraints on feature magnitudes (FeMax, FdMax, etc.), and ITI (inter-trial interval) configurations. It adjusts resolution compatibility with TR, sets up stimulus components, and prepares model st... | def __init__(self, TR, P, C, rho, stim_duration, n_stimuli, ITImodel=None, ITImin=None, ITImax=None, ITImean=None, restnum=0, restdur=0, t_pre=0, t_post=0, n_trials=None, duration=None, resolution=0.1, FeMax=1, FdMax=1, FcMax=1, FfMax=1, maxrep=None, hardprob=False, confoundorder=3):
self.TR = TR
self.P... |
def _clean_designs(self,weights,seed):
n = 0
rm = 0
while n == 0:
orders = [x.order for x in self.designs]
cors = np.corrcoef(orders)
isone = np.isclose(cors, 1.)
if len(isone) == 1:
n = 1
else:
np.fill_d... | This function advances to the next generation in an evolutionary algorithm by either performing genetic operations (mutation, crossover) for 'GA' optimization or immigration for 'simulation' optimization. It updates the population with new designs, tracks the best solution, checks for convergence, and retains top-perfo... | def to_next_generation(self, weights=None, seed=1234,optimisation=None):
'''
This function goes from one generation to the next.
:param weights: weights for efficiency calculation.
:type weights: list of floats, summing to 1
:param seed: The seed for random processes.
:t... |
def clear(self):
'''
Function to clear results between optimalisations (maximum Fe, Fd or opt)
'''
self.designs = []
self.optima = []
self.finished = False
self.change_seed()
if self.bestdesign:
bestdes = design(order=self.bestdesign.order,
... | This function performs design optimization using genetic algorithms (GA), handling multiple objectives (efficiency, durability, etc.) by iterating through generations. It clears prior data, initializes new designs with specified weights, and evolves them over cycles to maximize performance metrics. Progress bars track ... | def optimise(self,optimisation='GA'):
'''
Function to run design optimization
'''
if (self.exp.FcMax == 1 and self.exp.FfMax == 1):
self.exp.max_eff()
if self.exp.FeMax == 1 and self.weights[0] > 0:
# add new designs
self.clear()
... |
def get_y_true_and_score_from_frame(model, frame):
score = get_score_from_model_and_frame(model, frame)
y_true = get_y_true_from_frame(frame)
return np.array(y_true), np.array(score)
def get_accuracy_curves(y_true, y_prob):
"""
Calculate accuracy curves. Used for making ROC curve.
:param y_true:... | The code calculates the Gini coefficient using fallout and recall metrics derived from model predictions on a given frame. It extracts true labels and scores, computes accuracy curves, then calculates Gini from these curves. The function returns the fallout and recall values for further analysis. | def get_fallout_recall(model, frame):
y_true, score = get_y_true_and_score_from_frame(model, frame)
accuracy_curves = get_accuracy_curves(y_true, score)
gini = calculate_gini(accuracy_curves['fallout'],
accuracy_curves['recall'])
print('Calculated Gini is: %s' % gini)
retur... |
def _checkJson(json_db):
subimages = json_db.get('subimages')
if subimages is None:
_error('Error in spriteforhtml.create.create_sprites: property "subimages" is missing')
requiredKeys = [ 'filename']
for subimage in subimages:
for key in requiredKeys:
if subimage.get(key) is None:
_error... | The main task of the code is to generate a sprite image and corresponding CSS from a JSON configuration. It processes subimage data, arranges them into a combined sprite image, calculates positions, creates CSS styles with background positioning, and saves both the sprite and CSS files. The function handles layout vali... | def create_from_memory(json_db, rootDir='.'):
"""
Create sprites from a json object
See full description at top of this file
"""
_checkJson(json_db)
_openSubimages(json_db, rootDir)
error, msg = checkOverlapping(json_db['subimages'])
if error:
_error(msg)
sortSubimages(json_db)
_setCssSelector... |
def events(self):
# catch all events here
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
self.quit()
if event.key == pg.K_h:
... | This code defines a game loop that runs while `self.playing` is True, handling events, updating game state, and rendering graphics. It manages audio playback, pauses, and frame rate control using Pygame. The loop processes input, updates game logic (if not paused), and redraws the screen at a fixed FPS. | def run(self):
# game loop - set self.playing = False to end the game
self.playing = True
pg.mixer.music.play(-1, 0.0)
while self.playing:
self.dt = self.clock.tick(FPS) / 1000.0 # fix for Python 2.x
self.events()
if self.mute_audio:
... |
def toggle_menu(self):
if not self.can_toggle: return
self.game_paused = not self.game_paused
self.can_toggle = False
self.selection_time = pygame.time.get_ticks()
def toggle_menu_cooldown(self):
if self.can_toggle: return
current_time = pygame.time.get_ticks()
if... | This code manages a game loop by rendering sprites, handling user input, updating game states, and managing level progression. It checks for menu toggling, updates visible elements, processes enemy spawning, and transitions between paused/game states. Debug info and UI display are included, along with logic for ending ... | def run(self):
if not self.game_play_lock:
self.game_play_lock = True
self.toggle_in_game()
#self.visible_sprites.draw()
self.map_sprites.custom_draw(self.player)
#self.sprite_group.draw(self.display_surface)
self.structure_sprites.custom_draw(sel... |
def isFree(self,x,y):
return self._board[y][x] == '.'
def getColor(self,x,y):
if self._board[y][x] == '.':
return self.NOCOLOR
elif self._board[y][x].isupper():
return self.WHITE
elif self._board[y][x].islower():
return self.BLACK
def checkKingGuard(se... | This code generates valid moves for a pawn from a given position, including regular forward moves, double initial moves, captures, and en passant (EP) moves. It checks board state, piece color, and special conditions like EP targets, then filters moves using a king-guard check. Returns a list of moves and special move ... | def getValidPawnMoves(self,fromPos):
moves = []
specialMoves = {}
fx,fy = fromPos
if self._turn == self.WHITE:
movedir = -1
startrow = 6
ocol = self.BLACK
eprow = 3
else:
movedir = 1
startrow = 1
... |
def getValidKingMoves(self,fromPos):
moves = []
specialMoves={}
if self._turn == self.WHITE:
c_row = 7
c_king = self._white_king_castle
c_queen = self._white_queen_castle
k = "K"
else:
c_row = 0
c_king = se... | This function moves the king in a chess game, handling valid moves, castling (king/queen), updating the board, and game state variables like fifty-move counter and castling rights. It checks if the target position is valid, processes special moves, updates piece positions, and returns True if successful, False otherwis... | def moveKing(self,fromPos,toPos):
if self._turn == self.WHITE:
c_row = 7
k = "K"
r = "R"
else:
c_row = 0
k = "k"
r = "r"
moves,specialMoves = self.getValidKingMoves(fromPos)
if specialMoves.has_key(toPo... |
def getValidPawnMoves(self,fromPos):
moves = []
specialMoves = {}
fx,fy = fromPos
if self._turn == self.WHITE:
movedir = -1
startrow = 6
ocol = self.BLACK
eprow = 3
else:
movedir = 1
startrow = 1
... | The main task of the code is to execute a pawn move on a chessboard, validate the move, handle en passant captures, manage pawn promotions, update the board state, and record move details. It checks if the target position is valid, processes special moves (en passant, promotion), updates the board with the new piece po... | def movePawn(self,fromPos,toPos):
moves,specialMoves = self.getValidPawnMoves(fromPos)
if not toPos in moves:
return False
if specialMoves.has_key(toPos):
t = specialMoves[toPos]
else:
t = 0
if t == self.EP_CAPTUR... |
def updateKingLocations(self):
for y in range(0,8):
for x in range(0,8):
if self._board[y][x] == "K":
self._white_king_location = (x,y)
if self._board[y][x] == "k":
self._black_king_location = (x,y)
def getColor(self,x,y):
... | The function determines and returns a list of valid moves for the piece at the specified location, considering game state, piece type, and turn. It validates location bounds, checks if the piece belongs to the current player, and delegates to specific move-generating methods for each piece type. Returns an empty list i... | def getValidMoves(self,location):
"""
Returns a list of valid moves. (ex [ [3,4],[3,5],[3,6] ... ] ) If there isn't a valid piece on that location or the piece on the selected
location hasn't got any valid moves an empty list is returned.
The location argument must be a tuple containing... |
def gotoFirst(self):
"""
Goto before the first known move.
"""
self._state_stack_pointer = 1
self.loadCurState()
def _formatTextMove(self,move,format):
#piece,from,to,take,promotion,check
piece = move[0]
fpos = tuple(move[1])
... | The main task of the code is to retrieve all previously made chess moves in Algebraic notation, formatted according to the specified parameter. It checks if no moves exist (returns None) and traverses the internal state stack to collect moves, restoring the original state afterward. | def getAllTextMoves(self,format=1):
"""
Returns a list of all moves done so far in Algebraic chess notation.
Returns None if no moves has been made.
"""
if self._state_stack_pointer<=1: # No move has been done at this pointer
return None
res = []
poi... |
def undo(self):
"""
Undo the last move. Can be used to step back until the initial board setup.
Returns True or False if no more moves can be undone.
"""
if self._state_stack_pointer <= 1:
return False
self._state_stack_pointer -= 1
self.loadCurState()... | This function retrieves the latest chess move in Algebraic notation from the game history. It temporarily undoes the last move to access the stored move data, formats it, then restores the game state. Returns None if no moves exist. | def getLastTextMove(self,format=1):
"""
Returns the latest move as Algebraic chess notation.
Returns None if no moves has been made.
"""
if self._state_stack_pointer<=1: # No move has been done at thos pointer
return None
self.undo()
move = se... |
def make_main_window():
"""=================================================================================================================
This function creates the main window with necessary rectangle objects to interact with the database
:return win, recs: win is window object, recs are various rectang... | The main task of the code is to create a GUI window with interactive rectangles, connect to a SQLite database, and process user clicks to determine which rectangle was selected, keeping the window open until a specific exit rectangle is clicked, then closing the window and exiting the program. | def main():
"""=================================================================================================================
The main function calls make_window() and uses clicked() to determine which rectangle objects have been clicked.
==================================================================... |
def create_project(id, project_id):
title = project_title()
details = project_details()
total_target = project_total_target()
start_date= project_date()
end_date= project_date()
user_id=id
project={
'tilte': title,
'details': details,
'total_target': total_target,... | The code provides a menu-driven interface for managing projects, allowing users to create, view, edit, or delete projects. It uses a loop to display options and calls corresponding functions based on user input. A unique project ID is generated with uuid.uuid4() for creation, but the edit and delete functions may not c... | def project_menue(id):
while True:
print("\n1- Create Project\n2- View Project\n3- Edit Project\n4- Delete Project")
choice = int(input("Enter your choice: "))
project_id=uuid.uuid4()
if choice == 1:
create_project(id, project_id)
elif choice == 2:
vie... |
def validate_first_name():
str=input("Enter your firstName: ")
if str !="" and str.isalpha():
return str
else:
if str == "":
print("firstName is required")
else:
print("firstName must be characters only")
return validate_first_name()
def validate_last_n... | The main task of the code is to register a new user by collecting and validating their first name, last name, email, password, and mobile phone number. It generates a unique user ID using UUID, compiles the validated data into a dictionary, and saves the user information. The function ensures proper input validation, h... | def register():
first_name = validate_first_name()
last_name = validate_last_name()
email = validate_mail()
password = validate_password()
mobile_phone= input("Enter your mobile phone: ")
if not validate_phone(mobile_phone):
print("Unmatcehd Egyption number, Please try again")
re... |
def get_transect_area(data: pandas.DataFrame, row: int) -> float:
"""
Get the transect area of the specified row, in m2.
@param data: The data frame.
@param row: Row index.
"""
# Get transect area in m2.
transect_area = 0
if COL_TRWIDTH in data:
return transect_area_from_length_width(data, row)
if COL_SUBP... | This function aggregates per-individual biomass data into kg/ha by date, averaging across transects. It groups input data by date, calculates total live/dead biomass for each date by summing individual contributions, divides by transect count to get mean values, and returns a list of (date, live biomass, dead biomass) ... | def read_biomass_data(data: pandas.DataFrame, pcb: Callable[[float], None]) \
-> list[BiomassReading]:
"""
Aggregate biomass from per-individual into kg/ha.
Returns a list of tuples of (date, live biomass, dead biomass).
"""
# Date format in input data.
date_fmt = "%d/%m/%y"
result = []
groups = data.groupb... |
def zeroes(n: int) -> list[float]:
"""
Create an array of zeroes of the specified length.
"""
return [0.0] * n
def trim_to_start_year(in_file: Dataset, timestep: int
, data: list[float]) -> list[float]:
"""
Trim the given data to the start of the next year.
@param in_file: Input file.
@param timestep: Output ... | This function processes input data from a netCDF file by reading, cleaning (removing NaNs), aggregating to a specified timestep, converting units if needed, applying bounds checks, and trimming to annual start. It returns processed data while tracking progress and updating global time estimates for operations like read... | def _get_data(in_file: Dataset \
, in_name: str
, output_timestep: int \
, out_units: str \
, aggregator: Callable[[list[float]], float] \
, lower_bound: float \
, upper_bound: float \
, invert: bool \
, progress_cb: Callable[[float], None]) -> list[float]:
"""
Get all data from the input file and convert i... |
def read_raw_data(file: str) -> pandas.DataFrame:
"""
Read raw data from the input file.
"""
nas = ["Na", "NA", "na", "nA"]
return pandas.read_csv(file, parse_dates = True, na_values = nas)
def read_biomass_data(data: pandas.DataFrame, pcb: Callable[[float], None]) \
-> list[BiomassReading]:
"""
Aggregate bioma... | The code processes an input file by reading its data, processing biomass-related information, and writing results to a CSV file in the specified output directory. It tracks time spent on reading, processing, and writing phases, updating a progress callback with proportional progress. Global variables store time ratios ... | def process_file(file: str, out_dir: str, pcb: Callable[[float], None]):
"""
Read input data from file, aggregate data, write to a new file in out dir.
@param file: Input file.
@param out_dir: Output directory.
@param pcb: Progress callback function.
"""
log_information("Processing '%s'..." % file)
global _re... |
def _is_classification(self, target):
return target.dtype in (np.int64, np.int, np.int32) or target.apply(float.is_integer).all()
def _convert_to_categorical(self, data, categorical_columns):
for column in categorical_columns:
category_column = data[column].astype('category')
dat... | This function preprocesses a DataFrame by identifying categorical columns, converting them to categorical types, handling missing categories, sorting categories based on target relevance, and preparing them for modeling. It checks if the task is classification, manages small categories, and ensures proper encoding for ... | def fit_transform(self, data: pd.DataFrame, target: pd.Series):
data = data.copy()
is_classification = self._is_classification(target)
categorical_columns = self.cat_discover.discover_categories(data)
data = self._convert_to_categorical(data, categorical_columns)
self._find_small... |
def default_ray_sampling(ray_batch, N_samples, lindisp, perturb):
"""Samples coarse samples along rays.
Args:
ray_batch: array of shape [batch_size, ...]. All information necessary
for sampling along a ray, including: ray origin, ray direction, min
dist, max dist, and unit-magnit... | This function processes rays to render images using neural networks. It samples points along rays, computes view/light directions, evaluates RGB/density with a network, applies scaling, and performs importance sampling for refined results. It returns coarse and fine outputs including colors, alpha values, and sampled p... | def run_single_object(
ray_batch,
metadata,
network_fn,
network_query_fn,
use_viewdirs,
use_lightdirs,
lightdirs_method,
N_samples,
lindisp=False,
perturb=0.,
N_importance=0,
network_fine=None,
raw_noise_std=0.,
... |
def get_number_books(soup):
return int(
re.search(
r"\(([0-9]*)\)", soup.find("a", class_="selectedShelf").get_text()
).group(1)
)
def get_number_pages(num_books, limit):
if limit == 0 or limit >= num_books:
return math.ceil(num_books / 30)
else:
return math.c... | The code scrapes a bookshelf from a website by fetching multiple pages, parsing HTML content, and collecting book data. It handles pagination, applies a retrieval limit, and returns a list of book IDs. | def scrape_shelf(session, shelf_url, limit=0):
response = session.get(shelf_url)
first_page_soup = BeautifulSoup(response.text, "html.parser")
num_books = get_number_books(first_page_soup)
num_pages = get_number_pages(num_books, limit)
msg = "Scraping pages in shelf: "
progress(0, num_pages, m... |
def create_blob_client():
connection_string = os.environ['saunigiga_STORAGE']
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
return blob_service_client
def get_partner_data(blob_service_client: BlobServiceClient, country_name: str,
partners_list: list... | The code processes uploaded CSV files from Azure Blob Storage, extracting metadata like country and partner names. If files are in the "processed" folder, it retrieves partner data (e.g., Facebook, ITU), merges coverage data with a master dataset, saves results, and deletes temporary files. It sends Slack notifications... | def main(event: func.EventGridEvent):
event_data = event.get_json()
logging.info(event_data)
blob_url = event_data['blobUrl']
blob_file_path = re.search(r"(?<=(blob.core.windows.net\/))(.*)", blob_url)[0]
if not blob_file_path or not str(blob_file_path).endswith('.csv'):
logging.info(f'Upl... |
def _parse_file(self, filepath):
# Using LibCST
if filepath.endswith(".py"):
simple_cst = SimpleCST()
simple_cst.set_module(filepath=filepath)
_ = simple_cst.wrapper.visit(simple_cst)
return simple_cst.func_list
# Using TreeSitter
elif f... | This function processes Python and JavaScript files in a project directory, extracting function definitions, generating embeddings using an API, and storing them in a database table with metadata like function name, class, line number, and file path. It handles rate limits by retrying requests and deletes data on error... | def _encode_from_path(self, project_path, table_name, is_public, request):
for root, dirs, files in os.walk(project_path):
for file in files:
if file.endswith(".py") or file.endswith(".js"):
file_path = os.path.join(root, file)
func_list = self... |
def _check_if_public(self, url):
if self._check_if_valid_url(url=url):
return "Yes"
elif os.path.isdir(os.path.join("/mnt", url[1:])):
return "No"
else:
return "Error"
def _check_if_valid_url(self, url):
validation = validators.url(url, public=True)
... | The code processes a request to encode a project (from a public URL or local path) by checking if it's already indexed, cloning the repository if necessary, updating mapping/embedding tables, generating embeddings, and creating an index. It returns status codes (0-3) based on success/failure and existing indexing. | def handle_encode(self, request):
url = request.form["url"] # This can be public URL or local file path
is_public = self._check_if_public(
url=url
) # This can be "Yes" or "No" or "Error" depending on whether public URL or not
if is_public == "Yes":
if self._ch... |
def _create_faiss_index(self):
cpu_index = faiss.IndexFlatIP(self.configs["model"]["dimension"])
if faiss.get_num_gpus() == 0:
print("No GPU detected. Using CPU.")
self.index = cpu_index
else:
print("GPU detected. Using GPU.")
self.res = faiss.Sta... | This function processes a search request by extracting a URL and query, creating a FAISS index, validating the URL's public status, encoding input, checking index existence, generating indexes if needed, embedding the query, and retrieving nearest neighbors from the index to return search results. | def handle_search(self, request):
url = request.form["url"] # This can be public URL or local file path
query = request.form["query"]
print("query: ", query)
self._create_faiss_index()
is_public = self._check_if_public(
url=url
) # This can be "Yes" or "No"... |
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if self.wait:
self.hero.velocity = [0, 0]
return
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]:
self.hero.a... | This code runs a game loop that continuously handles events, updates the game state based on time delta, renders the current frame, and maintains a target frame rate (FPS) using Pygame. It fills the screen with a background color, processes input, updates game logic, and displays the rendered output in a loop. | def run(self):
while True:
self.handle_events()
dt = self.clock.tick(self.FPS) / 1000.0
self.screen.fill(self.BG_COLOR)
self.update(dt)
self.render(self.screen)
pygame.display.flip() |
def getGame(self):
request = self.generateGamesListRequest()
userGame = self.userInput.getInputInt(request)
weaponsLists = self.getWeaponLists()
return weaponsLists[userGame]
def getUserChoice(self,weapons):
request = self.getUserChoiceRequest(weapons)
player = self.userI... | The code's main task is to run a game loop where the user and computer select weapons (0-2), determine the winner of each round, and display the result repeatedly until the user stops choosing valid options. It retrieves game parameters, handles user and computer choices, evaluates outcomes, and outputs results in a co... | def play(self):
weapon = self.getGame()
player = self.getUserChoice(weapon)
while player in [0,1,2]:
computer = self.getComputerChoice(weapon)
result = self.determineWinner(player,computer)
self.userOutput.print(result)
player = self.getUserChoice(... |
def deploy_my_governance():
if not (MyToken):
deploy_my_token()
if not (GovernanceTimeLock):
deploy_governance_time_lock()
MyGovernor.deploy(
MyToken[-1],
GovernanceTimeLock[-1],
VOTING_DELAY,
VOTING_PERIOD,
PROPOSAL_THRESHOLD,
QUORUM_PERCENTA... | The code simulates a governance workflow by deploying a governance contract and a governed box, creating a proposal, voting, queuing, and executing it, while printing the proposal's state at each stage to demonstrate its lifecycle. | def main():
deploy_my_governance()
set_access_control_timeLock()
deploy_box_to_be_governed()
proposal_id = create_proposal()
print(f"state after propose = {MyGovernor[-1].state(proposal_id)}")
vote_proposal(proposal_id, 1)
print(f"state after vote = {MyGovernor[-1].state(proposal_id)}")
... |
def case1(soup, instagram_page_dict_final, timestamp):
m=get_portion_of_html_with_instagram_page_info(soup, timestamp)
instagram_page_dict_temp={}
if timestamp>=20130302000000:
instagram_page_dict_temp=json.loads('{'+m[0]+'}')
#get and clean user profile information
user_profile_dict_temp=get_user_profile_dict... | Your return The function `get_instagram_page_dict` processes Instagram page data by routing parsing logic to different cases (`case1`-`case4`) based on the provided timestamp. It updates the `instagram_page_dict_final` dictionary with extracted information from the HTML soup object, handling structural changes in Insta... | def get_instagram_page_dict(soup, instagram_page_dict_final: dict, username: str, timestamp: int):
'''
Passes the instagram_page_dict_final and Beautiful Soup object to the relevant case based on timestamp
soup: Beautiful Soup object that contains the html of the urim
instagram_page_dict_final: dictionary that wil... |
def reset_select(self):
for i in range(8):
for j in range(8):
if self.board[i][j] != 0:
self.board[i][j].selected = False
def move(self, start, end, castling, color):
global game
old_board = copy.deepcopy(self.board)
if self.board[end[0]... | This code handles chess piece selection and movement, including capturing, castling, and validation. It checks if a selected piece can move to a target position, executes the move if valid, and reverts changes if the move results in check. It also manages turn changes and checkmate detection, ensuring proper game state... | def select(self, row, col, color):
global game
prev = 0
castling = False
old_board = copy.deepcopy(self.board)
old_game = copy.copy(game)
for i in range(8):
for j in range(8):
if self.board[i][j] != 0:
if self.board[i][j].se... |
def FLUT_interpolator(self, Coord: tuple, Prop: str or tuple) -> np.array:
'''
input:
Coord: tuple containing GOR, P and T profiles (GOR, P, T are ndarrays)
Prop: string or tuple of strings of the properties that the user wants to interpolate
output:
if user i... | The code solves asphaltene deposition in a pipe using the ADEPT model, simulating concentration dynamics (dissolved/asphaltene particles) via PDEs with Crank-Nicolson scheme, incorporating advection, precipitation, aggregation, and deposition. It updates pressure/temperature profiles, calculates deposition thickness, a... | def ADEPT_Solver(self, T_prof: tuple, P_prof: tuple, GOR: float):
'''
Solves asphaltene deposition problem = f(z, t) using the ADEPT formulation
Parameters
----------
T : np.ndarray(float)
temperature profile (K).
P : np.ndarray(float)
... |
def decide_python_versions(distros: list[str], supported_versions: list[SupportedVersion]) -> list[PythonVersion]:
python_patch_re = "|".join([rf"^(\d+\.\d+\.\d+-{distro})$" for distro in distros])
python_wanted_tag_pattern = re.compile(python_patch_re)
# FIXME: can we avoid enumerating all tags to speed u... | The function generates all possible combinations of the latest Python and Node.js versions supported by each distro, filtering to the latest patch version for each Python minor version and the latest minor version for each Node.js major version. | def decide_version_combinations(
distros: list[str],
supported_python_versions: list[SupportedVersion],
supported_node_versions: list[SupportedVersion],
) -> list[BuildVersion]:
distros = list(set(distros))
# Use the latest patch version from each minor
python_versions = decide_python_versions(d... |
def ddim_reverse_sample(image, prompt, model, num_inference_steps: int = 20, guidance_scale: float = 2.5,
res=512):
"""
==========================================
============ DDIM Inversion ==============
==========================================
"""... | The code implements an adversarial attack on a diffusion model to generate imperceptible perturbations that mislead a pre-trained classifier. It uses DDIM inversion to create latent representations, optimizes unconditional embeddings for reconstruction, and manipulates attention maps during diffusion steps to alter the... | def diffattack(
model,
label,
controller,
num_inference_steps: int = 20,
guidance_scale: float = 2.5,
image=None,
model_name="inception",
save_path=r"C:\Users\PC\Desktop\output",
res=224,
start_step=15,
iterations=30,
verbos... |
def check_prefix(self, prefix):
prefix_list = prefix.split(' ')[-self.n:]
if len(prefix_list) < self.n:
warnings.warn(
'Prefix is too short, please provide prefix of length: %d. Random ngram used instead.' % self.n)
return self.random_ngram()
else:
... | This function generates a sequence of words by iteratively predicting the next word $k$ times using a language model. It starts with a given prefix, updates the context window for each prediction, and appends new words to the sequence. The temperature parameter controls the randomness of predictions. Finally, it return... | def generate_sequence(self, prefix, k, temperature=1):
prefix = self.check_prefix(prefix)
sequence = prefix.split(' ')
for i in range(k):
next_word = self.return_next_word(prefix, temperature=temperature)
sequence.append(next_word)
prefix = ' '.join(sequence[... |
def convert_gravity_value(value):
"""Convert a planet's "gravity" value to a float. Removes the "standard" unit of measure if
it exists in the string (case-insensitive check). Delegates to the function
< convert_to_float > the task of casting the < value > to a float.
If an exception is encountered the... | The code processes and validates data from CSV/JSON files related to *The Mandalorian* (people, starships, planets, etc.), tests conversion utilities, creates structured objects (planets, droids, characters), updates relationships (e.g., passengers, visited planets), and writes results to JSON files. It also sorts plan... | def main():
"""Entry point for program.
Parameters:
None
Returns:
None
"""
# PROBLEM 01
# Problem 1.2
mandalorian_people = utl.read_csv_to_dicts("./data-mandalorian_people.csv")
# Problem 1.3
mandalorian_starships = utl.read_json("./data-mandalorian_starships.json"... |
def bisect(G):
nodes = list(G.nodes)
random.shuffle(nodes)
middle_index = len(nodes)//2
V1 = set(nodes[:middle_index])
V2 = set(nodes[middle_index:])
B1 = V1.copy()
B2 = V2.copy()
p = -1
R = 10
counter = 0
while counter <= R and counter > - 100000:
c_pre = cost(V1, V2... | The code computes a feedback arc set (FAS) for a directed graph by recursively decomposing it into strongly connected components (SCCs). If the graph has one SCC, it splits into subgraphs H and J, finds back edges between them, and recursively processes these subgraphs. For multiple SCCs, it processes each individually... | def fas(G):
P = nx.strongly_connected_components(G)
P2 = list(P)
if len(P2) == 1:
H, J = bisect(G)
res = back_edges(H, J, G)
if(len(H) > 1):
res.extend(fas(nx.subgraph(G,H)))
if len(J) > 1:
res.extend(fas(nx.subgraph(G,J)))
else:
res = []
... |
def check_index_finger(hand_landmarks):
return check_finger(hand_landmarks, INDEX_FINGER_TOP, INDEX_FINGER_BOTTOM)
def check_middle_finger(hand_landmarks):
return check_finger(hand_landmarks, MIDDLE_FINGER_TOP, MIDDLE_FINGER_BOTTOM)
def check_ring_finger(hand_landmarks):
return check_finger(hand_landmarks, ... | The code determines if a hand gesture should trigger 'start', 'stop', or 'nothing' based on finger positions. It checks if the index finger is bent while others are straight and the thumb is near the index for 'start'. For 'stop', it verifies if the straight thumb's bottom landmark is lower than its top. Otherwise, it ... | def get_start_stop(hand_landmarks):
index_finger = check_index_finger(hand_landmarks)
middle_finger = check_middle_finger(hand_landmarks)
ring_finger = check_ring_finger(hand_landmarks)
pinky_finger = check_pinky_finger(hand_landmarks)
is_thumb_near_index = is_thumb_near_index_finger(hand_landmarks)... |
def check_index_finger(hand_landmarks):
return check_finger(hand_landmarks, INDEX_FINGER_TOP, INDEX_FINGER_BOTTOM)
def check_pinky_finger(hand_landmarks):
return check_finger(hand_landmarks, PINKY_FINGER_TOP, PINKY_FINGER_BOTTOM)
def check_middle_finger(hand_landmarks):
return check_finger(hand_landmarks, M... | This function detects a "ninja turtle" gesture by checking if the index and pinky fingers are straight while the middle and ring fingers are bent. If the condition is met, it returns a dictionary with 'ninja' and the index finger's coordinates; otherwise, it returns 'nothing'. | def search_for_ninja_turtle(hand_landmarks):
index_finger = check_index_finger(hand_landmarks)
pinky_finger = check_pinky_finger(hand_landmarks)
middle_finger = check_middle_finger(hand_landmarks)
ring_finger = check_ring_finger(hand_landmarks)
if index_finger['straight'] and pinky_finger['straight'... |
def make_qubit(self):
p = self.p
# print(p.cavity_options['cpw_options'].total_length)
qubit_opts = Dict()
self.copier(qubit_opts, p.qubit_options)
qubit_opts["pos_y"] = 0
qubit_opts["pos_x"] = "-1500um" if p.cavity_options['cpw_options'].total_length > 2.500 else "-1000... | The code defines a method `make` that initializes components of a quantum system. It assigns `self.p` to a local variable `p`, then sequentially creates a qubit, a cavity, and pins using the instance methods `make_qubit()`, `make_cavity()`, and `make_pins()`. The primary task is to set up the structural and operational... | def make(self):
p = self.p
self.make_qubit()
self.make_cavity()
self.make_pins() |
def load_data(self):
print("Loading data from {0}".format(self.filename))
self.cron_rules = self.read_file()
self.build_queue()
self.reload_event.clear()
def get_time_to_sleep(execute_time):
sleep_seconds = execute_time - tz_now().timestamp()
return sleep_seconds if sleep_second... | The code defines a scheduler's run method that processes tasks from a queue, waits until their scheduled execution time, and executes associated commands. It handles dynamic reloading of data, checks for restart signals, and reschedules subsequent executions. The loop continues until the queue is empty or a restart is ... | def run(self):
print("Scheduler start")
self.load_data()
while not self.restart.is_set() and not self.queue.empty():
if self.reload_event.is_set():
self.load_data()
entry = self.queue.get()[1]
print("First entry in queue is", entry)
... |
def __str__(self):
return f"{self.batch_item}({self.outgoing}->{self.incoming})"
def balance_outgoing(self):
if self.outgoing is not None and not self.is_done:
try:
outgoung_balance = self.outgoing.balance_set.get(
batch_item_id=self.batch_item_id
... | This code overrides the save method to generate a slug from the model's string representation, execute balance operations (outgoing/incoming) if the instance is approved, mark the task as completed, and then call the parent class's save method. | def save(self, *args, **kwargs):
self.slug = slugify(self.__str__())
if self.is_approved:
self.balance_outgoing()
self.balance_incoming()
self.is_done = True
super().save(*args, **kwargs) |
def inCheck(self):
if self.whiteToMove:
return self.squareUnderAttack(self.whiteKingLocation[0], self.whiteKingLocation[1])
else:
return self.squareUnderAttack(self.blackKingLocation[0], self.blackKingLocation[1])
def getKingSideCastleMoves(self, row, col, moves):
moves =... | This code generates valid castling moves for a chess king based on the current player's turn and castling rights. It first checks if the king is in check, returning no moves if so. Then, it appends king-side or queen-side castling moves (if allowed by currentCastlingRights) to the moves list, ensuring legal castling po... | def getCastleMoves(self, row, col, moves):
moves = list(moves)
if self.inCheck():
return moves # can't castle when in check
if self.whiteToMove and self.currentCastlingRights.wks or (not self.whiteToMove and self.currentCastlingRights.bks):
moves = self.getKingSideCastleM... |
def getAllMoves(self):
moves = []
for row in range(len(self.board)):
for col in range(len(self.board[row])):
turn = self.board[row][col][0] # Accesses the first character of the item in the square
if (turn == 'w' and self.whiteToMove) or (turn == 'b' and not s... | The code generates valid chess moves by checking if each move leaves the king in check, handling castling rights, en passant, and detecting checkmate/stalemate. It iterates through all moves, simulates them, and removes invalid ones. It also checks for draw conditions like repetition and returns the list of valid moves... | def getValidMoves(self):
tempEnPassantPossible = self.enPassantPossible
tempCastleRights = CastleRights(self.currentCastlingRights.wks, self.currentCastlingRights.bks,
self.currentCastlingRights.wqs, self.currentCastlingRights.bqs) # copies current castling rights
# 1) Generate all possi... |
def load_model(args):
"""Load and return the model and tokenizer"""
args.is_seq2seq_model = any([(model_type in args.model_name_or_path) for model_type in ["t5","T0"]])
args.is_decoder_only_model = any([(model_type in args.model_name_or_path) for model_type in ["gpt","opt","bloom"]])
if args.is_seq2seq... | The main task of the code is to generate text with and without watermarks, detect watermarks in outputs, and optionally launch a Gradio demo for interactive use. It processes command-line arguments, loads a model (if not skipped), generates outputs, runs detection, and prints results. The Gradio interface allows real-t... | def main(args):
"""Run a command line version of the generation and detection operations
and optionally launch and serve the gradio demo"""
# Initial arg processing and log
args.normalizers = (args.normalizers.split(",") if args.normalizers else [])
print(args)
if not args.skip_model_load:... |
def init_df_deals(start_price, start_wealth=0, start_inventory=0):
"""
Just deals dataframe init
"""
data = {'Time': [0.],
'Wealth': [start_wealth],
'Inventory': [start_inventory],
'Deal side': [0.],
'Mid': [start_price],
'Bid': [start_price],
... | The function performs multiperiod simulations by running `n` scenarios with `multiperiod` time steps each, using model parameters like price dynamics, inventory rules, and market data. It computes results for both inventory-based and constant strategies, aggregating profit-and-loss (PnL) and final inventory quantities.... | def run_multiperiod_sims(n, multiperiod, **kwargs):
"""
Function for multiperiod simulation
:param n: number of runs
:param multiperiod: number of periods per run
:param kwargs: all model parameters
:return: dataframe with results
"""
# Array structure:
# 0 1 2 ... |
def events(self):
for events in pg.event.get():
if events.type == pg.KEYUP:
if events.key == pg.K_SPACE:
self.deploy_unit("left", "elite_sword_infantry", self.player_selected_slot)
if events.key == pg.K_UP:
self.cha... | This code runs a game loop that maintains a target frame rate, processes events, updates game state, and renders graphics repeatedly while the game is active. | def run(self):
while self.playing:
self.clock.tick(self.fps)
self.events()
self.update()
self.draw() |
def _update_status_and_services(
self, container: model.Container, status: model.StatusBase):
"""Updates the status of the charm and Legend service(s).
Also updates the parent app if the unit is the leader.
Performs the following action on the Legend service(s) depending on status:
... | The main task of the code is to refresh the Legend charm's status by verifying the workload container's readiness, ensuring required relations are present, configuring JKS truststore if needed, generating service configurations, and writing them to the container. It updates the charm's status to reflect operational sta... | def _refresh_charm_status(self):
"""Refreshes the Legend charm status.
Performs the following checks/acions:
* checking if the Pebble API in the workload container is reachable
* checking all relations present
* setting up JKS truststore in container (if the service needs it)
... |
def ui_show_main_menu():
print('''
MAIN MENU
-------------------------------------------
1. Create / Read / Update / Delete Bookings
2. Other operations on Bookings
3. Undo / Redo
-------------------------------------------
0. Exit
''')
def ui_run_crud_menu_loop(bookings_manager):
... | The main task of the code is to display a main menu loop, process user input for navigation options (1-3), and delegate to corresponding submenu loops (CRUD, other operations, undo/redo) or exit (option 0). It handles invalid inputs by catching ValueErrors and prompting retries, ensuring valid integer selections for me... | def ui_run_main_menu_loop(bookings_manager):
while True:
ui_show_main_menu()
try:
option = int(input("What would you like to do? "))
if option == 1:
ui_run_crud_menu_loop(bookings_manager)
elif option == 2:
ui_run_other_operations_m... |
def sub_closest_carbon(self, value, pcharge):
# Find closest C and subsitute
C = self.find_closest_atoms(value[0][0], value[-1], self.nafion_types['1'], 1)[0]
self.sum_of_charges += pcharge
c_val = self.nafion_types['1'][C[0]]
self.data[int(C[0])-1] = (' ').join(c_val[0]) + ' ' + str(pcharge) + ' ' + (... | The main task of the code is to modify a molecular structure by substituting sulfur atoms with charged values, updating neighboring carbon and oxygen atoms, and removing specific atoms from data structures. It processes each sulfur in Nafion_types['4'], adjusts adjacent carbons (C5, C4, C2, C0) and fluorines, replaces ... | def rest_of_the_chain(self):
pcharge = self.pcharge_conv['S']
IDs = []
# For every sulfur
for key, value in self.nafion_types['4'].items():
# Substitute
self.data[int(key)-1] = (' ').join(value[0]) + ' ' + str(pcharge) + ' ' + (' ').join(value[-1]) + '\n'
self.sum_of_charges += pcharge
# Store... |
def _read_from_mem_cache(self, key: str) -> bytes:
with self._mem_cache_lock:
if key in self._mem_cache:
entry = bytes(self._mem_cache[key])
_LOGGER.debug("Memory cache HIT: %s", key)
return entry
else:
_LOGGER.debug("Memor... | The function `read_value` retrieves a value from a cache (either memory or disk) based on the provided key. It first attempts to read from memory; if the key is not found and persistence is enabled for disk, it reads from disk, updates memory, and queries the key if necessary. It then unpickles the retrieved value, rai... | def read_value(self, key: str) -> Any:
"""Read a value from the cache. Raise `CacheKeyNotFoundError` if the
value doesn't exist, and `CacheError` if the value exists but can't
be unpickled.
"""
key = f"{self.cache_name}:{key}"
try:
pickled_value = self._read_f... |
def getResponse(ints, intents_json,tagging=False):
global block
global emailid
mydb = mysql.connector.connect(host="localhost", user="root", passwd="",database="chatbot")
if tagging == True:
tag = ints
else:
tag = ints[0]['intent']
if tag == 'aganist':
block=1
... | This function processes user input to generate chatbot responses based on intent classification. If the input matches a known intent class, it returns a predefined response. For ambiguous inputs, it checks a machine learning model's confidence threshold (0.7775). If below threshold, it prompts for clarification. It als... | def chatbot_response(text):
global intents
global classes
global model
global emailid
emailLogin=emailid.get()
if text in classes:
res = getResponse(text,intents,tagging=True)
print("This is my response==================>"+str(res))
return res
# else:
# ... |
def normalization(alpha, lx, ly, lz):
"""Get normalization constant for Gaussian basis function
Args:
alpha (float): exponent of Gaussian
lx (float): angular momentum in x-direction
ly (float): angular momentum in y-direction
lz (float): angular momentum in z-direction
Retu... | The code computes the kinetic integral matrix between basis functions using recursive evaluation of integrals between primitive Gaussian functions. It iterates over all basis function pairs, calculates normalization factors, and evaluates kinetic integrals via helper functions (E, K). The matrix element [i][j] accumula... | def kinetic_recursive(molecule):
"""Generate kinetic integral matrix of between two basis function
Args:
molecule (list): basis functions of primitive gaussians
Returns:
ndarray: kinetic integrals between basis functions
"""
nbasis = len(molecule)
Tmatrix = np.zeros([nbasis, nb... |
def BiosVer(self):
aa=self.Get('UpdateService/FirmwareInventory/BIOS')
if isinstance(aa,dict): return aa.get('Version')
aa=self.Get('Systems/1')
if isinstance(aa,dict): return aa.get('BiosVersion')
def BmcVer(self):
aa=self.Get('UpdateService/FirmwareInventory/BMC')
if is... | The code collects system information via Redfish API calls, aggregating data on BIOS/BMC versions, network, memory, CPU, power, and chassis details. It extracts UUID-derived MAC addresses, manufacturer, board ID, serial number, and GUID from chassis data, then compiles all into a structured dictionary for return. | def Info(self):
naa={}
naa['version']={'bios':self.BiosVer(),'bmc':self.BmcVer()}
naa['network']=self.Network()
naa['redfish_hi']=self.RedfishHI()
naa['power']=self.Power('info')
naa['memory']=self.Memory()
naa['cpu']=self.Cpu()
aa=self.Get('Managers/1')
... |
def error(self,_type=None,msg=None):
if _type and msg:
self.err.update({_type:{TIME().Int():msg}})
else:
if not _type:
if self.err: return True,self.err
return False,'OK'
else:
get_msg=self.err.get(_type,None)
... | The main task of the code is to validate an IP address (potentially derived from a MAC address) for IPMI communication. It checks network reachability via ping, verifies IPv4 port validity, retrieves user/passwd credentials, and ensures MAC/IP consistency. If successful, it updates internal state and returns True with ... | def check(self,mac2ip=None,cancel_func=None,trace=False):
if cancel_func is None: cancel_func=self.cancel_func
chk=False
ip='{}'.format(self.ip)
for i in range(0,2):
if self.checked_ip is False:
if mac2ip and self.mac:
ip=mac2ip(self.mac)
... |
def Get(self,cmd,host=None):
if not host: host=self.host
if not isinstance(cmd,str): return False
data = WEB().Request(self.Cmd(cmd,host=host),auth=(self.user, self.passwd))
if data[0] and data[1].status_code == 200:
return json.loads(data[1].text)
return False
def Ba... | This function retrieves BIOS boot settings, identifies the PXE boot MAC address, parses boot options, and returns the boot mode, PXE boot index, and boot options. It first fetches BIOS attributes, determines the PXE MAC via network interfaces, processes boot entries to detect PXE-compatible options, and returns structu... | def Bootmode_bios(self,pxe_boot_mac=None):
rc=self.Get("Systems/1/Bios")
bios_boot=[]
pxe_boot_wait=0
if isinstance(rc,dict):
bios_boot=list(rc.get('Attributes',{}).items())
pxe_boot_wait=rc.get('Attributes',{}).get('PXEBootWaitTime',0)
if pxe_boot_mac is... |
def error(self,_type=None,msg=None):
if _type and msg:
self.err.update({_type:{TIME().Int():msg}})
else:
if not _type:
if self.err: return True,self.err
return False,'OK'
else:
get_msg=self.err.get(_type,None)
... | The function `run_cmd` executes a command with customizable parameters (path, timeout, retries, etc.), handles error checking, and evaluates return codes. It processes command formats, defaults variables, and retries on failures (e.g., network issues, invalid credentials). It checks command output against specified suc... | def run_cmd(self,cmd,append=None,path=None,retry=0,timeout=None,return_code={'ok':[0,True],'fail':[]},show_str=False,dbg=False,mode='app',cancel_func=None,peeling=False,progress=False,ip=None,user=None,passwd=None,cd=False,check_password_rc=[],trace_passwd=False):
if cancel_func is None: cancel_func=self.cancel... |
def get_cmd_module_name(self,name):
if isinstance(self.cmd_module,list):
for mm in self.cmd_module:
if Type(mm,('classobj','instance')) and IsSame(mm.__name__,name):
if mm.ready:
return mm,'Found'
else:
... | The main task of the code is to recover or reset a BMC (Baseboard Management Controller) user's password using IPMI commands. It checks current credentials, attempts to set or add a user with the original or default password, verifies success via command output, updates stored credentials if successful, and handles err... | def recover_user_pass(self):
mm,msg=self.get_cmd_module_name('smc')
if not mm:
return False,msg,None
was_user='{}'.format(self.user)
was_passwd='{}'.format(self.passwd)
ok,user,passwd=self.find_user_pass()
if ok:
printf("""Previous User({}), Passwo... |
def error(self,_type=None,msg=None):
if _type and msg:
self.err.update({_type:{TIME().Int():msg}})
else:
if not _type:
if self.err: return True,self.err
return False,'OK'
else:
get_msg=self.err.get(_type,None)
... | The function attempts to reset a BMC (Baseboard Management Controller) by executing an IPMI reset command, with retry logic. It checks network connectivity before and after the reset using ping, ensuring the BMC is reachable. If ping fails before reset, it retries up to 'retry' times. After reset, it verifies connectiv... | def reset(self,retry=0,post_keep_up=20,pre_keep_up=0,retry_interval=5,cancel_func=None):
for i in range(0,1+retry):
for mm in self.cmd_module:
if ping(self.ip,timeout=1800,keep_good=pre_keep_up,log=self.log,stop_func=self.error(_type='break')[0],cancel_func=self.cancel(cancel_func=ca... |
def run_cmd(self,cmd,append=None,path=None,retry=0,timeout=None,return_code={'ok':[0,True],'fail':[]},show_str=False,dbg=False,mode='app',cancel_func=None,peeling=False,progress=False,ip=None,user=None,passwd=None,cd=False,check_password_rc=[],trace_passwd=False):
if cancel_func is None: cancel_func=self.cancel... | This function sets or retrieves a system's boot order/boot mode via IPMI or Redfish interfaces, handling PXE, BIOS, HDD, CD, USB options. It supports persistent/temporary settings, IPXE boot, and returns status/EFI mode/persistence info. The function checks available modules, executes commands, and returns success/fail... | def bootorder(self,mode=None,ipxe=False,persistent=False,force=False,boot_mode={'smc':['pxe','bios','hdd','cd','usb'],'ipmitool':['pxe','ipxe','bios','hdd']},bios_cfg=None):
rc=False,"Unknown boot mode({})".format(mode)
ipmi_ip=self.ip
for mm in self.cmd_module:
name=mm.__name__
... |
def get_cmd_module_name(self,name):
if isinstance(self.cmd_module,list):
for mm in self.cmd_module:
if Type(mm,('classobj','instance')) and IsSame(mm.__name__,name):
if mm.ready:
return mm,'Found'
else:
... | This function configures or retrieves the LAN interface mode via IPMI OEM commands. It validates the input mode, executes the appropriate 'ipmi oem lani' command, and returns success/failure status with mode details. If no mode is provided, it fetches current LAN interface info. The function handles mode conversion, co... | def lanmode(self,mode=None):
mm,msg=self.get_cmd_module_name('smc')
if not mm:
return False,msg
if self.lanmode_convert(mode) in [0,1,2]:
rc=self.run_cmd(mm.cmd_str("""ipmi oem lani {}""".format(self.lanmode_convert(mode))),timeout=5)
if krc(rc[0],chk=True):
... |
def do_power(self,cmd,retry=0,verify=False,timeout=1200,post_keep_up=40,pre_keep_up=0,lanmode=None,cancel_func=None,fail_down_time=300):
timeout=Int(timeout,default=1200)
def lanmode_check(mode):
# BMC Lan mode Checkup
cur_lan_mode=self.lanmode()
if cur_lan_mode[0]:
... | This function manages power and boot mode settings for a system, handling commands like 'status' and configuring boot order via Redfish or IPMI. It retries on failure, adjusts boot modes (e.g., PXE/UEFI), and ensures persistent settings. Parameters control behavior, including retry counts, timeouts, and logging. | def power(self,cmd='status',retry=0,boot_mode=None,order=False,ipxe=False,log_file=None,log=None,force=False,mode=None,verify=True,post_keep_up=20,pre_keep_up=0,timeout=3600,lanmode=None,fail_down_time=240):
retry=Int(retry,default=0)
timeout=Int(timeout,default=3600)
pre_keep_up=Int(pre_keep_up... |
def get_holdings():
try:
logging.debug("getting holdings for the day ...")
resp = broker.kite.holdings()
df = get(resp)
logging.debug("filtering for required columns")
df["key"] = df["exchange"] + ":" + df["tradingsymbol"]
df.set_index("key", inplace=True)
"""... | The main task of the code is to process financial holdings by downloading master data, retrieving holdings, reading associated tokens, establishing WebSocket connections for real-time data feeds, saving processed data to a CSV file, and executing further operations using the connected WebSocket and holdings data. | def main():
# download master once in a day
dump()
## make a list of holdings we want to process
df = get_holdings()
if df.empty:
logging.info("No holdings to process. Exiting")
sys.exit(0)
## read tokens from dumped files
df = read_tokens(df)
## subscribe for rate feed f... |
def createSavingAccount(username, amount=1000):
accNo = createAccount(username)
query = f"INSERT INTO Saving VALUES('{accNo}', {amount})"
mycursor.execute(query)
mydb.commit()
def createInvestAccount(username, amount=0):
accNo = createAccount(username)
query = f"INSERT INTO Investment VALUES('{a... | The code registers a new customer by inserting their username and password into the 'Customer' database table, then automatically creates three accounts—saving, investment, and credit—for the user. It executes the SQL insertion, commits the transaction, and confirms the record insertion with a print statement. | def register(username, password):
query = f"INSERT INTO Customer (username, password) VALUES ('{username}', '{password}')"
mycursor.execute(query)
mydb.commit()
createSavingAccount(username)
createInvestAccount(username)
createCreditAccount(username)
print(mycursor.rowcount, "record inserted... |
def get_cond(self, patient_id):
return """--where="name='%s'" """%patient_id
def remote_to_local(self, table, cond, patient_id):
remote_settings = self.get_remote_settings(table, cond, patient_id)
local_settings = self.get_local_settings(table)
if table != 'tabSingles':
try:
# webnotes.errprint("""mysqld... | The function `initiate_sync_db` synchronizes data between local and remote databases. If a `patient_id` is provided, it filters data using a condition and syncs specific records from remote to local. Without a `patient_id`, it syncs all data from local to remote for each table, ensuring bidirectional database consisten... | def initiate_sync_db(self, patient_id=None):
cond = ''
if patient_id:
cond = self.get_cond(patient_id)
# webnotes.errprint(cond)
for table in tables:
if cond:
self.remote_to_local(table, cond, patient_id)
else:
# self.remote_to_local(table, cond,patient_id)
self.local_to_remote(table) |
def get_device_info():
if torch.cuda.is_available():
print('CUDA is available. Running on GPU.')
return 'cuda', "float16"
else:
print('CUDA is not available. Running on CPU.')
return 'cpu', "int8"
def run_whisperx(audio_files, output_dir, settings, device, compute_type):
base... | The code processes audio files by converting them to WAV format if needed, then uses WhisperX for transcription. It generates SRT files and organizes speaker segments into subdirectories. If diarization is enabled, it separates speaker segments; otherwise, it extracts audio based on the SRT. Finally, it merges segments... | def process_audio_files(input_folder, settings):
output_dir = os.path.join(input_folder, "output")
wav_dir = os.path.join(input_folder, "wav_files")
os.makedirs(output_dir, exist_ok=True)
os.makedirs(wav_dir, exist_ok=True)
device, compute_type = get_device_info()
for audio_file in os.listdir(... |
def select_input_folder():
root = tk.Tk()
root.withdraw()
return filedialog.askdirectory(title="Select input folder").replace("/","\\")
def load_settings(config_path):
with open(config_path, "r") as file:
return yaml.safe_load(file)
def process_audio_files(input_folder, settings):
output_dir... | The main task of the code is to process audio files from a user-selected input folder using predefined settings. The function selects an input directory, loads configuration parameters from a specified file, and applies these settings to process the audio files within the chosen folder. | def main():
input_folder = select_input_folder()
settings = load_settings(CONFIG_PATH)
process_audio_files(input_folder, settings) |
def do_connect(self):
self.zmq_out = context.socket(self.zmq_conf["out"]['type'])
if self.zmq_conf["out"]["bind"]:
self.zmq_out.bind(self.zmq_conf["out"]["address"])
else:
self.zmq_out.connect(self.zmq_conf["out"]["address"])
self.zmq_out_internal = conte... | The code connects to a system (frepple) and continuously monitors for new and open orders. It checks unconfirmed inquiry orders, sends confirmations to an MES system, verifies open orders' status, and periodically updates the plan. The loop runs at set intervals to ensure real-time order tracking and confirmation, main... | def run(self):
self.do_connect()
self.frepple = freppleConnect(self.user, self.password, self.url)
logger.info("Connected")
run = True
timeReading = datetime.now()
while run:
if (datetime.now() -timeReading).total_seconds()>self.frequency:
# fi... |
def do_connect(self):
self.zmq_in = context.socket(self.zmq_conf['in']['type'])
if self.zmq_conf['in']["bind"]:
self.zmq_in.bind(self.zmq_conf['in']["address"])
else:
self.zmq_in.connect(self.zmq_conf['in']["address"])
self.zmq_out = context.socket(self.zmq_conf[... | This code initializes a connection to a frePPle API and a ZeroMQ socket, then continuously listens for incoming MQTT messages. It processes each message by parsing its topic and payload, determining if it relates to a purchase or order update, and invoking the appropriate method (processPurchase or processOrder) with e... | def run(self):
logger.info("Starting")
self.do_connect()
logger.info("ZMQ Connected")
self.frepple = freppleAPImodule.freppleConnect(self.user, self.password, self.url)
run = True
while run:
while self.zmq_in.poll(500, zmq.POLLIN):
msg = self.z... |
def run_cmd_new(args):
"""
It creates a new project folder and then creates a virtual environment inside that folder
Args:
args (str): The arguments passed to the command.
Example:
```py
run_cmd_new("project_name")
```
Return:
None
"""
try:
... | The main task of the code is to route user commands to corresponding functions based on the input argument. It checks the value of `args.command` and executes functions like `run_cmd_new`, `run_cmd_install`, etc., while validating required parameters and providing error messages if missing. It also handles special comm... | def check_command(args):
"""
It checks the command that the user has entered and then runs the appropriate function
Args:
args (str): The arguments passed to the script
Example:
```py
check_command("new" or "install" or "uninstall" or "update" or "onlyenv")
```
Retu... |
def plan(algorithm, start_state):
if algorithm == 0:
return bfs(start_state)
if algorithm == 1:
return a_star(start_state)
elif algorithm == 2:
return oone(start_state)
elif algorithm == 3:
return greedy_dfs(start_state)
elif algorithm == 4:
return greedy_dfs_... | The main task of the code is to test a planning algorithm by executing its generated action sequence on a start state, then verifying if the resulting state satisfies the goal condition and printing the outcome along with the simulated time. | def test(algorithm, start_state):
print("\n\n testing:",start_state)
# call plan function
sequence = plan(algorithm, start_state)
print("\t found sequence:",sequence)
# apply plan to start state
state = start_state
for action in sequence:
state = state_transition(state,action)
... |
def get_rectangles(image, scales = [1, 1.5, 2, 2.5, 3],
ystarts = [400, 400, 450, 450, 460],
ystops = [528, 550, 620, 650, 700]):
global svc, X_scaler, orient, pix_per_cell, cell_per_block, spatial_size, hist_bins
out_rectangles = []
for scale, ystart, ystop in zip(s... | The code detects vehicles in an image by generating a heatmap from potential vehicle rectangles, applying a threshold to filter noise, labeling regions, and drawing bounding boxes around detected vehicles. It returns the original image with labeled vehicles or the original if none are found. | def find_vehicles(image):
rectangles = get_rectangles(image)
if not rectangles or len(rectangles) == 0:
return image
heatmap_image = np.zeros_like(image[:, :, 0])
heatmap_image = add_heat(heatmap_image, rectangles)
heatmap_image = apply_threshold(heatmap_image, 2)
labels = label(heatmap... |
def load(data_file):
global svc, X_scaler, orient, pix_per_cell, cell_per_block, spatial_size, hist_bins, detection_info
dist_pickle = pickle.load(open(f"{data_file}", "rb" ))
svc = dist_pickle["svc"]
X_scaler = dist_pickle["scaler"]
orient = dist_pickle["orient"]
pix_per_cell = dist_p... | The code processes video or image files using a preloaded model, handling input/output paths. It checks if input directories exist, creates output directories if needed, and applies `process_video` or `process_image` based on the input type. The script validates arguments, ensures directory existence, and outputs proce... | def main():
args = sys.argv
try:
in_type = str(args[1])
in_path = str(args[2])
out_path = str(args[3])
# check if the input directory exists or not
(in_dir, in_file) = os.path.split(in_path)
in_dir = os.path.relpath(in_dir)
if not os.path.exists(in_dir):
... |
def _can_evaluate(self):
"""
One annoying thing about the logger table is that the keys at each
iteration need to be the exact same. So unless you can compute
everything, skip evaluation.
A common example for why you might want to skip evaluation is that at
the beginning... | This function performs evaluation at each epoch if conditions are met, logs training metrics (steps, timesteps, rollouts), timing data (train/sample/eval durations), and ensures consistency in logged table keys. It records epoch progress and total training time, then dumps tabular logs. If evaluation isn't possible, it... | def _try_to_eval(self, epoch):
# logger.save_extra_data(self.get_extra_data_to_save(epoch))
if self._can_evaluate():
self.evaluate(epoch)
params = self.get_epoch_snapshot(epoch)
# logger.save_itr_params(epoch, params)
table_keys = logger.get_table_key_set... |
def pretrain(self):
"""
Do anything before the main training phase.
"""
pass
def get_epoch_snapshot(self, epoch):
data_to_save = dict(epoch=epoch, exploration_policy=self.exploration_policy)
if self.save_environment:
data_to_save["env"] = self.training_env
... | This code implements a meta-training loop for a reinforcement learning agent. It pretrains the model, collects data from multiple tasks (using prior/posterior distributions), performs gradient updates on parameters, and evaluates performance iteratively. The core tasks involve data collection, relabeling statistics com... | def train(self):
"""
meta-training loop
"""
self.pretrain()
params = self.get_epoch_snapshot(-1)
# logger.save_itr_params(-1, params)
gt.reset()
gt.set_def_unique(False)
self._current_path_builder = PathBuilder()
# at each iteration, we fi... |
def __random_placement(self):
'''
Loops through the list of ships and randomly place them on board
'''
ships = list_of_ships.copy()
while ships:
ship = ships.pop(0)
self.player.board.random_placement(ship())
self.computer.board.random_placemen... | The main task of the code is to initialize a game by setting up player and computer objects, handling board placement (random or manual), and initiating the game loop. It clears the console, creates players, manages board placement based on user input, and starts the game. | def __init_game(self):
'''Game entry point'''
os.system('cls||clear')
self.player = Player(choose_name())
self.player.add_new_board()
self.computer = Computer(self.player.name)
self.computer.add_new_board()
print(f'Name is {self.player.name}')
placemen... |
def rand_coord(self):
'''Returns a random coord from self.fog'''
return self.fog[random.randrange(len(self.fog))]
def is_empty(self, x, y):
'''
Checks if the coordinate is empty
Returns False if not, otherwise True
'''
if (x, y) in self.get_occupied_coords():
... | This function randomly places a ship on a game board by selecting an empty coordinate and a direction, recursively retrying if placement fails. It validates the ship's position, updates the board with the ship's coordinates, adds the ship to a set, and marks its positions. If the ship cannot be placed in any direction,... | def random_placement(self, ship, hide=False):
'''
Place a ship on the board in a random position
Will call itself recursively if unable to place ship and try again
with another random position
If finds a suitable position, place the value(s) on the board
Also adds ship to... |
def _get_incremental_data(self):
"""Helper function to get incremental data for processing"""
try:
dbutils = self._get_dbutils()
spark = self._get_spark()
logging.info("Entered incremental/latest process read mode")
filepath = self._filepath
... | The function `_load` determines the data loading strategy based on `self._process_type_load`. If set to 'incremental', 'latest', or 'full', it triggers incremental data loading via `_get_incremental_data()`. Otherwise, it skips incremental mode and uses Spark to read data from a specified path with given file format an... | def _load(self) -> DataFrame:
"""Helper function which gets called while reading a dataset via kedro"""
logging.info("Entering load function")
if self._process_type_load is not None and (
self._process_type_load.lower() == "incremental"
or self._process_type_load.lower()... |
def print_maxpool(max_pool, start_z, end_z, input_shape):
color = max_pool.get("color", "red")
shape = max_pool["output_shape"]
x1 = process_dimension(FACTOR_X, input_shape[0])
y1 = process_dimension(FACTOR_Y, input_shape[1])
z1 = start_z
x2 = process_dimension(FACTOR_X, shape[0])
y2 = proce... | This function iterates through neural network layers in reverse order, generating code snippets for each layer type. It specifically handles Maxpool layers by validating preceding CNN layers and printing associated code, while CNN layers are annotated based on output shape changes. Other layer types use a generic print... | def print_all_layers(layers, zs):
for i in range(len(layers) - 1, -1, -1):
layer = layers[i]
layer_type = layer["type"]
if layer_type == "maxpool":
if i < len(layers) - 1:
prev_layer = layers[i - 1]
if prev_layer["type"] == "conv":
... |
def load_data_json(filename):
json_data = None
with open(filename) as json_file:
json_data = json.load(json_file)
return json_data
def get_layer_zs(layers):
zs = []
curr_z = 0
for i in range(len(layers)):
layer = layers[i]
layer_type = layer["type"]
zs.append(curr... | The main task of the code is to generate a LaTeX TikZ diagram of a neural network from a JSON file. It reads the network architecture, processes layer positions, and outputs formatted LaTeX code with figure environment, TikZ picture, and optional caption/label, converting the JSON-defined structure into a visual repres... | def build_nn_from_file(filename):
json_data = load_data_json(filename)
layers = json_data["architecture"]["layers"]
zs = get_layer_zs(layers)
print("\\begin{figure}")
print("\\centering")
print("\\begin{tikzpicture}[x={(0.5pt,-0.5pt)},y={(0pt,1pt)},z={(1pt,0pt)},thick]")
print_all_layers(lay... |
def computehomography(listOfPairs):
A = []
B = []
for pair in listOfPairs:
y = pair[0][0]
x = pair[0][1]
y_ = pair[1][0]
x_ = pair[1][1]
A.append([y, x, 1, 0, 0, 0, -y*y_, -x*y_])#, -y_])
A.append([0, 0, 0, y, x, 1, -y*x_, -x*x_])#, -x_])
B.append(y_)
... | The code stitches two images (im1 and im2) using homography computed from a list of point pairs. It calculates the bounding box for the combined image, applies translation matrices, and composites the images by warping im2 onto im1 with a black background, resulting in a seamless panorama. | def stitch(im1, im2, listOfPairs):
# (1) compute homography
H = computehomography(listOfPairs)
# (2) compute bounding box and translation matrix
# use im1 as reference
bbox2 = computeTransformBBox(im2, linalg.inv(H))
I = array([array([1, 0, 0]), array([0, 1, 0]), array([0, 0, 1])])
bbox1 = ... |
def computehomography(listOfPairs):
A = []
B = []
for pair in listOfPairs:
y = pair[0][0]
x = pair[0][1]
y_ = pair[1][0]
x_ = pair[1][1]
A.append([y, x, 1, 0, 0, 0, -y*y_, -x*y_])#, -y_])
A.append([0, 0, 0, y, x, 1, -y*x_, -x*x_])#, -x_])
B.append(y_)
... | The main task of the code is to stitch multiple images into a seamless panorama by computing homographies between adjacent images, determining a unified bounding box, and compositing the transformed images using calculated transformations. It uses a reference image as a starting point, computes forward and backward hom... | def stitchN(listOfImages, listOfListOfPairs, refIndex):
# pair = im_i and im_i+1
# (1) compute homographies, H[i] = im[i]&im[i-1]
I = array([array([1, 0, 0]), array([0, 1, 0]), array([0, 0, 1])])
listOfH = []
for i in range(len(listOfImages)):
listOfH.append(0)
listOfH[refIndex] = I
... |
def get_model(self):
self.sock.send(pickle.dumps("get"))
self.model,self.layer_info=pickle.loads(self.sock.recv())
self.model.train()
self.row_states=[]
self.row_number=0
for i in range(len(self.layer_info)):
rows=[]
self.row_number+=len(self.layer... | The code trains a machine learning model over an epoch, tracking metrics like loss, accuracy (top1/top5), and timing. It adjusts learning rates, computes gradients, and synchronizes with other processes via sockets. Key tasks include measuring data/loading times, performing forward/backward passes, enforcing time const... | def train(self, epoch, start_time):
bar = Bar('Processing', max=self.train_loader_len)
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
end = time.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.