dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def put_request(self, url: str, path: str, headers: Dict[str, str], data: Dict):
"""
Makes a put request to the Frigidaire API and parses the result
:parm url: Base URL for the request (no slashes)
:param path: The path to the resource, including query params
:param data: The dat... | The code executes predefined actions on an appliance by sending PUT requests to an API endpoint. It iterates through components in the action list, constructs JSON payloads, and sends commands to control the appliance. If a FrigidaireException occurs, it re-authenticates and retries the request to ensure successful com... | def execute_action(self, appliance: Appliance, action: List[Component]) -> None:
"""
Executes any defined action on a given appliance
Will authenticate if the request fails
:param appliance: The appliance to perform the action on
:param action: The action to be performed
... |
def make_data(name, x_array, y_array, z_array, data_color='red'):
"""Generate a data object from three arrays."""
# Erase old name, create new.
pymol.cmd.delete(name)
pymol.cmd.create(name, None)
# Produce points.
for i in range(0, len(x_array)):
pymol.cmd.pseudoatom(name,
... | The function `plot3d` generates a 3D plot in PyMOL using input arrays for x, y, and optional z coordinates. It ensures all arrays have equal lengths, defaults z-values to zero if unspecified, and scales the Cartesian axes. The plot includes data points, axis lines, and optional connections between points (customizable ... | def plot3d(name, x_array, y_array, z_array=[], connect='red', scale=True,
axis_color='blue', num=0):
"""
Default plotting tool with optional z points, connection, and axis color.
"""
if not z_array:
z_array = [0] * len(x_array)
if not len(x_array) == len(y_array) == len(z_array):
... |
def _color_model(self, name, etype, s):
if etype == 'X11Colors':
palette = 'X'
else:
palette = 'R'
for i in range(0, len(s), 8):
score = ('%s' % s[(i + 6):(i + 8)])
color = palette + score
target = '%s and chain %s and resi %s' % (name... | The `process_packet` function parses and processes structured data packets, interpreting their type (e.g., PDB files, energy data, hydrogen bonds) and applying corresponding PyMOL commands to visualize or manipulate molecular structures. It extracts packet headers, decompresses data when needed, and executes operations... | def process_packet(self, msg):
""" Format description:
bytes 0:8 - packet type
byte 8 - flags
byte 9 - len(name)
bytes 10:... - name
bytes ...:... - message itself
"""
#print("the initial message is {0}".format(msg))
... |
def collision_constants(collision_dict, sample_rate, noise=False):
# properties of water
gamma = 7.
ref_density = 1000.
# calculate the amplitude of the incident and reflected velocities (across all components)
collision_dict['i'] = np.sqrt(collision_dict['ix']**2 + collision_dict['iy']**2 + c... | The function simulates seismic waveforms or frequency spectra from ice-water collision data, calculating P/S-wave amplitudes at a seismometer. It processes collision parameters, derives physical constants (wavenumber, attenuation), and generates time-domain waveforms or frequency-domain spectra based on amplitude_type.... | def icewater_collisions(x_seis, y_seis, z_seis, collision_df, endtime, starttime=0, sample_rate=1./200, sound_speed=1400., temperature=-10, sp_amplitude_ratio=0.5, amplitude_type='acceleration'):
# create a copy of the input pandas dataframe
if collision_df.columns[0] == 't':
collision_data = collision... |
def __seismic_sph_times(filename=None):
# read-in log file
if filename == None:
df = pd.read_csv('seismic_sph_output/seismic_sph.log', sep='|')
else:
df = pd.read_csv(filename+'_output/'+filename+'.log', sep='|')
time_vector = []
iter_vector = []
for i in range(0, len(df)):
... | The function processes SPH simulation data to extract collision information, including time, positions, normals, forces, and densities, then compiles these into a structured pandas DataFrame for analysis. | def seismic_sph_collisions(x, y, z, dx, set_obstacle, filename=None, sigma=sigma):
# read in time and fluid properties from file
time_vector, iter_vector = __seismic_sph_times(filename=filename)
fluid_vector = __seismic_sph_particles(time_vector, iter_vector, [], filename=filename, start=0, buffer=buff)
... |
def collect_investigation_package(self, evidence):
"""
Collect investigation package from machines for given evidence
https://docs.microsoft.com/en-us/microsoft-365/security/defender-endpoint/collect-investigation-package
:param evidence: evidence object
:exception: when isolatio... | The code performs automated machine actions based on VMRay Analyzer results and configuration settings. It checks if actions like collecting investigation packages, running antivirus scans, quarantining files, or isolating machines are enabled in the config and if the sample verdict matches specified criteria. If condi... | def run_automated_machine_actions(self, sample_data, evidence):
"""
Running automated machine actions based on confiuration and VMRay Analyzer results
:param sample_data: VMRay response for submitted sample
:param evidence: evidence object
:return void:
"""
# Col... |
def most_common_companies():
"""
PURPOSE
Find most common companies in database, before, we had 1300 companies
which we decided was too many classes for a database that only had
5000 movies to begin with.
INPUT
None
OUTPUT
set_companies: set of 20 most common movies
NOTES
... | The main task of the code is to clean and transform the original movie dataset by extracting specific fields (Budget, Genre, Title, Company, Release Date, Revenue), validating data integrity, normalizing company names, categorizing companies into "top 20 common" or "Other," and bracketing numerical values (budget/reven... | def clean_data():
"""
PURPOSE
Read the original database to get only the info we need.
Make sure data is valid, all relevant categories are not blank.
Write relevant data into new_database.csv. That database will be
used during the actual data mining and classification.
Info needed: Budget,... |
def _gini(rows):
"""
Calculate the Gini Impurity of the rows.
"""
# Count the unique class values and their frequency in rows
class_values = _count_class_values(rows)
gini_impurity = 1
# for each class value
for class_val in class_values:
prob = class_values[class_val] / float(l... | This function identifies the optimal attribute-value split to maximize information gain for a decision tree, excluding 'revenue' and 'title' columns. It calculates Gini impurity, iterates through each attribute's unique values, partitions data, skips empty splits, computes information gain, and retains the highest gain... | def _get_best_split(rows):
"""
Get the best split by iterating over every attribute
and its value and calculating its information gain
"""
best_gain = 0 # to hold the best gain to split
best_split_crit = None # to hold the best splitting criterion
current_uncertainty = _gini(rows)
size... |
def _get_best_split(rows):
"""
Get the best split by iterating over every attribute
and its value and calculating its information gain
"""
best_gain = 0 # to hold the best gain to split
best_split_crit = None # to hold the best splitting criterion
current_uncertainty = _gini(rows)
size... | The function `_build_tree` recursively constructs a decision tree by partitioning data rows based on the best splitting criterion (max information gain). If gain is zero (homogeneous class labels), it returns a leaf node. Otherwise, it splits data into true/false branches, recursively builds subtrees for each, and retu... | def _build_tree(rows):
"""
Build a tree using recursion
Base case: Information Gain = 0 (Class labels are equal)
Return Leaf
Else...
Split the rows using the best splitting criterion
"""
# Get the best gain and splitting criterion
gain, split_crit = _get_... |
def split_dataset(dataset, train_ratio):
"""
Split the data into training and testing dataset
"""
size = len(dataset) # size of dataset
# Shuffle the dataset randomly
shuffle(dataset)
# Split the data
train_data = dataset[:int(train_ratio * size)]
test_data = dataset[int(train_rat... | The main task of the code is to compute the average accuracy of a decision tree model over `n` trials by repeatedly splitting the dataset into training and test sets, building a tree, and evaluating its performance. It accumulates accuracy across trials, divides by `n` to calculate the average, and prints the result, p... | def _get_av_accuracy(dataset, train_ratio, n):
"""
Split the data n times and build a tree to find out the
average accuracy and the average time to build the tree.
"""
av_accuracy = 0
for i in range(n):
train, test = split_dataset(dataset, train_ratio)
tree = _build_tree(train)... |
def show_instructions():
"""Show the game instructions"""
# Print the game instructions
print('''
RPG Game
========
Commands:
go [direction]
get [item]
map ['m']
use [item]
instructions ['i']
status ['s']
''')
print('''
To win the game defeat
... | This code implements a text-based adventure game where a player navigates rooms, collects items, battles creatures (dragon, griffin, gnome, sphinx), and completes objectives. The player's health depletes upon failure, while acquiring specific items (key, trophy) triggers win/loss conditions. The loop processes commands... | def main():
# Initialize the player object and set the starting room
player = {
'current_room': 'Hall',
'inventory': ['map'],
'health': 100,
'counter': 0,
'dragon_defeated': 0,
'book': []
}
show_instructions()
objective1()
show_status(player)
... |
def load_lrit(fpath):
"""
Load LRIT file and return data field
"""
# Read file bytes from disk
file = open(fpath, mode="rb")
fileBytes = file.read()
headerLen, dataLen = parse_primary(fileBytes)
# Split file bytes into fields
headerField = fileBytes[:headerLen]
dataField = file... | The code processes image segments by loading their data fields, combining them into a single JPEG image based on the specified mode. It calculates vertical offsets for each segment, pastes them into a new image, and saves the final composite as a high-quality JPEG file. | def process_group(name, mode, files):
"""
Load data field of each segment and combine into one JPEG
"""
print("Processing {}...".format(name))
print(" Loading segments", end='')
segmentDataFields = []
# Load each segment from disk
for seg in files:
# Load file
headerF... |
def parse_fname(fpath):
"""
Parse LRIT file name into components
"""
split = fpath.split("_")
mode = split[1]
name = fpath.replace(".lrit", "")[:-3]
name = "IMG_" + name.split("IMG_")[1]
segment = int(split[6][:2])
return name, mode, segment
def get_total_segments(mode):
"""
... | The main task of the code is to parse input arguments, locate LRIT image files, group them into complete images by analyzing filenames, check for missing segments, and process them as groups or individual segments based on flags. It skips already generated images and handles unrecognized modes, ensuring only valid, unp... | def init():
"""
Parse arguments then locate images and segments
"""
# Check if input is a directory
if os.path.isdir(args.INPUT):
# Loop through files with .lrit extension in input folder
for f in glob.glob(args.INPUT + "/*.lrit"):
files.append(f)
files.sort()
... |
def _configurePort(self):
if (self._enableEcho() and self._disableFlowControl and self._disableRingAlerts() and self.ping()):
return True
else:
return False
def ping(self):
self._ensureConnectionStatus()
command = "AT"
self.s.write(f"{command}\r".enc... | This code initializes a serial connection to a RockBlock device using the specified port, configures the port settings, verifies connectivity with a ping, and triggers a callback if the connection succeeds. If any step fails, it raises an exception. The main task is establishing and validating a serial communication li... | def __init__(self, portId, callback):
self.s = None
self.portId = portId
self.callback = callback
self.autoSession = True
# When True, we'll automatically initiate additional sessions if more messages to download
try:
self.s = serial.Serial(self.portId, 192... |
def _ensureConnectionStatus(self):
if (self.s == None or self.s.isOpen() == False):
print("ensureConnectionStatus failed")
raise rockBlockException()
def _attemptConnection(self):
print("482 attempt connnection started")
self._ensureConnectionStatus()
TIME_ATTEMP... | The main task of the code is to check and establish a connection/session, trigger callbacks for reception start/failure, and return True if both connection and session attempts succeed, otherwise trigger failure callback. | def messageCheck(self):
self._ensureConnectionStatus()
if (self.callback != None and callable(self.callback.rockBlockRxStarted)):
self.callback.rockBlockRxStarted()
if (self._attemptConnection() and self._attemptSession()):
return True
else:
if (s... |
def _ensureConnectionStatus(self):
if (self.s == None or self.s.isOpen() == False):
print("ensureConnectionStatus failed")
raise rockBlockException()
def _queueMessage(self, msg):
try:
self._ensureConnectionStatus()
if (len(msg) > 340):
pr... | The main task of the code is to send a message via a RockBlock connection with retry logic. It checks connection status, triggers a "tx started" callback, queues the message, and attempts to establish a session up to three times with delays. If successful, it returns True; otherwise, it triggers a "tx failed" callback ... | def sendMessage(self, msg):
self._ensureConnectionStatus()
if (self.callback != None and callable(self.callback.rockBlockTxStarted)):
self.callback.rockBlockTxStarted()
print("179 starting if check on sendMessage")
try:
print("181 before queueMessage and Atte... |
def make_group_names():
stimulus_types = ['blocked', 'random']
#model_types = ['Two stimulus types, no RT', 'Two stimulus types, RT mod',
# 'Two stimulus types, RT dur',
# 'Two stimulus types, 2 RT dur only']
model_types = ['Two stimulus types, no RT', 'Two stimulus types... | The code simulates and analyzes reaction time (RT) data across multiple subjects and trials under varying RT difference conditions. It evaluates statistical power and correlations by generating synthetic data with specified distributions, adding noise, fitting models, and computing p-values and correlations between mod... | def group_2stim_rt_diff_vec(n_trials, repetition_time=1, mu_expnorm=600,
lam_expnorm=1 / 100, sigma_expnorm=75, max_rt=2000,
min_rt=0, event_duration=2, ISI_min=2, ISI_max=5,
win_sub_noise_sd={'dv_scales_yes': .1, 'dv_scales_no': .1},
btwn_sub_noise_sd={'dv_scal... |
def make_group_names():
stimulus_types = ['blocked', 'random']
#model_types = ['Two stimulus types, no RT', 'Two stimulus types, RT mod',
# 'Two stimulus types, RT dur',
# 'Two stimulus types, 2 RT dur only']
model_types = ['Two stimulus types, no RT', 'Two stimulus types... | This function simulates and evaluates statistical power/rejection rates for models with two stimulus types, varying beta2 parameters. It generates synthetic data with noise, fits models to each subject's data, and calculates p-values across simulations to assess how often effects are detected (rejection rates) under di... | def group_2stim_beta2_vec(n_trials, repetition_time=1, mu_expnorm=600,
lam_expnorm=1 / 100, sigma_expnorm=75, max_rt=2000,
min_rt=0, event_duration=2, ISI_min=2, ISI_max=5,
win_sub_noise_sd={'dv_scales_yes': .1, 'dv_scales_no': .1},
btwn_sub_noise_sd={'dv_scales... |
def project_point(camera, point3D):
M = camera.intr_extr
point2D = np.dot(M, np.array(
[point3D[0], point3D[1], point3D[2], 1], np.float32))
return point2D[:2] / point2D[2]
def compute_photo_consistency_along_ray(image0, image1, camera0, camera1, pixel0, photo_consistency_function, support_domain):... | The code projects a 3D point onto two images using camera parameters, computes photoconsistency along a ray between the images, identifies the correct pixel position via SSD, and visualizes consistency scores. It highlights the actual pixel location with a red line, compares maximum consistency with the true position, ... | def plot_photoconsistency_along_ray(
image0, image1, camera0, camera1, point3D, pc_func, support_domain):
# Project points to 2D
pixel0 = project_point(camera0, point3D).astype(np.int)
pixel1 = project_point(camera1, point3D).astype(np.int)
# Shoot a ray from camera0 through the pixel. Walk alo... |
def getE(W):
'''
get the energy from expansion coefficients for Ns unconstrained wave function
@input:
W: Expansion coefficients for Ns unconstrained wave functions, stored as
an (S0 * S1 * S2, Ns) matrix
@global variables
Vdual: Dual potential coefficients stored as a (S0 *... | The function performs preconditioned line minimization to minimize energy $ e $ by iteratively adjusting weights $ W $ using gradient descent with a dynamically computed step size $ \alpha $. It calculates the gradient $ g $, determines the search direction $ d $ as the negative preconditioned gradient $ -K(g) $, and u... | def pclm(W, niter):
'''
perform preconditioned line minimization for niter iterations to minimize e
'''
alpha_t = 3e-5
e = getE(W)
out_str = 'iteration: {:3d}, energy: {:.6f}, angle cosin: {:.3f}'
print(out_str.format(0, e, 0))
d = None # search direction from last step
for i in ran... |
def getE(W):
'''
get the energy from expansion coefficients for Ns unconstrained wave function
@input:
W: Expansion coefficients for Ns unconstrained wave functions, stored as
an (S0 * S1 * S2, Ns) matrix
@global variables
Vdual: Dual potential coefficients stored as a (S0 *... | The function performs preconditioned conjugate gradient (PCG) optimization for `niter` iterations to minimize energy `e`. It combines preconditioning (via `K`), line search (adjusting step size `alpha`), and conjugate gradient steps (computing search direction `d` with beta). The algorithm iteratively updates the param... | def pccg(W, niter):
'''
perform preconditioned conjugate gradient for niter iterations to minimize e
1, precondition
2, line minimizaton/line search
3, conjugate gradient
'''
alpha_t = 3e-5
e = getE(W)
out_str = 'iteration: {:3d}, energy: {:.6f}'
print(out_str.format(0, e, 0))
... |
def orthonormalizeW(W):
'''
orthonormalize W so that Wdag dot O(W) is identity matrix
'''
U = np.dot(W.conj().T, op.O(W))
U_inv = np.linalg.inv(U)
U_inv_sqrt = linalg.sqrtm(U_inv)
W_orthonormal = np.dot(W, U_inv_sqrt)
return W_orthonormal
def sd(W, niter):
'''
perform steepest de... | The code tests a quantum system simulation by generating random complex wavefunctions, orthonormalizing them, calculating energy levels in a harmonic potential, and visualizing electron density for s and p orbitals. It verifies expected energy levels (3, 5, 5, 5) and plots 3D slices of orbital densities. | def test_all():
ns = 4
W = np.random.rand(np.prod(global_vars.S), ns) + 1j * np.random.rand(np.prod(global_vars.S), ns)
W = orthonormalizeW(W)
sd(W, 500)
epsilon, Psi = getPsi(W)
# in harmonic potential with w = 2, the energy level should be 3, 5, 5, 5
print('energy levels: {:.3f}, {:.3f}, {... |
def orthonormalizeW(W):
'''
orthonormalize W so that Wdag dot O(W) is identity matrix
'''
U = np.dot(W.conj().T, op.O(W))
U_inv = np.linalg.inv(U)
U_inv_sqrt = linalg.sqrtm(U_inv)
W_orthonormal = np.dot(W, U_inv_sqrt)
return W_orthonormal
def sd(W, niter):
'''
perform steepest de... | The code tests a quantum system's energy levels and visualizes electron density in a harmonic potential. It generates random orthonormal states, computes eigenvalues (epsilon) for expected energy levels (3, 5, 5, 5), and visualizes s/p-orbital electron density distributions using 3D slices. | def test_all():
ns = 4
W = np.random.rand(np.prod(global_vars.S), ns) + 1j * \
np.random.rand(np.prod(global_vars.S), ns)
W = orthonormalizeW(W)
sd(W, 500)
epsilon, Psi = getPsi(W)
# in harmonic potential with w = 2, the energy level should be 3, 5, 5, 5
print('energy levels: {:.3f},... |
def orthonormalizeW(W):
'''
orthonormalize W so that Wdag dot O(W) is identity matrix
'''
U = np.dot(W.conj().T, op.O(W))
U_inv = np.linalg.inv(U)
U_inv_sqrt = linalg.sqrtm(U_inv)
W_orthonormal = np.dot(W, U_inv_sqrt)
return W_orthonormal
def sd(W, niter):
'''
perform steepest de... | The code tests a machine learning model by initializing a complex weight matrix W, orthonormalizing it, and iteratively optimizing it using stochastic descent (sd) and preconditioned conjugate gradient (pccg) methods to minimize an objective function, likely for tasks like signal processing or neural network training. | def test_lm():
ns = 4
W = np.random.rand(np.prod(global_vars.S), ns) + 1j * \
np.random.rand(np.prod(global_vars.S), ns)
W = orthonormalizeW(W)
sd(W, 20) # use sd in first steps to get to near the minimum
W = orthonormalizeW(W)
pccg(W, 200) |
def print_menu():
'''Prints menu for user.'''
print('1) Count Digits\n2) Sum digits\n3) Is Palindrome\n4) Reverse\n5) Exit')
def count_digits(num):
'''Returns count of total digits.'''
num = str(num)
return len(num)
def sum_digits(num):
'''Adds every integer to a variable sum to produce sum of e... | This code provides a menu-driven interface for users to perform integer operations including counting digits, summing digits, checking palindromes, reversing numbers, and exiting. It uses a loop to repeatedly display the menu, process user choices, and execute corresponding functions until the user selects to terminate... | def main():
'''Runs program that allows user to perform integer operations.'''
running = True # loop control variable
while running:
print_menu()
user_choice = input('Choice: ')
if user_choice == '1':
user_int = int(input('Enter a positive int: \n'))
count = ... |
def QueryMap(self, module, storage_function, params = None, block_hash = None, max_results = None, start_key = None, page_size = 100, ignore_decoding_errors = False, debug=True):
if debug:
self._debug(1, f"QueryMap > {module} - {storage_function} - {params}")
data = self._query_map(module, ... | The SmartLedger function retrieves and processes staking ledger data for a given accountID. It checks if the account exists in the ledger or bonded maps, handling cases where the account is bonded to another. If not found, it queries the data, updates the maps, and returns the processed data with a 'bonded' flag, or No... | def SmartLedger(self, accountID):
ledger = self.QueryMap('Staking', 'Ledger', page_size=1000, max_results=10000, ignore_decoding_errors=True, debug=False)
if accountID in ledger.keys():
data = copy.deepcopy(ledger[accountID])
data['bonded'] = False
return data
... |
def ErasInfo(self, filters={}):
data = {}
if 'eras' in filters.keys():
eras = sorted(set(filters['eras']))
else:
activeEra = self.Query('Staking', 'ActiveEra')['index']
historyDepth = self.query('Staking', 'HistoryDepth').value
eras = sorted(set(r... | The function aggregates validator data by querying staking information, including preferences, stake details (own and nominator contributions), and era-specific rewards. It processes eras, nominators, and validator ledgers to compile a structured dataset with total stakes, rewards (points, amounts, unclaimed), and comm... | def ValidatorsInfo(self, filters={}, erasInfo=None):
data = {}
if erasInfo == None:
erasInfo = self.ErasInfo(filters)
erasInfo = copy.deepcopy(erasInfo)
validators = self.QueryMap('Staking', 'Validators', page_size=1000, max_results=10000)
nominators = self.QueryMa... |
def ErasInfo(self, filters={}):
data = {}
if 'eras' in filters.keys():
eras = sorted(set(filters['eras']))
else:
activeEra = self.Query('Staking', 'ActiveEra')['index']
historyDepth = self.query('Staking', 'HistoryDepth').value
eras = sorted(set(r... | The code retrieves and structures information about blockchain nominators, including their stakes, targets, and validator associations across eras. It aggregates data from ledger records and era-specific validator stakes, organizing details by nominator and era to provide a comprehensive overview of staking activities. | def NominatorsInfo(self, filters={}, erasInfo=None):
data = {}
if erasInfo == None:
erasInfo = self.ErasInfo(filters)
nominators = self.QueryMap('Staking', 'Nominators', page_size=1000, max_results=10000)
for nominatorID in nominators:
ledger = self.SmartLedger... |
def snip(self, screen):
# set screen shot
screen.blit(self.screenshot_img, (0, 0))
# draw overlay
overlay_color = (220, 220, 220)
overlay = pygame.Surface((pygame.display.get_surface().get_width(), pygame.display.get_surface().get_height()))
overlay.set_alpha(50)
... | This method updates the application's state by executing specific actions based on the current state (snipping, cropping, etc.) and screen input. It transitions between states like SNIPPING, CROPPING, CROP, and CROPPED, triggering corresponding operations. When in the CROPPED state and the window is in PANNING mode, it... | def update(self, screen):
if self.state == State.SNIPPING:
self.snip(screen)
elif self.state == State.CROPPING:
self.cropping(screen)
elif self.state == State.CROP:
self.crop(screen)
elif self.state == State.CROPPED:
self.cropped(screen)
... |
def _recursive_descent_parser(self, line: list, parse_inline: bool, final_token: str) -> str:
"""Recursively descend into and parse nested structures"""
result = ""
if len(line) == 0:
result += "\n"
line = self._get_next_line()
while line:
token = line... | This function parses a line of text into HTML by identifying its type (e.g., comments, headings, code blocks, block quotes, lists, or paragraphs) and applying corresponding transformation rules. It uses recursive parsing for nested elements and delegates specific tasks to helper functions like _parse_heading, _parse_bl... | def _parse_line(self, line: list) -> str:
"""Process a line"""
if len(line) == 0:
return ""
if line[0] == "<!--":
return "\n<!--" +\
self._recursive_descent_parser(line[1:], True, "-->") +\
"-->\n"
if line[0] in ['#', '##', '#... |
def _read_markdown(markdown_file_location: str) -> list:
"""Reads a markdown file and returns a list of lines"""
with open(markdown_file_location) as file:
return file.readlines()
def _compile(self):
"""Entry point where the parsing of markdown begins"""
html = ""
while self.md_t... | The code initializes a class to convert a markdown file into HTML and generate a preview. It reads the markdown content, compiles it into HTML using a private method, and creates a preview using the `get_preview` method, storing these as instance attributes for further use. | def __init__(self, markdown_file_location: str):
"""Initialize attributes"""
self.md_tokens = _read_markdown(markdown_file_location) # list
self.html = self._compile() # str
self.preview = self.get_preview() |
def check_availability(self) -> bool:
"""
This function checks is there are any available application places
"""
user_living_place = self.customer.address
self.driver.find_element(By.ID, "country").find_elements(By.TAG_NAME, "option")[2].click()
self.driver.find_eleme... | The main task of the code is to automate filling a multi-step application form by interacting with web elements, entering personal information, selecting travel dates, handling a calendar picker, solving reCAPTCHA, and updating customer data. It navigates through form sections, scrolls to buttons, sets dynamic dates, a... | def fill_form(self) -> None:
"""Fill the entire form."""
order_by = "increase"
if self.check_availability():
self.driver.find_element(By.ID, 'btnAppCountNext').click()
wait = WebDriverWait(self.driver, 10)
self.fill_personal_info()
... |
def get_factory_name(factory_class: FactoryType) -> str:
"""Get factory fixture name by factory."""
return inflection.underscore(factory_class.__name__)
def make_declaration_fixturedef(
attr_name: str,
value: Any,
factory_class: FactoryType,
related: list[str],
) -> Callable[..., Any]:
"""Cr... | The main task of the code is to generate fixture definitions (FixtureDefs) for a given factory class. It creates fixtures for each declared attribute with overrides, generates a factory fixture if not already present in the caller's scope, and constructs a model fixture incorporating dependencies and related fields. Th... | def generate_fixtures(
factory_class: FactoryType, model_name: str, overrides: Mapping[str, Any], caller_locals: Mapping[str, Any]
) -> Iterable[tuple[str, Callable[..., Any]]]:
"""Generate all the FixtureDefs for the given factory class."""
factory_name = get_factory_name(factory_class)
related: list[... |
def eval(self, dataset_idx, biases=None, preprune = True):
"""Performs evaluation."""
print("Current idx: " + str(self.pruner.current_dataset_idx))
if not self.args.disable_pruning_mask:
print("Applying dataset mask for dataset: ", dataset_idx)
self.pruner.apply_mask(dat... | The code performs pruning on a neural network by evaluating the model before pruning, applying the pruning process, checking the pruned model, evaluating post-pruning accuracy, saving the pruned model, and optionally conducting fine-tuning to enhance performance. It also outputs pruning summaries and metrics. | def prune(self):
"""Perform pruning."""
print('Pre-prune eval:')
### Preprune reflects whether or not pruning has occured yet for the given task
self.eval(self.pruner.current_dataset_idx, preprune = True)
self.pruner.prune()
self.check(True)
print('\nPost-prune ... |
def initialize_3D_4th_rank_tensor(gamma_tuples):
coordinates = [0, 1, 2]
gamma = [[[[None for l in coordinates] for k in coordinates] for j in coordinates] for i in coordinates]
for indices, gamma_val in gamma_tuples:
gamma[indices[0]][indices[1]][indices[2]][indices[3]] = gamma_val
return gamma... | This function computes the third-order nonlinear susceptibility tensor (χ³) from raw gamma values by applying rotation averaging and Lorentz-Lorenz corrections, using input frequencies and molecular density. It initializes symbolic tensors, processes gamma data, calculates frequency-dependent corrections, and displays ... | def compute_and_display_chi3_from_raw_gamma(gamma_tuples, numb_density, lambda_out, lambda_1, lambda_2, lambda_3):
"""
Parameters:
gamma_tuples: list of tuples
gamma value in atomic units
[(axis0, axis1, axis2, axis3), gamma_value),...]
lambda_out: float
outpu... |
def initialize_3D_4th_rank_tensor(gamma_tuples):
coordinates = [0, 1, 2]
gamma = [[[[None for l in coordinates] for k in coordinates] for j in coordinates] for i in coordinates]
for indices, gamma_val in gamma_tuples:
gamma[indices[0]][indices[1]][indices[2]][indices[3]] = gamma_val
return gamma... | The function computes the corrected third-order susceptibility tensor (χ³) from input gamma and alpha tensors, applying the Lorentz-Lorenz local field correction using given number density and wavelengths. It initializes symbolic tensors, calculates uncorrected χ³, applies corrections, and displays results. The output ... | def compute_and_display_chi3_from_raw_gamma_alpha(gamma_tuples, alpha_tuples, numb_density, lambda_out, lambda_1, lambda_2, lambda_3):
"assumes all lambdas are the same"
chi3_elms = sp.symbols("chi^(3)_x:zx:zx:zx:z")
coordinates = [0, 1, 2]
# initializing chi3 symbolic tensor
chi3_sym = [[[[chi3_el... |
def check_house(self, complex: str, house: str) -> bool:
"""
Check if given house exists in the rumetr database
"""
self.check_complex(complex)
if '%s__%s' % (complex, house) in self._checked_houses:
return True
try:
self.get('developers/{develope... | This method adds a new apartment to a real estate database by formatting price and square parameters into decimals, then sending a POST request to a specific API endpoint under a developer's complex and house, using additional keyword arguments for data submission. | def add_appt(self, complex: str, house: str, price: str, square: str, **kwargs):
"""
Add a new appartment to the rumetr db
"""
self.check_house(complex, house)
kwargs['price'] = self._format_decimal(price)
kwargs['square'] = self._format_decimal(square)
self.pos... |
def check_house(self, complex: str, house: str) -> bool:
"""
Check if given house exists in the rumetr database
"""
self.check_complex(complex)
if '%s__%s' % (complex, house) in self._checked_houses:
return True
try:
self.get('developers/{develope... | This method updates an existing apartment by sending a PUT request to a specific API endpoint with formatted price and square data, after validating the house details. It constructs the URL using provided identifiers and includes additional parameters via **kwargs. | def update_appt(self, complex: str, house: str, price: str, square: str, id: str, **kwargs):
"""
Update existing appartment
"""
self.check_house(complex, house)
kwargs['price'] = self._format_decimal(price)
kwargs['square'] = self._format_decimal(square)
self.pu... |
def add_assignment(base_folder, exercise_number):
"""Adds assignment """
# Assignment name
assignment = "Exercise-%s" % exercise_number
print("Adding assignment %s" % assignment)
subprocess.call([ "nbgrader", "db", "assignment", "add", "%s" % assignment], cwd=base_folder)
return True
def up... | The main task of the code is to process a list of exercises by creating assignments, updating an autograding repository from GitHub, and generating release files for each exercise using nbgrader. It iterates through defined exercises, ensuring assignments are added and autograding resources are synchronized, streamlini... | def main():
# Iterate over exercises if they are defined
if len(exercise_list) > 0:
for enumber in exercise_list:
# Create Assignment
added = add_assignment(base_folder, enumber)
# Clone / pull the autograding repository from GitHub... |
def get_token():
"""Gets secure GitHub token for committing"""
token = os.getenv('GH_TOKEN')
return token
def create_submitted_folder(base_f):
"""Creates a submitted folder if it does not exist."""
# Submitted folder
submitted_f = os.path.join(base_f, "submitted")
# Check if the folder ... | The main task of the code is to clone and manage student GitHub repositories for exercises, handling multiple exercise types and users. It creates directories, updates repositories (clone/pull), renames folders for nbgrader compatibility, and handles additional classroom/extras repos, ensuring proper folder structures ... | def main():
# Get token
token = get_token()
# Iterate over exercises if they are defined
if len(exercise_list) > 0:
for enumber in exercise_list:
# Create submitted folder if it does not exist
submitted_f = create_submitted_folder(base_folder)
... |
def parse_html(self, html):
html = html.replace("<br>", "\n")
rows, num_header_rows = self.parse_into_rows(html)
num_cols = sum(val[-1] for val in rows[0])
new_rows = []
rowspan = {}
# deal with muti-row or multi col cells
for i, row in enumerate(rows):
... | This code renders an HTML table into a visual format using matplotlib. It parses HTML to extract rows and headers, calculates column/row dimensions, initializes a figure with specified DPI, and generates a rendered table output. The process involves setting font size, configuring rendering parameters, and structuring t... | def run(self, html):
self.fontsize = self.original_fontsize
self.text_fig = Figure(dpi=self.dpi)
self.renderer = RendererAgg(self.figwidth, self.figheight, self.dpi)
self.rows, self.num_header_rows = self.parse_html(html)
self.col_widths = self.calculate_col_widths()
self... |
def verification_all_values(id, name, type, description, usage, source, cve, attackos, phase):
if verify_id(id):
if verify_input(name):
veri_type = verify_type(type)
if veri_type != False:
type = veri_type
if verify_input(description):
... | The main task of the code is to update an item's details in a SQLite database, including handling many-to-many relationships with attackos. It verifies input values, updates the 'items' table, deletes existing 'item_attackos' entries for the item, inserts new entries for specified attackos, and commits changes. | def update_item(id, name, type, description, usage, source, cve, attackos, phase):
if verification_all_values(id, name, type, description, usage, source, cve, attackos, phase):
#try:
# Make connection with db file
conn = sqlite3.connect(sys.path[0] + '/cli/database.db')
cur = conn.cu... |
def welcome(text):
result = Figlet()
return colored.green(result.renderText(text))
def print_allitems():
head = ["id", "name", "type", "description", "usage", "source", "cve", "phase", "attack_oses"]
items = getdbinfo()
## Tabulate solution
ITER_items=[]
for item in items:
ITER_item... | This function provides a command-line interface for managing items. It displays options to list items, search items, add items, or return. Based on user input, it clears the screen, shows relevant menus, and invokes corresponding functions like print_allitems(), additemcli(), or exits the loop. The loop persists until ... | def startcommandline():
first = True
while True:
if first:
os.system("clear")
print(welcome("LeutMesiene"))
print("Command line utility\n")
first = False
print("Please select an option: ")
print("""\t1 : List items
2 : Sear... |
def setupGUI(self) -> tuple[dict[str]]:
"""
The main function that sets up all UI elements and encapsulates all functional return values
along with their potentially bound functions.
"""
###### Window Properties ########
self.geometry("400x335")
self.wid... | This code initializes a GUI window with timers and phase indicators, setting up UI components, encapsulating timer/image objects, and associating callbacks to synchronize phase changes and timer events with visual updates and state transitions in a Tkinter application. | def __init__(self, timerArgs: dict, *args, **kwargs):
# Set some basic options for our new top level window
tk.Toplevel.__init__(self, *args, **kwargs)
# These are properties of the boss itself that may be modified by our hotkeys later
self.observablePhaseInd = tk.IntVar(self, value = 0... |
def set_initial_states(self, decay_step):
self.g_step = tf.Variable(0., trainable=False)
self.lr = tf.train.exponential_decay(
self.init_lr, # Base learning rate.
self.g_step * self.batch_size, # Current index into the dataset.
decay... | The code dynamically expands or modifies a neural network during training based on performance thresholds. It performs selective retraining, prunes inactive units, and adds new units if the loss exceeds a threshold. The method handles network expansion, splitting, and duplication of layers to enhance model capacity whi... | def add_task(self, task_id, data):
trainX, trainY, self.valX, self.valY, testX, testY = data
self.train_range = np.array(range(len(trainY)))
data_size = len(trainX)
self.set_initial_states(data_size)
expansion_layer = [] # to split
self.expansion_layer = [0, 0] # new uni... |
def sort_detected_obj(predict_df, mode='chars'):
"""
function for sort detected by model object
predict_df - model recognition result in Pandas DataFrame format
mode - string param. If mode = 'chars' function applied sort algorithm for chars in plate,
if mode = 'plate' - function sort object (plates... | The function detects license plates in an image using two PyTorch models (model_plates and model_chars). It processes detected plates by sorting them, extracts character labels from plates via model_chars, and overlays bounding boxes with labels on the original image. If no plates are detected, it returns the original ... | def final_detect(image_array, model_plates, model_chars, font_path):
"""
image_array - NumPy array
model_plates, model_chars - PyTorch models
return - result image in numpy array format
"""
results_plates = model_plates(image_array, size=1280) # recognize image_array
pred_list_plates = resu... |
def normalize(v):
return v / sum(abs(v))
def getBaseColor(self, pt):
return self.material.color
def getShadow(self, pt, shapeSet, light_vector):
# check for intersection with other objects
r = Ray(pt, light_vector)
i = Intersection(r, RAY_T_MAX)
if shapeSet.doesIntersect(i, s... | The function calculates the color at a ray-intersection point by combining base material color, lighting effects from a light source, and refraction. It adjusts for shadows using shadow_color, which scales the total color. If refraction is enabled, it adds refracted light; otherwise, it uses black. The final color is s... | def getColor(self, intersection, light, shapeSet):
# Intersection has occured
pt = intersection.ray.calculate(intersection.t)
light_vector =normalize(light.center - pt)
base_color = self.getBaseColor(pt)
shadow_color = self.getShadow(pt, shapeSet, light_vector)
# if spo... |
def normalize(v):
return v / sum(abs(v))
def getShadow(self, pt, shapeSet, light_vector):
# check for intersection with other objects
r = Ray(pt, light_vector)
i = Intersection(r, RAY_T_MAX)
if shapeSet.doesIntersect(i, self):
return 1 - np.sqrt(self.material.color) + 0.1... | The function calculates the final color at an intersection point by combining shadow, light, and refraction effects. It computes the light vector, checks for shadows, determines light contribution, handles refraction if enabled, and blends these components using the material's refraction weight to produce the final col... | def getColor(self, intersection, light, shapeSet):
# Intersection has occured
pt = intersection.ray.calculate(intersection.t)
light_vector =normalize(light.center - pt)
#base_color = self.getBaseColor(pt)
shadow_color = self.getShadow(pt, shapeSet, light_vector)
# if sp... |
def abstract_score_preprocessing(self):
f = open("model\mrc_data.txt", "r")
data = f.read().split('\n')
for row in data:
word = row.strip()[:-3].strip().lower()
if(word in self.model.wv.vocab):
self.word_embeddings.append([self.model.wv[word]])
self.scor... | The main task of the code is to train a metaphor identification model by preprocessing text, computing context vectors for sentences, finding semantically similar contexts, analyzing candidate words via cosine similarity, and predicting metaphors. It also generates abstractive summaries of input sentences through speci... | def fit(self,sentences):
print("Training the model............")
self.abstract_score_preprocessing()
self.pcaf()
self.find_target_words(sentences)
for sentence in self.sentences_tokenized:
self.context_vectors.append(self.compute_context_vector(sentence))
for ... |
def perform_inference(sbi_params, sim_params,
data_params, neuron_params,
posterior, trial_dataset):
"""Infer parameters from all trials pre and post stimulus change."""
# Perform inference
# trials_to_fit = trial_dataset[trial_dataset['fit_trial']]
# trials_t... | This function either fits all trials from scratch using perform_inference or loads pre-existing fitted data, depending on the 'fresh_fitting' flag. It saves results to disk if fitting anew, handling missing files by automatically initiating inference. The core task is managing posterior parameter estimation for trial d... | def infer_parameters_for_all_trials(run_params, sbi_params, sim_params,
data_params, neuron_params,
plot_params, save_folder,
data_folder, posterior, trial_dataset):
"""Load or create posterior and sample pri... |
def gameOverFunc(self):
global running
if self.gameOverCounter == 12:
running = False
self.recordHighScore()
return
# Resets the screen around pacman
self.drawTilesAround(self.pacman.row, self.pacman.col)
# Draws new image
pacmanImage... | The code updates the game state by managing Pacman and ghost movements, checking for collected items, updating scores, handling level transitions, and rendering the game. It processes game logic like ghost behavior, power pellet effects, and checks for victory or game over conditions, while maintaining timing for anima... | def update(self):
# pygame.image.unload()
print(self.ghostStates)
if self.gameOver:
self.gameOverFunc()
return
if self.paused or not self.started:
self.drawTilesAround(21, 10)
self.drawTilesAround(21, 11)
self.drawTilesAround(21... |
def generate_anchors(self, lateral_n, bottom_n):
left_anchors, left_cut = self.generate_side_anchors(self.left_angles, x=0., nb_origins=lateral_n)
right_anchors, right_cut = self.generate_side_anchors(self.right_angles, x=1., nb_origins=lateral_n)
bottom_anchors, bottom_cut = self.generate_side_... | This code initializes a neural network model for lane detection using anchor-based approach and attention mechanisms. It sets up parameters for feature extraction, generates anchor points for lane positioning, filters anchors using frequency data, and initializes convolutional layers, classification/regression heads, a... | def __init__(self,
backbone='resnet34',
pretrained_backbone=True,
S=72,
img_w=640,
img_h=360,
anchors_freq_path=None,
topk_anchors=None,
anchor_feat_channels=64,
cfg=N... |
def get_data_name(self, lablefile):
base_name = os.path.splitext(os.path.basename(lablefile))[0]
data_files = list(filter(lambda a: a.startswith(base_name), self.images))
if len(data_files) == 0:
raise AttributeError(f"no data for {base_name}")
return data_files[0]
def mask_o... | This code defines the `__getitem__` method of a dataset class, which loads and preprocesses image-mask pairs. It constructs file paths for images and masks, loads them using specified openers, applies relabeling if enabled, and applies transformations to both image and mask. The method returns a dictionary containing t... | def __getitem__(self, idx):
mask_name = os.path.join(self.mask_dir, self.masks[idx])
img_name = os.path.join(self.image_dir, self.get_data_name(self.masks[idx]))
mask = self.mask_opener(mask_name)
relabel = False
if relabel:
mask = self.mask_to_other(mask)
# m... |
def showTime(self,tick):
time_var = datetime.now().strftime("%H:%M:%S")
return time_var
def updateTime(self, tick):
Clock.schedule_interval(self.showTime,1)
def setTargetTime(self,update_list):
for i in range(6):
hour = random.randint(10,20) # ra... | The main task of the code is to initialize a process by printing the survey number, updating time-related parameters, setting target times, checking notifications, and enabling continuous monitoring. It executes preparatory steps for time management and notifications before delegating further execution to the parent cl... | def on_start(self):
print("Survey Number on start: ",self.survey_number)
self.showTime(1)
self.updateTime(1)
self.setTargetTime(self.time_list)
self.checkNotification(1)
self.conituousylyCheck(1)
#print("Survey Number on start: ",self.survey_number)
return... |
def update_value(self, i, j):
error = self.R[i][j] - self.predict_value(i, j)
self.bias_U[i] += self.lr * (error - self.reg * self.bias_U[i])
self.bias_V[j] += self.lr * (error - self.reg * self.bias_V[j])
# self.bias_U[i] += self.lr * (error)
# self.bias_V[j] += self.lr * (error)
#pdb.set_trace()
dU = ... | This code trains a matrix factorization model for collaborative filtering by initializing user and item latent factors (U, V), biases, and a global bias. It iteratively updates these parameters using stochastic gradient descent over training data, computes loss and validation loss, and checks for overfitting. The model... | def train(self):
"""
R = U X V^T
"""
self.U = np.random.normal(scale=0.1,size=(self.M, self.f))
self.V = np.random.normal(scale=0.1,size=(self.N, self.f))
# self.U = np.zeros((self.M, self.f))
# self.V = np.zeros((self.N, self.f))
self.bias_U = np.zeros(self.M)
self.bias_V = np.zeros(self.N)
self.b... |
def draw(width, height):
print("\033c")
global display
for i in range(width):
for j in range(height):
if display[i][j] == 1:
print("┃", end="")
elif display[i][j] == 3:
print("●", end="")
else:
print(' ', end='')
... | The code implements a game loop that handles user input via a separate thread, updates game elements (paddle, ball), renders the display, tracks scores, and exits on 'q'. It maintains global variables for resolution, paddle size, and game state, updating the screen at a fixed interval while processing input and game lo... | def main():
global resolution_x
global resolution_y
global paddle_length
global display
global key
global thread_flag
global counter
p = Thread(target=get_input, args=())
p.start()
while (key != 'q'): # quit
draw(resolution_x, resolution_y)
update_paddle(resolut... |
def is_user(self, user_id: str) -> bool:
""" Return whether the user in in the database
:param user_id: The user ID of the person
"""
try:
user = self.db.collection(constants.COLLECTION).document(user_id).get()
if user.exists:
return True
... | This method deletes a user by first verifying their existence, then removing all their friendships, and finally deleting their database entry. | def delete_user(self, user_id: str) -> None:
""" Delete the user if it exists
:param user_id: Id of the user
"""
if self.is_user(user_id):
user_data = self.get_user_data(user_id)
for friend in user_data['friends']:
self.un_friend(by=user_id, to=... |
def tick_wait_time(self):
#have all the cars increase their wait time by 1 that are in the lanes going toward the intersection
for lane in self.toward_lanes:
for j in lane.contents:
if j != 0:
self.total_wait_time += 1
j.tick()
... | The code simulates moving vehicles through an intersection by updating wait times, moving cars in away lanes, handling intersection movement, managing green/red lane traffic, enabling right-on-red maneuvers, and updating the intersection model. It also checks for traffic light phase changes, incrementing counters to de... | def move(self):
#increase the wait time of all of the cars in the toward lanes
#need to tick cars in intersection
self.tick_wait_time()
#move all of the cars that are going away from the intersection
#then move the cars that are in the intersection into the right away lanes
... |
def util_map(self):
strawb = 1
pits = -1
human = -1
#Arrays for locations
strawb_loc = []
human_loc = []
pit_loc = []
robot_loc = (self.gameWorld.getRobotLocation().x, self.gameWorld.getRobotLocation().y)
#Get Strawberry ... | The code's main task is to determine the optimal robot action in a grid-based environment by analyzing the map, collecting entity positions (robot, strawberries, humans, pits), and using a utility function to select actions. It incorporates user feedback to adjust actions, updates a reward map with reinforcement learni... | def makeMove(self):
self.map = self.util_map()
robot_loc = (self.gameWorld.getRobotLocation().x, self.gameWorld.getRobotLocation().y)
#Arrays for locations
strawb_loc = []
human_loc = []
pit_loc = []
#G... |
def create_timestamped_directory(base_path: str) -> str:
"""Creates a directory with a timestamp as its name and returns its path."""
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
dir_path = os.path.join(base_path, timestamp)
os.makedirs(dir_path, exist_ok=True)
return dir_path
def proces... | The main task of the code is to process and embed data from a database in batches using a multithreaded approach. It initializes components like an embedder, data fetcher, and database connection, then iterates over batches to generate embeddings, manage memory constraints, and save results incrementally. The process h... | def main(args) -> None:
print("[Main] Starting...")
### Initialization ###
DATABASE_PATH = args.database_path
BATCH_SIZE = args.batch_size
DESCRIPTION_CHUNK_SIZE = args.description_chunk_size
OUTPUT_DIR = args.output_dir
MAX_MODEL_BATCH_SIZE = args.max_model_batch_size
SAVE_EVERY_N_BATC... |
def get_basic_inputs(inputs, task):
if task in ['mr', 'cr', 'SST-2', 'sst-5', 'subj', 'TREC']:
new_inputs = [ input_str for input_str in inputs ]
elif task in ['CB', 'MRPC', 'QNLI', 'QQP', 'RTE']:
new_inputs = [ input_str[0] + ' </s> ' + input_str[1] for input_str in inputs] # concat trick for... | The code processes and saves GLUE task data based on the specified mode. In mode 0, it generates basic input formats and stores them. In mode 1, it creates prompt-based inputs using masks for each tindex. In mode 2, it employs verbalizers and demonstration examples to generate prompt inputs, saving transformed data wit... | def main(args):
### data processing
data = GLUETask(args.task, args.train, args.valid, args.test)
new_train_labels = data.train_labels
new_valid_labels = data.valid_labels
new_test_labels = data.test_labels
if args.mode == 0:
new_train_inputs = get_basic_inputs(data.train_inputs, data.... |
def is_goal(state):
if state==goal:
return True
return False
def successors(state):
current_state = [state[i:i+ROWS] for i in range(0,len(state),ROWS)]
successor_nodes=[]
# MOVE_LEFT
for i in range(ROWS):
child1=move_left(current_state,i)
child_node = [x for sublist in child1... | The code implements an A* search algorithm to solve a puzzle (e.g., Rubik's cube) by finding the optimal sequence of moves. It uses a priority queue (heapq) to explore states, where each node tracks the current board configuration and move history. The heuristic function estimates the distance to the goal, guiding the ... | def solve(initial_board):
"""
1. This function should return the solution as instructed in assignment, consisting of a list of moves like ["R2","D2","U1"].
2. Do not add any extra parameters to the solve() function, or it will break our grading and testing code.
For testing we will call this function... |
def check_offsets(self) -> None:
"""
Updates the offsets of the grid.
Offsets are calculated based on the current position, visited cells and position of obstacles.
"""
xwest, ynorth, xeast, ysouth = self._offsets
visited = self.occupied_grid()
x0, y0 = s... | (The function advances a coverage solver by generating subgrids, analyzing free boundaries, and solving navigation problems. It checks for unvisited cells, defines problem types (complete/partial), and computes paths. If unsolvable, it increases subgrid size and adjusts offsets. Returns the path and a flag indicating i... | def proceed(self, subgrid_dim: int=5, offsets: Optional[List[int]] = None) -> Tuple[Union[np.array, bool]]:
"""
Advances the coverage solver by generating a subgrid and solving the corresponding problem.
Parameters
----------
subgrid_dim (int, optional): The dimension of the... |
def display_instruct():
"""Display game instructions"""
print(
"""
You will make you move known by entering a number 0-8. The number
will correspond to the board position as illustrated:
0 | 1 | 2
---------
3 | 4 | 5
--... | The code implements a turn-based game where a human and computer alternate moves on a board. It initializes the game, displays instructions, and alternates between human and computer moves. The computer uses a strategy to find the best move. The loop continues until a winner is determined, after which the winner is con... | def main():
display_instruct()
turn = pieces()
board = new_board()
display_board(board)
while not winner(board):
if turn == human:
move = human_move(board)
board[move] = human
else:
move = find_best_move(board)
board[move] = computer
... |
def calc_sma(self):
ma_days = [5, 10, 20, 50, 100, 200, 300]
x = self.data['Close']
self.ma_names = []
for l in ma_days:
ma_vec = []
for n in range(self.num_samples ):
st = np.max([0, n - l + 1])
ma = x[st:n].mean()
... | The main task of the code is to generate a summary DataFrame by calculating technical indicators (SMA, RSI, MACD signal) and average volume from stock data, using the count of closing prices as the sample size. It returns the compiled DataFrame without saving intermediate results. | def csv_creator(self):
self.num_samples = self.data['Close'].count()
self.calc_sma()
self.calc_average_volume()
self.calc_rsi()
self.calc_macd_signal()
df = self.create_summary_df()
# self.calc_log_return("Adj Close")
# self.calc_mfi()
# self.norma... |
def get_obj_data(obj):
obj_data = {}
if obj.parent:
obj_data['parent'] = get_obj_id(obj.parent)
obj_data['id'] = get_obj_id(obj)
obj_data['type'] = obj.type.lower()
obj_data['anim'] = get_anim_data(obj)
return obj_data
def get_obj_id(obj):
global _id
if 'time_id' not in obj:
... | This code exports Blender scene data to JSON, including frame range, background color, objects (with mesh geometry, materials, shape keys), camera settings, and hierarchy. It processes meshes using bmesh, handles subdivision surfaces, extracts animation curves, and sorts objects by parent-child relationships before ser... | def main():
scene = bpy.data.scenes[0]
data = {}
data['start'] = scene.frame_start
data['end'] = scene.frame_end
data['title'] = scene['title']
data['bg'] = {'color': list(scene.world.horizon_color)}
obj_datas = data['objs'] = []
camera_data = get_obj_data(scene.camera)
camera_data... |
def connect_to_broker():
client_m.connect(broker)
call_server("Client connected")
def print_menu():
while True:
print("1. Simulate card use")
print("2. Exit")
choice = input()
if choice == '1':
action1()
if choice == '2':
return 0
def disconnec... | The code defines a function `run_sender()` that connects to a broker, displays a menu, and then disconnects from the broker. Its main task is to execute a sender application workflow involving broker connection, user interface display, and proper disconnection. | def run_sender():
connect_to_broker()
print_menu()
disconnect_from_broker() |
def get_cursor():
return connection.cursor()
def convert_old_table_to_new_models(apps, old_table, new_app, new_model,
fields_to_migrate=None,
old_value_mapping=None,
new_value_mapping=None,
... | This function migrates data from legacy tables to new models using a mapping configuration, creating new records and updating existing ones if specified. It processes each table atomically, filters excluded IDs, bulk-creates new instances, and applies bulk updates for existing models. Postgres indexes are updated after... | def map_fields_from_table(apps, schema_editor, mapping_table, source_cursor=None, overwrite_existing=False):
source_cursor = source_cursor or get_cursor()
new_existing_models = {}
for mapping in mapping_table:
with transaction.atomic(): # Set each table as atomic, so on error only correct tables ar... |
def reload_devices():
global all_devices
all_devices = get_all_devices()
send_devices()
def is_whole_usb_device(device):
return device.get('DEVTYPE') == 'usb_device'
def send_devices():
global connected_devices
global all_devices_full_info
connected_devices = [d["serial_num"] for d in all_d... | The code handles USB device events by reloading connected devices, checking if the device is a complete USB device, printing the event action and device name, then sending updated device data and generating a YAML configuration file. | def handle_usb_event(action, device):
reload_devices()
if is_whole_usb_device(device):
print(f"USB Device {action}: {device['DEVNAME']}")
# handling code for USB device events
send_devices()
gen_yaml() |
def match_comp():
global s1
global sc1
global total_ply
global total_cpu
msg = tkinter.messagebox.showinfo("Match Ended","You Lost , Reshuffle to play again")
listp.clear()
listpc.clear()
plycardinfo.config(image=cardinfo)
cpucardinfo.config(image=cardinfo)
forget_buttons()
s... | This function handles a turn-based card game where the player and computer compare specific card attributes (Strength, Speed, Damage, Respect). It determines the winner of each round based on attribute values, updates card lists, and manages game state transitions. The player's turn involves selecting a power to compar... | def challangi(strpower):
global intp
global intpc
global meturn
global Strength
global Speed
global Damage
global Respect
global s1
global cpuchose
global compare_Strength
global compare_Speed
global compare_Damage
global lista
global listpc
if meturn==Tr... |
def alot(): # listmain=[2,4,6,5,3,7,1,0]
global intp
global intpc
if len(listp) == 0:
match_comp()
elif len(listpc) == 0:
match_comp2()
else:
intp=listp[-1]
intpc=listpc[-1]
def tcard():
totalplycards = len(listp)
totalcpucards = len(listpc)
totalcardply.... | This function compares a player's card attribute (strstat) against the CPU's card. If the player's value is higher, they win, updating UI elements and game state; if lower, the CPU wins. Ties result in both cards being added to lists. It manages message boxes, image updates, and triggers subsequent game actions like ca... | def realcheck(strstat):
global intp
global intpc
global meturn
global Strength
global Speed
global Damage
global s1
global cpuchose
global challangfan
plycardinfo.config(image=dictcards[intp]["img"])
s1.config(image=dictcards[intp]["stackimg"])
if dictcards[intp][strstat... |
def prettyprint(board):
"""Pretty-print the tic-tac-toe board (no return value)"""
print("")
for row in range(3,0,-1):
print("" + str(row) + " |" + board[(row-1)*3:(row)*3].replace(""," "))
print(" +------")
print(" A B C")
def getmovesfromoracle(board):
"""Return the movelist for a ... | This code implements a Tic-Tac-Toe game that allows players to view the strategic value (win/lose/tie) of each possible move via an external oracle. It maintains a game board, processes user inputs for moves or value checks, and dynamically updates the board state while displaying move evaluations until the game conclu... | def playttt():
"""Play the game of Tic-tac-toe and show the values of each move when requested"""
board = " " * 9
print("Welcome to Tic-Tac-Toe, brought to you by GamesCrafters!\n")
print("We've 'solved' the game, so you can see the value (win, lose, tie)")
print("of moves to make. Just type V whene... |
def formulate(self):
length = len(self.parent.data)
indexes = np.arange(length).reshape(length, 1)
self.word_indices = self.range if self.ranged else self.parent.data.get_level_indices(self.level)
self.total = len(self.word_indices)
np.random.shuffle(self.word_indices)
fo... | This code initializes a vocabulary test interface by determining test parameters (ranged words/level), validating user input, setting up GUI components (labels, buttons, options), configuring test type (definitions/words), and preparing test data from MongoDB. It handles error checks, layout adjustments, and initialize... | def __init__(self, parent: Main):
parent.init_window()
self.ranged = messagebox.askyesno("Test Type", "Words should be ranged?")
try:
if self.ranged:
start, end = askstring("Test Specs", "Enter range of words:").split(":")
start, end = int(start), int(... |
def GradientBoostingDecisionTree(action):
print('Evaluating Gradient Boosting Decision Tree..')
# Setting our classifier to Gradient Boosting
clf = GradientBoostingClassifier()
dir = input('Give Data Directory: ')
print('Loading Data..')
... | The code presents a menu-driven interface for machine learning tasks, allowing users to evaluate, compare, or export data from algorithms like Gradient Boosting, Logistic Regression, and KNN. It routes user choices to specific functions for prediction, feature importance, or data export, with options for popularity, vi... | def userInput():
print('Welcome')
print('What do you wish to do?')
print('\t1. Evaluate Machine Learning Algorithms')
print('\t2. Compare Machine Learning Algorithms')
print('\t3. Export Feature Importance')
print('\t4. Export All')
print('\t5. Export Presentation... |
def init_buttons():
global buttons
btn_size = 30
buttons = []
x = draw_width
y = 0
row_size = 4
start_sz = 0
for cl in colors:
if start_sz >= row_size:
start_sz = 0
x = draw_width
y += 10 + btn_size
buttons.append(Button((x, y, btn_size... | This code creates a pixel art editor using Pygame. It toggles between painting modes, selects colors via buttons, and draws on a grid. The main loop handles user input for quitting, escaping, mouse clicks to switch tools/colors, and updates the board's pixel colors based on mouse position. It continuously redraws the b... | def main():
run = True
painting = 1
color = colors["red"]
init_buttons()
while run:
for e in pygame.event.get():
if e.type == pygame.QUIT:
run = False
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_ESCAPE:
run = F... |
def continu(self) -> None:
'''makes the faller continue falling'''
copy = self.copygrid()
if ((self.row == 12) and (self.grid[self.row][self.col -1] is ' ')) or ((self.row < 12) and (self.grid[self.row+1][self.col -1] is not ' ')):
copy[self.row][self.col - 1] = ('[' + str(self.jewel... | This function determines the action to take during a "tick" based on the current state. If the state is 'fall', it calls self.continu(); if 'land', self.land(); if 'match', self.match(); if 'freeze', self.freeze(); otherwise, it does nothing. The function acts as a state-driven controller, executing specific behaviors ... | def tick(self) -> None:
'''function that dictates what action to take once user inputs blank line (tick)'''
if self.state == 'fall':
self.continu()
if self.state == 'land':
self.land()
elif self.state == 'match':
self.match()
elif self.state ==... |
def randomfaller(self) -> list:
'''creates a random faller'''
colors = ['T', 'R', 'P', 'Y', 'G', 'B', 'L']
color1 = random.choice(colors)
color2 = random.choice(colors)
color3 = random.choice(colors)
col = random.randint(1, 6)
faller = [col, color1, color2, color3... | The code runs a game loop using Pygame, managing a falling object (faller) on a grid. It initializes game elements, handles user input, updates the faller's state, checks for game over conditions, and redraws the screen. The loop controls faller movement, spawns new fallers periodically, and displays "GAME OVER" when t... | def run(self) -> None:
'''main user interface'''
T = (127, 255, 212)
R = (255,64,64)
P = (255,20,147)
Y = (255,215,0)
G = (69,139,0)
B = (100,149,237)
L = ((191,62,255))
grid = game.startgrid()
g = game.GameState()
f = self.randomf... |
def add_torrent(ses, filename, options):
atp = lt.add_torrent_params()
info_hash_v1 = None
info_hash_v2 = None
if filename.startswith('magnet:'):
print("add_torrent: parsing magnet link:", filename)
atp = lt.parse_magnet_uri(filename)
# currently, atp.info_hashes works only for... | The main task of the code is to implement a BitTorrent client with content-addressed storage (CAS), managing torrent downloads by organizing files into storage directories based on cryptographic hashes. It parses command-line arguments for configuration, initializes a libtorrent session, and processes torrents to dynam... | def main():
# global state
global store_prefix
global las_store_prefix
global store_dirs_v1
global store_dirs_v2
global store_files_v2
import argparse
parser = argparse.ArgumentParser(
description='bittorrent client with content-addressed storage'
)
parser.add_argum... |
def _restart(self):
self._content.seek(0, 0)
self._pos = 0
def _next_element(self, field=None):
element_type = self._next_type()
if element_type is BDecoder.TYPE_STRING and field is not None:
element = self._type_to_func(element_type)(field=field)
else:
el... | The `decode` method parses and validates a data structure (likely Bencode format) by reading elements from a byte stream. It resets the parser, retrieves the next element, and checks for an expected EOF after decoding. If extra data is found, it raises an `InvalidTorrentDataException`. The method returns the decoded da... | def decode(self):
"""
:rtype: dict|list|int|str|unicode|bytes
:raise: :any:`InvalidTorrentDataException` when parse failed or error
happened when decode string using specified encoding
"""
self._restart()
data = self._next_element()
try:
c =... |
def getData():
'''
Function:
Load json data from a json file.
Arguments:
None
Return:
data: a json object
'''
try:
with open(sys.argv[1], "r") as f:
data = json.load(f)
except Exception:
sys.stderr.write("inappropriate arguments, try again\n")
sys.exit()
return data
def che... | The main task of the code is to generate index files by processing data, extracting zones, creating token-posting lists for each zone, and writing them to TSV files. It handles errors related to storage paths and missing command-line arguments, ensuring data is validated and structured for efficient retrieval. | def createIndex():
'''
Function:
create the index files by calling writeToTSV function
Arguments:
None
Return:
None
'''
data = getData()
checkAll(data)
zones = getAllZones(data)
for zone in zones:
token_df_postings_dict = createTokenDfPostings(zone,data)
try:
writeToTSV(sys.a... |
def getQuery():
'''
Function: This function get the user second input comand line argument, which is a query in '...abc:de AND asdf:fsa' form
Then it check whether the input query are properly formed using above functions basicOperatorCheck and checkLogiExist()
If something error occ... | The main task of the code is to process a complex search query involving logical operators and field-specific terms, parse it into structured components, perform zone-specific searches, and combine results using set operations to return document identifiers matching the query. | def main():
path = sys.argv[1]
userQuery = getQuery() # example: '( book:birthday potter dada) NOT title:helo OR (NOT review:good AND rate:eight)' --->
userQuery = organized(userQuery)
userQuery = userQuery.replace(': ',':')
tsvFileList = getfileNames(path) #contain all zone name, filetype:... |
def train_shared(self, dag=None):
"""Train the language model for 400 steps of minibatches of 64
examples.
Args:
max_step: Used to run extra training steps as a warm-up.
dag: If not None, is used instead of calling sample().
BPTT is truncated at 35 timesteps.
... | This code trains a neural network by alternating between optimizing shared parameters (omega) and the controller's parameters (theta), as outlined in the ENAS paper. It first trains shared parameters for 400 steps (batch size 64), then trains the controller for 2000 steps. If 'single' is False, it alternates both phase... | def train(self, single=False):
"""Cycles through alternately training the shared parameters and the
controller, as described in Section 2.2, Training ENAS and Deriving
Architectures, of the paper.
From the paper (for Penn Treebank):
- In the first phase, shared parameters omega... |
def transform_input(input):
board = input
xs = len([x for x in board if x == "X"])
os = len([o for o in board if o == "O"])
o_plays = xs-1 == os
x_plays = xs == os
if not o_plays and not x_plays:
return "Error: The given board is corrupted."
if o_plays:
modified_board = [-... | The function determines the optimal move for a player on a board using a preloaded AI policy. It transforms the input board, loads the appropriate policy based on the player's symbol, executes the AI's decision-making process, and returns the chosen move after transforming the output back to the original format. | def pick_space_on_board(board, player_symbol):
localized_board = transform_input(board)
states_value = (loadPolicy("policies/policy_p1")
if player_symbol == "X"
else loadPolicy("policies/policy_p2"))
solution = play_ai(localized_board, 1, states_value)
final_solut... |
def quit(msg='', exitcode=1, test=False):
if test:
if exitcode == 0:
print("ICICLE quitting with error code zero.")
print("You shouldn't be seeing this.")
if msg == '':
msg = "Empty message in error"
print("IcicleError:")
print(msg)
raise I... | The function `getVal` parses an input value into an integer, register, memory address, or string. It checks if the input is a non-empty string, converts digits to integers, retrieves register values if present, handles memory addresses enclosed in brackets recursively, and extracts quoted strings. If invalid, it termin... | def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... |
def resetTest():
global INPUT_BUFFER, OUTPUT_BUFFER
reset()
INPUT_BUFFER = []
OUTPUT_BUFFER = ""
def prd(*args):
if DEBUG:
print(*args)
def run(test=False, limit=600):
global regs, program, insns_map
start = time.time()
if test:
insns_map['pr'] = prtest
insns_map[... | The main task of the code is to execute a program parsed from the input string `s`, using optional test input (`inp`) and a runtime limit. It initializes the program by splitting `s` into lines, resets test state if `inp` is provided, and invokes the `run` function to execute the program, returning its result. | def runstr(s, inp=[], limit=600):
global program, INPUT_BUFFER
if inp != []:
resetTest()
INPUT_BUFFER = inp
program = [line.strip() for line in s.split('\n')]
prd(program)
return run(inp != [], limit=limit) |
def quit(msg='', exitcode=1, test=False):
if test:
if exitcode == 0:
print("ICICLE quitting with error code zero.")
print("You shouldn't be seeing this.")
if msg == '':
msg = "Empty message in error"
print("IcicleError:")
print(msg)
raise I... | This function assigns a value to either a register or memory location based on the input 'loc'. If 'loc' is a valid register name, it stores 'val' in the corresponding register. If 'loc' is a memory address enclosed in brackets, it writes 'val' to that memory location using 'setMem'. The function validates 'loc' format... | def assign(loc, val):
global regs
if type(loc) != str or len(loc) == 0:
quit("Bad location "+str(loc)+" recieved!")
if loc in regNames:
regs[loc] = val
return
if loc[0] == '[' and loc[-1] == ']':
setMem(getVal(loc[1:-1]), val) |
def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... | The main task of the code is to subtract two integer values retrieved from the second and third arguments, then assign the result to the variable referenced by the first argument. It validates that both operands are integers, terminating execution with an error message if they are not. | def sub(*args):
a1 = getVal(args[1])
a2 = getVal(args[2])
if type(a1) != int or type(a2) != int:
quit("sub args not int!")
assign(args[0], getVal(args[1])-getVal(args[2])) |
def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... | This code multiplies two numeric values from the second and third arguments, assigns the result to the variable specified by the first argument, and raises an error if either operand is a string. It uses helper functions getVal (to retrieve values) and assign (to store results), ensuring only numeric types are processe... | def mult(*args):
a1 = getVal(args[1])
a2 = getVal(args[2])
if type(a1) == str or type(a2) == str:
quit("Both mult args are strings!")
assign(args[0], getVal(args[1])*getVal(args[2])) |
def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... | The code performs integer division of two values retrieved from arguments and stores the result in a variable, ensuring both operands are integers before execution. | def div(*args):
a1 = getVal(args[1])
a2 = getVal(args[2])
if type(a1) != int or type(a2) != int:
quit("div args not int!")
assign(args[0], getVal(args[1])//getVal(args[2])) |
def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... | This function computes the modulus of the second and third input arguments and assigns the result to the first argument, but only if both operands are integers. It exits with an error if either operand is not an integer. | def mod(*args):
a1 = getVal(args[1])
a2 = getVal(args[2])
if type(a1) != int or type(a2) != int:
quit("mod args not int!")
assign(args[0], getVal(args[1])%getVal(args[2])) |
def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... | The code defines a function `andd` that performs a bitwise AND operation on two integer values. It retrieves the values of the second and third arguments, checks if they are integers, and if valid, assigns the result of their bitwise AND to the first argument. If non-integer values are detected, it terminates with an e... | def andd(*args):
a1 = getVal(args[1])
a2 = getVal(args[2])
if type(a1) != int or type(a2) != int:
quit("and args not int!")
assign(args[0], getVal(args[1])&getVal(args[2])) |
def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... | The function performs a bitwise OR operation on two integers retrieved from the second and third arguments, then assigns the result to the variable referenced by the first argument. It first validates that both operands are integers, exiting with an error if not. | def orr(*args):
a1 = getVal(args[1])
a2 = getVal(args[2])
if type(a1) != int or type(a2) != int:
quit("or args not int!")
assign(args[0], getVal(args[1])|getVal(args[2])) |
def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... | This function performs an XOR operation on two values. If both inputs are integers, it directly computes their XOR. If not, it converts them to byte strings, decodes them, and applies a string XOR operation. The result is then assigned to the first argument, handling both numeric and string data types flexibly. | def xor(*args):
a1 = getVal(args[1])
a2 = getVal(args[2])
if type(a1) == int and type(a2) == int:
assign(args[0], getVal(args[1])^getVal(args[2]))
else:
a1 = long_to_bytes(a1).decode() if type(a1) == int else a1
a2 = long_to_bytes(a2).decode() if type(a2) == int else a2
a... |
def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... | This code converts a string (from args[1]) into a long integer by converting each character to its ASCII value, then combining them into a numerical representation. It first validates that the input is a string, raising an error if not. The result is assigned to the variable referenced by args[0]. | def strint(*args):
a1 = getVal(args[1])
if type(a1) != str:
quit("Attempting to convert non-string to int!")
assign(args[0], bytes_to_long(bytes([ord(i) for i in a1]))) |
def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... | This function converts an integer to a hexadecimal string, handles non-hexadecimal errors by padding with a zero, then converts the hex bytes to a string of characters. It first validates the input is an integer, converts it to bytes via hex, and assigns the resulting string to a variable. Main task: Convert integer to... | def intstr(*args):
a1 = getVal(args[1])
if type(a1) != int:
quit("Attempting to convert non-int to string!")
try:
b = bytes.fromhex(hex(a1)[2:])
except ValueError as e:
if 'non-hexadecimal' not in str(e):
raise e
b = bytes.fromhex('0'+hex(a1)[2:])
assign(a... |
def getVal(val):
if type(val) != str or len(val) == 0:
quit("Bad value "+str(val)+" recieved!")
if val.isdigit():
return int(val)
if val in regNames:
return regs[val]
if val[0] == '[' and val[-1] == ']':
return getMem(getVal(val[1:-1]))
if val[0] == '"' and val[-1] ==... | The code reverses the input value (either an integer or string) and assigns the result to the first argument. If the input is an integer, it uses revint(); otherwise, it reverses the string. | def rev(*args):
a1 = getVal(args[1])
if type(a1) == int:
ret = revint(a1)
else:
ret = a1[::-1]
assign(args[0], ret) |
def read_cp(self):
self.config = {}
try:
if self.CP is not None:
if self.CP.lateralTuning.which() == 'lqr' and self.lqr is not None:
self.config["scale"] = round(self.CP.lateralTuning.lqr.scale, 2)
self.config["ki"] = round(self.CP.lateralTuning.lqr.ki, 3)
self.con... | This method attempts to read configuration data using read_cp(), validate it with checkValid(), and write the validated configuration back using write_config(). If any step raises an exception, it is caught and ignored, ensuring the process does not fail catastrophically. The primary task is to handle configuration rea... | def write_default(self):
try:
self.read_cp()
self.checkValid()
self.write_config(self.config)
except:
pass |
def checkValid(self):
if self.lqr is not None:
return self.checkValidLQR()
elif self.indi is not None:
return self.checkValidINDI()
else:
return self.checkValidCommon()
def write_config(self, conf):
try:
with open(self.file, 'w') as f:
json.dump(conf, f, indent=2, sort_k... | The code reads a JSON configuration file, validates its contents, writes it if valid, and updates the system. If the file doesn't exist, it creates a default config, loads it, validates, writes, and updates. It returns True on success or False if an error occurs during the process. | def read(self):
try:
if os.path.isfile(self.file):
with open(self.file, 'r') as f:
self.config = json.load(f)
if self.checkValid():
self.write_config(self.config)
self.update()
else:
self.write_default()
with open(self.file, 'r') as f:... |
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
def do_auth():
global unauth_button
global auth_button
global selected_row
if selected_row is None:
messagebox.showerror('error','Please select a record first')
return
db = sqlite3.connect("app_data/user_... | The code creates an admin dashboard GUI with authentication controls, a logout button, and a table to display data. It initializes global variables, sets up a Tkinter window with buttons for authentication/unauthentication actions, a logout feature, and a Treeview table to show entries. The dashboard allows user intera... | def dashboard():
global selected_row
global auth_button_image
global unauth_button_image
global image_image_2
global logout_button_image
global auth_button
global unauth_button
dash_window = Toplevel()
dash_window.geometry("1440x900")
dash_window.configure(bg = "#FFFFFF")
sel... |
def addDerivation(word_tree,label,inflecs,derivations):
if label == "VBP_NN_T":
if "JJ" in inflecs:
label = "VBP_JJ_T"
word_tree.update({label:inflecs["JJ"]})
if "NN" in inflecs:
label = "VBP_NN_T"
addNoun(inflecs,label,word_tree)
elif "JJ" in infl... | The code processes an input word to generate a structured "word tree" of its possible derivational forms. It strips suffixes, identifies stems, and explores inflections using spaCy and custom rules. By applying first- and second-order suffix patterns, it transforms the word into related forms (e.g., nouns, adjectives, ... | def create_word_tree(raw):
raw = singularize(raw)
nlp = spacy.load("en_core_web_sm")
derivations = Derivations()
word_tree = {}
# stripping raw(input) from any suffix if possible
first_order_suffixes = {
"NN_JJ_F" : ['ful'],
"NN_JJ_L" : ['less'],
"NN_JJ_OUS" : ['ous'],... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.