dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def load_parameters(self, filename='mit_face_X'):
if os.path.isfile(filename + '_parameters.pickle'):
with open(filename + '_parameters.pickle', 'rb') as f:
self.fp_factor, self.fn_factor, self.fp_rate, self.fn_rate,\
self.weights, self.features, self.stumps, self.pol... | This code detects faces in an image using a pre-trained model, applying multi-scale window scanning with integral images for efficient processing. It identifies face regions, filters them using a threshold, and visualizes detected faces with bounding boxes. The function returns detected face regions after non-maximum s... | def face_detection(self, image_path, threshold=0.5, filename='mit_face_X'):
# if parameter exist, load it
if not self.weights:
self.load_parameters(filename)
# load image
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
width, height, scaling = self.width_traini... |
def is_flag_line(self, text: str) -> bool:
if not self.is_comment_line(text):
return False
try:
self.get_flags_from_flag_line(text)
return True
except AssertionError:
return False
def get_flags_from_flag_line(self, text: str) -> list[str]:
... | The main task of the code is to process input text by handling line flags to either comment/uncomment lines or manage multi-line comments. It iterates through lines, checks for flag lines, applies commenting rules based on flags, and constructs a cleaned output string, ensuring proper comment closure and formatting. | def clean(self, text: str) -> str:
output = ""
lines = text.split('\n')
index = 0
while index < len(lines):
output += f'{lines[index]}\n'
if not self.is_flag_line(lines[index]):
index += 1
continue
flags = self.get_flag... |
def ctrl_dictionary(archivo='model_control_file'):
"""
Funcion copiada de patolli
"""
f=list(filter(None,open(str(archivo)+'.txt','r').read().split('\n')))
sg_ikeys=[f.index(sg) for sg in f if 'NAME' in sg]+[len(f)]
diccio={}
for item in range(len(sg_ikeys)-1):
text = f[sg... | The main task of the code is to preprocess and concatenate multiple datasets, split them into training/validation and test sets, train various CNN models using specified hyperparameters, evaluate model performance with metrics like MSE and MAE, and save results in organized directories. The function handles data filter... | def main_function(control_file = 'txt-file_name',
output_dims = 1, test_val_frac=0.15):
#Joining dataframe
df = pd.read_csv('omdb_hr/dbset_macro.csv') #This is a support file to take interplanar distances
minpeaks = 6
peaks = pd.read_csv('omdb_hr/db_peaks.csv') #File containin... |
def engine_from_str(sql_engine: str) -> Engine:
"""
Helper function to create engine from a string.
Parameters
----------
sql_engine: str
filename of the SQLite database
Returns
-------
sqlalchemy.engine.base.Engine
A SQLAlchemy e... | The code initializes a class to process and merge biological data using an SQL engine. It collects Arrow tables, merges them into a Cytomining-compatible format, and prepares structures for Ray and Parquet data storage, enabling downstream analysis. | def __init__(
self,
engine: str,
compartments: List[str] = None,
join_keys: List[str] = None,
) -> None:
self.engine = self.engine_from_str(sql_engine=engine)
self.arrow_data = self.collect_arrow_tables()
self.tables_merged = self.to_cytomining_merged(
... |
def engine_from_str(sql_engine: str) -> Engine:
"""
Helper function to create engine from a string.
Parameters
----------
sql_engine: str
filename of the SQLite database
Returns
-------
sqlalchemy.engine.base.Engine
A SQLAlchemy e... | This code initializes a class to process and merge biological data. It sets up a SQL engine, collects pandas DataFrames, and merges them using specified compartments and join keys for cytometry analysis. | def __init__(
self,
engine: str,
compartments: List[str] = None,
join_keys: List[str] = None,
) -> None:
self.engine = self.engine_from_str(sql_engine=engine)
self.pandas_data = self.collect_pandas_dataframes()
self.dataframes_merged = self.to_cytomining_merge... |
def append_volume(volume_directory, half, label):
volume, T_mask = read_volume(volume_directory[0], label, half)
for i in range(len(volume_directory) - 1):
new_volume, T_mask = read_volume(volume_directory[i + 1], label, half)
volume = np.append(volume, new_volume, axis=0)
volume = sort_trim... | This function preprocesses training data by concatenating T1 and T2 volumes, extracting patches, encoding labels into categorical format, and reshaping inputs for neural network training. It processes input lists, applies volume appending, patch extraction, label encoding, and combines features for model input. | def preprocess_train_data(T1_list, T2_list, label_list, half):
T1 = append_volume(T1_list, half, label=False)
T2 = append_volume(T2_list, half, label=False)
label = append_volume(label_list, half, label=True)
T1 = extract_patch(T1, image_size)
T2 = extract_patch(T2, image_size)
label = extract_... |
def process_text(self, text_bytes, encoding):
encoding_map = {
0x05: 'latin1',
0x84: 'utf16-be',
0x90: 'sjis',
}
special_sjis_sequences = {
0xFD: {
**dict((0x65 + x, f"big {x}") for x in range(10)),
0x70: 'volume ico... | This function processes an "E2" command by parsing data bytes to extract parameters like row, encoding, and text. It calculates the row from data[1], processes the text with the specified encoding, and transmits the result to an emulator display. If the data length is 5, it sets a remaining bytes counter and returns Tr... | def handle_e2_command(self, data):
if len(data) == 5:
length = data[3] & 0b01111111
self.data_current_command_bytes_remaining = length
return True
else:
flag_bit = (data[2] & (1 << 7)) != 0
encoding = data[4]
what = data[2]
... |
def process_text(self, text_bytes, encoding):
encoding_map = {
0x05: 'latin1',
0x84: 'utf16-be',
0x90: 'sjis',
}
special_sjis_sequences = {
0xFD: {
**dict((0x65 + x, f"big {x}") for x in range(10)),
0x70: 'volume ico... | This code processes a text command by interpreting data bytes to determine display position (row, column), decoding text using specified encoding, and transmitting the result to an emulator. It handles both initial command setup (when data length is 4) and full command execution, logging actions and sending display ins... | def handle_text_command(self, data):
# Doesn't work sometimes - text length is miscalculated.
if len(data) == 4:
length = data[2] & 0b01111111
if not length:
return False
self.data_current_command_bytes_remaining = length
# The command isn'... |
def draw_ellipse(self, ellipse_center, rx, ry, heading):
ellipse = Ellipse((ellipse_center.x, ellipse_center.y),
rx*2, ry*2, angle = heading,
facecolor='None', edgecolor = 'k')
ellipse2 = Ellipse((ellipse_center.x, ellipse_center.y),
... | The main task of the code is to update a plot for visualizing ellipse-based obstacle avoidance. It clears the canvas, sets axis properties, draws an ellipse, aircraft, and reference points, then triggers a redraw to reflect real-time simulation data. | def update_plot(self):
self.ellipse_center = Coordinate(self.ex, self.ey)
self.aircraft = Aircraft(Coordinate(0.1, 0.0),
Coordinate(self.target_x, self.target_y))
self.sc.axes.cla() # Clear the canvas.
# self.sc.axes.axis('equal')... |
def Kib_to_b(kbs_number):
return int(kbs_number * 1024)
def Mib_to_b(mbs_number):
return Kib_to_b(mbs_number * 1024)
def Gib_to_b(gbs_number):
return Mib_to_b(gbs_number * 1024)
def Tib_to_b(tbs_number):
return Gib_to_b(tbs_number * 1024)
def Pib_to_b(pbs_number):
return Tib_to_b(pbs_number * 1024)
def Eib_to_b(eb... | The code converts a given size from a specified unit (Kb, Mb, Gb, Tb, Pb, Eb) to bytes by calling corresponding helper functions like Kib_to_b, Mib_to_b, etc., based on the input unit. | def unit_to_bytes(size,unit):
if(unit == "Kb"):
return Kib_to_b(size)
elif(unit == "Mb"):
return Mib_to_b(size)
elif(unit == "Gb"):
return Gib_to_b(size)
elif(unit == "Tb"):
return Tib_to_b(size)
elif(unit == "Pb"):
return Pib_to_b(size)
elif(unit == "Eb"):
return Eib_to_b(size) |
def copy_matrix(M):
""""""
rows = len(M)
cols = len(M[0])
MC = zeros_matrix(rows, cols)
for i in range(rows):
for j in range(rows):
MC[i][j] = M[i][j]
return MC
def determinant_fast(A):
# Section 1: Establish n parameter and copy A
n = len(A)
AM = copy_matrix(A... | The code computes the inverse of a square matrix using Gaussian elimination. It first checks if the matrix is invertible (non-zero determinant) and square. It then performs row operations to transform the input matrix into the identity matrix, applying the same operations to an identity matrix, which becomes the invers... | def get_inverse_matrix(A):
AM = copy_matrix(A)
# check if matrix is invertable
assert determinant_fast(A) != 0.0
assert len(A) == len(A[0])
n = len(A)
I = get_matrixI(n)
IM = copy_matrix(I)
indices = list(range(n)) # to allow flexible row referencing ***
for fd in range(n): # fd... |
def sortMatrixM(m):
""""""
rows = len(m)
cols = len(m[0])
transient_states = []
absorbing_states = []
for i in range(rows):
if sum(m[i]):
transient_states.append(i)
else:
absorbing_states.append(i)
states = transient_states + absorbing_states
m... | The code calculates absorption probabilities in a Markov chain by decomposing the transition matrix into transient and absorbing states. It constructs matrices Q (transient transitions) and R (transitions to absorbing states), computes $(I - Q)^{-1}R$, and returns the resulting probabilities as fractions. The solution ... | def solution(m):
""""""
t = 0
r = 0
rows = len(m)
cols = len(m[0])
assert rows == cols
assert rows <= 10 and cols <= 10
if (rows == 1 and cols == 1):
return [1, 1]
transitions = []
absorptions = []
matrix_sorted = sortMatrixM(m)
for i in range(rows): # row
... |
def load_mesh(path):
return trimesh.load_mesh(path)
def read_traj(path):
with open(path) as f:
traj_file = f.readlines()
# convert traj to json dict
poses_from_traj = {}
for line in traj_file:
traj_timestamp = line.split(" ")[0]
poses_from_traj[f"{round(float(traj_timestamp),... | The main task of the code is to load an augmented reality (AR) scene's data by reading a 3D mesh, camera trajectory (pose), and intrinsic camera parameters. It takes file paths as inputs, loads the mesh geometry, trajectory data, and camera calibration matrix, then returns these three components for AR scene reconstruc... | def LoadARSceneData(traj_path, mesh_path, intrinsic_path):
mesh = load_mesh(mesh_path)
pose = read_traj(traj_path)
K = read_intrinsic(intrinsic_path)
return pose, mesh, K |
def prepare_dataset(self):
if not self.PCD:
print(":: Sample point clouds from two meshes")
self.source = self.sample_pc(self.source_mesh, self.num_points)
self.target = self.sample_pc(self.target_mesh, self.num_points)
else:
self.source = copy.deepcopy(s... | The code registers point clouds by first preparing the dataset, then performing global registration using RANSAC with downsampled point clouds and FPFH features. It refines the alignment via ICP: standard ICP with voxel size if "standard" is specified, or multiscale ICP otherwise. The method raises an error for unsuppo... | def register(self):
self.prepare_dataset()
self.result_ransac = self.execute_global_registration(self.source_down, self.target_down,
self.source_fpfh, self.target_fpfh,
self.voxel_size)
if s... |
def create_initial_race_version(new_race):
print(f"Debug: In create_initial_race_version, race id: {new_race.id}")
initial_exists = RaceVersion.objects.filter(
race=new_race, version_number=1).exists()
print(f"Debug: Initial version exists: {initial_exists}")
if not initial_exists:
pri... | The function `create_result_versions` updates race positions, initializes a new race version and its result versions, checks the total race count, recalculates versions if more than two races exist, and creates or updates classification entries for the new race. It ensures data consistency by triggering recalculations ... | def create_result_versions(new_race):
# Update Result positions for the new_race
new_race.calculate_positions()
# Create initial RaceVersion and its ResultVersions for the new race
create_initial_race_version(new_race)
total_races = Race.objects.count()
# When we have more than two races, we ... |
def mechanism_clause_active(self) -> np.ndarray:
# Drops clauses randomly based on clause drop probability
return (self.rng.rand(len(self.weight_banks), self.number_of_clauses) >= self.clause_drop_p).astype(jnp.int32)
def mechanism_literal_active(self) -> np.ndarray:
# Literals are dropped based... | The code trains a model by encoding input data, applying clause/literal activation mechanisms, and updating parameters based on target/not-target samples. It shuffles data, iterates through samples, and tracks metrics like "update_p" for evaluation. The function returns aggregated metric statistics (mean/std) post-trai... | def fit(
self,
X: np.ndarray,
Y: np.ndarray,
shuffle: bool = True,
metrics: typing.Optional[list] = None,
*args,
**kwargs
):
metrics = metrics or []
assert len(X) == len(Y), "X and Y must have the same length"
... |
def get_next_root(df, out_col, positive_attr):
l = list(df.columns)
l.remove(out_col)
# Get the root node
root = ""
max_infogain = 0
for attr in l:
t = cal_information_gain(df, attr, out_col, positive_attr)
if(t>max_infogain):
max_infogain =t
root = a... | This function recursively constructs a decision tree subtree by filtering data based on a root attribute value, determining the next root attribute, generating decision rules, and handling unknown values with further recursion. It returns a dictionary representing the subtree structure with the current root and its dec... | def construct_subtree(k, root, df, out_col, positive_attr):
# Create new dataset
dff = df[df[root]==k]
dff = dff.drop(root, axis=1)
temp_root = get_next_root(dff, out_col, positive_attr)
# print("Root: ", root," || Subroot: ",temp_root)
temp_dict = get_decisions(dff, temp_root, out_col... |
def get_data(file, index_col):
df = pd.read_csv(file, index_col=index_col)
return df
def get_next_root(df, out_col, positive_attr):
l = list(df.columns)
l.remove(out_col)
# Get the root node
root = ""
max_infogain = 0
for attr in l:
t = cal_information_gain(df, attr, out_col... | Your return
The code constructs an ID3 decision tree from a dataset. It extracts data, determines the root node based on attributes, builds initial decision branches, and recursively creates subtrees for unresolved nodes ('?'). The tree is stored in a dictionary, with the root added, and then visualized. The main tas... | def construct_ID3_tree(data_file, index_col, out_col, positive_attr, root_spaces):
# Extract data
df = get_data(data_file, index_col)
# Final decision tree dictionary
id3_tree = {}
# Get root node
root = get_next_root(df,out_col,positive_attr)
id3_tree = get_decisions(df,root, out_... |
def __get_file_size(self, file_path):
return os.path.getsize(file_path)
def _upload_file_in_chunks(self, file_path, file_name=None):
upload_id, end_offset = self._start_chunk_upload(file_path, file_name)
self._transfer_chunk(upload_id, end_offset, file_path)
file_id = self._end_chunk_upl... | This function uploads a file to a server, either directly if under 20MB or in chunks if larger. It generates an MD5 hash for file integrity verification, constructs a POST request with metadata, and sends the file data. The method handles both small and large files efficiently while ensuring correct asset type identifi... | def upload_file(self, file_path, file_name=None):
file_size = self.__get_file_size(file_path)
if file_size > (20 * 1024 * 1024):
return self._upload_file_in_chunks(file_path, file_name)
url = self.client.build_url(self.client.base_url, f"file/{self.asset_type}/ad/upload/")
d... |
def open_root(rootfile, mode='read'):
try:
tfile = ROOT.TFile.Open(rootfile, mode)
yield tfile
finally:
tfile.Close()
def build_tree(tracks, vertices):
tracks = [Track(t) for t in tracks]
track_ids = [t.id for t in tracks]
for t in tracks:
parent_id = vertices[t.track... | This code processes a ROOT file to extract tracks and vertices from each event, builds hierarchical tree structures from them, and prints event details along with track/vertex counts and tree representations. It iterates through all events in the 'Events' tree, retrieves simulation data, constructs trees using build_tr... | def print_tracks_and_vertices(rootfile, n):
with open_root(rootfile) as f:
tree = f.Get('Events')
i = 0
for _ in tree:
i += 1
print(f'{rootfile}: event {i}')
tracks = tree.SimTracks_AllSimTracksAndVerticesProducer_AllSimTracks_RECO.product()
v... |
def generate_growth_decay_operators(size,max_growth,max_decay,num_operators):
"""
Generate a random square matrix,
then create a list of scaled copies where the dominant eigenvalue's modulus changes linearly from max growth to max decay
Parameters
----------
size : int
The size of the r... | The function `trajectory_wrapper` generates synthetic time-series data with specified growth/decay dynamics and noise. It then applies multiple DMD variants (e.g., STDMD, WTDMD, DMDEnKF) to predict future states, computes prediction errors relative to true data, and returns these errors. Key steps include data generati... | def trajectory_wrapper(random_state,
max_growth,max_decay,num_data,n_step_ahead,window_size,rho,num_for_spin_up,
hankel_dim,system_cov_const,obs_cov_const,eig_cov_const,ensemble_size):
"""
Generates data, fits each iterative DMD variant, then calculates the relative n step ahe... |
def _get_topo_map(self, check_active=True):
topo_map = {}
dps_objs = self.faucet_config.get(DPS_CFG)
if not dps_objs:
return None
for local_dp in dps_objs:
for local_port, iface_obj in local_dp.interfaces.items():
if 'stack' not in iface_obj:
... | This function restores the dataplane state from Prometheus metrics by extracting active links, identifying the stack root (converting DPID to dp_name), mapping switches with their hop ports, and updating the topology state with the collected data. It processes metrics to build a link graph, determine the root switch, a... | def _restore_dataplane_state_from_metrics(self, metrics):
"""Restores dataplane state from prometheus metrics. relies on STACK_STATE being restored"""
link_graph, stack_root, dps, timestamp = [], "", {}, ""
topo_map = self._get_topo_map(False)
for key, status in topo_map.items():
... |
def _get_access_switch(self, mac):
"""Get access switch and port for a given MAC"""
learned_switches = self.learned_macs.get(mac, {}).get(MAC_LEARNING_SWITCH)
for switch, port_map in learned_switches.items():
port = port_map[MAC_LEARNING_PORT]
port_attr = self._get_port_... | The function determines the active egress path for a given MAC address by identifying the connected access switch and port, retrieving the egress path from the switch, and returning the path details or a state summary if no valid path exists. It constructs a response with the source IP and egress path or reports errors... | def get_active_egress_path(self, src_mac):
"""Given a MAC address return active route to egress."""
src_switch, src_port = self._get_access_switch(src_mac)
if not src_switch or not src_port:
return self._make_summary(
State.broken, f'Device {src_mac} is not connected ... |
def _get_switch_map(self):
"""returns switch map for topology overview"""
switch_map = {}
switch_map_obj = {}
if not self.switch_states:
return {}
change_count = 0
last_change = '#n/a' # Clevery chosen to be sorted less than timestamp.
with self.lock:... | This function aggregates the current dataplane state by collecting switch maps, stack topology, and egress information, tracking change counts and timestamps across components, then returns a structured DataplaneState object with these details. | def _get_dataplane_state(self):
"""get the topology state impl"""
dplane_state = {}
change_count = 0
last_change = '#n/a' # Clevery chosen to be sorted less than timestamp.
switch_map = self._get_switch_map()
dplane_state['switch'] = switch_map
change_count += s... |
def _get_switch_config(self, switch_name):
dps_configs = {str(x): x for x in self.faucet_config[DPS_CFG]}
if switch_name not in dps_configs:
raise Exception(f'Missing switch configuration for {switch_name}')
return dps_configs[switch_name]
def _get_port_state(self, switch: str, port:... | This function retrieves and structures a switch's state information, including attributes, dynamic status, port details, learned MAC addresses, and root path data, into a dictionary. It populates attributes like dp_id, restart events, operational state (active/down), and port states based on provided parameters. | def _get_switch_raw(self, switch_name, port):
"""get switches state"""
switch_map = {}
# filling switch attributes
switch_states = self.switch_states.get(switch_name)
attributes_map = switch_map.setdefault("attributes", {})
switch_config = self._get_switch_config(switch_... |
def _make_summary(self, state, detail):
summary = StateSummary()
summary.state = state
summary.detail = detail
return summary
def get_active_egress_path(self, src_mac):
"""Given a MAC address return active route to egress."""
src_switch, src_port = self._get_access_switch... | The function determines the active path between two hosts in a core network using their MAC addresses. It validates MAC addresses, checks their existence in a learned list, and returns path details including IPs and routing. If `to_egress` is true, it retrieves an egress-specific path. Errors are returned for invalid o... | def get_host_path(self, src_mac, dst_mac, to_egress):
"""Given two MAC addresses in the core network, find the active path between them"""
if not src_mac:
return self._make_summary(
State.broken, 'Empty eth_src. Please use list_hosts to get a list of hosts')
if not d... |
def keyPair(order):
"""
Generate a key pair for RSA encryption.
Parameters:
order (int): Bit length of the key pair.
Returns:
tuple: Tuple containing the private exponent, public exponent, and modulus.
"""
e = 149
p = PrimeOfOrder(order)
q = PrimeOfOrder(order)
n = p * q
... | The code simulates an RSA communication model by generating public and private keys based on a specified bit length. It encrypts the message "I love Hania <3!" using the public key, decrypts it with the private key, and verifies if the decrypted message matches the original. The process involves encoding the message in... | def communication_model(order):
"""
Simulate a communication model using RSA encryption and decryption.
Parameters:
order (int): Bit length of the key pair.
"""
mess = 'I love Hania <3!'
private_key, public_key, n = keyPair(order)
mes_as_int = np.array(list(mess.encode("ascii")))
... |
def keyPair(order):
"""
Generate a key pair for RSA encryption.
Parameters:
order (int): Bit length of the key pair.
Returns:
tuple: Tuple containing the private exponent, public exponent, and modulus.
"""
e = 149
p = PrimeOfOrder(order)
q = PrimeOfOrder(order)
n = p * q
... | The code simulates an RSA encryption attack by attempting to decrypt a message without the private key. It generates a key pair, encrypts a predefined message, uses an "attack" function to derive the private key from the public key and modulus, then decrypts the ciphertext. If the decrypted message matches the original... | def attack_model(order):
"""
Simulate an attack on RSA encryption by attempting to decrypt an encrypted message without the private key.
Parameters:
order (int): Bit length of the key pair.
"""
mess = 'I love Hania <3!'
_, public_key, n = keyPair(order)
mes_as_int = np.array(list(mess... |
def keyPair(order):
"""
Generate a key pair for RSA encryption.
Parameters:
order (int): Bit length of the key pair.
Returns:
tuple: Tuple containing the private exponent, public exponent, and modulus.
"""
e = 149
p = PrimeOfOrder(order)
q = PrimeOfOrder(order)
n = p * q
... | The code simulates an RSA attack without encryption by attempting to derive the private key from the public key and modulus. It generates a key pair, performs an attack to extract the private key, and checks if the extracted key matches the original. If not, it prints "The attack failed!" indicating the attack's inabil... | def attack_model_no_encryption(order):
"""
Simulate an attack on RSA encryption without encryption being performed.
Parameters:
order (int): Bit length of the key pair.
"""
true_private_key, public_key, n = keyPair(order)
private_key = attack(public_key, n)
if true_private_key != priv... |
def reset_selection(self):
if self._selected_data['item'] is not None:
self.graph.itemconfig(self._selected_data['item'], fill='red')
self._selected_data['item'] = None
self._selected_data["x"] = 0
self._selected_data["y"] = 0
def start_interpolation(self):
if not (s... | The code defines a `setup_panel` method that creates a right-side configuration panel with multiple frames for editing modes (Add, Remove, Drag, Select), curve types (Source/Destination), coordinate input fields, resolution sliders, and control buttons (Start/Reset). It initializes UI elements like radio buttons, entry... | def setup_panel(self):
# Right panel for options
self.frame_pannel = Frame(self, relief=RAISED, bg="#e1e1e1")
self.frame_points_type = Frame(self.frame_pannel, bg="#e1e1e1")
self.frame_edit_mode = Frame(self.frame_pannel, bg="#e1e1e1")
self.frame_polygon = Frame(self.frame_pannel... |
def _initialize_weights(y):
m = len(y[y == 0])
n = len(y[y == 1])
ws = np.zeros_like(y, dtype=np.float32)
ws[y == 0] = 1 / (2 * m)
ws[y == 1] = 1 / (2 * n)
return ws
def argsort_features(computed_features: np.ndarray) -> np.ndarray:
# create zero array for storing the... | The main task of the code is to train a stage of a cascade classifier using AdaBoost by iteratively selecting weak classifiers with the lowest error, updating their weights, and combining them until the false alarm rate meets a threshold. It normalizes weights, evaluates feature errors, computes classifier parameters (... | def _train_stage(self):
"""
Train the current stage of the cascade classifier using AdaBoost
"""
# Step 0: Initialize the variables for the current stage
weak_classifiers = []
wc_thresholds = []
wc_polarities = []
wc_classifiers = []
wc_alphas = [... |
def _get_stage(self):
"""
Get the size of the current cascade classifier
"""
return len(self.thresholds_stage)
def initialize_features(self):
"""
Initialize the haar features which will be used for training
"""
self.features = ft.generate_haar_features(sel... | This code trains a cascade classifier with multiple stages using AdaBoost. Each stage updates training data via hard negative mining, trains weak classifiers (decision stumps), checks termination conditions based on acceptance ratio, saves the classifier, and logs timing data. The process iterates through stages, appen... | def train(self):
# get the start stage
start_stage = self._get_stage()
# initialize the features
self.initialize_features()
data_gen_times = []
train_times = []
# loop through the stages
for stage in range(start_stage, self.args.numStages):
... |
def parse(dwalk: str):
splitlist = splitpath(dwalk)
mem_csv = StringIO()
mem_csv.writelines([tup[0] + '\n' for tup in splitlist])
mem_csv.seek(0)
dataframe: DataFrame = read_csv(mem_csv, sep=' ',
skipinitialspace=True, header=None,
... | The main task of the code is to generate a formatted HTML table displaying the top data usage records for a specific user. It parses input data, filters by the user, sorts by descending byte values, converts byte values to human-readable units (e.g., KB, MB), and outputs the result as an HTML table either directly in a... | def topcmd(threads: int, filename: str, user: str) -> None:
datatable: DataFrame = parse(filename)
selected = datatable.get_group(user)
sorted = selected.sort_values('bytes', ascending=False)
sorted['bytes'] = [str(int(num)) + un for num, un in
[unitreduce(x) for x in sorted['byte... |
def reset_vars():
departures.clear()
def geocode_address(row=None, address=None):
address = row['City'] + ' ' + row['Country']
f_tmp = os.path.join('tmp', address.replace(' ', '').replace(',', '') + '.pkl')
if os.path.isfile(f_tmp):
with open(f_tmp, 'rb') as f:
coord = pkl.load(f)
... | This code creates a Streamlit web app that visualizes tour dates from a CSV file on a map, allows users to select departure cities, and searches for Ryanair flight options to concert locations. It includes country-specific parameters, custom styling, and dynamic flight data retrieval based on user inputs, with special ... | def main():
""" Wrapper """
# TODO make this a function that scrapes the gigs from SONGKICK
csv = 'data/Tour-dates.csv'
tour_name = 'DEATH TO FALSE TOURS'
df = pd.read_csv(csv)
reset_vars()
# Center the map on some city around the center of Europe
eu_center = {'Country':'Germany', 'Cit... |
def load_cocodoom_images_paths(path, pic_type='rgb'):
data = []
for dirname in sorted(os.listdir(path)):
if re.search('map', dirname) is not None:
dir_path = '/'.join((path, dirname, pic_type))
for filename in sorted(os.listdir(dir_path)):
image_path = '/'.join((d... | The main task of the code is to process COCO dataset images into multi-channel arrays or visualizations by separating RGB objects/background, combining them with depth data, and saving results as arrays, strips, or videos for analysis. It loads image subsets, applies masks to isolate objects, resizes data, and outputs ... | def main(path, root, ann_file, video_size=2 * 35, amount=20, strip=False, array=True, video=False, shape=None):
dataset = dset.CocoDetection(root=root,
annFile=ann_file,
transform=transforms.ToTensor())
data_path_rgb = load_cocodoom_images_paths... |
def move_pen_down(self, down):
if down:
self.servo_z.set(1000)
else:
self.servo_z.set(0)
if self.debug:
print('up/down')
else:
self.servo_z.move()
sleep(cm.UP_DOWN_DURATION / 1000)
def preset(self, new_pos):
self.new_pos... | The code processes a command to control a pen's movement. It checks if the pen's down state needs updating, adjusts it if necessary, sets the new position using the command's coordinates, and executes the movement. | def cmd(self, cmd: gp):
if self.down != cmd.pen_down:
self.move_pen_down(cmd.pen_down)
self.down = cmd.pen_down
self.preset(np.array([cmd.x, cmd.y]))
self.move() |
def init_value(self,m=25):
'''
Sample m support vectors and initialize
V (m x d) = (V(s_1) ... V(s_m)) where V(s_i) = R_i
Where R_i is given by the environment or sampled
from the system dynamics and then computed using equation (7) from paper
:param m: Number of support ... | The code implements policy iteration for a reinforcement learning algorithm using Gaussian Processes (GP). It initializes a value function with sampled support points, trains a GP model on the environment's state-value pairs, and iteratively updates the value function via policy evaluation (using GP predictions) and im... | def run(self,T=50):
'''
Steps of algorithm 1 from paper
1-2 Modeling System dynamics
3: Init Value function by sampling m support points
4: Policy Iteration
:param T: Number of steps to run per episode
:return:
'''
####################... |
def init_value(self,m=25):
'''
Sample m support vectors and initialize
V (m x d) = (V(s_1) ... V(s_m)) where V(s_i) = R_i
Where R_i is given by the environment or sampled
from the system dynamics and then computed using equation (7) from paper
:param m: Number of support ... | The code implements Algorithm 1 from a paper, focusing on policy iteration with Gaussian Process (GP) approximation. It initializes a value function using sampled support points, models system dynamics, and iteratively updates the value function (via GP fitting) over T steps. For each iteration, it evaluates policies b... | def run(self,T=50):
'''
Steps of algorithm 1 from paper
1-2 Modeling System dynamics
3: Init Value function by sampling m support points
4: Policy Iteration
:param T: Number of steps to run per episode
:return:
'''
####################... |
def set_sleep_after_interrupt(self, enable=True):
"""Sleep After Interrupt. When enabled, the device will automatically
enter low power mode when the INT pin is asserted. Normal operation is
resumed when INT pin is cleared over I2C.\n
"""
self.write_flag_data([enable], APDS_996... | This code resets a device by disabling all active interrupts (proximity, ALS, gesture) and power-up features, ensuring a clean state for reinitialization or shutdown. | def reset(self):
self.set_sleep_after_interrupt(False)
self.enable_all_engines_and_power_up(False)
self.enable_proximity_interrupts(False)
self.enable_proximity_saturation_interrupts(False)
self.enable_als_interrupts(False)
self.enable_als_saturation_interrupts(False)
... |
def next_token():
global INPUT,I
ans = None
read_blanks()
if I!=len(INPUT):
if is_digit(): ans = read_num()
elif is_neg(): ans = read_neg_num()
else: ans = read_par()
return ans
def parse_tree():
tkn = next_token()
if tkn == ')':
return parse_tree()
elif tkn == '(':
sig = next_token()
if type(sig) ... | The main task of the code is to process a sequence of tokens, skipping closing parentheses, parsing trees, and validating each parsed tree against a condition using the `solve` function. It prints "yes" or "no" based on the validation result for each tree, iterating through tokens until they are exhausted. | def main():
global INPUT, I
tkn = next_token()
while tkn != None:
while tkn == ')':
tkn = next_token()
if tkn == None:
break
tree = parse_tree()
print('yes' if solve(tkn,tree) else 'no')
tkn = next_token() |
def call(*args, **kwargs):
global seq
seq += 1
return tcp_request(server, make_request(*args, seq=seq, **kwargs))
def quit_away():
try:
call("quit")
except:
pass
def spawn_subprocess():
global ready
print("prettierd: spawning subprocess")
sublime.status_message("Prettier:... | The main task of the code is to check if a Prettier server is already running by sending a "ping" request. If the server responds with "ok", it marks the server as ready, updates the status, and schedules a view refresh. If the ping fails, it terminates any existing server process and spawns a new subprocess to start a... | def knock_knock():
global ready
try:
data = call("ping")
response = sublime.decode_value(data)
if "ok" in response:
print("prettierd: use existing server")
sublime.status_message("Prettier: ready.")
ready = True
sublime.set_timeout_async(re... |
def init_driver(self):
self.main_driver = load_profile_page(userid=self.userid)
self.axn = ActionChains(self.main_driver)
def extract_profile_infos(self):
self.extract_follower()
self.extract_following()
self.extract_post_count()
self.extract_profile_pic_uri()
def screens... | The code's main task is to demonstrate a quick automation workflow: initializing a web driver, extracting profile information from a webpage, and capturing a screenshot of the main page. This method likely automates browser-based tasks like data scraping or UI testing, combining setup, data extraction, and visual docum... | def quick_demo(self):
self.init_driver()
self.extract_profile_infos()
self.screenshot_main() |
def extract_json_from_html(self):
html_file = open(self.directory, 'r')
html = html_file.read()
html_file.close()
regex_pattern = r'(?<=require\.config\.params\["args"\].=.)[\s\S]*?;'
data_txt = re.findall(regex_pattern, html)[0]
# add quotations for json parser
... | This function processes soccer match data to analyze passing interactions among first eleven players. It filters passes by team, calculates average player positions, counts passes between players, and merges positional data. It returns pass statistics, player locations, team data, match results, and metadata like match... | def get_passes_between_df(self):
data = self.extract_json_from_html()
matchId = data['matchId']
events_dict, players_df, teams_dict, home_players_df, away_players_df = self.extract_data_from_dict()
passes_df = self.get_passes_df()
home_id = data["matchCentreData"]['home']['teamI... |
def download_set_guard(self, download_id: int) -> None:
self.post(
"download-guard",
BASE_URL + "?DownloadGuard",
data=f"DownloadId={download_id}&_scid=&icharset=utf-8",
headers=HEADERS,
)
def download_check_is_ready(self, download_id: int) -> bool:
... | The code initiates a file download by generating a unique ID, preparing the download with parameters, waiting until the file is ready, and then fetching the file via a GET request using the generated ID. It returns the downloaded file content as bytes. | def download(self, download_params: dict[str, str]) -> bytes:
download_id = int(time.time() * 1000)
self.download_set_guard(download_id)
self.download_check_is_ready(download_id)
self.download_start(download_id, download_params)
while True:
if self.download_check_is... |
def movementsAlongLine(self, game_state, pos, line):
valid_movements = []
positions = self.positionsOnLine(pos, line)
positions.remove(pos)
#Regex: Pass through 0 or more empty spaces, followed by 0 or more counters, then one empty space.
regex = re.compile(f"{EMPTY}*[{CNTR_0}{... | The code generates all legal actions for an agent's turn in a board game, including placing rings, moving rings with potential flips, and removing sequences. It checks for valid moves by simulating board changes, identifies sequences, and returns actions like 'place ring', 'place and move', or 'place, move, remove' bas... | def getLegalActions(self, game_state, agent_id):
actions,agent = [],game_state.agents[agent_id]
#A given turn consists of the following:
# 1. Place a counter of an agent's colour inside one of their rings.
# 2. Move that ring along a line to an empty space.
# - An... |
def BuildTree(self, gameState, actions):
rootNode = Node(gameState, None)
dumps = pickle.dumps(gameState)
for action in actions:
tempState = pickle.loads(dumps)
tempState = self.gameRule.generateSuccessor(tempState, action, self.id)
childNode = Node(tempState,... | This code implements a Monte Carlo Tree Search (MCTS) algorithm to select the optimal action in a game. It builds a decision tree, performs iterative simulations within a time limit, and backpropagates results to determine the action with the highest accumulated value. | def SelectAction(self, actions, gameState):
self.startTime = time.time()
self.curr = self.gameRule.calScore(gameState,self.id)
self.oppo = self.gameRule.calScore(gameState, 1-self.id)
count = 0
rootNode = self.BuildTree(gameState, actions)
"MCTS ITERATION"
while... |
def get(self, btn):
if btn == self.b1: return 1
if btn == self.b2: return 2
if btn == self.b3: return 3
if btn == self.b4: return 4
if btn == self.b5: return 5
if btn == self.b6: return 6
if btn == self.b7: return 7
if btn == self.b8: return 8
if b... | This code handles a player's move in a turn-based game by updating the board with the player's symbol, disabling the button, and checking for a win. It then triggers the computer's move by calling a function to determine the computer's next position and updates the UI accordingly. | def change(self, btn):
# Player Move
logic(self.board)
btn.config(state=DISABLED)
btn.config(image=self.circle_pic, height=64, width=64)
number = self.get(btn)
insertLetter(player, number)
self.board = board
self.check_winner()
# Comp Move
... |
def get_recipient_list(request, ticket_id):
pub_result = []
int_result = []
error = []
rcpts = tickets_participants.objects.select_related('user').filter(ticket=ticket_id)
for rcpt in rcpts:
# leave out myself
if rcpt.user != request.user:
if rcpt.user.email:
... | The function sends emails to internal and public recipients when a ticket's fields are updated. It retrieves recipients, checks for changes in form data, and sends notifications with the ticket's details, using different authors (creator/updater) for internal/public emails. Error handling adds messages if emails fail, ... | def mail_ticket(request, ticket_id, form, **kwargs):
int_rcpt, pub_rcpt = list(get_recipient_list(request, ticket_id))
if 'rcpt' in kwargs and kwargs['rcpt']:
int_rcpt.append(kwargs['rcpt'])
tic = get_ticket_model().objects.get(pk=ticket_id)
new, old = field_changes(form)
if len(int_rcpt) ... |
def _call_plugin(self, plugin, fn, args):
host = self._this_host()
return self.get_session().xenapi.host.call_plugin(
host, plugin, fn, args)
def _get_XenAPI(self):
# Delay importing XenAPI as this module may not exist
# for non-XenServer hypervisors.
if self._XenAPI ... | The function `execute` runs a specified command using a plugin, handling input/output and errors. It validates the command, serializes it to JSON, invokes the plugin's `run_command` method, and returns the result's return code, output, and error. If the command is invalid or a XenAPI failure occurs, it logs the error, ... | def execute(self, cmd, stdin=None):
out = ""
err = ""
if cmd is None or len(cmd) == 0:
err = "No command specified."
return oslo_rootwrap_cmd.RC_NOCOMMAND, out, err
try:
result_raw = self._call_plugin(
'netwrap', 'run_command',
... |
def split_tree(df, target_col ):
p_df = df[df[target_col] == 1]
n_df = df[df[target_col] == 0]
return p_df.shape[0], n_df.shape[0]
def best_attr(df,attributes,target_col,impurity_type):
max_info_gain = float("-inf")
best_attr = None
for attr in attributes:
if impurity_type==1:
ig = Info_... | The code implements a decision tree algorithm that recursively splits a dataset based on the best attribute to minimize impurity. It creates nodes, handling base cases by generating leaf nodes when no further splits are possible. The tree is built by partitioning data subsets, removing used attributes, and recursively ... | def dtree(df,attributes,target_col,impurity_type):
global arr
p, n = split_tree(df, target_col)
if p == 0 or n == 0:
leaf = Node(None)
leaf.pos=p
leaf.neg=n
arr.append(leaf)
leaf.leaf = True
if p > n:
leaf.value = 1
else:
le... |
def dtree(df,attributes,target_col,impurity_type):
global arr
p, n = split_tree(df, target_col)
if p == 0 or n == 0:
leaf = Node(None)
leaf.pos=p
leaf.neg=n
arr.append(leaf)
leaf.leaf = True
if p > n:
leaf.value = 1
else:
le... | The code builds a decision tree classifier using training data, applies pruning (post-pruning or depth-based) based on user input, and evaluates accuracy on validation and test datasets. It reads command-line arguments for impurity type, pruning method, and dataset paths, processes data, constructs the tree, prunes it ... | def main():
impurity_type=int(sys.argv[1])
pruning_type=int(sys.argv[2])
train_dataset=sys.argv[3]
valid_dataset=sys.argv[4]
test_dataset=sys.argv[5]
df=pd.read_csv(train_dataset,header=None)
myList=[]
for i in range(len(df.columns)):
myList.append('p'+str(i))
... |
def pose_exponential(x: np.ndarray, u: np.ndarray, dt: float) -> np.ndarray:
u = u * dt
theta = x[2]
rotation = np.array([
[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]
])
phi = u[2]
correction = np.array([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
])
if phi != 0:
corre... | The main task of the code is to compare four numerical integration methods (pose exponential, Runge-Kutta, three-eighths, and Euler) by computing their results for a given state and control input, converting angular outputs to degrees, calculating errors relative to the pose exponential method, and benchmarking their e... | def main() -> None:
x = np.array([0.0, 0.0, np.pi / 3])
u = np.array([40.0, 10.0, 10.0])
dt = 0.05
x_exponential = pose_exponential(x, u, dt)
x_runge = runge_kutta(x, u, dt)
x_three_eighths = three_eighths(x, u, dt)
x_euler = euler(x, u, dt)
x_exponential[2] = np.rad2deg(x_exponential[2])
x_runge[2] = np.rad... |
def get_pkg_metadata(name):
try:
f = url_open("https://micropython.org/pi/%s/json" % name)
except:
f = url_open("https://pypi.org/pypi/%s/json" % name)
s = read_lines(f)
try:
return json.loads(s.decode('UTF8'))
finally:
f.close()
def url_open(url):
global warn_uss... | This function installs a Python package by downloading its latest version from a specified URL, decompressing the retrieved data, extracting the contents using tar, and installing them into the given directory. It retrieves metadata, verifies package availability, handles decompression, and executes the installation pr... | def install_pkg(pkg_spec, install_path):
data = get_pkg_metadata(pkg_spec)
latest_ver = data["info"]["version"]
packages = data["releases"][latest_ver]
assert len(packages) == 1
package_url = packages[0]["url"]
print("Installing %s %s from %s" % (pkg_spec, latest_ver, package_url))
f1 = url... |
def help_msg():
print("""\
micropip - Simple PyPI package manager for MicroPython
Runs on a PC under Python 3.2 or above, and installs to a PC directory for
subsequent transfer to target hardware.
Usage: micropip.py install [-p <path>] <package>... | -r <requirements.txt>
The above requires micropip.py to have exe... | The main task of the code is to parse command-line arguments for an installation tool, supporting 'install' as the only valid command. It processes options like `-p` (install path), `-r` (reading package lists from a file), and `--debug`, collecting package names into `to_install`. After validating inputs, it resolves ... | def main():
global debug
global g_install_path
if len(sys.argv) < 2 or sys.argv[1] == "-h" or sys.argv[1] == "--help":
help_msg()
return
if sys.argv[1] != "install":
fatal("Only 'install' command supported")
to_install = []
i = 2
while i < len(sys.argv) and sys.ar... |
def signin_max_attemp_user():
username = input('Please enter your Username (Mobile number) to confirm: ')
user = find_user_by_username(username)
if user != any:
date_of_birth = input('Please Enter your Date of Birth # DD/MM/YYYY (No Space): ')
print(user[3])
if user[3] == date_of_b... | The main task of the code is to handle user sign-in with a maximum of 3 attempts. It validates credentials using `validate_signin()`, resets attempts on success, and triggers a password reset prompt if attempts are exhausted. If validation fails, it exits. On successful login, it proceeds to the sign-in menu. | def signin():
attemp = 0
is_valid = False
while is_valid == False:
if attemp == 3:
print("You have used the maximum attemps of login.\nPlease reset the password by entering the below details:")
return signin_max_attemp_user()
valid_user = validate_signin()
... |
def prepare_tree_source(self):
to_value = '_____' + ''.join([random.choice(string.ascii_lowercase) for i in range(10)])
self.change_node_none(None, to_value)
self.tree_source = sorted(self.tree_source)
self.change_node_none(to_value, None)
def make_tree_by_node(self):
for parent,... | The code initializes a tree structure from a given source list by preparing the data, building a node-based tree, creating a recursive tree representation, and setting an indentation tab for formatting. | def __init__(self, tree_source: list):
self.tree_source = tree_source
self.prepare_tree_source()
self.tree_by_node = dict()
self.tree_by_node[None] = Node('ROOT', None)
self.make_tree_by_node()
self.tree_recursive = {None: {}}
self.make_tree_recursive()
se... |
def create_nlp(labels, lang, config):
logging.info("Initializing spaCy model...")
nlp = lang.from_config(config)
spancat = nlp.get_pipe("spancat")
for label in labels:
spancat.add_label(label)
return nlp
def load_data(nlp, train_docbin_path, test_docbin_path):
train_corpus = Corpus(train... | (The main task of the code is to implement an active learning loop that iteratively selects informative samples from an unlabeled dataset using a specified strategy, queries labels for them, and re-trains a model to optimize performance within a labeling budget. It initializes a seed dataset, trains a base model, and i... | def main():
"""AL loop pseudocode
Input: Unlabeled dataset Du, Base model Mb, Acquisition Batch Size B,
Strategy S, Labeling budget L
Output: Labeled dataset Dl, Trained model Mt
Query oracle for initial seed dataset Ds from Du (not RANDOM!!)
Let Dl = Ds
Mt = Train(Mb, Dl)
while ... |
def findSleepiestGuard(self):
# print(f'Guards: {guards}')
# for each guard
sleepiest = 0
max = 0
for guard in self.guards:
#print(f'inspecting guard: {guard}, max: {max}')
currentSleep = self.calculateGuardSleep(guard)
if currentSleep > max:
... | The code identifies the guard who slept the most and determines their most frequent sleep minute. It then calculates the product of the guard's ID and their sleepiest minute. Additionally, it finds the minute most frequently slept across all guards, multiplying that minute by its occurrence count. The function returns ... | def solve(self):
g = self.findSleepiestGuard()
print(g)
print(self.findSleepyMinute(g))
return self.findSleepyMinute(g) * g, self.findMostSleptMinute()[0] * self.findMostSleptMinute()[1] |
def play_easy(map, list, list_bot):
# random function
map, list, list_bot = play_random (map, list, list_bot)
return map, list, list_bot
def play_medium(map, list, list_bot, list_player):
# check if bot has 2 in row
bot_with_2, win_line = check_3_row (list_bot, 2)
# ...and finish line if... | The function `play_bot` processes game logic based on the specified difficulty level. It delegates tasks to `play_easy`, `play_medium`, or `play_hard` functions, which modify the game map and input lists accordingly. The updated map and input lists are returned after processing, enabling different gameplay behaviors de... | def play_bot(map, input_list, input_list_bot, input_list_player, difficulty):
if difficulty == "easy":
map, input_list, input_list_bot = play_easy(map, input_list, input_list_bot)
if difficulty == "medium":
map, input_list, input_list_bot = play_medium(map, input_list, input_list_bot, inpu... |
def get_map_centrality(graph: nx.Graph, centrality: str = "degree", **kwargs):
"""
Compute the cliques of a graph
"""
centrality, centrality_kwargs = compute_centrality(graph, centrality)
node_traces = get_plotly_node_traces(graph, get_scatter_geo_kwargs=centrality_kwargs)
fig = get_plotly_map(g... | This function generates a network visualization (map) based on a specified graph analysis measure. It routes input to specialized helper functions for centrality, community detection, k-components, cliques, core-periphery, dominating sets, or PageRank, returning a Plotly figure. If the measure is unrecognized, it raise... | def get_map_for_measure(graph: nx.graph, measure: str, **kwargs) -> go.Figure:
match measure:
# if startswith("centrality"):
# return display_centrality
case "centrality-degree" | "centrality-eigenvector" | "centrality-closeness" | "centrality-katz" | "centrality-betweenness":
... |
def initialize(self):
self._initialize()
def do_each_gen(self):
"""
Operations which algorithms perform at the end of each generation.
"""
self._do_each_gen()
do_each_gen(algorithm=self)
if self.debug:
print(f'{self.nEvals}/{self.problem.maxEvals}')
de... | The main task of the code is to execute an evolutionary algorithm by initializing parameters, iterating through generations while evaluating solutions (up to a maximum number of evaluations), and finalizing the process. It manages population progression, generation steps, and ensures termination when the evaluation lim... | def _solve(self):
self.start_executed_time_algorithm = time.time()
self.initialize()
self.do_each_gen()
while self.nEvals < self.problem.maxEvals:
self.nGens += 1
self.next(self.pop)
self.do_each_gen()
self.finalize() |
def load_combobox_layers(self):
""" Loads the combobox with existing layers """
# Fetch the currently loaded layers
layers_map = QgsProject.instance().mapLayers()
# Clear the contents of the comboBox from previous runs
self.dlg.layer_combobox.clear()
# Populate the combo... | (The main task of the code is to create a QGIS plugin dialog that allows users to select a layer and attribute, fill color data into the attribute, handle errors, and update the layer. It initializes GUI components, connects signals, validates selections, creates new attributes if needed, checks attribute type, process... | def run(self):
"""Run method that performs all the real work"""
# Create the dialog with elements (after translation) and keep reference
# Only create GUI ONCE in callback, so that it will only load when the plugin is started
if self.first_start:
self.first_start = False
... |
def _set_starting_level(self):
print(f"\ncontroller: Setting random starting level")
# Get random integer within range
#starting_level = random.randint(50, 70)
starting_level = random.randint(
self.sessionpars['min_start'].get(),
self.sessionpars['max_start'].get... | The main task of the code is to increment the trial counter, update the trial display, generate a random starting level with offset, create and play a stimulus. It handles errors for missing audio files by showing an error message and aborting playback if the file isn't found. | def _on_start(self):
""" Increases trial counter, and if not at end of task, then
generates a new, random starting level, applies offset,
and calls play function.
"""
# Update trial label
self.trial_var.set(f"Trial {self.counter} of " +
f"{self.sessi... |
def read_config():
config = configparser.ConfigParser()
config.read('config.ini')
return config
def map_variant(line, product_types):
name = line[7]
variant_name = line[0]
country = line[1]
price = Decimal(line[2])
descriprion = line[3]
sizes = line[4].split('/')
colors = line[5]... | The main task of the code is to implement a menu-driven program for managing products and sales orders. It reads product data from a CSV file, allows users to view product lists or create orders, processes user commands, and displays product/order details. The program handles input validation, product type mapping, and... | def main():
variants = []
products = []
product_types = []
sales_orders = []
config = read_config()
products_file = config['Files']['products_file']
print("Welcome to DeliveRoutes!")
print("What would you like to do?")
print("Enter 'view' to view the list of products.")
print("E... |
def get_db_cursor():
conn = sqlite3.connect('mydb.db')
cursor = conn.cursor()
return conn, cursor
def calculate_global_apy():
conn, cursor = get_db_cursor()
# Assuming the total supplied and borrowed amounts are stored per asset in 'supplied_assets' and 'borrowed_assets' tables
cursor.execute("... | The code retrieves and processes financial data for a user's dashboard, including borrowed assets, liquidations, total assets, and APY. It calculates accrued interest, yield, and net asset values, sorts assets by balance, and renders a template with the data if the user is authenticated. | def dashboard(user_id):
conn, cursor = get_db_cursor()
cursor.execute("SELECT * FROM users WHERE _id=?", (user_id,))
user = cursor.fetchone()
# Fetch borrowed assets for user
cursor.execute("SELECT * FROM borrowed_assets WHERE user_id=?", (user_id,))
borrowed_assets_db = cursor.fetchall()
... |
def load_bitmap(self):
self.PIL_image = im = Image.open("cloneskin.bmp")
#Rows of tiles
self.revealed = [IMTK.PhotoImage(im.crop(((16*i), 0, (16*i)+16, 16))) for i in range(9)]
self.tiles = [IMTK.PhotoImage(im.crop(((16*i), 16, (16*i)+16, 32))) for i in range(8)]
self.numbers = ... | This code initializes a Minesweeper game by reading configuration settings, setting up game parameters (board size, mines), creating the game board, binding mouse events for interactions, and preparing the GUI interface with a canvas and menu bar. | def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.title("PySweeper")
self.resizable(0, 0)
#Read the config and create game board with the set defaults
self.config_file = config_file = configparser.ConfigParser()
config_file.read('config.ini')
... |
def __vote(self, splitted_dataset):
# print("Voting:", splitted_dataset.shape)
labels = [sample[-1] for sample in splitted_dataset]
res = max(set(labels), key=labels.count)
# print("Voting:", res)
return res
def __getSplitPoint(self, splitted_dataset):
features = rd.sampl... | This function recursively splits a decision tree node into left and right children based on data subsets. It handles base cases for empty splits, depth limits, and minimum leaf size constraints. When conditions are met, it creates leaf nodes via voting or continues splitting recursively, building a tree structure for c... | def __split(self, node, depth):
left, right = node['splits']
del node['splits']
if not len(left) or not len(right):
node['left'] = node['right'] = self.__vote(
np.append(left, right, axis=0))
return
if self.max_depth is not None and depth >= self.... |
def read_input(filename):
lines = open(filename).readlines()
draws = [int(x) for x in lines[0].split(',')]
boards = create_boards_from_lines(lines[1:])
return draws, boards
def find_non_winners(boards):
return list(filter(lambda b: not is_winner(b), boards))
def mark_boards(boards, draw):
for ... | The code processes a Bingo game input to determine the final losing board. It iteratively draws numbers, marks boards, and eliminates boards that have already won. Once only one board remains, it calculates the score for that board using the last drawn number. The main task is to identify the last board to win and comp... | def day4_part2(input_filename):
draws, boards = read_input(input_filename)
last_draw = None
remaining_boards = boards
while len(remaining_boards) > 1:
last_draw, draws = draws[0], draws[1:]
remaining_boards = find_non_winners(remaining_boards)
mark_boards(boards, last_draw)
... |
def read_input(filename):
lines = open(filename).readlines()
draws = [int(x) for x in lines[0].split(',')]
boards = create_boards_from_lines(lines[1:])
return draws, boards
def has_winner(boards):
return find_winner(boards) is not None
def mark_boards(boards, draw):
for board in boards:
... | The code processes a Bingo game by reading input, simulating number draws, marking boards, identifying the first winning board, and calculating its score using the last drawn number. | def day4_part1(input_file):
draws, boards = read_input(input_file)
last_draw = None
while not has_winner(boards):
last_draw, draws = draws[0], draws[1:]
mark_boards(boards, last_draw)
winner = find_winner(boards)
return calculate_board_score(winner, last_draw) |
def conduct_once(self, t_span = None) -> None:
if t_span is None:
t_span = self.t_span
#def doubling(t,y,*args):
# return (y-y[:,-1])
#doubling_event = lambda t,y: doubling(t, y)
#doubling.terminal = False
#doubling.direction = -1
... | This code repeatedly executes a process for a specified number of cycles, performing an action (`conduct_once`), incrementing the cycle counter, and then either terminating (`kill`) or diluting (`dilute`) based on the `killing` flag status. | def conduct(self, cycles = 15):
for c in range(cycles):
self.conduct_once()
self.cycles +=1
self.kill() if self.killing else self.dilute() |
def get_not_extinct(self):
return [g for g in self.genotypes if not g.extinct]
def conduct_once(self, t_span = None) -> None:
if t_span is None:
t_span = self.t_span
#def doubling(t,y,*args):
# return (y-y[:,-1])
#doubling_event = lambda t,y: dou... | This code simulates the iterative evolution of genotypes over multiple cycles and time steps. It processes each time interval, allowing mutation of genotypes based on their 'stepdy' values, tracks population states, and applies population control (killing/diluting). The simulation stops if all genotypes extinct or afte... | def conduct_steps(self, cycles = 15, steps = 25, mutate = False, stop_after_first_extinct = False):
if steps is None:
t_spans = [self.t_span]
else:
l,step = np.linspace(self.t_span[0], self.t_span[1], steps, retstep=True, dtype='float64')
t_spans = [[0,step]]... |
def find_account(self, acc_id: int, lock: bool, dirty: bool) -> account:
if acc_id in self.most_accessed_accounts:
return self.most_accessed_accounts[acc_id]
if acc_id in self.recently_created_accounts:
return self.recently_created_accounts[acc_id]
if acc_id in self.cache... | This function recommends new account connections by analyzing mutual friends' networks, updating a recommendation history with time-based decay, and returning top candidates based on calculated scores while avoiding blocked accounts and existing connections. | def recommend_new_accounts(self, account_id: int, time: int, recommend_history: dict):
acc = self.find_account(acc_id=account_id, lock=False, dirty=False)
res = {}
new_declines = {}
for friend in acc.connections:
friend_acc = self.find_account(int(friend), lock=False, dirty=F... |
def network_topo_parse_wrapper(network_topo_file):
# parse network topo from given file
f = Path(network_topo_file)
if f.is_file():
if(parse_network_topo(network_topo_file) == 0): # file syntax error
print("ERROR: In file:", "\""+network_topo_file+"\"")
return 0
els... | The function `bullk_parse` sequentially parses multiple network configuration files (topology, routing table, GCL, queue definitions, traffic definitions, and traffic mapping). It validates each parsing step, updating filenames if needed and terminating early with `0` on failure. If all steps succeed, it returns `1`, i... | def bullk_parse(network_topo_file, queue_definition_file, GCL_file, traffic_definition_file):
# network topo
n_topo_return_value = network_topo_parse_wrapper(network_topo_file)
if n_topo_return_value == 0:
return 0
# else if there is a filename change
elif type(n_topo_return_value) is tupl... |
def _check_test_inputs(self, X):
"""
Input validation on a test sample before predict and transform.
The input is checked to be a non-empty 2D array containing only finite
values. If the dtype of the array is object, attempt converting to
float, raising on failure.
Parameters
----------
X : {array-lik... | The code filters inliers from a test set `X` by retaining samples whose T² scores, computed via `score_samples`, are below the upper control limit (UCL) determined by `ucl(X)`. It ensures `X` has the same number of features as the training data, checks input validity, and returns the filtered inlier samples. | def transform(self, X):
"""
Filter inliers.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Test set of samples, where `n_samples` is the number of samples and
`n_features` is the number of features.
Returns
-------
X_filtered : array-like, shape (n_samples_f... |
def handle_chat_response(self):
response = self.provider.execute_response()
if response is None or response.status != 200: return
try:
self.prepare_to_response()
except Exception:
raise
# without key declaration it would failt to append there later in c... | This function handles chat responses by attempting to process them. If the context length exceeds limits, it prompts the user to delete the two farthest message pairs, then retries processing. For invalid user input or unknown errors, it displays appropriate error messages and exits. The core task is managing context l... | def handle_response(self):
try:
self.handle_chat_response()
except ContextLengthExceededException as error:
do_delete = sublime.ok_cancel_dialog(msg=f'Delete the two farthest pairs?\n\n{error.message}', ok_title="Delete")
if do_delete:
Cacher().drop_fi... |
def create_message(self, selected_text: Optional[str], command: Optional[str], placeholder: Optional[str] = None) -> List[Dict[str, str]]:
messages = []
if placeholder: messages.append({"role": "system", "content": f'placeholder: {placeholder}', 'name': 'OpenAI_completion'})
if selected_text: me... | This function manages chat completion by formatting selected text with syntax scope, creating messages, preparing payloads for AI processing, caching interactions in panel mode, and handling errors. It ensures proper input formatting, tracks conversation history, clears selections post-input, and processes AI responses... | def manage_chat_completion(self):
wrapped_selection = None
if self.region:
scope = self.window.active_view().scope_name(self.region.begin())
scope_name = scope.split('.')[-1]
wrapped_selection = f"```{scope_name}\n" + self.text + "\n```"
messages = self.creat... |
def _check_wheel_compatible(path: Path, info: InfoSpec) -> None:
from packaging.utils import (
InvalidWheelFilename,
parse_wheel_filename,
)
from packaging.version import InvalidVersion
from packaging.version import parse as version_parse
target_python = version_parse(info.python)
... | The main task of the code is to generate a `PackageSpec` object from an on-disk wheel file. It validates the wheel's compatibility, extracts metadata (name, version, etc.), canonicalizes the package name, computes a SHA256 hash, and constructs a spec with attributes like file path, install directory, imports, and an in... | def package_spec_from_wheel(path: Path, info: InfoSpec) -> PackageSpec:
"""Build a package spec from an on-disk wheel.
Warning - to reliably handle dependencies, we need:
1) To have access to all the wheels being added at once (to handle extras)
2) To know whether dependencies are available in ... |
def package_spec_from_wheel(path: Path, info: InfoSpec) -> PackageSpec:
"""Build a package spec from an on-disk wheel.
Warning - to reliably handle dependencies, we need:
1) To have access to all the wheels being added at once (to handle extras)
2) To know whether dependencies are available in ... | The main task of the code is to add a list of wheel files to a PyodideLockSpec, creating a new lock specification with updated package information. It processes each wheel file to generate package specs, resolves dependencies, sets relative paths using a base path or URL, and merges the new packages into the existing l... | def add_wheels_to_spec(
lock_spec: PyodideLockSpec,
wheel_files: list[Path],
base_path: Path | None = None,
base_url: str = "",
ignore_missing_dependencies: bool = False,
) -> PyodideLockSpec:
"""Add a list of wheel files to this pyodide-lock.json and return a
new PyodideLockSpec
Parame... |
def _add_or_update_strava(self, strava_credentials: StravaCredentials) -> None:
"""
Add or update the Strava table.
:param strava_credentials:
:return:
"""
athlete_id = strava_credentials["athlete"]
if self._record_exist("athlete_id", athlete_id, self.strava_tabl... | This function adds or updates user data in the 'oauth' (Strava), 'rel_strava_notion', and 'notion' tables using provided OAuth credentials. It delegates tasks to helper methods to update Strava, link Strava-Notion relationships, and update Notion data, ensuring user information is synchronized across systems. | def add_or_update_user(self, credentials: OauthCredentials) -> None:
"""
Add or update a user.
It add or update the tables : oauth (for Strava), rel_strava_notion and notion.
:param credentials:
:return:
"""
self._add_or_update_strava(credentials["strava"])
... |
def moveTurn(self, player):
turn = self.inplay.index(player)
if self.loop == 0:
if player == self.inplay[-1]:
self.turn = self.inplay[0]
else:
self.turn = self.inplay[turn + 1]
else:
if player == self.inplay[0]:
... | The main task of the code is to manage turn progression in a game, handling card plays, updating player states, and checking win conditions. It processes played cards by removing them from the player's hand, updates the current card state, manages turn transitions, and adjusts game variables like `inplay`, `inround`, a... | def updateTurn(self, playCard, player):
self.moveTurn(player)
if self.first:
self.first = False
if playCard:
for card in playCard:
self.findPlayerHand(player).remove(card)
self.currentCard = playCard
if self.keepLoop:
... |
def main_menu():
'''
controls the main menu console interface
'''
menu = '''
1. Candy
2. Cookie
3. Ice cream
4. Sundae
5. Admin Module
Which would you like to add to the order? (1-5, Enter for done):
'''
order = []
while True:
print(menu)
item = input()
if item =... | The main task of the code is to process a customer order by calculating subtotal, tax, and total cost, then printing a detailed receipt. It adds items to an order, sorts them by price, retrieves customer data from a database, handles payment options, and allows placing another order or exiting. The code manages order t... | def main():
'''
adds some items to the order class
'''
customer_order = main_menu()
order = Order()
order.add(customer_order) # adds whatever is ordered into a list
order_count = len(order.items)
# all the math for the prices happens in this chunk
order_subtotal = order.order_cost(o... |
def loadMetroGISParcels():
counties = ['Anoka', 'Carver', 'Dakota', 'Hennepin','Ramsey', 'Scott', 'Washington']
geo_files = [ loadMetroGISCountyParcels(county) for county in counties]
df = pd.concat(geo_files, axis=0)
# Project to lat/lon
df = df.to_crs('EPSG:4326')
df = df[~df['COUNTY_PIN'].is... | The main task of the code is to group related records (parcels, licenses) into portfolios using Union-Find, by matching keys like names, addresses, emails, and phone numbers. It processes and cleans data from multiple sources, creates tags for identifiers, merges datasets, and links records to form clusters. Finally, i... | def createGroups():
USE_SECT_STATE = True
# Load data
tc_parcels = loadMetroGISParcels()
mpls_licenses = loadMplsLicense()
mpls_licenses = clean(mpls_licenses)
mpls_licenses['address'] = mpls_licenses['address'] + ', MINNEAPOLIS'
if USE_SECT_STATE:
sect_state = loadSectState()
... |
def uploadImage(self, image):
try:
#open filedialog
filename = filedialog.askopenfilename(initialdir='../data/',
title='select a file',
filetypes=(
... | This code initializes a GUI application for image reconstruction using Tkinter. It sets up buttons to upload images, perform reconstruction, calculate quality metrics (PSNR, SSIM), and manage models. The interface displays original, reconstructed, and reference images alongside metric results. The app supports model sw... | def __init__(self):
super().__init__()
self.geometry('1000x420')
self.title('Image reconstruction app')
self.resizable = (False, False)
self.image_to_reconstruct = None
self.reconstructed_image = None
self.reference_image = None
self.button_frame = tk.Fram... |
def load_all_tokens(args):
all_set_tokens = []
language = args.language
if os.path.exists(args.token_pkl):
print("LOADING dialogre dataset")
with open(args.token_pkl, "rb") as f:
all_set_tokens = pickle.load(f)
return all_set_tokens
else:
if language == 'cn':
... | The main task of the code is to train and evaluate a sequence classification model for tasks like dialogue relation extraction, using a hybrid architecture combining LSTM and graph-based components. It processes input data, configures hyperparameters (e.g., learning rate, batch size, sequence length), and supports trai... | def main():
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir",
default='.',
type=str,
# required=True,
help="The input data dir. Should contain the .tsv files (or other data files) for the task.")
... |
def create_token_charseqs(self):
self.charseqs = []
for sentence in self.tokens:
sentence_charseq = []
start = 0
for token in sentence:
sentence_charseq.append([start,start+len(token)])
start+=len(token)+1
... | This code initializes an object to process and analyze a collection of sentences and their corresponding tokens. It sets up parameters for filtering (e.g., excluding single triggers or first sentences) and prepares data structures like tokenized text, character sequences, and sentence spans. The `create_token_charseqs(... | def __init__(self,
sentence_dict: dict,
tokenizer: AutoTokenizer,
policy,
exclude_single_trigs,
exclude_first_sents):
self.policy = policy
self.exclude_single_trigs = exclude_single_trigs
self.exclude_first_sent... |
def _get_sequence_step_enables(self):
# based on VL53L0X_GetSequenceStepEnables() from ST API
sequence_config = self._read_u8(_SYSTEM_SEQUENCE_CONFIG)
# pylint: disable=bad-whitespace
tcc = (sequence_config >> 4) & 0x1 > 0
dss = (sequence_config >> 3) & 0x1 > 0
... | This function calculates the required timing budget for a sensor measurement sequence, ensuring it does not exceed the provided budget. It sums predefined timeouts for various steps (TCC, DSS, MSRC, pre-range, final-range) based on enabled flags, checks if the total exceeds the budget, and configures the final range ti... | def measurement_timing_budget(self, budget_us):
# pylint: disable=too-many-locals
assert budget_us >= 20000
used_budget_us = 1320 + 960 # Start (diff from get) + end overhead
tcc, dss, msrc, pre_range, final_range = self._get_sequence_step_enables()
step_timeouts = self._get_seq... |
def get_sockets():
net6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
net6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
net6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
net4 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
net4.setsockopt(socket.SOL_SOCKET, socket.SO_REUS... | The code monitors the network for unsolicited mDNS responses, detecting devices advertising services (e.g., Redfish REST). It sets up IPv4/IPv6 sockets to join multicast groups, listens for packets, and triggers handlers when devices appear/disappear. It tracks peers via MAC addresses, processes responses, and notifies... | def snoop(handler, byehandler=None, protocol=None, uuidlookup=None):
"""Watch for unsolicited mDNS answers
The handler shall be called on any service coming online.
byehandler is called whenever a system advertises that it is departing.
If no byehandler is specified, byebye messages are ignored. The h... |
def parse_input(input_file_name: str) -> list[list[dict[Colour, int]]]:
res: list[list[dict[Colour, int]]] = []
with open(input_file_name, "r") as f:
for line in f:
res.append(parse_line(line[:-1])) # removes \n from line
return res
def part1(games: list[list[dict[Colour, int]]]) -> None... | The main task of the code is to process a list of games parsed from "input.txt", where each game contains color-count dictionaries. It executes two functions: `part1` likely calculates the sum of possible cube counts for valid games, and `part2` determines the minimum cube set required for each game to be valid, return... | def main() -> None:
INPUT_FILE = "input.txt"
games: list[list[dict[Colour, int]]] = parse_input(INPUT_FILE)
part1(games)
part2(games) |
def check(self,i,j):
if i != 0 and self.label[i-1][j] != 0:
self.label[i][j] = self.label[i-1][j]
elif j != 0 and self.label[i][j-1] != 0:
self.label[i][j] = self.label[i][j-1]
else:
self.label[i][j] = self.lb_cnt
self.set.append(-1)
se... | The main task of the code is to process a mask and labels to identify and prune connected components. It first marks regions in the mask, applies union-find to group labels, computes bounding boxes for each label, and prunes labels based on their bounding box dimensions. The result is a dictionary mapping labels to the... | def two_pass(self):
lb_set = []
obj = {} # obj[label] = [max_i,min_i,max_j,min_j]
for i,m1 in enumerate(self.mask):
for j,m2 in enumerate(m1):
if m2 == 255:
self.check(i,j)
for i,l1 in enumerate(self.label):
for j,l2 i... |
def readTestFiles(path):
pattern = '*.txt'
for textFile in os.listdir(path):
if fnmatch.fnmatch(textFile, pattern):
buff=[]
for row in open(os.path.join(path, textFile)):
buff.append(row)
yield np.array(buff, dtype='str'), textFile
def computeSumHV(text, itemMemory, N, D):
block = np.zeros((N, D), dt... | The function evaluates language identification accuracy by comparing predicted labels (via cosine similarity of HV vectors) against actual labels from test texts, using a language code mapping. It calculates and returns accuracy as correct/total predictions. | def testHV(iM, langAM, N, D, langLabels):
langMap = {}
langMap ['af'] = 'afr'
langMap ['bg'] = 'bul'
langMap ['cs'] = 'ces'
langMap ['da'] = 'dan'
langMap ['nl'] = 'nld'
langMap ['de'] = 'deu'
langMap ['en'] = 'eng'
langMap ['et'] = 'est'
langMap ['fi'] = 'fin'
langMap ['fr'] = 'fra'
langMap ['el'] = 'ell'
... |
def computeSumHV(text, itemMemory, N, D):
block = np.zeros((N, D), dtype='int')
sumHV = np.zeros((1, D), dtype='int')
i = 0
for key in getKeys(text):
block = np.roll(block, 1, [0,1])
itemMemory, block[0,:] = lookupItemMemory(itemMemory, key, D)
if i >= N:
nGrams = block[0, :]
for j in range(1, N, ... | The main task of the code is to compute the cosine similarity between a binarized text vector (textHV) and multiple language vectors (langAM) to determine the most similar language label. It returns the language label with the highest cosine angle, indicating the closest match to the input text. | def testHV(iM, langAM, N, D, langLabels, s):
accuracy={}
iMn, textHV = computeSumHV(s, iM, N, D)
textHV = binarizeHV(textHV)
if np.not_equal(iM, iMn):
print('------NEW ITEM IN TEST SENTENCE-----')
else:
maxAngle = -1
for label in langLabels:
angle = cosAngle(langAM[label], textHV[0,:])
accuracy[lab... |
def uniqueSortedValuesPlusAll(listOfValues):
unique = np.unique(listOfValues).tolist()
unique.sort()
unique.insert(0, 'All')
return unique
def widgetsRegister(uuid, control):
"""Register a control for reuse of functions"""
global ctrls
if lenzi(ctrls.loc[ctrls['uuid'].isin([uuid])]):
... | The function `dashboardTS` generates an interactive dashboard with multiple tabs for data analysis and modeling. It creates widgets like dropdowns, sliders, and buttons to control data selection, seasonal decomposition, statistical tests, and model parameters. These widgets are linked to event handlers and organized in... | def dashboardTS(data, option="dashboard", model=None):
"""
Principal function to return a dashboard or an applayout
"""
global commonData
commonData = data
if model is not None:
global userModel
userModel = model
if option == "dashboard":
ddData = widgets.Dropdown(na... |
def getOptionsControl(control):
"""Return the options of DropDownControl"""
return re.search("description=\'([^']+)\'", str(control)).group(0)
def updateRegisterValue(control, value):
"""Update value of control in the register"""
global ctrls
ctrls.at[ctrls.index[(ctrls['control'] == control)].tolis... | The code defines a function `TestListener` that handles changes in the Second tab by retrieving control options from the owner, updating a register value with the new change data, and interacting with the ThirdTab component. Its main task is to manage dynamic updates and coordination between tabs in a UI framework. | def TestListener(change):
"""
control Listener for Second tab
"""
result = getOptionsControl(change.owner)
updateRegisterValue(result, change.new)
ThirdTab() |
def Carga(self):
if(self.dielectrico==1):
Q=self.voltaje * (self.Capacitancia() /self.k)
elif(self.dielectrico==2):
Q= (2*self.Capacitancia()/(self.k+1))*self.voltaje
else:
Q= self.voltaje * self.Capacitancia()
return Q
def Densidad(self, a):
... | This function calculates the bound charge density $ D $ based on the dielectric type (`self.dielectrico`) and parameter $ a $. For dielectric type 1, it uses $ D = \frac{\text{Carga}}{4\pi R_e^2} $ if $ a=1 $, or scales $ D $ by $ (1 - 1/k) $ otherwise. For type 2, it applies $ (1 - 1/k) $ to either $ \text{Densidad}(3... | def DensidadLigada(self, a):
if (self.dielectrico == 1):
if (a==1):
D = self.Carga() / (4 * np.pi * (self.Re**2))
else:
D = self.DensidadLigada(1) * (1 - 1/self.k)
elif(self.dielectrico==2):
if(a==1):
D = self.Densidad(... |
def resetAPIKey(self):
'''
Resets self.APIKey to None, causing no API key to be passed to TSDR
(without a key set, expect urllib.error.HTTPError: "HTTP Error 401: Unauthorized")
'''
self.APIKey = None
return
def resetXSLT(self):
'''
Resets self.XSLT to No... | The main task of the code is to reset all values and control fields in a TDSRReq object. It resets API key, XSLT transform, PTO format (control fields), and XML data (data fields), with the latter's reset cascading to CSV and TSDR map formats. The method ensures a complete state reset for the object. | def reset(self):
'''
Resets all values and control fields in TDSRReq object
'''
# reset control fields (API key, XSLT transform, PTO format)
self.resetAPIKey()
self.resetXSLT()
self.resetPTOFormat()
# reset data fields
self.resetXMLData() # Resetti... |
def _waitFromTime(fromtime, duration):
'''
Wait until the specified duration (in seconds) after fromtime (datetime) has occurred
'''
DEBUG = False
now = datetime.now()
if DEBUG: print(datetime.now(), "ENTERING _waitFromTime")
td = timedelta(seconds=duration)
end_time = fromtime+td
pa... | The main task of the code is to retrieve XML trademark data from the PTO or a local file based on the provided identifier and tmtype parameters. If tmtype is unspecified, it uses the filename directly. The function clears prior data, waits for TSDR rate limits, and sets instance variables like XMLData, CSVData, and ima... | def getXMLData(self, identifier=None, tmtype=None):
'''
Obtain XML trademark data from the PTO or local file
Parameters:
identifier: serial or registration number at PTO; or
filename, if fetched locally
tmtype:
"s" to indicate applic... |
def getXMLData(self, identifier=None, tmtype=None):
'''
Obtain XML trademark data from the PTO or local file
Parameters:
identifier: serial or registration number at PTO; or
filename, if fetched locally
tmtype:
"s" to indicate applic... | The main task of the code is to retrieve XML trademark data from the PTO or a local file, parse it into key/data pairs, and generate a structured TSDR information dictionary. It uses the identifier (serial/registration number or filename) and tmtype ("s" for application, "r" for registration) to determine the data sour... | def getTSDRInfo(self, identifier=None, tmtype=None):
'''
Obtain XML trademark data from the PTO or local file, parse it to key/data pairs
and produce a dictionary of TSDR information.
Parameters:
identifier: serial or registration number at PTO
filena... |
def remove_comments(raw_code: str) -> str:
""" from stackoverflow.com/questions/241327/remove-c-and-c-comments-using-python
"""
def replacer(match):
s = match.group(0)
if s.startswith('/'):
return " " # note: a space and not an empty string
else:
return s
pattern = re.compile(
r'//.*... | The function `get_tapa_init_version` processes a given code file by reading its content, removing comments, modifying syntax (adding spaces, newlines), replacing HLS streams, top functions, task pointers, and header files using an AST. It returns the transformed code, nearly ready for TAPA synthesis, but stream directi... | def get_tapa_init_version(top_path, top_name) -> str:
"""
the result is almost the final tapa code
however, the stream directions have not been determined
"""
ast = get_top_ast(top_path, top_name)
_temp_code = open(top_path, 'r').read()
_temp_code = remove_comments(_temp_code)
_temp_code = add_space_aro... |
def get_top_func(top_path: str, top_name: str) -> str:
"""
extract the top kernel function from the raw file
"""
raw_code = open(top_path, 'r').read()
start_index, end_index = get_func_range(raw_code, top_name)
return raw_code[start_index: end_index+1]
def add_type_defs(temp_code: str, top_path: str) -> str... | The function `get_top_ast` processes a C++ function's source code by retrieving the function, modifying it with type definitions, and removing stream names and template usage. It then writes the cleaned code to a temporary file, parses it into an abstract syntax tree (AST), applies a visitor to revert fake types, and r... | def get_top_ast(top_path: str, top_name: str) -> c_ast.Node:
_temp_code = get_top_func(top_path, top_name)
_temp_code = add_type_defs(_temp_code, top_path)
_temp_code = remove_stream_names(_temp_code)
_temp_code = remove_template_usage(_temp_code)
open('/tmp/tapaconverter_fake_top_func.cpp', 'w').write(_t... |
def HBT(self, m):
t = 0
order = list()
makespans = list()
ops = self.get_operations_for_machine(m)
while ops:
available = list(filter(lambda op: op.r <= t, ops))
while not available:
t += 1
available = list(filter(lambda op:... | This code implements a shifting bottleneck heuristic to schedule operations on machines. It iteratively selects the most constrained machine (max value in M), determines the optimal operation sequence (order_dict) for it, records the sequence and intervals, creates dependencies between consecutive operations as edges i... | def shifting_bottleneck(self):
machines = self.machines
while machines:
order_dict = dict()
M = dict()
for m in machines:
M[m], order_dict[m] = self.HBT(m)
m = get_key_by_value(M, max(M.values()))
machines.remove(m)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.