dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def closeShape(x, y):
newPoint = Point(x, y)
if (len(points) == 0):
points.append(newPoint)
elif (len(points) == 1):
newLine = Line(points[len(points) - 1], newPoint)
points.append(newPoint)
lines.append(newLine)
drawLine(grid, newLine)
else:
newLine = Lin... | This code defines a Pygame loop handling user input to create and close shapes. It limits FPS, processes keyboard/mouse events to build shapes, captures impulse positions on Enter, and outputs the final shape data. The loop clears the grid, updates the display, and exits gracefully on quit or Enter, ensuring consistent... | def programLoop():
global shapeOut
global impulsePosition
fpsLimit = 60
runMe = True
while runMe:
# Limit the framerate
clock.tick(fpsLimit)
# Clear the grid by filling all white
if (len(points) == 0):
grid.fill(white)
# Event handler
for... |
def get_covid_numbers(country):
"""Get covid numbers in country from last week
return: cases, dates | both in list format
"""
global cases, dates, recovered, total_cases, total_recovered, total_deaths
# using postman API
url = "https://api.covid19api.com/dayone/country/{}".format(country)
tr... | The code fetches the latest 7-day COVID-19 cases, dates, and recovered numbers for a selected country from a combo box, then visualizes this data in a chart and updates related GUI elements. | def click(event):
country = combo_Box.get()
cases, dates, recovered = get_covid_numbers(country)
lw_cases = cases[-7:]
lw_dates = dates[-7:]
lw_recovered = recovered[-7:]
chart_to_gui(lw_cases, lw_dates, lw_recovered)
values(country) |
def getName():
taskName = input("Type the name of the task and hit enter: ")
return taskName
def getDate():
month = getMonth()
day = getDay()
year = getYear()
newDate = date(year, month, day)
return newDate
def getPrio():
prio = int(input("Enter the priority of the task (1-LOW priority, ... | The function `changeSelector` updates a task's attributes based on user selection. If the selection is "Change name," "Change date," or "Change priority," it retrieves the new value via corresponding functions and updates the task. If the selection is unrecognized, it prints "Quitting." and returns `True`. Otherwise, i... | def changeSelector(task, selection):
if (selection == "Change name"):
taskName = getName()
task.updateName(taskName)
elif (selection == "Change date"):
newDate = getDate()
task.updateDate(newDate)
elif (selection == "Change priority"):
prio = getPrio()
task.... |
def confirmation(title):
options = ["Yes", "No"]
return displayMenu(options, title)
def getDictTask(task):
return({"name": task.returnName(), "month": task.returnDate().month,
"day": task.returnDate().day, "year": task.returnDate().year,
"prio"... | This function handles adding or editing a task by displaying its information, prompting user confirmation, and allowing modifications through a menu. If confirmed, it executes the operation (add/edit) using service parameters and updates task data. If not confirmed, it lets users adjust specific fields like name, date,... | def editAddLoop(service, option, task1, task2):
old_values = {}
new_values = {}
done = False
while (done == False):
task1.printTaskInfo()
message = "Is this information correct?"
if (confirmation(message) == "Yes"):
if(option == "Edit"):
old_values = g... |
def check_fleet_edges(settings, aliens):
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(settings, aliens)
break
def check_aliens_bottom(settings, stats, screen, ship, aliens, bullets):
screen_rect = screen.get_rect()
for alien in aliens.sprites(... | The function `update_aliens` manages alien behavior in a game. It checks if aliens have reached screen edges, updates their movement, verifies if any aliens have reached the bottom (triggering game-over logic), and detects collisions between the player's ship and aliens. If a collision occurs, it triggers the `ship_hit... | def update_aliens(settings, stats, screen, ship, aliens, bullets):
check_fleet_edges(settings, aliens)
aliens.update()
check_aliens_bottom(settings, stats, screen, ship, aliens, bullets)
if pg.sprite.spritecollideany(ship, aliens):
ship_hit(settings, stats, screen, ship, aliens, bullets) |
def get_gps_location():
""" () -> float, float
Calls get_valid_coordinate function to get the latitude and longitude
Returns two floats for the coordinates
>>> get_gps_location()
What is your latitude ?45.51
What is your longitude ?-73.56
(45.51, -73.56)
>>> get_gps_location()
What ... | The code defines a `vessel_menu` function that manages a boat-related menu system. It retrieves GPS coordinates and boat dimensions, then lets users check safety at the current location, verify passenger capacity based on boat size, or update the boat’s position after a wave impact. The loop continues until the user ex... | def vessel_menu():
""" () ->
Void function that runs the menu and allows user to check the safety
of the boat, if the boat can hold the number of passengers and
update the position of the boat
"""
print("Welcome to the boat menu!")
[lat, long] = get_gps_location()
print("Your current po... |
def position_direction_word(letter_list, word):
"""(list[str], str) -> list[list[int]]
returns a nested list of the position and direction of the word
>>> el = ["A","B","C","D","E","D"]
>>> position_direction_word(el, "ABC")
[[0, 1]]
>>> el = ["A","B","C","D","E","D"]
>>> position_direction... | The function identifies a "magic word" by checking which words from the input list can be formed using the given letters, considering their positions and directions. It processes each word to determine valid placements, then constructs the magic word by combining valid segments from the letter list, returning the resul... | def word_search(letter_list, word_list):
"""(list[str], list[str]) -> str
Finds the word from a list of characters and a list of words
>>> letter_list = ["H", "G", "I", "L", "E", "R", "T", "O"]
>>> word_list = ['G','LERTO']
>>> word_search(letter_list, word_list)
HI
>>> letter_list = ['... |
def step_up(self) -> bool:
""" take a step to the left, if possible"""
if not self.can_go_up:
return False
to_x = self.pos_x
to_y = self.pos_y - 1
return self._move(to_x, to_y)
def step_down(self) -> bool:
""" take a step to the left, if possible"""
if... | The function `trace_path` executes a sequence of movement actions (up, down, left, right) in a maze, tracing the path taken. It optionally resets on falling into holes or halts upon reaching the goal. It returns an ASCII maze representation with the path marked, restoring original drawing settings after execution. | def trace_path(self, actions: list[str],
autoreset_on_holes: bool = True,
autohalt_on_goal: bool = True) -> str:
""" runs the sequens of actions as passed and returns
a representation of the maze with the path marked out
actions are:
"lef... |
def getAllPossibleMoves(self):
moves = []
# Nested for loop to traverse every element in the 2D list
for row in range(len(self.board)): # Number of rows on the board
for column in range(len(self.board[row])): # Number of columns in the given row
turn = self.board[row... | The code generates all possible moves, validates them by checking if they leave the king in check, removes invalid moves, and determines checkmate/stalemate. It iterates backward through moves, simulates each, checks for opponent attacks, and undoes changes to maintain board state. | def getValidMoves(self):
# 1. Generate all possible moves
moves = self.getAllPossibleMoves()
# 2. For each move, make a move
for i in range(len(moves) - 1, -1, -1): # When removing from a list, go backwards through the list
self.makeMove(moves[i])
# 3. Generate ... |
def propogateRange(self, X, doClear=True):
output = []
c = 0
for i in X:
if doClear: self.clear()
# If it's recurrent data, propogate each one, not clearing
# Not clearing means that the recurrent layer will recur
if type(i) == np.ndarray and i.ndi... | This function iterates over pairs of accumulated gradients (accs) and input data (X), performing forward propagation on each input, backpropagating gradients using the corresponding accumulated values, and then clearing internal state. It processes each data-sample-gradient triplet to update model parameters during tra... | def backpropogateRange(self, accs, X):
for acc, x in zip(accs, X):
self.propogateRange([x])
self.prop_backprop(acc)
self.clear() |
def showStatus():
global opcode, currentOp, currentInst
global operand, accum
print("\n\n\n -------------------------------------------------------------------\n ========================= status = " + statStr[status] + "==========================")
print(''' ------------------------------------... | This function simulates a basic fetch-decode-execute instruction cycle for a simple CPU. It fetches instructions from memory using the program counter (progCntr), decodes opcodes and operands, executes instructions via doInstruction(), updates the program counter, and handles memory boundary checks. The loop continues ... | def runProg():
global progCntr, nextPC
global status
global opcode, currentInst
global operand, currentOp
progCntr = 0
status = 1
while(status == 1):
currentOp = "load Instruction Register"
instructionRegister = memory[progCntr]
opcode = instructionRegi... |
def __assert_machine_values(self, machine_id):
machine_values = list(range(1, self.machines_number+1))
assert machine_id in machine_values, (
f"machine_id should be one of the values {machine_values},"
f" but machine_id={machine_id}")
def __assert_date(self, date):
assert... | The function determines if a machine should run on a specified date by checking if its ID exists in a list of machines scheduled for that date. It validates the machine ID and date, retrieves the list of active machines for the date, and returns True if the machine ID is present, otherwise False. | def check_should_run_date(self, date, machine_id):
"""Checks if the machine should run in a date.
Parameters
----------
date: datetime.datetime
Date to check.
machine_id: int
The number that identifies the machine.
Return
... |
def __assert_machine_values(self, machine_id):
machine_values = list(range(1, self.machines_number+1))
assert machine_id in machine_values, (
f"machine_id should be one of the values {machine_values},"
f" but machine_id={machine_id}")
def __assert_date(self, date):
assert... | This function determines if a machine should run during a specific hour by validating inputs, checking the date, and verifying the timesheet entry for that hour. It calculates the relevant time range, retrieves the timesheet data, and compares the machine ID with the hourly entry. | def check_should_run_hour(self, date, machine_id):
"""Checks if the machine should run in a hour.
Parameters
----------
date: datetime.datetime
Date to check.
machine_id: int
The number that identifies the machine.
Return
... |
def getStatistic(predicted, observed, statistic):
""" Calculates and returns the statistic of the predicted vs observed, specified by statistic """
if statistic == "RMSE":
return rmse(predicted, observed)
elif statistic == "NMB":
return nmb(predicted, observed)
elif statistic == "NME":
... | The function generates a dataframe containing statistical metrics (e.g., RMSE, NMB, NME) comparing predicted values from multiple models to observed data. It calculates these statistics, their 95% confidence intervals, and optionally time-specific results for given intervals. Model names are used as the dataframe's ind... | def getStatDF(predictedList, observed, names=None, timestampIndex=None, timesToTest=None, statsList=["RMSE", "NMB", "NME"]):
"""
Generates a dataframe with different statistical values
@param: predictList - the list of predictions from different models
@param: ovserved - the observed values to compar... |
def _verify_time(self):
time_now = int(
datetime.timestamp(
datetime.now()
)
)
deleted_time = self._dns_message.time_to_live \
+ self._dns_message.added_time
if deleted_time <= time_now:
return False
else:
... | The code handles DNS response generation. It checks if a record exists in the database and if the time is valid. If true, it builds and updates the response. Otherwise, it fetches an authority request, processes it, saves data, and returns the DNS response. | def response(self):
dns_response: bytes = None
if self._is_record_in_db and self._verify_time():
dns_response = self._build_response()
self._update()
else:
dns_response = self._make_authority_request()
print(dns_response)
self._data_rec... |
def card_ranks(hand):
'''Return a list of the ranks, sorted with higher first.'''
ranks = ['--23456789TJQKA'.index(r) for r, s in hand]
ranks.sort(reverse = True)
return [5, 4, 3, 2, 1] if (ranks == [14, 5, 4, 3, 2]) else ranks
def straight(ranks):
'''Return True if the ordered ranks form a 5-card s... | The function calculates the probability of a given poker hand by evaluating its rank (e.g., straight flush, four of a kind, full house, etc.) using combinatorial mathematics. It returns the probability as a fraction of total 5-card hands, with numerators derived from combinations of ranks and suits, and denominators fi... | def probability(hand):
'''Returns the probability of the hand'''
ranks = card_ranks(hand)
if straight(ranks) and flush(hand):
return (comb(10,1) * comb(4,1) - comb(4,1)) / comb(52,5)
elif kind(4, ranks):
return (comb(13,1) * comb(12,1) * comb(4,1)) / comb(52,5)
elif kind(3, ranks) a... |
def white_can_castle(board):
return board[8, 1, 0] == 1
def castle_king_side(board, colour):
'''
Castles kingside given a colour. Returns None on failure
TODO: Proper exception, optimize if else branching
Again a big assumption here is that this move is LEGAL to play
'''
if colour == 'w':
... | This function handles castling moves for both white and black pieces on a chessboard. If the move indicates a castling (e.g., 'e1g1' for white king-side), it executes the corresponding castling function. Similarly, it checks for black castling moves (e.g., 'e8g8'). If the move isn't a castling, it proceeds to play the ... | def play_move_on_np_board(board, move):
move_str = str(move)
if white_can_castle(board) and (move_str == 'e1g1' or move_str=='e1c1'):
# Then king is castling. Error handling:
if move_str == 'e1g1': # yes, I know i check twice. Live with it.
castle_king_side(board, 'w')
else:
... |
def _spi_flash_read(self, address, size) -> bytes:
assert size <= 0x1d
argument = address.to_bytes(4, "little") + size.to_bytes(1, "little")
ack, report = self._send_subcmd_get_response(b'\x10', argument)
if not ack:
raise IOError("After SPI read @ {address:#06x}: got NACK")
... | The main task of the code is to read and process calibration data from a Joy-Con's SPI flash memory. It retrieves color data, deadzone values, and IME (inertial measurement unit) calibration parameters, distinguishing between user-provided and factory-default settings. The data is stored for later use in color identifi... | def _read_joycon_data(self):
color_data = self._spi_flash_read(0x6050, 6)
self.color_body = tuple(color_data[:3])
self.color_btn = tuple(color_data[3:])
self._read_stick_calibration_data()
buf = self._spi_flash_read(0x6086 if self.is_left() else 0x6098, 16)
self.deadzon... |
def set_accel_calibration(self, offset_xyz=None, coeff_xyz=None):
if offset_xyz and coeff_xyz:
self._ACCEL_OFFSET_X, self._ACCEL_OFFSET_Y, self._ACCEL_OFFSET_Z = offset_xyz
cx, cy, cz = coeff_xyz
self._ACCEL_COEFF_X = (1.0 / (cx - self._ACCEL_OFFSET_X)) * 4.0
sel... | This code initializes a Joy-Con controller by validating the provided vendor and product IDs, setting up internal state variables, connecting to the device, configuring sensors, and starting a daemon thread to handle input reports. It ensures proper device identification and prepares the controller for data processing ... | def __init__(self, vendor_id: int, product_id: int, serial: str = None, simple_mode=False):
if vendor_id != JOYCON_VENDOR_ID:
raise ValueError(f'vendor_id is invalid: {vendor_id!r}')
if product_id not in JOYCON_PRODUCT_IDS:
raise ValueError(f'product_id is invalid: {product_id!r... |
def refresh(self):
for row in range(self.rows):
for col in range(self.cols):
self.cell_clr[row][col] = self.cell_clr1[row][col]
self.update_board_clr(self.cell_clr)
self.board.clr_res()
def handle_evidence(self, row, col):
cur_dis = abs(row - self.ghost_r) + ... | This function handles user clicks on a grid. It checks if the click is within bounds, then either reveals evidence or a ghost based on the 'catch' state. Special cases handle time advancement and toggling the 'catch' flag, updating the UI each time. | def handle_click(self, row, col):
if 0<=row<self.rows and 0<=col<self.cols:
if self.catch == 0:
self.refresh()
self.handle_evidence(row, col)
else:
self.refresh()
self.reveal_ghost(row, col)
self.catch = 0
... |
def roll_east(lines):
return [roll_line_east(l) for l in lines]
def roll_south(lines):
return transpose_listgrid(roll_east(transpose_listgrid(lines)))
def roll_west(lines):
return [roll_line_west(l) for l in lines]
def roll_north(lines):
return transpose_listgrid(roll_west(transpose_listgrid(lines))) | The main task of the code is to perform a sequence of directional rolls on input lines: first rolling north, then west, followed by south, and finally east. This creates a cyclic transformation of the lines by applying four consecutive rotation operations in a specific order. | def do_a_cycle(lines):
return roll_east(roll_south(roll_west(roll_north(lines)))) |
def seed_user_messages(self, messages: list[str]):
self.state["messages"] = []
for m in messages:
self.add_user_message(m)
def enrich_user_message(message: str, content: list[str]):
"""
Add retrieved information into message.
"""
as_string = "\n".join(content)
return f"{m... | The main task of the code is to initialize a chat context for an NBA team by resetting the agent's memory, loading team data, and seeding the conversation with a predefined message about the selected team. It updates the session state, ensures the correct team is selected, and prepares the agent with relevant datasets ... | def set_chat_context(self):
"""
Creates a clean context for chat.
Mutates st.session_state and the agent as side effects.
Probably should be a closure to make this a pure function?
"""
logger.info(f"team_picker {self.team_picker} current_team {self.team}")
if sel... |
def sha1_auth(message):
secret = b'nodarius123'
return sha1(secret + message)
def md_padding_with_mlen(length):
return md_padding(b'a' * length)
def sha1_modified(message, h0, h1, h2, h3, h4, prefix_length):
message += md_padding_with_mlen(len(message) + prefix_length)
for i in range(0, len(message)... | The code attempts to forge a valid SHA-1-based message authentication code (MAC) by appending ";admin=true" to a message. It iterates through possible padding lengths, computes the modified hash using initial hash values, and checks if the forged message's hash matches the original. If a match is found, it prints "succ... | def main():
original = b'comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon'
sha1hash = sha1_auth(original)
a = int(sha1hash[0:8], 16)
b = int(sha1hash[8:16], 16)
c = int(sha1hash[16:24], 16)
d = int(sha1hash[24:32], 16)
e = int(sha1hash[32:40], 16)
for sec_le... |
def load_dataset(user):
training_list = list() # dictionary of all training dataframes [1..40]
testing_dict = {'skilled': [], 'genuine': [], 'random': []} # dictionary of all testing dataframes [41..56]
training_fs_list = list() # list of training dataframes (feature selection) [alltrain - validation]
... | The code evaluates different training configurations on user data from 'features_HMM.csv', computes Equal Error Rates (EER) for multiple experiments (a-p), and visualizes average EER results in two plots. It loads datasets, tests models with varying parameters (n_mix, n_comp), stores results, and plots grouped EER comp... | def testing():
exp = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
results = dict()
for i in exp:
results[i] = [None] * N_USERS
with open('features_HMM.csv', mode='r') as feature_file:
feature_reader = csv.reader(feature_file, delimiter=',', quotecha... |
def bw(
self,
*args,
ignore_errors: bool = False,
envs: typing.Optional[typing.Dict[str, str]] = None,
) -> typing.Tuple[int, str, str]:
if envs is not None:
self._update_bw_environment(envs)
exit_code, stdout, stderr = self._bw.run(args=args, retcode=None... | This method attempts to log into Bitwarden using the 'bw' CLI tool. It first checks if already logged in, then logs out if needed. Depending on available credentials (API key, password, or password file), it executes corresponding 'bw login' commands. It handles errors from the CLI tool or other exceptions, logs them, ... | def login(self):
error_message = None
exception = None
self.__log.info('Logging into Bitwarden...')
try:
self.__log.debug('Check if login already performed')
code, out, err = self.bw('login', '--check', ignore_errors=True)
self.__log.debug('Check artif... |
def login(self):
error_message = None
exception = None
self.__log.info('Logging into Bitwarden...')
try:
self.__log.debug('Check if login already performed')
code, out, err = self.bw('login', '--check', ignore_errors=True)
self.__log.debug('Check artif... | This code retrieves secrets (login credentials) from Bitwarden by listing items, handling empty responses with retry logic, parsing JSON output, and structuring results into a CredentialsContainer with name, username, and password fields extracted via JMESPath. | def get_secrets(self):
retries = 5
self.login()
self.sync()
self.__log.info('Loading the secrets from Bitwarden')
args = ['list', 'items']
if self.__collection_id:
args.extend(['--collectionid', self.__collection_id])
out = self.bw_simple_with_key(*arg... |
def get_variable_coef_map(exp): # return which variables are associated with the expression
global coef_variable_map_table
left_exp = str(exp.arg(0))
coef_variable_map = {}
#print(exp)
var = left_exp.split("+")
index = []
#print("var = ", var)
for variable in var:
num_start = 1
... | The code processes an expression `exp` by extracting its sub-expression (`exp1`), generating an automata table for `exp1`, applying a NOT operation to the table, and printing both the original and modified tables. The main task is to transform a logical expression's automata table by negating its states, likely for for... | def parse_not(exp, n):
print("Inside Not with exp = ", exp)
#print(exp.children())
exp1 = exp.arg(0) # getting the expression without Not keyword
n = len(get_variable_coef_map(exp1))
table = get_automata_table(exp1, n)
print("table without Not = ")
print_table(table)
new_table = (create... |
def get_automata_table(exp, n):
global binary, coefficients
coefficients = []
left_variables = []
table = []
binary = []
#print("n = ", n)
print("expression = ", str(exp))
# generating the binary combinations
for i in range(2 ** n):
binary.append(padded_bin(i, n)[2:])
# ... | The main task of the code is to process an expression by generating an automata table using `get_automata_table`, mapping variables to coefficients via `get_variable_coef_map`, and printing the resulting table. This likely involves parsing or analyzing the expression `exp` with parameter `n`, extracting variable-coeffi... | def Q1_atomic_expression():
table = get_automata_table(exp, n)
get_variable_coef_map(exp)
print_table(table) |
def get_variable_coef_map(exp): # return which variables are associated with the expression
global coef_variable_map_table
left_exp = str(exp.arg(0))
coef_variable_map = {}
#print(exp)
var = left_exp.split("+")
index = []
#print("var = ", var)
for variable in var:
num_start = 1
... | The function evaluates a logical AND operation between two expressions, handling potential NOT operators in each sub-expression. It processes each expression's automata table, computes their results, applies NOT if present, and combines the results with an AND operation, printing intermediate steps and the final outcom... | def parse_and(exp, n):
print("And")
ch = 0
exp1 = exp.arg(0)
exp2 = exp.arg(1)
not_index = []
if(exp1.decl().name() == "not"):
ch = ch - 1
if (exp2.decl().name() == "not"):
ch = ch + 2
if ch == 0:
RHS1 = int(str(exp1.arg(1)))
RHS2 = int(str(exp2.arg(1)))
... |
def parse_and(exp, n):
print("And")
ch = 0
exp1 = exp.arg(0)
exp2 = exp.arg(1)
not_index = []
if(exp1.decl().name() == "not"):
ch = ch - 1
if (exp2.decl().name() == "not"):
ch = ch + 2
if ch == 0:
RHS1 = int(str(exp1.arg(1)))
RHS2 = int(str(exp2.arg(1)))
... | The function evaluates logical expressions (AND, NOT) using truth tables. It maps variables to values, processes expressions based on their type, computes results, and prints outcomes. For "and", it uses `parse_and`; for "not", it evaluates the sub-expression, negates the result, and prints both intermediate and final ... | def Q4_solving_function():
global exp, n, values, value_map
for i in range(1,n+1):
value_map[i] = values[i-1]
if exp.decl().name() == "and":
table = parse_and(exp, n)
else:
if exp.decl().name() == "not":
table = parse_not(exp, n)
var_index = []
... |
def supported_shells():
return sorted(set([x.split('_')[0] for x in supported_oneliners.keys()]))
def get_description_for(shell):
udp_support = ''
win_support = ''
desc = 'One-liner for {0}{1}{2}'
if has_udp_support(shell):
udp_support += ' | Supports UDP'
if has_win_support(shell):
... | The code parses command-line arguments for generating reverse shell one-liners, validating inputs like IP, port, protocol (TCP/UDP), and platform (Windows). It checks supported shells, protocol compatibility, and platform-specific scripts, then returns a configured `OneLiner` object with the selected parameters. | def parse_arguments():
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
description='''Yet another one-liner reverse shell generator script,
based on PayloadAllTheThings reverse shells''',
epilog='''
Examples:
1. Simple bash tcp reverse shell:
./rs_oneliner.py -i 127.0.... |
def GeomertyCentered(self, w, h):
x = (self.window.winfo_screenwidth() - w) / 2
y = (self.window.winfo_screenheight() - h) / 2
self.window.geometry('%dx%d+%d+%d' % (w, h, x, y))
def TextFrame(self):
notesseract_text = utils.GetNoTesseractText()
self.tPanelText = customtkinter.CTk... | This code initializes a GUI application for an OCR tool by creating a non-resizable window titled "OCR Tool," centering it on the screen, setting up text and button frames, handling window close events, and launching the main event loop to display the interface. | def __init__(self):
self.window = OT_TK()
self.GeomertyCentered(376,376)
self.window.resizable(False, False)
self.window.title("OCR Tool")
self.TextFrame()
self.ButtonsFrame()
self.window.protocol("WM_DELETE_WINDOW", self.on_close)
self.window.mainloop() |
def tail(data):
x,y=ecdf_points(data)
return x, 1-y
def get_power_law_fit(data,x_min):
data_s=np.sort(data)
x,y=tail(data_s)
ind=find_nearest(data_s,x_min)
ind1=find_nearest(x,x_min)
x_sample=data_s[ind:]
x1=x[ind1:]
b=mle_pl_beta(x_sample,x_min)
a=y[ind1]*x_min**b
y_pred=pow... | The function determines the optimal x_min by minimizing the Kolmogorov-Smirnov statistic between normalized data and power-law fits. It iterates over possible x_min values, computes power-law fits, normalizes data, calculates KS statistics, and returns the minimum KS value and corresponding x_min. | def x_min_pred(data):
es1=[]
x,y=tail(data)
for i in range(len(x)-2):
xs,ys,a,b=get_power_law_fit(data,x[i])
y_norm=y[i]
yn=y[i:]/y_norm
ysn=ys/y_norm
e1=KS_stat(yn,ysn)
es1.append(e1)
ind1=np.argmin(es1)
x_min_pred=x[ind1]
return es1,x_min_pred |
def tail(data):
x,y=ecdf_points(data)
return x, 1-y
def get_power_law_fit(data,x_min):
data_s=np.sort(data)
x,y=tail(data_s)
ind=find_nearest(data_s,x_min)
ind1=find_nearest(x,x_min)
x_sample=data_s[ind:]
x1=x[ind1:]
b=mle_pl_beta(x_sample,x_min)
a=y[ind1]*x_min**b
y_pred=pow... | This function identifies the optimal x_min within a specified interval [x_l, x_u] by minimizing the Kolmogorov-Smirnov (KS) statistic from power-law fits. It sorts data, validates the interval, computes KS values for candidate x_min values in the range, and returns the x_min with the smallest KS statistic and correspon... | def x_min_pred_interval(data,x_l,x_u):
data=np.sort(data)
if (x_l>=data[0] )& (x_u<data[-2]):
es1=[]
x,y=tail(data)
ind=np.where((x_l<=x) & (x<=x_u))[0]
for i in ind:
xs,ys,a,b=get_power_law_fit(data,x[i])
y_norm=y[i]
yn=y[i:]/y_norm
... |
def on_parse_begin(string):
pass
def _unexpected_end_of_input():
_parse_error('Unexpected end of input.')
def _unexpected_token(token):
if token['type'] == EOF:
_unexpected_end_of_input()
_tokenizer.throw_unexpected_token(
token['value'],
token['start_line'],
token['star... | This code parses an input string using a stack-based LR parser. It initializes a tokenizer, processes tokens via a state transition table, and applies grammar rules to reduce symbols. It handles shifts (adding tokens to the stack), reductions (applying production rules with semantic actions), and acceptance (returning ... | def parse(string):
global __, __loc, yytext, yyleng
on_parse_begin(string)
if _tokenizer is None:
raise Exception('_tokenizer instance wasn\'t specified.')
_tokenizer.init_string(string)
# Init the stack with start state 0.
stack = [0]
token = _tokenizer.get_next_token()
shi... |
def squareUnderAttack(self, r, c):
self.whiteToMove = not self.whiteToMove # switch to opponent's turn
oppMoves = self.getAllPossibleMoves()
for move in oppMoves:
if move.endRow == r and move.endCol == c: #square is under attack
return True
self.whit... | The code generates valid castling moves for a chess game by checking if the current square is under attack, verifying the player's castling rights (king/queen side), and invoking corresponding methods to add legal castling moves to the list. It ensures castling is only allowed when not in check and when the respective ... | def getCastleMoves(self,r,c,moves):
if self.squareUnderAttack(r, c):
return #can't castle while we are in check
if (self.whiteToMove and self.currentCastlingRight.wks):
self.getKingsideCastleMoves(r,c,moves)
elif (not self.whiteToMove and self.cu... |
def checkForPinsAndChecks(self):
pins = [] # squares where the allied pinned piece is and direction pinned from
checks = [] # squares where enemy is applying a check
inCheck = False
if self.whiteToMove:
enemyColor = 'b'
allyColor = 'w'
startRow = self... | The code generates valid chess moves for the current player, considering checks. If in check, it filters moves to block checks or capture attackers, or moves the king if double-checked. If not in check, it returns all possible moves and adds castling options. | def getValidMoves(self):
moves = []
self.inCheck, self.pins, self.checks = self.checkForPinsAndChecks()
if self.whiteToMove:
kingRow = self.whiteKingLocation[0]
kingCol = self.whiteKingLocation[1]
else:
kingRow = self.blackKingLocation[0]... |
def create_engine() -> None:
global engine
engine = sqlalchemy.create_engine('sqlite:///src\\static\\db\\database.db', echo=True)
pass
def get_id_last_printer_add():
global engine
if engine == None:
create_engine()
try:
global printers
s = printers.select().order_by(desc(... | The main task of the code is to save a printer's data into a database, including its model, sector, purchase date, and maintenance count. If the printer has maintenance records, it retrieves the last inserted printer's ID and saves the maintenance details. The function returns True on success or False if an error occur... | def save_printer(printer) -> bool:
global engine
if engine == None:
create_engine()
try:
global printers
stmt = printers.insert().values(model=printer.model,
sector=printer.sector,
date_purchased=printer.... |
def GetLatestBlockNumber():
response = get(GetLatestBlockURL())
data = response.json()
block_number = data["result"]
return block_number
def GetBlockURL(block_number):
url = BASE_URL + f"?module=block&action=getblockreward&blockno={block_number}&apikey={API_KEY}"
return url
def get_transactions(... | The main task of the code is to retrieve the latest blockchain block's details, including its number, timestamp, miner, and transaction data, by making API requests and returning them as a Block object. | def get_latest_block():
block_number = GetLatestBlockNumber()
response = get(GetBlockURL(block_number))
data = response.json()["result"]
block_miner = data["blockMiner"]
timestamp = data["timeStamp"]
transaction_response = get(get_transactions(block_number))
transaction_data = transaction_... |
def is_edge_between_islands(self, edge):
return edge.point1 in self.get_islands_positions() \
and edge.point2 in self.get_islands_positions()
def is_edge_interfering_with_edge(self, edge):
if edge.is_horizontal():
for vertical_edge in self.get_vertical_edges():
... | This function checks if an edge can be added based on specific conditions: ensuring it connects exactly two islands, doesn't interfere with existing edges, hasn't been added twice, and isn't connecting more than two islands. If all conditions are met, the edge is added and True is returned; otherwise, False is returned... | def add_edge_if_possible(self, edge):
if self.is_edge_between_islands(edge) \
and not self.is_edge_interfering_with_edge(edge) \
and not self.is_edge_between_more_than_two_islands(edge) \
and self.specific_edge_count(edge) < 2:
self.__add_edge(edge)
... |
def build_deck():
global deck
deck = []
while len(deck) > 0:
deck.pop(0)
values = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')
suits = ('Images/Hearts.jpg', 'Images/Diamonds.jpg', 'Images/Spades.jpg', 'Images/Clubs.jpg')
color = (255, 0, 0)
for i in range(len(su... | The code defines a Blackjack game interface using Pygame, initializing game states, handling user interactions (buttons), and managing transitions between main menu, rules, betting, and gameplay. It sets up the game window, loads assets, and processes events for actions like hitting, standing, and betting, while mainta... | def interface():
global width, height, counter, deck, player_hand, p_hand_val, hit, set, pos
global bet, hand_cash, bet_value, stand, b_hand_val, bot_hand, p_dis, b_dis, compare
global BetRatio, DoubleDown
width = 500
height = 400
win = pygame.display.set_mode((width, height))
mainbackground... |
def mathcer(self, user_name, user_comment, repo_name, pr_number, step=2):
pr_link = "https://www.github.com/"+repo_name+"/pull/"+str(pr_number)
## 1. match the bot keyword
if self.match_bot_tag(user_name) == 2:
self.bot_df.loc[self.bot_df.shape[0]] = dict(zip(self.bot_df.columns, [... | This code evaluates a bot identification model by classifying GitHub pull requests as bot or human activity. It iterates through input data, compares model predictions (classification_result) against known labels (ground_truth), and calculates precision, recall, and F1-score metrics. Finally, it saves the bot analysis ... | def run(self, df, step=4):
ground_truth = []
classificaiotn_result = []
for index, row in track(df.iterrows(), description="Bot identification...", total=df.shape[0]):
classificaiotn=self.mathcer(row["user"], row["comment_body"].lower(), row["repo_name"], row["pull_number"], step=s... |
def clean_mol(smiles: str, canonicalize: bool = True, flatten_stereochem: bool = False, neutralize: bool = True,
check_for_uncommon_atoms: bool = True, desalt: bool = True, remove_solvent: bool = True,
unrepeat: bool = True, sanitize: bool = True) -> (str, str):
""" Clean a SMILES string... | The code's main task is to clean a list of SMILES strings by parsing and validating them, handling failures, and returning successfully parsed molecules. It processes each SMILES, uses a progress bar if enabled, applies cleaning settings, logs successes/failures, and returns the cleaned list. | def clean(self, smiles: list[str], progressbar: bool = True) -> list[str]:
""" Clean a list of SMILES strings
:param smiles: SMILES that need cleaning
:param progressbar: toggles the progressbar
:return: a list of all successfully parsed SMILES strings
"""
if type(smiles... |
def logdata(logf,msg,printflag):
currTime=datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
if printflag == 1:
print(currTime + " - " + msg)
logf.write(currTime + " - " + msg + "\n")
logf.flush()
os.fsync(logf.fileno())
def sendEmail(emailAdd,logFile,errFile,errMsg,Subject,cursor1):
logdata(logFile,"Sending email to... | The main task of the code is to merge multiple Snowflake staging tables into a target table, handling environment-specific configurations (prod/stg/dev), retrieving secrets for authentication, resizing warehouses if needed, validating chunk counts, and logging errors. It connects to Snowflake, merges data, checks row c... | def mergeSFstgtable(dbName,schemaName,tblName,noPieces,logFile,errFile,envType,srcNumrows,cursor1,emailAdd,sfRole,sfWh):
logdata(logFile,"Now starting the SF merge process",0)
if configFile.Config.PRDSUFF in envType:
sfEnv = 'cisco.us-east-1'
#sfkeepToken='s.D3TQWMYhSw6fPdirrdIgxeiR.2LCYK'
sfkeepToken=configFil... |
def bfspossible():
visited_states.clear()
visited_states.add(final_state)
count = 1
fringe = deque()
fringe.append(Node())
while fringe:
v = fringe.popleft()
for d in possible_moves[v.state.find('0')]:
temp = make_move(v.state, d)
if temp not in visited_st... | The main task of the code is to generate random solvable puzzles, solve them using BFS, and print each puzzle's solution along with the path length from the start state to the solved state. It demonstrates BFS performance on multiple puzzles by calculating and displaying the number of possible states and solving time f... | def main():
#print("A possible solvable puzzle: " + make_puzzle(Node()))
print('Number of states possible: ' + str(bfspossible()))
listofpuzzles = randpuzzle(3)
for puzzle in listofpuzzles:
print('PUZZLE: ' + puzzle)
solved_node = bfssolve(Node(puzzle, None))
result = 'LENGTH: '... |
def getOrderRestaurant(request):
restaurant = ""
customer_exists = Customer.objects.filter(user_id = request.user.id).exists()
if customer_exists:
customer = Customer.objects.get(user_id = request.user.id)
order_qs = Order.objects.filter(customer_id=customer.id, ordered=False)
if ord... | The main task of the code is to handle a user's cart functionality by retrieving, updating, and displaying their pending order items. It processes POST requests to modify item notes, quantities, and order instructions, calculates the cart subtotal, and renders the cart page with dynamic context based on user authentica... | def cart(request):
context = {}
if request.user.id:
customer = Customer.objects.get(user_id = request.user.id)
context = {
'restaurant': getOrderRestaurant(request)
}
order_qs = Order.objects.filter(customer_id=customer.id, ordered=False)
if order_qs.exists():
... |
def get_restaurant_of_item(item):
menu = Menu.objects.get(id = item.menu_id_id)
restaurant = Restaurant.objects.get(id = menu.restaurant_id_id)
return restaurant
def load_restaurant_view(restaurant_id):
restaurant = Restaurant.objects.get(pk = restaurant_id)
menu_objs = list(Menu.objects.filter(rest... | The code adds an item to a user's shopping cart, ensuring it belongs to the same restaurant as existing items in the cart. It handles authenticated users by updating the database with quantities and associating items with an order, while non-authenticated users use session-based cart storage. The function checks for ex... | def add_to_cart(request, id, restaurant_id):
context = {}
if request.user.id:
customer = Customer.objects.get(user_id = request.user.id)
item = get_object_or_404(Item, id=id)
quantity = int(request.POST['quantity'+ str(item.id)])
restaurant = get_restaurant_of_item(item)
... |
def getOrderRestaurant(request):
restaurant = ""
customer_exists = Customer.objects.filter(user_id = request.user.id).exists()
if customer_exists:
customer = Customer.objects.get(user_id = request.user.id)
order_qs = Order.objects.filter(customer_id=customer.id, ordered=False)
if ord... | The code handles the checkout process for authenticated users by retrieving their pending order, calculating fees, and rendering the checkout page with order details. It processes form submissions to manage shipping/billing addresses (default or new), validates inputs, updates the order, and redirects to the payment pa... | def checkout(request):
context = {}
if request.user.id:
customer = Customer.objects.get(user_id = request.user.id)
restaurant = getOrderRestaurant(request)
order = ''
context = {
'num_of_items': getCartSize(request),
'restaurant':restaurant,
}
... |
def getCartSize(request):
num_of_items = -1
if request.user.id:
customer = Customer.objects.get(user_id = request.user.id)
order_qs = Order.objects.filter(customer_id=customer.id, ordered=False)
if order_qs.exists():
order = order_qs[0]
num_of_items = order.get_to... | The code processes a payment request using Stripe, handling both authenticated and session-based users. It retrieves the customer's order, validates payment details, charges the card, updates the order status, and renders confirmation templates. Error handling for Stripe exceptions ensures proper feedback. If authentic... | def payment(request):
if request.user.id:
customer = Customer.objects.get(user_id = request.user.id)
order = Order.objects.get(customer_id=customer.id, ordered=False)
context = {
'num_of_items': getCartSize(request),
}
if request.method == 'GET':
conte... |
def gen_model(args):
norm = "both" if args.use_norm else "none"
if args.use_labels:
model = VAE(
in_feats + n_classes,
n_classes,
n_hidden=args.n_hidden,
n_layers=args.n_layers,
n_heads=args.n_heads,
activation=F.relu,
... | The main task of the code is to train and evaluate a Variational Autoencoder (VAE) model on the OGBN-Arxiv dataset using DGL, with configurable hyperparameters like learning rate, number of layers, attention heads, and dropout rates. The code processes graph data by adding reverse edges, self-loops, and PPMI edge weigh... | def main():
global device, in_feats, n_classes, epsilon
argparser = argparse.ArgumentParser("VAE on OGB", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
argparser.add_argument("--cpu", action="store_true", help="CPU mode. This option overrides --gpu.")
argparser.add_argument("--gpu", type=int,... |
def gen_model(args):
norm = "both" if args.use_norm else "none"
if args.use_labels:
model = GAT(
in_feats + n_classes,
n_classes,
n_hidden=args.n_hidden,
n_layers=args.n_layers,
n_heads=args.n_heads,
activation=F.relu,
... | The main task of the code is to train and evaluate a Variational Autoencoder (VAE) model on an OGB dataset (e.g., ogbn-products or ogbn-arxiv) using multiple runs for robustness. It processes graph data by adding reverse edges, self-loops, and PPMI edge weights, configures device settings (CPU/GPU), and performs traini... | def main():
global device, in_feats, n_classes, epsilon
argparser = argparse.ArgumentParser("VAE on OGB", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
argparser.add_argument("--cpu", action="store_true", help="CPU mode. This option overrides --gpu.")
argparser.add_argument("--gpu", type=int,... |
def check_count_target_reached(self):
return self.get_links_count() + len(self.links_to_scrape) >= self.scrape_count
def extract_with_dynamic_content(self):
try:
height_change = True
while height_change:
height_change = self.driver_manager.scroll_to_bottom()
... | The code extracts links from a search engine website by dynamically scraping content, navigating through pages, and handling errors like infinite loops or missing next-page buttons. It stores scraped links, monitors progress, and logs issues via a database controller if the target link count isn't met or errors occur d... | def extract_all_links(self):
print(f"EXTRACTING LINKS FROM: {self.search_engine_details.get(WebRadarWebsites.WEBSITE_URL.value)}")
try:
while not self.check_count_target_reached():
if self.next_page_click_count > 4:
DatabaseController(self.search_string_de... |
def input_search_string(self):
print(f"INPUTTING SEARCH STRING: {self.search_string_details.get(WebRadarStings.SEARCH_STRING.value)}")
if not (search_box := self.driver_manager.find_element_with_wait((By.XPATH, self.search_engine_details.get(WebRadarWebsites.SEARCHBAR_XPATH.value)), 30)):
ra... | The code's main task is to initiate a web scraping process by inputting a search string, extracting all relevant links from the page, closing the browser driver, and then scraping the identified pages to gather data. | def initiate_link_scraping(self):
self.input_search_string()
self.extract_all_links()
self.driver_manager.close_driver()
self.scrape_pages() |
def is_train_test_file_exists(self)->bool:
try:
logging.info("Checking if training and test file is available")
# Initializing the existance of train and test files
is_train_file_exist = False
is_train_file_exist = False
# Get actual train and test fi... | The main task of the code is to validate data by checking the existence of train/test files, verifying dataset schema compliance, and detecting data drift. It then generates a DataValidationArtifact with validation results, logs it, and returns it. If any step fails, it raises an exception. | def initiate_data_validation(self) -> DataValidationArtifact:
try:
# Call validation function is_available()
self.is_train_test_file_exists()
# Call validation function validate_dataset_schema()
self.validate_dataset_schema()
# Call validation functi... |
def query(self, qid, verbose = False):
"""
Return qid metadata (assuming it exists..)
"""
return self.get(["query", qid], verbose = verbose)
def count(self, qid, params = None, verbose = False):
"""
Get number of rows in a query
"""
return int(self.get(["... | This method retrieves data rows based on a query ID (qid), handling pagination and row limits. It checks if the requested page size exceeds the system's row limit, raising errors if so. Parameters like format, page size, and page number are used to construct a GET request, returning data in the specified format while r... | def data(self, qid, params = None, form = 'text/csv', pagesize = None, page = None, verbose = False, cols = False, inline_clobs = False):
"""
Get data rows
"""
rowsLimit = self.query(qid, verbose = True)["rowsLimit"]
count = int(self.count(qid))
ps = ["query", q... |
def qid(self, query):
"""
Create query based on [query] and return its ID
"""
return self.get(["query"], query)
def query(self, qid, verbose = False):
"""
Return qid metadata (assuming it exists..)
"""
return self.get(["query", qid], verbose = verbose)
def... | This function retrieves all rows from a database query in JSON format by paginating through results. It calculates the total pages needed, fetches data incrementally, aggregates results, and verifies the row count matches expectations. If discrepancies exist, it raises an error. The output is a list of rows in JSON arr... | def json_all(self, query, params = None, verbose = False, cols = False, inline_clobs = False):
"""
Get all rows in JSON format (array of arrays)
"""
rows = []
qid = self.qid(query)
rowsLimit = self.query(qid, verbose = True)["rowsLimit"]
cou... |
def collect_dots(self, position):
low, high = 0, len(self.clusters) - 1
while low <= high:
mid = (low + high) // 2
current_value = self.clusters[mid][0]
if current_value == position:
dots = self.clusters[mid][1]
self.clusters[mid][1] ... | This code processes agent actions in a game environment, updating position and resources based on "advance," "retreat," "boom," or "rush" commands. It modifies tensors representing position, energy, and collected dots, applying conversion rates for "boom" and "rush" actions. If enabled, it triggers an opponent's action... | def act(self, actions: Mapping[ActionName, Action], trigger_default_opponent_action : bool = True) -> Observation:
action = actions["Move"]
assert isinstance(action, GlobalCategoricalAction)
if action.label == "advance":
# Move forward as many times as the attack speed is set to
... |
def display_grid(self):
ref_pos = self.fiancee.rect.left - block_side, self.fiancee.rect.top - block_side
# Hiding the area of the maze and showing known part
self.screen.blit(self.bg, self.rects[0].topleft, (self.rects[0].topleft, maze_shape))
self.screen.blit(self.maze_surface, ref_po... | The code implements a game loop for a maze-solving application, handling user input via buttons and keyboard to control a character (fiancee) manually or using AI agents (OnlineDFS and LRTA*). It updates the game state, checks for maze completion, displays the grid, manages timers, and renders UI elements like buttons ... | def play(self):
# Update the clock
self.clock.tick()
time = 0
# Displaying fixed screen elements
self.screen.blit(self.bg, (0, 0)) # overriding home screen buttons
self.screen.blit(self.button_return, self.button_return_rect)
self.screen.blit(self.button_update... |
def update(self):
self.maze.update_maze() # update the grid
self.fiancee.reset() # reset the fiance
self.solver = None # reset the solver
self.load_maze() # update the maze
# Game background music
if not self.channel_music.get_busy():
self.channel_music.p... | The code initializes a Pygame game by creating a display window titled "Fiance Escape" and entering a loop that continuously updates the game state, renders the main screen, and starts gameplay. The `init_game` method sets up the display surface, configures the window caption, and triggers the game loop through `update... | def init_game(self): # method that start the game
# Creating a display Surface
self.screen = pygame.display.set_mode(size)
pygame.display.set_caption("Fiance Escape")
while True:
self.update()
self.main_screen()
self.play() |
def _load_service_model(self, service_name, api_version=None):
json_model = self._loader.load_service_model(service_name, 'service-2',
api_version=api_version)
service_model = ServiceModel(json_model, service_name=service_name)
self._register_... | The function creates a client for an AWS service by loading the service model, generating a client class, preparing configuration arguments, and returning an instantiated client with specified parameters like region, security, and credentials. | def create_client(self, service_name, region_name, is_secure=True,
endpoint_url=None, verify=None,
credentials=None, scoped_config=None,
api_version=None,
client_config=None):
service_model = self._load_service_model(service... |
def _check_if_table_exists(tableName,tableSchema):
print("Checking if table exists!")
table_id = BQ.dataset(BQ_DATASET).table(tableName)
try:
BQ.get_table(table_id)
print("table already exists!")
except Exception:
print("table does not exist, creating now...")
... | The code processes incoming data by extracting bucket name, filename, and timestamp. It matches the filename against config entries (via regex) to determine schema and format. If matched, it checks table existence and loads data into a table using either JSON or CSV format based on the config. Error handling is include... | def streaming(data):
bucketname = data['bucket']
print("Bucket name",bucketname)
filename = data['name'][:-4]
print("File name",filename)
timeCreated = data['timeCreated']
print("Time Created",timeCreated)
try:
for config_entry in config:
config_entry_name... |
def find_neighbors( self, session_items, input_item_id, session_id):
possible_neighbors = self.possible_neighbor_sessions( session_items, input_item_id, session_id )
possible_neighbors = self.calc_similarity( session_items, possible_neighbors )
possible_neighbors = sorted( possible_neig... | The function predicts the next items a user might interact with in a session by analyzing session history, item neighbors, and popularity. It updates session/session-item mappings, scores items based on neighbors, applies reminders for recent items, boosts popular items, and returns normalized prediction scores for spe... | def predict_next( self, session_id, input_item_id, predict_for_item_ids, input_user_id=None, skip=False, type='view', timestamp=0 ):
if( self.session != session_id ): #new session
if( self.extend ):
item_set = set( self.session_items )
self.session_item_m... |
def sales(self):
"""Sales by year
Depends on random base value in year 0 which is then modified by a percent decay rate that may
vary by year.
"""
# Scalar to range (consider creating function for this)
if np.isscalar(self.demand_decr):
self.demand_decr = np... | The main task of the code is to convert a financial model's data into a pandas DataFrame. It stacks multiple financial metrics (sales, contribution, revenue, etc.) vertically, then transposes the result if specified, creating columns for each metric. The DataFrame is structured with either transposed columns (when `tra... | def model_to_df(self, transpose=True):
"""Create DataFrame version of financial model table
Financial model table is transposed so that financial measures are columns.
"""
X = np.vstack([self.sales(), self.unit_contribution(),
self.net_revenue(), self.depreciation... |
def binary_filename():
"""Returns the expected filename for OptiMathSAT's binary."""
return "optimathsat.exe" if os.name == 'nt' else \
"optimathsat"
def optimathsat_compile(config, solver_config=None):
"""Compiles a FlatZinc model in SMT-LIB format."""
assert common.is_binary_in_path(binary_... | (The function `optimathsat` executes OptiMathSAT based on the provided configuration. It first verifies the presence of the required binary. If `config.smt2` is true, it compiles the input using `optimathsat_compile`; otherwise, it solves the problem via `optimathsat_solve`, leveraging the solver configuration. The cor... | def optimathsat(config, solver_config=None):
"""Runs OptiMathSAT with the given configuration."""
common.exit_if_binary_not_in_path(binary_filename())
if config.smt2:
optimathsat_compile(config, solver_config)
else:
optimathsat_solve(config, solver_config) |
def binary_filename():
"""Returns the expected filename for z3's binary."""
return "z3"
def zthree_compile(config):
"""Compiles a FlatZinc model in SMT-LIB format."""
assert common.is_binary_in_path(binary_filename())
assert config.smt2
optimathsat_config = argparse.Namespace(**vars(config))
... | The function `zthree_solve` solves a FlatZinc model using Z3 by converting it into an SMT-LIBv2 formula via OptiMathSAT. It generates temporary files for the SMT formula, output variables, and trace logs, then executes the solver, captures results, checks for errors, extracts solution status and models, and outputs the... | def zthree_solve(config, solver_config=None):
"""Solves a FlatZinc model with Z3.
The FlatZinc model is compiled to a SMT-LIBv2
formula with OptiMathSAT first."""
assert common.is_binary_in_path(binary_filename())
assert not config.smt2
with tempfile.TemporaryDirectory() as tmp_dir:
co... |
def binary_filename():
"""Returns the expected filename for z3's binary."""
return "z3"
def zthree_compile(config):
"""Compiles a FlatZinc model in SMT-LIB format."""
assert common.is_binary_in_path(binary_filename())
assert config.smt2
optimathsat_config = argparse.Namespace(**vars(config))
... | The main task of the code is to execute the Z3 solver using a configuration specified by the `config` parameter. It first checks if the Z3 binary is accessible. If `config.smt2` is True, it compiles Z3; otherwise, it runs the solver with the provided configuration and optional solver-specific settings. The function act... | def zthree(config, solver_config=None):
"""Runs Z3 with the given configuration."""
common.exit_if_binary_not_in_path(binary_filename())
if config.smt2:
zthree_compile(config)
else:
zthree_solve(config, solver_config) |
def get_distance_between_entries(row, distancethreshold=-1):
if row_is_good(row):
# get string distance between two numbers
row_distance = edit_distance(*row, True)
return row_distance
else:
return -1
def row_is_good(row):
return row[0] and row[1]
def handle_names(names, scor... | The main task of the code is to calculate a composite score to determine if two data rows (row1 and row2) represent the same person. It evaluates fields like account numbers, names, dates of birth, sex, addresses, and zip codes, adjusting the score based on similarities or discrepancies. Lower scores indicate higher li... | def is_same_person(row1, row2, file_pointer):
rows = []
for i in range(len(row1)):
rows.append([row1[i], row2[i]])
file_pointer.write(f"Comparing rows...\n{row1}\n{row2}")
# lower the score, more likely they are the same
score = 0
distance = 0
# ignore 0 and 1
acct_nums = rows... |
def get_linear_velocity_at_t(self, t):
return self.velocities[int(t*self.t.size-1)]
def get_headings(self):
self.headings = [ np.arctan2(self.dy[i], self.dx[i]) for i in range(len(self.dx)) ]
return self.headings
def get_left_velocity_at_t(self, trackwidth, t):
if self.get_curvature_at_t... | The code generates a text file ("states.txt") containing time-stamped state data of a system, including linear velocity, heading angle, and left/right wheel velocities. It iterates through time points, calculates relevant values using internal methods, and writes them in a formatted string for later analysis or logging... | def generate_file_of_states(self, trackwidth):
velocities = [ (self.t_v[int(t*self.t_v.size-1)], self.get_linear_velocity_at_t(t), self.get_headings()[int(t*self.t.size-2)], self.get_left_velocity_at_t(trackwidth, t), self.get_right_velocity_at_t(trackwidth, t)) for t in self.t[1:] ]
with open("states.t... |
def control_points_from_file(self, filename):
control_points = []
with open(filename, "r") as f:
for line in f.readlines():
point = line.rstrip().split(" ")
control_points.append(Point2D(float(point[0]), float(point[1])))
self.update_control_points(con... | This function reads control points from a file, extracts their coordinates, updates a plot's data points, generates rough paths, updates path plot data, and adjusts the plot's axis limits to provide a margin around the control points. | def draw_control_points():
self.control_points_from_file("control_points.txt")
waypoints = self.get_points()
control_point_x = [point.get_x() for point in waypoints]
points.set_xdata(control_point_x)
control_point_y = [point.get_y() for point in waypoints]
... |
def generate_x(self):
n = len(self.get_points())
return [ sum( [MathHelperFunctions.choose(n-1, i)*(1-t)**((n-1)-i)*(t**i) * self.p[i].get_x() for i in range(n)] ) for t in self.t ]
def generate_y(self):
n = len(self.get_points())
return [ sum( [MathHelperFunctions.choose(n-1, i)*(1-t)**... | The main task of the code is to generate normalized tangent vectors for a parametric curve. It computes derivatives of x and y components, constructs tangent vectors, calculates their magnitudes, and returns unit vectors by dividing each tangent vector by its magnitude, ensuring direction preservation without scaling. | def generate_tangent_vector(self):
x = self.generate_x()
y = self.generate_y()
dx = self.generate_x_derivative()
dy = self.generate_y_derivative()
vectors = [(dx[i], dy[i]) for i in range(len(dx))]
magnitudes = [sqrt(v[0]**2 + v[1]**2) for v in vectors]
return [(v... |
def generate_x(self):
n = len(self.get_points())
return [ sum( [MathHelperFunctions.choose(n-1, i)*(1-t)**((n-1)-i)*(t**i) * self.p[i].get_x() for i in range(n)] ) for t in self.t ]
def generate_y(self):
n = len(self.get_points())
return [ sum( [MathHelperFunctions.choose(n-1, i)*(1-t)**... | The code generates left and right trajectories by offsetting original x/y data points based on calculated headings. It computes lateral displacements using sine and cosine of headings to create parallel paths, returning tuples of (left_x, left_y) and (right_x, right_y) coordinates for trajectory visualization or simula... | def generate_trajectories(self):
xdata = self.generate_x()
ydata = self.generate_y()
headings = self.generate_heading()
left_x = [xdata[i] - 0.5*sin(headings[i]) for i in range(len(headings))]
left_y = [ydata[i] + 0.5*cos(headings[i]) for i in range(len(headings))]
right_... |
def generate_x(self):
n = len(self.get_points())
return [ sum( [MathHelperFunctions.choose(n-1, i)*(1-t)**((n-1)-i)*(t**i) * self.p[i].get_x() for i in range(n)] ) for t in self.t ]
def generate_y(self):
n = len(self.get_points())
return [ sum( [MathHelperFunctions.choose(n-1, i)*(1-t)**... | The function `update(t)` dynamically updates a plot's elements (lines and trajectories) based on the parameter `t`, which likely represents animation progress. It sets the plot aspect ratio, redraws control points, generates and slices trajectory data, and updates line objects with the sliced data. For `t > 0`, left an... | def update(t):
ax.set_aspect('equal')
draw_control_points()
xdata = self.generate_x()[:int(t*199)]
ydata = self.generate_y()[:int(t*199)]
left_trajectory_data, right_trajectory_data = self.generate_trajectories()
ln.set_data(xdata, y... |
def getNeighbors(node , nodes) :
closest = 99
#Format : [Down , Up , Left , Right]
neighbors = ['' , '' , '' , '']
counter = 0
found = ''
for n in nodes :
if node.x == n.x and (node.y - n.y != 0) and (abs(node.y - n.y) < closest) and (n.y > node.y):
do = 1
for y i... | The function `fancySolve` checks if a node can form a bridge with a neighbor based on specific conditions: if the neighbor has 2, 3, or 4 connections and meets value thresholds (e.g., neighbor.v ≥ 3, 5, 7 and node.v ≥ 1). If valid, it creates a bridge, prints a message, and returns 1; otherwise, returns 0. The task inv... | def fancySolve(node , nodes) :
if node.v == 0 :
return 0
global bridges
validNeighbors = getNeighbors(node , nodes)
numberNeighbors = numNeighbors(node , nodes)
for n in validNeighbors :
if n != '' :
neighbor = getNode(n , nodes)
neighborNumber = numN... |
def getNeighbors(node , nodes) :
closest = 99
#Format : [Down , Up , Left , Right]
neighbors = ['' , '' , '' , '']
counter = 0
found = ''
for n in nodes :
if node.x == n.x and (node.y - n.y != 0) and (abs(node.y - n.y) < closest) and (n.y > node.y):
do = 1
for y i... | This function processes a "trivial node" in a graph by forming bridges with its neighbors based on specific value conditions. It checks node values, neighbor counts, and sums to determine how to resolve the node: creating bridges when the average neighbor value is 2, when the node has a single neighbor, or when the nod... | def solveTrivialNode(node , nodes) :
if node.v == 0 :
return 0
global bridges
validNeighbors = getNeighbors(node , nodes)
numberNeighbors = numNeighbors(node , nodes)
total = 0
for n in validNeighbors :
if n != '' :
total = total + getNodeVal(n , nodes)
... |
def _has_procedure_run_mode_argument(proc):
proc_args = proc.get_arguments()
if proc_args and proc_args[0].value_type.pytype is not None:
return issubclass(proc_args[0].value_type.pytype, Gimp.RunMode)
else:
return False
def _pythonize(str_):
return str_.replace('-', '_')
def _get_pdb_argument_type_hint... | (The main task of the code is to insert argument nodes into a Python AST for a procedure, generating type hints and default values. It processes procedure arguments, skips the first if it's a run-mode parameter, reverses the remaining arguments, creates AST nodes with Pythonized names and type annotations, inserts them... | def _insert_pdb_procedure_arguments(procedure_node, procedure):
proc_args = procedure.get_arguments()
if _has_procedure_run_mode_argument(procedure):
proc_args = proc_args[1:]
for proc_arg in reversed(proc_args):
arg_node = ast.arg(
arg=_pythonize(proc_arg.name),
annotation=_get_pdb_argument... |
def _add_proc_blurb_to_docstring(procedure, proc_docstring):
proc_blurb = procedure.get_blurb()
if proc_blurb:
proc_blurb = proc_blurb.strip()
if not proc_blurb.endswith('.'):
proc_blurb += '.'
proc_blurb = proc_blurb[0].upper() + proc_blurb[1:]
proc_blurb = textwrap.fill(
proc_blurb,
... | The function `_insert_pdb_procedure_docstring` generates a comprehensive docstring for a procedure node by concatenating metadata, parameters, return values, and formatting directives. It sequentially adds blurbs, image types, menu labels, paths, help text, and parameters using helper functions, adjusting formatting ba... | def _insert_pdb_procedure_docstring(procedure_node, procedure):
proc_docstring = ''
proc_docstring = _add_proc_blurb_to_docstring(procedure, proc_docstring)
add_extra_newline = True
proc_docstring, is_specified = _add_image_types_to_docstring(
procedure, proc_docstring)
add_extra_newline = add_extra_ne... |
def _create_pdb_procedure_node(procedure_name, procedure):
func_name = _pythonize(procedure_name)
# Constructing a `FunctionDef` node this way is more readable and less error-prone.
func_positional_args_str = 'self'
func_run_mode_arg_str = 'run_mode: Gimp.RunMode = Gimp.RunMode.NONINTERACTIVE'
has_run_mode ... | The function `_insert_pdb_procedure_node` creates a procedure node from a given procedure, adds its arguments and docstring, then appends this node to the body of a specified class node in a PDB (Python Debugger) structure. | def _insert_pdb_procedure_node(pypdb_class_node, procedure_name, procedure):
procedure_node = _create_pdb_procedure_node(procedure_name, procedure)
_insert_pdb_procedure_arguments(procedure_node, procedure)
_insert_pdb_procedure_docstring(procedure_node, procedure)
pypdb_class_node.body.append(procedure_node) |
def _add_imports(root_node):
new_import_nodes = ast.parse(
'\n'
+ '\n'.join([
'from typing import List, Tuple',
'from gi.repository import Gegl',
'from gi.repository import GLib',
'from gi.repository import Gio',
'from gi.repository import GObject',
])
)
for new_import_n... | The code generates a Python stub file from the pypdb module by parsing its source code, modifying the AST to remove function implementations, adding necessary imports, inserting procedure nodes, and writing the resulting structure to a stub file in the specified output directory. | def generate_pdb_stubs(output_dirpath):
if not os.path.isfile(PYPDB_MODULE_FILEPATH):
raise RuntimeError(f'pypdb module does not exist at "{os.path.dirname(PYPDB_MODULE_FILEPATH)}"')
with open(PYPDB_MODULE_FILEPATH, 'r', encoding=TEXT_FILE_ENCODING) as f:
root_node = ast.parse(f.read())
_add_imports(roo... |
def get_mlovlp(mol, auxmol):
""" Returns three center-one electron intergrals need for basis
set projection
"""
pmol = mol + auxmol
nao = mol.nao_nr()
naux = auxmol.nao_nr()
eri3c = pmol.intor('int3c1e_sph', shls_slice=(0, mol.nbas, 0, mol.nbas, mol.nbas, mol.nbas + auxmol.nbas))
return... | The function `get_datapoint` computes quantum chemical data for a molecular system using PySCF, generating electronic structure matrices, integrals, and features like density matrices, energy, and grid-based properties. It handles basis sets, spin states, and density fitting, returning total energy, a placeholder ident... | def get_datapoint(atoms, xc='', basis='6-311G*', ncore=0, grid_level=0,
nl_cutoff=0, grid_deriv=1, init_guess = False, ml_basis='',
do_fcenter=True, zsym = False, n_rad=20,n_ang=10, spin=0, pol=False,
ref_basis='', ref_path = '', ref_index=0, dfit = False, non_local... |
def set_power(power):
power = int(power)
try:
#p.ChangeDutyCycle(power)
print(power)
if power == 100:
playsound('winning.mp3')
playsound('wii winner.mp3')
except KeyboardInterrupt:
pass
def set_light(light, light_on=False):
#from main import lig... | The code processes a request to control vehicle components by calling functions to set power, light, horn, and charge status based on the input parameters. | def handle_request(request):
set_power(request['power'])
set_light(request['light'], light_on)
set_horn(request['horn'])
set_charge(request['charge'], is_charging) |
def read_file():
'''
This function will return a dictionary that maps misspelled
words to correctly spelled words.
'''
misspellings = {}
misspelling_file = open('misspellings.txt', 'r')
# Loop through each line in misspelling_file and
# split by each word into a list
for lin... | The main task of the code is to perform spell-checking on a document by either replacing misspelled words with correct ones or suggesting possible corrections, based on user input. It reads a misspellings dictionary, takes an input file, and applies the specified mode ('replace' or 'suggest') to process and modify the ... | def main():
# Get input file and the mode of spellcheck
in_file = input('Enter input file:\n')
mode = input('Enter spellcheck mode (replace or suggest):\n')
# Get the misspellings dictionary
misspells = read_file()
# Run one fuction(replace or suggest) depending on mode
if mod... |
def generer_chemin(population, liste_fleur):
for pop in range(100):
bee = Bee.Bee()
id = random.sample(range(len(liste_fleur)), len(liste_fleur))
for i in id:
bee.add_step(getFleur(liste_fleur, i))
bee.calcul_longueur()
population.append(bee)
return population... | This function iteratively generates and optimizes a population of flower paths (chromosomes) over 1000 generations. It initializes a first population, calculates its average distance, then iteratively creates new populations using the previous generation's mean distance. The process tracks average distances in a list, ... | def iteration(liste_fleur):
liste_moyenne = []
firstPop = []
firstPop = generer_chemin(firstPop, liste_fleur)
liste_moyenne.append(distanceMoyenne(firstPop))
for i in range(2, 1001):
moyenne_precedente = liste_moyenne[-1]
newPop = new_generation(moyenne_precedente, liste_fleur, first... |
def load_train_images(self):
descriptions = self.load_description()
# Create a list of all image names in the directory
images_name = glob.glob(self.images_path + '*.jpg')
train_img = [i.split('\\')[-1] for i in images_name]
train_descriptions = self.lo... | The main task of the code is to load and preprocess training data by encoding images and descriptions, then returning processed data (images, sequences, labels, and word mappings) while optionally saving them. It uses `load_train_images` to fetch data, `prepare_data` to structure it, and `Saving` to store results if `s... | def load_data(self,save=False):
encoding_train,train_descriptions = self.load_train_images()
X_img, X_seq, y, ixtoword, wordtoix = self.prepare_data(train_descriptions,encoding_train)
if save:
self.Saving(X_img,X_seq,y,ixtoword,wordtoix)
return X_img, X_seq, y, ixtoword, word... |
def contains(words, st):
""" Returns if any of the words are in the string. """
for word in words:
if word in st:
return True
return False
def fix_string(st):
""" Fixes any similar occurences of coordinates. """
i = 0
new_st = st.lower()
for square_variants in common_vari... | The code parses natural language input (e.g., from Alexa) into standard chess move notations. It identifies commands like "redo," "end," or "draw," and converts verbal chess moves (e.g., "move knight to e5") into algebraic notation (e.g., "Ne5") and UCI format (e.g., "g1e5"). It handles piece names, coordinates, promot... | def parse_move(input_st):
""" Parses Alexa input into a chess readable notation.
As a tuple (<algebraic notation>, <uci notation>) """
piece_words = ['rook', 'bishop', 'king', 'queen', 'knight', 'horse', 'pawn', 'night']
redo_words = ['redo', 'undo', 'do over', 'back', 'return']
end_words = ['end',... |
def feedforward_comp(W_out_new, W_HL1_new, B_out_new, B_HL1_new, data_inputs):
# print("---------------------------------------------------------------")
# print("feedforward_comp: W_HL1_new = ", W_HL1_new)
# print("feedforward_comp: B_HL1_new = ", B_HL1_new)
# print("\n")
# print("feedforward_... | The function `Conjugate_Gradient_HL1` trains a neural network using the conjugate gradient optimization algorithm. It iteratively updates weights (W_out, W_HL1) and biases (B_out, B_HL1) to minimize training error by computing gradients via backpropagation, maintaining conjugate direction vectors (h_W, h_B), and applyi... | def Conjugate_Gradient_HL1(user_Validation_error, W_out, W_HL1, B_out, B_HL1, data_Tr_inputs, data_outputs_Tr, max_epoch):
Training_error_collection = []
num_epoch_iterated = 0
W_out_new = [W_out, None]
W_HL1_new = [W_HL1, None]
B_out_new = [B_out, None]
B_HL1_new = [B_HL1, None]
... |
def feedforward_comp(W_out_new, W_HL1_new, B_out_new, B_HL1_new, data_inputs):
print("---------------------------------------------------------------")
print("feedforward_comp: W_HL1_new = ", W_HL1_new)
print("feedforward_comp: B_HL1_new = ", B_HL1_new)
print("\n")
print("feedforward_comp: W_ou... | The main task of the code is to implement the Conjugate Gradient optimization algorithm for training a single-hidden-layer neural network. It iteratively updates weights and biases (W_out, W_HL1, B_out, B_HL1) by computing gradients via a feedforward pass, applying line search for step size (etah), and using conjugate ... | def Conjugate_Gradient_HL1(user_Validation_error, W_out, W_HL1, B_out, B_HL1, data_inputs, data_outputs, max_epoch):
Training_error_collection = []
num_epoch_iterated = 0
W_out_new = [W_out, None]
W_HL1_new = [W_HL1, None]
B_out_new = [B_out, None]
B_HL1_new = [B_HL1, None]
h... |
def feedforward_comp(W_out_new, W_HL1_new, B_out_new, B_HL1_new, data_inputs):
# print("---------------------------------------------------------------")
# print("feedforward_comp: W_out_new = ", W_out_new)
# print("feedforward_comp: W_HL1_new = ", W_HL1_new)
# print("\n")
# print("feedforward_... | The code implements the **Conjugate Gradient Optimization Algorithm** for training a neural network with one hidden layer (HL1). It iteratively updates weights (W_out, W_HL1) and biases (B_out, B_HL1) to minimize training error while preventing overfitting by comparing validation error. Key steps include:
1. **Feedfo... | def Conjugate_Gradient_HL1(user_Validation_error, W_out, W_HL1, B_out, B_HL1,
data_inputs_Tr, data_outputs_Tr, max_epoch):
Training_error_collection = []
num_epoch_iterated = 0
W_out_new = [W_out, None]
W_HL1_new = [W_HL1, None]
B_out_new = [B_out, None]
B_... |
def variable_times_variable(variable1_idx, variable2_idx, variable1_sign, \
variable2_sign, variable_bit_count, variable_count, triplet_count):
v1_spins = tuple(
spin_index(variable1_idx, bit_idx, variable_count, variable_bit_count, \
triplet_count) for bit_idx in range(variable_bit_count)
... | This function constructs a Hamiltonian for a quantum system by combining interaction terms (J), local fields (h), and a constant (c) from three variables and their pairwise interactions. It processes self-terms (t1t1, t2t2, t3t3), cross-terms (t1t2, t1t3, t2t3), and sum-related terms (t1t, t2t, t3t, tt), merging and ad... | def triplet_hamiltonian(variable1_idx, variable2_idx, variable3_idx, \
variable1_sign, variable2_sign, variable3_sign, variable_count, \
variable_bit_count, triplet_idx, triplet_count):
J, h, c = {}, {}, 0.0
# t1t1
Jterm, hterm, cterm = variable_times_variable(variable1_idx, \
variable... |
def triplet_hamiltonian(variable1_idx, variable2_idx, variable3_idx, \
variable1_sign, variable2_sign, variable3_sign, variable_count, \
variable_bit_count, triplet_idx, triplet_count):
J, h, c = {}, {}, 0.0
# t1t1
Jterm, hterm, cterm = variable_times_variable(variable1_idx, \
variable... | The code constructs a Hamiltonian from given triplets of variables with associated signs and weights. It iterates over each triplet, computes interaction terms (J), local fields (h), and a constant (c) using a helper function. Weights are applied, terms are aggregated, and zero entries are removed. Finally, it converts... | def hamiltonian(variable_count, variable_bit_count, triplet_refls, \
triplet_signs, triplet_weights=None, verbose=False):
if triplet_weights is None:
triplet_weights = [1.0 for t in triplet_refls]
triplet_count = len(triplet_refls)
J, h, c = {}, {}, 0.0
for j, triplet in enumerate(triplet... |
def Recognization(self, frame, gray, faces):
# print('Yes')
haarcascade_path = r'C:\Users\hsri2\Desktop\HTML _ css codes\majorproject\Testing_codes\face_detect.xml' # Replace with the actual absolute path
haascascade = cv.CascadeClassifier(haarcascade_path)
# Load pre-trained f... | This code initializes a camera for real-time face detection using OpenCV. It captures video, converts frames to grayscale, detects faces with a Haar Cascade classifier, and highlights detected faces with rectangles. If faces are found, it triggers recognition; otherwise, it shows no recognition. User inputs 'c' save da... | def __init__(self):
self.capture = cv.VideoCapture(0)
if not self.capture.isOpened():
print("Error: Unable to open camera.")
return
self.haarcascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')
while True:
... |
def generate_batch(self, lang1, lang2, name):
"""
Prepare a batch (for causal or non-causal mode).
"""
params = self.params
lang1_id = params.lang2id[lang1]
lang2_id = params.lang2id[lang2] if lang2 is not None else None
if lang2 is None:
x, lengths =... | This code implements a training step for a causal language model (CLM) by performing next-word prediction. It generates a batch of input sequences, applies a causal mask to predict future tokens, computes the loss using a language model, scales it by a coefficient, and updates model parameters via optimization. It also... | def clm_step(self, lang1, lang2, lambda_coeff):
"""
Next word prediction step (causal prediction).
CLM objective.
"""
assert lambda_coeff >= 0
if lambda_coeff == 0:
return
params = self.params
name = 'model' if params.encoder_only else 'decoder... |
def generate_batch(self, lang1, lang2, name):
"""
Prepare a batch (for causal or non-causal mode).
"""
params = self.params
lang1_id = params.lang2id[lang1]
lang2_id = params.lang2id[lang2] if lang2 is not None else None
if lang2 is None:
x, lengths =... | This function performs masked language modeling (MLM) or two-language modeling (TLM) by predicting masked tokens in input sequences. It generates batches, masks tokens, computes prediction loss, scales it by λ, updates model parameters, and tracks statistics. It handles both single-language (MLM) and cross-language (TL... | def mlm_step(self, lang1, lang2, lambda_coeff):
"""
Masked word prediction step.
MLM objective is lang2 is None, TLM objective otherwise.
"""
assert lambda_coeff >= 0
if lambda_coeff == 0:
return
params = self.params
name = 'model' if params.en... |
def poetry_repositories() -> Dict[str, _PoetryRepoConfig]:
"""Get repositories configured in Poetry"""
poetry_config_proc = subprocess.run(
["poetry", "config", "repositories"], capture_output=True, check=True
)
config_from_poetry = parse_poetry_repo_config(poetry_config_proc.stdout.decode())
... | The function `_fetch_auth_tokens` retrieves authentication tokens for CodeArtifact repositories defined in Poetry's configuration. It iterates through Poetry repositories, parses their URLs into CodeArtifact configurations, and generates tokens using provided auth parameters. Non-CodeArtifact repositories are skipped. ... | def _fetch_auth_tokens(config: AuthConfig) -> Iterable[NameAndToken]:
repositories = poetry_repositories()
if not repositories:
raise NoCodeArtifactRepositoriesError(
"No repositories found. Make sure a valid pyproject.toml which defines "
"extra sources is available in a current... |
def get_ca_auth_token_for_params(
repo_config: CodeArtifactRepoConfig,
login_params: AwsLoginParameters,
duration_seconds: int = None,
) -> str:
"""Fetch a CodeArtifact token enabling repository access"""
auth_args = asdict(login_params) if login_params else {}
boto3_session = boto3.Session(**au... | The main task of the code is to execute a `pip install` command with authentication to a specified repository. It generates an authentication token from the provided configuration, constructs an authenticated URL, and installs packages using `pip` with the given arguments, ensuring the operation succeeds by raising an ... | def run_pip_install_with_auth(config: AuthConfig, repository: str, pip_args: List[str]):
"""Runs pip install with authentication"""
ca_config = CodeArtifactRepoConfig.from_url(repository)
token = get_ca_auth_token_for_params(ca_config, auth_params_from_config(config, ""), 3600)
subprocess.run(
[... |
def generate_historical_edges(self, graph, num_edges):
'''
Generates historical negative edges.
Arguments
---------
graph : dict
Positive edges.
Dictionary whose keys are edges (represented as tuples of
length 2) and values are occurrence counts.
num_edges : int
Number of edges to generate.
... | The code generates a dataset of graphs with injected negative edges for testing. It creates a generator yielding arrays of edges (timestamp, origin, destination, occurrence count, label) where labels are 1 (positive) or 0 (negative). Depending on `neg_type` ('easy', 'historical', 'inductive'), it adds negative edges vi... | def generate_dataset(self, neg_type='easy'):
'''
Returns a generator object whose elements are the graphs
from the test set with injected negative edges.
Arguments
---------
neg_type : str, default='easy'
Type of negative edges to generate.
Possible values:
- 'easy': random rewiring of positive e... |
def _build_adjacency_matrices(self, X):
'''
Converts an array of temporal edges into a list of sparse
adjacency matrices.
Arguments
---------
X : array of shape (n_edges, 4)
Array of temporal edges.
Each row contains four values: timestamp, top node, bottom
node, and number of occurrences.
Ret... | This function computes optimal mixing coefficients for each time step in temporal edge data, builds adjacency matrices from input edges, fits weights, records timestamps, and appends the weights to the model's historical coefficient sequence. | def fit_and_append_weights(self, X):
'''
Computes the optimal mixing coefficients for each time step in
the input data, then appends them to the model's sequence of
historical mixing coefficients.
Arguments
---------
X : array of shape (n_edges, 4)
Array of temporal edges.
Each row contains four v... |
def _build_adjacency_matrices(self, X):
'''
Converts an array of temporal edges into a list of sparse
adjacency matrices.
Arguments
---------
X : array of shape (n_edges, 4)
Array of temporal edges.
Each row contains four values: timestamp, top node, bottom
node, and number of occurrences.
Ret... | The code calculates the negative reconstruction error for each temporal edge in input data to identify anomalies. It constructs adjacency matrices, computes mixing weights (either optimal or periodic), and evaluates reconstruction error. High error (low score) indicates anomalous edges. The function returns an array of... | def score_samples(self, X, order=1, period=None):
'''
Returns the opposite of the reconstruction error for each
temporal edge in the input data.
High reconstruction error (i.e. low score) means anomalous
temporal edge.
Arguments
---------
X : array of shape (n_edges, 4)
Array of temporal edges.
... |
def _create_list_of_files(self, rootDir):
self._statesync = StateSync(os.path.join(rootDir, "jenkinssync.json"))
for dirName, subdirList, fileList in os.walk(rootDir):
subdirList.sort()
for fname in sorted(fileList):
if fname.endswith(".Jenkinsfile"):
... | The code synchronizes files from a local directory to Jenkins by comparing the current file list with a previous state. It identifies changes/deletions, connects to Jenkins, uploads updated files, and updates the state if modifications are detected. If no changes are found, it exits early. | def sync_folder_to_jenkins(self, rootDir):
self._create_list_of_files(rootDir)
print("Files to sync:")
diff = self._statesync.diff()
self._dump_diff(diff)
if len(diff["changed"]) == 0 and len(diff["deleted"]) == 0:
print("No changes were made. Nothing do do!")
... |
def return_tables_referenced(self, tables, engine):
# this is only going one level deep, might need to be recursive. Not sure if I want that?
insp = reflection.Inspector.from_engine(engine)
for table in tables:
for foreign_key in insp.get_foreign_keys(table.name):
tab... | This code generates table models for each input table, establishes foreign key relationships between them using a database engine, and returns the resulting models. It first creates individual table models, then processes relationships to ensure proper foreign key constraints are applied across the generated models. | def generate_table_models(self, tables):
results = []
self.return_tables_referenced(tables, self.engine)
for table in tables:
print(f"Generate Table Models - {table.schema}.{table.name}")
results.append(self.generate_table_model(table, self.engine))
for table in ... |
def cacheToUnfollow(self):
self.following = self.readFromCache(FOLLOWEE_FILE)
self.followers = self.readFromCache(FOLLOWER_FILE)
self.whitelist = self.readFromCache(WHITELIST_FILE)
self.toUnfollow = self.following - self.followers
self.toUnfollow = self.toUnfollow - self.whitelis... | The main task of the code is to unfollow all users in the `toUnfollow` list by iterating through them, handling both list/tuple and single-user formats, updating the `following` cache, logging progress, and introducing delays to avoid detection. It ensures systematic unfollowing while maintaining cached data and provid... | def unfollowAll(self):
self.cacheToUnfollow()
if len(self.toUnfollow)>0:
self.printLog ("Now Unfollowing: %d people"%len(self.toUnfollow))
for i,user in enumerate(self.toUnfollow):
if type(user) is list or type(user) is tuple:
self.unfollow(use... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.