dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def extend_tree(root):
"""
Transforms a tree of nodes type(node) to ExtNode which holds information required to create paths (i.e.,
depth, leaf number, and log_parents) and returns a list of containing all leaves
:param root: root of the tree to extend
:return: extended tree and the list of its leav... | The main task of the code is to generate all valid paths between leaf nodes in a UAST (Universal Abstract Syntax Tree) under constraints on maximum path length and width. It processes a UAST file, identifies leaf nodes, computes paths between pairs of leaves via their lowest common ancestor (LCA), filters paths by leng... | def get_paths(uast_file, max_length, max_width, token_extractor, split_leaves=True):
"""
Creates a list of all the paths given the max_length and max_width restrictions.
:param uast_file: file containing a bblfsh UAST as string and binary-coded
:param max_length:
:param max_width:
:param token_e... |
def recursive_glob(rootdir='.', pattern='*'):
"""Search recursively for files matching a specified pattern.
Adapted from http://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-recursively-in-python
"""
matches = []
for root, dirnames, filenames in os.walk(rootdir):
for filename ... | The code extracts code paths from AST files, maps unique tokens to IDs, and returns token-converted paths along with the token-to-ID mapping for analysis or modeling tasks. | def extract_paths(data, extension, max_length, max_width):
"""
Computes the code paths of each file and the lists of all tokens seen
:param data: folder where the AST files are (for now bblfsh binary UASTs)
:param extension: extension to filter by; default uast.bin as saved by 'repos_to_uast.py'
:pa... |
def make_replay_buffer(self, num_examples: int) -> None:
"""
Takes in the desired number of examples to make the replay buffer from (basically the size of the replay buffer).
Saves a list of tuples of the form <s, a, r, s'> in the variable replay_buffer.
----------------
Input:
... | This code performs iterative linear regression on a replay buffer to update the weight matrix W until the changes between consecutive iterations fall below a threshold (0.01), indicating convergence. It repeatedly fits a model to training data, reshapes coefficients into W, and checks for stopping criteria based on wei... | def train(self, num_examples):
"""
Does a linear regression to produce new W
"""
W_old = -np.copy(self.W)
replay_buffer = self.make_replay_buffer(num_examples)
X_train = self.make_training_set(replay_buffer)
while True:
targets = self.make_targets(repl... |
def get_HTML(q):
# Obtain the source HTML of the relevant search page
url = get_URL(q)
page = urlopen(url)
html = page.read()
soup = BeautifulSoup(html,'html.parser')
# THIS IS FOR TESTING AND DEBUGGING PURPOSES!!!
# Save the source HTML code to a local file for easy reading and debuggi... | This code retrieves Japanese translations and furigana for a given query by parsing HTML results. It checks for search errors, extracts translation text, replaces kanji with furigana for kana output, counts search results, and saves formatted results to a file with console output. | def get_translation(q):
soup = get_HTML(q)
# SEARCH VALIDATION SECTION-------------------------------------------------------
# Check to see if the "Sorry, couldn't find anything matching ___" div is there
# If it is, it means that either the query isn't a real word or there no Japanese translation... |
def write_msg_file(self, data):
contact = sorted(set([data['source']] + data['target']))
hash_object = hashlib.md5(''.join(contact).encode('utf8'))
with open('data/' + str(self.Id) + '/' + hash_object.hexdigest(), 'a+')\
as msgF:
msgF.write(json.dumps(data) + '\n')
de... | This function processes incoming messages by managing contacts, writing messages to files, handling file/recording transfers, and triggering actions like shaking or playing sounds. It checks if a contact is active, updates the UI, moves files to user-specific directories, and plays a sound for notifications. | def deal_msg(self, data):
contact = sorted(set([data['source']] + data['target']))
self.write_msg_file(data)
# Check active chat.
if contact == sorted(set(self.presentContact + [self.Id])):
self.show_msg(data)
else:
contactBtn = self.add_contact(sorted... |
def initUI(self):
self.addFriendBtn= QPushButton(' Add friend')
self.addFriendBtn.setIcon(QtGui.QIcon('resources/add.png'))
self.addFriendBtn.setIconSize(QtCore.QSize(25, 25))
self.addFriendBtn.setFixedSize(140, 30)
self.addFriendBtn.clicked.connect(self.add_friend_btn_clicked)... | The code initializes an object with a unique ID, sets up directory structures for data storage (contacts, files, recordings), initializes the UI, loads contact information, and starts a message receiver on port 7070 to handle incoming data. | def __init__(self, Id):
super().__init__()
self.Id = Id
self.presentContact = []
self.initUI()
self.read_contact_file()
idDir = 'data/' + str(self.Id) + '/'
idFileDir = 'data/' + str(self.Id) + '/files/'
idRecordingDir = 'data/' + str(self.Id) + '/recordi... |
def read_config(self, config_path):
config = {
"metadata":[],
"plugins":[],
"handles":[],
"workflow":[]
}
current_field = None
current_line = None
with open(config_path) as handle:
for line in handle:
... | The code initializes a class with configuration data from a specified file path. It reads the config, sets metadata, plugins, handles, and workflow attributes, then checks if all plugins require necessary metadata. | def __init__(self, config_path):
self.metadata = None
self.plugins = None
self.handles = None
self.workflow = None
self.current_sequence = None
config = self.read_config(config_path)
self.set_metadata(config["metadata"])
self.set_plugins(config["plugin... |
def get_data(self, df):
"""Calls functions 'formatting' to correct typos."""
self.get_index()
parameters['question'].append(formatting(df['question'][parameters['index'][-1]]))
print("parameters['question']", parameters['question'][-1])
parameters['correct'].append(formatting(df... | The code initializes a GUI application to display and interact with quiz questions fetched from a URL. It loads JSON data into a DataFrame, sets up a window with styled labels, buttons, and a score tracker, and arranges elements using a grid layout to create an interactive quiz interface. | def __init__(self, lvl_url, lvl_name):
super().__init__()
with urlopen(lvl_url) as webpage:
print(lvl_url)
data = json.loads(webpage.read().decode())
self.df = pd.DataFrame(data['results'])
# print(df['question'])
# print(df.head())
... |
def worldToMap(self, world_x, world_y, map_origin_x, map_origin_y, map_resolution):
"""
Converts the coordinates of a world point to the grid coordinates.
Args:
world_x (int): x_coordinate of the world point to convert.
world_y (int): y_coordinate of the world point to c... | The function processes a service request to navigate the robot to a relative point. It calculates the absolute goal coordinates using the robot's current position and orientation, checks if the goal is within the map's boundaries and not obstructed, then approves or rejects the request. If approved, it temporarily adds... | def callback_go_to_relative_point_srv(self, req):
"""
Callback for go_to_relative_point_srv service: Sends the robot to the coordinates (in meters and relative to the robot)
specified in the request message.
Args:
req: go_to_relative_point request message. {x(float), y(float... |
def createPosesSequence(self, places, isSetCurrentPlace):
"""
Given a list of known places it creates a set of poses corresponding to the position and orientation of each
place.
Args:
places (list): List of places to create the set of poses.
isSetCurrentPlace (bo... | This function handles a service request to navigate to a specified place. It uses either direct navigation (graph=0) or graph-based shortest path routing (graph=1) to determine the route. If valid, it sends the destination or route to the action client and returns 'approved'; otherwise, it returns 'not-approved' for in... | def callback_go_to_place_srv(self, req):
"""
Callback for go_to_place_srv service: If graph is 0, send the objective directly to the action client.
If, on the contrary, graph is 1, it maps the place of origin and finds the shortest route between it
and the target place and sends each pl... |
def publish_simple_feedback(self, time):
"""
SimpleFeedback publishes the navigation_status for the time (in seconds) specified by parameter.
Args:
time (int): Time for wich it must be published in seconds.
"""
duration = rospy.Duration(time)
beginTime = ros... | The main task of the code is to handle status updates from a move_base action client, logging navigation status, retrying failed goals, sending subsequent goals in a sequence, generating random targets if enabled, and managing error states like cancellations or rejections, while updating feedback and system status acco... | def callback_done(self, status, result):
"""
Callback for status change of the action client: Prints information related to the status on the goal sent to the
move_base action. Also if the goal was reached checks if all the goals in poses_sequence were sent and if not it
send the remain... |
def getOppositePossibleMoves(self):
# get all opposite player moves
self.whiteToMove = not self.whiteToMove # swap players move
oppositeMoves = self.getPossibleMoves()
self.whiteToMove = not self.whiteToMove # swap players move
return oppositeMoves
def checkExist(self, opposite... | This function checks if a checkmate exists by iterating through possible moves, simulating each move, and verifying if the opponent can escape check. If no valid escape moves remain or the last move captures a protected piece, it returns True, indicating checkmate. | def mateExist(self, moves):
# check if check-mate exists
for i in range(len(moves) - 1, -1, -1):
bol = True
startMove = self.board[moves[i].startRow][moves[i].startCol]
endMove = self.board[moves[i].endRow][moves[i].endCol]
self.board[moves[i].startRow][mo... |
def calculate_avg_ear(landmarks, left_eye_idxs, right_eye_idxs, image_w, image_h):
# Calculate Eye aspect ratio
left_ear, left_lm_coordinates = get_ear(landmarks, left_eye_idxs, image_w, image_h)
right_ear, right_lm_coordinates = get_ear(landmarks, right_eye_idxs, image_w, image_h)
Avg_EAR = (left_ear ... | The code processes a video frame to detect drowsiness by calculating the Eye Aspect Ratio (EAR) using facial landmarks. If EAR falls below a threshold, it accumulates time; if this duration exceeds a设定 delay, it triggers an alarm. The frame is annotated with EAR values, drowsy time, and color-coded alerts. It returns t... | def process(self, frame: np.array, thresholds: dict):
"""
This function is used to implement our Drowsy detection algorithm
Args:
frame: (np.array) Input frame matrix.
thresholds: (dict) Contains the two threshold values
WAIT_TIME and EAR_T... |
def init_gen(pop_size, selection_method, mutation_rate, elitism_perc, run_name, unit_list, sequence_list, spear_thresh, run_label):
'''
Create initial population
Parameters
-----------
pop_size: int
number of individuals in the population
selection_method: str
Type of selection ... | The code executes a genetic algorithm (GA) to evolve molecular structures, managing both initial runs and restarts. It initializes or reloads parameters, random states, and directories, then evaluates generations until convergence (based on `spear_thresh` and `conv_gen`). If not converged, it evolves the next generatio... | def main(pop_size, selection_method, mutation_rate, elitism_perc, spear_thresh, conv_gen, run_label, run_name, first_run, current_gen):
# Create list of possible building block unit SMILES in specific format
unit_list = utils.make_unit_list()
# Create all possible numerical sequences for hexamers with 1 or... |
def send_close(self, code=None, reason=None):
with self.SendLock:
if not self.CloseSent:
body = b''
if code is not None:
body = struct.pack('!H', code)
if reason:
body = body + reason.encode("utf-8")
... | This method closes a connection by sending a close signal, waiting for confirmation, and then shutting down. It checks if the instance is already closed; if not, it sends the close message, waits for the 'CloseReceived' flag to be set, and calls shutdown. If already closed, it does nothing. | def close(self, code=1000, reason=None):
#print("call close()")
if not self.Closed:
self.send_close(code, reason)
while not self.CloseReceived:
self.recv_fragment()
#print("close received")
self.shutdown()
#print("closed")
... |
def closed(self):
return self.CloseReceived or self.Closed
def peek(self, timeout=0):
if self.closed():
raise EOF("Websocket has been closed")
with self.RecvLock:
saved_timeout = self.Sock.gettimeout()
self.Sock.settimeout(timeout)
try:
... | This function receives and assembles WebSocket messages by handling data fragmentation, determining message type (binary/text), enforcing timeout constraints, and managing connection closure. It collects message fragments, decodes text data, and returns the final payload while raising exceptions for EOF or timeout erro... | def recv(self, timeout=None):
#print("recv(): Closed=", self.Closed)
with self.RecvLock:
if self.closed():
raise EOF("Websocket has been closed")
fragments = []
final = False
eof = False
binary = None
first_fragment ... |
def XYcoordinatesMove3(PodMatrix):
aisles = [0, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 37]
crossaisles = [0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90]
while True:
YCoordinate = random.randint(1,36)
XCoordinate = random.randint(1,89)
PodValue = PodMatrix[YCoor... | The function calculates the distance between a warehouse location (Xws, Yws) and a pod matrix position (x, y) based on directional logic. It determines travel direction (aisle or cross-aisle) and applies case-specific distance formulas (Case 1-4) depending on whether the location aligns with the travel direction. Retur... | def DistanceCalculator_Move3(Xws,Yws, Location, PodMatrix): # Coordinates of WS, location (east/west/south/north)
Move3 = XYcoordinatesMove3(PodMatrix)
x = Move3[0]
y = Move3[1]
PodMatrix = Move3[2]
AisleTravelDirection = AisleInformation(y)[1]
if Location == 'West' or Location == 'East':
... |
def XYcoordinatesMove1(PodMatrix):
aisles = [0, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 37]
crossaisles = [0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90]
while True:
while True:
XCoordinate = random.randint(1,89)
if XCoordinate in crossaisles:
... | This function calculates the distance between a workstation (WS) and a pod (POD) based on their coordinates, aisle directions, and specified location (West/East/North/South). It uses conditional logic to determine the appropriate distance calculation case (1-4) depending on alignment of the POD's aisle direction with t... | def DistanceCalculator_Move1(Xws,Yws, Location, PodMatrix):
Move1 = XYcoordinatesMove1(PodMatrix)
x = Move1[0]
y = Move1[1]
PodMatrix = Move1[2]
AisleTraveldirectionPOD = AisleInformation(y)[1]
AisleTravelDirectionWS = AisleInformation(Yws)[1]
if Location == 'West' or Location == 'East':
... |
def send_rip_packets(self):
"""
Sends RIP packets to all the output ports.
"""
message = self.create_rip_packet()
send_socket = self.input_sockets[0]
for port in self.router.get_outputs():
try:
send_socket.sendto(message, (LOCAL_HOST, port))
... | The main task of the code is to implement the RIP protocol's continuous operation by sending routing packets, receiving updates, checking timeout entries, and managing route timers to maintain an accurate routing table. The infinite loop ensures periodic updates and validation of network routes. | def rip_protocol(self):
"""
The main RIP protocol loop.
"""
self.send_rip_packets()
while(1):
self.routing_table.print_table()
self.receive_packets()
self.check_timeout_entries_periodically()
self.check_route_timers(... |
def __get_drop_row_index(self, board, column_index):
# This returns the index a piece would fall to if dropped at this column.
column = board[:, column_index]
row_index = None
for x in range(0, column.size):
if column[x] == '-':
row_index = x
else... | This function evaluates potential moves in a game using the Minimax algorithm with alpha-beta pruning. It assesses a given column's validity, determines the player's turn, and recursively explores the game tree to find the optimal move. For the maximizing player (AI), it selects the best move by maximizing scores, whil... | def __evaluate_move_minimax(self, board, column_index, tree_depth, is_enemy, alpha, beta):
# Determine whether or not this column has an open space
available_row_index = self.__get_drop_row_index(board, column_index)
if available_row_index is not None:
# Determine which player this ... |
def cross_combos(self, *args) -> tuple[tuple[str,...], ...]:
"""
Takes unspecified number of arguments, where arg[i] is 2d sequence
Returns cartesian product of args
Example:
- cross_combos(((a,b), (a,c)), ((d,e), (d,f))) -> ((a, b, d, e), (a, b, d, f), (a, c, d, e), (a, c, d... | (The function generates all possible combinations of guards and forwards, excluding the center, by cross-combining them into tuples of length 8, representing lineups without a central player.) | def no_center(self) -> tuple[tuple[str,str,str,str,str,str,str,str], ...]:
"""
Creates tuples of len() = 8, where all parts of lineup but center
"""
return self.cross_combos(self.guards(), self.forwards()) |
def cross_combos(self, *args) -> tuple[tuple[str,...], ...]:
"""
Takes unspecified number of arguments, where arg[i] is 2d sequence
Returns cartesian product of args
Example:
- cross_combos(((a,b), (a,c)), ((d,e), (d,f))) -> ((a, b, d, e), (a, b, d, f), (a, c, d, e), (a, c, d... | (The code generates valid basketball lineups by combining player combinations across positions, ensuring salary constraints for centers (minimum $4,800) and other positional rules, then validating each lineup with a checker. It returns all compliant lineups as nested tuples.) | def lineups(self) -> tuple[tuple[str,str,str,str,str,str,str,str,str], ...]:
"""
Creates full lineups with all position constraints satisfied
"""
# Center never lt 5_000
centers = tuple([name for name in self.players['C'] if self.checker.pvalue(name, 'salary') >= 4_800]) if not... |
def cost(self, names: tuple[str,...]) -> int:
"""
Returns the cost of players in names
"""
return self.rc_sumvalues(names, 'salary')
def n_teams(self, names: tuple[str,...]) -> int:
"""
Returns the total number of teams present for players in names
"""
ret... | This function checks if four players are compatible for a team by ensuring their total cost does not exceed a maximum limit, they are not all from the same team, and they satisfy teammate rules. It returns True if valid, False otherwise. | def check4(self, names: tuple[str,str,str,str]) -> bool:
"""
Checks to make sure 4 players are good together, duplicates already checked
Checks involved here:
- Teammate rules
- Affordability
Will be PG/SG/SF/PF
"""
if self.PAST:
retur... |
def cost(self, names: tuple[str,...]) -> int:
"""
Returns the cost of players in names
"""
return self.rc_sumvalues(names, 'salary')
def n_teams(self, names: tuple[str,...]) -> int:
"""
Returns the total number of teams present for players in names
"""
ret... | The main task of the code is to verify if four players are compatible based on affordability (total cost ≤ five_max_cost) and team diversity (must belong to more than one team). It enforces teammate rules by checking if they are not all from the same team and ensures the group's total cost adheres to a specified maximu... | def check5(self, names: tuple[str,str,str,str]) -> bool:
"""
Checks to make sure 4 players are good together, duplicates already checked
Checks involved here:
- Teammate rules
- Affordability
Will be PG/SG/SF/PF/C
"""
if self.PAST:
ret... |
def cost(self, names: tuple[str,...]) -> int:
"""
Returns the cost of players in names
"""
return self.rc_sumvalues(names, 'salary')
def n_teams(self, names: tuple[str,...]) -> int:
"""
Returns the total number of teams present for players in names
"""
ret... | The main task of the code is to verify if four players form a valid team by checking affordability (cost constraints) and teammate rules. It ensures the team's total cost does not exceed a maximum limit, avoids single-team compositions, and adheres to predefined team compatibility rules. The function returns `True` if ... | def check6(self, names: tuple[str,str,str,str]) -> bool:
"""
Checks to make sure 4 players are good together, duplicates already checked
Checks involved here:
- Teammate rules
- Affordability
Will be PG/SG/SF/PF/C/G
"""
if self.PAST:
r... |
def cost(self, names: tuple[str,...]) -> int:
"""
Returns the cost of players in names
"""
return self.rc_sumvalues(names, 'salary')
def n_teams(self, names: tuple[str,...]) -> int:
"""
Returns the total number of teams present for players in names
"""
ret... | The function checks if four players are compatible by verifying affordability (cost limit) and team diversity (minimum 3 teams). It returns True if the group meets these criteria, ensuring valid team composition and cost constraints are satisfied. | def check7(self, names: tuple[str,str,str,str]) -> bool:
"""
Checks to make sure 4 players are good together, duplicates already checked
Checks involved here:
- Teammate rules
- Affordability
Will be PG/SG/SF/PF/C/G/F
"""
if self.PAST:
... |
def n_teams(self, names: tuple[str,...]) -> int:
"""
Returns the total number of teams present for players in names
"""
return len(set(self.teams(names)))
def cost(self, names: tuple[str,...]) -> int:
"""
Returns the cost of players in names
"""
return sel... | The function `check4` verifies if four players are compatible by ensuring they aren't all from the same team, their combined cost doesn't exceed a limit, and they adhere to teammate rules. It returns `True` if all checks pass, otherwise `False`. Key validations include team distribution, affordability, and teammate com... | def check4(self, names: tuple[str,str,str,str]) -> bool:
"""
Checks to make sure 4 players are good together, duplicates already checked
Checks involved here:
- Teammate rules
- Affordability
"""
# Technically possible but extremely unlikely to have all f... |
def cost(self, names: tuple[str,...]) -> int:
"""
Returns the cost of players in names
"""
return self.rc_sumvalues(names, 'salary')
def teams(self, names: tuple[str,...]) -> tuple[str,...]:
"""
Returns tuple of teams for each player
"""
return self.pvalue... | The code checks if eight player names form a valid lineup by verifying cost constraints, team distribution (no team exceeding 4 players), and other criteria like teammates and salaries. It returns True if all conditions are met, with past lineups only requiring cost and team checks. | def check8(self, names: tuple[str,str,str,str,str,str,str,str]) -> bool:
"""
Checks to make sure 8 players are good together, including checking for duplicates
For past, only checking if eligible lineups
"""
if self.PAST:
# if self.cost(names) > self.eight_max_cost:
... |
def follows_rules(self, names: tuple[str,str,str,str,str,str,str,str,str]) -> bool:
"""
Follows contest rules, added to below for now
"""
# return self.check9(names)
teams = self.teams(names)
return self.mincost <= self.cost(names) <= self.maxcost and max([teams.count(tea... | This function checks if nine players are compatible by verifying rules, team affiliations, game eligibility, and teammate relationships, ensuring no duplicates. It returns True if all conditions are met, otherwise False. | def check9(self, names: tuple[str,str,str,str,str,str,str,str,str]) -> bool:
"""
Checks to make sure 9 players are good together, including checking for duplicates and cost
"""
if self.PAST:
# PAST only cares about if rules are followed
return self.follow... |
def _get_backingstore(self):
"""
Backing store is now influenced by the caller more than the file. Setting
Return the backingStore: of the parsed yaml object. In most cases the file
key was not set anyway - since vault was the only supported option. Since
we are introducing new o... | The code validates the structure and configuration of secrets in a system. It checks for mandatory fields like 'name', ensures valid formats for 'vaultPrefixes', 'targetNamespaces', 'labels', and 'annotations', verifies non-empty fields, and detects duplicate secret names or field names. It returns errors for invalid c... | def _validate_secrets(self):
backing_store = self._get_backingstore()
secrets = self._get_secrets()
if len(secrets) == 0:
self.module.fail_json("No secrets found")
names = []
for s in secrets:
# These fields are mandatory
for i in ["name"]:
... |
def sanitize_values(self):
"""
Sanitizes the secrets YAML object version 2.0
Parameters:
Returns:
Nothing: Updates self.syaml(obj) if needed
"""
v = get_version(self.syaml)
if v not in ["2.0"]:
self.module.fail_json(f"Version is not 2.0: ... | The code parses and processes secrets by sanitizing values, retrieving configurations, and generating Kubernetes secret objects. It iterates through secrets, injects fields, applies policies, and creates Kubernetes secrets based on the backing store type, returning the total number of processed secrets. | def parse(self):
self.sanitize_values()
self.vault_policies = self._get_vault_policies()
self.secret_store_namespace = self._get_secret_store_namespace()
backing_store = self._get_backingstore()
secrets = self._get_secrets()
total_secrets = 0 # Counter for all the secre... |
def __conv_bn_layer(self, input_layer, shape, strides=None, use_bn=True):
if strides is None:
strides = [1, 1, 1, 1]
_conv = self.__convolution_layer(input_layer, shape=shape, strides=strides)
if use_bn:
return self.__batch_norm(_conv)
else:
return tf.... | The code defines a convolutional neural network (CNN) model for classification tasks. It constructs multiple convolutional layers with batch normalization, max-pooling, and dropout for regularization. The output is flattened and processed through fully connected layers with batch normalization and dropout. The model co... | def build_model(self):
self.is_training = tf.placeholder(tf.bool)
self.x = tf.placeholder(tf.float32, shape=[None] + self.config.state_size)
self.y = tf.placeholder(tf.float32, shape=[None, 10])
self.hold_prob_conv = tf.placeholder(tf.float32)
self.hold_prob_fc = tf.placeholder(... |
def connect(readerIP,readerPort):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP)
s.connect((readerIP, readerPort))
return s
except Exception as ex:
addLogFunc(whoami(),str(ex))
return (0)
def CheckDigit(a, b, c):
i = a + b + c + 413
if i < 255:
i = 256 - i
elif i < 511:
i ... | The main task of the code is to send formatted data to a remote device via a socket connection. It pads the input data with null bytes, splits it into 2-byte chunks, constructs a command with check digits, and sends each chunk. It handles errors, logs exceptions, and returns responses or warnings. If successful, it cal... | def writeData(data, readerIP, readerPort):
s = connect(readerIP,readerPort)
if s:
try:
print("WRITE DATA")
if data == "":
return "WARNING: PLEASE ENTER SOME DATA IN THE TEXT BOX"
for i in range(12-len(data)):
data = data + chr(0)
for j in range(6):
b2 = (data[j*2])
b1 = (data[j*2+1])
... |
def connect(readerIP,readerPort):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP)
s.connect((readerIP, readerPort))
return s
except Exception as ex:
addLogFunc(whoami(),str(ex))
return (0)
def writeData(data, readerIP, readerPort):
s = connect(readerIP,readerPort)
if s:
try:
... | The main task of the code is to write data to a remote server via a socket connection. It prepends a control character (chr(1)) to the input data, sends it, and checks if the server returns the same data. If successful, it returns a confirmation; otherwise, it returns warnings or error messages for empty input, transmi... | def patronWrite(data1, readerIP, readerPort):
s = connect(readerIP,readerPort)
if s:
try:
data = chr(1) + data1
ret = writeData(data, readerIP, readerPort)
if data == chr(1):
return ("WARNING: PLEASE ENTER SOME DATA IN THE TEXTBOX")
if ret == data:
return ("SUCCESS: WRITTEN "+ret)
else:
... |
def loadFile(self,filename):
#f = open(filename, "r")
f = open(filename, 'r', encoding='latin-1')
sTxt = f.read()
f.close()
return sTxt
def tokensize(self,sText,doc_class):
#splitting the text in file
stop_words = set(stopwords.words(... | The main task of the code is to process a training dataset by categorizing reviews into positive and negative classes based on filenames, tokenizing the text, and calculating prior probabilities for a classification model. It lists files in the "testing/" directory, separates them into positive/negative lists using fil... | def train_set(self):
trainDir = "testing/"
lFileList = []
for fFileObj in os.walk("testing/"):
lFileList = fFileObj[2]
break
print(" Total training reviews",len(lFileList))
#creating list of positive and negative reviews
positive_list=[]
... |
def detect(files):
threshold = 50
id_files = id(files)
time_cut = time.time()
print('=============== Begin ==================')
cut(files)
time_cut = time.time() - time_cut
print('===============Time Cut==================')
print(time_cut)
print('----------------------------------... | The code processes input files by detecting features, generating unique identifiers, rendering outputs in axial, coronal, and sagittal views, and returning a success status, detected data, and directory paths for rendered results. | def predict(files):
output = detect(files)
idFile = id(files)
render(output[1], output[2], idFile)
status = True
dirOutput = [
f'{file_save_path}/render/{idFile}/axial/',
f'{file_save_path}/render/{idFile}/coronal/',
f'{file_save_path}/render/{idFile}/sagittal/'
... |
def retrieve_instructions(self, process_list):
self.select_process(self.optimization_target, -1, process_list)
while self.required_stock:
required_name = next(iter(self.required_stock))
if not self.select_process(required_name, self.required_stock[required_name], process_list):
... | The code initializes a class to manage stock optimization, copying initial stock data, setting up data structures for tracking stock requirements and instructions, retrieving process instructions, finalizing processes within a cycle limit, and calculating an initial score to evaluate optimization progress toward a defi... | def __init__(self, initial_stock, optimization_target, process_list, max_cycle, max_instructions):
self.optimization_target = optimization_target
self.process_list = process_list
self.max_instructions = max_instructions
self.current_stock = initial_stock.copy()
self.updated_stock... |
def get_class_doc(klass, config=default_config):
"""Return doc for a class."""
if config.exclude_class:
for ex in config.exclude_class:
if ex.match(klass.__name__):
return None
nested_doc = []
class_dict = klass.__dict__
for item in dir(klass):
if item i... | The function `get_module_doc` generates documentation for a Python module, including its submodules, classes, and functions. It avoids recursion by tracking processed items and excludes modules specified in the config. It parses the module's source code to identify and exclude imported items, then recursively processes... | def get_module_doc(module, config=default_config, already_met=None):
"""Return doc for a module."""
# Avoid recursion loops (init)
if already_met is None:
already_met = set()
if config.exclude_module:
for ex in config.exclude_module:
if ex.match(module.__name__):
... |
def read_images(folder):
images = []
for filename in os.listdir(folder):
img = cv2.imread(filename,0)
if img is not None:
images.append(img)
return images
def find_all_points(cut_img):
dst = cv2.goodFeaturesToTrack(cut_img, 200, 0.0001, 10)
dst = np.int0(dst[:, 0])
re... | The code processes images by detecting edges and specific points (e.g., 1-9) using filters and custom functions. It visualizes these points on colorized images, draws shapes based on the points, and saves coordinates to Excel files. The task involves image segmentation, feature extraction, and data storage for hand sha... | def main():
images=read_images(path)
for index,img in enumerate(images):
m,n=img.shape
color_img=cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
cut_img = cv2.bilateralFilter(img, 11, 150, 150)
cut_img = cv2.Canny(cut_img, 50, 120)
points=find_all_points(cut_img)
point_7=fin... |
def find_all_points(cut_img):
dst = cv2.goodFeaturesToTrack(cut_img, 200, 0.0001, 30)
dst = np.int0(dst[:, 0])
return dst
def find_7(cut_img):
dst = cv2.goodFeaturesToTrack(cut_img, 25, 0.005, 20)
dst = np.int0(dst[:, 0])
m,n=cut_img.shape
point=find_closest_point(dst,(n*1/2,m*2/3))
retu... | The code processes images to detect and visualize specific points (e.g., 1-9) using edge detection and custom functions. It converts grayscale images to color, applies bilateral filtering and Canny edge detection, identifies key points, and draws them with distinct markers. The detected points are then used to construc... | def part_two(images):
for img in images:
m,n=img.shape
color_img=cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
cut_img = cv2.bilateralFilter(img, 11, 150, 150)
cut_img = cv2.Canny(cut_img, 50, 120)
#cut_img = cv2.bilateralFilter(img, 11, 150, 150)
#cut_img = cv2.Canny(cut_img... |
def log(string):
if not this.siltent_log:
print(string)
def get_memory_usage():
log(f"RAM Used (GB): {psutil.virtual_memory()[3] / 1000000000}")
return psutil.virtual_memory()[3] / 1000000000
def get_starmap_strategies(data_cache, buy, sell, brange, srange, single_strat, agg):
log("generating st... | The function `run` processes financial data by fetching historical price data, generating trading strategies (CPU/GPU), executing them, and analyzing results to return strategy performance metrics, including memory usage and execution time. | def run(data_cache, src, symbol, start, end, days, include_partial_today, cpu, buy, sell, brange, srange, single_strat, tdelta, set_siltent_log=False, pregenerated_strategies=None, agg=0):
this.siltent_log = set_siltent_log
data_cache.poll_data(
src,
symbol,
start,
end,
d... |
def get_skip_today_value(self, include_partial_today, start_hour, end_hour):
current_hour = datetime.now().hour
skip_today = (
True
if not include_partial_today
and current_hour >= start_hour
and current_hour < end_hour
else False
)
... | The function retrieves financial data from either a cache or a source (yfinance/AWS), based on parameters like symbol, time range, and caching rules, then stores the data in an instance variable and a pickle file for future use. | def poll_data(
self, source, symbol, start_hour, end_hour, days, include_partial_today, overwrite=False, tdelta=0
):
if self.data is not None and not overwrite:
return
skip_today = self.get_skip_today_value(include_partial_today, start_hour, end_hour)
file_name = self.get... |
def angle_to_centerline(pose: np.ndarray, centerline: np.ndarray):
points = centerline[:, :2]
closest_idx = get_closest_idx(pose, centerline)
next_idx = (closest_idx + 1) % len(centerline)
centerline_angle = np.arctan2(
*(points[next_idx] - points[closest_idx])[::-1])
raw_angle_diff = pose[2... | The function `transform_state` processes the environment state to generate a feature vector for an agent. It extracts the ego-vehicle's position, velocity, acceleration (from previous state), angle to the centerline, LiDAR scans, previous steering input, collision status, and future curvature values along the centerlin... | def transform_state(env: F1EnvWrapper, state, prev_state=None, prev_action=None):
idx = state["ego_idx"]
pose = np.array([state[s][idx]
for s in ["poses_x", "poses_y", "poses_theta"]])
pose[2] = np.mod(pose[2], 2 * np.pi)
vel = np.array([state[s][idx] for s in ["linear_vels_x", "line... |
def writeToIntermediateFile(fileno):
global inverted_index
global lif
lif=int(fileno)
filename="index_files/intermediate_files/"+fileno+".txt"
print("Writing into intermediate file ",fileno)
try:
f=open(filename,'x')
except FileExistsError:
f=open(filename,'w')
for word,value in sort... | The code processes each document by incrementing a global counter, extracting metadata (docId, title, content), writing intermediate files at intervals defined by DOCSPERINTERMEDIATE, and returning a processed dataframe from content analysis. It delegates title and content processing to separate functions, ensuring str... | def process(elements):
global docsParsed
docsParsed+=1
docId=elements.docId
title=elements.title
content=elements.text
if(docId % DOCSPERINTERMEDIATE == 0 and docId>0):
writeToIntermediateFile(str(int(docId/DOCSPERINTERMEDIATE)))
process_title(title,docId)
df=process_content(content,docId)... |
def get_with_caching(command, function):
if command in response_cache:
tic, response = response_cache.get(command)
if time.time() - tic < LAG:
return response
response = function()
update_cache(command, response)
return response
def get_volume(leading_text=True, nb_top=3):
... | The function `generate_text_response` processes user input to determine the command and returns appropriate responses for a Coinmetro bot. It handles commands like `/help`, `/volume`, `/topvolume`, `/sentiment`, `/admin`, and `/code`, providing data, links, or messages. It validates arguments (e.g., checking numerical ... | def generate_text_response(message_part):
response = None
command = match_command(message_part)
if command is Command.START:
return "Hey, I'm an unofficial bot for Coinmetro. Use the /help " \
"command to see an overview of currently available commands."
elif command is Command.HE... |
def fetch_latest(self, max_pages=5) -> List[BookmarkRecord]:
latest_bm = self.db.get_latest_bookmark(self.uid)
start_time = self.since
if latest_bm is not None and latest_bm["pocket_created_at"]:
start_time = latest_bm["pocket_created_at"]
start_timestamp = None
if start_time:
start_tim... | The main task of the code is to synchronize the latest items by fetching their associated text and metadata resources, then saving all updated items together. It ensures data integrity by only saving records if no errors occur during the process, returning the total number of items processed. | def sync_latest(self) -> int:
items = self.fetch_latest()
# Fetch urls
resources = self.fetch_resources(items)
for item in items:
pocket_item_id = item["pocket_item_id"]
if pocket_item_id in resources:
self.logger.debug(f"adding text for {pocket_item_id}")
item["text"] = res... |
def setup_logger():
"""Set up the logger"""
logging.basicConfig(
level=logging.INFO, format="%(asctime)s %(name)s %(message)s"
)
def draw_map():
"""Draw the map!"""
# Define the projection, scale, the corners of the map, and the resolution.
base_map = mpl_toolkits.basemap.Basemap(
... | The main task of the code is to initialize logging, generate a map visualization, and create a GIF from the visualized data. The `setup_logger()` function configures logging, `draw_map()` produces a map, and `create_gif()` compiles the output into an animated GIF, likely for data presentation or analysis. | def main():
setup_logger()
draw_map()
create_gif() |
def parseForLinks(self, url):
try:
data = requests.get(url, verify=False, headers={'User-agent': 'yogurt 0.1'})
except UnicodeError:
print("Couldn't connect to "+url)
return 0
if data.status_code == 200:
print("Connection successful !")
els... | The code's main task is to launch a web crawler that scans URLs, extracts forms and GET parameters, and iteratively processes new URLs in passes. It initializes by parsing the start URL, then enters a loop where it checks for forms/GET args, prompts user confirmation, and scans additional URLs. Each pass clears prior d... | def launchCrawler(self):
self.visitedurls.add(str(self.start.split("?")[0]))
self.parseForLinks(self.start)
self.parseForForms(self.start)
# Call payloads.py on the forms and other gathered data
while 1:
if len(self.forms) > 0:
print("\nExample form :\... |
def initialize_weights():
W_2 = np.random.uniform(-1,1,(HIDDEN_NEURONS,INPUT_NEURONS))
W_3 = np.vstack(np.random.uniform(-1,1,(OUTPUT_NEURONS,HIDDEN_NEURONS)))
return W_2, W_3
def forward_pass(input_data,W_2,W_3):
A1 = calculate_A(input_data,INPUT_NEURONS)
X2 = np.matmul(W_2,A1)
A2 = calculate_... | This code trains a neural network with two hidden layers using gradient descent to minimize mean squared error (MSE) over training data. It initializes weight matrices, iterates through epochs, performs forward passes, calculates errors, computes gradients, updates weights with the learning rate, tracks MSE every 200 e... | def training(max_epochs,training_inputs,expected_outputs,learning_rate):
num_of_epochs = 0
epoch_inc_200 = 0 # 200 epochs increment
# initialize and assign weight matrices
weight_matrices = initialize_weights()
W_2 = weight_matrices[0] # input-to-hidden layer weight matrix
W_3 = weight_matr... |
def place_image(self, img):
"""Method to place a image in the image frame.
Args:
img (str): The name of the file with the image.
"""
# https://www.c-sharpcorner.com/blogs/basics-for-displaying-image-in-tkinter-python
# https://stackoverflow.com/questions/32060837/rem... | The main task of the code is to initialize and start the Hangman game by placing the game image, setting up letter underscores, arranging letter buttons, and entering the main game loop for user interaction and gameplay progression. | def start_game(self):
"""Method to execute the app once.
"""
self.place_image("img/hangman.png")
self.set_underlines()
self.place_buttons()
self.main_loop() |
def _check_keydown_events(self, event):
if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
self.game_stats.save_high_score()
sys.exit()
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
if event.key == pygame.K_LEFT:
self.ship.moving_left = True
if event.key == pygame.K_SPACE:
... | This method processes Pygame events to handle user inputs: it quits the game and saves the high score on window close, delegates key presses/relases to specific methods, and checks for mouse clicks to trigger the play button, updating game state accordingly. | def _check_events(self):
"""Handles keyboard and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.game_stats.save_high_score()
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._che... |
def _check_fleet_edges(self):
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
if self.game_stats.ships_left > 0:
#Decrease ships left
self.game_stats.ships_left -= 1
self.sb.prep_ships()
#Delete all aliens and bullets
se... | The function updates alien positions, checks if the fleet has reached screen edges, detects collisions between the ship and aliens to trigger hit responses, and verifies if any aliens have reached the bottom of the screen. | def _update_aliens(self):
"""Checks if fleet has reached the edge of screen
and updates all alien positions"""
self._check_fleet_edges()
self.aliens.update()
#Checks collision of any alien with ship
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom() |
def _check_events(self):
"""Handles keyboard and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.game_stats.save_high_score()
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._che... | The code defines a method `run_game` that starts the game's main loop, continuously checking for events, updating game elements (ship, bullets, aliens) if the game is active, and rendering the screen to create an interactive gameplay experience. | def run_game(self):
"""Starts the main loop of the game"""
while True:
self._check_events()
if self.game_stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen() |
def get_season_name(year,prefix=True):
if prefix:
return('20'+str(year)+'-'+str(year+1))
else:
return(str(year)+'-'+str(year+1))
def dprint(*args):
if DEBUG:
print(*args)
return
def get_next_n_fixtures(standings, team_map_dict, bigdf, current_gw, n):
ret_list = []
dprint(... | The main task of the code is to process football (soccer) player data across multiple gameweeks, aggregate key performance statistics, and construct feature vectors for machine learning analysis. It merges game data with team mappings, calculates cumulative player metrics, and extracts features including historical per... | def main(season=16):
bigdf = pd.read_csv('data/2016-17/gws/gw1.csv',encoding='latin-1').head(1)
standings = pd.read_csv('data/standings/' + get_season_name(season, prefix=False) + '.csv', header=None, index_col=None)
team_mapping = pd.read_csv('data/master_team_list.csv',encoding='latin-1')
team_mappin... |
def git_current_branch(working_directory):
return run_process(["git", "branch", "--show-current"], working_directory)
def change_branch_func(cwd, branch_name):
def change_branch():
return git_checkout(cwd, branch_name)
return change_branch
def fetch_pull_func(cwd):
def fetch_pull():
result = git_fetch(cwd)
... | The code generates an HTML page with interactive links for repository and issue management tasks. It constructs a structured webpage containing headers, repository branches, and issue-specific actions like creating/changing branches, fetching pulls, and navigating to develop branches, using predefined functions stored ... | def get_html_content():
placeholder_issues = [Issue("1001", "issue_1"), Issue("1002", "issue_2")]
html_start = """
<html>
<body>
"""
html_end = """
</body>
</html>
"""
html_content = ""
html_content += "<h1>General</h1>"
for repository in REPOSITORIES:
html_content += "</br>"
html_content += "<h3... |
def initialize_log(filename,u0):
path = Path(filename)
log = []
if path.is_file():
interdict=load_object(filename)
for i in interdict:
u1=Login(i['uname'],i['pid'],i['signin'],i['signout'],i['ttotal'])
log.append(u1)
else:
log=[u0]
return log
def p... | The code manages user sign-in/sign-out operations, maintains a pool of active users, and logs activities. It presents a menu for users to select actions: signing in (adding to the pool), signing out (removing from the pool), or accessing an admin menu. Logs are updated and saved after each action, while the user pool i... | def main():
options=[1,2,9987]
u0=Login("Shade","0303",datetime.now().replace(microsecond=0),datetime.now().replace(microsecond=0)+timedelta(hours=3),timedelta(hours=3))
log=list((initialize_log('log.json',u0))) # initialize log list
pool=set(pool_load("pool.json")) # initialise the set of signed in nam... |
def run_practice_mode(self):
while self.mode == "practice":
audio = self.get_audio_block()
text = self.audio_to_text(audio)
print('my text: ',text)
self.detect_command(text)
if self.command:
if self.command == 'stop':
... | The code's main task is to execute either "practice" or "conversation" modes in a loop while `self.mode` is active, then terminate by speaking "good bye". It repeatedly runs the corresponding mode method based on `self.mode`'s value until `self.mode` becomes falsy, ensuring continuous operation in the selected mode unt... | def run(self):
## if not self.mode
while self.mode:
if self.mode == "practice":
self.run_practice_mode()
if self.mode == "conversation":
self.run_conversation_mode()
self.speak("good bye")
return |
def menu_use_card(player, enemy):
print(read_current_deck(player))
chosen_card = input_index("> Enter index of card to use: ", player.current_deck)
print(read_dice(player))
chosen_dice = input_index("> Enter index of dice to use: ", player.current_dice)
try:
if chosen_dice not in chosen_ca... | The code defines a turn-based combat menu system for a player to interact during a battle. It presents options to use cards, check player/enemy status, or end the turn. Based on user input, it executes corresponding actions like using cards, viewing status details, or breaking the loop to end the turn. The loop continu... | def menu_combat(player, enemy):
COMBAT_MENU = ["use card", "my status", "enemy status", "end turn"]
while True:
print(f"What will {player.name} do?")
print_delay()
# combat menu
print(COMBAT_MENU)
command = input_selection("> Enter command: ", COMBAT_MENU)
... |
def status_dice(character):
print(f"{character.name}'s dice: ")
print(read_dice(character))
def menu_combat(player, enemy):
COMBAT_MENU = ["use card", "my status", "enemy status", "end turn"]
while True:
print(f"What will {player.name} do?")
print_delay()
# combat menu
... | This function simulates a turn-based combat between a player and an enemy. It alternates between player and enemy turns, handling dice rolls, deck refreshes, status checks, and combat actions. The loop continues until an EndCombat exception is triggered, returning True if the enemy is defeated (HP=0) or False otherwise... | def combat_loop(player, enemy):
print(f"A wild {enemy.name} appears!")
print_delay()
try:
while True:
# player turn
player.turn_dice() # refresh player dice
player.turn_deck() # refresh player deck
print(f"{player.name}'s turn.")
print_de... |
def extract_self_if_method_call(args: List[Any], func: Callable) -> Optional[object]:
"""Check if this is a method rather than a function.
Does this by checking to see if `func` is the attribute of the first
(`self`) argument under `func.__name__`. Unfortunately, this is the most
robust solution to thi... | This function enqueues a request into a batch queue, handling both functions and methods. It extracts arguments, determines where to inject the batch queue (as an attribute of the function or object), applies dynamic configuration (max batch size, timeout) from the object/function's attributes, creates an asynchronous ... | def enqueue_request(args, kwargs) -> asyncio.Future:
self = extract_self_if_method_call(args, _func)
flattened_args: List = flatten_args(extract_signature(_func), args, kwargs)
if self is None:
# For functions, inject the batch queue as an
# attribute... |
def __draw_cell(self, i, j):
if self.window is not None:
self._cells[i][j].draw()
self.__animate()
def _break_entrance_and_exit(self):
if self.window is None:
return
self._cells[0][0].has_left_wall = False
self.__draw_cell(0, 0)
self._cells[se... | This method initializes a grid of cells for a maze, positions each cell, draws them, breaks walls recursively to generate paths, measures the time taken for wall-breaking, and resets visited flags. | def __create_cells(self):
self._cells = [[0 for _ in range(self.num_rows)] for _ in range(self.num_cols)]
for i in range(self.num_cols):
for j in range(self.num_rows):
next_p = Point(self.x1, self.y1) + Point(i * self.cell_size_x, j * self.cell_size_y)
cell =... |
def display_image_selector():
st.header("Image Selector")
st.write(descpr)
option = st.selectbox("Select an option", ["A", "B", "C", "D"])
image_path = image_selector(option)
image = Image.open(image_path)
st.image(image)
def display_chatbox():
st.subheader("Chatbox")
messages = []
... | The code defines a function `show_app()` that initializes an application by calling three components: `display_image_selector()` to show an image selection interface, `display_chatbox()` to create a chat interface, and `main()` to execute the core application logic. The primary task is to launch the app by setting up i... | def show_app():
display_image_selector()
display_chatbox()
main() |
def display_image_selector():
st.header("Image Selector")
st.write(descpr)
option = st.selectbox("Select an option", ["A", "B", "C", "D"])
image_path = image_selector(option)
image = Image.open(image_path)
st.image(image)
def display_chatbox():
st.subheader("Chatbox")
if "chat_history... | The main task of the code is to initialize and display an application interface by calling three functions: `display_image_selector()` to show an image selection component, `display_chatbox()` to present a chat interface, and `main()` to execute the core application logic. This structure sets up the app's UI and functi... | def show_app():
display_image_selector()
display_chatbox()
main() |
def find_baby_name_and_index_in_master(baby_id,master=master):
'''it scans all of the name of the babies in the master file and return the correct name and its index'''
baby_names = np.array(master['Study Number (Original)'])
found=False
for i in range(len(baby_names)):
if is_SameBaby(baby_id,ba... | This code initializes a baby object by loading clinical data and physiological measurements, processes timestamps, calculates statistical metrics (e.g., PR, SpO2, PI), identifies bradycardia episodes using thresholds, and stores results for analysis. It handles data cleaning, time calculations relative to birth, and ca... | def __init__(self, baby_id, babies=master, additional_info=master_complementary, verbose=False, warning=True):
'''Input the study number to initialise a baby, e.g. baby_id="FMC003" '''
self.verbose = verbose
self.warning = warning
self.baby_id = baby_id.upper()
self.data_found = ... |
def __upload_tar(self, path, decoder):
if verbose:
print('Uncompressing tar archive: %s' % path)
with tarfile.open(path, decoder) as tar:
for item in tar:
if item.isreg():
f = tar.extractfile(item)
dicom = f.read()
... | The main task of the code is to determine the file type based on its extension and decompress/upload it using the appropriate method. It checks for archive formats like .tar.bz2, .tar.gz, .zip, .tar, .bz2, .gz, and defaults to a general file upload if no specific format is matched. | def __decode_file(self, path):
extension = os.path.splitext(path)[1]
if path.endswith('.tar.bz2'):
self.__upload_tar(path, 'r:bz2')
elif path.endswith('.tar.gz'):
self.__upload_tar(path, 'r:gz')
elif extension == '.zip':
self.__upload_zip(path)
... |
def read_operation(memory2):
continue_type = True
while continue_type:
print(msg_0)
x, oper, y = input().split()
try:
x, y = variables_value(x, y, memory2, oper)
except ValueError:
print(msg_1)
continue
if y == 0 and oper == "/":
... | The main task of the code is to repeatedly perform mathematical operations based on user input, store the results in memory, and print them. It uses a loop to read operands and operators, calculates the result, updates memory with the stored result, and continues until the loop terminates. | def main(memory1, con_store_result1):
continue_calc = True
while continue_calc:
x, y, oper = read_operation(memory1)
result = check_operator(x, y, oper)
print(result)
memory1 = store_result(memory1, result, con_store_result1) |
def bestR(s, times, oppositions):
initR = 7
rs = [ ]
incBy = 0.15
r = initR
for outerLoopC in range(6):
for innerLoopCounter in range(10):
if r <= 7 or r >= 9:
break
c, e1, e2, z, errors, maxErr = bestOrbitInnerParams(r, s, times, oppositions)
... | This function iteratively refines Mars' orbital parameters (r, s) using bestR and bestS until the error threshold is met, then computes additional orbit parameters (c, e1, e2, z) via bestOrbitInnerParams, returning optimized values and errors for accurate orbital modeling. | def bestMarsOrbitParams(times, oppositions):
r = 6
s = 360 / 687
maxErr = 1
itteration = 0
while maxErr > (4 / 60):
r, errors, maxErr = bestR(s, times, oppositions)
s, errors, maxErr2 = bestS(r, times, oppositions)
itteration = itteration + 1
c, e1, e2, z, errors, maxErr ... |
def load_audio(filepath, sr=None, mono=True, dtype='float32'):
if '.mp3' in filepath:
from pydub import AudioSegment
import tempfile
import os
mp3 = AudioSegment.from_mp3(filepath)
_, path = tempfile.mkstemp()
mp3.export(path, format="wav")
del mp3
x, fs = sf.read(path)
os.remove(path)
else:
x, fs... | The function `cfp_process` extracts and processes audio features for vocal or melody analysis. It loads an audio file, computes time-frequency representations (e.g., `tfrL0`, `tfrLF`, `tfrLQ`), normalizes them, and concatenates them into a 3D array `W`. If a ground truth file (`ypath`) is provided, it loads the data (f... | def cfp_process(fpath, ypath=None, csv=False, sr=None, hop=hop, model_type='vocal', mono=True):
print('CFP process in ' + str(fpath) + ' ... (It may take some times)')
y, sr = load_audio(fpath, sr=sr, mono=mono)
if 'vocal' in model_type:
# 1250
# 32 2050
# Z, time, CenFreq, tfrL0, tfrLF, tfrLQ = feature_extrac... |
def _fetch_custom_role(module, api_instance):
if module.params["key"] is not None:
try:
# Get a webhook given an id.
api_instance.get_custom_role(module.params["key"])
return True
except ApiException as e:
if e.status == 404:
return Fal... | This code defines an Ansible module to manage LaunchDarkly custom roles. It allows creating/updating roles when 'state' is 'present' or deleting them when 'state' is 'absent'. The module uses parameters like 'key', 'name', and 'description' to identify and configure roles, leveraging the LaunchDarkly API for operations... | def main():
argument_spec = ld_common_argument_spec()
argument_spec.update(
dict(
state=dict(type="str", default="present", choices=["absent", "present"]),
key=dict(type="str", required=True, aliases=["custom_role_key"]),
name=dict(type="str"),
description... |
def _fetch_flag(module, api_instance):
try:
response = api_instance.get_feature_flag(
module.params["project_key"], module.params["key"]
)
return response
except ApiException as e:
if e.status == 404:
return None
else:
fail_exit(module,... | (The main task of the code is to create an Ansible module for managing LaunchDarkly feature flags. It defines parameters for configuring flags (name, kind, variations, etc.), validates required inputs, and interacts with the LaunchDarkly API to create, update, or delete flags based on the "state" parameter. The module ... | def main():
required_if = [
["kind", "str", ["variations"]],
["kind", "json", ["variations"]],
["kind", "number", ["variations"]],
]
argument_spec = ld_common_argument_spec()
argument_spec.update(
dict(
state=dict(type="str", default="present", choices=["abse... |
def load_html(file=html):
with open(file, 'r') as f:
return f.read().strip()
def find(el, *attrs):
try:
return el.find(*attrs).text
except TypeError:
return None
def get_tags(s):
dict_ = defaultdict(list)
for tag in tag_list:
try:
el = find_all(s, tag)
... | The main task of the code is to extract key-value pairs from HTML content, generate JSON/YAML files, and translate these pairs into multiple languages using a progress bar. It loads HTML, parses tags, creates structured data, and iterates over language codes to translate keys via chosen engines, saving results as local... | def main():
page = load_html()
soup = bs(page, 'html.parser').find("body")
tags = get_tags(soup)
key_values = generate_keys(tags)
e = json.dumps(key_values, indent=2)
print(e)
create_yml(key_values)
lang_codes = get_codes()
libretranslate_codes = get_libretranslate_codes()
pr... |
def _swap(self, i: int, j: int) -> None:
i_el, j_el = self._arr[i], self._arr[j]
self._pos[i_el.name] = j
self._pos[j_el.name] = i
self._arr[i], self._arr[j] = j_el, i_el
def _poplast(self) -> X:
_ret = self._arr.pop()
del self._pos[_ret.name]
return _ret
def _bub... | This code extracts the minimum element from a heap by swapping the root with the last element, removing the last element (former root), and then restoring the heap property via a downward bubble operation. | def extract_min(self) -> X:
self._swap(0, -1)
root = self._poplast()
self._bubble_down()
return root |
def _swap(self, i: int, j: int) -> None:
i_el, j_el = self._arr[i], self._arr[j]
self._pos[i_el.name] = j
self._pos[j_el.name] = i
self._arr[i], self._arr[j] = j_el, i_el
def _poplast(self) -> X:
_ret = self._arr.pop()
del self._pos[_ret.name]
return _ret
def _bub... | This code implements the deletion of an element from a priority queue (heap). It swaps the target element with the last element, removes the last element, and restores the heap property by either bubbling up or down depending on the replacement element's key relative to its parent. | def delete(self, x_name: Hashable) -> X:
_ind, _replace = self._pos[x_name], self._arr[-1]
self._swap(_ind, -1)
ret = self._poplast()
# if we deleted the root => invariably bubble down
if _ind == 0:
self._bubble_down()
return ret
if _replace.key ... |
def requires_update(paragraph):
if not is_empty(paragraph) and not is_ingredient(paragraph) and not is_heading(paragraph):
if paragraph.style.name not in acceptable_styles_list:
return True
return False
def determine_style(paragraph):
if is_italicized(paragraph):
if is_cuisine(pa... | The code modifies a Word document by updating paragraph styles and font colors based on predefined criteria. It loads a document, iterates through paragraphs, applies new styles where needed, sets font colors using RGB values determined by the style, and saves the revised document to a specified file path. | def write_paragraphs_to_file(path, save_file):
document = docx.Document(path)
styles = document.styles
print([style for style in styles])
for paragraph in document.paragraphs:
if requires_update(paragraph):
try:
new_style = styles[determine_style(paragraph)].name
... |
def get_ingredient_paragraphs(paragraphs):
return [paragraph for paragraph in paragraphs
if len(paragraph.runs) > 0 and not paragraph.runs[0].italic]
def get_paragraphs(document):
return [paragraph for paragraph in document.paragraphs]
def run(paragraphs, file_name):
groups = create_groups(parag... | The code extracts ingredient-related paragraphs from a document, processes them, and saves the results to 'ingredient_groups.json' | def run_for_ingredients(document):
paragraphs = get_ingredient_paragraphs(get_paragraphs(document))
run(paragraphs, 'ingredient_groups.json') |
def get_dish_paragraphs(paragraphs):
return [paragraph for paragraph in paragraphs
if len(paragraph.runs) > 0 and paragraph.runs[0].italic and "cuisine" not in paragraph.text]
def get_paragraphs(document):
return [paragraph for paragraph in document.paragraphs]
def run(paragraphs, file_name):
gr... | The main task of the code is to extract dish-related paragraphs from a document by first splitting it into paragraphs, filtering those relevant to dishes, and then saving the processed data into a JSON file named 'dish_groups.json'. This involves parsing the input document, identifying dish-specific content, and struct... | def run_for_dishes(document):
paragraphs = get_dish_paragraphs(get_paragraphs(document))
run(paragraphs, 'dish_groups.json') |
def weight_variable(shape):
ini = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(ini)
def bias_variable(shape):
ini = tf.constant(0.1, shape=shape)
#ini = tf.ones(0.1, shape=shape)
return tf.Variable(ini)
def conv2d_BN(X, W, B, tst, iter, stride):
x = tf.nn.conv2d(X, W, strides=[1, st... | The main task of the code is to train a convolutional neural network (CNN) for image classification using TensorFlow. It defines a 4-layer CNN with batch normalization, dropout, and adaptive learning rate decay. The model is trained on provided datasets with optional data augmentation, evaluates accuracy and loss durin... | def run_training(img_size, X_train, Y_train, X_test, Y_test, test_data, iteration, batch_size
, dropout, augmentation, min_learning_rate, max_learning_rate, decay_speed):
DISPLAY = True
DISPLAY_ITER = 10
DISPLAY_STEP = iteration / DISPLAY_ITER
TEST_SUMMARY = True
TEST_EVAL = 50... |
def load_data(json_file, required_keys=()):
try:
with open(json_file, 'r') as f:
try:
data = json.load(f, object_pairs_hook=error_on_duplicate_keys)
except ValueError:
error('invalid json')
return None
except IOError:
error(... | The main task of the code is to validate a problem configuration by checking the data types, consistency with Git repository names, and correctness of settings like problem type, time/memory limits, and metadata (name, title). It issues warnings or errors for invalid configurations, ensuring compliance with predefined ... | def verify_problem():
problem = load_data(os.path.join(BASE_DIR, 'problem.json'), ['name', 'title', 'type', 'time_limit', 'memory_limit'])
if problem is None:
return problem
if not isinstance(problem['name'], string_types):
error('name is not a string')
elif WEB_TERMINAL is None or WEB_... |
def load_data(json_file, required_keys=()):
try:
with open(json_file, 'r') as f:
try:
data = json.load(f, object_pairs_hook=error_on_duplicate_keys)
except ValueError:
error('invalid json')
return None
except IOError:
error(... | This function validates subtask configurations by checking if global and per-subtask validators exist, ensuring required keys (e.g., 'samples', 'index', 'score') are present, verifying score sums to 100, and confirming all indexes are accounted for. It warns about unused validators and returns subtasks data if valid, o... | def verify_subtasks():
subtasks_data = load_data(os.path.join(BASE_DIR, 'subtasks.json'), ['global_validators', 'subtasks'])
if subtasks_data is None:
return None
validators = get_list_of_files(os.path.join(BASE_DIR, 'validator/'))
used_validators = set()
if not isinstance(subtasks_data['g... |
def load_data(json_file, required_keys=()):
try:
with open(json_file, 'r') as f:
try:
data = json.load(f, object_pairs_hook=error_on_duplicate_keys)
except ValueError:
error('invalid json')
return None
except IOError:
error(... | The main task of the code is to validate solution files against defined subtasks by checking verdict consistency, ensuring correct file existence, handling exceptions, and verifying that all solutions are properly accounted for, raising errors for mismatches or missing files. | def verify_solutions(subtasks):
solutions = load_data(os.path.join(BASE_DIR, 'solutions.json'))
if solutions is None or subtasks is None:
return solutions
model_solution = None
solution_files = set(get_list_of_files(os.path.join(BASE_DIR, 'solution/')))
for solution in solutions:
i... |
def verify_problem():
problem = load_data(os.path.join(BASE_DIR, 'problem.json'), ['name', 'title', 'type', 'time_limit', 'memory_limit'])
if problem is None:
return problem
if not isinstance(problem['name'], string_types):
error('name is not a string')
elif WEB_TERMINAL is None or WEB_... | The code verifies the existence and integrity of problem, subtasks, and solutions files by checking necessary JSON files and dependencies. It uses global variables to track the verification context, collects errors/warnings, and outputs colored status messages indicating verification success or issues. Conditional chec... | def verify():
global namespace
namespace = 'problem.json'
verify_problem()
namespace = 'subtasks.json'
subtasks = verify_subtasks()
namespace = 'solutions.json'
verify_solutions(subtasks)
namespace = 'not found'
verify_existence(necessary_files)
if HAS_GRADER == "true":
... |
def go_up(self):
if self.height == "down":
self.goto_rang(self.rang, "up")
self.height = "up"
def goto_file(self, f):
self.arm.set_hor_pos(f*5+0.01)
def grip_rang(self, r, piece_height):
self.arm.release()
if self.height == "down":
self.goto_rang(self.... | The main task of the code is to control a robotic arm to move upward, position itself at a calculated file coordinate (7 - file), and then grip a piece within a specified range and height. The function orchestrates vertical movement, horizontal positioning, and gripping actions to handle objects at precise locations. | def grip_cord(self, rang, file, piece_height):
self.go_up()
self.goto_file(7-file)
self.grip_rang(rang, piece_height) |
def go_up(self):
if self.height == "down":
self.goto_rang(self.rang, "up")
self.height = "up"
def goto_file(self, f):
self.arm.set_hor_pos(f*5+0.01)
def release_rang(self, r):
if self.height == "down":
self.goto_rang(self.rang, "up")
time.sleep(0.1)
... | The code navigates to a specific file location by moving up a level and adjusting the file index, then releases a specified range. The main task is to position the system at a target file and execute a range release operation, likely for resource management or data processing. | def release_cord(self, rang, file):
self.go_up()
self.goto_file(7-file)
self.release_rang(rang) |
def goto_file(self, f):
self.arm.set_hor_pos(f*5+0.01)
def grip_cord(self, rang, file, piece_height):
self.go_up()
self.goto_file(7-file)
self.grip_rang(rang, piece_height)
def go_up(self):
if self.height == "down":
self.goto_rang(self.rang, "up")
self.hei... | This code moves a chess piece from a specified source position to a destination position on a board. It navigates to the source column, grips the piece at the source coordinates, lifts it, delays briefly, then releases it at the destination coordinates. Finally, it updates the board's internal state to reflect the piec... | def move_piece(self, piece_height, src_file, src_rank, dst_file, dst_rank):
self.goto_file(7-src_file)
self.grip_cord(src_rank, src_file, piece_height)
self.go_up()
time.sleep(0.1)
self.release_cord(dst_rank, dst_file)
self.board.move_piece(src_file, src_rank, d... |
def cria_conjunto_palavras():
'''cria_conjunto_palavras: ->conjunto_palavras
cria_conjunto_palavras() devolve um conjunto de palavras vazio.'''
return []
def acrescenta_palavra(conjunto,pp):
''' acrescenta_palavra: conjunto_palavras x palavra_potencial ->
acrescenta_palavra(conj... | The function generates all valid permutations from the input tuple elements according to a grammar, creating a set of valid words. It first generates all possible permutations of varying lengths, checks each permutation's validity using a grammar rule, and adds valid permutations as potential words to a set. The result... | def gera_todas_palavras_validas(tuplo):
'''gera_todas_palavras_validas: tuplo -> conjunto_palavras
gera_todas_palavras_validas(tuplo) devolve um conjunto_palavras contendo
as palavras validas de acordo com a gramatica.'''
# GERADOR DE TODAS AS PERMUTACOES POSSIVEIS A PARTIR DO TUPLO ... |
def e_palavra_potencial(universal):
''' e_palavra_potencial : universal -> logico
e_palavra_potencial(universal) devolve True caso o argumento seja do
tipo palavra_potencial, False em caso contrario. '''
if not isinstance(universal,str):
return False
for i in universal... | This function adds a valid potential word to a player's valid words set and updates their score based on the word's length, provided the arguments are valid. It checks if the word is not already in the player's valid words, then adds it and increases the score by the word's length. | def adiciona_palavra_valida(jog,p):
'''adiciona_palavra_valida: jogador x palavra_potencial ->
adiciona_palavra_valida(jog,p) tem como efeito adicionar a palavra_potencial
ao conjunto de palavras validas propostas pelo jogador e atualiza a pontuacao
do jogador.'''
if e_palavra_po... |
def e_palavra_potencial(universal):
''' e_palavra_potencial : universal -> logico
e_palavra_potencial(universal) devolve True caso o argumento seja do
tipo palavra_potencial, False em caso contrario. '''
if not isinstance(universal,str):
return False
for i in universal... | The function adds a valid potential word to a player's invalid words set and decreases their score by the word's length, after validating inputs. It checks if the word is a valid potential word and the player is valid, raising an error if not. If the word isn't already in the player's invalid list, it's added, and the ... | def adiciona_palavra_invalida(jog,p):
'''adiciona_palavra_invalida: jogador x palavra_potencial ->
adiciona_palavra_invalida(jog,p) tem como efeito adicionar a palavra_potencial
ao conjunto de palavras invalidas propostas pelo jogador e atualiza a pontuacao
do jogador.'''
if... |
def ditongo_palavra(inp):
"""
<ditongo_palavra> ::= AI | AO | EU | OU
"""
return inp in ('AI', 'AO', 'EU', 'OU')
def vogal_palavra(chr):
"""
<vogal_palavra> ::= <artigo_def> | E
"""
return artigo_def(chr) or chr == 'E'
def consoante_freq(inp):
"""
<consoante_freq> ::= D | L | M |... | This function checks if a two-character input string matches specific monosyllabic word patterns, including predefined pairs like 'AR'/'IR', diphthongs, vowel-consonant combinations, or frequent consonant-vowel pairs. It returns True if the input fits any valid rule, otherwise False. | def monossilabo_2(inp):
"""
<monossilabo_2>::= AR | IR | EM | UM | <vogal_palavra> S | <ditongo_palavra> | <consoante_freq> <vogal>
"""
if len(inp) != 2:
return False
if inp in ('AR', 'IR', 'EM', 'UM'):
return True
else:
return (ditongo_palavra(inp)) or (vogal_palavra(in... |
def consoante(inp):
"""
<consoante>::= B| C| D| F| G| H| J| L| M| N| P| Q| R| S| T| V| X| Z
"""
return inp in ('B', 'C', 'D', 'F', 'G', 'H', 'J', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'X', 'Z')
def vogal(chr):
"""
<vogal> ::= I | U | <vogal_palavra>
"""
return (chr in ('I', 'U')) ... | Your return | def monossilabo_3(inp):
"""
<monossilabo_3> ::= <consoante> <vogal> <consoante_terminal>
| <consoante> <ditongo>
| <par_vogais> <consoante_terminal>
| <consoante> <vogal> <vogal>
"""
if len(inp) == 3:
return ((consoante(inp[0]... |
def par_vogais(inp):
"""
<par_vogais> ::= <ditongo> | IA | IO
"""
return ditongo(inp) or (inp in ('IA', 'IO'))
def consoante(inp):
"""
<consoante>::= B| C| D| F| G| H| J| L| M| N| P| Q| R| S| T| V| X| Z
"""
return inp in ('B', 'C', 'D', 'F', 'G', 'H', 'J', 'L', 'M', 'N', 'P', 'Q', 'R', '... | The function checks if a 2-character input string matches one of three phonological patterns: a pair of vowels, a consonant followed by a vowel, or a vowel followed by a final consonant, returning True if any pattern matches and False otherwise. | def silaba_2(inp):
"""
silaba_2 ::= <par_vogais> | <consoante> <vogal> | <vogal> <consoante_final>
"""
if len(inp) != 2:
return False
return par_vogais(inp) or (consoante(inp[0]) and vogal(inp[1:])) or (vogal(inp[0]) and consoante_final(inp[1:])) |
def vogal(chr):
"""
<vogal> ::= I | U | <vogal_palavra>
"""
return (chr in ('I', 'U')) or vogal_palavra(chr)
def consoante(inp):
"""
<consoante>::= B| C| D| F| G| H| J| L| M| N| P| Q| R| S| T| V| X| Z
"""
return inp in ('B', 'C', 'D', 'F', 'G', 'H', 'J', 'L', 'M', 'N', 'P', 'Q', 'R', 'S'... | This function checks if a 3-character input string matches specific syllable patterns defined in the grammar rules, such as 'QUA', 'QUE', or combinations of vowels and consonants. It returns True if the input conforms to any of these rules, otherwise False. | def silaba_3(inp):
"""
<silaba3>::= QUA| QUE| QUI| GUE| GUI|<vogal> NS
|<consoante><par_vogais>
|<consoante><vogal><consoante_final>
|<par_vogais><consoante_final>
|<par_consoantes><vogal>
"""
if len(inp) != 3:
return False
return (inp... |
def par_vogais(inp):
"""
<par_vogais> ::= <ditongo> | IA | IO
"""
return ditongo(inp) or (inp in ('IA', 'IO'))
def consoante(inp):
"""
<consoante>::= B| C| D| F| G| H| J| L| M| N| P| Q| R| S| T| V| X| Z
"""
return inp in ('B', 'C', 'D', 'F', 'G', 'H', 'J', 'L', 'M', 'N', 'P', 'Q', 'R', '... | The function `silaba_4` validates if a 4-character input string matches specific phonetic patterns for syllables, checking rules like pairs of vowels followed by "NS," consonant-vowel combinations with "NS" or "IS," pairs of consonants and vowels, or consonant-vowel-consonant structures. It returns `True` if the input ... | def silaba_4(inp):
"""
<silaba_4>::= <par_vogais> NS
| consoante><vogal> NS
| <consoante><vogal> IS
| <par_consoantes><par_vogais>
| <consoante><par_vogais><consoante_final>
"""
if len(inp) != 4:
return False
return ((par_... |
def vogal_palavra(chr):
"""
<vogal_palavra> ::= <artigo_def> | E
"""
return artigo_def(chr) or chr == 'E'
def monossilabo_2(inp):
"""
<monossilabo_2>::= AR | IR | EM | UM | <vogal_palavra> S | <ditongo_palavra> | <consoante_freq> <vogal>
"""
if len(inp) != 2:
return False
if... | The function `monossilabo` checks if an input string matches any of three linguistic patterns: `vogal_palavra` (possibly checking if it starts with a vowel), `monossilabo_2` (maybe a two-character structure), or `monossilabo_3` (a three-character pattern). It returns `True` if any of these conditions are met, indicatin... | def monossilabo(inp):
"""
<monossilabo> ::= <vogal_palavra>|<monossilabo_2>|<monossilabo_3>
"""
return vogal_palavra(inp) or monossilabo_2(inp) or monossilabo_3(inp) |
def monossilabo_2(inp):
"""
<monossilabo_2>::= AR | IR | EM | UM | <vogal_palavra> S | <ditongo_palavra> | <consoante_freq> <vogal>
"""
if len(inp) != 2:
return False
if inp in ('AR', 'IR', 'EM', 'UM'):
return True
else:
return (ditongo_palavra(inp)) or (vogal_palavra(in... | The function `silaba_final` checks if the input `inp` matches any of four syllable patterns defined by `monossilabo_2`, `monossilabo_3`, `silaba_4`, or `silaba_5`, returning `True` if any condition is met. Its main task is to validate whether the input conforms to one of these specific syllable structures, likely for l... | def silaba_final(inp):
"""
<silaba_final>::=<monossilabo_2> | <monossilabo_3> | <silaba_4> | <silaba_5>
"""
return monossilabo_2(inp) or monossilabo_3(inp) or silaba_4(inp) or silaba_5(inp) |
def vogal(chr):
"""
<vogal> ::= I | U | <vogal_palavra>
"""
return (chr in ('I', 'U')) or vogal_palavra(chr)
def silaba_2(inp):
"""
silaba_2 ::= <par_vogais> | <consoante> <vogal> | <vogal> <consoante_final>
"""
if len(inp) != 2:
return False
return par_vogais(inp) or (conso... | The code defines a function `silaba` that checks if an input string matches any of several syllable patterns (`vogal`, `silaba_2` to `silaba_5`). It returns `True` if the input conforms to any of these patterns, effectively validating the string against a grammar rule where a syllable can be a vowel or one of the speci... | def silaba(inp):
"""
<silaba>::=<vogal>|<silaba_2>|<silaba_3>|<silaba_4>|<silaba_5>
"""
return vogal(inp) or silaba_2(inp) or silaba_3(inp) or silaba_4(inp) or silaba_5(inp) |
def func_name():# Import the function which creates a server query(also a script of running webcam thru python, and also alpr code to be placed here)
# If possible make the function return boolean values, True for a successful updation in library
return Take_entry_photograph()
def call_entry_allowed... | The function `decider_for_entry_button` determines the appropriate UI frame to display based on the result of `func_name()`. If `func_name()` returns `True`, it shows the "entry allowed" frame; if `False`, the "verify no plate" frame; otherwise, the "new user not detected" frame. Its main task is to route user interfac... | def decider_for_entry_button():
decide = func_name()
if decide == True:
call_entry_allowed_frame_on_top()
elif decide== False:
call_verify_no_plate_frame_on_top()
else:
call_new_user_not_detected_frame_on_top() |
def func_checher():
return_value = Take_exit_photograph()
print("EXIT code " + str(return_value))
return return_value
def call_exit_allowed_frame_on_top():
start_frame.grid_forget()
exit_if_plate_not_recognised_frame.grid_forget()
create_widgets_in_exit_allowed_frame()
exit_allowed_frame.gri... | The function determines which exit frame to display based on `func_checher()`'s result. If true, it shows the allowed exit frame; otherwise, the plate-unrecognized frame. It acts as a decision maker for exit process logic. | def decider_for_exit_button():
if func_checher():
call_exit_allowed_frame_on_top()
else:
call_exit_if_plate_not_recognised_frame_on_top() |
def check_goal_reached(self):
if (
abs(
np.linalg.norm(
np.array(
[self.current_waypoint[0], self.current_waypoint[1]],
np.dtype("float64"),
)
- np.array(
... | This code controls a robot's movement toward a target waypoint using force-based navigation. It calculates combined forces (desired, obstacle, social), updates velocity, adjusts orientation with PID control, and publishes velocity commands. The loop continues until the goal is reached, then stops the robot and marks su... | def execute_cb(self, goal):
rospy.loginfo("Starting social drive")
r_sleep = rospy.Rate(30)
cancel_move_pub = rospy.Publisher("/move_base/cancel", GoalID, queue_size=1)
cancel_msg = GoalID()
cancel_move_pub.publish(cancel_msg)
self.goal_set = True
self.current_wa... |
def desired_force(self):
desired_direction = self.current_waypoint - self.robot_position
desired_direction_vec_norm = np.linalg.norm(desired_direction)
if desired_direction_vec_norm != 0:
norm_desired_direction = desired_direction / desired_direction_vec_norm
else:
... | This code calculates a robot's movement force by combining desired, obstacle, and social forces, updates velocity while enforcing speed limits, adjusts orientation using PID control, and publishes velocity commands for navigation. | def run(self):
while not rospy.is_shutdown():
if self.goal_set:
complete_force = (
self.force_factor_desired * self.desired_force()
+ self.force_factor_obstacle * self.obstacle_force()
+ self.force_factor_social * self.socia... |
def verify_check_digit(library_card):
if len(library_card) != 10:
return False, "The length of the number given must be 10"
for i in range (0,5):
if (ord(library_card[i]) < 65) or (ord(library_card[i]) > 90):
error = str(library_card[i])
i = str(i)
return (F... | The main task of the code is to repeatedly validate library cards by checking their check digit, displaying whether they are valid or invalid, and providing associated student information (school and grade) if valid. The loop allows continuous input without restarting the process, ensuring efficient repeated verificati... | def main():
'''The main function allows for me to be able to repeat rhis process without reprinting the steps over and over'''
while(1):
library_card = input("Enter Library Card. Hit Enter to Exit ==> ")
(result,explan) = verify_check_digit(library_card)
if result == True:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.