dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def load_models(self):
http = urllib3.PoolManager()
self.url = "https://alphacephei.com/vosk/models"
self.r = http.request('GET', self.url)
soup = BeautifulSoup(self.r.data, 'html.parser')
head_list = []
item_list = []
model_list = []
la... | The code initializes a GUI application for downloading VOSK speech-to-text models. It sets up a Tkinter interface with language/model selection, directory browsing, and download functionality. The app loads available models, displays metadata, and allows users to specify a download path. It prepares the environment by ... | def __init__(self):
rospack = rospkg.RosPack()
rospack.list()
self.package_path = rospack.get_path('rofunc_ros')
model_path = '/speech2text/models/'
self.model_dir = self.package_path + model_path
model_folder = os.path.join(self.package_path, 'speech2text/models')
... |
def UserInputInfo():# get user input and return name and characteristic trait to call it in other functions
name = input("Enter your name: ")
trait = input ("Enter an adjective that describes you the most: ")
return name, trait
def introduction(name, trait): # showing title, the introduction of the game and... | The main task of the code is to collect user personal information (name and trait) via the `UserInputInfo` function, generate an introduction using the `introduction` function, and initiate a game loop with the `gameloop` function using the user's name. The `main` function orchestrates these steps sequentially to creat... | def main(): # main function
name, trait = UserInputInfo() #calling the userimputinfo function to ask user for his personal information
introduction(name, trait) # calling the introduction function
gameloop(name) |
def scan_step(ref):
global scan_list, current_angle, us_step
current_angle += us_step
if current_angle >= max_angle:
current_angle = max_angle
us_step = -STEP
elif current_angle <= min_angle:
current_angle = min_angle
us_step = STEP
status = get_status_at(current_angl... | The main task of the code is to continuously scan the environment using `scan_step(35)`, check if specific sensor values (indices 3-7) are not `[2,2,2,2]`, and if so, stop, randomly turn left/right, move backward, and wait. If the values match `[2,2,2,2]`, it continues moving forward. This implements a basic navigation... | def main():
while True:
scan_list = scan_step(35)
if not scan_list:
continue
print("scan_list : " ,scan_list)
tmp = scan_list[3:7]
print("tmp : ",tmp)
if tmp != [2,2,2,2]:
stop()
direction = randrange(1,3)
turn_speed = r... |
def extractIfClause(string, number = 0):
endPattern = r"{\[ %endif ]}"
end = re.findall(endPattern, string)
pattern = r"\{\[\s*%if\s+(not\s+)?([a-zA-Z]+)(?:=\"(.+?)\")?\s*\]\}"
match = getNthMatch(pattern, string, number)
if match:
inverted = bool(match.group(1))
propName = match.group(2)
valu... | This function processes inline if-clauses in a list of lines, recursively evaluating conditions based on provided properties. It removes unsatisfied clauses, adjusts line content, and handles nested clauses by updating indices and reprocessing lines. | def handleInlineIfClauses(lines: list, index: int, props: dict, current: int = 0):
clause = extractIfClause(lines[index], current)
if not clause:
return
if not clause["inline"]:
handleInlineIfClauses(lines, index, props, current + 1)
return
if not isIfClauseSatisfied(clause, props):
# If ... |
def fixEndIfTokens(line):
pattern = r"{\[\s*%endif\s*\]}"
fixed = re.sub(pattern, endIfToken, line)
return fixed
def handleInlineIfClauses(lines: list, index: int, props: dict, current: int = 0):
clause = extractIfClause(lines[index], current)
if not clause:
return
if not clause["inline"]:
... | This function processes lines of code to evaluate and prune conditional logic (if/endif blocks) based on provided properties. It fixes token endings, handles inline if-clauses, tracks nested if blocks, validates syntax, and removes lines inside if blocks that fail condition checks. It ensures proper nesting, raises err... | def handleComponentIfLogic(lines: list, props: dict):
for index in range(len(lines)):
lines[index] = fixEndIfTokens(lines[index])
handleInlineIfClauses(lines, index, props)
nestedIfs = []
index = 0
while index < len(lines):
clause = extractIfClause(lines[index])
endClause = lines[index].find(en... |
def extractComponentData(line: str):
pattern = r"<!--\s*%MLKY\s+(\w+(?:-\w+)*)\s+([a-zA-Z]+=\"[^\"]*\s*\"(?:\s+[a-zA-Z]+=\"[^\"]*\s*\")*)*\s*-->"
match = re.search(pattern, line)
if not match:
return None
componentName = match.group(1)
rawProps = match.group(2)
props = {}
if rawProps:
propPat... | The main task of the code is to insert a component into a codebase by replacing a component indicator with the content of a corresponding file. It extracts component data, verifies the file exists, processes the component's logic and props, and wraps the component's code around the split parts of the original indicator... | def getComponentInsert(writeLines: list, index: int) -> list[str] | None:
component = extractComponentData(writeLines[index])
if component:
name = component["name"]
output(f"Found '{name}' component indicator, searching for file...")
path = "./components/" + name.lower() + ".mcomp"
if not os.p... |
def concatenateComponentLines(lines) -> list[str]:
newLines = []
currentComponent = None
line: str
for line in lines:
componentStart = line.find("<!-- %MLKY")
componentEnd = line.find("-->")
if currentComponent:
currentComponent += " " + line.strip()
if componentStart != -1:
r... | This function processes input lines to substitute components iteratively. It copies input lines, repeatedly searches for components, replaces them with their substitutions, and continues until no components remain. The output mode is controlled by the `doOutput` parameter, which determines if substitutions are applied ... | def doComponentSubstitutions(inputLines, doOutput = True):
setOutputMode(not doOutput)
writeLines = copy.copy(inputLines)
# We initialize this to True since there is no "do while"
# construct in Python for some reason...
foundComponent = True
while foundComponent:
foundComponent = False
writeLines... |
def propagate(self, N_iter_msg = 5, phi = 0.55, entire = False):
"""
Propagates beliefs and messages through the graphical model.
Parameters:
N_iter_msg (int): Number of iterations for message propagation.
phi (float): Potential value for vertices.
en... | The code performs full inference on a graph by iteratively propagating messages between nodes, updating weights using specified parameters (lambd, d, alpha, beta), and evaluating model performance via AUC metrics. It randomly selects observed nodes, splits them into training and test sets, and iterates (N_iter times) t... | def full_inference(self,obs_rate = 0.3, N_iter = 60, N_iter_msg = 5, lambd = 0.05, d = 0.0001, alpha = 0.00001, beta = 0.00001):
"""
Perform full inference on the graph.
Parameters:
obs_rate (float): Observation rate for nodes in the graph.
N_iter (int): Number o... |
def _get_1d_arrays(*args):
results = [np.atleast_1d(arg) for arg in args]
sizes = [arr.size for arr in results]
npts = max(sizes)
msg = "All input arguments should be either a float or ndarray of shape ({0}, )"
assert set(sizes) <= set((1, npts)), msg.format(npts)
return [np.zeros(npts).astype(a... | This function computes the halo mass at a given redshift using the Behroozi+13 fitting formula (Equations H2-H6), calibrated for h=0.7. It takes the halo mass at z=0 and input redshift(s), applies the model's cosmological scaling, and returns the corresponding halo mass at the specified redshift(s). | def halo_mass_vs_redshift(halo_mass_at_z0, redshift):
"""Fitting function from Behroozi+13, https://arxiv.org/abs/1207.6105,
Equations (H2)-(H6). Calibration assumes h=0.7.
Parameters
----------
halo_mass_at_z0 : float or ndarray
Mass of the halo at z=0 assuming h=0.7.
redshift : float... |
def ballmovement(self):
self.ball_rect.center = self.ball_rect.center[0] + self.velocity[0], self.ball_rect.center[1] + self.velocity[1]
if self.ball_rect.center[0] <= ball_rad / 1.4:
self.ball_rect.center = ball_rad / 1.4, self.ball_rect.center[1]
self.velocity[0] = -self.velo... | This code manages a Pygame game loop, handling user input, updating game states (playing, ball-in-paddle, game-over, win), dynamically changing brick colors based on game mode, rendering backgrounds, ball/paddle physics, collision detection, score display, and live counters. It also manages transitions between states, ... | def run(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
self.clock.tick(40)
for brick in self.bricks:
if self.game_form == 1:
if brick.color == (255, 0, 255):
pass
else... |
def get_embedding(self, input_ids, attention_mask, ce_mask, token_type_ids, subword_group,
context_ce_mask, context_subword_group, context_map,
input_word, input_char, input_pos,
l_input_word, l_input_char, l_input_pos,
r_input_word... | This function processes input data through an embedding layer and encodes it using either a standard LSTM or a context-aware LSTM, depending on the 'context_lstm' flag. It computes sequence lengths, generates embeddings via 'get_embedding', and applies encoding to produce a hidden state representation. The output is th... | def forward(self, input_ids, attention_mask=None, ce_mask=None, token_type_ids=None, subword_group=None,
context_ce_mask=None, context_subword_group=None, context_map=None,
input_word=None, input_char=None, input_pos=None,
l_input_word=None, l_input_char=None, l_input_po... |
def monsterSelection(player):
return player.area.monsters[random.randint(0,(len(player.area.monsters)-1))]
def inputcheck(message:str):
while True:
try:
message=int(input(message))
break
except ValueError:
print("Try again with a num")
return message
def a... | This code implements a turn-based battle system where a player fights a monster. It handles move selection, damage calculation, HP tracking, item usage, status checks, and escape attempts. The battle proceeds in rounds, with attacks resolved based on speed. The player can attack, use items, view stats, or try to run. T... | def battle(self):
m:characters=monsterSelection(self)
m.restore()
monmove=m.monMoveSelect()
print(Fore.LIGHTBLUE_EX+self.name+Style.RESET_ALL+" encounters a "+Fore.YELLOW+m.name)
while self.currenthp>0 and m.currenthp>0:
# Player selection of moves
print()... |
def restore(self):
self.currentmp=self.mana
self.currenthp=self.health
def stats(self):
print()
print("----------------"+self.name+"'s Stats----------------")
print("Class: "+self.rpgclass)
print("Level "+str(self.level)+" <-> "+str(self.xp)+"/"+str(self.xpcontainer)+" XP... | This function handles character leveling by continuously granting levels when XP exceeds a threshold, distributing random stat boosts, allowing players to allocate bonus points to attributes, and updating the character's stats and display. | def levelup(self):
# continuosly levels up until xp isn't over the cap
while self.xp>=self.xpcontainer:
self.xp=int(self.xp-self.xpcontainer)
self.level+=1
self.xpcontainer=int(self.xpcontainer*1.5)
print(Fore.YELLOW+"You Leveled Up!"+Style.RESET_ALL+" ... |
def checkType( self, typ: TokenType ) -> bool:
if self.isAtEnd():
return False
return self.peek().typ == typ
def advance( self ) -> Token:
if not self.isAtEnd():
self.current += 1
return self.previous()
def check( self, typ: Union[Keyword, UnaryType] ) -> bool:
if self.isAtEnd():
return False
retur... | This code consumes a token of a specified type from the input stream. It checks if the current token matches the expected type (either TokenType, Keyword, UnaryType, or Symbol). If it matches, it advances the token stream and returns the token; otherwise, it raises an error with the provided message. | def consume( self, typ: TokenType | Keyword | UnaryType | Symbol, message: str ) -> Token:
if isinstance(typ, TokenType):
if self.checkType(typ):
return self.advance()
else:
if self.check(typ):
return self.advance()
raise self.error( self.peek(), message ) |
def advance( self ) -> Token:
if not self.isAtEnd():
self.current += 1
return self.previous()
def isAtEnd( self ) -> bool:
return self.peek().typ == TokenType.EOF
def previous( self ) -> Token:
return self.tokens[self.current - 1]
def peek( self ) -> Token:
return self.tokens[self.current] | The main task of the code is to advance through a token stream until it encounters either a slash (Symbol.SLASH) or specific keywords (e.g., DECLARE, EXPORT), at which point it stops and returns. It skips tokens iteratively, checking conditions to determine when to halt processing. | def syncronize( self ) -> None:
self.advance()
while not self.isAtEnd():
if self.previous().value == Symbol.SLASH:
return
if self.peek().value in (
Keyword.DECLARE,
Keyword.EXPORT,
Keyword.CHECK,
Keyword.CALL,
Keyword.GIVE,
Keyword.UNTIL,
):
return
self.advance() |
def __getClosestGeoNodeFromDHT(self, node):
closest = self.nodes[0]
minDiff = math.inf
for currNode in self.nodes:
temp = ((node.coordinates[0]-currNode.coordinates[0])**2 + (node.coordinates[1]-currNode.coordinates[1])**2)**0.5
if temp < minDiff:
minDiff ... | This code adds a new node to a Distributed Hash Table (DHT) by routing it to its correct position using hashing, maintaining sorted order, updating routing tables with encountered nodes, and managing node count and mappings for efficient data distribution in a peer-to-peer network. | def addNodeToDHT(self, node):
if (self.numberOfNodes == 0):
self.nodes.append(node)
self.nodes.sort(key=lambda x: x.nodeId)
self.nodeIdToNodeDict[node.nodeId] = node
self.numberOfNodes += 1
# print("Added first============")
return
... |
def partition_dataset(multilabel_dataset):
partitioned_labels = partition_labels(multilabel_dataset)
return \
Stream(partitioned_labels) \
.map(lambda label_... | (The code processes a multilabel dataset by partitioning it, applying feature selection to each partition, classifying the transformed data using a classifier, and combining results across partitions to produce a unified output.) | def transform_problem(multilabel_dataset, feature_selector, classifier) -> []:
partitioned_datasets = partition_dataset(multilabel_dataset)
fitted_feature_selectors = \
Stream(partitioned_datasets) \
... |
def get_apod_date():
"""Gets the APOD date
The APOD date is taken from the first command line parameter.
Validates that the command line parameter specifies a valid APOD date.
Prints an error message and exits script if the date is invalid.
Uses today's date if no date is provided on the comma... | The code retrieves the APOD (Astronomy Picture of the Day) for a specified date, caches it in a local directory, and sets the image as the desktop background. It fetches the date from the command line, initializes a cache, stores the APOD data, and uses the file path from the database to update the desktop background i... | def main():
## DO NOT CHANGE THIS FUNCTION ##
# Get the APOD date from the command line
apod_date = get_apod_date()
# Get the path of the directory in which this script resides
script_dir = get_script_dir()
# Initialize the image cache
init_apod_cache(script_dir)
# Add the APOD fo... |
def deal():
"""Returns a random card from the deck."""
card = random.randint(1, 13)
return card
def total(hand):
"""Returns the total value of the hand."""
t = 0
for card in hand:
t += value(card)
return t
def hit(hand):
"""Adds a card to the hand and returns the total value."""
... | This code defines a Blackjack game function where the player and dealer each receive two cards. The player decides to hit or stand, with their total displayed. If the player busts, they lose. Otherwise, the dealer reveals their hand, hits until reaching 17, and the winner is determined by comparing totals. The game end... | def play():
"""Plays a single game of blackjack."""
player_hand = []
dealer_hand = []
player_hand.append(deal())
dealer_hand.append(deal())
player_hand.append(deal())
dealer_hand.append(deal())
print("You were dealt", player_hand)
print("The dealer has a", dealer_hand[0], "showing, a... |
def is_empty(self):
return len(self.collection) == 0
def _pop_last(self):
last = self.collection.pop()
del self._pos[self._key_getter(last)]
return last
def _sift_down(self, node):
node_val = self._get_val(node)
left = self._left_child(node)
if not left:
... | This function removes and returns the smallest element from a priority queue (min-heap), maintaining the heap structure. It replaces the root with the last element, updates its position, and sifts down to restore the heap property. If the heap is empty, it returns None. | def dequeue_min(self):
if self.is_empty():
return None
smallest = self.collection[0]
last = self._pop_last()
if self.is_empty():
return last
self.collection[0] = last
self._pos[self._key_getter(last)] = 0
self._sift_down(0)
return s... |
def is_there_empty_court():
global courts
for court in courts:
if court["occupied"] == False:
return court["court_number"]
return 0
def is_there_empty_court_for_me(current_time:int):
for court in courts:
if court["occupied"] == True and court["end_time"] < current_time - 1:
... | The code's main task is to allocate courts to players in a waiting list based on their preferences and availability. It sorts the waiting list by arrival time, checks for empty courts, and matches requests to single or double courts using preference-specific functions. It skips already matched entries, attempts to matc... | def allocate_court():
global courts
global waiting_list
global matched_list
#sort waitinglist by arrival time
waiting_list = sorted(waiting_list, key=lambda k: k['arrival_time'])
for i in range(len(waiting_list)):
if i in matched_list:
continue
#can i obtain court fo... |
def _get_bounced_address_counter(self, bounced_address, domain):
con = self._get_db_conn()
cur = con.cursor()
stmt = '''
SELECT counter FROM temporary_bounces
WHERE bounced_address=:bounced_address AND domain=:domain;
'''
cur.execute(stmt.strip(), {
... | This function checks if a bounced email address has exceeded a temporary bounce threshold. If so, it transitions the address to permanent bounce handling, resets its counter, and returns. Otherwise, it increments the counter for temporary bounces. The logic determines whether to treat the bounce as temporary or permane... | def _handle_temporary_bounced_address(self, bounced_address, domain, mail):
temporary_threshold = self.handler_config['temporary_threshold']
current_counter = self._get_bounced_address_counter(
bounced_address, domain)
if current_counter > temporary_threshold:
self._hand... |
def is_inside_map(interpolated_points, map_size):
"""
Take the extreme points and ensure that their distance is smaller than the map side
"""
xs = [t[0] for t in interpolated_points]
ys = [t[1] for t in interpolated_points]
min_x, max_x = min(xs), max(xs)
min_y, max_y = min(ys), max(ys)... | The function `is_valid_road` checks if a road, represented by a list of points, is valid based on four criteria: (1) the road must be a simple (non-intersecting) path, (2) it must not be too sharp (checked via interpolation), (3) it must contain at least 3 points, and (4) all points must lie within the map boundaries. ... | def is_valid_road(points):
"""
If the road is not simple, or if the road is too sharp, or if the road has less than 3 points, or if
the last point is not in range, then the road is invalid
Args:
points: a list of points that make up the road
Returns:
A boolean value.
"""
in_ra... |
def prepare_data_loader(root='cartoon_dataset', test_size=50):
dataset = CartoonDataset(root, get_transform(True))
indices = torch.randperm(len(dataset)).tolist()
data_loader = None
if test_size < len(dataset):
dataset_train = torch.utils.data.Subset(dataset, indices[:-test_size])
data_l... | The code trains a neural network model on a cartoon dataset using stochastic gradient descent (SGD) with momentum and weight decay. It prepares data loaders, configures an optimizer and learning rate scheduler, trains over multiple epochs, evaluates on a test set if specified, and saves the trained model's parameters t... | def train(model, device, root='cartoon_dataset', model_target_dir='model',
num_epochs=10, test_size=50):
data_loader, data_loader_test = prepare_data_loader(root, test_size)
model.to(device)
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=0.... |
def reset_choice():
global choice_a, choice_b, a_followers, b_followers
choice_a = choice_b
a_followers = b_followers
def new_choice():
global choice_b, b_followers
choice_b = get_random_data()
b_followers = choice_b['follower_count']
choice_b = format_data(choice_b)
def check_duplicate_ch... | The function `game_should_continue()` manages game state by resetting choices, generating new ones, and checking for duplicates to ensure valid progression. It calls `reset_choice()` to clear previous selections, `new_choice()` to create fresh options, and `check_duplicate_choice()` to validate uniqueness, maintaining ... | def game_should_continue():
reset_choice()
new_choice()
check_duplicate_choice() |
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def game_should_continue():
reset_choice()
new_choice()
check_duplicate_choice()
def print_data():
global choice_a, choice_b, a_followers, b_followers
print(f"Compare A: {choice_a}")
print(vs)
print(f"Against B: {choic... | The code's main task is to determine if the user's choice (A or B) correctly identifies which entity has more followers, updating the score if correct and continuing the game, or ending it if incorrect. It also handles invalid input by informing the user. | def game():
global play, score, choice_a, choice_b, a_followers, b_followers
choice = input("Who has more followers? Type 'A' or 'B': ").upper()
clear_screen()
print(logo)
if (choice == 'A' and a_followers > b_followers) or (choice == 'B' and a_followers < b_followers):
score += 1
pr... |
def get_user_choice(message, options):
"""
Get user to choose from a range of options. User input is sanitised and
checked to ensure it is valid.
"""
valid_choice = False
while not valid_choice:
choice = input(message).strip().lower()
valid_choice = choice in options
if n... | The main task of the code is to determine the program's directory (whether run as an executable or script), prompt the user to choose between encoding data or decoding an image, and execute the corresponding function (`main_encode` or `main_decode`) with the identified directory. It ensures compatibility with PyInstall... | def main():
"""
Main entry point for the program. Ask the user whether they would like to
encode data or decode an image and pass the program onto the corresponding
function.
"""
# This code is taken directly from the documentation for pyinstaller,
# which is used to compile this program int... |
def draw_camps(camps, screen):
for camp in camps:
x,y = camp.position.x, camp.position.y
w = camp.width
h = camp.height
dx = w / 2
dy = h / 2
r = pygame.Rect( (x-dx,y-dy)
, (w, h) )
color = camp.owner.color
pygame.draw.rect(screen, color, r, 5)
def draw_goal(goal, wo... | This function renders a game scene by clearing the screen, drawing camps, goals, jet streams (based on seekers' acceleration), seekers, score animations, and player information, then updating the display with Pygame. It visualizes game elements like player positions, movement trails, scores, and UI data, ensuring all c... | def draw(players, camps, goals, animations, clock, world, screen):
# clear screen
screen.fill(background_color)
# draw camps
draw_camps(camps, screen)
# draw goals
for g in goals:
draw_goal(g, world, screen)
# draw jet streams
for p in players:
for s in p.seekers:
a = s.acceleration
... |
def get_blocks (A):
blocks = []
flag = False
block = Pair (0, 0, 0)
aux_blocks = []
j = 0
for i in range (len (A)):
aux_blocks.append (Pair (0, 0, 0))
block.index = len (blocks)
if A[i] == 1:
if not flag:
flag = True
block.i = i... | The function computes the minimum matching between two sequences (A and B) using dynamic programming. It divides the sequences into blocks, calculates variance between blocks, initializes a memory matrix for dynamic programming, and fills it with average-based matching values to determine the optimal alignment. The res... | def min_matching_dynamic_avg (A, B):
blocks_A = get_blocks (A)
blocks_B = get_blocks (B)
var = get_var (blocks_A, blocks_B)
for i in range (len (A)):
mem_pg.append ([])
for j in range (len (blocks_B)):
mem_pg[i].append (Matching (0, [], 0))
min_matching = fill_matrix_avg ... |
def compute_datetime(rule, present: datetime, unit=None, special_value=None):
if special_value == None:
if rule.get("operation") == "-":
return present - rule.get("relativedelta_function")
elif rule.get("operation") == "+":
return present + rule.get("relativedelta_function")
... | The main task of the code is to parse a datetime value from a given tag using predefined rules. It first attempts to compute the datetime directly using a rule associated with the tag. If that fails, it tokenizes the tag, converts numerical words, and checks for singular/plural time units. Upon finding a match, it uses... | def get_datetime_object(tag: str, present: datetime, rules: Dict) -> List:
try:
rule = rules.get(tag)
datetime_object = compute_datetime(rule, present)
return {"entity": tag, "parsed_value": datetime_object}
except:
tokens = tokenize(tag)
tokens = convert_numerical_words(... |
def client_nice_announcement_printer(head : str):
width = 150
margin = 25
buff = (width-len(head))//2
print((buff-25)*"-", head, (width-len(head)-buff-margin)*"-")
def resolve_dns_challenge(self, challenge : Challenge, record : str) -> None:
client_nice_printer(challenge.__dict__, "RESOLVING DNS... | This method resolves DNS-01 or HTTP-01 challenges by iterating through stored challenges and delegating to specific resolution methods based on challenge type. It uses the provided record for DNS challenges and triggers appropriate resolution logic for each challenge type. | def resolve_challenges(self, challenge_type : str, record : str) -> None:
client_nice_announcement_printer("RESOLVING CHALLENGES...")
for challenge in self.challenges:
if challenge_type == 'dns01' and challenge.type == 'dns-01':
self.resolve_dns_challenge(challenge, record)
... |
def load_cfg(cp: Path) -> AttrDict:
return AttrDict.from_yaml(cp / 'cfg.yaml')
def load_model(cp: Path, cfg: Optional[AttrDict] = None) -> Model:
if cfg is None:
cfg = load_cfg(cp)
state = torch.load(cp / 'model.state.pt') # type: ignore
model_cls = get_model_class(cfg)
model = model_cls(cf... | This function loads a machine learning model checkpoint, restoring the configuration, model architecture, optimizer state, training context, and EMA model from a saved file. It moves the model to the specified device (CPU/GPU) and returns all components for resuming training or evaluation. | def load_checkpoint(cp: Path, device: torch.device,
) -> Tuple[AttrDict, Model, AdamW, TrainingContext, Model]:
cfg = load_cfg(cp)
model = load_model(cp, cfg)
model.to(device)
optim = load_opim(cp, cfg, model)
ctx = load_ctx(cp)
ema = load_ema(cp, cfg)
load_perf_data(cp)
... |
def _resolve_device(device: Optional[Union[str, torch.device]]
) -> torch.device:
if device is None:
return torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if isinstance(device, str):
return torch.device(device)
return device
def _resolve_img(img_or_n: Union[... | This function generates diffusion model samples in batches, yielding images at intervals determined by the ratio of requested yields (n_yields) to total diffusion steps (T). It uses a beta schedule for sampling, accumulates progress via a threshold counter, and yields images only when the threshold reaches 1.0, ensurin... | def sample_iter(model: Model, cfg: AttrDict, n_yields: int,
img_or_n: Union[Tensor, int] = 1,
device: Optional[Union[str, torch.device]] = None,
show_bar: bool = False) -> Iterator[Tensor]:
T = cfg.diffusion.T
assert n_yields <= T
device = _resolve_device(devi... |
def validate_solution(handle, problem_id, deadline):
latest_data = get_latest_submissions(handle, 20)
for submission in latest_data:
if safe_submission(submission):
if (
submission["creationTimeSeconds"] < deadline.timestamp()
and submission["verdict"]... | The main task of the code is to validate a user's solution to a programming challenge, update their virtual rating based on validation success/failure and deadline status, and return whether validation succeeded. It checks if the challenge is active, validates the solution, calculates rating changes using problem ratin... | def validate_challenge(profile):
if not profile.in_progress:
return False
validate_result = validate_solution(
profile.handle, profile.current_problem, profile.deadline
)
contest_id, index = parse_problem_id(profile.current_problem)
contest_id = int(contest_id)
problem = Probl... |
def collect_abs(n, q, alpha, a, sB, istar, l):
coeffs_abs = collect_signals(n, q, alpha, a, sB, istar, l)
return coeffs_abs
def get_zeros(coeffs, n):
zero_count = 0
temp_count = 0
for i in range(n):
if coeffs[i] == 0:
temp_count += 1
else:
if temp_count > zero... | The code implements an attack algorithm to identify valid error patterns in a cryptographic context. It processes parameters related to lattice-based cryptography, iteratively generates candidate error vectors (Sign), and verifies their validity using recursive checks (Rec, Check). The function returns `1` if a valid s... | def New_attack(n, q, alpha, a, sB, Lambda):
global zero
global query
global candi_num
global Max_candi_num
global lenErrors
ans_num = 0
AbsB = collect_abs(n, q, alpha, a, sB, 0, 4)
zero_count = get_zeros(AbsB,n)
zero += zero_count
if zero_count == 1:
return fluhrer_atta... |
def open_file(filename):
'''Read file and convert to numpy array'''
with open(filename) as input_file:
ciphertext = base64.b64decode(input_file.read())
return ciphertext
def compute_possible_key_len(cyphertext, low_key_len, high_key_len):
average_distances = []
for keysize in range(low_key_l... | The code decrypts a Vigenère cipher by reading ciphertext from a file, estimating possible key lengths using statistical analysis, and breaking the cipher with the most likely key length. It outputs the recovered plaintext and the identified key. | def main():
filename = "input_p6.txt"
ciphertext = open_file(filename)
possible_key_len = compute_possible_key_len(ciphertext, 2, 41)
plain_text, key = break_ciphertext(ciphertext, possible_key_len)
print(f"plain text: {plain_text}\nkey: {key}") |
def get_block_size(oracle):
ciphertext_length = len(oracle(''))
i = 1
while True:
data = ''
data += ''.join(['A' for _ in range(i+1)])
new_ciphertext_length = len(oracle(data))
block_size = new_ciphertext_length - ciphertext_length
if block_size:
return bl... | The code constructs an admin user profile by padding and concatenating encoded data blocks. It creates a profile with "role=admin" by manipulating the encoded string through calculated padding, exploiting block size vulnerabilities to inject the admin role into the profile, then returns the decrypted result after combi... | def create_admin_profile():
block_size = get_block_size(profile_for)
# Fixed byte of profile
fixed_byte = "email=&uid=10&role="
full_encode_len = (len(fixed_byte)//block_size + 1) * block_size
email_len = full_encode_len - len(fixed_byte)
email = 'A' * email_len
profile_prefix = profile... |
def parsing(text):
'''input format: foo=bar&baz=qux&zap=zazzle'''
kv_list = text.strip().split('&')
out_dict = {}
for i in range(len(kv_list)):
kv = kv_list[i].strip().split('=')
out_dict[kv[0]] = kv[1]
return out_dict
def profile_for(text):
'''input format: krvwu@example.com'''
... | The code processes a query string by parsing key-value pairs, generates an encoded user profile for a given email, and creates an admin profile. The main tasks involve parsing input data, encoding user information, and generating administrative user profiles for system management or authentication purposes. | def main():
my_txt = "foo=bar&baz=qux&zap=zazzle"
parsing(my_txt)
encoded_string = profile_for("oweda@example.com")
# print(encoded_string)
admin_profile = create_admin_profile()
print(admin_profile) |
def prepare_folder_data(self, meta_path, label_path):
label_files = [file for file in os.listdir(label_path) if file.endswith('.txt')]
meta_files = [file for file in os.listdir(meta_path) if file.endswith('_parse.txt')]
big_I_meta, big_P_meta, big_mius, big_labels = [], [], [], []
for... | This function evaluates a model's performance on given data by loading metadata and labels, generating predictions using a contextual predictor, and computing evaluation metrics based on specified ratios and types. It handles both single files and directories, prepares data, infers predictions, and returns evaluation r... | def evaluate_(self, meta_path, label_path, ratio, Type = 0):
# self.contextual_predictor.load_from(self.model_save_path)
I_meta, P_meta, mius, labels = [], [], [], []
if os.path.isdir(meta_path):
I_meta, P_meta, mius, labels = self.prepare_folder_data(meta_path, label_path)
... |
def get_team_list(teams_cols):
teams_df = split_bootstrap_data('teams', teams_cols)
team_list = teams_df['short_name'].tolist()
return team_list
def get_fixtures_data():
fixtures_url = base_url + '/fixtures/'
resp = requests.get(fixtures_url)
data = resp.json()
fixtures_df = pd.DataFrame(dat... | The function retrieves and processes upcoming football fixtures for specified teams, filtering by gameweek range, mapping team IDs to names, calculating FDR (Fantasy Draft Rank) averages, handling duplicates, and generating a heatmap. It aggregates fixture data, computes metrics like 'next5' opponents and their FDR, an... | def get_upcoming_fixtures(upc_gw, teams_df, fixt_num):
team_list = get_team_list(teams_cols)
fixt_df = get_fixtures_data()
fixt_df = fixt_df.loc[(fixt_df['event2'] >= upc_gw) &
(fixt_df['event2'] < upc_gw + fixt_num)]
fixt_df['home_team_name'] = fixt_df['team_h'] \
.map... |
def get_player_ids(df):
player_id_data = df[['id', 'web_name']]
#units = np.arange(len(player_id_data))
units = np.array(player_id_data.index)
ids = [player_id_data['id'][num] for num in units]
names = [player_id_data['web_name'][num] for num in units]
player_ids = {}
for i in range(0,len(i... | The function collates player data by filtering out rows with 'form' = '0.0', retrieves player IDs, and aggregates processed player data (including team stats and shifted columns) into a DataFrame. It handles the first player separately, appends subsequent players' data, and catches KeyErrors if new player data is incom... | def collate_player_history(df):
form_df = df[df['form'].astype(str) != '0.0']
ids = get_player_ids(form_df)
for i, name in ids.items():
print('Getting ' + str(name) + ' data')
if i == int(list(ids.keys())[0]):
data = get_player_data(int(list(ids.keys())[0]))
data = ge... |
def load_config(self):
print("Loading config...")
#
fname_base = "locup.config"
fname_default = "config/"+fname_base
fname_user = "user/"+fname_base
if os.path.isfile( fname_user ):
fname = fname_user
print("Found user file.")
else:
fname = fname_default
print("Using... | The main task of the code is to repeatedly run a predefined pattern with user confirmation, handling quit commands ('q') and debugging options. It loads configuration/data, prompts the user to start each pattern run, executes the pattern (or debug mode), and increments a counter after each successful run. The loop cont... | def run(self):
self.load_config()
self.load_pattern_data()
##############
while( 1 ):
#
if self.get_edges() == -1: return # quit on 'q'
#
######################################
# This section is here to make sure the human doesn't
# keep moving to edges and hitting ... |
def validate_puzzle_id(puzzle_id):
# Note - we need to ensure the puzzle exists...
try:
puzzle = get_one_row(puzzleTable, "id", puzzle_id)
if puzzle is not None:
return True
except:
print("error validating puzzle id, probably failed to query airtable")
return False
de... | This code processes incoming tweets to handle puzzle-related interactions. It checks for bot activity, extracts puzzle IDs and equations from tweets using regex, validates puzzle IDs, and queues tasks if valid. It returns appropriate responses for bots, parsing errors, or successful processing. | def on_new_tweet():
user_name = request.form.get("user__name")
tweet_id = request.form.get("id")
twitter_user_id = request.form.get("user__id")
if user_name == "Sinerider bot" or twitter_user_id == '1614221762719367168':
print("Detected bot tweet, ignoring...")
return "We don't respond ... |
def get_one_row(table, fieldToMatch, value):
formula = EQUAL(FIELD(fieldToMatch), to_airtable_value(value))
try:
all_rows = table.all(formula=formula)
if len(all_rows) == 0:
return None
return all_rows[0]
except:
print("Shouldn't have happened!")
return "... | The function `do_scoring` processes user puzzle submissions by validating the puzzle, generating a submission URL from encoded data, checking for existing scores, sending the submission to a scoring service, and notifying the user via Twitter with their result, including leaderboard status, time, character count, and a... | def do_scoring(workRow):
# Note - we need to load the puzzle URL from the Puzzles table
puzzle_id = workRow["fields"]["puzzleId"]
expression = workRow["fields"]["expression"]
player_name = workRow["fields"]["twitterHandle"]
tweet_id = workRow["fields"]["tweetId"]
print("Scoring for player: %s" %... |
def get_annotator(self, img):
return Annotator(img, line_width=self.args.line_thickness, example=str(self.model.names))
def xyxy_to_xywh(*xyxy):
"""" Calculates the relative bounding box from absolute pixel values. """
bbox_left = min([xyxy[0].item(), xyxy[2].item()])
bbox_top = min([xyxy[1].item(),... | The main task of the code is to process object detection results, track detected objects using DeepSort, and generate annotated output images with metadata. It handles batch processing, logs detection counts per class, converts bounding boxes to tracking format, applies DeepSort for tracking, and returns a dictionary c... | def write_results(self, idx, preds, batch, vid_cap):
global cfg_rslt
p, im, im0 = batch
all_outputs = []
log_string = ""
if len(im.shape) == 3:
im = im[None] # expand for batch dim
self.seen += 1
im0 = im0.copy()
if self.webcam: # batch_size... |
def get_annotator(self, img):
return Annotator(img, line_width=self.args.line_thickness, example=str(self.model.names))
def xyxy_to_xywh(*xyxy):
"""" Calculates the relative bounding box from absolute pixel values. """
bbox_left = min([xyxy[0].item(), xyxy[2].item()])
bbox_top = min([xyxy[1].item(),... | This code processes detection results by tracking objects using DeepSORT, visualizes bounding boxes with identities and labels on frames, and logs detected object counts per class. It handles batch/detection data, converts bounding box formats, updates tracking, and draws results for video/image analysis. | def write_results(self, idx, preds, batch, vid_cap):
p, im, im0 = batch
all_outputs = []
log_string = ""
if len(im.shape) == 3:
im = im[None] # expand for batch dim
self.seen += 1
im0 = im0.copy()
if self.webcam: # batch_size >= 1
log_str... |
def incomePreparsing(income, knownExpenses):
expenses = 0
for expense in knownExpenses:
expenses += expense
remainingAmount = income - expenses
return remainingAmount
def conditionsPreparsing(conditions):
parsedConditions = [{"name": condition["name"],
"isExtendable": condition[... | The code uses a genetic algorithm to optimize a budget by allocating funds based on user-defined conditions, ensuring expenses meet constraints, and handling surplus/deficit scenarios. It calculates remaining income, evolves a population of potential budgets, selects the fittest, and computes final expense allocations,... | def budgetCreationGA(income,knownExpenses,conditions, savings):
max_gen = 1000
remainingAmount = incomePreparsing(income,knownExpenses)
global usableAmount
usableAmount = remainingAmount + savings
global userIncome
userIncome = income
bestGenome = Genome([],9999)
conds = conditionsPrepa... |
def get_possible_moves(board):
possible_moves = []
for i in range(3):
for j in range(3):
if board[i][j] == '-':
possible_moves.append((i,j))
return possible_moves
def ai_turn(board, ai_player):
best_score = -1000
best_move = None
for i, j in get_possible_moves... | The function `enter_move` handles a player's or computer's turn in a game. If it's the player's turn, it prompts for valid row/column inputs until a legal move is chosen. For the computer's turn, it uses an AI function to determine the move. It updates the board with the current player's symbol and prints the updated b... | def enter_move(board, whose_turn, player):
if whose_turn == player:
print("Player move:")
while True:
i = int(input("\tPlease enter row index:"))
j = int(input("\tPlease enter column index:"))
if (i, j) in get_possible_moves(board):
break
else:... |
def get_possible_moves(self):
"""Generating a list of possible moves"""
possible_moves = []
for i in range(3):
for j in range(3):
if self.board[i][j] == '-':
possible_moves.append((i,j))
return possible_moves
def player_move(self):
... | The main task of the code is to handle a player or AI move in a game by determining the move coordinates, updating the game board with the current player's symbol, drawing the corresponding mark (X or O) at the cell's midpoint, and switching to the next player's turn. | def enter_move(self):
"""Apply the move"""
self.get_possible_moves()
if self.whose_move == self.player_symbol: i, j = self.player_move()
else: i, j = self.ai_move()
p1 , p2 = self.grid[i][j]
point = ((p1[0] + p2[0])/2, (p1[1] + p2[1])/2, 0)
self.board[i][j] = self... |
def print_board(board):
for i in board:
print('|'.join(i))
print('')
def enter_move(board, whose_turn, player):
if whose_turn == player:
print("Player move:")
while True:
i = int(input("\tPlease enter row index:"))
j = int(input("\tPlease enter column index:")... | The code simulates a Tic-Tac-Toe game between a human player (PLAYER_O) and an AI (PLAYER_X). It initializes a 3x3 board, randomly selects the starting player, and alternates turns. After each move, it checks for a win or tie. If a player wins or the game ties, it prints the result and exits. The AI's move logic is not... | def tic_tac_toe():
board = [['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']]
player = PLAYER_O
ai_player = PLAYER_X
if random.randint(0, 1):
whose_turn = player
else:
whose_turn = ai_player
print()
print_board(board)
while True:
ent... |
def create_board(self, size=CELL_SIZE):
"""Drawing a game board"""
board_location_point = rs.GetPoint("Set board starter point")
if board_location_point:
self.board_location_point = board_location_point
point = self.board_location_point
self.grid = []
for i in... | The code initializes and manages a Tic Tac Toe game by creating a board, determining the starting player (randomly between AI and human), alternating turns, checking for wins or ties after each move, and displaying results via message boxes. The loop continues until a victory or tie is detected, ensuring game flow and ... | def start(self):
"""Starts the game"""
self.create_board()
self.get_player_symbol()
# Who will start the game?
if random.randint(0, 1):
self.whose_move = self.ai_symbol
while True:
self.enter_move()
if self.is_victory():
... |
def read_file_in_a_list():
f_name = "text.txt"
employee_id_list, first_name_list, surname_list, employee_email_list, employee_salary_list = \
show_all_employee(f_name)
list1 = "ID: " + str(employee_id_list) + "\n" + "First Name: " + str(first_name_list) + \
"\n" + "Surname: " + str(surna... | The function `get_choice` routes user input to specific operations like reading files, displaying, modifying, or generating employee data based on numeric choices, with error handling for non-numeric inputs. | def get_choice(choice):
try:
if choice == int(1):
read_file_in_a_list()
elif choice == int(2):
show_employee()
find_employee()
elif choice == int(3):
change_salary()
elif choice == int(4):
add_employee()
elif choice ... |
def load_data():
employee_details_list = "Load File" + "\n" + "ID: " + str(employee_id_list) + "\n" + "First Name: " + \
str(first_name_list) + "\n" + "Surname" + str(surname_list) + \
"\n" + "Email: " + str(employee_email_list) + "\n" + \
... | The main task of the code is to manage employee data through a menu-driven interface. It loads data, displays a menu, processes user choices, and exits the loop when option 8 is selected, saving the updated data to "employees.txt". The program continuously interacts with the user until termination. | def main():
load_data()
while True:
users_choice = show_menu()
get_choice(users_choice)
if users_choice == 8:
break
save_data("employees.txt") |
def is_empty(self):
return len(self) == 0
def _swap(self, i, j):
tmp = self._index(j)
self._set(j, self._index(i))
self._set(i, tmp)
def _pop(self):
node = self._tail
self._tail = node.get_previous()
if self._tail == None:
self._data = None
self._length ... | The code removes the minimum element from a priority queue by swapping the root with the last element, popping the last element, and restoring the heap property via downheap operation. | def remove_min(self):
if self.is_empty():
raise Empty('Priority queue is empty.')
self._swap(0, self._length - 1)
item = self._pop()
self._downheap(0)
return item |
def extract_city_area_information(train_x: np.ndarray, test_x: np.ndarray) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""
Extracts the city_area information from the training and test features.
:param train_x: Training features
:param test_x: Test features
:return: Tuple of (tr... | The code loads training and test data from CSV files, extracts city area information, splits data into training/test sets, trains a model using the training data, evaluates predictions on the test set, computes a cost function, and optionally performs extended evaluation. It also includes plotting and counting area-spe... | def main():
train_x = np.loadtxt('train_x.csv', delimiter=',', skiprows=1)
train_y = np.loadtxt('train_y.csv', delimiter=',', skiprows=1)
test_x = np.loadtxt('test_x.csv', delimiter=',', skiprows=1)
# Extract the city_area information
train_x_2D, train_x_AREA, test_x_2D, test_x_AREA = extract_city_... |
def place_project(config):
"""
Places the Visual Studio project in the build directory
:param config: The project configuration settings
:type config: ``dict``
:return: The project (sub)directory
:rtype: ``str``
"""
entries = ['root','build','camel']
util.check_config_keys(config... | (The code generates a Visual Studio project using provided configuration settings, copying templates, modifying project files, adding source files, and optionally generating icons. It prepares the project structure for manual building in Visual Studio rather than compiling it directly.) | def make(config):
"""
Creates the Vsual Studio project
This only creates the Visual Studio project; it does not actually build the
project. To build the project, you must open it up in Visual Studio.
:param config: The project configuration settings
:type config: ``dict``
"""
print()
... |
def place_project(config):
"""
Places the Android project in the build directory
:param config: The project configuration settings
:type config: ``dict``
:return: The project directory
:rtype: ``str``
"""
entries = ['root','build','camel','appid']
util.check_config_keys(c... | The main task of the code is to configure and generate an Android Studio project structure based on provided settings. It copies the project template, modifies Gradle settings, adjusts NDK/CMake build files, and generates Android icons if specified. The function does not compile the project, only sets up the necessary ... | def make(config):
"""
Creates the Android Studio project
This only creates the Android Studio project; it does not actually build the project.
To build the project, you must open it up in Android Studio.
:param config: The project configuration settings
:type config: ``dict``
"""
... |
def place_project(config):
"""
Places the XCode project in the build directory
:param config: The project configuration settings
:type config: ``dict``
:return: The project directory
:rtype: ``str``
"""
entries = ['root','build','camel']
util.check_config_keys(config,entr... | The code generates an XCode project structure based on a configuration dictionary, modifying project settings, adding assets/sources, adjusting build targets, and generating icons if specified. It creates necessary files but does not compile the project, requiring manual opening in XCode for building. | def make(config):
"""
Creates the XCode project
This only creates the XCode project; it does not actually build the project. To
build the project, you must open it up in XCode.
:param config: The project configuration settings
:type config: ``dict``
"""
print()
print('Conf... |
def gen_macos(self,root):
"""
Generates the icons for macOS
The icons will be placed in the 'Mac.xcassets/AppIcon.appiconset' subdirectory
of the root directory. To add icons directly to an XCode project, the root should
be the Resources folder of your XCode project.
... | The code generates platform-specific application icons (iOS, macOS, Android, Windows) within subdirectories under the provided root path. It checks for a valid image source, then delegates icon creation to platform-specific methods, organizing outputs into platform-named folders while maintaining directory structure co... | def generate(self,root):
"""
Generates the icons for all major platforms.
The icons will be placed relative to the given root directory. Each platform will
get a subfolder for its name (e.g. iOS, macOS, android, windows). See the platform
specific generation methods for ... |
def ciphertext_from_file(file_name):
"""
Take the base64 encoded ciphertext and decode it to return the ciphertext
:param file_name: name of the file containing the ciphertext
:return: base64 decoded ciphertext
"""
with open(file_name, "r") as f:
text = f.read().replace("\n", "")
... | The code decrypts a ciphertext by testing possible key sizes. It reads the ciphertext, identifies key sizes with minimal distance, transposes the ciphertext into blocks, deciphers each block to find likely plaintext, and assembles the results. The goal is to determine the most probable plaintext and corresponding key s... | def main():
ciphertext = ciphertext_from_file("6.txt").decode("utf-8")
key_sizes = get_key_size_with_smallest_distance(ciphertext)
for size in key_sizes:
plaintexts = []
blocks = transpose_ciphertext(ciphertext, size)
for block in blocks:
plaintexts.append(find_likely_pla... |
def _is_sender_user_owner(sender_user_uuid: uuid.UUID,
requested_user_uuid: uuid.UUID) -> bool:
"""
Returns:
--------
boolean value, that represents meaning "is user owner or not"
Parameters:
-----------
sender_user_uuid: uuid.UUID
requested_user_uu... | The function prepares and returns a context dictionary for rendering a user profile page in a Django template, containing the requested user's data, task counts grouped by period, friend list, ownership status, selected period details, additional period options, and a date filter parameter for template rendering. | def get_context_for_userprofile_page(request: HttpRequest,
period_abbreviature: str,
requested_user_uuid: uuid.UUID):
"""
Returns:
--------
context for view with next keys:
:dict_key: 'user' -- CustomUser model
... |
def combined_prior(self):
"""
Combined prior distribution function for parameters: mu, sigma, amplitude, and delta_w.
Returns:
- prior: Function representing the combined prior probability density.
"""
c=299792.458
amp_low = 0.05
amp_high = 0.6
mu... | The code performs posterior analysis using the Metropolis-Hastings MCMC algorithm to sample parameter values from a posterior distribution. It iteratively proposes new parameters, evaluates their likelihood and prior probabilities, and accepts/rejects them based on an acceptance ratio. Accepted samples are stored and r... | def posterior_analysis(self, wv, flux, wvc, initial_param, num_iterations):
"""
Perform posterior analysis using the Metropolis-Hastings MCMC algorithm.
Parameters:
- wv (array-like): Array of observed wavelengths.
- flux (array-like): Array of observed flux values corre... |
def _draw_register_outline(self, register: Register, label: str, draw_x: bool = False) -> None:
if label is not None:
self._dwg.add(
self._dwg.text(label, x=[str(float(self._current_size_parameters['left_offset'] / 2)) + "mm"],
y=[str(float((self._verti... | This method visualizes a register's structure by drawing its outline, top strands, and cell strand labels. It uses internal methods to render the register's boundary, strand connections, and textual annotations, with optional X-axis visualization. The function orchestrates the layout of biological or data elements with... | def draw_contents(self, register: Register, label: Optional[str] = None, draw_x: bool = False) -> None:
self._draw_register_outline(register, label, draw_x)
self.draw_strands(register, register.top_strands, 1)
self._draw_cell_strand_labels(register) |
def create_basic_strand_types(transition_data, domain_template, simulation):
import seaborn as sns
palette = sns.color_palette(None, len(transition_data) + 3)
palette = [convert_rgb_to_hex(*x) for x in palette]
strand_name_template = '({},{})_{}'
strand_data = Strand([], False)
for key, color i... | This function prepares simulation data for a Turing Machine (TM) by clearing existing simulation structures, creating a 'Tape cell' with domains derived from transition rules, generating strand types, encoding register data, and producing TM instructions. It translates TM transition logic into SIMD-compatible simulatio... | def generate_tm_to_simd_data_from_transitions(transition_data, tm_data, register_name, simulation):
simulation.cell_types.clear()
simulation.strand_types.clear()
simulation.registers.clear()
simulation.instructions.clear()
# Create cell type
tape_cell = Cell([])
domain_template = '({},{})-{... |
def contains_outside_list(items: List, restricted_chars: List[str]) -> bool:
for item in items:
if str(item) not in restricted_chars:
return True
return False
def add_simd_transition(state, read, data, transition_data) -> None:
key = (state, read)
if 'write' not in data.keys():
... | This function converts a Turing Machine (TM) described in a YAML file into SIMD instructions. It validates the TM's transition table for supported symbols (0, 1, blank), processes transitions, and generates SIMD-compatible data if valid. If unsupported symbols are detected, it aborts with an error message. | def convert_tm_to_simd(simulation: Simulation) -> None:
filename = input('Enter the YAML file name: ')
with open(filename, 'r') as file:
data = yaml.safe_load(file)
if 'input' not in data.keys():
data['input'] = ''
blank = str(data['blank'])
state_table_contains_uns... |
def calculate_expected_total_cells(obs_barcodes: int, n_gems: int = N_G) -> float:
"""Solve for the observed cell counts.
Given an observed number of cell barcodes, try to solve for
the number of likely observed cells in the original mixture by estimating the number
of different k-lets implied by that ... | The code initializes a Joint Inference model that exploits stoichiometry to estimate cell populations and latent states. It configures parameters like maximum k-lets, generates multiplet combinations (latent states), prepares data matrices for regression, and sets initial values for optimization. The model integrates o... | def __init__(
self,
data,
model,
optimize_pop_freqs=False,
max_k_lets=_MAX_K_LETS_TO_CONSIDER,
n_gems=N_G,
):
"""
Fit a Joint Inference by Exploiting Stoichiometry
:param data:
:param model:
:param optimize_pop_freqs: Optimize t... |
def init_game(self):
self.run, self.win, self.auto = True, False, False
self.point, self.open = 0, 0
self.boom_cell = None
mines = random.sample(range(self.rows*self.cols), self.mines)
self.squares = []
for i in range(self.rows*self.cols):
val = MINE if i in ... | The main task of the code is to handle user input events in a Pygame game. It processes keyboard commands (QUIT, restart, toggle auto-mode, flagging) and mouse clicks to interact with game squares, opening them or toggling flags, while managing game state transitions like initialization and termination. | def user_play(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.run = False
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
if not self.run:
s... |
def flagging(self):
for square in self.squares:
if not square.visible:
square.flag = False
for square in self.squares:
if square.visible and square.val > 0: # square is open and have mines around
neibors, neibors_flag = [], []
r,c... | The code's main task is to control an agent's action in a grid-based game (e.g., Minesweeper). If no initial point is set, it randomly selects a square. Otherwise, it uses the agent's value-based strategy to flag potential mines and choose an action. The agent then opens an unvisited, unflagged square, introducing a 1-... | def agent_play(self):
if self.point == 0:
i = random.randint(0, self.rows * self.cols - 1)
square = self.squares[i]
else:
if self.agent.is_value_based():
self.flagging()
square = self.agent_action()
if not square.visible and not sq... |
def agent_play(self):
if self.point == 0:
i = random.randint(0, self.rows * self.cols - 1)
square = self.squares[i]
else:
if self.agent.is_value_based():
self.flagging()
square = self.agent_action()
if not square.visible and not sq... | The code's main task is to continuously run either agent-controlled or user-controlled gameplay in a loop, based on the 'auto' flag, and update the display with 'self.paint()' after each iteration. It checks 'self.auto' and 'self.run' to decide between agent_play() or user_play(), ensuring persistent game execution and... | def start(self):
while True:
if self.auto: # agent play
if self.run:
self.agent_play()
else: # user play
self.user_play()
self.paint() |
def printIntro():
print("This progra sumulate a game of racquetball between two")
print("player called A and B , the ability of each other is")
print("indicated by a probability that")
print("The player wins the point when serving, Player A always")
print("has the first serve.")
def getInputs():
... | The main task of the code is to simulate a series of games between two players with specified probabilities of winning each game. It begins by printing an introduction, retrieves user inputs for probabilities and number of games, simulates the games, and finally prints a summary of the results, including the number of ... | def main():
printIntro()
probA , porbB , n = getInputs()
winsA , winsB = simNGame(n,probA, porbB)
printSummary(n,winsA, winsB) |
def MCpaths(x,G):
for j in range(0,N): #Empties array
x[j]=0;
for j in range(0, 5*N_COR): #Thermalizes array
update(x)
for alpha in range(0, N_CF): #Calculates G[alpha][n]
for j in range(0, N_COR):
update(x)
... | The main task of the code is to compute and visualize correlation functions (G(t)) and energy differences (ΔE(t)) from Monte Carlo simulations. It performs binning, bootstrap resampling for error estimation, and plots the averaged correlation function against an exponential decay model. The code also visualizes ΔE(t) w... | def main():
'''
Defining path x as an array and the correlation function as a 2D array
'''
x = np.zeros(N);
G_cor = np.zeros((N_CF, N));
btsp = []
ave_tot_G = []
##Creates the correlation functions for each time slice and configuration
MCpaths(x, G_cor)
... |
def cup(rtn, motorcoor, Grip):
"motorcoor = [[pos1x,pos1y,pos1z],[pos2x,pos2y,pos2z],[pos3x,pos3y,pos3z]]"
InvokeGripper = Grip[0]
OpenGripper = Grip[1]
P = 1
for code in motorcoor:
"code = [pos1x,pos1y,pos1z]"
xcoor = code[0]
ycoor = code[1]
zcoor = code[2]
... | The main task of the code is to automate a robotic coffee-making system by controlling a robotic arm to pick up cups, dispense coffee/sugar/milk based on orders, and deliver to a person. It manages gripper states, navigates to predefined cup/dispenser/person locations, processes order quantities, and uses servos for di... | def main():
print("Main initialize...")
Operation = True
CupSide = True # Prata flip for cupside, cus 2 cup slot
Grip = [True,True] # 1st for invoking grip action (True to invoke), 2nd for open/close of g... |
def handle_help(self, message):
memes = sorted([
f'{k} ({v["id"]})' for k, v in self.templates_by_name.items()])
thread = self.api.create_thread(message)
while memes:
msg = '\n- {}'.format('\n- '.join(memes[:50]))
self.api.create_message(thread['id'], msg)
... | This code processes incoming messages to trigger meme-related actions. It checks for a help command, searches for predefined meme patterns in the message content, and executes corresponding handlers. If no specific pattern matches, it uses a general regex to identify meme triggers and applies the appropriate handling l... | def handle(self, message):
content = message.data.get('content')
if isinstance(content, str):
if content.lower().startswith('!help memes'):
self.handle_help(message)
return None
matches = [
m for m in [
(i, re.... |
def __drawn_on_figure_window(self):
"""
The method to check whether the figure is drawn on figure window or not.
Returns
-------
boolean
True if the figure is drawn on figure window.
"""
return len(self.__gui.corpus) > 40
def __reset_canvas(self):
... | This function handles a canvas click event to initiate clustering. It checks if the cut status is active, determines a cutoff value from the event's x/y data, resets the canvas, starts a clustering thread with the cutoff, and redraws the figure. | def _canvas_on_click(event):
# Check whether cut status is True or not.
if event.inaxes is not None and self.__gui.cut_status is True:
if not self.__drawn_on_figure_window():
cut_off = event.xdata
else:
... |
def load_policy(self):
with open(self.policy_file_name, 'rb') as f:
self.state_values = pickle.load(f)
def decay_epsilon(self):
if self.epsilon > self.epsilon_min:
self.epsilon = self.epsilon * self.epsilon_decay
def get_available_actions(self, board):
i, j = np.where(boa... | This code trains a reinforcement learning agent for Tic Tac Toe by playing multiple games, updating policy values based on rewards, and saving the learned policy. It loads an existing policy if available, decays exploration rate (epsilon) periodically, tracks game states, and iteratively improves the agent's decision-m... | def do_training(self, games_to_play):
# Check for existing policy to continue training
if os.path.isfile(self.policy_file_name):
self.load_policy()
# Train!
for current_game in range(games_to_play):
if current_game % 1000 == 0:
print(f'playing game... |
def load_policy(self):
with open(self.policy_file_name, 'rb') as f:
self.state_values = pickle.load(f)
def get_available_actions(self, board):
i, j = np.where(board == 0)
self.avail_actions = list(zip(i,j))
def choose_action(self):
if self.playing_human:
action, n... | This code simulates a game where the CPU (agent) plays against a human, recording game states and rewards. It uses imitation learning to update its policy based on gameplay history, storing states and rewards during the game. After completion, it replays the game data to adjust the policy and saves the updated strategy... | def play_human(self, game):
# Check for existing policy to continue training
if os.path.isfile(self.policy_file_name):
self.load_policy()
self.game = game
else:
print('No policy available!')
return
if self.side == self.game.player_now:
... |
def keyMenuProcessingFunction():
global pageID, timeSettingLabel
if pageID == 2 and selectSettingOptions <= 1:
timeSettingLabel += 1
if timeSettingLabel > 2:
timeSettingLabel = 0
pageID += 1
if pageID > 2:
pageID = 2
def judgmentBuzzerSwitch():
global startBeepFla... | This function processes key inputs by incrementing counters for menu, down, and up keys. It triggers specific processing functions when counters are within a threshold (0-20) and resets them. It manages a buzzer by counting beeps and turning it off after three beeps. If counters exceed 20, it resets them or calls exit ... | def keyProcessing(keyValue):
global keyMenuValue, keyDownValue, keyUpValue, beepCount, startBeepFlag
if keyValue == KEY_MENU:
keyMenuValue += 1
if keyValue == KEY_DOWN:
keyDownValue += 1
if keyValue == KEY_UP:
keyUpValue += 1
if startBeepFlag == 1:
beepCount += 1
... |
def parse_arguments():
parser = argparse.ArgumentParser(description='Image captioning script with optional output clearing.')
parser.add_argument('--clear-output', action='store_true', help='Clear the output directory and delete the captions file.')
return parser.parse_args()
def clear_output(output_dir, ca... | The main task of the code is to generate image captions using multiple pre-trained models (Salesforce BLIP and nlpconnect ViT-GPT2) for images in a specified input directory. It recursively processes images, saves outputs in a designated folder, and writes captions to a Markdown file. The script optionally clears exist... | def main():
args = parse_arguments()
input_dir = 'data/input'
output_dir = 'data/output'
captions_file = 'captioned_images.md'
models = ['Salesforce/blip-image-captioning-base',
'Salesforce/blip-image-captioning-large',
'nlpconnect/vit-gpt2-image-captioning']
if ... |
def __search_artist(self, artist_name):
url = 'https://api.spotify.com/v1/search'
params = {
'q': artist_name,
'type': 'artist',
'limit': 1
}
json_result = self.__make_request(url, params)
artist = json_result['artists']['items'][0]
ret... | This function retrieves comprehensive information about an artist, including their albums, tracks, and track features. It starts by searching for the artist's ID, then fetches their albums, extracts album IDs, and gathers album details. It subsequently retrieves track data from these albums, collects track IDs, and obt... | def get_all_information_from_artist(self, artist_name: str):
artist_information = self.__search_artist(artist_name)
artist_id = artist_information.get('id')
albums_of_artist = self.__get_albums_of_artist(
artist_id, limit=20)
albums_id = [album.get('id') for album in albums_... |
def getSession(self):
self.session = requests.session()
self.header = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Connection':... | The code's main task is to initiate a process by retrieving a session, preparing data, and executing operations to post daily options data and download CSV files. The `start` method orchestrates these steps sequentially, with an optional mock data feature commented out. | def start(self):
self.getSession()
self.prepareData()
#self.mockData()
self.postDailyOption()
self.postDownloadCsv() |
def getSession(self):
self.session = requests.session()
self.header = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Connection':... | The main task of the code is to execute a sequence of methods (`getSession()`, `getQueryDate()`, `getMarketCode()`) to perform automated data retrieval or setup, while measuring and printing the total execution time in seconds. The method initializes a timer, invokes these operations, and outputs a completion status al... | def auto(self):
start_time = time.time()
self.getSession()
self.getQueryDate()
self.getMarketCode()
print('\tDone!')
print("Elapsed time:", time.time() - start_time, "seconds") |
def menu():
option = int(input())
if option == 1: return random_board()
elif option == 2: return user_board()
elif option == 3: return input_positions()
else: print("Only enter 1, 2 or 3")
def black_king_moves(Q_moves, K_moves, k_matrix):
Q_cords = util.cords(Q_moves)
K_cords = util.cords(K_moves)
k_cor... | The code analyzes a chess board's state by determining the queen's and kings' possible moves, checks if the black king is in check, and identifies checkmate conditions. It retrieves piece positions, calculates move matrices, and evaluates threats to the black king. The output includes valid moves, check status, and che... | def execution():
board = menu()
print()
util.print_board(board)
k_cord = util.find_piece('k', board)
K_cord = util.find_piece('K', board)
Q_cord = util.find_piece('Q', board)
Q_moves = piece.Q_moves(Q_cord, K_cord)
K_matrix = piece.king_moves(K_cord)
k_matrix = piece.king_moves(k_cord)
print(black_k... |
def readStateInfo (self, current_state):
# reads and returns relevant information for state operations
turn_size = len (self.att_ship_list) + len (self.def_ship_list)
# which ship is firing ?
after_damage_state = current_state.copy()
turn = after_damage_state[0]
if turn ... | The function computes the win chance for a given game state by iterating through all possible damage outcomes, applying damages, and recursively determining the best next state assignment. It aggregates probabilities weighted by their likelihood, considering alive entities and transition outcomes. If no entities are al... | def computeStateWinChance (self, current_state) :
# Writes and solves the win chance equation for the hp state for all round
# round number is added at the start of the index
turn, sign, after_damage_state, indexes, alive, npc_flag, prio_list, prio_rift_list = self.readStateInfo (current_state... |
def readStateInfo (self, current_state):
# reads and returns relevant information for state operations
turn_size = len (self.att_ship_list) + len (self.def_ship_list)
# which ship is firing ?
after_damage_state = current_state.copy()
turn = after_damage_state[0]
if turn ... | This function propagates state expectancy by iterating through possible damage outcomes, applying self-inflicted damage, evaluating optimal next states, and updating the state expectancy dictionary with weighted probabilities based on current state values. | def propagateStateExpectancy (self, current_state, full_miss) :
# Ranges all dice results and propagates expectancy through it
turn, sign, after_damage_state, indexes, alive, npc_flag, prio_list, prio_rift_list = self.readStateInfo (current_state)
if alive >0:
damages_per_result = ... |
def listToTuple (integer_list):
tuple = ()
for integer in integer_list:
tuple += (integer,)
return (tuple)
def propagateStateExpectancy (self, current_state, full_miss) :
# Ranges all dice results and propagates expectancy through it
turn, sign, after_damage_state, indexes, alive, n... | This code computes the battle expectancy for a turnless state in a strategy game, handling scenarios where all attacker or defender ships are destroyed. It propagates missile round expectancies, solves a linear system for canon rounds (accounting for recursive dependencies), and updates win probabilities and ship survi... | def computeExpectancy(self, turnless_state):
turn_size = len (self.att_ship_list) + len (self.def_ship_list)
#check whether there is at least 1 ship alive
att_hp =0
def_hp =0
for i in range (self.att_index, self.def_index ):
att_hp += turnless_state[i]
... |
def blockSize (nb_ships, hull):
#computes the size of a state block for given number of ships and hull
block = 1
for i in range (1, nb_ships+1):
block = (block*(hull+1+i))//i
return (block)
def makeGraph (nb_ships, hull, print_tables=False):
# makes 5 table which, for each index, says how ma... | This code simulates a battle between attacker and defender ships, calculating the probability of each side winning based on ship attributes (hit points, initiative, etc.) using dynamic programming. It propagates win chances backward through possible states, then forward to compute survival probabilities, finally genera... | def __init__ (self, attacker_ship_list, defender_ship_list, remaining_ships = True):
self.att_ship_list = attacker_ship_list
self.def_ship_list = defender_ship_list
# State of battle is one big array, with each coordinate corresponding to :
# 0: round initiative order
# 1-end-... |
def find_id_band(self, band):
for obj in self.list_bands:
if obj.name_band == band:
return obj.id_band
return None
def get_connect(self):
p = '/home/julie47/JUST_DO/python/WEB2(4)/app/data/app.db'
return sqlite3.connect(p)
def refresh(self):
self.selec... | This function saves album data to a database after validating non-empty inputs. It converts price to an integer, retrieves the band's ID, inserts the album details into the 'albums' table, commits the transaction, and returns a success message. If any required fields are empty, it returns an error message. | def save_alb(self, band, name_alb, date, price):
price = int(price)
if name_alb != "" and date != "" and price != "" and band != "":
id_band = self.find_id_band(band)
conn = self.get_connect()
c = conn.cursor()
sql = ''' INSERT INTO albums(name_album, a_da... |
def _parse_args(argv=None) -> argparse.Namespace:
"""Parse command-line args."""
def _positive_int(value):
"""Define a positive integer ArgumentParser type."""
value = int(value)
if value <= 0:
raise argparse.ArgumentTypeError(
"Value must be positive, {} was... | The code processes input text files into structured dialogue datasets, splits them into training and test sets, and saves them as JSON files for machine learning tasks. It parses command-line arguments, concatenates file contents, processes lines into dialogues, splits data proportionally, and writes outputs to specifi... | def run(argv=None):
args = _parse_args(argv)
raw_data = _concat_files(list(Path(args.sentence_files).iterdir())[:NUMBER_OF_SPLITS])
print("Processing files...")
dialogues = _process_lines(raw_data, args)
print("Splitting to train and test...")
train, test = _split_dataset(dialogues, args.train_s... |
def generate_maze(self):
grid_width = MAZE_WIDTH // GRID_SIZE
grid_height = MAZE_HEIGHT // GRID_SIZE
grid = [[0 for _ in range(grid_width)] for _ in range(grid_height)]
self.recursive_division(grid, 0, 0, grid_width, grid_height)
maze_walls = pygame.sprite.Group() # Create a sp... | The code's main task is to train a model, generate a maze, and run a game loop that handles user events, auto-plays the game by moving a player along a path if enabled, and renders the game state with delays. It initializes Pygame, manages game logic, and quits the game when done. | def run(self):
# Train on data
self.model, self.X_test, self.y_test = start_training()
# Generate the maze
self.generate_maze()
while self.running:
self.handle_events()
if self.values["Auto-play"]:
self.player.move_along_path(self.path)
... |
def FormatString(self):
print(" PC OPC INS AMOD OPRND AC XR YR SP NV-BDIZC")
def checkingNegativeAndZero(self, register):
if register == 0:
self.Z = 1
else:
self.Z = 0
if (register & 128) >> 7 == 1:
self.N = 1
else:
self.N = 0... | This code simulates CPU execution by processing opcodes, updating registers/flags, and printing detailed execution traces. It handles arithmetic, branching, stack operations, and memory access for a 6502-like processor, executing instructions until encountering opcode '00', with each cycle modifying the program counter... | def PrintRunningProgram(self, userInput):
self.FormatString();
userInput = userInput[:-1]
self.PC = int(userInput, 16)
count = 0
self.N = 0
self.V = 0
self.B = 0
self.D = 0
self.I = 0
self.Z = 0
self.C = 0
self.OPRND1 = 0
... |
def get_available_device():
"""
Allows training on GPU if available. Can help with running things faster when a GPU with cuda is
available but not a most...
Given a device, one can use module.to(device)
and criterion.to(device) so that all the computations will be done on the GPU.
"""
return... | The function `train_and_test_helper` trains and evaluates specified models (LogLinear_1, LogLinear_W2V, LSTM) using different data configurations (one-hot, word2vec). It initializes data managers, constructs models, trains them with hyperparameters, tests on validation data, computes accuracy/loss, and saves results fo... | def train_and_test_helper(model_name):
dm = None
model = None
# TRAIN
if model_name == "LogLinear_1":
dm = DataManager(data_type=ONEHOT_AVERAGE, batch_size=64)
model = LogLinear(dm.get_input_shape()[0]).to(get_available_device())
train_model(model, dm, LogLinear_epochs, 0.01, 0.0... |
def MLE_b_train(self):
"""
(b)
Trains the model. emissions e(xi|yi) and transmission q(yi|y_i-1) probabilities
based on MLE
:return:
"""
print("------Train 4b------")
for sent in self.train_set:
for word, tag in sent:
tag = self... | The function performs a smoothed probabilistic word alignment test using the Viterbi algorithm. It ensures prerequisite models (MLE_b, MLE_4c, MLE_4e) are trained, then applies Viterbi on the input sentence with smoothed emission probabilities from the trained models to determine optimal alignment. | def e_smoothed_pw_test(self, sent):
if not self.b4_trained:
self.MLE_b_train()
if not self.c4_trained:
self.MLE_4c_train()
if not self.e4_trained:
self.mle_4e_train()
return self.viterbi(sent, self.t_mle, self.e_mle_pw_smoothed) |
def MLE_b_train(self):
"""
(b)
Trains the model. emissions e(xi|yi) and transmission q(yi|y_i-1) probabilities
based on MLE
:return:
"""
print("------Train 4b------")
for sent in self.train_set:
for word, tag in sent:
tag = self... | This method ensures all necessary models (b4, c4, e4) are trained using MLE, then applies the Viterbi algorithm on the input sentence with smoothed emission probabilities from the e4 model to perform a probabilistic tagging or sequence prediction task. | def e_smoothed_pw_test_nz(self, sent):
if not self.b4_trained:
self.MLE_b_train()
if not self.c4_trained:
self.MLE_4c_train()
if not self.e4_trained:
self.mle_4e_train()
return self.viterbi(sent, self.t_mle, self.e_mle_pw_smoothed_nz) |
def MLE_b_test(self, sentence):
"""
Returns the tag that appeared most often with the given word
formally it is max{p(tag|word)} by the MLE: #(tag,word)/#(word)
Since this is a maximum query, not the exact probability we can omit the division by constant #(word)
:param sentence... | This function evaluates the accuracy of a part-of-speech tagging model by comparing predicted tags with true tags in a test set. It computes three metrics: overall accuracy (correct/total), accuracy excluding unseen words, and the proportion of correct unseen words. The function handles multiple model types, updates a ... | def accuracy(self, model):
"""
accuracy measures the number of correctly tagged words divided by the test set size
model - the model we are testing
"""
counter_correct, counter_total, counter_unseen, unseen_correct = 0, 0, 0, 0
size = sum([len(self.test_set[i]) for i in r... |
def squareUnderAttack(self, r, c):
self.whiteToMove = not self.whiteToMove # switches to opponents turn
oppMoves = self.getAllPossibleMoves()
self.whiteToMove = not self.whiteToMove
for move in oppMoves:
if move.endRow == r and move.endCol == c:
return True
... | This function generates valid castling moves for a chess game. It first checks if the king's current square is under attack, returning early if so. Then, it checks if kingside or queenside castling is permitted based on turn and castling rights, calling respective methods to add valid moves to the list. | def getCastleMoves(self, r, c, moves):
if self.squareUnderAttack(r, c):
return # Can't castle while in check
if (self.whiteToMove and self.currentCastlingRight.wks) or (not self.whiteToMove and self.currentCastlingRight.bks):
self.getKingSideCastleMoves(r, c, moves)
if ... |
def getAllPossibleMoves(self, board='gs'):
if board == 'gs':
board = self.board
elif board == 'chessboard':
board = self.chessboard
moves = []
for r in range(len(board)):
for c in range(len(board[r])): # length of current row we are looking at for co... | This function generates valid chess moves by first collecting all possible moves, then filtering out those that leave the king in check. It temporarily stores en passant and castling rights, simulates each move, checks for king safety, and removes invalid moves. It also handles castling moves and determines checkmate/s... | def getValidMoves(self, board='gs'):
if board == 'gs':
board = self.board
elif board == 'chessboard':
board = self.chessboard
tempEnpassantPossible = self.enpassantPossible
tempCastleRights = CastleRights(self.currentCastlingRight.wks, self.currentCastlingRight.bk... |
def connect_to_blockchains():
try:
# If g.acl has not been defined yet, then trying to query it fails
acl_flag = False
g.acl
except AttributeError as ae:
acl_flag = True
try:
if acl_flag or not g.acl.status():
# Define Algorand client for the application
... | The main task of the code is to process a trade request by validating the payload's required fields, verifying cryptographic signatures, and checking blockchain transaction details (Ethereum/Algorand) to ensure authenticity and correctness before committing the order or rejecting it with errors. | def trade():
# time.sleep(3)
print("In trade", file=sys.stderr)
connect_to_blockchains()
# get_keys()
if request.method == "POST":
content = request.get_json(silent=True)
columns = ["buy_currency", "sell_currency", "buy_amount", "sell_amount", "platform", "tx_id", "receiver_pk"]
... |
def check_relation_already_reserved(self, relation):
with open(self.multi_config_file_path, 'r') as file:
multi_config = json.load(file)
if relation in multi_config['started_relations']:
return True
else:
with open(self.multi_config_file_path, 'w') as file:
... | The code manages a pipeline for processing relations by creating output directories, logging operations, and conditionally executing relation-specific tasks. It handles multi-processing by checking if relations are already processed, runs them if not, joins processes, and resets resources. The main task involves orches... | def run(self):
Path(self.output_folder + f"{self.name}/summary").mkdir(parents=True, exist_ok=True)
Path(self.output_folder + f"{self.name}/facts").mkdir(parents=True, exist_ok=True)
logger.info(f"Starting Run for these Relations: {self.relations}")
token_dict = {}
for relation i... |
def generate_subkey(key):
# P10
key = p10(key)
# split key
key_l = key[:5]
key_r = key[5:]
# LS-1
key_l_shifted = key_shift(key_l)
key_r_shifted = key_shift(key_r)
key = key_l_shifted + key_r_shifted
# P8 --> subkey 0
subkey_0 = p8(key)
# split key2
key_l = key[:5]
... | The code implements a simplified Data Encryption Standard (DES) algorithm. It encrypts plaintext by applying an initial permutation, two rounds of Feistel networks using generated subkeys, and a final permutation to produce ciphertext. The process involves key scheduling, substitution, and permutation operations to ens... | def des_encrypt(plaintext, key):
state = plaintext
# subkey generation (scheduling) = generate 2 subkeys
subkeys = generate_subkey(key)
# initial permutation
state = ip(state)
# 2 fiestel networks
for i in range(2):
state = feistel(state, subkeys[i])
# final permutation
state... |
def __stop_consumer(self):
self.logger.info('>>> Stop consumer service.')
script = """
# noqa: E501
CID_FILE={task_home}/consumer/run.cid
CID=$(cat $CID_FILE)
cat ~/.passwd | sudo -S -p '' docker stop $CID
cat ~/.passwd | sudo -S -p '' docker... | The main task of the code is to gracefully stop or terminate related services by sequentially invoking three private methods: stopping the consumer service, stopping the provider services, and stopping the etcd (distributed key-value store) component, ensuring a controlled shutdown of the system's core functionalities. | def __stop_services(self):
self.__stop_consumer()
self.__stop_providers()
self.__stop_etcd() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.