dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _build_encoder(self):
encoder_input=self._add_encoder_input()
conv_layers=self._add_conv_layers(encoder_input)
bottleneck=self._add_bottleneck(conv_layers)
self._model_input=encoder_input
self.encoder=Model(encoder_input,bottleneck,name="encoder")
def _build_decoder(self):
... | The code defines a `_build` method that constructs an autoencoder by sequentially building its encoder, decoder, and the autoencoder itself. The primary task is to initialize the model's architecture, enabling it to learn efficient data representations through encoding and decoding processes. | def _build(self):
self._build_encoder()
self._build_decoder()
self._build_autoencoder() |
def getAvgPosition(self):
avgX=0;
avgY=0;
i=0;
while(i<self.currentIndex):
tmpSamp=self.currentSamples[i];
avgX=avgX+tmpSamp[0];
avgY=avgY+tmpSamp[1];
i=i+1;
avgX=avgX/(self.currentIndex);
avgY=avgY/(self.curren... | The code's main task is to compute the average position using `getAvgPosition()`, reset internal state with `zeroize()`, log the result for debugging, and return the computed average value. | def consume(self):
ret = self.getAvgPosition();
self.zeroize();
self.debugLvl(1, "avgSamp: ", ret);
return ret; |
def debugLvl(self, lvl, *args):
if(lvl <= self.dbgLvl):
print(args);
def test(self, tp):
# test against minZ in the push() function so we can differentiate between
# fails due to minZ and fails due to x/y proximity
#if(tp[2] < self.minZ):
# return False;
#e... | This function processes a touchpoint (tp) by validating it against minimum Z-value (minZ) and proximity constraints. If valid, it stores the TP in a buffer; otherwise, it resets the buffer. It returns True when enough consecutive valid samples are collected, False otherwise. | def push(self, tp):
if(tp):
if(self.currentIndex>=self.consecutiveSamps):
return True; # exit early if we've already collected enough data
# valid tp tuple; test minZ
if(tp[2]>=self.minZ):
self.debugLvl(1, "RX TP: ", tp);
... |
def get_user_profile( # noqa: CCR001
request: http.HttpRequest, param: str
) -> models.Profile:
if param == "self":
upk = request.user.id
try:
uprof = models.Profile.objects.get(user_id=upk) # type: ignore
except ObjectDoesNotExist:
from django.contrib.auth impo... | The function retrieves the current student's data based on request parameters and context. It determines the user profile using 'self' or 'path' logic, checks if the user is a student, and constructs the student data either independently or within a classroom context, returning it as a dictionary or None if invalid. | def get_current_student(
request: http.HttpRequest, classroom: Optional[models.ClassRoom], par: str
) -> Optional[dict]:
param: str = "self" if (classroom or par == "self") else "path"
user_profile = get_user_profile(request, param)
if user_profile.role != "student":
return None
if not cla... |
def generate_vectors_by_similarity(rs, n, s):
# generate vector 1
u1 = normed_uniform(rs, n)
# generate a vector orthogonal to v1
u1_ = normed_uniform(rs, n)
u1_ = normalize(u1_ - u1 * np.dot(u1, u1_))
# generate vector 2
u2 = u1 * s + u1_ * (1 - s)
return u1, u2
def find_offset(rs, logits, event_rate, step... | This function generates synthetic patient data with controlled event rates and feature correlations. It creates n_patients with n_features, computes event probabilities using similarity-adjusted coefficients, and generates binary events (e1,e2) with specified rates. It also calculates diagnostic statistics like event r... | def generate_data_linear(
n_patients, n_features, event_rate, similarity,
random_seed=RANDOM_SEED, step_size=STEP_SIZE,
print_output=PRINT_OUTPUT, plot=PLOT
):
rs = np.random.RandomState(random_seed)
# generate n_features-dimensional feature vector for n_patients
x = rs.randn(n_patients, n_features)
# gene... |
def getEdges(geno_idx, num_rows, num_cols):
"""
Gets all edges from a given chromosome index. Excludes edge to itself.
Returns list of all pixels reachable from itself.
Returns: [(r1, c1), ..., (rn, cn)]
"""
edges = [
get_neighbor_from_dir(geno_idx, d, num_rows, num_cols) for d in range(... | The function generates a minimum spanning tree (MST) using Prim's algorithm starting from a random pixel in a 2D grid. It encodes the MST as a genotype (list of integers) for genetic algorithms, where each entry indicates the parent node in the tree. After constructing the MST, it replaces the `num_segments` most expen... | def mst(arr, num_rows, num_cols, num_segments=0):
"""
Generates a minimum spanning tree from a randomized starting location
Returns mst encoded as a genotype for GA chromosome
Returns: [int]
"""
num_pixels = num_rows * num_cols
genotype = [i for i in range(num_pixels)]
visited = set()
... |
def get_neighbours_from_other_segment(segments, num_rows, num_cols, origin):
"""
Gets the neighbors of a pixel, if the neighbor belongs to a different segment
than the pixel.
Returns: [int] where list can be empty
"""
neighbors = [
arr_idx_to_genotype_idx(get_neighbor_from_dir(origin, d,... | The function calculates the total edge value of an image by summing the Euclidean distances between neighboring pixels belonging to different segments. It iterates over each pixel, identifies adjacent pixels in other segments, computes their RGB Euclidean distance, and accumulates the total. This measures dissimilarity... | def edge_value(pixel_arr, segments, num_rows, num_cols):
"""
Calculates total edge value for the entire image, which is the
total euclidean distance between all neighboring pixels belonging
to different segments:
Returns: Float
"""
tot_dist = 0
for i in range(len(segments)):
# G... |
def mst(arr, num_rows, num_cols, num_segments=0):
"""
Generates a minimum spanning tree from a randomized starting location
Returns mst encoded as a genotype for GA chromosome
Returns: [int]
"""
num_pixels = num_rows * num_cols
genotype = [i for i in range(num_pixels)]
visited = set()
... | The code processes an image by repeatedly applying segmentation and analysis functions (mst, find_segments, edge_value, connectivity, overall_deviation) in a loop, measuring execution time and outputting metrics like edge values, connectivity, and deviation. The image is modified with specific pixel values during each ... | def main():
arr = load_image("training_images/86016/Test image.jpg")
print(arr.shape)
start_time = time.time()
for i in range(100):
c = mst(arr, arr.shape[0], arr.shape[1])
c[12000] = 12000
c[10000] = 10000
c[4500] = 4500
s = np.array(find_segments(c))
e ... |
def supported_types(self) -> list:
""" The source types supported with this module"""
return ['pickle', "csv", "parquet", "json"]
def _load_df_from_csv_in_mc(self, mc_key: str, **pandas_options) -> pd.DataFrame:
if not self.exists():
return pd.DataFrame()
content = self._down... | The main task of the code is to load a canonical dataset from a specified source using the ConnectorContract, inferring or validating the file type, processing parameters, ensuring thread safety via a lock, and returning the dataset as a DataFrame, dict, or GzipFile based on the file type. It handles multiple formats l... | def load_canonical(self) -> Union[pd.DataFrame, dict, GzipFile]:
""" returns the canonical dataset based on the connector contract. This method utilises the pandas
'pd.read_' methods and directly passes the kwargs to these methods.
Extra Parameters in the ConnectorContract kwargs:
- ... |
def lookahead_is(self, *tpe) -> bool:
return self._lookahead and self._lookahead.type in tpe
def any_range(self):
self._eat('ANY')
if self.lookahead_is('UNISCALAR'):
return self.uniscalar_values()
elif self.lookahead_is('KEYWORD'):
return self.keyword()
def betwee... | This function determines the appropriate range-handling method based on the current lookahead token. It checks for tokens like 'ANY', 'BETWEEN', 'UNICODE', etc., and delegates to corresponding methods like any_range(), between_range(), or unicode_range(). If no specific token matches, it defaults to calling self.keywor... | def range_expression(self):
if self.lookahead_is('ANY'):
return self.any_range()
if self.lookahead_is('BETWEEN'):
return self.between_range()
if self.lookahead_is('UNICODE'):
return self.unicode_range()
if self.lookahead_is('DIGIT'):
return... |
def alternation(self) -> str:
self._eat('ALTERNATION')
return '|'
def concatenation(self) -> str:
self._eat('CONCATENATION')
return ','
def nonterminal(self) -> str:
value = ''
match self._lookahead.type:
case 'CATEGORY':
value = self.category(... | This method parses expressions by checking the type of the lookahead token. If the token is 'ALTERNATION' or 'CONCATENATION', it delegates to respective parsing functions. For 'STRING', 'CATEGORY', or 'CODE' types, it calls the nonterminal() method, returning the parsed result as a string. | def statement(self) -> str:
match self._lookahead.type:
case 'ALTERNATION':
return self.alternation()
case 'CONCATENATION':
return self.concatenation()
case 'STRING' | 'CATEGORY' | 'CODE':
return self.nonterminal() |
def lookahead_is(self, *tpe) -> bool:
return self._lookahead and self._lookahead.type in tpe
def _eat(self, token_type: str):
token = self._lookahead
if token is None:
raise SyntaxError(f'Unexpected end of input, expected: {token_type}')
if token_type != token.type:
... | The code parses comma-separated expressions, handling 'OR' to build alternatives. It collects range expressions into 'alternations' and returns a choice structure combining the initial 'left' value with these alternatives, or just 'left' if no alternations exist. | def comma_expression(self, left):
alternations = []
while self.lookahead_is('COMMA', 'OR'):
if self.lookahead_is('COMMA'):
self._eat('COMMA')
if self.lookahead_is('OR'):
self._eat('OR')
alternations.append(self.range_expression())
... |
def name(self) -> str:
name = self._eat('NAME')
value = decamelize(camelize(name))
return value
def assignment(self) -> str:
self._eat('ARROW')
return '='
def statement_list(self, stop_lookahead=None) -> str:
statement_list = [self.statement()]
while self._lookahe... | The code defines a method `definition` that constructs and returns a string by concatenating the results of three instance methods: `name()`, `assignment()`, and `statement_list()`, followed by a semicolon. Its main task is to generate a formatted string representing a code element or declaration, likely for syntax gen... | def definition(self) -> str:
"""
# Main entry point.
#
"""
return f'{self.name()} {self.assignment()} {self.statement_list()} ;' |
def writeSLHABlocks(blocks, precision=8):
"""Return an SLHA definition as a string, from the supplied blocks dict."""
if not blocks:
return ""
sep = 3 * " "
blockstrs = []
for bname, b in blocks.items():
namestr = b.name
if b.q is not None:
namestr += " Q= " + _au... | The function `writeSLHA` generates an SLHA (Standard Les Houches Accord) formatted string from a provided `doc` object. It combines content from three components—blocks, decays, and xsections—using specified precision and handling options. Non-empty parts are joined with double newlines, producing a structured SLHA def... | def writeSLHA(doc, ignorenobr=False, precision=8):
"""Return an SLHA definition as a string, from the supplied Doc."""
ss = [x for x in (writeSLHABlocks(doc.blocks, precision), writeSLHADecays(doc.decays, ignorenobr, precision), writeSLHAXSections(doc.xsections, precision)) if x]
return "\n\n".join(ss) |
def get_role_dedicated_groups():
role_groups_dict = dict()
# team level groups
role_groups_dict = add_role_groups(role_groups_dict, 'Nexus Lead', f'cgm-{TEAM_KEY_PLACEHOLDER}-product-owner')
role_groups_dict = add_role_groups(role_groups_dict, 'Product Owner', f'cgm-{TEAM_KEY_PLACEHOLDER}-product-owner'... | The main task of the code is to map users (devstack_ids) to their assigned groups based on roles, teams, and placeholders (ART/SOLUTION/TEAM_KEY). It processes affiliations, replaces placeholders with actual values using mappings, and builds two dictionaries: (1) groups to their members and (2) members to their groups.... | def get_working_directories():
role_dedicated_groups = get_role_dedicated_groups()
affiliations = get_affiliations_dict(load_prev_result=False)
team_mapping = get_team_mapping()
result_group_members = dict()
result_member_groups = dict()
for affiliation in affiliations.values():
devsta... |
def load_opened_bugs(self):
self.opened_bugs = self.search(created=True, sprint=False, reporter="currentUser()", issue_type='Bug').json()["issues"]
def load_done_tickets(self):
self.done_tickets = self.search(status="Done", status_changed=True).json()["issues"]
def load_ready_for_testing(self):
... | The main task of the code is to load various types of issues or tickets by calling four methods: loading opened bugs, completed tickets, issues ready for testing, and testing-related data. This likely aggregates or initializes different categories of issues for tracking or processing in a system, ensuring all relevant ... | def load_issues(self):
self.load_opened_bugs()
self.load_done_tickets()
self.load_ready_for_testing()
self.load_testing() |
def new_task(self):
# information
self._is_started = False
self.n_frames = 0
self.output = None
def new_line(self):
self.line = bytes(self.line_bytes).decode("utf-8")
self.line_bytes = bytearray()
return self.line
def process_line(self, line: str):
# print... | This code runs a Blender render process in a subprocess, monitors its output line by line, handles interactive prompts (e.g., "[y/N]"), updates a task's progress, and manages graceful shutdowns or errors. It executes a render script on a Blender project, processes real-time output, and returns True on successful comple... | def run(self) -> bool:
self.new_task()
# * run in subprocess and iter each line of output
args = [
self.blender_cmd,
"--background",
os.path.join(_DIR, "blender_project", "render_flame.blend"),
"--python",
os.path.join(_DIR, "blender_p... |
def __request_type(self):
return self.request['requestType'] if 'requestType' in self.request else 'json';
def __data(self):
if 'body' in self.request:
return self.request['body']
return None
def __json(self):
if self.__is_json_request() and self.__data() != None:
... | This function generates the appropriate body content for a cURL request based on the request type. It handles 'urlencoded' data by encoding it, 'text' data by converting it to a string, and JSON data by serializing it. If the request type is 'form', it returns a placeholder message indicating form data is not yet suppo... | def __curl_body(self):
type = self.__request_type()
if type == 'form':
return 'CURL FORM DATA NOT SUPPORT YET'
elif type == 'urlencoded':
data = self.__data()
return data if isinstance(data, str) else urlencode(data)
elif type == 'text':
da... |
def __body_str(self):
b_json = self.__json()
if b_json != None:
return json.dumps(b_json, indent=2)
b_data = self.__data()
if b_data == None:
return None;
if isinstance(b_data, str):
return json.dumps(b_data, indent=2)
return b_data
def... | The code logs HTTP request details with colored formatting: it prints the request method, URL, headers (as JSON), and body, highlighting JSON data. It enhances readability for debugging by using colors and structured output. | def __log_request(self):
cprint(' REQUEST ', 'black', 'on_blue')
data = self.__body_str()
print(colored(self.__method().upper(), 'blue', attrs=['bold']), colored(self.__url(), attrs=['bold']))
print(colored('Request Headers ', 'magenta', attrs=['bold']), '\n', json.dumps(self.__headers... |
def __headers(self):
headers = self.request['headers'] if 'headers' in self.request else {}
if 'Content-Type' not in self.request:
headers['Content-Type'] = self.__content_type()
if('basicAuth' in self.request):
headers['authorization'] = self.__basic_auth()
retur... | This function generates and prints a formatted cURL command string using the object's method, URL, headers, and body data. It constructs the command with proper line breaks, escaping, and includes headers (-H) and data (-d) if present, ending with -kv for verbose output. | def print_curl(self):
H = '-H ' if self.__headers() != None else ''
H += '\n-H '.join(["'{0}: {1}' \\".format(x, self.__headers()[x]) for x in self.__headers()])
data = self.__curl_body()
D = ("-d '" + data + "'") if data != None else ''
print('curl -X ', self.__method().upper(),... |
def __log_request(self):
cprint(' REQUEST ', 'black', 'on_blue')
data = self.__body_str()
print(colored(self.__method().upper(), 'blue', attrs=['bold']), colored(self.__url(), attrs=['bold']))
print(colored('Request Headers ', 'magenta', attrs=['bold']), '\n', json.dumps(self.__headers... | The code's main task is to execute an HTTP request by logging the request, preparing data/JSON payloads based on request type, sending the request, validating the response, logging results, and handling exceptions by marking the response as failed, displaying error messages in red, and terminating the process. | def execute(self):
self.__log_request()
try:
data = self.__data() if not self.__is_json_request() else None
json = self.__json() if self.__is_json_request() else None
self.response = self.__send_request(self.__method(), self.__url(), data, json, se... |
def mk_folders_frame(container):
frame = ttk.Frame(container)
frame.columnconfigure(0, weight=2)
frame.columnconfigure(0, weight=6)
frame.columnconfigure(0, weight=1)
#Input folder
ttk.Label(frame, text='Input folder: ').grid(column=0, row=0, sticky=tk.W)
iFol_entry = ttk.Entry(frame,n... | The code creates a GUI application using Tkinter, setting up a non-resizable window titled 'Extractor'. It organizes the interface with multiple frames for managing folders, options, video settings, and a bottom panel. Widgets like labels, checkboxes, and input fields are added, with some disabled post-creation. The la... | def Main():
# root window
root = tk.Tk()
root.title('Extractor')
root.geometry('400x351')
root.resizable(0, 0)
root.attributes('-toolwindow', True)
# layout on the root window
root.columnconfigure(0, weight=4)
#root.columnconfigure(1, weight=4)
folders_frame = mk_folders_... |
def get_hs_descriptor(self, domain: str):
self.logger.info(f"Fetching descriptor for {domain}")
controller = stem.control.Controller(self.control_socket)
controller.authenticate(self.control_password)
desc = controller.get_hidden_service_descriptor(domain, timeout=30)
if not desc... | The code generates a report for an onion domain by validating its format, extracting the raw onion identifier, retrieving hidden service descriptors, testing open ports (HTTP/HTTPS), and collecting HTTP headers, TLS, and Apache mod_status data, then compiling these into a structured Report object with relevant findings... | def run_report(self, domain: str):
if not domain.endswith(".onion"):
raise ValueError("Not an onion domain")
raw_onion = domain.removesuffix(".onion").rsplit(".", 1)
if len(raw_onion) == 2:
raw_onion = raw_onion[1]
else:
raw_onion = raw_onion[0]
... |
def gameOver(self, winner):
print('%s won the game' % winner.playerName)
self.displayHand(winner)
def displayInfo(self):
pass
def displayHand(self, player):
print(len(player.singles), len(player.jokers))
cards = player.getCardList()
a = decorate(cards)
print(a)
d... | This code manages a turn-based card game where players draw, play, and drop cards. It initializes a deck, distributes cards to players, handles human and computer turns, checks for wins, and updates the game state. The human player interacts via input to pick/draw cards, while computer players automatically play. The l... | def gamePlay(self):
self.deck = card.Deck()
self.deck.shuffle()
self.hands = self.deck.distribute(self.no_of_players, self.no_of_cards)
for hand in self.hands:
hand.checkForJokers()
self.name = input('Enter your name ? ')
self.hands[0].playerName = self.name
... |
def constructVariableArray(board):
result = []
totalRows = len(board)
domain = [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9]
for row in range(totalRows):
variableRowList = []
for column in range(10):
if (board[row][column] != -1):
value = board[row][column]
variable = Variable("Row|Column {}|{}".... | The main task of the code is to construct a Constraint Satisfaction Problem (CSP) model for a Tenner Grid puzzle. It creates variables for each cell in the grid, assigning domains based on pre-set values or allowing 0-9 for empty cells. The model enforces binary constraints to ensure no duplicate values in rows and col... | def tenner_csp_model_1(initial_tenner_board):
'''Return a CSP object representing a Tenner Grid CSP problem along
with an array of variables for the problem. That is return
tenner_csp, variable_array
where tenner_csp is a csp representing tenner grid using model_1
and variable_array i... |
def constructVariableArray(board):
result = []
totalRows = len(board)
domain = [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9]
for row in range(totalRows):
variableRowList = []
for column in range(10):
if (board[row][column] != -1):
value = board[row][column]
variable = Variable("Row|Column {}|{}".... | The function `tenner_csp_model_2` constructs a Constraint Satisfaction Problem (CSP) for the Tenner Grid puzzle using model_2. It creates variables for each cell, with domains based on the input board (0-9 for empty cells, fixed values otherwise). The CSP includes **all-different constraints** for each row, **sum const... | def tenner_csp_model_2(initial_tenner_board):
'''Return a CSP object representing a Tenner Grid CSP problem along
with an array of variables for the problem. That is return
tenner_csp, variable_array
where tenner_csp is a csp representing tenner using model_1
and variable_array is a l... |
def find(screenshot, folderName):
# dictionary for digits grouped by "y"
found = dict()
filePath = folderName + '/{}.png'
# find all digits
for digit in range(10):
positions = pyautogui.locateAll(filePath.format(digit), screenshot, True,confidence = 0.9)
for x,y... | The main task of the code is to determine whether to flip a coin or guess the outcome (heads/tails) in a game based on current scores, remaining flips, and a probability matrix. It uses screenshots to read game data, checks for inconsistencies, handles game-over states, and applies a strategy matrix to decide actions, ... | def decideFlipOrGuess(count):
global global_heads
global global_tails
global currentScore
headsScoreImg = pyautogui.screenshot(region = (1042,427,88,30))
tailsScoreImg = pyautogui.screenshot(region = (1025,467,88,30))
flipsLeftImg = pyautogui.screenshot(region = (1000,800,120,45))
scor... |
def load_Courtois():
r"""This function returns the Courtois Markov chain transition matrix."""
mP = np.array([[.85, 0, .149, .0009, 0, .00005, 0, .00005],
[.1, .65, .249, 0, .0009, .00005, 0, .00005],
[.1, .8, .0996, .0003, 0, 0, .0001, 0],
[0, .0004,... | This function computes the modified resolvent approximation for Kemeny constant derivatives. It calculates matrices mQ_1 and mQ_2 from input transition matrix mP (or loaded Courtois data) and derived matrices mG_alpha/mH_alpha. The resulting mQ matrix is used to compute directional derivatives in all state pairs, retur... | def calc_Kemeny_derivatives(mP = None, alpha = 10**(-6),
mG_alpha = None, mH_alpha = None):
r"""This function calculates the modified resolvent approximation
for the Kemeny constant derivatives. Optionally, one can insert the
matrices for mG_alpha and mH_alpha. """
if mP is ... |
def condition_A(self):
"""Returns bool whether condition A is True or False. """
nrInCO_A = int(self.get_nr_in_brackets(self.CO_A))
if self.CO_A[:6] == 'CO_A_1':
return self.iterCounter < nrInCO_A
elif self.CO_A[:6] == 'CO_A_2':
return self.MC.nEc < nrInCO_A
... | The main task of the code is to apply the KDA (K-cut Decomposition Algorithm) by iteratively cutting graph edges based on conditions A and B. It selects edges using different strategies depending on the CO_B parameter: CO_B_1 cuts edges via connectivity threshold, CO_B_3 cuts edges below a threshold, and defaults to an... | def apply_KDA(self):
"""Applies KDA with conditions A and B. """
self.iterCounter = 0 # of the outer while loop of KDA
while self.condition_A():
# start a new cutting "iteration"
if self.CO_B[:6] == 'CO_B_1':
# find edges to cut
e = se... |
def load_Courtois():
r"""This function returns the Courtois Markov chain transition matrix."""
mP = np.array([[.85, 0, .149, .0009, 0, .00005, 0, .00005],
[.1, .65, .249, 0, .0009, .00005, 0, .00005],
[.1, .8, .0996, .0003, 0, 0, .0001, 0],
[0, .0004,... | The function calculates the mean first passage matrix of a given transition matrix mP by combining the identity matrix, deviation matrix, ergodic projection, and diagonal operations. It uses matrix inversion and multiplication to derive the result, defaulting to a predefined matrix if none is provided. | def calc_mean_first_pass(mP = None):
r"""This function calculates the mean first passage matrix of mP."""
if mP is None:
mP = load_Courtois()
# init
n = len(mP)
mI = np.eye(n)
mPiP = calc_ergodic_proj(mP)
D_P = calc_deviation_matrix(mP)
dg_D_P = np.diag(np.diag(D_P))
dg_mPi... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-o", "--output-dir", help="output directory to use", default="."
)
parser.add_argument(
"action",
choices=["collect", "clean"],
help="Action to perform",
default="collect",
nargs="?... | The main task of the code is to execute either data collection or cleaning operations based on the specified action ("collect" or "clean"), using the provided output directory. The `main` function parses command-line arguments, determines the action, and invokes the corresponding function (`collect` or `clean`) with th... | def main(output_dir="."):
args = parse_args()
if args.action == "collect":
collect(output_dir=args.output_dir)
elif args.action == "clean":
clean(output_dir=args.output_dir) |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-o", "--output-dir", help="output directory to use", default="."
)
parser.add_argument(
"action",
choices=["collect", "clean"],
help="Action to perform",
default="collect",
nargs="?... | The main task of the code is to execute actions based on command-line arguments. It parses input parameters, checks if the specified action is "collect" or "clean", and invokes the corresponding function (`collect` or `clean`) with the provided output directory path. The code serves as a controller to trigger data coll... | def main():
args = parse_args()
if args.action == "collect":
collect(output_dir=args.output_dir)
elif args.action == "clean":
clean(output_dir=args.output_dir) |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-o", "--output-dir", help="output directory to use", default="."
)
parser.add_argument(
"action",
choices=["collect", "clean"],
help="Action to perform",
default="collect",
nargs="?... | The main task of the code is to execute either "collect" or "clean" operations based on the command-line argument `args.action`, directing results to a specified output directory. The function parses arguments, then conditionally invokes `collect()` or `clean()` with the provided output path, enabling flexible data pro... | def main(output_dir="."):
args = parse_args()
if args.action == "collect":
collect(output_dir=args.output_dir)
elif args.action == "clean":
clean(output_dir=args.output_dir) |
def roulette_wheel(collection, fitness, topn):
total_fit = float(sum(fitness))
relative_fitness = [f / total_fit for f in fitness]
dictionary = dict(zip(range(0,20),relative_fitness))
dictionary = dict(sorted(dictionary.items(), key=lambda x: (-x[1], x[0])))
chosen = []
while len(chosen) in ra... | The function evolves a collection of rulesets using genetic algorithms by selecting top-performing rulesets, generating new ones, applying crossover and mutation operations, and combining them to form the next generation. It returns the updated collection for the next iteration. | def evolve(collection, rule_choices, fitness, crossover_pct, mutation_pct):
# Select best two rulesets from last iteration
iteration_collection = roulette_wheel(collection, fitness, 2)
# Randomly generate two new rulesets
iteration_collection.extend(generate_collection(2, 10, rule_choices))
# S... |
def deformat(s):
"""Used to deformat the string from markdown format to API response.Required to store responses in the file.
@params
s: The string to be deformatted.
Returns:
_type_: str
"""
s = s.replace("<b>", "**")
s = s.replace("</b>", "**")
s = s.replace("<br>", "... | The code processes POST requests to handle user interactions by retrieving session data, determining client IP addresses, checking input relevance, and generating responses via API calls. It logs interactions, checks for duplicate entries, and returns structured JSON responses with output, headers, or error messages ba... | def datapost(request):
if request.method=="POST":
email=request.session['email']
type_1=request.POST.get('type')
client_ip=None
try:
import socket
hostname = socket.gethostname()
client_ip = socket.gethostbyname(hostname)
except:
... |
def deformat(s):
"""Used to deformat the string from markdown format to API response.Required to store responses in the file.
@params
s: The string to be deformatted.
Returns:
_type_: str
"""
s = s.replace("<b>", "**")
s = s.replace("</b>", "**")
s = s.replace("<br>", "... | The main task of the code is to process user input data for generating conversation responses and managing conversation history. It either retrieves existing question-answer pairs from a file based on user email and query type, or generates a new header and random type identifier when the query type is '9999'. The func... | def process_data(email, type_1, input_data):
"""Used to process the data based on the user input for generating conversation response and manage conversation history
@params
email: The email of the user.
type_1: The type of the query.
input_data: The input data to be used for generating the res... |
def load_data():
data = dict()
data["train"] = lambda: load(conf.data_path + "/train")
data["test"] = lambda: load(conf.data_path + "/test")
return data
def prepocess_train(img, cond,):
img = scipy.misc.imresize(img, [conf.adjust_size, conf.adjust_size])
cond = scipy.misc.imresize(cond, [conf.ad... | The code trains a Conditional Generative Adversarial Network (CGAN) by loading data, initializing the model, setting up Adam optimizers for the discriminator and generator, and running training loops. It processes batches of images and conditions, updates model parameters, tracks losses, saves checkpoints periodically,... | def train():
data = load_data()
model = CGAN()
d_opt = tf.train.AdamOptimizer(learning_rate=conf.learning_rate).minimize(model.d_loss, var_list=model.d_vars)
g_opt = tf.train.AdamOptimizer(learning_rate=conf.learning_rate).minimize(model.g_loss, var_list=model.g_vars)
saver = tf.train.Saver()
... |
def read_components(self):
"""list all components selected items"""
for component in self.data["composant"]:
if component == "Protective":
for compo in PROTECTIVE_COMPONENTS:
print(compo)
item = Item.objects.get(name=compo)
... | The main task of the code is to process form data, populate an `industry_dict` by calling `read_components()`, `read_reaction()`, and `read_items()` methods, and return the populated dictionary. It initializes `self.data` with cleaned form input, constructs `industry_dict`, and returns it as the final output. | def make_list(self, form):
"""main function for home view"""
self.data = form.cleaned_data
self.industry_dict = {}
self.read_components()
self.read_reaction()
self.read_items()
return self.industry_dict |
def is_off():
return db.get_value("value", table="config", search_filter="name", value=("status",)) == "off"
def send_messages():
print("Send messages")
global last_check
global accounts
global messages_log
token1 = db.get_value("value", "config", "name", "token1")
token2 = db.get_value("va... | The main task of the code is to continuously check if a system is not in "off" status, send messages, update the database to mark it as "off", delete old messages, and repeat this process every second to maintain operational state and data integrity. | def main():
while True:
if not is_off():
send_messages()
db.cmd("UPDATE config SET value=%s where name=%s", ("off", "status"))
delete_old_messages()
# print("sleep 500")
time.sleep(1) |
def flatten_features(self):
self.train_x=self.fetch_flattened_2d_version(self.train_x)
# self.test_x=self.fetch_flattened_2d_version(self.test_x)
# print("Shape of train array after flattening is ", self.train_x.shape)
# print("Shape of test array after flattening is ", self.test_x.shap... | This code initializes a clustering model by setting up training data, cluster parameters, and initial cluster assignments. It prepares features, initializes centroid positions, and begins the clustering process using a specified method. The code also prepares structures to track reassignments and optimization steps, la... | def __init__(self, train_x, train_y, num_clusters, init_method="rand_part", dist_metric="euclidean"):
assert(num_clusters>0)
self.train_x=train_x
# self.test_x=test_x
self.train_y=train_y
# self.test_y=test_y
self.num_clusters=num_clusters
#############... |
def _construct_connections(self) -> None:
"""Construct squares connections
"""
self._connections = {p: set([]) for p in self._field}
def add_conn(p: Point, i: int, j: int) -> None:
conn = self._points[i, j]
self._connections[p].add(conn)
self.... | This method solves a Sudoku puzzle in-place using constraint propagation techniques like hidden singles and pairs, iteratively reducing domains without creating new objects. It applies these strategies up to 10 times to progress toward a solution, then marks the puzzle as solved. | def solve_inplace(self) -> None:
"""Solve sudoku without creating new object
"""
if self._solved:
return
self._construct_connections()
self._initial_domain_cut()
limit = 0
while self._to_solve and limit < 10:
limi... |
def init_database_tables():
init_sleeps_table()
init_dailies_table()
#init_manually_updated_activities_table()
#init_activity_files_table()
#init_pulseox_table()
#init_user_permissions_change_table()
#init_user_metrics_table()
#init_move_iq_activities_table()
#init_body_comps_table()... | The main task of the code is to initialize database tables, populate them with data from a file, and create research-specific tables. The function `start_program()` sequentially executes these steps: first setting up database structure (`init_database_tables()`), then loading data (`fill_database_from_file()`), and fin... | def start_program():
init_database_tables()
fill_database_from_file()
create_research_tables() |
def get_parser() -> argparse.Namespace:
"""Parse command line arguments.
Returns:
argparse.Namespace: Parsed arguments namespace object.
"""
parser = argparse.ArgumentParser(
description="Manage docker-compose and Django management commands."
)
parser.add_argument(
"-c",... | The main task of the code is to parse command-line arguments and execute corresponding commands, either via `manage_py` for Django-like tasks or Docker Compose commands (e.g., build, up, down). It handles argument validation, runs specified commands with options like detached mode, and returns 0 for success or 1 if no ... | def main() -> int:
"""Parse arguments and execute the appropriate command."""
parser = get_parser()
args = parser.parse_args()
compose_command = args.compose_command
if compose_command is None and args.command is None:
print("No command specified.")
parser.print_help()
return... |
def execute_move(player: Player, game: Game, move):
if game.turns >= 360:
game.finished = True
knowledge_update = defaultdict(int)
while player.hand[15] > 0:
player.board.redThrees += 1
player.hand[15] -= 1
if move == "goOut":
card = 0
for i in range(4, 15):
... | The main task of the code is to execute a player's action in a turn-based game, update the game state, and return the converted game nodes along with the current player's index. The function processes the action, updates the game state via `execute_move`, and returns a tuple containing the transformed game state data a... | def step(self, action):
execute_move(self.players[self.get_player_id()], self, action)
return (
nodes_conversion(
self.players[self.turn % self.playersCount].hand,
self.players[self.turn % self.playersCount].board,
self.discardPile,
... |
def getDimensiones(A):
return (len(A),len(A[0]))
def createMatriz(m,n,v):
C = []
for i in range(m):
C.append([])
for j in range(n):
C[i].append(v)
return C
def detMatriz(A):
m,n = getDimensiones(A)
if m != n:
print("La matriz no es cuadrada")
return -... | The main task of the code is to compute the cofactor matrix of a given matrix A. It calculates each element C[i][j] as (-1)^(i+j) multiplied by the determinant of the minor matrix obtained by removing row i and column j from A. The resulting matrix C is returned as the cofactor matrix. | def getMatrizAdyacente(A):
m,n = getDimensiones(A)
C = createMatriz(m,n,0)
for i in range(m):
for j in range(n):
C[i][j] = (-1)**(i+j)*detMatriz(getMenorMatriz(A,i,j))
return C |
def detMatriz(A):
m,n = getDimensiones(A)
if m != n:
print("La matriz no es cuadrada")
return -1
if m == 1:
return m
if m == 2:
return A[0][0]*A[1][1] - A[0][1]*A[1][0]
det = 0
for j in range(n):
det += (-1)**(j)*A[0][j]*detMatriz(getMenorMatriz(A,0,j))
... | The code calculates the inverse of a matrix A using the adjugate method. It first computes the determinant of A; if zero, it returns 0 as the matrix is non-invertible. Otherwise, it finds the transpose of A, computes the adjugate of the transpose, and scales each element by 1/detA to form the inverse matrix C, which is... | def getMatrizInversa(A):
detA = detMatriz(A)
if detA == 0:
print("La matriz no tiene inversa")
return 0
At = getMatrizTranspuesta(A)
adyAt = getMatrizAdyacente(At)
m,n = getDimensiones(A)
C = createMatriz(m,n,0)
for i in range(m):
for j in range(n):
C[i]... |
def get_auth_header():
insert_user("testuser", "test")
response = client.post("/token", dict(username="testuser", password="test"))
jwt_token = response.json()["access_token"]
header = {"Authorization": f"Bearer {jwt_token}"}
return header
def check_user(username, mail):
query = """ SELECT * FR... | This test function verifies the POST /v1/user endpoint by creating a user with admin privileges, checking the 201 response status, confirming user data persistence via check_user(), and cleaning the database afterward. It tests user creation functionality with authentication headers and validation. | def test_post_user():
auth_header = get_auth_header()
user_dict = {
"name": "user2",
"password": "secret",
"mail": "pavif@example.com",
"role": "ADMIN",
}
response = client.post("/v1/user", json=user_dict, headers=auth_header)
# print(response.json())
assert re... |
def convert_dtype_date(df, col):
dtype = df[col].dtype.__repr__()
if dtype in {"datetime64[ns, UTC]"}:
return df[col]
else:
return pd.to_datetime(df[col], utc=True).copy()
def convert_dtype_array(df, col):
"""
Converts a list or tuple column to a tuple column and fills missing
va... | The function `convert_dataframe_columns` converts specified DataFrame columns to predefined data types using a dictionary (`dtype_dict`). It iterates through each column-type pair, applying corresponding conversion functions (e.g., for dates, arrays, booleans, integers, floats, or strings) based on the detected data ty... | def convert_dataframe_columns(df, dtype_dict):
"""
Converts each column to its appropriate data type
:param df:
:return:
"""
for col, dtype in dtype_dict.items():
# Dates
if check_dtype_date(dtype=dtype):
df[col] = convert_dtype_date(df=df, col=col)
# Arrays
... |
def darknet_body(x):
"""Darknent body having 52 Convolution2D layers"""
x = DarknetConv2D_BN_Leaky(32, (3, 3))(x)
x = resblock_body(x, 64, 1)
x = resblock_body(x, 128, 2)
b3 = resblock_body(x, 256, 8)
b2 = resblock_body(b3, 512, 8)
b1 = resblock_body(b2, 1024, 4)
return b1, b2, b3
def ma... | The code constructs a YOLOv3 model in Keras by combining feature maps from three scales (b1, b2, b3) through upsampling and concatenation. It processes each branch with `make_last_layers` to generate detection outputs (y1, y2, y3) containing anchor-box predictions and class probabilities. The model returns three output... | def make_yolo_model(input, num_anchors_per_scale, num_classes):
"""Create YOLO_V3 model CNN body in Keras."""
b1, b2, b3 = darknet_body(input)
x, y1 = make_last_layers(b1, 512, num_anchors_per_scale * (5 + num_classes))
x = compose(
DarknetConv2D_BN_Leaky(256, (1, 1)),
UpSampli... |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | This function installs the 'conda' package on Google Colab using 'condacolab' if not already installed. It checks for existing conda installation, installs condacolab via pip on Colab, executes its installation, and confirms the result. Non-Colab environments receive a restriction message. | def install_condacolab():
if found_installation("conda"):
return True
if on_colab():
print("Installing condacolab via pip ... ", end="")
print("Restarting the notebook might be required afterwards ... ", end="")
os.system("pip install -q condacolab")
import condacolab
... |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | The function installs the GLPK solver (glpsol) if not already detected. It checks the environment: if on Google Colab, it uses apt-get; otherwise, it uses conda from the conda-forge channel. After installation, it confirms the presence of glpsol. | def install_glpk():
if found_installation("glpsol"):
return True
if on_colab():
print("Installing glpk on Google Colab via apt-get ... ", end="")
os.system('apt-get install -y -qq glpk-utils')
else:
print("Installing glpk via conda ... ", end="")
os.system('conda ins... |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | The function checks if Gecode is already installed; if not, it notifies the user that no installation procedure is implemented for Colab or other environments and then confirms the installation status of Gecode. | def install_gecode():
if found_installation("gecode"):
return True
if on_colab():
print("No procedure implemented to install gecode ... ", end="")
else:
print("No procedure implemented to install gecode ... ", end="")
return confirm_installation("gecode") |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | This function installs the Gurobi optimization library's Python interface (gurobipy) by checking if it's already installed. If not, it installs via pip on Google Colab or via conda in other environments, then confirms the installation. It handles environment-specific installation methods to ensure Gurobi is available f... | def install_gurobi():
if found_installation(module="gurobipy"):
return True
if on_colab():
print("Installing gurobi on Google Colab via pip (without license) ... ", end="")
os.system("pip install -q gurobipy")
else:
print("Installing gurobi via conda (without license) ... ",... |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | This function installs the CPLEX optimization library, checking if it's already installed. If not, it installs via pip on Google Colab or via conda in other environments, then verifies the installation. | def install_cplex():
if found_installation(module="cplex"):
return True
if on_colab():
print("Installing cplex on Google Colab via pip (without license) ... ", end="")
os.system("pip install -q cplex")
else:
print("Installing cplex via conda (without license) ... ", end="")
... |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | The code installs the MOSEK optimization library, checking if it's already installed. If not, it installs via pip on Google Colab or via conda on other environments, then confirms the installation. It returns True if successful. | def install_mosek():
if found_installation(module="mosek.fusion"):
return True
if on_colab():
print("Installing mosek on Google Colab via pip (without license) ... ", end="")
os.system("pip install -q mosek")
else:
print("Installing mosek via conda (without license) ... ", ... |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | This function installs the 'xpress' module by checking if it's already installed. If not, it installs via pip on Google Colab or via conda from the 'fico-xpress' channel otherwise. It returns True if installation succeeds. | def install_xpress():
if found_installation(module="xpress"):
return True
if on_colab():
print("Installing xpress on Google Colab via pip (without license) ... ", end="")
os.system("pip install -q xpress")
else:
print("Installing xpress via conda (without license) ... ", end... |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | This function installs the SCIP optimization library via conda, checking for existing installation first. If not found, it installs pyscipopt using conda, with special handling for Colab environments, then verifies the installation. | def install_scip():
if found_installation("scip"):
return True
print("Installing scip via conda ... ", end="")
if on_colab():
install_condacolab()
os.system("conda install -y -q pyscipopt")
return confirm_installation("scip") |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | This function installs the Pyomo package using Conda if not already installed, with a fallback to install_idaes() on Colab environments. It checks for existing installations, performs the installation via system command, and confirms the result. | def install_pyomo():
if found_installation(module="pyomo"):
return True
if on_colab():
return install_idaes()
else:
print("Installing pyomo via conda ...", end="")
os.system("conda install -y -q -c conda-forge pyomo")
return confirm_installation(module="pyomo") |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | This function installs the Ipopt solver by checking for existing installation, using Colab-specific handling if detected, or installing via conda from conda-forge otherwise, then verifying the installation. | def install_ipopt():
if found_installation("ipopt"):
return True
if on_colab():
return install_idaes_solvers()
else:
print("Installing Ipopt via conda ... ", end="")
os.system('conda install -y -q -c conda-forge ipopt')
return confirm_installation("ipopt") |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | The function `install_cbc` checks if the CBC solver is already installed. If not, it installs CBC via `apt-get` on non-Colab environments or delegates to `install_idaes_solvers` on Colab. It confirms the installation afterward. | def install_cbc():
if found_installation("cbc"):
return True
if on_colab():
return install_idaes_solvers()
else:
print("Installing cbc via apt-get ... ", end="")
os.system('apt-get install -y -qq coinor-cbc')
return confirm_installation("cbc") |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | This function checks if Bonmin is installed; if not, it attempts installation via `install_idaes_solvers()` on Colab environments. If not on Colab, it alerts the user to try `install_idaes_solvers()` as an alternative, then confirms the installation status. | def install_bonmin():
if found_installation("bonmin"):
return True
if on_colab():
return install_idaes_solvers()
else:
print("No procedure implemented to install bonmin ... ", end="")
print("You may try to use install_idaes_solvers() instead ... ", end="")
return confir... |
def found_installation(executable=None, module=None):
"""Print message confirming that package was found, then return True or False."""
is_available = _check_available(executable, module)
if is_available:
name = next(n for n in (executable, module) if n is not None)
print(f"{name} was previo... | The function `install_couenne` attempts to install the Couenne solver. It first checks if Couenne is already installed; if not, it conditionally installs it via `install_idaes_solvers()` on Colab environments. If neither applies, it notifies the user of missing installation procedures and suggests alternatives. Finally... | def install_couenne():
if found_installation("couenne"):
return True
if on_colab():
return install_idaes_solvers()
else:
print("No procedure implemented to install couenne ... ", end="")
print("You may try to use install_idaes_solvers() instead ... ", end="")
return con... |
def country_list():
return create_list("country.json", "country", "country")
def capital_list():
return create_list("capital.json", "capital", "capital")
def currency_list():
return create_list("currency.json", "currency", "currency")
def language_list():
return create_list("language.json", "language", "language") | The code's main task is to display country details, including their capital, currency, and language, by iterating through parallel lists. It prints each country's information sequentially, using a loop to access corresponding entries in the lists, and separates each entry with a dashed line for clarity. | def learn():
learn_country = country_list()
learn_capital = capital_list()
learn_currency = currency_list()
learn_language = language_list()
len_list = len(learn_country)
i = 0
while i < len_list:
first_letter_country = learn_country[i][0]
print("COUNTRY : " + learn_country[i])
print("CAPITAL : " + learn_c... |
def display_board():
print(board[0] + "|" +board[1] + "|" + board[2] + "|")
print(board[3] + "|" + board[4] + "|" + board[5] + "|")
print(board[6] + "|" + board[7] + "|" + board[8] + "|")
def handle_turn(player):
position_str = input("Choose a position from 1 to 9: ")
position = int(position_str) - ... | The main task of the code is to manage a game loop that displays the board, alternates players' turns, processes each player's move, checks for game-ending conditions (win/tie), and switches players until the game concludes. It orchestrates gameplay flow by repeatedly handling turns and updating the game state until `g... | def play_game():
#Display the initial board
display_board()
#while the game is still going
while game_still_going:
#handle a single turn of an arbitrary player
handle_turn(current_player)
#check if the game has ended
check_if_game_over()
#flip to the g... |
def getAuthenticationToken():
URL = "https://api-gw-service-nmn.local/keycloak/realms/shasta/protocol/openid-connect/token"
kSecret = getK8sClient().read_namespaced_secret("admin-client-auth", "default")
secret = b64decode(kSecret.data['client-secret']).decode("utf-8")
DATA = {
"grant_type": "... | The main task of the code is to validate HSM (Hardware State Manager) and SLS (System Lifecycle Service) component consistency across different cabinet types (River, Mountain/Hill, EX2500) by retrieving authentication tokens, HSM data, Redfish endpoints, and SLS hardware information. It processes these data into struct... | def main():
authToken = getAuthenticationToken()
if authToken == "":
print("ERROR: No/empty auth token, can't continue.")
return 1
hsm_state_components_raw, stat = getHSMComponents(authToken)
if stat != 0:
print("HSM components returned non-zero.")
return 1
# Put HS... |
def getAuthenticationToken():
"""Fetch auth token for HMS REST API calls."""
URL = "https://api-gw-service-nmn.local/keycloak/realms/shasta/protocol/openid-connect/token"
kSecret = getK8sClient().read_namespaced_secret("admin-client-auth", "default")
secret = b64decode(kSecret.data['client-secret']).de... | The main task of the code is to authenticate, retrieve management node components from HSM, filter unlocked nodes, attempt to lock them, and report outcomes. It handles error cases, skips locked nodes, and exits with status codes based on success/failure, ensuring only eligible nodes are locked through API calls. | def main():
"""Entry point"""
numErrs = 0
compList = []
compLockList = []
bmcList = []
authToken = getAuthenticationToken()
if authToken == "":
print("ERROR: No/empty auth token, can't continue.")
print("\nFor troubleshooting and manual steps, see https://github.com/Cray-HPE/... |
def initialize_users(n_users, seed=None):
if seed is not None:
np.random.seed(seed)
opinions = np.random.rand(n_users)
influences = np.random.rand(n_users)
return opinions, influences
def select_influencer(influences):
normalized_influences = influences / np.sum(influences)
return custom... | This function simulates the evolution of user opinions over time steps using a model where each user updates their opinion based on an influencer's opinion, adjusting by parameters epsilon and mu. It tracks opinions in a matrix and stops early if stabilization is detected (opinion changes fall below a threshold). Retur... | def run_model(n_users, t_max, epsilon, mu, n_average=10, stop_tol=1e-6, seed=None):
opinions, influences = initialize_users(n_users, seed)
opinion_matrix = np.zeros((t_max, n_users))
opinion_matrix[0] = opinions.copy()
for t in range(1, t_max):
for user in range(n_users):
influencer... |
def check_pos_data(self):
if self.pos_data is None:
self.pos_data=np.zeros(list(self.data.shape[:2])+
list(np.array(self.pos_data_gui).shape))
self.pos_data[:,:]=np.array(self.pos_data_gui)[np.newaxis,np.newaxis,:,:]
if self.markers is None:
self.uc_... | This function refines atom positions in a unit cell using the center-of-mass (COM) method across all data entries. It iterates over each row and column of the dataset, applying the refinement algorithm to update positional data. After processing, it adds markers to the unit cell structure. The process repeats for speci... | def refine_uc_atoms_com(self,iters=5,**args):
self.check_pos_data()
for r in range(self.data.shape[0]):
print(r,"/",self.data.shape[0])
for c in range(self.data.shape[1]):
_pos=self.pos_data.copy()
self.pos_data[r,c,:,:]=refine_image_positions_com(... |
def load_public_key(filename):
with open(filename, "rb") as key_file:
return serialization.load_pem_public_key(key_file.read())
def send_encrypted_credentials(client_socket, public_key, user_id, password):
credentials = f"ID: {user_id} Password: {password}"
encrypted_credentials = encrypt_with_publi... | The code establishes a secure connection to a bank server using public-key encryption, authenticates user credentials, and provides a menu-driven interface for banking operations like money transfers and balance checks. It continuously prompts for login details until successful, handles encrypted communication, and all... | def connect_to_bank_server(host, port, public_key_path):
public_key = load_public_key(public_key_path)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((host, port))
print(f"Connected to bank server at {host}:{port}")
server_public_key_data... |
def calculateMin(self):
# function to get the minimal of the dataset
# time function included here to get the execution time
start_time = time.time()
input_str = self.num_entry.get()
num_list = self.split_numbers(input_str)
if not num_list:
return None
... | The main task of the code is to save calculated statistical values (min, max, mean, mode, median, MAD, SD) to a CSV file named after the user. It appends these values to the file, handles cases with no input data, logs results, and updates a GUI label by clearing previous content before saving. | def write_file(self):
# function to save results to local
self.result_label.delete('1.0', tk.END)
with open(f"Output_{self.username}.csv", "a+", newline="") as f:
wt = csv.writer(f, delimiter=',')
min_value = self.calculateMin()
max_value = self.calculateMax()... |
def parse_args_and_config():
parser = argparse.ArgumentParser(description=globals()["__doc__"])
parser.add_argument(
"--config", type=str, default="cifar10_sparse.yml", help="Path to the config file"
)
parser.add_argument(
"--device", type=str, default="cuda:0", help="CUDA DEVICE"
)... | The code generates images using a diffusion model, either by loading a distilled checkpoint or a pretrained model. It performs diffusion steps with specified beta schedules, processes the output, and saves the generated images as PNGs in the 'sample' directory with filenames indicating the time step and model type. | def main():
args, config = parse_args_and_config()
if not args.use_pretrained:
ckpt = f"output/logs/CIFAR10_pd_dis_to_4/distill_ckpt_{args.time_step}_step.pth"
states = torch.load(ckpt, map_location=args.device)
model = Model(config)
model = model.to(args.device)
model.lo... |
def get_eigenvalues(model, weightfile, layer=7):
"Read the keras weightfile, get weights for the layer, and compute the eigenvalues(-1)"
W = load_keras_matrix(model, weightfile, layer)
u, sv, vh = svd(W)
eigenvalues = sv*sv
return eigenvalues
def logloghist(eigenvalues, bins=100, alpha=0.25, color='blue', den... | The main task of the code is to plot the empirical spectral distribution (ESD) of eigenvalues and fit it with the Marchenko-Pastur distribution. It calculates the sigma parameter from the maximum eigenvalue if not provided, computes the percentage of spikes outside the bulk, and overlays the theoretical MP distribution... | def plot_ESD_and_fit(eigenvalues=None, model=None, weightfile=None,
layer=2, Q=1.0, num_spikes=0, sigma=None,
alpha=0.25, color='blue', skip=False, verbose=True,
loglog=False):
"""Plot histogram of eigenvalues, for Q, and fit Marchenk Pastur.
If n... |
def get_eigenvalues(model, weightfile, layer=7):
"Read the keras weightfile, get weights for the layer, and compute the eigenvalues(-1)"
W = load_tf_matrix(model, weightfile, layer)
u, sv, vh = svd(W)
eigenvalues = sv*sv
return eigenvalues
def logloghist(eigenvalues, bins=100, alpha=0.25, color='blue', densit... | The function `plot_ESD_and_fit` plots the empirical spectral distribution (ESD) of eigenvalues and fits it to the Marchenko-Pastur (MP) distribution. It accepts eigenvalues or a Keras model/weightfile to compute them. If `sigma` is unspecified, it estimates it from the largest eigenvalues. The histogram (log-log or lin... | def plot_ESD_and_fit(eigenvalues=None, model=None, weightfile=None,
layer=2, Q=1.0, num_spikes=0, sigma=None,
alpha=0.25, color='blue', skip=False, verbose=True,
loglog=True):
"""Plot histogram of eigenvalues, for Q, and fit Marchenk Pastur.
If no... |
def init_names__(self, name, log_time):
self.logging_name = sys.path[0] + "/logging/" + name
self.checkpoint_name = sys.path[0] + "/checkpoints/" + name
if log_time:
now = datetime.now().strftime("%d_%m_%Y__%H_%M_%S")
self.logging_name += "_" + now
self.checkp... | The code simulates a multi-player game environment over a specified number of games, handling player relocation, AI training, and checkpointing. It initializes game parameters, manages game loops with periodic resets, trains the AI brain, and logs progress. The function supports human players, device configuration, and... | def game(self, n_games, n_players, relocation_freq = 180, training_freq = 45, checkpoint_freq = None, device = "cpu", name = "default", log_time = True, with_human = False, reset_all = True):
self.n_players = n_players
self.device = device
self.n_games = n_games
self.reset_all = reset_al... |
def get_accounts(key):
try:
with requests_cache.disabled():
secret, password = get_secrets(key)
auth_client = gdax.AuthenticatedClient(key, secret, password)
gdax_accounts = auth_client.get_accounts()
return gdax_accounts
except Exception as error:
... | The function retrieves account values using an access token, calculates the total USD value across all accounts, and returns an Alexa response stating the total. It handles errors by logging exceptions and returning an error message. | def account_value(event):
# Alexa Response - AccountValue
try:
d = get_accounts(event['session']['user']['accessToken'])
accounts = get_accounts_of_value(d)
total_value = get_total_account_value(accounts)
s = '' if len(accounts) == 1 else 's'
speech = 'Your total account ... |
def log_req(request):
"""
DEBUGGING ONLY
"""
data = ''
if request.method == 'GET':
logger.debug('GET')
for key, value in request.GET.items():
data += '"%s": "%s", ' % (key, value)
if request.method == 'POST':
logger.debug('POST')
for key, value in requ... | The main task of the code is to handle POST requests to the "/api/alexa" endpoint by parsing incoming JSON data, identifying the Alexa intent, and delegating to specific functions (e.g., account overview, coin status) to generate appropriate responses. It logs requests, processes intent-based logic, and returns structu... | def alexa_post(request):
"""
View /api/alexa
"""
log_req(request)
try:
body = request.body.decode('utf-8')
event = json.loads(body)
logger.info(event)
intent = event['request']['intent']['name']
if intent == 'AccountOverview':
return acct_overview... |
def get_host_specs(**data):
ncpu = data.get("ncpu")
hostname = data.get("hostname")
queue = data.get("queue")
if ncpu < 0:
raise ValueError("Number of cpus cannot be negative")
if "newblue" in hostname:
system = 'pbs'
if ncpu > 16:
raise ValueError("Too many cpu... | The main task of the code is to process command-line arguments for a job submission script, validate input parameters, gather system specifications, and execute either file-based or directory-based submission based on the 'files' argument, ensuring compatibility with node count and submission method constraints. | def main(*args):
narg = len(args)
if len(args) != 7:
raise ValueError("Invalid number of input arguments ({})".format(narg))
names = ["prog", "wd", "nodes", "ncpu", "time", "files", "queue"]
data = dict(zip(names, args))
data["ncpu"] = int(data["ncpu"])
data["nodes"] = int(data["nodes"... |
def first_time_setup(self):
self.delete_old_config()
paths = self.read_paths_from_config()
if not paths['steamcmd'] or not paths['palserver']:
if not paths['steamcmd']:
paths['steamcmd'] = self.prompt_for_directory("Select SteamCMD Folder")
if not paths['p... | This code initializes a GUI application for managing a Palworld server, setting up a dark-themed interface with tabs for application control, configuration editing, and banned player management. It handles directory setup, executable path detection, player interaction (kick/ban), resource monitoring (CPU/memory), and s... | def __init__(self, master=None):
super().__init__(master)
sv_ttk.set_theme("dark")
cursor_point = "hand2" if platform != "darwin" else "pointinghand"
self.app_name = 'PalworldControlCenter' # Replace with your application's name
self.config_file_name = 'app_config.json'
... |
def run_bat_file(file_path, steam_cmd):
try:
subprocess.run(file_path, shell=True, cwd=steam_cmd)
except Exception as e:
messagebox.showerror("Error", f"Failed to start the server: {e}")
def is_application_running(app_name):
"""Check if the application is currently running."""
for proc i... | The main task of the code is to start an application by executing a batch file, then check if it runs successfully within 10 seconds (5 intervals of 2 seconds). If successful, it updates status indicators, initiates resource monitoring, and shows a confirmation message. If the application fails to start, it displays an... | def start_app(self):
# Run the batch file to start the application
run_bat_file(self.bat_file_path, self.steamcmd_path)
# Attempt to check if the application started for a certain period
for _ in range(5): # Try for 5 intervals
time.sleep(2) # Wait for 2 seconds between ch... |
def random_clusters(self,x):
# idx=np.random.choice(np.arange(0,x.shape[0]),self.K) # don't use cuz it can give repeatition
idx=random.sample(range(0,x.shape[0]),self.K) # no repeatition
self.mu=x[idx,:]
def train(self,x,show=True,showat=100):
loss_list=[]
if self.mu is None:... | The code generates multiple random initializations of a model by iterating `num_of_models` times, training each with `random_clusters` and `train`, then selects the initialization with the lowest loss using `argmin` to set `self.mu` as the optimal starting point. | def random_initializations(self,x,num_of_models=100):
mu_list=[]
loss_list=[]
for i in range(num_of_models):
self.random_clusters(x)
mu_list.append(self.mu)
self.train(x,show=False)
loss_list.append(self.loss(x))
idx=np.argmin(loss_list)
... |
def random_clusters(self,x):
# idx=np.random.choice(np.arange(0,x.shape[0]),self.K) # don't use cuz it can give repeatition
idx=random.sample(range(0,x.shape[0]),self.K) # no repeatition
self.mu=x[idx,:]
def random_initializations(self,x,num_of_models=100):
mu_list=[]
loss_li... | This code implements the elbow method to determine the optimal number of clusters (K) in a clustering algorithm. It iterates over K values from 1 to the specified maximum, trains the model for each K, records the loss (e.g., inertia), and plots the loss against K to visualize the "elbow" point where increasing K yields... | def elbow_method(self,x,K=10):
original_k=self.K
k_list=list(range(1,K+1))
loss_list=[]
for k in k_list:
print('with ',k,' clusters:')
self.K=k
self.random_clusters(x)
self.random_initializations(x,num_of_models=10)
self.train(x... |
def vectorize_jokes(self, jokes, index):
vec = CountVectorizer()
X = vec.fit_transform(jokes)
return pd.DataFrame(X.toarray(), columns=vec.get_feature_names(), index=index)
def filter_by_tf_idf(self, df, n):
top_words = self.get_top_words_by_tf_idf(self.tf_idf(df), n)
return d... | The main task of the code is to transform raw joke data into a lower-dimensional feature representation suitable for machine learning. It vectorizes jokes, filters features using TF-IDF, applies PCA for dimensionality reduction, and combines the transformed features with original labels into a labeled DataFrame for dow... | def engineer_features(self, data):
df_vec = self.vectorize_jokes(list(data['_joke']), data['_id'])
# print('\n\VECT ::: VECT\n\n')
#print(df_vec.head())
#print(df_vec.shape)
#print('\n\TF_IDF ::: TF_IDF\n\n')
df_filtered = self.filter_by... |
def delete_internal_node(self, node, data, index):
order = self.order
if node.leaf:
if node.keys[index] == data:
node.keys.pop(index)
return
return
if len(node.child[index].keys) >= order:
node.keys[index] = self.delete_predece... | This function deletes a specified data value from a B-tree node. It checks if the node is a leaf, directly removing the key if found. For internal nodes, it locates the target key, recursively deletes from the appropriate child, and maintains tree balance by borrowing or merging with siblings when child nodes have insu... | def delete(self, node, data):
order = self.order
index = 0
while index < len(node.keys) and data > node.keys[index]:
index += 1
if node.leaf:
if index < len(node.keys) and node.keys[index] == data:
node.keys.pop(index)
return
... |
def initialise_parameters(self, x_train, y_train):
mu, sigma = 0, 0.01
self.number_images = x_train.shape[0]
input_dimension = x_train.shape[1]
number_classes = y_train.shape[1]
for layer in self.model.keys(): # Iterate through hidden layers and initialise their parameters
... | This function trains a neural network using mini-batch gradient descent. It initializes parameters, iterates through specified epochs, processes mini-batches via forward/backward passes, computes loss/accuracy, updates weights, and logs training/test metrics. It prints progress intervals, plots cost/accuracy trends, an... | def train_model(self, x_train, y_train, x_test, y_test, iterations, learning_rate, mini_batch_size):
self.initialise_parameters(x_train, y_train)
print('Training started ...\n')
for epoch in range(0, iterations): # Iterate through the specified number of iterations (ephocs)
ephoc_cos... |
def estado_inicial(eP, m1, m2):
"""
Esta funcao e responsavel por gerar o quadrimomento das particulas que irao ser colididas.
:param eP: Energia do proton utilizado na colisao.
:param m1: Massa da particula 1.
:param m2: Massa da particula 2.
:return: Os quadrimomentos das particulas 1 e 2.
"""
... | The code simulates particle collision events, generating quadrimomenta (energy and momentum components) for particles A, B, X, Y, and initial partons. It converts input values to consistent units (GeV), validates energy thresholds, performs collision and decay calculations, applies detector effects, and saves results t... | def main(n,eP,mX,mY,m1,m2,mA,mB):
#Declaracao das unidades de medida
unum.Unum.reset()
unum.Unum.VALUE_FORMAT = "%0.2E"
unum.Unum.UNIT_HIDE_EMPTY = True
#Unidades de massa e energia
eV = unum.Unum.unit('eV')
keV = unum.Unum.unit('keV', 10 ** 3 * eV)
MeV = unum.Unum.unit('MeV', 10 ** 6 * eV)
GeV = unum.U... |
def process(frameDir,resultFile,numberOfFrames,indexFunc,divH=1,divW=1):
period = 100
area = divH*divW
frame = 0
while frame<numberOfFrames:
print("---------- SEEDING ----------")
frame = seed(resultFile,d)[0]//area
ct = 0
while ct<period and frame<numberOfFrames:
... | The code processes image frames from specified directories using different functions based on input 'n'. It handles tasks like frame analysis, range calculation, and result generation, utilizing parameters such as frame divisions, index functions, and output directories. The main tasks include frame processing, directo... | def main(n):
#1-129 : new = 496, 74.6; old = 195, 147;
#93
#142-260
#281-
frameDir = "T4/"
resDir = "T4-100/"
rangeFile = "range.txt"
numberOfFrames = 3747
rangeNumber = 20
#frameNums = [26,196,278,325,380,397,405,434,446,513,549,585,629,733,849,932]
# scene1, scene2, loadi... |
def resolve_query_string(query_string):
query_string = query_string.lower()
if query_string in api.name_map:
return api.name_map[query_string]
elif check_flag(query_string):
code = code_from_flag(query_string).lower()
if code in api.name_map:
return api.name_map[code]
... | This function processes user text to determine the appropriate command: resolves queries, directs to country-specific commands if resolved, checks for 'world' context, identifies US/German states, or replies with an 'unknown place' message if no match is found. | def handle_text(update, context):
query_string = update.message.text.lower()
resolved = resolve_query_string(query_string)
if resolved:
command_country(update, context, resolved)
elif WORLD_IDENT in query_string:
command_world(update, context)
elif query_string.title() in api.us_stat... |
def get_loss_rate_one_set(t0, J1, J2, e1=None, e2=None, s1=0., s2=5.5, q=1.):
if e1 is None:
e1 = 2.e-6/479.603977 # emittance geometric for 2 micrometers normalized at 450GeV
if e2 is None:
e2 = 2.e-6/479.603977 # emittance geometric for 2 micrometers normalized at 450GeV
J1e = J1/e1
... | The code combines loss data from multiple files to calculate total beam losses using three distributions (parabolic, q-exponential, exponential). It integrates loss rates over time, computes systematic and statistical errors, and returns a dictionary with loss rates, errors, integrated losses per hour, and intensity es... | def combine_losses(fname_list, Jz_list, e1=None, e2=None, bunch_length=None, energy='450GeV', q=1., rfvoltage=6):
if e1 is None:
e1 = 2.e-6/479.603977 # emittance geometric for 2 micrometers normalized at 450GeV
if e2 is None:
e2 = 2.e-6/479.603977 # emittance geometric for 2 micrometers normali... |
def __load_datasets_from_yaml(self):
dataset_from_yaml = input('\nWould you like to import datasets from yaml file ? (y/n) ---> ').lower()
if dataset_from_yaml == "y":
yaml_file = str(input('\nPlease input the path to the yaml file: '))
self.framework.datasets_dict = self.frame... | The code's main task is to evaluate datasets using specified metrics. It loads datasets and metrics from YAML configurations, checks for their existence, evaluates the metrics, generates a CSV report, and outputs the results. If no datasets or metrics are found, it exits with appropriate messages. The process includes ... | def run(self):
self.__load_datasets_from_yaml()
datasets = self.__add_dataset()
if not datasets:
print("No dataset(s) to be evaluated.")
exit()
else:
self.__load_input_metrics_from_yaml()
metrics = self.__set_metrics()
if not me... |
def get_low_points(lines):
max_rows = len(lines)
max_columns = len(lines[0]) - 1
points = []
for i in range(0, max_rows):
for j in range(0, max_columns):
if low_point(lines, max_rows, max_columns, i, j):
points.append((i, j))
return points
def expand_basin(... | The code processes input data to identify and calculate the sizes of the three largest basins in a grid. It reads input lines, detects low points, expands each into a basin, tracks the top three basin sizes, and multiplies them for the final result. | def part_two():
with open("input.txt", "r") as f:
lines = f.readlines()
low_points = get_low_points(lines)
results = []
for low_p in low_points:
basin = expand_basin(lines, low_p)
basin_size = len(basin)
print_basin(lines, basin)
if... |
def decode_request_body(request):
body = json.loads(request.body.decode('utf-8'))
logger.info("Getting Request params")
return body
def pre_validation(self,sender_info,request_info):
"""
"""
amount_to_transfer, currency = request_info.get(const.AMOUNT), request_info.get(const.CURREN... | This function transfers funds between wallets by decoding the request, validating sender and recipient details, initiating the transaction, and returning a status indicating success or failure along with error reasons if exceptions occur. | def transfer_fund(self, sender_info, request):
"""
transfer funds between wallets.
"""
logger.info("Triggering Transaction...")
response_status = {const.TRANSACTION_STATUS: ""}
try:
request_info = decode_request_body(request)
logger.info("Start val... |
def is_train_test_file_exists(self) -> bool:
try:
logging.info("Checking if training and test file available or not.")
train_file_path = self.data_ingestion_artifact.train_file_path
test_file_path = self.data_ingestion_artifact.test_file_path
is_train_file_exists... | The main task of the code is to perform data validation by checking the existence of train/test files, validating the dataset schema, and detecting data drift. It then creates a `DataValidationArtifact` with validation results and logs it. If any step fails, it raises a `HousingException` with the error. | def initiate_data_validation(self):
try:
self.is_train_test_file_exists()
self.validate_dataset_schema()
self.is_data_drift_found()
data_validation_artifact = DataValidationArtifact(schema_file_path=self.data_validation_config.schema_file_path,
... |
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
def handle_turn(player):
global position
print(player + " 's turn")
position=input("Choose position from 1-9: ")
... | This code defines a function to play a game, typically Tic-Tac-Toe, by displaying the board, handling player turns, checking for game-ending conditions, and alternating players until the game concludes. It then declares the winner or announces a tie based on the outcome. | def play_game():
display_board()
#loop for next turn
while game_still_going:
handle_turn(current_player)
check_if_game_over()
flip_player()
if winner=="X" or winner=="O":
print(winner + " is the winner")
elif winner==None:
print("Tie") |
def _is_valid_file(self, file_path: str) -> bool:
"""Check if the file is valid for processing."""
is_valid = (
not file_path.endswith("/")
and any(file_path.endswith(ext) for ext in self.SUPPORTED_EXTENSIONS)
and self._is_likely_useful_file(file_path)
)
... | This function processes files in a specified directory by filtering out ignored directories, reading valid files, formatting their content with comment syntax and relative paths, cleaning the content, and concatenating all processed text into a single string for output. | def _process_directory(self) -> str:
"""Process files from a directory and return the processed text."""
processed_texts = []
for root, dirs, files in os.walk(self.repo_path):
dirs[:] = [d for d in dirs if d not in self.ignore_dirs]
for file in files:
fil... |
def _is_valid_file(self, file_path: str) -> bool:
"""Check if the file is valid for processing."""
is_valid = (
not file_path.endswith("/")
and any(file_path.endswith(ext) for ext in self.SUPPORTED_EXTENSIONS)
and self._is_likely_useful_file(file_path)
)
... | The main task of the code is to extract and process text from valid files within a ZIP archive. It identifies file types, applies appropriate comment syntax, cleans the content, and concatenates all processed files into a single string with separators. | def _process_files(self, zip_file: zipfile.ZipFile) -> str:
"""Process files from the zip file and return the processed text."""
processed_texts = []
for file_path in zip_file.namelist():
if self._is_valid_file(file_path):
file_content = zip_file.read(file_path).decod... |
def _process_url(self) -> str:
"""Process files from a GitHub repository URL and return the processed text."""
if "/tree/" in self.repo_path:
self.repo_path = f"https://download-directory.github.io/?{self.repo_path}"
response = requests.get(f"{self.repo_path}/archive/master.zip")
... | The main task of the code is to determine the type of repository path provided and delegate processing to the appropriate helper method: `_process_url()` for URLs, `_process_zip()` for ZIP files, or `_process_directory()` for local directories, returning a string result accordingly. | def process_repo(self) -> str:
"""Process files from the repository."""
if self.repo_path.startswith("http"):
return self._process_url()
elif self.repo_path.endswith(".zip"):
return self._process_zip()
else:
return self._process_directory() |
def centroid(current_frame):
''' Using a threshold segment out the cells in each image and calculate the centroid for each object and store in an array '''
centroid_measurements = []
# conver to binary img
thresh = 145
im_bin = cv2.threshold(current_frame, thresh, 255, cv2.THRESH_BINARY)[1]
#... | The main task of the code is to track cells in a sequence of images using centroid detection and Kalman filtering. It preprocesses cell images, calculates centroids for each frame, applies a Kalman filter to predict object movement, and visualizes the tracked paths by drawing lines on each frame. The final output is a ... | def main():
# preprocess the images
cell_folder = os.path.abspath(r'C:\Users\leyan\Documents\CS585\PA4\CS585-Cells')
cell_list = [os.path.join(cell_folder, file) for file in sorted(os.listdir(cell_folder)) if os.path.isfile(os.path.join(cell_folder, file)) and 'tif' in file]
cell_images = []
for f... |
def kalmanFilter(image_frames, measurements):
'''
takes in image frames and measurements, make predictions based on previous prediction and current measurements.
Return a list of tracks of objects between frames, from previous frame to this frame.
'''
img = image_frames[0]
img_x, img_y = img.s... | The code loads bat image and localization data, applies a Kalman filter for tracking, generates tracked frames, and saves results. It processes PPM images and TXT localization files, uses Kalman filtering for trajectory estimation, and visualizes tracks on image frames, outputting tracked bat movements as saved images. | def main():
# load data, parameter types refer to preprocessing.py
img_dir=r'C:\Users\leyan\Documents\CS585\PA4\CS585-BatImages\Gray'
loc_dir=r'C:/Users\leyan\Documents\CS585\PA4\Localization_Bats'
loc_path = os.path.abspath(loc_dir)
loc_list = [os.path.join(loc_path, file) for file in os.listdir(l... |
def restart(self):
self.blockMat = [['empty'] * self.colNum for i in
range(self.rowNum)]
self.piece = MovingPiece(self.colNum, self.rowNum, 'uncreated')
self.lineClearStatus = 'idle'
self.clearedLines = [-1, -1, -1, -1]
gameClock.fall.preFrame = gameClo... | This function handles game actions based on the current state. It processes inputs for restarting, pausing, rotating pieces, and collision detection. When running, it moves the piece, checks for game over, clears lines, updates scores, and manages animations. Paused state toggles via key presses. Game over triggers a r... | def gameAction(self):
if self.gameStatus == 'firstStart':
if key.enter.status == 'pressed':
self.restart()
elif self.gameStatus == 'running':
if key.restart.trig == True:
self.restart()
key.restart.trig = False
if sel... |
def spawn(self):
self.dropScore = 0
origin = [0, 3]
for i in range(0, 4):
self.currentDef[i] = list(pieceDefs[self.type][i])
spawnTry = 0
while spawnTry < 2:
if self.spawnCollisionCheck(origin) == False:
break
else:
... | This code handles block movement in a game, checking collision states and updating position based on input keys. It transitions the block's status between 'uncreated', 'moving', and 'collided', applying directional movement logic with collision detection for down, left, and right directions. The function also triggers ... | def move(self, lastBlockMat):
if self.status == 'uncreated':
self.status = 'moving'
self.blockMat = lastBlockMat
self.spawn()
global mainBoard
if mainBoard != None:
run_ai(mainBoard, mainBoard.colNum, mainBoard.rowNum)
elif sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.