dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_tensor(val):
t = torch.Tensor([val])
t.requires_grad = True
return t
def add_val(val, name):
"""Add the val and grad of a torch.Tensor."""
torch_res.append([name, val.item(), val.grad.item()])
def test_against_cn(code, show=False):
"""Do the test."""
my_impl_res = get_res(code)
... | This function tests the ELU activation function in PyTorch by constructing a computational graph with tensor operations, computing gradients via backpropagation, and comparing results against a reference implementation (clear net). It creates tensors, applies ELU, performs mathematical operations, retains gradients, an... | def do_test_elu():
"""Test againts clear net elu."""
global torch_res
torch_res = []
elu = torch.nn.ELU(0.1)
a = create_tensor(5)
a.requires_grad = True
b = create_tensor(-6)
b.requires_grad = True
c = elu(b)
d = a * (c - b)
e = d * d
f = elu(e)
c.retain_grad()
... |
def start_counter(i):
_nb_counter[i]=_nb_counter[i]+1
_start_counter[i]=True
_start_time_counter[i]=time.time()
def log_binomial_coefficient(n: int, k: int):
"""
Computes the log of the binomial coefficient (n
k)
(log of the total number of com... | This function calculates the delta (change in criterion value) when merging two adjacent intervals in a doubly linked list. It computes the difference between the original MODL value and a new criterion value derived from binomial coefficients and logarithmic terms, updating the `rightMergeDelta` attribute of the left ... | def criterion_delta_for_one_adjacent_interval_merge(dll,LeftIntervalNode,indexPassed=True,mode='DeltaCalc'):
start_counter(1)
if indexPassed:
LeftIntervalNode = dll.getNth(LeftIntervalNode)
RightIntervalNode = LeftIntervalNode.next
if RightIntervalNode==None:
... |
def start_counter(i):
_nb_counter[i]=_nb_counter[i]+1
_start_counter[i]=True
_start_time_counter[i]=time.time()
def criterion_delta_for_one_adjacent_interval_merge(dll,LeftIntervalNode,indexPassed=True,mode='DeltaCalc'):
start_counter(1)
if indexPassed:
LeftIntervalNode = dll.get... | This function computes the criterion delta for all possible adjacent interval merges in a doubly linked list (dll). It iterates through each element in the dll, invoking a helper function to calculate the delta for merging adjacent intervals at each position. The start_counter and stop_counter calls likely track perfor... | def compute_criterion_delta_for_all_possible_merges(dll):
start_counter(2)
size = dll.size()
for i in range(size):
criterion_delta_for_one_adjacent_interval_merge(dll,i)
stop_counter(2) |
def start_counter(i):
_nb_counter[i]=_nb_counter[i]+1
_start_counter[i]=True
_start_time_counter[i]=time.time()
def stop_counter(i):
_start_counter[i]=False
diff = time.time() - _start_time_counter[i]
_deltatime_counter[i] = _deltatime_counter[i]+diff
_start_time_counter[i]=time.time()
def ... | This code performs a greedy algorithm to iteratively merge intervals by selecting the best merge candidates from 'best_merges', updating the MODL (Minimum Description Length) value of the interval structure, and maintaining potential merges. It merges intervals by combining their nitj values, adjusts model complexity c... | def greedySearch(best_merges,Intervals,N):
start_counter(3)
for step in range(N):
if len(best_merges)>0:
best_merge_tuple = best_merges.pop()
else:
# print("Getting out of the loop, no more merges in the list best merges")
break
if best_merge_tuple[0]>... |
def splitInterval(interval,Intervals, data,i):#i is interval index in IntervalsList
#Doing the split
# if i==0:
# print("BEGIN SPLIT")
if interval==Intervals.head:
IncludingLeftBorder=True
LeftBound=data[0][0]
else:
IncludingLeftBorder=Fals... | The function `PostOptimizationToBeRepeated` iteratively optimizes intervals by performing repeated splitting and merging operations to minimize the MODL criterion value. It sorts data, loops through intervals, and applies splitting/merging strategies while comparing MODL values before and after each operation. The proc... | def PostOptimizationToBeRepeated(Intervals,data,i=0):
data=SortedKeyList(data, key=itemgetter(0))
interval=Intervals.head
OlD_MODL_CRITERION_VALUE=Intervals.MODL_value
CriterionValueAfterOptimization=None
LoopingCount=0
#Merge Split
while True:
LoopingCount+=1
i=0
whi... |
def createElementaryDiscretization(dll,data):
'''
params
data : list of lists, each internal list contains [data value, treatment value, y value]
returns
1- a list of lists. Each internal list represents an interval and contains Effectifs of T0J0, T0J1, T1J0, T1J1 respectively.
2- fron... | The function `ExecuteGreedySearchAndPostOpt` performs greedy search and post-optimization on discretized intervals of data. It converts input columns to integers, sorts data, and applies elementary discretization. It calculates merge costs between adjacent intervals, executes a greedy merge strategy, and refines result... | def ExecuteGreedySearchAndPostOpt(df):
# print("df is ",df)
columnName=df.columns[0]
treatmentCol_name=df.columns[1]
y_name=df.columns[2]
df[treatmentCol_name]=df[treatmentCol_name].astype(int)
df[y_name]=df[y_name].astype(int)
df=df.values.tolist()
df=sorted(df, key=item... |
def Generate(self, state: State, n_player: int) -> Tuple[int, str] :
#choose column randomly
col = random.randint(0, state.board.col-1)
myPlayer = state.players[n_player]
# choose shape
if self.getShapeQuota(myPlayer) > 3:
pick_shape = myPlayer.shape #my sha... | The function performs stochastic hill climbing to determine the optimal move for a player in a game. It generates random neighbor states, evaluates their value, and iteratively updates the current state if a better neighbor is found, within a time limit. The goal is to maximize the player's score by selecting the best ... | def findHillClimbing (self, state: State, thinking_time: int, n_player:int) -> Tuple[str, str]:
# setting variables
time_now= time()
current = copy.deepcopy(state)
# generate one random state
hasil_generate = self.Generate(current, n_player)
col = hasil_generate[0]
... |
def is_terminal_node(self, cur_state: State):
return (is_win(cur_state.board) or (len(self.get_location_valid(cur_state)) == 0) )
def get_location_valid(self, cur_state : State):
valid_local = []
for col in range(cur_state.board.col):
if self.is_location_valid(cur_state, col):
... | The function `alpha_beta_search` performs alpha-beta pruning to determine the optimal move for a player in a game (e.g., Connect Four). It evaluates the game state recursively, considering terminal states, valid moves, and alternating maximizing/minimizing players. It returns the best shape, column, and heuristic value... | def alpha_beta_search(self, cur_state, n_player, depth, alpha, beta, maximizing) -> Tuple[str, int, int]:
# return (shape : str, col : int, val : int)
is_terminal = self.is_terminal_node(cur_state)
valid_locations = self.get_location_valid(cur_state)
if depth == 0 or is_terminal:
... |
def encode_file_name(x, y, file_name):
x, y = check_create_frame(x, y)
paint_pixel(x, y, COL_DELIM)
x, y = check_create_frame(x + BIT_SIZE, y)
x, y = encode_bytes(x, y, str.encode(file_name))
x, y = check_create_frame(x, y)
paint_pixel(x, y, COL_DELIM)
return check_create_frame(x + BIT_SIZE,... | The code encodes a file's binary data into a visual pixel grid by converting each bit into a colored pixel (COL_0 or COL_1). It processes the file in chunks, iterates through each byte's bits, and places them sequentially on a frame. When the frame overflows, it creates a new frame. A delimiter pixel marks the end of t... | def encode_file(file_name, frame_x=0, frame_y=0):
frame_x, frame_y = encode_file_name(frame_x, frame_y, file_name)
with open(file_name, "rb") as f:
for piece in read_in_chunks(f):
for byte in piece:
for i in range(8):
val = (byte >> (7 - i)) & 1
... |
def getRFC(sock, host, port):
rfcNumber = input("Enter an RFC number: ")
rfcTitle = input("Enter the title of the RFC: ")
# Look up RFC with server
msg = "LOOKUP RFC " + rfcNumber + " P2P-CI/1.0\n"
msg = msg + "Host: " + host + "\n"
msg = msg + "Port: " + str(port) + "\n"
msg = msg + "T... | This code implements a P2P-CI client that connects to a server, exchanges RFC information, and handles user commands (GET, ADD, LIST, LOOKUP) for file retrieval and indexing. It maintains a listening thread for peer requests and terminates on EXIT. | def main():
# Create the connection - IPv4, TCP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#hostC = socket.gethostname()
host = socket.gethostname()#input("What is my host name? -> ")
port = 7734
sock.connect((host, port))
port = int(input("Enter a port number: "))
# Send c... |
def pre_processed_data(option, rand, dry=True):
data = get_data(folder=option.folder, data_file=option.data)
print_dry('data loaded', dry)
return pre_processed_file(data, option, rand)
def pre_processed_data_arg(data, option, rand, dry=True):
data = randomize_file(data, option, rand)
if option.contr... | This function processes and returns training and test datasets based on input options. It first prepares training data, applies additional preprocessing, and handles cross-validation or test data splitting. If testing is enabled, it loads and concatenates test data, applying preprocessing. If not, it uses existing data... | def pre_processed_data_all(option, rand, dry=True):
data_train, data_train_test = pre_processed_data(option, rand, dry)
data_train = pre_processed_data_arg(data_train, option, rand, dry)
if option.cross_validate is not None:
return data_train, data_train
if option.test:
data_test = pre_p... |
def cross_validate(fn, data, label, k=10, dry=False,
**kwargs):
measures = []
datas = np.array(np.array_split(data, k))
print(len(datas), [i.shape for i in datas])
labels = np.array(np.array_split(label, k))
for i in range(k):
print('fold %d' % i)
data_train = np.c... | The function `run_function` either performs cross-validation or trains/test a model. If `cross` is provided, it runs cross-validation; else, it trains the model on training data, predicts on test data, computes evaluation metrics, compares class predictions, and returns the average metrics. | def run_function(fn, cross, data_train, label_train, data_test, label_test,
**kwargs):
if cross is not None:
print('cross_validating')
return cross_validate(fn, data_train, label_train, cross, **kwargs)
else:
print('training then testing')
predicted = fn(data_tra... |
def add_sidebar():
st.sidebar.header("Cell measurements given by lab:")
data=get_data()
slider_labels=[
("Radius (mean)", "radius_mean"),
("Texture (mean)", "texture_mean"),
("Perimeter (mean)", "perimeter_mean"),
("Area (mean)", "area_mean"),
("Smoothness (mean)", "smooth... | The main task of the code is to create a Streamlit web application that predicts breast cancer using machine learning. It takes user inputs via a sidebar, displays a radar plot of the data, and generates predictions. The app includes a title, description, and a two-column layout for visualization and results, leveragin... | def main():
st.set_page_config(
page_title=("Breast Cancer Predictor"),
page_icon=("doctor:"),
layout="wide",
initial_sidebar_state="expanded"
)
input_data=add_sidebar()
with st.container():
st.title("Breast Cancer Predictor")
st.write("this app... |
def __update_collisions(self):
self.ray_intersections = [[] for _ in range(6)]
for obstacle in self.simulation.obstacles:
self.__collision_detection(obstacle)
self.zone_obstacle_dist = {}
for zone_name, ray in zip(Environment.zone_names, self.ray_intersections):
... | The code updates an agent's position in a simulation by retrieving pedestrian targets, checking collisions, calculating movement parameters, applying directional movement, and terminating the target if reached. It adjusts speed and turning angle, computes displacement using trigonometry, and updates the agent's positio... | def update(self):
self.targets = self.simulation.get_pedestrians()
self.__update_collisions()
movement_speed, turning_angle = self.__get_update_params()
move = (movement_speed*1.25) / self.simulation.tick_rate * np.array([np.cos(self.angle_rad), np.sin(self.angle_rad)])
self.__u... |
def _test_checkout_update_submit(client, tmp_path):
assert get_state(client) == "CLEAN"
list_global(client, usersession)
assert get_state(client) == "CLEAN"
assert get_diff(client) == []
url = "https://example-bogus-1.org/"
add_url(client, usersession, url, tmp_path)
assert get_state(clie... | This test verifies that after executing the checkout update submit process, the system state transitions to "CLEAN". It uses a client, temporary directory, and mocks requests to simulate the update. The test calls the update function, lists global resources with a user session, and asserts the final state is "CLEAN", e... | def test_checkout_update_submit(
clean_workdir, client, usersession, mock_requests, tmp_path
):
_test_checkout_update_submit(client, tmp_path)
# Before getting the list URLListManager will check if the mock PR is done
# (it is) and set the state to CLEAN
list_global(client, usersession)
assert ... |
def _test_checkout_update_submit(client, tmp_path):
assert get_state(client) == "CLEAN"
list_global(client, usersession)
assert get_state(client) == "CLEAN"
assert get_diff(client) == []
url = "https://example-bogus-1.org/"
add_url(client, usersession, url, tmp_path)
assert get_state(clie... | This test function verifies the submission process of a GitHub PR checkout/update workflow. It executes the core test logic via _test_checkout_update_submit, then confirms the PR remains in the "PR_OPEN" state after operations using list_global and get_state assertions. The test ensures proper handling of PR states dur... | def test_ghpr_checkout_update_submit(clean_workdir, client, usersession, tmp_path):
_test_checkout_update_submit(client, tmp_path)
# This is a *real* PR
list_global(client, usersession)
assert get_state(client) == "PR_OPEN" |
def Initialize(X,E,psi0=1e-5,psi1=1e-5):
'''
Initializes all the variables needed for finding the
solution using Numerov Method
q->phi
f->(V-E)
psi->Our solution to the schrodinger equation
'''
dx=X[1]-X[0]
f0=F(X[0],E)
f1=F(X[1],E)
q0=psi0*(1-dx**2*f0/12)
q1=psi1*(1-dx**... | The function `Run_both` processes input data `X` in both forward and reversed directions. It initializes parameters for each direction, runs equations using `run_eq`, and merges the resulting `psi` values from both runs via the `Merger` function. The merged result, `N_psi`, combines bidirectional computations to enhanc... | def Run_both(X,e=.5,psi_0=1e-10,psi_1=1e-10):
'''
Runs the solutions in both directions and the use merger
to mergs both the functions.
'''
X_b=X[::-1]
psi,f,q=Initialize(X,e,psi_0,psi_1)
psi_b,f_b,q_b=Initialize(X_b,e,psi_0,psi_1)
run_eq(X,e,psi,f,q)
run_eq(X_b,e,psi_b,f_b,q_b)
... |
def spectral_distance(fine_image_t0, coarse_image_t0):
spec_diff = fine_image_t0 - coarse_image_t0
spec_dist = 1/(abs(spec_diff) + 1.0)
print ("Done spectral distance!", spec_dist)
return spec_diff, spec_dist
def temporal_distance(coarse_image_t0, coarse_image_t1):
temp_diff = coarse_image_t1 -... | The code predicts a reflectance image by combining spectral, temporal, and spatial distances. It calculates differences between fine and coarse images, computes combined distances, filters similar pixels, applies weights, adjusts reflectance values, and generates a reshaped prediction. The process integrates multi-moda... | def predict(fine_image_t0, coarse_image_t0, coarse_image_t1, shape):
spec = spectral_distance(fine_image_t0, coarse_image_t0)
spec_diff = spec[0]
spec_dist = spec[1]
temp = temporal_distance(coarse_image_t0, coarse_image_t1)
temp_diff = temp[0]
temp_dist = temp[1]
spat_dist = spatial_distan... |
def get_input(cell_texts: list[tk.Text], grid_dim: int) -> tuple[bool, list[list[str]]]:
""" Retrieves an input from the puzzle grid, and also checks if it is a valid input or not.
Args:
cell_texts (list[tk.Text]): The text boxes in the puzzle grid, contains the user's input.
grid_dim (int): Th... | This function solves a Sudoku puzzle using a SAT solver. It validates input, configures the solver with puzzle constraints, attempts to find a solution, updates the UI with results, disables the solve button, and enables the clear button. If no solution exists, it displays an error. | def solve_sudoku(root: App) -> None:
""" Solves the puzzle.
Args:
root (App): Needed to access cell_option, cell_texts, solve_button, clear_button and grid_dim.
"""
cell_option = root.misc_solve_options.cell_option.get()
cell_texts = root.puzzle_grid.cell_texts
solve_button = root.solv... |
def ncr_to_var(number: int, column: int, row: int, grid_dim: int) -> int:
""" Converts a combination of a number, a column and a row to a unique identifier.
Args:
number (int): The cell's number.
column (int): The cell's column.
row (int): The cell's row.
grid_dim (int): The sid... | The code generates SAT clauses to enforce standard Sudoku constraints: placing numbers in cells, ensuring each row, column, and block contains unique numbers, and handling grid-specific block divisions for 6x6 and other sizes. | def define_standard_clauses(puzzle: list[list[str]], sat_solver: SatSolver, grid_dim: int) -> None:
""" Creates clauses for standard sudoku rules.
Args:
puzzle (list[list[str]]): The sudoku puzzle stored as a 2D array of strings.
sat_solver (SatSolver): The SAT solver.
grid_dim (int): T... |
def ncr_to_var(number: int, column: int, row: int, grid_dim: int) -> int:
""" Converts a combination of a number, a column and a row to a unique identifier.
Args:
number (int): The cell's number.
column (int): The cell's column.
row (int): The cell's row.
grid_dim (int): The sid... | This function generates SAT clauses for a Killer Sudoku puzzle by encoding cage constraints. It processes each cage's cells to find valid number permutations that sum to the cage's total, converts these into CNF clauses, and adds them to the SAT solver. It also integrates standard Sudoku rules to ensure rows, columns, ... | def define_killer_sudoku_clauses(puzzle: list[list[str]], sat_solver: SatSolver, root: App) -> None:
""" Creates clauses for a killer sudoku puzzle.
Args:
puzzle (list[list[str]]): The killer sudoku puzzle stored as a 2D array of strings.
sat_solver (SatSolver): The SAT solver.
root (Ap... |
def ncr_to_var(number: int, column: int, row: int, grid_dim: int) -> int:
""" Converts a combination of a number, a column and a row to a unique identifier.
Args:
number (int): The cell's number.
column (int): The cell's column.
row (int): The cell's row.
grid_dim (int): The sid... | The code generates logical clauses for a Greater Than Sudoku puzzle to be solved by a SAT solver. It encodes constraints based on the puzzle's grid, ensuring each cell's value adheres to greater-than relationships with adjacent cells (horizontal/vertical). It creates CNF clauses for number ranges in each cell, consider... | def define_gt_sudoku_clauses(puzzle: list[list[str]], sat_solver: SatSolver, root: App) -> None:
""" Creates clauses for a greater than sudoku puzzle.
Args:
puzzle (list[list[str]]): The greater than sudoku puzzle as a 2D array of strings.
sat_solver (SatSolver): The SAT solver.
root (A... |
def define_standard_clauses(puzzle: list[list[str]], sat_solver: SatSolver, grid_dim: int) -> None:
""" Creates clauses for standard sudoku rules.
Args:
puzzle (list[list[str]]): The sudoku puzzle stored as a 2D array of strings.
sat_solver (SatSolver): The SAT solver.
grid_dim (int): T... | This function defines logical clauses for a Sudoku puzzle in a SAT solver based on the puzzle type specified in the root object. It routes to specialized clause-definition functions for standard, killer, hyper, or greater-than Sudoku, using the puzzle grid and solver instance to encode constraints appropriate for the p... | def define_clauses(puzzle: list[list[str]], sat_solver: SatSolver, root: App) -> None:
""" Defines the clauses for different sorts of sudoku puzzle.
Args:
puzzle (list[list[str]]): The sudoku puzzle input stored as a 2D array of strings.
sat_solver (SatSolver): The SAT solver.
root (App... |
def _init_callbacks(self):
def fw(key):
return [fn for (_,fn) in find_fns(self, '_widget_on_%s' % key)]
def ft(key):
return [fn for (_,fn) in find_fns(self.rftool, '_widget_on_%s' % key)]
self._widget_callbacks = {
'init': fw('init'), # ca... | This code initializes an object by setting up its components, callbacks, state machine, and drawing system. It assigns attributes from the provided `rftool`, configures event handlers, triggers initialization callbacks, initializes a finite state machine (FSM) with a 'main' start state, prepares drawing functionality, ... | def __init__(self, rftool, **kwargs):
self.rftool = rftool
self.rfcontext = rftool.rfcontext
self.actions = rftool.rfcontext.actions
self.redraw_on_mouse = False
self._init_callbacks()
self._callback_widget('init', **kwargs)
self._fsm.init(self, start='main')
... |
def authenticate_by_auth(auth_info):
info = base64.b64decode(auth_info).decode().split(":")
if len(info) != 2: # format error
return False, None
username = info[0].strip()
password = info[1].strip()
if os.path.exists(auth_path):
auth_lock = ServerThread.file_locks[auth_path]
... | This code handles HTTP requests by receiving data from a client socket, parsing headers to determine the request method (GET/POST/HEAD), authenticating via Basic Auth or cookies, managing session IDs, and routing the request to a URL handler. It also handles connection closure and sends appropriate HTTP responses based... | def run(self):
while True:
try:
request = self.client_socket.recv(2*1024*1024)
self.client_socket.settimeout(0.05)
while True:
try:
data = self.client_socket.recv(2*1024*1024)
request ... |
def cancel_walk_1(self, touch):
"""Cancel Walking Animation"""
self.parent.touched = False
touch.ungrab(self.parent.down_button)
self.parent.down_button.complete()
self.parent.player.anim_delay = 0.1
self.parent.player_head.anim_delay = self.parent.player.anim_delay
self.animate_walk()
self.timer = Cloc... | This code handles touch events to control character movement and direction. It checks if a touch occurs within the widget, disables parent movement if conditions are met, cancels ongoing animations if buttons are moving, and triggers directional changes or delayed walking actions based on position and state conditions. | def on_touch_down(self, touch):
"""On Touch Down"""
if self.collide_point(*touch.pos):
self.parent.touched = False
if self.parent.walk_left or self.moving: return False
elif self.parent.down_button.moving:
self.parent.down_button.anim.on_complete = lambda _: self.cancel_walk_1(touch)
elif self.paren... |
def cancel_walk_1(self, touch):
self.parent.touched = False
touch.ungrab(self.parent.left_button)
self.parent.left_button.complete()
self.parent.player.anim_delay = 0.1
self.parent.player_head.anim_delay = self.parent.player.anim_delay
self.animate_walk()
self.timer = Clock.schedule_once(lambda _: self.ac... | This code handles touch input to control movement and direction. It checks if the touch is within the widget, disables parent movement if active, cancels walking animations if buttons are moving, and triggers looking or delayed walking based on conditions. | def on_touch_down(self, touch):
"""On Touch Down"""
if self.collide_point(*touch.pos):
self.parent.touched = False
if self.parent.walk_down or self.moving: return False
elif self.parent.left_button.moving:
self.parent.left_button.anim.on_complete = lambda _: self.cancel_walk_1(touch)
elif self.paren... |
def extractTokens(resp):
if not resp:
return []
if not resp.raw_response:
return []
if not resp.raw_response.content:
return []
textContent = ""
soup = BeautifulSoup(resp.raw_response.content, 'html.parser')
for bodyTag in soup.find_all('body'):
textContent += " ... | The code scrapes web pages, checks for uniqueness using Simhash, tracks the longest page by token count, counts token occurrences (excluding stop words), and monitors subdomains under ics.uci.edu. It avoids redundant crawling by comparing similarity hashes and only processes valid links, storing data in shared structur... | def scraper(url, resp):
if 200 <= resp.status < 400:
pageTokens = extractTokens(resp)
pageSimHash = Simhash(' '.join(pageTokens))
# 1) For finding unique pages
data.uniqueLinks.add(url)
if len(pageTokens) < 300:
#if there's less than 300 tokens of text or the... |
def init_taxdb(dbfile):
if not dbfile:
ncbi_taxa = NCBITaxa()
else:
dirname = os.path.dirname(dbfile)
cmd = "mkdir -p {}".format(dirname)
p1 = subprocess.Popen(cmd, shell=True, stdin=None)
p1.wait()
cmd = "touch {}".format(dbfile)
p2 = subprocess.Popen(cmd... | The code processes Diamond output files to assign taxonomy ranks to query sequences using specified modes (score, rank_lca, rank_vote). It reads input files, merges taxonomy lineage data, applies thresholds, and outputs ranked taxonomy assignments. Optional formats include compatibility with blobtools. The script handl... | def main():
parser = ArgumentParser()
parser.add_argument("diamondfile", type=str,
help="Diamond output file")
parser.add_argument("outfile", type=str,
help="Output file")
parser.add_argument("-m", "--mode", type=str, default="rank_lca", choices=['rank_lca... |
def store_lengths(files, names):
r = {}
for i, f in enumerate(files, start=0):
r[names[i]] = {}
for record in parse(f, "fasta"):
r[names[i]][record.id] = len(record.seq)
return r
def generate_stat_df(r):
index = ["contigs", "total_size_bp", "min_length", "max_length", "avg_le... | The code processes input FASTA contig files to compute statistical summaries and size distributions. It parses command-line arguments for input files, assembly names, and output files. It validates input consistency, calculates contig lengths, generates statistics (e.g., size, lengths), and outputs results as tab-separ... | def main():
parser = ArgumentParser()
parser.add_argument("-i", "--infile", type=str, nargs="+", help="Fasta file of contigs", required=True)
parser.add_argument("-n", "--names", type=str, nargs="+", help="Assembly names", required=True)
parser.add_argument("--size-dist-file", type=str,
... |
def setParam(self, label, value):
for p in self.params:
if p["label"]==label:
p["value"]=value
return
raise Exception(f"Param {label} not found")
def __calculateTemperature__(self):
if self.status["mapstodat"]==False:
self.writeMapsToDat()
... | The code generates a temporary output file, processes data to create an image from a numpy array, and optionally saves it to a specified filename. It returns the image object after validating the output file path and performing calculations. | def getOutput(self, outputfilename=None):
self.setParam("outputfile",pn.createRandomTemporaryPathableFromFileName('a.dat').getPosition())
self.__calculateTemperature__()
F=self.getParam("outputfile")
if F is None:
raise Exception("Output file not defined")
O = readOut... |
def parse_params():
parser = ArgumentParser(description='Synchronize used private key with OBS')
parser.add_argument('--key', '-k', required=True)
parser.add_argument('--output', '-o', required=True)
parser.add_argument('--local', action='store_true', default=False)
args = parser.parse_args()
re... | The main task is to generate a local key pair or retrieve one from S3 using temporary credentials, then set file permissions. If --local is specified, it creates a new key pair and saves it to the output file. Otherwise, it fetches a key from S3 using provided credentials, downloads it to the output file, and applies r... | def main():
"""Run the script"""
args = parse_params()
key_file = args.output
if args.local:
_generate_new_pair(key_file)
print('Generated local key pair:', key_file)
else:
credential = acquire_temporary_ak_sk()
key_file = get_key_from_s3(key_file, args.key, credenti... |
def question1():
res = []
for j in range(1000):
amount = []
for i in strategy(18 / 38):
if i == 80:
amount.append(i)
res.append(len(amount))
k = 0
for i in res:
if i >= 0:
k += 1
return k
def question2():
res = 0
for j i... | Your return The code `report_q()` generates a report by writing simulation results from three functions (`question1()`, `question2()`, `question6()`) into a text file (`p1_results.txt`). It writes introductory text and outputs for each question, detailing: (1) episodes needed for $80 winnings using an initial strategy,... | def report_q():
# Sample output results
# Specify the file path
file_path = "p1_results.txt"
# Open the file in write mode
with open(file_path, 'w') as file:
# Write the output results to the file
q1_intro = """Question 1:
The simulation is executed across 1000 episodes
of ... |
def reverse_check(instructions):
dic = {}
for i in range(len(instructions)):
e = eval(instructions[-i][0])
if e in pla and not_in_others(e, instructions):
dic[e] = 1
if len(dic) != 0:
return tuple(list(dic.keys()))
def reverse_calculate(instructions, index = -1):
if e... | This function recursively generates and evaluates all possible mathematical expressions using numbers from the 'math' list and operators in 'ops'. It tracks the best score by combining numbers with operators, updating global variables like best_score, best_pc, and best_ri. The recursion explores expression combinations... | def recurse(st, math, x, i1, i2):
global t1
global sum_set
global best_score
global best_pc
global best_ri
global real_instructions
global m
ma = list(math)
if x:
e = eval(x)
ma.append(e)
ma.pop(i1)
if (i1 < i2):
ma.pop(i2-1)
e... |
def _handle_critical_event(self, data):
"""
Handle critical event
"""
event = CriticalEventEnum(data.event_type)
if event == CriticalEventEnum.APPEAR:
self._handle_appear(data.angle_new_1)
if event == CriticalEventEnum.DISAPPEAR:
self._ha... | The function processes critical and move events from the input data, applying thread safety via a lock. It iterates through events to handle critical updates, processes gap moves, and triggers a gap tree publication if events exist, ensuring synchronized state management. | def _handle_collection(self,data):
"""
Handles update on topic collection_critical_and_moved
data (CollectionCriticalAndMoved):
"""
self.lock.acquire()
for event in data.events.events:
self._handle_critical_event(event)
for move in data.gap_moves.gap... |
def toggle_music(self):
self.music_enabled = not self.music_enabled
if self.music_enabled:
pygame.mixer.init()
pygame.mixer.music.load('music.mp3')
pygame.mixer.music.set_endevent(pygame.constants.USEREVENT) # Comment!
pygame.mixer.music.play(loops=-1) # p... | This code initializes a GUI-based video recorder application with exercise tracking, featuring counters for pushups, squats, and situps, a money system, music toggle, and a shop. It sets up a dark-themed interface using Tkinter, integrates OpenCV for video capture, and includes buttons to start/stop recording, switch e... | def __init__(self, root):
self.root = root
self.root.title("Video Recorder App")
self.root.geometry("800x800")
self.root.configure(bg="#191414") # Set background color to Spotify's dark theme
self.total_pushups = 0
self.total_squats = 0
self.total_situps = 0
... |
def generate_img2img_lora(self,prompts,init_images,negative_prompts, image_names, prev_class_id, class_names=None):
if self.args.dataset in ['imagenette','imagenet100','imagenet1k']:
class_ids = [image_name.split("/")[0] for image_name in image_names]
groups = group_lists(class_ids, prompts,... | The main task of the code is to generate images based on the specified method (e.g., SDI2I_LoRA, SDT2I_LoRA, SDI2I, SDT2I, or SDXLRefine) by routing input parameters like prompts, initial images, and negative prompts to corresponding helper functions. It returns the generated images and an updated class ID, adapting th... | def generate(self, prompts,init_images,negative_prompts, image_names, prev_class_id,class_names=None):
# Generate
if self.method in ['SDI2I_LoRA']:
images, prev_class_id = self.generate_img2img_lora(prompts,init_images,negative_prompts, image_names, prev_class_id,class_names)
elif se... |
def get_pipe(self,pid):
if self.method in ['SDI2I_LoRA']:
pipe = self.get_img2img(pid)
elif self.method in ['SDT2I_LoRA']: # SDI2I_LoRA'
pipe = self.get_stablediffusion(pid)
elif self.method in ['SDI2I']:
pipe = self.get_img2img()
elif self.method in [... | This code generates synthetic images for the ImageNet1k dataset using a specified method (e.g., SDI2I_LoRA). It loads training data, processes batches with prompts/negative prompts, generates images via a pipeline, saves outputs to a directory, and copies the original file list for labels. The process uses subset sampl... | def generate_ImageNet1k(self):
print(f"Generation: {self.method}")
print("Full",self.if_full)
prev_class_id = 'all' if self.if_full else None
self.pipe = self.get_pipe(prev_class_id) # all, sdi2i_lora
img_size, bsz, out_version, use_caption, caption_path, ImageNetPath... |
def print_path_worker_notifes(self, curr_env_time, not_worker_id):
#prints initial trajectories for worker who sends notifictaion
#renoves their ompleted tasks
plan_output=''
plan_output+='{0} ({1},{2})->'.format(not_worker_id,0,0)
for loc_id,loc_time_interval in self.i... | The function processes a notification from a worker about an unassignable task, updates locations/statuses of capable workers, removes the task from the notifier's list, and returns reassigned workers and the current time. It identifies workers who can perform the task, updates their trajectories, and compiles a list o... | def handleNotifications(self,curr_travel_time, curr_env_time, not_worker_id,task_comp_id,task_not_comp_id, notification_x,notification_y, previous_comp_task_max_time):
#simulate abnormal assignments
print('Worker {0} issued a notification about {1} at ({2},{3}) and at time t = {4} '.format(n... |
def createTasks(self,jobs):
tasks={}
for jobs_id,jobs_info in jobs.items():
for task_id,task_info in jobs_info.items():
tasks.setdefault(task_id,[])
tasks[task_id]=task_info
#passed
#test
#print(self.tasks)
ret... | The code initializes a system to manage worker-task assignments by creating tasks from jobs, generating worker-specific task lists, preparing a depot model for VRP (Vehicle Routing Problem), assigning travel paths, and tracking incomplete tasks. It sets up a framework for optimizing task allocation and routing efficien... | def __init__(self,workers,jobs,skills):
self.workers=workers
self.jobs=jobs
self.skills=skills
self.tasks=self.createTasks(jobs)
self.tasks_by_workers=self.__createTaskList__(workers,self.tasks)
#creates distance matrix for each worker which can be passed onto vrp
... |
def get_env_time(self,not_worker_id,task_comp_id,task_not_comp_id, notification_x,notification_y, previous_compl_task_max_time):
#id of completed task from initial trajectory
task_comp_id_x=self.worker_task_locations[not_worker_id][task_comp_id][0]
#id of uncompleted task from ... | The main task of the code is to simulate task re-assignment in response to an abnormal situation, such as an uncompleted task notification. It calculates travel times, identifies eligible workers, updates worker trajectories, and prints logs of re-assignment details, including affected workers' new paths and the time t... | def simulate_abnormal_situation(self):
#re-assignemnt task starts
start_assignment_vrp = datetime.datetime.now()
#worker who notifies
not_worker_id=self.notification_id
#get task previous task which worker has completed before notification
initi... |
def createTasks(self,jobs):
tasks={}
for jobs_id,jobs_info in jobs.items():
for task_id,task_info in jobs_info.items():
tasks.setdefault(task_id,[])
tasks[task_id]=task_info
#passed
#test
#print(tasks)
return t... | This code initializes a task assignment system by setting up workers, jobs, and skills. It creates tasks, assigns them to workers, generates normal trajectories, prepares distance matrices for routing, matches tasks to locations, simulates disruptions, and tracks incomplete tasks. The main task is to model and manage t... | def __init__(self,workers,jobs,skills):
self.workers=workers
self.jobs=jobs
self.skills=skills
self.tasks=self.createTasks(jobs)
self.tasks_by_workers=self.__createTaskList__(workers,self.tasks)
#get trajectories without abnormality
self.__createNormalTrajectories... |
def atom3d(PDBcode, rename = True):
"""
Return a dataframe from a PDB code.
Parameters:
-----------
code: str
The code for a PDB file.
Returns:
--------
df: pd.DataFrame()
A dataframe containing the model, chain, residue number, residue name
and coordina... | The function processes a PDB file to center and color protein data, calculates a translation vector between two specified residue interfaces, and generates translated data ensuring no overlap. It returns original data, translated data, and the minimal translation vector to align interfaces without intersection, using c... | def get_parameters(pdbFile: str, interface1: list, interface2: list, penetration: float, group: str = 'p1'):
"""
Return the data (d), the translated data (t) and the translation vector u such
that the intersection of (d) and (t) is null and u is minimal.
Parameters:
-----------
pdbFile: PDB fil... |
def normalize(vector):
v_norm = np.linalg.norm(vector)
if v_norm != 0:
return vector / np.linalg.norm(vector)
else:
return vector
def centroid(polyhedra):
x = [vertex[0] for vertex in polyhedra]
y = [vertex[1] for vertex in polyhedra]
z = [vertex[2] for vertex in polyhedra]
r... | This function implements the GJK (Gilbert–Johnson–Keerthi) algorithm to determine if two convex polyhedra intersect and compute their minimum distance. It iteratively constructs a simplex using support points in the direction between centroids, checks for collision via the origin's inclusion in the Minkowski difference... | def gjk(polyhedra1, polyhedra2):
d = normalize(centroid(polyhedra2) - centroid(polyhedra1))
simplex = [get_support_point(polyhedra1, polyhedra2, d)]
d *= -1
dist = -1
while True:
A = get_support_point(polyhedra1, polyhedra2, d)
simplex += [A]
if np.dot(A,d) < 0:
... |
def normalize(vector):
v_norm = np.linalg.norm(vector)
if v_norm != 0:
return vector / np.linalg.norm(vector)
else:
return vector
def centroid(polyhedra):
x = [vertex[0] for vertex in polyhedra]
y = [vertex[1] for vertex in polyhedra]
z = [vertex[2] for vertex in polyhedra]
r... | The code computes the minimum distance between two convex polyhedra using the GJK (Gilbert–Johnson–Keerthi) algorithm. It iteratively constructs a simplex from support points in the direction of the normalized vector between centroids, checks for termination conditions, and visualizes intermediate results. The algorith... | def test(polyhedra1, polyhedra2):
d = normalize(centroid(polyhedra2) - centroid(polyhedra1))
simplex = [get_support_point(polyhedra1, polyhedra2, d)]
V = [list(get_support_point(polyhedra1, polyhedra2, d))]
d *= -1
dist = [np.linalg.norm(V[0])]
while True:
A = get_support_point... |
def yes_or_no(prompt:str) -> bool:
'''
Prompt the user to enter either yes or no.
Parameters:
prompt : str
The prompt to display to the user.
Returns:
True if the user selects "yes".
False if the user selects "no".
'''
YES = 'Y'
NO = 'N'
print(prom... | This function saves a user's score with a timestamp to a file, handles potential file corruption, and allows the user to choose whether to save the score or view their past scores. It loads existing scores, updates them with the new score, and provides options for saving and displaying the scores. | def save_and_view_scores(name : str, score_file_path:str, score:int):
'''
Allow the user to save their score and view their past scores.
Parameters:
name : str
The user's name.
score_file_path : str
The path to the score file.
score : int
The user... |
def _simple_stratified_split(
features, outcomes, test_size, random_state
):
df = pd.concat([features, outcomes], axis=1)
train_set, val_set = train_test_split(
df,
test_size=test_size,
random_state=random_state,
stratify=outcomes.event.values,
)
return _get_surviva... | This function performs stratified data splitting based on the specified 'type' parameter, maintaining outcome distribution in splits. It routes to '_simple_stratified_split', '_stratified_shuffle_split', or '_stratified_continuous_split' depending on the type, ensuring consistent class proportions in test/train sets fo... | def _stratified_split(
features,
outcomes,
test_size,
random_state,
type="simple",
):
args = (features, outcomes, test_size, random_state)
match type:
case "simple":
return _simple_stratified_split(*args)
case "shuffle":
return _stratified_shuffle_spli... |
def init_conf_mat(self):
"""
Initialize confusion matrix
"""
self.conf_mat = {}
self.conf_mat['trajectory_based'] = {} # single key
self.confidence = [] # hack for writing the data to txt file
for class_gt in preferences.CLASSES:
sel... | The main task of the code is to perform cross-validation by shuffling data files, training and testing a model across multiple epochs, accumulating confusion matrices, and saving results with timestamps. It initializes metrics, iterates through epochs to shuffle data, estimate model performance, scales confusion matric... | def cross_validate(self):
year, month, day, hour, minute = time.strftime("%Y,%m,%d,%H,%M").split(',')
out_fname = 'results/'+ year +'_'+ month +'_'+ day +'_'+ hour +'_'+ minute + \
'_emd' + \
'_hier_' + (preferences.HIERARCHICAL) + '.txt'
self.init_con... |
def training(csv_file):
data, targets, features = import_data(filename=csv_file)
tree = make_tree(data, targets, features)
return tree
def validator(filename, tree):
with open(filename, 'r') as f:
reader = csv.reader(f)
raw_data = list(reader)
features = ['class', 'cap-shape', 'cap-... | The main task of the code is to train a decision tree classifier using the "MushroomTrain.csv" dataset, validate its accuracy on the "MushroomTest.csv" dataset, print the decision tree structure, and display the percentage of correct classifications. The code executes these steps sequentially: loading data, building th... | def main():
train_file = "MushroomTrain.csv"
test_file = "MushroomTest.csv"
decision_tree = training(train_file)
perc_correct = validator(test_file, decision_tree)
print("============================")
print_tree(decision_tree, 'root')
print("============================")
print("class ... |
def read_file(filename: str) -> str:
"""
Opens and reads filename and returns the containing
"""
file_path = join(SCRIPT_PATH, FOLDER, filename+EXT)
file_container = None
with open(file_path, "r") as file:
file_container = file.read()
if not file_container:
raise SyntaxEr... | The main task of the code is to parse a file into structured execution tasks. It reads the file, divides its content into individual task executions, parses these tasks into a structured format, and returns them as a list of lists of `Execution` objects. | def parse_the_file(filename: str) -> List[List[Execution]]:
"""
Main function to parsing of the file
"""
file_container = read_file(filename)
task_unparsed_container = divide_into_task_execute(file_container)
tasks = parse_all_task_execute(task_unparsed_container)
return tasks |
def read_the_file_current(filename: str) -> str:
"""
Opens and reads filename and returns the containing
"""
file_container = None
filename += ".ns"
with open(filename, "r") as file:
file_container = file.read()
if not file_container:
raise SyntaxError("The file is empty"... | The main task of the code is to parse a file into a structured list of execution tasks. It reads the file, splits its content into individual tasks, and parses each task into `Execution` objects, returning a list of lists of these parsed tasks for further processing or execution. | def parse_the_file_current(filename: str) -> List[List[Execution]]:
file_container = read_the_file_current(filename)
task_unparsed_container = divide_into_task_execute(file_container)
tasks = parse_all_task_execute(task_unparsed_container)
return tasks |
def compute_mean_mles(train_data, train_labels):
'''
Compute the mean estimate for each digit class. You may iterate over
the possible digits (0 to 9), but otherwise make sure that your code
is vectorized.
Arguments
train_data: size N x 64 numpy array with the images
train_labels: s... | The main task of the code is to implement a Gaussian Naive Bayes classifier by estimating class means and covariances from training data, compute conditional likelihoods, evaluate model performance via average log-likelihood and classification accuracy on training/test sets, and visualize principal eigenvectors of clas... | def main():
train_data, train_labels, test_data, test_labels = data.load_all_data()
# Fit the model
means = compute_mean_mles(train_data, train_labels)
covariances = compute_sigma_mles(train_data, train_labels)
b = conditional_likelihood(train_data, means, covariances)
# Evaluation
tr... |
def compute_mean_mles(train_data, train_labels):
'''
Compute the mean estimate for each digit class. You may iterate over
the possible digits (0 to 9), but otherwise make sure that your code
is vectorized.
Arguments
train_data: size N x 64 numpy array with the images
train_labels: s... | The main task of the code is to train a probabilistic model by estimating class-specific means and covariances from training data, evaluate its performance using average conditional log-likelihood and classification accuracy on both training and test sets, and visualize the leading eigenvectors of each class's covarian... | def main():
train_data, train_labels, test_data, test_labels = data.load_all_data()
# Fit the model
means = compute_mean_mles(train_data, train_labels)
covariances = compute_sigma_mles(train_data, train_labels)
# Evaluation
train_log_llh = avg_conditional_likelihood(train_data, train_labels, m... |
def motion(self):
"""Applies a simple linear motion model that considers the last n_steps steps."""
for t in self.tracks:
last_pos = list(t.last_pos)
# avg velocity between each pair of consecutive positions in t.last_pos
if self.motion_model_cfg['center_only']:
... | The main task of this code is to perform real-time object tracking by updating existing tracks with new detections, applying motion models to predict positions, and managing track states (active/inactive). It processes input images through a neural network to detect objects, matches detections with existing tracks, upd... | def step(self, image):
"""This function should be called every timestep to perform tracking with a blob
containing the image information.
"""
for t in self.tracks:
# add current position to last_pos list
t.last_pos.append(t.pos.clone())
# apply motion mod... |
def create_train_state(
rng,
model_cls,
trainloader,
lr=1e-3,
lr_layer=None,
lr_schedule=False,
weight_decay=0.0,
total_steps=-1,
):
model = model_cls(training=True)
init_rng, dropout_rng = jax.random.split(rng, num=2)
params = model.init(
{"params": init_rng, "dropou... | This function trains a neural network model specified by 'layer' on a given 'dataset', using provided hyperparameters. It initializes randomness, loads data, constructs the model, trains over multiple epochs with validation, tracks best performance metrics, saves checkpoints, and logs results via wandb. Special handlin... | def example_train(
dataset: str,
layer: str,
seed: int,
model: DictConfig,
train: DictConfig,
):
# Warnings and sanity checks
if not train.checkpoint:
print("[*] Warning: models are not being checkpoint")
# Set randomness...
print("[*] Setting Randomness...")
torch.rando... |
def evaluation(fname):
paths, attributes = svg2paths(fname)
logger.debug("{} paths found".format(len(paths)))
res = []
for i in range(len(paths)):
res.append({'i': i, 'len': paths[i].length(error=1e-5)})
items = sorted(res, key=itemgetter('len'), reverse=True)
svg_tot_len = 0
for ite... | The code evaluates SVG files for signature authenticity, logging results and categorizing files based on their ratings. It processes individual files or directories, handling errors, and moves files to designated folders according to evaluation outcomes. Results are recorded in CSV format if enabled, with debug logs ot... | def run_evaluation(input_data, save_csv=True):
"""Evaluate signatures on a set of SVG files"""
if save_csv:
logging.basicConfig(format='%(message)s', filename=path.CSV_PATH, level=logging.INFO)
else:
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
logger.debug("Process SVG... |
def inverseMatrix(a):
dim = arrDim(a)
if (dim[0] == dim[1]):
deter = matrixDeterminent(a)
if (deter != 0):
inverse = [[0 for x in range(len(a[0]))] for y in range(len(a))]
if (len(inverse) == 1):
inverse[0][0] = 1
else:
sign ... | The function `systemEquations(a, b)` solves a system of linear equations represented by matrix `a` and vector `b` using matrix inversion. It checks if the dimensions of `a` and `b` are compatible. If valid, it computes the inverse of `a`, adjusts it by dividing by its determinant, multiplies it with the transposed vect... | def systemEquations(a,b):
dimA = arrDim(a)
if dimA[1] == len(b):
invA = inverseMatrix(a)
deter = matrixDeterminent(invA)
tranB = transposeMatrix([b])
for x in range(len(invA)):
for y in range(len(invA[x])):
invA[x][y] = (invA[x][y] ... |
def get_compatibility_mode(comment):
compatibility_mode = re.search(r'Compatibility mode: (\d+)', comment.body)
if compatibility_mode is None:
return 1
else:
return int(compatibility_mode.group(1))
def close_match_count(lyrics, index, text):
text = clean_up_text(text)
result = 0
... | The function traverses a chain of Reddit comments to calculate the extent of a lyric progression. It checks if comments match a specified song name and position, accumulating counts until a root comment or mismatch is found. If a matching comment is identified, it returns infinity to indicate a complete chain; otherwis... | def get_lyric_extent(song, song_name, comment, index, username):
current_comment = comment
current_index = index
current_extent = 0
while current_index >= 0:
if current_comment.author.name == username:
# find the current position using regex "Current position: <current_position>"
... |
def recommend_clubs_friends(
person_to_friends: Dict[str, List[str]],
person_to_clubs: Dict[str, List[str]],
person: str,) -> Dict[str, int]:
"""Return a dictionary that maps the clubs that friends of person from
"person to friends" dictionary person_to_friends are a part of but person
... | The function `recommend_clubs` generates personalized club recommendations for a given person by analyzing their friends' and acquaintances' club memberships. It prioritizes clubs not already joined by the person, scoring them based on friends' memberships (if unaffiliated) or acquaintances' memberships (if affiliated)... | def recommend_clubs(
person_to_friends: Dict[str, List[str]],
person_to_clubs: Dict[str, List[str]],
person: str,) -> List[Tuple[str, int]]:
"""Return a list of club recommendations for person based on the
"person to friends" dictionary person_to_friends and the "person
to clubs" dic... |
def normalize(data):
data = data.copy()
for column in data:
data[column] = (data[column] - data[column].min()) / (data[column].max() - data[column].min())
return data
def validate(train, val, k, k_num_correct):
num_correct = 0
for row in range(len(val)):
pred = predict(train, val.ilo... | The code implements a k-NN classifier for heart disease prediction. It loads and shuffles the dataset, splits it into training (60%), validation (20%), and test (20%) sets, normalizes features, tunes the optimal k-value (odd numbers up to 5) using validation accuracy, evaluates the best model on the test set, and calcu... | def main():
df = pd.read_csv('heart.csv')
df = df.sample(frac=1) # Shuffle the dataset
kNN_train = df.iloc[:182, :] # k-NN training set (60% of dataset)
kNN_val = df.iloc[182:242, :] # k-NN validation set (20% of dataset)
kNN_test = df.iloc[242:, :] # k-NN test set (20% of dataset)
# Normal... |
def _get_response_from_field(self, field_to_read, status_to_send=None):
field_value = None
try:
response = self.connection.recv(1024).decode('utf8')
response = json.loads(response)
if field_to_read in response:
field_value = response[field_to_read]
... | The code initializes a thread by retrieving a name, setting up a logger, and entering a loop to handle incoming messages. It processes game-end scenarios, parses commands when not waiting for a match, logs connection issues, and ensures proper closure of the connection upon exceptions or completion. | def run(self):
self.name = self._get_response_from_field(
field_to_read='my_name',
status_to_send='waiting'
)
self.logger = create_logger(name=f'{self.name}', color='YELLOW')
self.is_waiting_match = True
self.logger.info('new thread running...')
t... |
def _apply_move(self, position: int):
self._is_space_on_board() # TODO unsure if this is needed any more
self._taken_moves.add(position)
self._board.update_board(self._current_player, position)
def _count_moves(self) -> int:
return len(self._get_moves())
def _check_for_winner(self, move... | This function applies a move to the game state, checks for a win, determines if the game is a draw, and switches players if necessary. It first applies the move, checks for a win, exits early if won, checks for a draw if maximum moves are reached, and switches players based on move count. | def _move_and_switch_players(self, position: int):
self._apply_move(position)
move_count = self._count_moves()
self._check_for_winner(move_count)
if self.is_won():
return # TODO do we need this early return? Could we bundle two into check_win_or_draw()
if self._cou... |
def _is_valid_type(self, move: str) -> bool:
return move.isdigit()
def _is_available_move(self, move: int) -> bool:
is_in_range = self._is_valid_cell(move)
is_available = self._is_available_cell(move)
return is_in_range and is_available
def _move_and_switch_players(self, position: int):
... | The code validates a move's type and availability, executes it if valid, and returns status codes for invalid types or unavailable moves. It converts the move to an integer, checks validity, processes the move, switches players, and returns a success status upon valid execution. | def handle_move(self, move: str) -> str:
if not self._is_valid_type(move):
return Constants.INVALID_MOVE_TYPE
processed_move = int(move)
if not self._is_available_move(processed_move):
return Constants.UNAVAILABLE_MOVE
self._move_and_switch_players(processed_mov... |
def get_cities_list(csv_name):
# read cities
cities = []
with open(csv_name, newline='', encoding='ISO-8859-1') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
for row in reader:
cities.append(city_factory(row))
return cities
def generate_edges(cities):
edges = ... | The main task of the code is to read a list of cities from a CSV file, generate edges (connections) between them, and write these edges to a new CSV file named 'edges.csv'. | def main():
cities = get_cities_list('../data/cleancities.csv')
edges = generate_edges(cities)
write_to_csv(edges, 'edges.csv') |
def isLowestPoint(list, x, y):
if y == 0:
if not int(list[y][x]) < int(list[y + 1][x]):
return False
if x == 0:
if not int(list[y][x]) < int(list[y][x + 1]):
return False
if y == len(list) - 1:
if not int(list[y][x]) < int(list[y - 1][x]):
return F... | The code identifies the three largest "basil sizes" in a 2D grid. It iterates through each cell, checks if it's a lowest point, calculates the basil size from that point, and maintains the top three largest values. Finally, it returns the product of these three values. Your return | def findSolution(list):
threeLargest = [0] * 3
for y in range(len(list)):
for x in range(len(list[0])):
if isLowestPoint(list, x, y):
coordinatesAlreadySeen.append([x, y])
basilSize = findBasilSize(list, x, y)
threeLargest = addToArrayIfInThree... |
def checkPass():
#!check if the given key is correct by checking if the md5 hash of the given key matches the hash in thoth script.
givenHash = eval(open(joinAddr(globalCurrentDirectoryObject.path, f"{globalCurrentDirectoryObject.name}.ththscrpt"), "r").read())['hash']
key = generateKey(passBox.get())
h... | The function securely encrypts selected files using a password-derived key, adds them to an encrypted folder, and updates a progress UI while restricting .thth/.ththscrpt file selection. | def addFilesIntoEncryptedFolder():
if not checkPass():
return
if not messagebox.askokcancel('Encrypt and add files', 'In the following window, select the files you want to encrypt and add into the target folder.'):
return
fileList = list(filedialog.askopenfilenames(title='Select files to enc... |
def checkPass():
#!check if the given key is correct by checking if the md5 hash of the given key matches the hash in thoth script.
givenHash = eval(open(joinAddr(globalCurrentDirectoryObject.path, f"{globalCurrentDirectoryObject.name}.ththscrpt"), "r").read())['hash']
key = generateKey(passBox.get())
h... | This function decrypts a selected encrypted file using a password, moves the decrypted file to a desktop folder named 'fromThoth', and updates the UI with a progress window. It checks password validity, generates a decryption key, confirms user intent via a dialog, creates the destination folder, and uses modifyByChunk... | def removeFileFromEncryptedFolder():
if not checkPass():
return
filename = globalCurrentlySelectedPath.split(sep="\\")[-1]
key = generateKey(passBox.get())
if not messagebox.askokcancel("Decrypt and move to desktop...", f"This function decrypts {Fernet(key).decrypt(filename.removesuffix('.thth')... |
def checkPass():
#!check if the given key is correct by checking if the md5 hash of the given key matches the hash in thoth script.
givenHash = eval(open(joinAddr(globalCurrentDirectoryObject.path, f"{globalCurrentDirectoryObject.name}.ththscrpt"), "r").read())['hash']
key = generateKey(passBox.get())
h... | This function decrypts and opens an encrypted file using a password, creates a progress window, handles decryption errors, temporarily stores the decrypted file, and manages UI widgets to prevent accidental modifications. It warns against opening encrypted files directly and ensures proper cleanup by re-encrypting and ... | def startFile(event):
global globalCurrentlySelectedPath
global globalCurrentDirectoryObject
path = globalCurrentlySelectedPath
key = generateKey(passBox.get())
if globalIsTranslatedBoolean and isFile(path):
if checkPass():
name = Fernet(key).decrypt(path.split(sep='\\')[-1].remo... |
def predict(t_net, t_cfg, vali_Dataloader, mode=-1):
'''
:param t_net: pa_rnn_net(encoder, decoder, encoder_optimizer, decoder_optimizer)
:param t_dat: data include train and evaluation and test.
:param t_cfg: config file for train
:param on_train: when on_train, predict will evaluate the result usi... | The function evaluates a model's performance on a validation dataset by predicting outputs, reshaping tensors, clipping negative values, scaling predictions, and computing a MAE score using either single or multi-task evaluation. It returns the score, original/truth values, and processed predictions for analysis. | def evaluateResult(net, config, vali_Dataloader, logger, mode=-1):
y_vali_pred, y_vali, y_vali_ori, y_vali_pred_c, y_vali_ori_c, truex = predict(net, config, vali_Dataloader, mode=mode)
y_vali_pred = y_vali_pred.reshape(-1,y_vali_pred.shape[-1])
y_vali_pred_c = y_vali_pred_c.reshape(-1,y_vali_pred.shape[-1... |
def createSequences (k):
all_sequences = []
sequence = emptySequence(k)
gold_tiles = 0
while (gold_tiles <= k):
all_sequences += completeSequence(sequence,gold_tiles,0)
gold_tiles += 1
return all_sequences
def createArtwork (sequence, original, gold, complexity):
complexity -... | The code determines the minimum number of tiles to flip in a fractile sequence to uniquely identify all possible configurations. It processes input parameters (K=tiles, C=complexity, S=students) to generate valid sequences, transforms them, and checks feasibility with S flips. If S equals K, it returns all tile positio... | def fractiles (sample):
sample = sample.split(' ')
K = int(sample[0]) # number of tiles
C = int(sample[1]) # complexity: number of transformations
S = int(sample[2]) # students: number of tiles that can be turned over
if (S == K): # TIME SAVER: save some time discarding sequences we can see entir... |
def write_output(time,mem_limit,tr,action):
with open("out","a") as f_out:
f_out.write("{},{},{},{}\n".format(time,mem_limit,tr,action))
def update_bash(self):
if np.array(self.bash_tmp).shape[0]<25:
self.bash_tmp.append([
self.memorygetter.get_mem_proc() / 1048576 ,
... | The code's main task is to monitor a benchmark process, track elapsed time, and periodically trigger inference actions at intervals defined by 'FINESSE' once the first benchmark response is received. It updates system state, logs time/metrics, and runs in parallel with a benchmark thread, ensuring operations occur with... | def run(self):
start_time = time.process_time()
write_output("time","mem_limit","time_reponse","action")
self.t = round(time.process_time()-start_time,2)
Thread(target=run_bench).start()
while self.t<DURATION:
diff_t = round(time.process_time() - self.t - start_t... |
def planet_invasion_storyline_two():
"""
Displays planet invasion second storyline to the user
"""
slowprint("\n"
"You approach a large red planet,"
" covered in cityscapes \n"
"*Your terminal reads: Planet ⏚⟟⎅* \n"
"You: 'Max power to thrusters, s... | The function `ship_storyline_select` presents users with three narrative options to choose from, each leading to distinct story branches (e.g., pressing buttons or pulling levers). Depending on input (1, 2, or 3), it directs players to different storylines like `planet_invasion_storyline_two` or `bounty_hunt_storyline_... | def ship_storyline_select():
"""
Gives the user options to solve the mission
"""
ship_storyline_choices = UserNumbers(
"You press the big red button and there is a weird glow around"
" the outer of the \n"
"ship \n"
"Time bends, a black hole emerges and you appear in a n... |
def planet_invasion_storyline():
"""
Displays planet invasion storyline to the user
"""
slowprint("\n"
"You know you are ready to take the next step in"
" assisting the galaxy \n"
"*The friendly alien sees you nod your head* \n")
slowprint("\n"
... | The function allows a player to choose between two storylines by responding to a yes/no question about helping the Galaxy. It validates input, directs to 'planet_invasion_storyline()' for "yes" or 'bounty_hunt_storyline()' for "no", and recursively prompts again for invalid inputs, ensuring a valid choice is made to pr... | def distress_beacon_select():
"""
Allows player to select the storyline they want to go with
"""
spacing()
distress_beacon_choices = UserChoices(
"You nod your head, agreeing to help \n",
"You shake your head, choosing your own path \n",
"Please select yes or no. \n")
d... |
def parseCSVFile(path, delimiter, fieldnames=None, encoding="utf-8-sig"):
#Load in and parse a CSV file
#path - the filepath at which it is located
#delimiter - the separator type used in the CSV file
#fieldnames - a list of strings representing the headings of the CSV file, in order left-to-right
#... | The code evaluates a trained argument mining model's performance by comparing detected premises/conclusions (from `pc_pairs`) against a test dataset. It calculates recall (when training/test data overlap) and precision (when disjoint), using F1 scores. Results, including counts and metrics, are saved in a CSV file. The... | def testArgumentMining(model, pc_pairs, same_test_train_data):
#Run tests on the argument mining performance
#model - the trained premise/conclusion classifier
#pc_pairs - the extracted list of [list of extracted premises, list of extracted conclusions]
#same_test_train_data - bool, if true tests recall... |
def send_sign_in(self):
self.amqp.send_something(self.create_status_msg(status="sign in"))
def hook_send_sign_out(self):
import atexit
def exit_handler():
self.send_sign_out()
atexit.register(exit_handler)
def should_send_waiting(self):
current_time = int(time.time())... | The main task of the code is to manage a client's interaction with a game server, including signing in, handling game state transitions (in/out of game), sending waiting status when idle, and transmitting game moves via AMQP messaging. It continuously listens for messages, processes game steps, and maintains communicat... | def run(self):
logging.info("Client.run has started")
self.send_sign_in()
self.hook_send_sign_out()
while True:
self.amqp.try_recv(LISTENING_TIMEOUT)
if not self.ingame:
logging.info("not in game")
if self.should_send_waiting():
... |
def initialize_parameters(layers_dims):
"""
Initialize parameters dictionary.
Weight matrices will be initialized to random values from uniform normal
distribution.
bias vectors will be initialized to zeros.
Arguments
---------
layers_dims : list or array-like
dimensions of each layer in the... | The code implements a multilayer neural network using gradient descent with line search optimization to minimize a cost function. It initializes parameters, computes forward and backward passes, and dynamically adjusts the learning rate via a line search algorithm (Wolfe-Powell conditions) to ensure convergence. Regula... | def L_layer_model(
X, y, layers_dims, learning_rate=0.01, num_iterations=3000,
print_cost=False, hidden_layers_activation_fn="relu", lambda_reg=1e-2):
"""
Implements multilayer neural network using gradient descent as the
learning algorithm.
Arguments
---------
X : 2d-array
data, shape: n... |
def getVersion(module):
directory = getCurrentDirectory() + '/' + module.split('/')[-1]
file = open(directory + "/pom.xml", "r")
version = ""
ignore = False
for line in file:
if isInArray(skippedPomFragments, line):
ignore = True
if isInArray(endSkippedPomFragments, line)... | The function `incrementVersion` retrieves the current version of a module, increments it by inserting a zero (e.g., 1.0 → 1.0.1), logs the change, and updates the module's version. It handles versioning logic, logging, and modification of module versions. | def incrementVersion(module):
currentVersion = getVersion(module)
incrementedVersion = insertZero(currentVersion)
Logger.getInstance().log('Increment version of ' + module + ' from ' +
currentVersion + ' to ' + incrementedVersion)
changeVersion(module, currentVersion, increm... |
def menu_bar(screen, settings, x):
if settings.game_over:
try_rect = TRY_AGAIN.get_rect()
try_rect.center = (settings.screen_size // 2 + settings.square_size, settings.screen_size + (settings.screen_bot / 2))
if try_rect.left <= x <= try_rect.right:
settings.play_again = True
... | This function handles user events in a game, checking for quit signals and mouse clicks. It calculates grid coordinates from mouse positions, triggering actions like opening the menu bar (left-click in the menu area) or selecting/clicking cells (left-click on grid). Right-click flags cells if the game isn't over, using... | def check_events(screen, settings):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
if event.type == pygame.MOUSEBUTTONDOWN:
left, mid, right = pygame.mouse.get_pressed()
pos = pygame.mouse.get_pos()
col = int(pos[0] // setti... |
def load_r_tree(file_path):
r_tree_index = Rtree(file_path)
return r_tree_index
def match_nodes_to_polygon(tag_ids, nodes, r_tree_index, polygons):
for node in nodes:
features = get_features(node.tags, tag_ids, "count")
if len(features) == 0:
return polygons
matches... | This function matches node and way features to polygons using an R-tree spatial index. It loads the index, then iterates through nodes and ways by tag ID, associating each feature list with polygons via spatial queries. The modified polygons with matched features are returned. | def match_polygons_to_features(polygons, r_tree_path, nodes, ways, areas=None):
r_tree_index = load_r_tree(r_tree_path)
logging.info("\t\tMatching node features to polygons...")
for tag_id, nodes_lst in nodes.items():
polygons = match_nodes_to_polygon(tag_id, nodes_lst, r_tree_index, polygons)
... |
def file_exists(self, name):
"""
:param name: name for any type of file which could be directory file or regular file
:return: True if file exists
"""
command = "fs -ls | grep '{name}'".format(name=name)
output = self.shell(command)
print('Searching for',name, c... | This function executes a MapReduce job using Hadoop Streaming by validating input data, formatting mapper/reducer arguments, constructing a shell command to run the job, and retrieving results. It ensures unique output directories, handles file existence checks, and streams data processing through specified mapper and ... | def map_reduce(self,data_src, mapper, reducer, mapper_arguments=None, reducer_arguments=None, output_dir = 'output'):
if not self.file_exists(data_src):
raise Exception('No such file exists: '+ data_src)
output_dir = self.find_unique_output_directory(output_dir)
mapper_arguments =... |
def find_prefix_path(basePat, TreeNode):
Conditional_patterns_base = defaultdict(lambda: None)
while TreeNode != None:
prefixPath = []
transveral(TreeNode, prefixPath)
if prefixPath!=None and len(prefixPath) > 1:
Conditional_patterns_base[frozenset(prefixPath[1:])] = TreeNod... | This function recursively generates frequent itemsets from an FP-Tree by iterating through sorted header items, building conditional patterns, and appending valid itemsets to the result list while propagating through sub-trees. | def get_frequent(FPTree, HeaderTable, minSupport, prefix, frequent_itemset):
bigL = [v[0] for v in sorted(HeaderTable.items(),key=lambda p: p[1][0])]
for basePat in bigL:
new_frequentset = prefix.copy()
new_frequentset.add(basePat)
frequent_itemset.append((new_frequentset))
... |
def randomGene(self):
gene = []
for i in range(self.geneLength):
if(random() > 0.5):
gene.append('C')
else:
gene.append('A')
return gene
def fitness(self, gene):
steps = self.recursiveSolver.solve(gene)
if steps < self.minSt... | The code implements a genetic algorithm to evolve a population of genes toward a target fitness of 0. It initializes a random population, iterates through generations, and applies selection, reproduction, and mutation. It tracks the best individual, halting early if a solution is found or returning the best after max g... | def run(self):
population = []
for i in range(self.populationSize):
population.append(self.randomGene())
# attempting to find fitness no larger than 0
best = min(population, key = lambda c: self.fitness(c))
for g in range(self.maxGenerations):
# early retu... |
def safePositions(self):
threats = [-1] * self.n * self.n
for row in range(0, self.n):
for column in range(0, self.n):
pos = (column, row)
if pos in self.queens:
continue
threats[row * self.n + column] = self.queenThreats(po... | The code checks if the total number of distinct king arrangements computed by `totalKingArrangements` matches the target value `targetDistinctKingArrangements` and whether a validity condition (`ok`) is satisfied, returning `True` only if both are met. | def satisfiesTarget(self, targetDistinctKingArrangements):
safePositions = self.safePositions()
groupKingCounts = self.safePositionGroupKingArrangementCounts()
amount,ok = self.totalKingArrangements(groupKingCounts, 0, [], targetDistinctKingArrangements)
return (amount == targetDistinctK... |
def create_random_list(length, max_value):
return [random.randint(0, max_value) for _ in range(length)]
def bubble_sort(L):
for i in range(len(L)):
for j in range(len(L) - 1):
if L[j] > L[j+1]:
swap(L, j, j+1)
def insertion_sort(L):
for i in range(1, len(L)):
inse... | The code conducts an experiment to compare the time efficiency of Bubble Sort, Insertion Sort, and Selection Sort across different list sizes. It generates random lists of varying lengths, runs each sorting algorithm multiple times, calculates average execution times, and plots the results to visualize performance diff... | def Experiment1():
list_lengths = [10, 100, 500, 1000, 5000]
num_runs = 5
bubble_time = {}
insertion_time = {}
selection_time = {}
for length in list_lengths:
avg_bubble_time = 0
avg_insertion_time = 0
avg_selection_time = 0
for run in range(num_runs):
... |
def _download_experiment_files(exp: Experiment):
exp_root = f"data/{exp.name}"
os.makedirs(exp_root, exist_ok=True)
global_gating_ml_f_path = _download_global_gating_ml(exp, exp_root)
_upload_to_s3(f_path=global_gating_ml_f_path)
n = len(exp.fcs_files)
for idx, fcs_file in enumerate(exp.fcs_f... | The code processes multiple experiments by downloading their files, extracting annotations, compiling them into a single Excel file ("Annotations.xlsx"), and uploading the file to S3 while removing the local copy. The task involves logging experiment names, aggregating annotation data, and managing file storage. | def process_experiments(experiments):
experiment_names = [exp.name for exp in experiments]
logger.info(f"Process experiments: {experiment_names}")
annotations_df = pd.DataFrame()
n = len(experiments)
for idx, exp in enumerate(experiments, 1):
with logger.contextualize(exp=f"({idx}/{n}) {ex... |
def up(self, index):
self.tick(index)
self.current_s[index,5] += 1.0
if self.current_s[index,5] >= 32:
if self.current_s[index,1] < 0.5: # Square
if self.current_s[index,4] > 15:
self.last_r[index] = float(15.0-self.current_s[index,4])/16.0
... | This function converts a policy value `pi` into an action by attempting to move in a direction (up, down, left, or right) at a given `index`. It repeats the action `repeats` times. If any attempt causes a "round change" (via `self.up()`), it returns `True`. Otherwise, after all attempts, it returns `False`. | def pi_to_action(self, pi, index, repeats=1):
round_changed = False
for i in range(repeats):
if pi == 0: round_changed = self.up(index)
elif pi == 1: self.down(index)
elif pi == 2: self.left(index)
elif pi == 3: self.right(index)
else: exit('Va... |
def freeze_layers(model, unfrozen_types=[], unfrozen_keyword=None):
""" Freezes all layers in the given model, except for ones that are
explicitly specified to not be frozen.
# Arguments:
model: Model whose layers should be modified.
unfrozen_types: List of layer types which shouldn't b... | The main task of the code is to compile and finetune a given neural network model using specified methods (e.g., 'last', 'full', 'chain-thaw') and evaluation metrics (e.g., accuracy). It processes training, validation, and test data, configures the model's optimizer and loss function based on the number of classes, app... | def finetune(model, texts, labels, nb_classes, batch_size, method,
metric='acc', epoch_size=5000, nb_epochs=1000,
error_checking=True, verbose=1):
""" Compiles and finetunes the given model.
# Arguments:
model: Model to be finetuned
texts: List of three lists, containi... |
def unsafe_preliminar_delete_import_range(session):
"""
Deletes the previously imported records and their
corresponding import range registry from the db.
"""
to_delete = session.scalars(sqlalchemy.select(ImportRegistry).order_by(ImportRegistry.id))
unsafe_delete_import_range(session, to... | This code's main task is to import CSV data into a database in batches, handling command-line arguments, parsing input files, and managing database transactions. It reads CSV records, processes them in chunks, and inserts them into a database session while avoiding DictReader for performance. The function supports head... | def main():
"""
main routine. Coordinates all the concepts and ideas into a single function.
"""
parser = cli_parser()
args = parser.parse_args()
stream = manage_input(args.input)
delimiter = args.delimiter
has_header = args.has_header
with stream as file, session_builder... |
def Get_residues_from_pose(pose):
"""
Get the sequence and residue numbers for a specific chain in a given pose.
Parameters:
- pose: PyRosetta Pose object
- chain: Chain identifier (e.g., 'A')
Returns:
A tuple containing the chain sequence and a list of residue numbers.
"""
re... | The function `apt_rosetta` performs threading optimization on a protein structure by mutating specific residues in a starting pose to align with a target sequence. It uses a score function to evaluate structural energy, mutates identified positions, repacks the structure, and saves the optimized pose as a PDB file. Dep... | def apt_rosetta(seq, starting_pose, scorefxn, dg_method, index_ind, index_cycle):
"""
Perform threading optimization for a sequence.
Parameters:
- seq: Target sequence for threading
- starting_pose: PyRosetta Pose object representing the initial protein structure
- scorefxn: Score function to e... |
def Get_residues_from_pose(pose):
"""
Get the sequence and residue numbers for a specific chain in a given pose.
Parameters:
- pose: PyRosetta Pose object
- chain: Chain identifier (e.g., 'A')
Returns:
A tuple containing the chain sequence and a list of residue numbers.
"""
re... | The function `apt` optimizes a protein structure to align with a target sequence using adaptive threading. It mutates specific residues in the initial pose, repacks the structure, and relaxes it. The optimized structure is saved as a PDB file. Depending on `dg_method`, it calculates either binding energy (`bind`) or fo... | def apt(seq, starting_pose, scorefxn, dg_method, index_ind, index_cycle):
"""
Perform an optimization process on a protein structure using an adaptive protein threading approach.
Parameters:
- seq: Target sequence to optimize towards
- starting_pose: PyRosetta Pose object representing the initial p... |
def saturation_specific_humidity(pressure, temperature):
"""Calculate saturation specific humidity."""
q_star = mpcalc.specific_humidity_from_mixing_ratio(
mpcalc.saturation_mixing_ratio(pressure, temperature))
if not hasattr(pressure, 'size') and not hasattr(temperature, 'size'):
return q_s... | The function `moist_lapse_dj` computes temperatures along pseudoadiabats using Davies-Jones' (2008) method. It calculates the wet-bulb temperature for given pressures, starting from an initial temperature and reference pressure. The process involves determining saturation-specific humidity, equivalent potential tempera... | def moist_lapse_dj(
pressure, initial_temperature, reference_pressure=None, improve=True):
"""
Compute temperature from pressure along pseudoadiabats.
Follows the method of Davies-Jones (2008).
Args:
pressure: Array of pressures for which the temperature is to
be found.
... |
def saturation_specific_humidity(pressure, temperature):
"""Calculate saturation specific humidity."""
q_star = mpcalc.specific_humidity_from_mixing_ratio(
mpcalc.saturation_mixing_ratio(pressure, temperature))
if not hasattr(pressure, 'size') and not hasattr(temperature, 'size'):
return q_s... | This function computes temperatures along reversible adiabats using Davies-Jones' (2008) method, with corrected equations. It iteratively applies Newton's method to calculate temperatures for given pressure profiles, starting from initial conditions (temperature, humidity, liquid ratio). The result is an array of tempe... | def reversible_lapse_daviesjones(
pressure, initial_temperature, initial_liquid_ratio,
reference_pressure=None, improve=2):
"""
Compute temperature along reversible adiabats.
Uses the method of Davies-Jones (2008). Variable names follow the
notation of Davies-Jones.
Errors were fou... |
def search_instrument(self, instrument, exchange='NSE'):
"""
Search for an instrument
Args:
instrument: instrument key
exchange: exchange, default is 'NSE'
Returns:
A list of matching instruments
"""
assert isinstance(instrument, str... | The `start_job` method submits a backtesting (BT), paper trading (PT), or real trading (RT) job for a strategy on the AlgoBulls Platform. It validates and processes parameters like strategy code, timestamps, instruments, lots, and trading mode, ensuring compatibility with required formats. It configures strategy settin... | def start_job(self, strategy_code=None, start_timestamp=None, end_timestamp=None, instruments=None, lots=None, strategy_parameters=None, candle_interval=None, strategy_mode=None, initial_funds_virtual=None, delete_previous_trades=True,
trading_type=None, broking_details=None, **kwargs):
"""
... |
def __prepare_to_get_cumulative_energy(self) -> None:
if self.energy_coefficient is None:
try:
self.energy_coefficient = self.get_coefficient_for_cumulative_energy()
time.sleep(self.internal_xmit_interval)
except MomongaResponseNotPossible:
... | This function retrieves historical cumulative energy data for a specified day, processes raw byte data from a device response, converts it into timestamped energy values, and returns a list of dictionaries with timestamps and corresponding energy readings, adjusting for reverse data flags and special values. | def get_historical_cumulative_energy_1(self,
day: int = 0,
reverse: bool = False,
) -> list[dict[str: datetime.datetime,
str: dict[st... |
def __prepare_to_get_cumulative_energy(self) -> None:
if self.energy_coefficient is None:
try:
self.energy_coefficient = self.get_coefficient_for_cumulative_energy()
time.sleep(self.internal_xmit_interval)
except MomongaResponseNotPossible:
... | This function retrieves historical cumulative energy data from a device, processing byte responses into a list of dictionaries. It extracts timestamps and energy values (normal/reverse directions), converts bytes to integers, applies unit coefficients, handles invalid data (0xFFFFFFFE), and returns results in 30-minute... | def get_historical_cumulative_energy_2(self,
timestamp: datetime.datetime = None,
num_of_data_points: int = 12,
) -> list[dict[str: datetime.datetime,
... |
def convertLoadAmountToNum(self, load_amount) -> float:
#converts the currency string '$343.43' into float
return float(load_amount[1:])
def checkCustomerID(self, customer_id) -> bool:
#This checks if we were given a integer string for customer_id
return str.isdigit(customer_id)
def addN... | The function processes a user's deposit attempt by validating the customer ID, checking daily and weekly deposit limits (both in count and amount), resetting counters if needed, and updating user records if all checks pass; returns a response indicating acceptance or rejection. | def processUserLoad(self, customer_json):
#The main function for processing deposit attempts
#Does a check if customer_id is an integer string
#Then runs all the checks for daily load quota, daily amount deposit quota,
#weekly amount deposit quota, and then updates accounts_json records ... |
def lrc(bits, parity='E'):
print('**** LRC ****')
l = len(bits)
streams = []
lrC = None
for i in range(int(l/8)):
str_ = int(bits[i*8:i*8+8], 2)
streams.append(str_)
if lrC == None:
lrC = str_
else:
lrC = lrC ^ str_
lrC = bin(lrC)[2:]
... | The code implements a menu-driven program for error detection techniques. It allows users to select LRC, VRC, CRC, or checksum methods, input required parameters (data, bits, parity, etc.), and execute the chosen error-checking algorithm. The loop handles input validation, ensures correct options, and exits on user req... | def main():
while True:
try:
ans = int(
input("Press 1 for LRC\nPress 2 for VRC\nPress 3 for CRC\nPress 4 for checksum\nPress 0 to exit\nEnter your choice: "))
except ValueError:
print("Select a correct option")
continue
if ans == 1 or ans ... |
def resetSkeleton( heading ):
global skeleton
skeleton = ""
if heading == '' :
heading = "CodeForces Problem"
#\usepackage[a4paper, total={6in, 8in}]{geometry}
packages = ["inputenc", "fontenc", "xcolor", "amsmath", "geometry"]
encoding = [ "", "T1", "", "", "a4paper, total={6in, 10in}... | The main task of the code is to generate a contest PDF document by compiling individual problem PDFs. It takes a list of problem links and a contest name, processes each link to create a PDF section, appends page breaks between problems, and combines them into a single LaTeX document. The global `skeleton` variable is ... | def createContestPDF( problemlinks, contestName ):
global skeleton
resetSkeleton( '' )
#In this case, skeleton needs to be reset only once globally.
try :
for link in problemlinks :
makePDF( link, contestName, 1 )
skeleton += "\n\\newpage"
skeleton += "\n\\end{do... |
def get_sql_prompt(
self,
question: str,
doc_list: list,
question_sql_list: list,
**kwargs,
):
"""
Example:
```python
vn.get_sql_prompt(
question="What are the top 10 customers by sales?",
question_sql_list=[{"question":... | The main task of the code is to generate an SQL query that answers a given question by leveraging similar question-SQL pairs, related database schema definitions (DDL), and documentation. The function constructs a prompt using these elements, submits it to a language model, extracts the SQL from the response, and retur... | def generate_sql(self, question: str, **kwargs) -> str:
"""
Args:
question (str): The question to generate a SQL query for.
Returns:
str: The SQL query that answers the question.
"""
initial_prompt = None
question_sql_list = self._embedding_store... |
def _search_qubrics_by_qid(values, db, config):
"""
Searches for spectra in the QUBRICS database based on the provided qid.
Parameters:
-----------
values : dict
A dictionary of values containing the input qid.
db : QubricsDB
The QUBRICS database object.
Returns:
------... | The function `search_spectra` searches for spectra in either the SpecDB or QUBRICS database based on input parameters. It checks the presence of a QID and the `is_qubrics` flag to determine the appropriate search method: querying by QID or coordinates. The function routes requests to specialized helper functions (`_sea... | def search_spectra(values, db, is_qubrics=False, config=None):
"""
Searches for spectra in the SpecDB or QUBRICS database based on the
provided values.
Parameters:
-----------
values : dict
A dictionary of values containing the input coordinates or qid.
db : SpecDB or QubricsDB
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.