dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def inCheck(self):
if self.whiteToMove :
return self.squareUnderAttack(self.whiteKingPosition[0],self.whiteKingPosition[1])
else :
return self.squareUnderAttack(self.blackKingPosition[0], self.blackKingPosition[1])
def getKingSideCastleMoves(self,r,c,moves):
pieceColor = ... | This function generates valid castling moves for the king based on the current player's turn and available castle rights. It checks if the king is not in check and verifies if king-side or queen-side castling is permitted, then calls corresponding methods to add valid castling moves to the provided list. | def getCastleMoves(self,r,c,moves):
if self.inCheck() :
return
if (self.whiteToMove and self.currentCastleRight.wks) or (not self.whiteToMove and self.currentCastleRight.bks):
self.getKingSideCastleMoves(r,c,moves)
if (self.whiteToMove and self.currentCastleRight.wqs) or ... |
def getAllPossibleMoves(self):
moves = []
for r in range(len(self.board)) :
for c in range(len(self.board[r])):
turn = self.board[r][c][0]
#piece = self.board[r][c][1]
if (turn=='w' and self.whiteToMove) or (turn=='b' and not self.whiteToMove) ... | The code generates valid chess moves by first copying current game states (en passant, castling rights), generating all possible moves, then iterating through them to check if they leave the king in check. Invalid moves are removed, and checkmate/stalemate is determined if no valid moves remain. Finally, it restores or... | def getValidMoves(self):
tempEnPassantPossible = self.enPassantPossible
tempCastleRights = CastleRights(self.currentCastleRight.wks,self.currentCastleRight.bks,
self.currentCastleRight.wqs,self.currentCastleRight.bqs) #copy the current castling rights
#... |
def select(self, cell):
cell.color = SELECTED_COLOR
def drawy(self, drawer):
drawer()
self.update()
pygame.display.flip()
def check_goals(self, cell, drawer):
for goal in self.goals:
if cell == goal:
if not goal.is_finished():
goal... | This code implements a Breadth-First Search (BFS) algorithm to explore a grid. It dequeues cells, visualizes them, checks for goal states, expands free neighboring cells, tracks paths via parent pointers, and updates the visualization at each step to demonstrate the search process and pathfinding progression. | def bfs(self, drawer):
queue = deque()
queue.append(self.start)
while queue:
c_cell = queue.popleft()
self.select(c_cell)
self.drawy(drawer)
if self.check_goals(c_cell, drawer):
self.drawy(drawer)
for cell in self.get... |
def select(self, cell):
cell.color = SELECTED_COLOR
def drawy(self, drawer):
drawer()
self.update()
pygame.display.flip()
def check_goals(self, cell, drawer):
for goal in self.goals:
if cell == goal:
if not goal.is_finished():
goal... | This code implements a depth-first search (DFS) algorithm to traverse a grid. It uses a stack to explore cells, selecting each cell, checking if it's a goal, expanding free neighbors, and visualizing progress through draw operations. The search tracks paths via 'father' pointers and marks reached cells. | def dfs(self, drawer):
stack = []
stack.append(self.start)
while stack:
c_cell = stack.pop()
self.select(c_cell)
self.drawy(drawer)
if self.check_goals(c_cell, drawer):
self.drawy(drawer)
for cell in self.get_neighboo... |
def select(self, cell):
cell.color = SELECTED_COLOR
def drawy(self, drawer):
drawer()
self.update()
pygame.display.flip()
def check_goals(self, cell, drawer):
for goal in self.goals:
if cell == goal:
if not goal.is_finished():
goal... | This code implements the A* pathfinding algorithm to find a route from a start cell to a goal cell on a grid. It uses a priority queue to explore cells, updating their distances and parent pointers when more optimal paths are found. The algorithm visualizes the search process by drawing selected cells and checking for ... | def a_star(self, drawer):
pq = PriorityQueue()
self.start.eval = 0
pq.put((self.start))
while not pq.empty():
c_cell = pq.get()
self.select(c_cell)
self.drawy(drawer)
if self.check_goals(c_cell, drawer):
self.drawy(drawer)
... |
def _load_files(self):
self._log("Loading Json Data...\n")
self._log("{:<20} {:<20}".format("File", "Loaded"))
for key, value in self._json_file_names.items():
time.sleep(0.5)
self._json_data[key] = self._get_json_data(value)
self._log("Json Data Loaded ✅\n")
def ... | The code initializes a ConfigSyncer class to manage and synchronize configuration data from multiple JSON files. It sets up data structures for storing configuration details, loads existing JSON files, updates moon-related extra information, removes outdated data, and synchronizes scrap data. The primary task is to org... | def __init__(self):
self._log_prefix = "ConfigSyncer: "
self._json_file_directory_name = "Json Files"
self._moon_names = []
self._json_file_names = {
"scrap": "scrap.json",
"outside": "outside.json",
"inside": "inside.json",
"daytime": "day... |
def handle_terminal_path(self, path, node):
"""Handle a terminal path."""
terminal = path[:-1] + path[-1].capitalize()
end = node.index
# Update labels
self.labels[terminal] = self.labels[path]
# Update the 'Path' column in the DataFrame
self.data.loc[se... | This function splits decision tree nodes using a specified metric, evaluating feature splits to optimize classification. It processes data paths, checks termination conditions (e.g., insufficient samples or pure class), calculates scores, selects best splits, updates tree structure/labels, and handles terminal nodes. M... | def get_splits(self, metric):
"""Split the decision tree for that level"""
data = self.data # Store a reference to self.data for faster access
feats = list(data.columns[4:])
class_idx = self.class_idx # Store a reference to self.class_idx
labels = self.labels # Store a refere... |
def handle_categorical(self, col, node_tar):
condition = col > 0
mask, node_diff = self.handle_condition(condition, node_tar)
if node_diff > 0.95 * self.node_diff:
return pd.DataFrame({0: mask})
return pd.DataFrame()
def handle_continuous(self, col, node_tar):
# Handl... | This function calculates the optimal split metric for a given data feature in a decision tree, handling both categorical and continuous data. It checks unique values to determine data type, processes splits, computes scores using the specified metric (e.g., Gini), filters results, and returns the best split score or fo... | def test_split(self, col, metric, node_tar, gini):
"""Calculate metric based on data feature turning on or off"""
mixed = 0
if col.nunique() == 1:
return f'== 0 {np.nan} 0'
if col.nunique() <= 2: # Handling categorical data
df = self.handle_categorical(col, node... |
def variablesFromGroup(self,group):
variables = [self.variableFromSentence(sentence=p) for p in group]
return variables
def train(self,input_variable, target_variable,
encoder, decoder, context, context_hidden,
encoder_optimizer, decoder_optimizer, criterion,
last,max... | The main task of the code is to train an encoder-decoder model with a context module using sequence data. It initializes optimizers, iterates through training groups, computes loss via NLLLoss, accumulates gradients, and performs backpropagation. The function tracks training loss, prints metrics periodically, saves mod... | def trainIters(self,encoder=None, decoder=None,
context=None, print_every=100, plot_every=100, evaluate_every=500,
learning_rate=None):
encoder = self.encoder_model
decoder = self.decoder_model
context = self.context_model
learning_rate = self.learning_rate
... |
def get_coreferenced_str(testStrs):
coreferenced_strs = []
for testStr in testStrs:
clusters = coref.one_shot_coref(utterances= testStr)
testStr = coref.get_resolved_utterances()[0]
coreferenced_strs.append(testStr)
return coreferenced_strs
def transform_testdata(test_strs, vocabular... | The code predicts movie labels (e.g., genres, titles) from input text using a trained model, incorporating coreference resolution, event extraction, named entity recognition, and sentence embeddings. It transforms input strings into feature vectors, applies the model to generate predictions, and returns the top 1–5 mov... | def predict_movie(testStrs, model, labels_dict, vocabulary, event_voc, ners_voc, multiple = False):
#testStrs = ["A young girl rises to fame in Broadway while many other theatre figures are jealous and disgusted. She starts as a general assistant to another bright star of Broadway and slowly she becomes the new sta... |
def get_square_value(self, col_id: int, row_id: int) -> str:
return Square.objects.get(game=self.pk, col_id=col_id, row_id=row_id).value
def update_square_value(self, username: str, col_id: int, row_id: int) -> None:
player_symbol: str = self.get_player_symbol(username)
Square.objects.fil... | The main task of the code is to process a single player's move in a turn-based game. It validates the move by checking if the game is active, if it's the player's turn, and if the selected square is empty. If valid, it updates the game state, checks for a win or draw, and returns appropriate notifications. If invalid, ... | def process_one_turn(self, username: str, col_id: int, row_id: int) -> dict[str, str]:
notifier: Notifier = Notifier(board_status=Game.get_board_status(pk=self.pk))
# Start game if there are two players
if (self.opponent is None):
response: dict[str, str] = notifier.get_wai... |
def listen_for_keyword(keyword):
detected_word = recognize_speech().lower()
if keyword in detected_word:
return True
else:
return False
def recognize_speech():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
audio = recognizer.listen(source, phrase_time_limi... | The code implements a voice-activated chatbot that plays an introduction sound, listens for a trigger keyword ("hey chatbot"), and responds to voice commands with synthesized speech. It continuously recognizes speech input, generates responses, and plays audio feedback, terminating upon receiving "exit" or "goodbye" | def main():
os.system("mpg321 intro.mp3")
while True:
if listen_for_keyword("hey chatbot"):
os.system("mpg321 dingding.mp3")
while True:
os.system("mpg321 ding.mp3")
user_input = recognize_speech()
if user_input in ['exit', 'goodbye'... |
def lambda_objective() -> Callable[[float, float, float, float, int, float], float]:
"""Generate a lambdified objective function.
Returns
-------
Callable[(float, float, float, float, int, float), float]
Objective function whose roots yield periastron distances for isoradials. The function
... | The function calculates the impact parameter $ b $ for each polar angle $ \alpha $ by solving for periastron distances using a root-finding method. It employs an objective function (defaulting to a predefined one) and fallbacks to an elliptical orbit calculation if no root is found. Parameters include observer angle $ ... | def impact_parameter(
alpha: npt.NDArray[np.float64],
r_value: float,
theta_0: float,
n: int,
m: float,
objective_func: Optional[Callable] = None,
**root_kwargs
) -> npt.NDArray[np.float64]:
"""Calculate the impact parameter for each value of alpha.
Parameters
----------
alp... |
def lambda_normalized_bolometric_flux() -> Callable[[float, float, float], float]:
"""Generate the normalized bolometric flux function.
See `generate_image` for an example of how to use this.
Returns
-------
Callable[(float, float, float), float]
The returned function takes (1+z, r, M) as ... | The function simulates the bolometric flux of an accretion disk near a black hole by calculating the impact parameter, redshift, and reoriented angles for light rays, using the observer's polar angle, black hole mass, and image order. It returns reoriented angles, impact parameter, redshift, and normalized flux, incorp... | def simulate_flux(
alpha: np.typing.NDArray[float],
r: float,
theta_0: float,
n: int,
m: float,
objective_func: Optional[Callable] = None,
root_kwargs: Optional[Dict[Any, Any]] = None,
) -> Tuple[
np.typing.NDArray[float],
np.typing.NDArray[float],
np.typing.NDArray[float],
n... |
def lambda_normalized_bolometric_flux() -> Callable[[float, float, float], float]:
"""Generate the normalized bolometric flux function.
See `generate_image` for an example of how to use this.
Returns
-------
Callable[(float, float, float), float]
The returned function takes (1+z, r, M) as ... | The function `simulate_flux` calculates the observed bolometric flux from an accretion disk near a black hole, considering relativistic effects. It computes the impact parameter $ b $, redshift $ 1+z $, and reorients the polar angle $ \alpha $ for a given observer inclination $ \theta_0 $, black hole mass $ m $, and ra... | def simulate_flux(
alpha: npt.NDArray[np.float64],
r: float,
theta_0: float,
n: int,
m: float,
objective_func: Optional[Callable] = None,
root_kwargs: Optional[Dict[Any, Any]] = None,
) -> Tuple[
npt.NDArray[np.float64],
npt.NDArray[np.float64],
npt.NDArray[np.float64],
npt.N... |
def get_unique_letters(puzzle):
return [i for i in set(''.join(break_puzzle(puzzle))) if i.isalpha()]
def get_valid_permutations(puzzle):
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
letters = get_unique_letters(puzzle)
critical_indices = get_starting_letters(puzzle, letters)
poss_per... | The code solves cryptarithmetic puzzles by mapping unique letters to digits, validating permutations, and displaying solutions if found. It checks for invalid cases (e.g., >10 unique letters), generates possible digit assignments, verifies equation correctness, and outputs valid solutions with letter-digit mappings and... | def solve_puzzle():
user_puzzle = entry_puzzle.get()
letters = get_unique_letters(user_puzzle)
if len(letters) > 10:
messagebox.showerror("Error", "Invalid equation: More than one letter maps to the same digit")
return
solutions = []
for poss in get_valid_permutations(user_puzzle):... |
def run_all(self, solvers, options, load, **kwargs):
merits = np.empty((len(self.problems), len(solvers), self.feature_options["rerun"], self.max_eval))
result = Parallel(n_jobs=1)(self.run_one(problem, solver, k, options[j], load, **kwargs) for problem, (j, solver), k in product(self.problems, enumerat... | The code generates performance and data profiles for multiple solvers across optimization problems. It computes merit function values, determines convergence thresholds using tau parameters, normalizes solver performance relative to the best solver, and plots results. Profiles are saved as PDFs and CSVs, comparing solv... | def generate_profiles(self, solvers, names, options, load, **kwargs):
# Run the computations.
logger = get_logger(__name__)
logger.info(f'Starting the computations with feature="{self.feature}"')
merits = self.run_all(solvers, options, load, **kwargs)
# Constants for the perform... |
def img_to_bit_seq(frame, pt1 = (), pt2 = (), props = PROPS):
'''
Convert black and white color to "0" and "1" respectively.
:param frame: Image.
:type frame: ndarray
:param pt1: vertex of the area bounded by qr codes.
:type pt1: tuple, defaults to ()
:param pt2: vertex of the area bounded ... | The function `recv_frame` receives and processes video frames to decode binary data from QR codes. It waits for a start signal, detects QR codes, handles frame rotations, decodes color sequences into bits, and updates a GUI. It stops upon detecting an end signal, storing decoded bits in a shared variable and displaying... | def recv_frame(fps, is_pilot_bit_found , recver, bit_seq, flag, bit_mess, props = PROPS):
'''
Funtion that received frames from the sender function. It does all the manipulation of the captured iamge
here, such as detecting start and end signals, checking rotations and decoding color codes back to 0 and 1.
... |
def infer_action(Qs, A, B, C, num_actions, policies):
# Initialization of the negative EFE.
neg_G = np.zeros(len(policies))
# Loop over every possible policy and compute EFE of each policy.
for i, policy in enumerate(policies):
neg_G[i] = expected_free_energy(policy, Qs, A, B, C)
... | This code implements active inference by iteratively inferring actions, updating environment states, and refining beliefs (Qs) through Bayesian updates. It generates policies, simulates interactions with an environment, and adjusts the posterior distribution using likelihood and prior estimates, visualizing belief stat... | def active_inference(env, A, B, C, Qs):
# Number of time steps
T = 10
# Length of policies we consider
policy_len = 6
# Generate all possible combinations of policies.
policies = control.construct_policies([B.shape[0]], [env.env.nA], policy_len)
env.reset()
for t in range... |
def is_center(self, x, y):
if (x,y) in self.centers:
return True
else:
return False
def get_color(self, c):
return bcolors.COLORS[self.centers.index(c) % len(bcolors.COLORS)]
def is_horizontal_border(self, x,y):
if x != int(x):
return self.is_horizontal_border(x-0.5, y) or self.is_hori... | This method renders a visual grid representation of a board, displaying cells with optional grid lines, borders, and unknown markers. It iterates over an expanded range to handle border elements, using conditional logic to determine symbols like 'o' for cells, '│', '─', and corners for grid lines, and '?' for unknown c... | def show(self, showgrid=True, showborder=False, showunknown=False):
for i in range(-1, self.board_size*2):
for j in range(-1, self.board_size*2):
if self.is_center(j/2,i/2):
print(f'{self.get_color((j/2,i/2))}o{bcolors.RESET} ', end='')
else:
sign = ' '
if showgr... |
def get_neighbors(self,x,y):
neighbors=set()
check_list = { (x+1, y), (x-1, y), (x, y+1), (x, y-1) }
for xx, yy in check_list:
if self.is_on_board(xx, yy):
neighbors.add((xx,yy))
return neighbors
def get_reachable_and_possible_centers(self,x,y):
reachable = self.get_reachable_centers(x... | This function attempts to connect a galaxy part at (x,y) to a center (c) by identifying valid neighboring positions. If only one valid neighbor exists, it marks the connection and recursively continues. When 'try_hard' is True, it explores multiple paths, checks for consistent solutions, and raises an error if multiple... | def try_to_connect_galaxy(self, x,y,c, try_hard=False):
# tries to connect separated galaxy part on x,y to the center (c), you have to
# be sure they are separated, it's not checked here
# try_hard: in case the center is reachable on multiple pathes
good_neighbors = set()
any_change = False
for ... |
def enumerateStates(self):
""" Enumerates all possible bar states
Internally represents bars as a list with self.cols elements
where the maximum value of each element is self.rows.
Example: on this bar, X's are uneaten squares
-sum the X's to get the bar ID.
X X X 0... | This code initializes a game environment with a grid-based board, tracking game states, possible moves, and statistics. It sets up parameters like grid size, bead constraints, and initializes arrays to track eaten beads, game states, and possible next states. The class also prepares data structures for game progression... | def __init__(self, rows=3, cols=4, bounty=3, maxBeads=3, minBeads=1):
self.rows = rows
self.cols = cols
self.eaten = np.zeros([rows, cols], dtype=int)
self.allStates = self.enumerateStates()
self.finished = False # game over if this is True
self.boxes = self.getBoxes(bou... |
def make_negative_one(matrix_row, idx, size):
value = matrix_row[idx]
if value[0] > 0:
multiplicand = (-1 * value[1], value[0])
else:
multiplicand = (value[1], -1 * value[0])
for col_idx in range(idx + 1):
matrix_row[col_idx] = multiply_fractions(multiplicand, (matrix_row[col_idx... | The function `find_probabilities` computes the probability of reaching a specified end state in a Markov chain represented by a transition matrix. It modifies the matrix using Gaussian elimination-like steps, appending auxiliary values to each row, and iteratively eliminating variables to isolate the probability in the... | def find_probabilities(transition_matrix, end_row_idx):
matrix_copy = [[col_val for col_val in row] for row in transition_matrix]
size = len(matrix_copy)
for i in range(size):
if i == end_row_idx:
matrix_copy[i].append((1, 1))
else:
matrix_copy[i].append((0, 1))
f... |
def add_fractions(a, b):
lcm = find_lcm(a[1], b[1])
a_multiplicand = lcm / a[1]
b_multiplicand = lcm / b[1]
dividend = a[0] * a_multiplicand + b[0] * b_multiplicand
gcd = find_gcd(dividend, lcm)
return dividend / gcd, lcm / gcd
def multiply_fractions(a, b):
dividend = a[0] * b[0]
divisor... | This function calculates the determinant of a square matrix using cofactor expansion along the first row, handling fractional arithmetic with tuples to represent numerators and denominators, ensuring precision without floating-point operations. | def get_determinant(matrix):
if len(matrix) == 1:
return matrix[0][0]
if len(matrix) == 2:
return add_fractions(multiply_fractions(matrix[0][0], matrix[1][1]), multiply_fractions((-1,1), multiply_fractions(matrix[0][1], matrix[1][0])))
determinant = (0, 1)
for col_idx in range(len(matri... |
def add_fractions(a, b):
lcm = find_lcm(a[1], b[1])
a_multiplicand = lcm / a[1]
b_multiplicand = lcm / b[1]
dividend = a[0] * a_multiplicand + b[0] * b_multiplicand
gcd = find_gcd(dividend, lcm)
return dividend / gcd, lcm / gcd
def find_probabilities(transition_matrix, end_row_idx):
matrix_c... | The code calculates the absorption probabilities in a Markov chain with terminal states. It constructs a transition matrix by normalizing non-zero rows and adjusting diagonal entries to account for self-transitions. If the first state is terminal, it returns a predefined output. Otherwise, it computes probabilities of ... | def solution(m):
terminal_states = []
transition_matrix = []
for row_idx, row in enumerate(m):
row_sum = sum(row)
if row_sum == 0:
terminal_states.append(row_idx)
transition_row = []
for col_idx, col in enumerate(row):
if col == 0:
tran... |
def get_sub_matrix(matrix, i, j):
sub_matrix = []
for row in matrix[:i] + matrix[i + 1:]:
sub_matrix_row = []
for num in row[:j] + row[j + 1:]:
sub_matrix_row.append(num)
sub_matrix.append(sub_matrix_row)
return sub_matrix
def get_determinant(matrix):
if len(matrix) =... | This code computes the inverse of a square matrix using the adjugate method. It calculates the cofactor matrix by iterating through each element, generating submatrices, determining their determinants, and applying the sign based on position. The cofactor matrix is transposed, then each element is divided by the determ... | def get_inverse(matrix):
inverse = []
n = len(matrix)
for row in range(n):
numerator_row = []
for column in range(n):
sub_matrix = get_sub_matrix(matrix, row, column)
determinant = get_determinant(sub_matrix)
numerator_row.append(multiply_fractions(((-1)**... |
def find_gcd(a, b):
a = abs(a)
b = abs(b)
if a == 0 or b == 0:
return max(a, b)
else:
if a > b:
return find_gcd(a % b, b)
else:
return find_gcd(a, b % a)
def get_rq(markov, terminal, non_terminal):
r = []
q = []
for row in non_terminal:
... | The code computes the absorption probabilities in an absorbing Markov chain. It identifies terminal (absorbing) and non-terminal (transient) states from the input matrix, constructs a reduced transition matrix, and calculates the probability of reaching each terminal state from non-terminal states. Key steps include fo... | def solution(m):
terminal_states = []
non_terminal_states = []
markov_matrix = []
for row_idx, row in enumerate(m):
row_sum = sum(row)
if row_sum == 0:
terminal_states.append(row_idx)
else:
non_terminal_states.append(row_idx)
markov_row = []
... |
def close_cookies_or_ad():
try:
close_cookies()
except:
try:
close_Ad()
except:
pass
def get_page_source():
close_cookies_or_ad()
result = driver.page_source
soup = to_bs4_object(result)
return soup
def Get_Position_Value(Text_Value, value_address)... | Your return
The function `get_professor_count` scrapes a webpage to extract the number of professors and the university name from a search results header. It closes ads/cookies, retrieves page source, locates the header element, and attempts to parse the professor count and university name. If parsing fails, it defau... | def get_professor_count():
close_cookies_or_ad()
soup = get_page_source()
pagination_header = soup.find('div', class_='SearchResultsPage__SearchResultsPageHeader-vhbycj-3')
try:
professor_count = int(Get_Position_Value(pagination_header, 0))
uni_name = pagination_header.div.h1.span.b.get... |
def get_available_terms_in_model(list):
available = []
for term in list:
if term in embedding_model.vocab:
available.append(term)
return available
def _build_corpus(sentences):
"""Construct corpus from provided sentences.
Parameters
----------
sentences : list of :class:... | The function `summarize` generates a condensed version of input text by selecting the most representative sentences. It processes the text, splits it into sentences, and uses parameters like `ratio` or `word_count` to control summary length. Optional query-based filtering and redundancy removal refine relevance. Output... | def summarize(text, ratio=0.2, word_count=None, query=None, split=False, redundancy_removal=True):
"""Get a summarized version of the given text.
The output summary will consist of the most representative sentences
and will be returned as a string, divided by newlines.
Note
----
The input shou... |
def Ruin(s):
A = [i for i in range(220)]
route_dict = {}
for r in s:
for e in r:
route_dict[e] = s.index(r)
A.remove(e)
l_max = min(L_max, sum(len(r) for r in s)/len(s) - sum([1 if len(r) == 0 else 0 for r in s]))
k_max = (4*c_avarage)/(1 + l_max) - 1
k_s = math.f... | The code implements a simulated annealing algorithm to optimize a solution `s` by iteratively ruining and recreating it. It maintains the best solution `s_best`, adjusts temperature `T` iteratively, and accepts new solutions based on cost reduction and probabilistic thresholds. The function returns the optimal solution... | def local_search(s):
s_best = s_0
T = T_0
for f in range(iterations):
s_ruin = Ruin(copy.deepcopy(s))
s_new = Recreate(s_ruin)
if s_new != -1:
if costTotal(s_new) < costTotal(s) - T * math.log(random.uniform(0, 1)):
s = s_new
if costTotal(s_new... |
def strToDict(str):
paramdict = {}
http_body = ''
params = str[(str.index(']')+2):len(str)-1]
if(FILE_START in params):
http_body = params[params.index(FILE_START)+len(FILE_START):params.index(FILE_END)]
params = params[0:params.index(FILE_START)] + params[params.index(FILE_END)+len(FIL... | The main task of the code is to handle client connections by processing incoming packets. It identifies packet types (SYN/ACK), responds with appropriate packets, decodes ACK payloads, extracts parameters/commands, analyzes them, and sends back results. It manages network communication, error handling, and data process... | def handle_client(conn, data, sender):
msg = ''
print(f"\n[NEW CONNECTION] {sender} connected.")
try:
p = Packet.from_bytes(data)
print("Router: ", sender)
print('Package Type: ' + PACKAGE_TYPE[p.packet_type])
if (PACKAGE_TYPE[p.packet_type] == 'SYN'):
new_packet ... |
def save(self, folder, log_tag):
import os
if not os.path.exists(folder + log_tag):
os.makedirs(folder + log_tag)
th.save(self.policy_net.state_dict(), folder + log_tag + "/policy")
th.save(self.transition_net.state_dict(), folder + log_tag + "/transition")
t... | The main task of the code is to train a multi-agent reinforcement learning model over a specified number of timesteps. It processes observations, beliefs, and actions for each agent, updates the belief network, computes losses, and logs training data. The model periodically saves checkpoints, resets the environment upo... | def learn(self, total_timesteps):
env = self.env
env.reset()
all_losses = pd.DataFrame()
for learning_timestep in tqdm(range(total_timesteps)):
if(learning_timestep % self.args.log_time == 0 and not self.args.compare):
log_tag = "models-" + str(int(learning_... |
def initialize_latex(self):
self.trial_id = self.xml_processor.trial_object['registration_number']
self.add_to_latex("\documentclass[6pt]{article}")
self.add_to_latex("\\usepackage{booktabs}")
self.add_to_latex("\\usepackage{multirow}")
self.add_to_latex("\\usepackage{multicol}")
self.add_to_latex("\\usepac... | The code's main task is to generate a LaTeX document by sequentially initializing the structure, adding sections for populations, outcomes, interventions, arms, arm groups, hypotheses, heterogeneity, and judgment calls, then finalizing the document. It compiles these components into a structured LaTeX format for report... | def generate_latex(self):
self.initialize_latex()
self.add_populations()
self.add_outcomes()
self.add_interventions()
self.add_arms()
self.add_armsgroups()
self.add_hypotheses()
self.add_heterogeneity()
self.add_judgmentcalls()
self.close_latex() |
def get_trial_number_from_trial(trial):
aea_id = trial['RCT_ID']
match = re.search(r"\d+$", aea_id)
if match:
numval = int(match.group())
else:
numval = None
return numval
def get_md5sum(path):
with open(path, "r", encoding='utf-8') as f:
filedata = f.read()
return ha... | The code transforms a trial dictionary into a structured data dictionary for a template. It extracts and formats fields like title, abstract, registration details, intervention dates, topics, and data availability, using helper functions. The output dictionary maps trial data to predefined keys, preparing it for struct... | def templatedct_from_trialdct(trial):
d = {'title': f"<![CDATA[{trial['Title']}]]>",
'abstract': f"<![CDATA[{trial['Abstract']}]]>",
'registration_number': get_trial_number_from_trial(trial),
'registration_date': trial['First registered on'],
'aea_site_data_file': get_md5sum(TRIALSFILE),
'i... |
def get_trial_schema(self,):
self.trial_schema = XMLSchema('rg-schema.xsd')
def get_trial_object(self):
self.trial_object = self.trial_schema.to_dict(self.file_path)
def generate_latex(self):
self.initialize_latex()
self.add_populations()
self.add_outcomes()
self.add_interventions()
self.add_arms()
self... | The code's main task is to process XML data by retrieving trial schema and object information, generate LaTeX code, write it to a file, and convert the LaTeX document into a PDF. This workflow transforms structured data into a formatted PDF document through a series of processing steps. | def run(self):
self.xml_processor.run()
self.get_trial_schema()
self.get_trial_object()
self.generate_latex()
self.write_latex()
self.tex_to_pdf() |
def read_trials(fname='data/trials.csv'):
with open(fname, 'r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
trials = {}
for row in reader:
trials[row['RCT_ID']] = row
return trials
def get_trial_from_number(trials, x):
rct_id = format_trial_id(x)
re... | The main task of the code is to generate a formatted trial template by substituting placeholders with data from a specific trial. It reads trial data, selects a trial via a command-line argument, prepares a template dictionary, applies the template, and outputs the filled result. | def main():
trials = read_trials()
assert len(sys.argv)==2, "Should have exactly one argument"
trialno = int(sys.argv[1])
trial = get_trial_from_number(trials, trialno)
tdct = templatedct_from_trialdct(trial)
t = Template(trial_template)
# print(str(trial))
print(t.safe_substitute(tdct)) |
def convert_key(key: str, key_type: KeyType = KeyType.STRING) -> Optional[bytes]:
"""Convert a key that could be of differents format to a bytes string.
Args:
key (str): The key to transform to bytes string.
key_type (KeyType, optional): The type of the key from which to convert. Defaults to Ke... | (The main task of the code is to decrypt Covenant communication data from a file using an AES key. It reads input files, skips specified packets, identifies encrypted data or base64-encoded payloads, converts the provided key into bytes, and decrypts payloads using the AES key. The function handles different key format... | def decrypt_communication(
file_path: Annotated[
Path,
typer.Option(
"-i",
"--input",
help="Path to the file containing Covenant data traffic.",
exists=True,
file_okay=True,
dir_okay=False,
writable=False,
... |
def get_raw_results(video_path):
frames = []
raw_results = []
count = 0
cap = cv2.VideoCapture(video_path)
frames_count = get_number_of_frames(video_path)
with tqdm(total=frames_count, desc='Reading video') as p_bar:
while (cap.isOpened()):
succ, frame = cap.read()
... | The code processes video data by extracting and refining object detection predictions through confidence maximization, label filling, and smoothing. It generates a refined video output and computes metrics against ground truth data for evaluation. | def create_video(video_path, anomaly_window, bbox_window_size, gt_right_path, gt_left_path):
# Create raw results
frames, raw_results = get_raw_results(video_path)
# Extraction
extracted_results = extract_all_results(raw_results)
# Maximal confidence
max_conf_predictions = deepcopy(extracted_r... |
def getAveDistances(vectors, n):
ave_distances = np.full(n,0.0)
for i in range(n):
dist = 0.0
for j in range(n):
if j!= i:
dist+=distance(vectors[i],vectors[j])
ave_distances[i]=dist/(n-1)
return ave_distances
def findTrueMax(vectors, ave_distances):
m... | The code identifies the most cohesive subset of words (up to 4) from a dictionary of word vectors by iteratively removing the word farthest from the group's average vector. It continues refining this subset until all words are within a threshold distance (0.065) of each other. Finally, it computes an ideal vector as th... | def findIdealVector(dictOfWords):
listOfVectors = list(dictOfWords.items())
maxDistAllowed = 0.065
if len(dictOfWords)>=4:
num_words = 4
else:
num_words = len(dictOfWords)
closest_words = np.full((num_words,1), " "*30) #the closest together words
vectors = np.full((num_words... |
def setVectors(dictOfWords):
for word in dictOfWords.keys():
word_vector = embeddings.get(word)
#parse through data and find the vector for the word
dictOfWords[word] = word_vector
return dictOfWords
def findIdealVector(dictOfWords):
listOfVectors = list(dictOfWords.items())
maxD... | The code processes a dictionary of game words, initializes zero vectors, assigns actual vectors via `setVectors`, computes an ideal vector to represent 'our words', refines it by excluding opposing and assassin words, then outputs a clue, the count of correlated words, and the list of words. | def spymaster(inputDict):
# split the inputted dictionary into the appropriate dictionaries, base vector being 0,0,0,0,...
# format is {"word": vector, "word 2": vector 2, ...}
our_words = {}
their_words = {}
neutral_words = {}
assassin_word = {}
# assign the global all words
board_words... |
def translate_and_reconstruct(nets, args, x_src, y_src, c_src, x_ref, y_ref, c_ref, filename):
N, C, H, W = x_src.size()
s_ref = nets.style_encoder(x_ref, y_ref)
masks = nets.fan.get_heatmap(x_src) if args.w_hpf > 0 else None
x_fake = nets.generator(x_src, s_ref, c_ref, masks=masks)
x_fake_rgb, x_fa... | The function `debug_image` generates diagnostic images for model analysis by performing reference-guided and latent-guided image synthesis, cycle consistency checks, and pivot image creation. It uses input data and neural networks to produce visual outputs saved in the specified directory, including reference-guided re... | def debug_image(nets, args, inputs, step):
x_src, y_src, c_src = inputs.x_src, inputs.y_src, inputs.c_src
x_ref, y_ref, c_ref = inputs.x_ref, inputs.y_ref, inputs.c_ref
device = inputs.x_src.device
N = inputs.x_src.size(0)
# translate and reconstruct (reference-guided)
filename = ospj(args.sam... |
def interpolate(nets, args, x_src, s_prev, s_next):
''' returns T x C x H x W '''
B = x_src.size(0)
frames = []
masks = nets.fan.get_heatmap(x_src) if args.w_hpf > 0 else None
alphas = get_alphas()
for alpha in alphas:
s_ref = torch.lerp(s_prev, s_next, alpha)
x_fake = nets.gene... | The function generates a video by interpolating latent vectors from a styleGAN-like model. It maps random latent codes to style vectors, computes averages, and interpolates between them using a blending factor (psi). Frames are generated by interpolating between consecutive style vectors, creating smooth transitions. T... | def video_latent(nets, args, x_src, y_list, z_list, psi, fname):
latent_dim = z_list[0].size(1)
s_list = []
for i, y_trg in enumerate(y_list):
z_many = torch.randn(10000, latent_dim).to(x_src.device)
y_many = torch.LongTensor(10000).to(x_src.device).fill_(y_trg[0])
s_many = nets.mapp... |
def interpolate(nets, args, x_src, s_prev, s_next):
''' returns T x C x H x W '''
B = x_src.size(0)
frames = []
masks = nets.fan.get_heatmap(x_src) if args.w_hpf > 0 else None
alphas = get_alphas()
for alpha in alphas:
s_ref = torch.lerp(s_prev, s_next, alpha)
x_fake = nets.gene... | This function generates a video by interpolating frames between a source image and reference frames using a style encoder. It processes reference data, interpolates styles, creates frames through sliding and concatenation, appends repeated final frames, and saves the result as a video file. | def video_ref(nets, args, x_src, x_ref, y_ref, fname):
video = []
s_ref = nets.style_encoder(x_ref, y_ref)
s_prev = None
for data_next in tqdm(zip(x_ref, y_ref, s_ref), 'video_ref', len(x_ref)):
x_next, y_next, s_next = [d.unsqueeze(0) for d in data_next]
if s_prev is None:
x... |
def sample_stratified(self, rays_o, ray_start, ray_end, N_samples, is_disparity=False):
"""
Return depths of approximately uniformly spaced samples along rays.
"""
N, M, _ = rays_o.shape
if is_disparity:
depths_coarse = torch.linspace(0, 1,
... | The main task of the code is to perform volume rendering using a neural network with coarse and fine passes. It samples stratified depths along rays, computes color and density values via a decoder, and aggregates results using ray marching. The function returns final RGB colors, depth maps, and accumulated weights for... | def forward(self, features, decoder, rays_o, rays_d, op):
self.plane_axes = self.plane_axes.to(rays_o.device)
depths_coarse = self.sample_stratified(rays_o, op['ray_start'], op['ray_end'],
op['N_samples'],
op['... |
def iterstates(self):
"""
iterate over non-terminal and non-blocking states
"""
for r in range(self.dimensions[0]):
for c in range(self.dimensions[1]):
if (r, c) not in self.traps:
yield r, c
def iteractions(self, state: tuple):
"""... | The method initializes transition probabilities for a Markov Decision Process (MDP) by iterating over all states and actions. For each state-action pair, it generates transition probabilities using the environment's dynamics and sets them in the MDP. This establishes the likelihood of transitioning between states based... | def __init_transition_probabilities(self):
"""
Initialize the transition probabilities of the MDP given the dynamics of the environment.
:return:
"""
for state in self.iterstates():
for action in self.iteractions(state):
transition_probs = self.__gener... |
def playing_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT: #Quitting
self.running = False
# User clicks
if event.type == pygame.MOUSEBUTTONDOWN:
selected = self.mouseOnGrid()
... | This code defines a game loop that runs while 'self.running' is True. When the game state is "playing", it processes events, updates game logic, renders visuals, and retrieves puzzle data from the provided 'board'. The loop exits when 'self.running' becomes False, then quits Pygame and exits the program. | def run(self, board):
# print(board)
# self.getBoard(board)
while self.running:
if self.state == "playing":
self.playing_events()
self.playing_update()
self.playing_draw()
self.getPuzzle(board)
pygame.quit()
... |
def _generate_timestamps_range(curve: Curve, range_in_minutes: int = MINUTES_IN_A_WEEK) -> list[float]:
start_datetime = datetime.combine(curve.week_start, datetime.min.time())
end_datetime = start_datetime + timedelta(minutes=range_in_minutes)
return [
start_datetime.timestamp() + i * 60 for i in r... | The function calculates a Quality of Service (QoS) metric by integrating the product of interpolated availability ratios and cumulative consumption profiles over time. It first generates a timestamp range, computes availability ratios from inventory curves, calculates cumulative consumption from the consumption profile... | def _calculate_qos_metric(inventory_curves: list[Curve], consumption_profile_curves: list[Curve]) -> float:
timestamps_range = _generate_timestamps_range(inventory_curves[0])
availability_ratios = _calculate_availability(inventory_curves, timestamps_range)
consumption_profile_curve = consumption_profile_cur... |
def load_data(index_name):
curPath = os.path.abspath(os.path.dirname(__file__))
name = '/Indices data/' + index_name + '.csv'
Path = os.path.abspath(curPath + name)
data = pd.read_csv(Path)
data_idx = data.set_index(["Date"], drop=True)
date = data_idx.index
close_index = data_idx['Close']
... | The code performs time series prediction using a trained model. It loads financial index data, trains a model, normalizes the data, generates predictions, and plots the original vs. predicted values for comparison. | def plot_origin_predict(index_name):
close_index, date = load_data(index_name)
model, device = train_model(close_index, index_name)
all_test_data, norm = normalize(close_index.values)
all_test_data, _ = create_dataset(all_test_data)
result = []
for data in all_test_data:
model.eval()
... |
def load_data(index_name):
curPath = os.path.abspath(os.path.dirname(__file__))
name = '/Indices data/' + index_name + '.csv'
Path = os.path.abspath(curPath + name)
data = pd.read_csv(Path)
data_idx = data.set_index(["Date"], drop=True)
date = data_idx.index
close_index = data_idx['Close']
... | The main task of the code is to load financial data for a given index, train a predictive model on its closing prices, use the last five data points to generate a prediction, and return the forecasted result. The process involves data loading, model training, and prediction using the trained model on recent data to est... | def main(index_name):
close_index, date = load_data(index_name)
model, device = train_model(close_index, index_name)
predict_data = (close_index.values)[-5:]
predict_result = predict(predict_data, date, model, device)
return predict_result |
def is_service_configured(self):
"""Return whether the etcd service has been configured or not.
It may happen that a pod gets recreated and handling certain events should not be
done until pebble is ready. This method allows checking this dynamically rather than
relying on stored state.... | The method `_process_clustering` checks if the service is configured, sets up clustering parameters, and ensures the etcd service is started or restarted if required, maintaining proper clustering functionality. | def _process_clustering(self):
if not self.is_service_configured():
return
self.configure_clustering()
if self._etcd_needs_start():
self._maybe_restart_etcd() |
def is_service_configured(self):
"""Return whether the etcd service has been configured or not.
It may happen that a pod gets recreated and handling certain events should not be
done until pebble is ready. This method allows checking this dynamically rather than
relying on stored state.... | The code handles pod recreation by re-rendering config files to update listen URLs when storage is lost. It checks if the service is configured, applies config changes, and processes clustering to ensure correct setup post-recreation. | def _on_start(self, event):
# If a pod gets recreated, the storage used for rending a config file will be
# gone so we need to re-render the config to change listen URLs.
if self.is_service_configured():
self._apply_config_change()
self._process_clustering() |
def winLose(otherPiece):
#if king dies
popup = tkin.Tk()
popup.geometry("1000x800")
popup.wm_title("You WIN!!!")
label = tkin.Label(popup, font=("Helvetica", 100))
if otherPiece.color == "b":
#white wins
msg = "White Wins!!"
... | This function handles moving a chess piece on a board, updating UI elements, managing captures, promotions, and turn transitions. It de-highlights previous selections, updates board positions, swaps or captures pieces, handles pawn promotion, and triggers the next player's turn by calling `pickPiece` with the appropria... | def doMove(event,origSquare,possibleMoves):
print("DOMOVE")
#Canvases
newSquare = event.widget
origSquare = origSquare
print(origSquare)
print(newSquare)
#indexes
oldIndex = board.index(origSquare)
newIndex = board.index(newSquare)
#obj... |
def convert_state_to_tensor(self, state):
char_list = [float(char) for char in state]
return T.tensor(char_list)
def set_td_error(self, prev_state, state, reward):
self.td_error = self.calculate_target(state, reward) - self.forward(prev_state)
def calculate_loss(self):
return self.td_error ** 2 | The code propagates updates to a neural network using temporal difference (TD) learning. It converts input states to tensors, computes the TD error, calculates the loss, performs backpropagation, and updates the network's parameters via the optimizer. This process adjusts the model to minimize prediction errors based o... | def propagate(self, prev_state, current_state, reward):
prev_state = self.convert_state_to_tensor(prev_state)
current_state = self.convert_state_to_tensor(current_state)
self.set_td_error(prev_state, current_state,reward)
loss = self.calculate_loss()
loss.backward()
self.network.optimizer.step() |
def refreshPict(opt,val):
writeToMeta_P(opt,val)
getFromMeta()
resetScreen(False)
def customPictChanging(col1,col2,col3,opt):
pygame.draw.rect(screen,col1,[190,200,770,350])
pygame.draw.rect(screen,col3,[190,200,770,350],3)
pygame.draw.rect(screen,col3,[230,300,700,200])
noteTitle = WriteBo... | This function handles image changes based on user input. It updates background or sidebar images when options 4/5 are selected and a left-click occurs, using global variables. If a custom image is chosen, it triggers a custom change function and sets a flag. If no custom image is selected, it resets the screen. | def pictureChanging(opt): #changing events
global backgroundPict,sideBarPict,customPictChoose
if opt == 4:
for x in pos:
if event.button == 1 and x:
refreshPict(opt,backgrounds[pos.index(x)])
if opt == 5:
for x in pos:
if event.button == 1 and x:
... |
def setAlarmAddNoteDraw():
global setAlarmSetDateDayChoosing,setAlarmSetDateMonthChoosing
pygame.draw.rect(screen,col3,[160,250,250,300])
goBackButtonRect = pygame.draw.rect(screen,col2,[360,199,50,50],3)
goBackButtonX = WriteRegular(30,"X",col2,[385,227])
screen.blit(goBackButtonX.writeText,goBack... | This code handles alarm settings by processing button actions for date selection, note addition, and sound toggling. It validates the chosen date, schedules the alarm using system tasks, and writes metadata to files. If the date is invalid, it displays an error; otherwise, it confirms the alarm setup with visual feedba... | def setAlarmButtonAction():
global setAlarmSetDate, finalTime, wake_nr, setAlarmIt
global setAlarmSetDateDayChoosing,setAlarmSetDateMonthChoosing, setAlarmSetDateToday
global setDateDay,setDateMonth
global addNoteEvents,noteText,noteTextList
... |
def remove_symbol(self, part: Union[Head, Tail]):
if type(part) == Head:
symbols = self.game_board[self.head.y][self.head.x]
if 'H' in symbols:
symbols.remove('H')
if type(part) == Tail:
symbols = self.game_board[part.y][part.x]
if part.nam... | This code moves an object's head upward by a specified number of steps, updating its position and ensuring it doesn't move beyond the top boundary. For each step, it removes the old head symbol, adjusts the position, adds the new head symbol, and updates the tail segments. | def move_up(self, moves: int = 1):
for i in range(moves):
if self.head.y > 0:
self.remove_symbol(self.head)
self.head.y -= 1
self.set_symbol(self.head)
for tail in self.tails:
self.update_tails() |
def remove_symbol(self, part: Union[Head, Tail]):
if type(part) == Head:
symbols = self.game_board[self.head.y][self.head.x]
if 'H' in symbols:
symbols.remove('H')
if type(part) == Tail:
symbols = self.game_board[part.y][part.x]
if part.nam... | This function moves the head of a snake-like object down by a specified number of steps. It checks if the head's vertical position is within bounds, then updates its position and redraws the symbol. After each move, it updates the tail positions to maintain the snake's structure. | def move_down(self, moves: int = 1):
for i in range(moves):
if self.head.y < self.height - 1:
self.remove_symbol(self.head)
self.head.y += 1
self.set_symbol(self.head)
self.update_tails() |
def remove_symbol(self, part: Union[Head, Tail]):
if type(part) == Head:
symbols = self.game_board[self.head.y][self.head.x]
if 'H' in symbols:
symbols.remove('H')
if type(part) == Tail:
symbols = self.game_board[part.y][part.x]
if part.nam... | The main task of the code is to move an entity's head left by a specified number of steps, updating its position on a grid. For each move, it checks if the head can move left (x > 0), removes the current symbol, updates the head's x-coordinate, redraws the symbol at the new position, and adjusts the tails. This handles... | def move_left(self, moves: int = 1):
for i in range(moves):
if self.head.x > 0:
self.remove_symbol(self.head)
self.head.x -= 1
self.set_symbol(self.head)
self.update_tails() |
def remove_symbol(self, part: Union[Head, Tail]):
if type(part) == Head:
symbols = self.game_board[self.head.y][self.head.x]
if 'H' in symbols:
symbols.remove('H')
if type(part) == Tail:
symbols = self.game_board[part.y][part.x]
if part.nam... | This function moves an object's head right by 'moves' steps, updating its position and tails within bounds. It removes the current head symbol, increments its x-coordinate, adds the new symbol, and updates trailing parts, ensuring movement stays within the defined width. | def move_right(self, moves: int = 1):
for i in range(moves):
if self.head.x < self.width:
self.remove_symbol(self.head)
self.head.x += 1
self.set_symbol(self.head)
self.update_tails() |
def get_scenario(scen_nm,obj):
'''Allow for either dictionary or HXD object'''
try:
return [scen for scen in obj if scen["resultSetTypeNm"] == scen_nm][0]
except:
return [scen for scen in obj if scen.resultSetTypeNm == scen_nm][0]
def calculate_metrics(source_str):
'''
Calculates Met... | The function `set_scenario_fields` calculates metrics, change amounts, and change percentages for each scenario (excluding 'expiring') in a rate walk. It retrieves rating results for 'expiring' and 'quote' scenarios, filters scenarios to include 'rate' and other scenarios, then iterates through each, comparing them to ... | def set_scenario_fields(scenarios,rw,rw_compare):
'''Calculates the metrics for each scenario of the rate walk'''
# Set paths
rw_exp = get_scenario(scen_nm="expiring",obj=rw).ratingResult
rw_qte = get_scenario(scen_nm="quote",obj=rw).ratingResult
# Remove expiring from scenarios
scen_subse... |
def get_scenario(scen_nm,obj):
'''Allow for either dictionary or HXD object'''
try:
return [scen for scen in obj if scen["resultSetTypeNm"] == scen_nm][0]
except:
return [scen for scen in obj if scen.resultSetTypeNm == scen_nm][0]
def calculate_metrics(source_str):
'''
Calculates Met... | The function `rate_walk` calculates rate walks for multiple insurance scenarios by comparing each scenario's rating results against predefined reference scenarios (e.g., "expiring" or "quote"). It sets up scenario-specific metrics, maps comparisons using `rw_compare`, computes metrics for the "expiring" scenario, appli... | def rate_walk(rw,scenarios: str):
"""Calculate rate walk for all scenarios"""
# Set paths
rw_exp = get_scenario(scen_nm="expiring",obj=rw).ratingResult
rw_qte = get_scenario(scen_nm="quote",obj=rw).ratingResult
# Scenario mappings - what to compare each scenario to
rw_compare = {
"rene... |
def solve_representer_proxy(self, K, y, lmbda, weights=1.):
m = K.shape[1]
# initialize the representer coefficients
alpha = torch.randn(size=[m, self.out_dim], requires_grad=True)
alpha.data *= 0.01
loss = np.inf
while loss > self.div_tol:
def closure():
... | This code performs iterative data point selection by computing influence measures using kernel methods and gradient-based optimization. It removes the least influential samples based on hyperparameters (nu, mu) and returns the chosen indices along with influence statistics. The process involves kernel matrix computatio... | def select(self, X, y, m, kernel_fn_np, lmbda=1e-4, mu=0., nu=0., inc_weight=1.):
n = X.shape[0]
chosen_indexes = np.arange(n)
X = X.numpy()
K = torch.from_numpy(kernel_fn_np(X, X)).float()
outer_weights = torch.ones([n])
outer_weights[m:] = inc_weight
weights =... |
def search_walmart(key, query, category_id=None, facet=False, brand=None, price_range=None,num_items='10'):
'''
Query the Walmart Search API, returning results in json.
Parameters:
key (str) - required: your API key
query (str) - required: your query (e.g. ipod)
category_id (str) -... | This function queries Walmart's Search API with a product description and API key to predict the most common product sub-category from search results. It handles misspellings by refining the query and extracts taxonomy paths from responses, returning the dominant category prediction. | def predict_sub_category(vendor_description_clean, key, category_id = '1229749'):
'''
Query Walmart's Search API, returning most common product taxonomy of the
search results.
Parameters:
vendor_description_clean (str): the product description from that should
... |
def get_training_data(sampleNum=5):
'''read in the training data and take a random sample of it that respects
the sub_category balance.
'''
train_df = data().get_data_not_yet_predicted()
print(len(train_df.index),' rows still left to predict')
try:
train_df = remove_previous_predictions(... | The main task of the code is to process training data by querying an API for predictions, applying correction rules to refine results, comparing outputs with labeled data, appending previous predictions, and saving the updated dataset. It retrieves data, maps predictions, enforces rules, validates against existing labe... | def main(sample=200):
'''
main function
1. gets data saved in folder
2. calls api and maps predictions
3. applies rules that are common mistakes the api makes and corrects them
4. compares results to previously labeled data
5. appends predictions to previously predicted data
6. sav... |
def valid_move(self,state,column):
return state[0][column]==0
def next_open_row(self,state,column):
for r in reversed(range(state.shape[0])):
if state[r][column]==0:
return r
else:
continue
def is_gameover(self,state,row,column,piece):
... | The code determines the optimal move for a non-human player in a turn-based game using different AI strategies (Random, Minimax, Simplemax). It evaluates potential moves by simulating game states, applying depth-specific evaluation matrices, and selecting the best column based on the highest calculated value. If multip... | def determine_preference(self):
if self.playerlist[self.turn].model=='Human':
return
if self.playerlist[self.turn].depth==1:
minimatrix = [2, 49, 198, 1000]
elif self.playerlist[self.turn].depth==3:
minimatrix = [20, 160, 241, 999]
elif self... |
def fitStoichiometric(x,y, thr=1.0):
f,ferror = SGTEfit(SGTE2, x, y)
if ferror > thr:
f,ferror = SGTEfit(SGTE3, x, y)
if ferror > thr:
f,ferror = SGTEfit(SGTE4, x, y)
if ferror > thr:
f,ferror = SGTEfit(SGTE5, x, y)
if ferror > thr:
f,ferror = SGTEfit(SGTE6, x, y)
return f,ferror
def outexpr... | The function `proStoichiometricG` fits stoichiometric thermodynamic data to derive expressions for Gibbs energy (G), enthalpy (H), entropy (S), and heat capacity (Cp) as functions of temperature. It retrieves temperature and Gibbs energy data, adjusts for reference enthalpy (H298), and performs a fit on a subset of dat... | def proStoichiometricG():
#try:
x = zthermo.get("temperature (K)")
y = zthermo.get("Gibbs energy (eV/atom)")
H298 = threcord.get("H298.15 (J/mol-atom)")
x = np.array(list(map(float, x)))
y = np.array(list(map(float, y)))*eVtoJ - H298
i0 = 0
for i,T in enumerate(x):
... |
def fitStoichiometricCp(x,y, thr=0.001):
f,ferror = CSGTEfit(SGTEC2, x, y)
#if ferror > thr:
# f,ferror = CSGTEfit(SGTEC2, x, y)
if ferror > thr:
f,ferror = CSGTEfit(SGTEC3, x, y)
if ferror > thr:
f,ferror = CSGTEfit(SGTEC4, x, y)
return f,ferror
def fitStoichiometricH(x,y,c):
zz = H_SGTE(x,c)
... | The function fits stoichiometric thermodynamic data (Cp, H, S) to temperature-dependent curves, calculates polynomial coefficients with errors, constructs Gibbs free energy expressions, and stores fitted results in a dictionary. It processes input data, performs regression, derives thermodynamic equations, and returns ... | def proStoichiometricCp():
#try:
uncertanty = {}
x = zthermo.get("temperature (K)")
y = zthermo.get("Cp (J/mol-atom/K)")
H298 = threcord.get("H298.15 (J/mol-atom)")
x = np.array(list(map(float, x)))
y = np.array(list(map(float, y)))
i0 = 0
for i,T in enumerate(x):
... |
def thermoplot(folder,thermodynamicproperty,x,y,yzero=None,fitted=None,xT=None,xlabel="T (k)"):
cwd = os.getcwd()
os.chdir( folder )
plt.rc('font', size=24)
fig,ax=plt.subplots()
fig.set_size_inches(12,9)
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.set_xlim... | The main task of the code is to process thermodynamic data from a file, calculate key properties (e.g., Gibbs energy, enthalpy, entropy) at 298 K using spline interpolation, filter data up to melting temperature or specific heat limits, generate plots of thermodynamic properties, fit an equation of state (e.g., Morse) ... | def Genergy(thermofile,dir0):
tmelt = 9999.
ele = threcord.get("Elements")
if len(ele)==1:
tmelt = ELEMENTS[ele[0]].tmelt
folder = dir0+'/'+"figures"
if not os.path.exists(folder):
os.mkdir(folder)
thermo = np.loadtxt(thermofile, comments="#", dtype=np.float)
thermo[np.isnan(thermo)] = 0.0
for... |
def jitter_cam_lights(self):
''' Adds jitter (random location change) to the camera and lights for
lighting and camera diversity between scenes
'''
def rand(L):
return 2.0 * L * (random.random() - 0.5)
# Add random jitter to camera position
if self.args.came... | The main task of the code is to render a 3D scene with randomized objects, compute spatial/directional relationships between objects, and save the rendered image along with a structured JSON description of the scene, including object metadata and relationships. The function initializes rendering settings, adds random o... | def render_scene(self,
output_index=0,
output_split='none',
output_image='render.png',
output_scene='render_json',
output_blendfile=None
):
# Initialize the settings for scene rendering
... |
def optimally_contain(parent_obj: BpyObj, child_obj: BpyObj, direction: str = 'left') -> None:
''' Wrapper for optimally contain so that an output .blender file is saved on
an assertion error for debugging purposes
'''
try:
val = real_optimally_contain(parent_obj, child_obj, direction)
excep... | This function generates 3D matrices for "can contain" and "can support" relationships between object triples by evaluating geometric compatibility using preloaded 2D relationship matrices. It iterates through all object combinations, checks containment/support feasibility, assigns 0 (impossible), 1 (possible), or -1 (u... | def pregenerate_predicates(shapes: list, con_path: str, sup_path: str, save_uncertain_scenes: bool) -> Tuple[np.ndarray, np.ndarray]:
''' Iterates through every possible combination of 3 objects, filling the "can
contain" and "can support" relationship matrices with values to indicate the
possibility of th... |
def get_shapes(properties_json: str) -> list:
''' Loads the list of shapes from the JSON properties file and returns the
list of shape names from that file
- properties_json: the path to the properties JSON file
- returns: list of shape names
'''
with open(properties_json, 'r') as f:
pro... | The code processes a Blender scene by loading a base file, generating interaction matrices (containment/support) between 3D shapes, saving these matrices to files, and updating a JSON configuration with their file paths. It checks for existing files to avoid overwriting, generates data if missing, and outputs the resul... | def main(args):
bpy.ops.wm.open_mainfile(filepath=args.base_scene_blendfile)
save_file_template = '%s_rels_%%s' % args.set_name
save_file_template = os.path.join(args.save_directory, save_file_template)
file_endings = ['contain_dou.dat', 'support_dou.dat', 'contain_tri.npy', 'support_tri.npy']
save_... |
def get_knowledge_graph_from_chunk(
chunk: Document,
llm: ChatOpenAI,
allowed_nodes: list[str] | None = None,
allowed_rels: list[str] | None = None,
verbose: bool = False,
) -> KnowledgeGraph:
"""Runs the LLM function to extract a Knowledge Graph from a document chunk."""
return get_extract... | The function creates a GraphDocument by converting an Obsidian note into a knowledge graph. It loads file data, generates nodes/relationships from document chunks using an LLM, links chunks to notes/vaults, and embeds chunk information. The output includes vault-note, note-chunk, and chunk-node relationships with embed... | def create_graph_document_from_note(
file_name: str,
llm: ChatOpenAI,
allowed_nodes: list[str] | None = None,
allowed_rels: list[str] | None = None,
verbose: bool = False,
) -> GraphDocument:
file_store = file_handling.load_file_store()
if file_store is None:
print("Failed to retrie... |
def validate_ship_size(initial_position, final_position, len):
pos_x_init, pos_x_final = int(initial_position[1:]) - 1, int(final_position[1:]) - 1
pos_y_init, pos_y_final = get_row(initial_position), get_row(final_position)
if pos_x_init == pos_x_final:
if pos_y_final - pos_y_init == len - 1:
... | The code's main task is to allow a user to place ships on a game board by inputting initial and final positions for each ship type (porta aviones, acorazado, crucero, submarino, destructor). It validates the ship's size and position, saves valid positions, and updates the board. Each ship has a specific length (5, 4, 3... | def set_ships(self):
print("Seleccionar posicion inicial para el porta aviones (5 casillas): ")
initial_position = input("Posicion inicial (Ej: A7): ")
print("Seleccionar posicion final: ")
final_position = input("Posicion final: ")
if validate_ship_size(initial_position, final_p... |
def sprinkledb_connect():
global mydb
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="sprinkle"
)
def start_pump():
print("Starting pump")
# Opening Pump
pump = 'Pump'
GPIO.setup((9, led), GPIO.OUT)
GPIO.output((... | The main task of the code is to control sprinklers based on configurations stored in a database. It connects to the database, retrieves sprinkler settings (name and runtime), activates each sprinkler using specified GPIO pins, runs them for their configured duration, and then stops them. The pump is started before oper... | def sprinkle_all():
led = 27
# pins on rpi. 10 is reserved for the pump
pin = ['14', '5', '23', '12', '3', '2', '17']
# time to sleep between operations in the main loop
sprinkledb_connect()
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM sprinkle_config")
myresult = mycursor.fe... |
def sprinkledb_connect():
global mydb
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="sprinkle"
)
def stop_sprinkle(gpioID):
print("Stopping sprinkle %s" % gpioID)
sprinkle_report_stop(gpioID)
GPIO.output(int(gpioID), GP... | The main task of the code is to control a specific irrigation valve via GPIO by checking its current state, updating the database with runtime logs if stopped, and triggering either start or stop actions. It interacts with a database to fetch valve configurations, logs manual operation timestamps, and manages hardware ... | def open_one_valve(gpioID):
print("Opening one valve only: %s" % gpioID)
sprinkledb_connect()
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM sprinkle_config WHERE gpioID = %s" % gpioID)
myresult = mycursor.fetchone()
fields = {myresult[0]: [myresult[1], myresult[2]]}
sprinkle_name... |
def five_to_four(self, message):
"""Decodes bits from 4/5b coding."""
res = ''
for i in range(0, len(message), 5):
tmp = message[i:i + 5]
res = res + self.decoding_table[tmp]
return ''.join(res)
def get_destination(self, message):
"""Returns destination fr... | This code parses a structured message into its components: destination, source, length, payload, and hash. It processes the input message by slicing and extracting each field sequentially, converting data formats where needed, and verifies the hash integrity. | def __init__(self, message, with_preamble):
if with_preamble:
message = message[8 * 8:]
self.data = []
message = self.five_to_four(message)
self.destination = self.get_destination(message)
self.data += message[:6 * 8]
message = message[6 * 8:]
self.... |
def defineterritory(self):
for self.i in range (0, 9):
for self.j in range (0, 9):
self.blackboard[self.i][self.j][1][0] = 0
self.whiteboard[self.i][self.j][1][0] = 0
self.blackboard[self.i][self.j][2][0] = self.i
self.blackboard[self.i... | The main task of the code is to update the board state with a player's move, check for suicide (invalid capture) or repetition (previous state), and return True if the move is invalid due to either condition, otherwise False. | def updateboard(self, x, y, btn):
self.board[x][y] = btn.turn
self.defineterritory()
self.suicide = self.capture(x, y, btn)
self.repeat = self.checkrepetition(x, y, btn)
if self.suicide or self.repeat:
return True
else:
return False |
def new_id(self):
with Controller.from_port(port=self.tor_cport) as controller:
controller.authenticate(password=self.password)
controller.signal(Signal.NEWNYM)
self.logger.info(
f"TOR cport auth: {controller.is_authenticated()}. TOR NEW IDENTITY. Sleep 3 sec.... | The code tests TOR proxy functionality by generating a new ID, verifying request headers, checking IP address consistency across 20 single-threaded requests, and testing multithreaded IP retrieval (40 requests). It uses IP API endpoints to validate proxy anonymity, counts result frequencies, and ensures TOR's ability t... | def test(self):
print("\n******************TOR NEW ID test******************\n")
self.new_id()
print("\n******************HEADERS test******************\n")
check_anything = self.get("https://httpbin.org/anything")
print(check_anything.text)
print("\n******************O... |
def W_prime_particle(self):
'''
Total energy in electrons and protons:
'''
return self.xi*self.W_prime_e()
def W_prime_B(self):
'''
Comoving energy in the magnetic field
'''
return (self.V_prime_blob()*self.U_B).to("erg")
def R_prime_blob(self):
''... | The function calculates the total power of a relativistic jet in the stationary frame of the galaxy. It computes the sum of contributions from particles and magnetic fields (Wtot), then multiplies by the blob's cross-sectional area, squared luminosity function, beta factor, speed of light, and normalizes by the blob's ... | def Pj(self):
'''
Total power jet in the stationary frame (i.e. the frame of the galaxy)
'''
Wtot = self.W_prime_particle() + self.W_prime_B()
return 2*np.pi*pow(self.R_prime_blob(),2.)*self.beta*pow(self.LF,2.)*c_cgs*(Wtot/self.V_prime_blob()) |
def RatioMagneticFields(self):
'''
'''
return self.e_B/self.e_B_min()
def Pj(self):
'''
Total power jet in the stationary frame (i.e. the frame of the galaxy)
'''
Wtot = self.W_prime_particle() + self.W_prime_B()
return 2*np.pi*pow(self.R_prime_blob(),2.)*... | The code formats and prints a table row containing a model name and computed physical parameters, including tvar, Doppler shift, magnetic field strength, magnetic field ratio, jet power, luminosity ratios, and blob radius. Values are formatted with specific decimal places and scientific notation to align columns neatly... | def printTable(self, model_name):
print("{}\t\t{:.0f}\t\t{:.0f}\t{:.2f}\t{:.2f}\t{:.2f}\t\t{:.0f}\t\t{:.2f}\t\t{:.2e}\t\t{:.2f}".format(model_name, self.tvar.value, self.doppler, self.B.value*1e3, self.RatioMagneticFields(),self.Pj()/1e46 ,self.JetPowerRatio(), self.TotalLuminosity()/1e42, self.TotalLuminosity(... |
def prepare_data_label_for_forward(data, target, device, bce_use, survival=False):
if survival==True:
assert(target.shape[1]==2)
if bce_use==True:
target=target.to(torch.float)
else:
target=target.squeeze(-1)
data, target = data.to(device), target.to(device)
return data, targ... | The function processes one training or evaluation epoch for a machine learning model. It handles data loading, model forward/backward passes, loss/metric computation, learning rate scheduling, and optional inference. It supports BCE loss, survival analysis, and metrics aggregation, returning model states, epoch loss/me... | def on_one_epoch(epoch, data_loader, model, device, num_classes, bce_use,
learning_rate, optimizer, metric_used, \
loss_fn=None,
class_weights=None, scheduler=None,
lr_adjuster_on_val=None, lr_div_factor=None, \
survival=False, one_cycle_... |
def set_enumerable(self, data_loader):
if self.use_progbar == True:
return tqdm(data_loader, total=len(data_loader), position=0, leave=True)
else:
return data_loader
def on_batch_begin(self):
pass
def prepare_data_label_for_forward(self, data, target):
'''Input: d... | This method processes an epoch of data, computes loss/metrics, handles training/evaluation modes, and returns aggregated loss, metric, and prediction/target lists. It initializes enumerables, manages batch processing, applies data preparation, forwards/backwards passes, learning rate scheduling, and metric accumulation... | def on_one_epoch(self, epoch, data_loader, train, inference_on_holdout):
'''Input: epoch, data_loader, train status, inference_on_holdout status
Output: loss_epoch, metric_epoch, pred_list[1:], target_list[1:]
Hooks available:
on_epoch_begin, on_epoch_end,'''
enumerable=self.set... |
def on_train_epoch_begin(self):
pass
def on_one_epoch(self, epoch, data_loader, train, inference_on_holdout):
'''Input: epoch, data_loader, train status, inference_on_holdout status
Output: loss_epoch, metric_epoch, pred_list[1:], target_list[1:]
Hooks available:
on_epoch_begin, ... | This method trains the model for one epoch using the provided data loader, tracks the epoch's loss and metrics, appends them to lists for monitoring, and triggers epoch-specific start/end hooks. It executes training steps, updates internal metrics, and prints training summaries at the epoch's conclusion. | def on_one_train_epoch(self, epoch, data_loader):
'''Input: epoch, data_loader
Output: loss, metric, predictions list, target list'''
self.on_train_epoch_begin()
loss_epoch, metric_epoch, \
_, _ = self.on_one_epoch(
epoch=epoch,
... |
def on_valid_epoch_begin(self):
pass
def on_one_epoch(self, epoch, data_loader, train, inference_on_holdout):
'''Input: epoch, data_loader, train status, inference_on_holdout status
Output: loss_epoch, metric_epoch, pred_list[1:], target_list[1:]
Hooks available:
on_epoch_begin, ... | This method processes a single validation epoch by computing loss and metrics on the provided data loader, appending results to validation tracking lists, and invoking lifecycle callbacks for validation epoch start and end. It executes inference without training, stores metrics, and logs results. | def on_one_valid_epoch(self, epoch, data_loader):
'''Input: epoch, data_loader
Output: loss, metric, predictions list, target list'''
self.on_valid_epoch_begin()
loss_epoch, metric_epoch, \
_, _ = self.on_one_epoch(
epoch=epoch,
... |
def on_test_begin(self):
pass
def on_one_epoch(self, epoch, data_loader, train, inference_on_holdout):
'''Input: epoch, data_loader, train status, inference_on_holdout status
Output: loss_epoch, metric_epoch, pred_list[1:], target_list[1:]
Hooks available:
on_epoch_begin, on_epoc... | This function processes a single test epoch by evaluating the model on the provided data loader. It computes loss and metrics, stores them in lists, and appends predictions/targets. The process begins with `on_test_begin`, executes evaluation via `on_one_epoch` (with inference mode), logs results, and concludes with `o... | def on_one_test_epoch(self, epoch, data_loader):
'''Input: epoch, data_loader
Output: loss, metric, predictions list, target list'''
self.on_test_begin()
loss_epoch, metric_epoch, \
self.pred_test_list, self.target_test_list = self.on_one_epoch(
... |
def on_epoch_begin(self):
pass
def on_one_train_epoch(self, epoch, data_loader):
'''Input: epoch, data_loader
Output: loss, metric, predictions list, target list'''
self.on_train_epoch_begin()
loss_epoch, metric_epoch, \
_, _ = self.on_one_epoch(
... | This method trains and validates a model for a specified number of epochs, using hooks for customization. It initializes FP16 scaling if enabled, processes training data, validates if a loader exists, adjusts learning rates, saves progress periodically, and tests if a test_loader is provided. It tracks losses and metri... | def fit(self, epochs):
'''Runs training and validation loop for epochs, then tests, if test_loader
is available.
Hooks available:
on_one_epoch,
on_one_train_epoch,
on_one_valid_epoch,
one_one_test_epoch,
on_train_epoch_begin, on_train_epoch_end
on_... |
def _step_safety_checker(
self,
batch_size: int,
queries: List[torch.LongTensor],
responses: List[torch.LongTensor],
scores: List[torch.FloatTensor],
masks: Optional[List[torch.LongTensor]] = None,
):
"""s
Check if the input data is valid for training.... | This function performs a Proximal Policy Optimization (PPO) training step using query-response pairs and rewards. It processes inputs, scales/clips rewards, computes log probabilities and rewards via model forward passes, trains the model in mini-batches, updates the policy, and returns training statistics including KL... | def step(
self,
queries: List[torch.LongTensor],
responses: List[torch.LongTensor],
scores: List[torch.FloatTensor],
response_masks: Optional[List[torch.LongTensor]] = None,
):
"""
Run a PPO optimisation step given a list of queries, model responses, and rewar... |
def check_size(rank, size, edge_cnt, local_edge_cnt, remain):
"""
check if the size of processors can split the edges
:param rank: the rank of processor
:param size: the size of processors
:param edge_cnt: the number of edges
:param local_edge_cnt: the number of edges in each processor's local_... | The code implements a parallel Minimum Spanning Tree (MST) algorithm using MPI. It distributes edge data across processors, with each handling a subset of edges. The Boruvka algorithm is executed in parallel, and the MST is constructed on rank 0. The task involves reading input data, scattering edges, and measuring exe... | def main():
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
# Each processor read the vertices and edges count form the first line of a csv file
input_file = sys.argv[1]
f = open(input_file, "r")
first_line = f.readline().replace('\n', '').split(' ')
vertices_cnt = i... |
def strategy_0(self, hand, table, start):
hand_indices = np.where(hand>0.5)[0]
np.random.shuffle(hand_indices)
k = 0
while not self.check_legal(hand_indices[k], hand, table, start):
k = k+1
l = hand_indices[k]
return l
def check_legal(self, card, hand, table, ... | The code implements a strategy function for a card game, selecting moves based on the 'strat' parameter. It handles three strategies: strat 0 uses a basic method, strat 1 calculates optimal moves via scoring and legal checks, and 'input' mode lets users choose cards. The function returns the next legal move, considerin... | def strategy(self, node=None, card=None, **kwargs):
#print('strat: ', self.strat)
strat = self.strat
if strat==0:
hand = kwargs['hand']
table= kwargs['table']
start= kwargs['start']
return self.strategy_0(hand, table, start)
elif strat==1:
... |
def initialize(self, player=0):
pygame.init()
self.screen = pygame.display.set_mode(self.size)
self.bg = self.pilImageToSurface(self.handler.current_table)
#pygame.event.get()
self.screen.fill((0,0,0))
self.update_window()
def generate_guesses(self):
for i in rang... | The code simulates a game where players make guesses, play rounds, and compute scores based on guess accuracy versus actual tricks. It initializes game state, iterates through rounds to determine winners, updates scores using a formula involving guess-trick differences, and returns aggregated player scores as a formatt... | def play_hand(self, scores):
if self.prints:
print('start is in game: ', self.start)
self.initialize()
self.generate_guesses()
while self.num_rounds < self.n:
winner = self.play_round()
if self.prints:
print('table: ', dec_table(self.t... |
def select(self,node):
'''select a path that get to a leaf node based on uct values '''
path = []
while True:
path.append(node)
if node not in self.children or not self.children[node]:
return path
unexplored = self.children[node] - self.childr... | This code performs a single Monte Carlo Tree Search (MCTS) simulation: it selects a path from the given node, expands the terminal leaf node, simulates a game outcome from that node, and backpropagates the reward along the path to update the tree. The process includes tracking comparison counts during node selection an... | def rollout(self,node):
'''do one simulation and get one more node of the tree'''
self.num_comparison = 0
path = self.select(node)
# print("Number of explored depth: ",len(path))
# print("Num_of_comparison of uct values: ",self.num_comparison)
leaf = path[-1]
self... |
def is_eye(self,i, j, piece_type):
interesting_pos=self.detect_neighbor(i,j)+self.detect_diagonal(i,j)
for pos in interesting_pos:
if self.board[pos[0]][pos[1]]!= piece_type:
return False
return True
def detect_neighbor(self, i, j):
'''
Detect all the ... | The code calculates a score for a given piece type on a board by evaluating eyes (surrounded empty spaces) and liberties (adjacent empty spaces). It counts eyes, assigns weights based on liberty counts, and accumulates a score using factors and weights. The result combines eye contributions (with multipliers) and liber... | def advanced_score(self, piece_type):
visited=set()
eyes_info = {}
board = self.board
cnt = 0
factor = 1
if piece_type == 2:
factor = 1.0
for i in range(self.size):
for j in range(self.size):
if board[i][j]==0 and self.is_e... |
def is_eye(self,i, j, piece_type):
neighbor = self.detect_neighbor(i, j)
diagonal = self.detect_diagonal(i,j)
if self.at_edge(i,j):
for pos in neighbor:
if self.board[pos[0]][pos[1]] != piece_type:
return False
for pos in diagonal:
... | This code evaluates the strength of a player's pieces on a Go board by analyzing eyes (surrounded empty spaces), liberties (available moves), and positional advantages. It counts stones sharing multiple eyes, applies weighted values based on liberties, and adjusts scores for corner/edge positions. The result is a compo... | def advanced_evaluation(self,piece_type):
visited = set()
eyes_info = {}
board = self.board
cnt = 0
factor = 1
if piece_type == 2:
factor = 1.0
for i in range(self.size):
for j in range(self.size):
if board[i][j] == 0 and s... |
def valid_place_check(self, i, j, piece_type, test_check=False):
'''
Check whether a placement is valid.
:param i: row number of the board.
:param j: column number of the board.
:param piece_type: 1(white piece) or 2(black piece).
:param test_check: boolean if it's a tes... | This function places a chess piece on the board if valid, updates the game state, removes captured pieces of the opponent, and increments move count. It returns True for valid placements or False if invalid, triggering a board fill with the opponent's pieces and ending the game. | def place_chess(self, i, j, piece_type):
'''
Place a chess stone in the board.
:param i: row number of the board.
:param j: column number of the board.
:param piece_type: 1('X') or 2('O').
:return: boolean indicating whether the placement is valid.
'''
#... |
def seq_eight_bits(texte):
binary_seq =binary_huffman(texte)
added_0 = 0
while len(binary_seq) % 8 != 0:
binary_seq += '0'
added_0 +=1
#print('8 bits binary sequence: \n' + binary_seq)
return binary_seq, added_0
def seq_unicode(texte):
eight_bits, _ = seq_eight_bits(texte)
u... | The code performs Huffman compression on input text by generating 8-bit sequences, Unicode encryption, a Huffman code dictionary, and an additional component. It processes the text to prepare data structures for compression, returning encrypted data, auxiliary information, and the Huffman encoding for efficient data re... | def huffman_compression(texte):
eight_bits, _ = seq_eight_bits(texte)
cryption = seq_unicode(texte)
_,addition = seq_eight_bits(texte)
code = dico_huffman(texte)
return cryption,addition,code,eight_bits |
def is_vpn_has_status(vpn_name, status):
return status == utils.execute_cmd('networksetup -showpppoestatus "{}"'.format(vpn_name))
def connect(vpn_name):
utils.display_notification(vpn_name, 'Connecting 🐾 🚀')
connect_vpn(vpn_name)
if utils.wait_until_condition(lambda: is_vpn_has_status(vpn_name, VPN... | This function manages a VPN connection based on user activity and internet status. It connects/reconnects when the user is active and internet is available, disconnects when the user is inactive, and notifies of interruptions due to lost connectivity. It maintains the connection state, ensures proper handling of transi... | def enable_vpn(is_vpn_enabled, set_running_state, vpn_name, user_name):
set_running_state(True)
connection_established = False
interruption_detected = False
while is_vpn_enabled():
internet_connected = utils.is_internet_connected()
# connects to the VPN, for the current user
if... |
def handle_vpn_threads_async(self):
thread = threading.Thread(target=lambda: self.handle_vpn_threads(),
daemon=True)
thread.start()
def handle_auto_connecting_vpn_async(self):
thread = threading.Thread(target=lambda: self.handle_auto_connecting_vpn(),
... | The code's main task is to manage a VPN application by handling threads, auto-connecting VPNs, managing existing connections, adjusting network preferences, and initiating the application. It orchestrates asynchronous operations for VPN thread management, automatic connection logic, connected state handling, and networ... | def run(self):
self.handle_vpn_threads_async()
self.handle_auto_connecting_vpn_async()
self.handle_already_connected_vpn_async()
self.handle_network_preferences_async()
self.app.run() |
def Euclidean(vec1, vec2) :
return math.sqrt(sum(math.pow((v1-v2),2) for v1,v2 in zip(vec1, vec2)))
def Magnitude_Difference(vec1, vec2) :
return abs(VectorSize(vec1) - VectorSize(vec2))
def Theta(vec1, vec2) :
return math.acos(Cosine(vec1,vec2)) + math.radians(10) | The function calculates a value based on the Euclidean distance, magnitude difference, and angle between two vectors, combining them in a formula involving π and converting the angle from degrees to a fraction of a circle. | def Sector(vec1, vec2) :
ED = Euclidean(vec1, vec2)
MD = Magnitude_Difference(vec1, vec2)
theta = Theta(vec1, vec2)
return math.pi * math.pow((ED+MD),2) * theta/360 |
def add_spaces(reaction):
"""
Args:
reaction (str) - reaction of any formatting
Returns (str):
reaction with no added spacings
Example:
>>>add_spaces("[Cr(N2H4CO)6]4[Cr(CN)6]3(S)+MnO4^-(AQ)+H2O=Cr2O7^2-(AQ)+CO2(G)+NO3^-(AQ)+Mn^2+(AQ)+H^+")
'[Cr(N2H4CO)6]4[Cr... | The code formats an unformatted chemical reaction string into LaTeX notation, properly capitalizing elements, adding subscripts/superscripts for charges and quantities, separating states of matter, and ensuring correct spacing and arrow placement. It processes input like "cr7n66h96c42o24+mno4^-+h2o=>cr2o7^2-+mn^2++co2+... | def format_full_reaction(reaction):
"""
Args:
reaction (str) - unformatted reaction
Returns (str):
Latex formatted reaction - with
Example:
>>>format_full_reaction("cr7n66h96c42o24+mno4^-+h2o=>cr2o7^2-+mn^2++co2+no3^-+h3o^+")
'Cr_{7}N_{66}H_{96}C_{42}O_... |
def init_chat(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM )
svr = SERVER if self.args.d == None else (self.args.d, CHAT_PORT)
self.socket.connect(svr)
self.sm = csm.ClientSM(self.socket)
def output(self):
if len(self.system_msg) > 0:
print(se... | The main task of the code is to manage a chat session by initializing the chat, authenticating the user, displaying a welcome message, and maintaining an active session. It processes and outputs messages in a loop, periodically refreshing online user lists, and terminates when the system state becomes offline. The func... | def run_chat(self): #run on the thread mainloop
self.init_chat()
#self.system_msg += 'Welcome to ICS chat\n'
#self.system_msg += 'Please enter your name: '
self.output()
while self.login() != True: #try to login if the state is offline
self.output()
self.syste... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.