dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def make_post_data(self, data):
"""
process a dictionary of {parameter names : parameter data} in order to
generate appropriate post_data data to add to the REST call
Args:
data {parameter names : parameter data} : a dictionary representing the post_datas
... | The function retrieves withdrawal fee and status information for a specified asset and withdrawal method by making a POST request to a private API endpoint, returning details like method, asset, amount, fee, status, and transaction data. | def get_withdrawstatus(self, asset, method=""):
"""
Retrieve fee information about potential withdrawals for a particular asset, key and amount.
Args:
asset: (string) REQUIRED - asset being withdrawn
method: (string) name of withdrawal method
Returns:
... |
def make_post_data(self, data):
"""
process a dictionary of {parameter names : parameter data} in order to
generate appropriate post_data data to add to the REST call
Args:
data {parameter names : parameter data} : a dictionary representing the post_datas
... | This function cancels a cryptocurrency withdrawal request by sending a POST request to the 'WithdrawlCancel' API endpoint with specified asset and withdrawal reference ID (refid). It prepares the request data, executes the call, and returns the processed response containing cancellation status or related information. | def cancel_withdraw(self, asset, refid):
"""
Retrieve fee information about potential withdrawals for a particular asset, key and amount.
Args:
asset: (string) REQUIRED - asset being withdrawn
refid: (string) REQUIRED - withdrawal reference ID
Returns:
... |
def make_post_data(self, data):
"""
process a dictionary of {parameter names : parameter data} in order to
generate appropriate post_data data to add to the REST call
Args:
data {parameter names : parameter data} : a dictionary representing the post_datas
... | This function facilitates transferring assets between Kraken wallets, specifically from the Spot Wallet to the Futures Wallet. It constructs a POST request with parameters like asset, amount, and transfer direction, then processes the API response. The reverse transfer (Futures to Spot) requires a separate Kraken Futur... | def request_wallet_transfer(self, asset, amount, frm="Spot Wallet", to="Futures Wallet"):
"""
Transfer from Kraken spot wallet to Kraken Futures holding wallet. Note that a transfer in the other direction
must be requested via the Kraken Futures API endpoint.
Args:
asset: (st... |
def open_initial_window(self):
cv2.namedWindow("Frame with Keypoints")
def process_frames(self):
text_thread = threading.Thread(target=self.update_text)
text_thread.start()
while True:
ret, frame = self.video_captured.read()
frame = cv2.resize(frame, (640, 360))
... | The main task of the code is to initialize a window, process frames to identify a body, and then clean up resources. The `find_body` method sequentially opens an initial window, processes frames (likely for detection or analysis), and releases resources, ensuring proper execution and cleanup of the task. | def find_body(self):
self.open_initial_window()
self.process_frames()
self.cleanup() |
def setIcmpType(self, icmpType):
self.__icmpType = icmpType
def setIcmpCode(self, icmpCode):
self.__icmpCode = icmpCode
def setPacketIdentifier(self, packetIdentifier):
self.__packetIdentifier = packetIdentifier
def setPacketSequenceNumber(self, sequenceNumber):
self.__pa... | This function constructs an ICMP echo request packet by setting its type to 8 (echo request), code to 0, assigning the provided identifier and sequence number, adding fixed test data, and recalculating the checksum for proper packet formatting. | def buildPacket_echoRequest(self, packetIdentifier, packetSequenceNumber):
self.setIcmpType(8)
self.setIcmpCode(0)
self.setPacketIdentifier(packetIdentifier)
self.setPacketSequenceNumber(packetSequenceNumber)
self.__dataRaw = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg... |
def _run_with_pipe(base_url, options, args):
result = True
stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
while True:
uml_code = _read_uml_code(stdin)
if not uml_code:
break
try:
if args.syntax:
fmt = 'check'
use_p... | This code processes PlantUML files by executing commands like URL encoding/decoding, syntax checking, and diagram generation. It uses a base URL and options from parsed arguments, handling input files/directories. If --pipe is specified, it runs via a pipe; --computeurl encodes URLs, --decodeurl decodes them, --syntax ... | def main(args):
"""Run action as plantuml command.
Args:
args: Parsing result from the parser created by `make_parser`.
"""
base_url, options = sabacan.utils.get_connection_info(
'plantuml', default_url=DEFAULT_SERVER_URL)
if args.pipe:
_run_with_pipe(base_url, options, arg... |
def create_mock_request_matcher(self, method, url, url_match_type='urlPath',
query_parameters=None, headers=None, cookies=None,
json_body=None, regex_matching=False):
"""Creates a mock request matcher to be used by wiremock.
Return... | This method creates a default mock mapping for WireMock by defining a request matcher (based on HTTP method and URL pattern) and a response (with status, headers, body, and templating option). It combines these into a mapping to simulate API behavior during testing, allowing customizable HTTP responses for specified re... | def create_default_mock_mapping(self, method, url, status=200, status_message=None,
response_headers=None, response_body=None, template=False):
"""Creates a default expectation to be used by wiremock.
`method` is the HTTP method of the mocked endpoint
`url` ... |
def get_replacement_cost(self):
# Article 28c: Replacement Cost
# For repurchase transactions and securities or commodities lending or borrowing transactions, RC is determined as the
# amount of cash lent or borrowed; cash lent by the investment firm is to be treated as a positive amount and ca... | This function calculates the net exposure value by summing the replacement cost and potential future exposure, subtracting the collateral, and ensuring the result is non-negative. It returns the maximum of this computed value or zero, representing the minimum exposure risk after accounting for collateral. | def get_exposure_value(self):
replacement_cost = self.get_replacement_cost()
potential_future_exposure = self.get_potential_future_exposure()
collateral = self.get_collateral()
return max(0., replacement_cost + potential_future_exposure - collateral) |
def get_exposure_value(self):
replacement_cost = self.get_replacement_cost()
potential_future_exposure = self.get_potential_future_exposure()
collateral = self.get_collateral()
return max(0., replacement_cost + potential_future_exposure - collateral)
def get_risk_factor(self):
i... | The main task of the code is to initialize three key attributes—exposure_value, risk_factor, and credit_valuation_adjustment—by retrieving their respective values through dedicated methods, preparing the object for subsequent risk assessment or financial modeling tasks. | def initialize(self):
self.exposure_value = self.get_exposure_value()
self.risk_factor = self.get_risk_factor()
self.credit_valuation_adjustment = self.get_credit_valuation_adjustment() |
def validate_request(self, file_):
"""Validate that the request has an image"""
try:
# Fetch key from the InmutableDict so we can read the bytes-object
keyword = [*file_][0]
binary_image = file_[keyword].read()
except (KeyError, IndexError):
retur... | The main task of the code is to process a request by validating the input file, formatting the data with the validated image, and verifying the request parameters before sending, ensuring data integrity and correct preparation for transmission. | def main(self, data, file_, path):
"""Method Main"""
binary_image = self.validate_request(file_=file_)
data = self.format_request(data=data, image=binary_image)
self.verify_sending_request(data=data, path=path) |
def extract_features_commits_df(df):
'''
Extracts features from commit history in a DataFrame.
Parameters:
- df (pd.DataFrame): DataFrame containing commit history with relevant columns.
Returns:
- pd.DataFrame: DataFrame with features extracted for each author.
Note:
- Extracts featu... | The function performs K-means clustering on developers using commit history features, optionally incorporating issue data. It extracts features from commits, merges with issue-derived features if provided, validates cluster count, and returns a DataFrame mapping developers to cluster assignments. | def kmeans(commits_df, num_clusters=2, response_json_issues = None):
'''
Performs K-means clustering on developers based on their commit history.
Parameters:
- commits_df (pd.DataFrame): DataFrame containing commit history with relevant columns.
- num_clusters (int): Number of clusters for K-means.... |
def test_adjust_algorithms(tx_s, tx_time, time_between_adjusts, initial_records, ar_goal, ar_min):
algorithms = [adjust_binary, adjust_linear, adjust_quadratic]
data = defaultdict()
for algorithm in algorithms:
data[algorithm.__name__] = run_simulation(
time_between_adjusts,tx_s, tx_tim... | The code's main task is to test and visualize algorithms for transaction processing adjustments. It sets system parameters, runs `test_adjust_algorithms` to evaluate performance under varying transaction rates and time intervals, and generates plots to analyze average records per transaction (`ar_per_n_records`) and re... | def main():
# system variables
time_between_adjusts = 1000 # ms
tx_s = 1000 # expected tx/s that the row receives
tx_time = 5 # avg duration of the transaction (ms) [0, 1000]
initial_records = 1 # number of initial_records
test_adjust_algorithms(tx_s, tx_time, time_between_adjusts,initial_recor... |
def run_tests_function():
# Test generate_readme function
test_answers = {
'project_name': 'README.md Generator',
'project_description': 'Certainly! The provided Python script is a command-line tool for generating README.md files for software projects...',
'project_homepage': 'https://gi... | The code defines a CLI function that conditionally executes test functions or the main function based on the 'run_tests' flag. If 'run_tests' is True, it runs test functions; otherwise, it invokes the main function with the same parameters, potentially handling tasks like generating a README if 'create_new_readme' is e... | def cli(run_tests, create_new_readme):
if run_tests:
run_tests_function()
run_additional_tests()
else:
main(run_tests, create_new_readme) |
def _count_mines(self, y: int, x: int) -> int:
"""Count the number of mines among the neighbours of (y, x)."""
count = 0
for dy, dx in DIRECTIONS:
if (self.dimensions[0] > y + dy >= 0 <= x + dx < self.dimensions[1]
and is_mine(self.minefield[y + dy][x + dx])):
... | The function uncovers cells in a Minesweeper-like grid, using DFS for zero-value cells to reveal connected regions. It returns three lists: new boundary cells, removed boundary cells, and inner boundary cells. These classifications help enforce constraints on possible game boundaries during gameplay. | def _uncover_search(self, *cells: Cell) -> tuple[list[Cell], list[Cell],
list[Cell]]:
"""
Uncover each cell in cells. If some is zero, do a DFS to uncover whole
chunk. Return the list of new cells on the boundary, the list of cells
rem... |
def _can_be_mine(self, given_boundary: _Boundary, y: int, x: int) -> bool:
"""
Given an incomplete boundary, can cell (y, x) be a mine according to
neighbouring uncovered cells?
"""
if given_boundary.get_number_of_mines() == self.total_mines:
# all available mines wer... | This function recursively generates all possible extensions of an incomplete boundary by considering each cell in `cells_to_add` as either a mine or empty, branching when both options are valid. It yields each valid configuration through recursive calls, ensuring all combinations are explored. | def _extend(self, incomplete_boundary: _Boundary,
cells_to_add: list[Cell]) -> Generator[_Boundary]:
"""Extend incomplete_boundary to given cells in every possible way."""
if not cells_to_add:
yield incomplete_boundary
return
mine = self._can_be_mine(incom... |
def _remove_from_untouched(self, y: int, x: int) -> None:
"""Remove (y, x) from mine_cells or empty_cells."""
if (y, x) in self.empty_cells:
self.empty_cells.remove((y, x))
elif (y, x) in self.mine_cells:
self.mine_cells.remove((y, x))
def _uncover_safe(self, y: int, x: i... | This method handles a left-click on a grid cell (y, x) in a Minesweeper-like game. It determines if the cell is safe to uncover, checks boundaries, triggers explosions if unsafe, and dynamically adjusts the minefield by overwriting mine positions based on available boundaries. It also manages untouched cells, ensures v... | def _uncover(self, y: int, x: int) -> None:
"""Handle left-click on (y, x)."""
pos: Region
if (y, x) in self.normal_directions:
pos = (y, x)
else:
self._remove_from_untouched(y, x)
pos = UNTOUCHED
if pos in self.possible:
self._unco... |
def parse_the_script(self, script_path):
with open(script_path) as f:
parsed_script = json.load(f)
self.script = parsed_script
self.recorder = parsed_script["recorder"]
self.recorder["avatar"] = (
parsed_script.get("recorder", {}).get("avatar")
... | The code initializes a video processing class by parsing a script, calculating the start and end times of a video segment, determining its duration, and logging key timing parameters including gaps in audio and video tracks to ensure accurate output formatting. | def __init__(self, script_path, config):
self.config = config
self.h = config["video_height"]
self.w = config["video_width"]
self.size = (self.w, self.h)
self.parse_the_script(script_path)
self.calculate_start_time()
self.calculate_end_time()
self.duration... |
def fill_the_video_gaps(self):
"""
Given a set of videos, this function will merge the videos and the gaps
between them into a single list
:param set_video_paths: List of video files
:return: List of VideoClips
"""
gaps = self.gen_gaps_of_set_videos()
cli... | The code generates a seamless webcam stream by filling gaps in video/audio recordings with the user's avatar, synchronizing audio, adding a name box, and combining elements into a composite video with a specified background color and duration. | def create_webcam_stream(self):
# get the solid webcam stream
# fill the gaps (where recorder turn off the camera)
# with his/her avatar image
video_streams = self.fill_the_video_gaps()
solid_webcam_clips = concatenate_videoclips(video_streams, method="compose")
# get th... |
def str2Bin(strVal, doPrefix = True):
result = '0b' if doPrefix else ''
for i in range(len(strVal)):
result += dec2Bin(ord(strVal[i]), False)
return result
def dec2Bin(decVal, doPrefix = True, numBits = 8):
bits = '0b' if doPrefix else ''
for n in range(numBits):
bits += ('1' if get_bit(decVal, numBit... | This code implements the SHA-256 cryptographic hash function. It processes an input string by padding it to a multiple of 512 bits, then applies the SHA-256 compression algorithm in 512-bit chunks. The algorithm uses predefined constants, bitwise operations, and rotational functions to compute the hash. Finally, it con... | def sha256(strVal):
# initialize hash values & constants
hsh = [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19,
]
k = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807a... |
def sha256(strVal):
# initialize hash values & constants
hsh = [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19,
]
k = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807a... | The function generates a salted SHA-256 hash of an input string by creating a random base64-encoded salt, appending it to the original string, hashing the result, and returning the concatenated hash and salt. The salt length (default 12) determines the randomness bit size, ensuring uniqueness and security against preco... | def getSaltedHash(origStr, saltLen = 12):
if saltLen == 0:
return sha256(origStr)
bitLen = saltLen * 6
maxVal = 2 ** bitLen
randVal = secrets.randbelow(maxVal)
salt = b64UrlEncode(bin2B64(dec2Bin(randVal, False, bitLen)))
return sha256(origStr + salt) + salt |
def getPath(self,path):
fileBox = QtWidgets.QFileDialog(self)
inFile = QtCore.QFileInfo(fileBox.getOpenFileName(filter='*.xls* *.csv')[0])
filepath = inFile.absoluteFilePath()
if any([filepath.endswith('.xls'),filepath.endswith('.xlsx'),filepath.endswith('.csv')]):
path.setTe... | This code creates a GUI for a SNP scanner application. It sets up input fields for file path, sheet name, cell reference, and output file name, along with buttons to select files and initiate scanning. The interface validates input before triggering SNP scanning functionality, with error handling for missing file paths... | def __init__(self, parent = None):
super(Form, self).__init__(parent)
pathLine = QtWidgets.QLineEdit()
pathLine.setReadOnly(True)
self.getFileButton = QtWidgets.QPushButton('...')
sheetLine = QtWidgets.QLineEdit('Sheet1')
cellLine = QtWidgets.QLineEdit('A1')
... |
def get_tick(session):
resp = session.get('http://localhost:9999/v1/case')
if resp.status_code == 401:
raise ApiException('The API key provided in this Python code must match that in the RIT client')
case = resp.json()
return case['tick']
def check_tender(session):
resp = session.get('http:... | The code simulates a trading system that checks for tenders using an API session. It evaluates tenders against a hurdle rate, accepts valid ones via POST requests, and runs a trading loop within a time limit (tick < 300). The process repeats until the simulation ends, ensuring real-time tender handling and trade execut... | def main():
with requests.Session() as s:
s.headers.update(API_KEY)
tick = get_tick(s)
while tick < 300 and tick >0:
tender = check_tender(s)
while len(tender)>0:
print( 'Tender received, checking book...')
if check_... |
def get_tick(session):
resp = session.get('http://localhost:9999/v1/case')
if resp.status_code == 401:
raise ApiException('Get tick - ERROR')
case = resp.json()
return case['tick']
def check_news(session, targets, news_count):
resp = session.get('http://localhost:9999/v1/news?since='+str(new... | The main task of the code is to simulate a trading strategy within a 300-tick timeframe. It authenticates via an API, monitors news updates, and triggers predefined trading strategies at specific intervals (60-70, 120-130, 180-190, 240-250 ticks). The simulation tracks news counts, updates global targets, and executes ... | def main():
global targets
global update
global ticker_name
# creates a session to manage connections and requests to the RIT Client
with requests.Session() as s:
# add the API key to the session to authenticate during requests
s.headers.update(API_KEY)
# get the current time... |
def choose_coffee(self):
print()
type = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, "back" - to back menu: \n')
if type == '1':
self.make_coffee([250, 0, 16, 1, 4])
elif type == '2':
self.make_coffee([350, 75, 20, 1, 7])
elif t... | The code defines a method `do_action` that executes different operations based on the input `action` parameter. It handles 'buy' (select coffee), 'fill' (refill resources), 'take' (collect money), 'remaining' (display status), or 'exit' (terminate the program). Other actions trigger an incomplete default case. | def do_action(self, action):
if action == 'buy':
self.choose_coffee()
elif action == 'fill':
self.fill_machine()
elif action == 'take':
self.take_money()
elif action == 'remaining':
self.remaining()
elif action == 'exit':
... |
def get_num_hits(query_params:dict) -> int:
response_json = call_api({
'q': query_params['q'],
'sort': query_params['sort'],
'size': 1,
'page': 1,
'fields': 'id',
'earliest_date': query_params['earliest_date']
})
hits = response_json['hits']['total']
logg... | The main task of the code is to retrieve documents from an API based on query parameters, split large queries into smaller date-based intervals to comply with API limits, store the documents in a MongoDB collection, and return a list of downloaded document IDs. It recursively handles date-range splitting and pagination... | def download_docs(query_params:dict, db_collection:pymongo.database.Database) -> list:
'''Get documents from API and store on DB.
Split by date is also handled by this function.
'''
ids_downloaded = []
# This first api call will check the number of hits
# if it is greater then 10k documents th... |
def get_total_stock(product):
with open("data/inventory.csv", "r") as file:
total_count = 0
for line in file.readlines():
if product in line:
product_line = line.split(",")
quantity = int(product_line[5])
total_count += quantity
return ... | The function `sell_product` checks if there's sufficient stock for a product sale. If the available stock meets or exceeds the quantity to sell, it updates the inventory. If stock is insufficient but available, it alerts the user of the maximum sellable amount. If no stock exists, it notifies the user. The function rel... | def sell_product(sold_product_name, sold_quantity, sell_price):
total_stock = get_total_stock(sold_product_name)
if total_stock >= sold_quantity:
update_inventory_file(check_and_update_stock(sold_product_name, sold_quantity, sell_price))
elif total_stock > 0:
return console.print(f"You do ... |
def T(y, k):
"""
Calculates one-hot encoding of y
:param y: Target vector
:param k: number of classes
:return: one hot encoding of y
"""
one_hot = np.zeros((len(y), k))
one_hot[np.arange(len(y)), y] = 1
return one_hot
def check(X, Y, W1, W2, b1, b2, d, k, N):
"""
Does gradien... | The code trains a softmax regression model using gradient descent to minimize loss and maximize accuracy. It initializes weights and biases, computes forward passes with softmax activation, calculates gradients, updates parameters iteratively, and tracks loss and accuracy over 8000 epochs. The model predicts class labe... | def train(X, y):
"""
Trains the model using softmax regression
:param X: Dataset
:param y: Target vector
:return: Loss and accuracy
"""
alpha = 0.0001
N, d = X.shape
k = 2
W1 = np.random.random((d, k))
W2 = np.random.random((d, k))
b1 = np.random.random((1, k))
b2 = ... |
def read_dataset(filename):
"""
Reads dataset
:param filename: Name of file
:return: data
"""
file = open(filename)
reader = csv.reader(file)
header = next(reader)
rows = []
for row in reader:
rows.append(row)
file.close()
return rows
def separate_classes(dataset)... | The code trains a Naive Bayes classifier on a spam filtering dataset (`q3.csv`) by splitting classes and estimating parameters. It then tests the model on a separate dataset (`q3b.csv`), predicting labels for each test instance and printing original vs. predicted values. Finally, it calculates and prints the accuracy a... | def main():
"""
Trains and tests spam filtering dataset using
Naive bayes classifier
:return:
"""
dataset = read_dataset("q3.csv")
split = separate_classes(dataset)
params = train(split)
test_set = read_dataset("q3b.csv")
predicted = list()
for row in test_set:
label ... |
def get_config_path() -> str:
"""
Detects if in testing or prod env, and returns the right config path.
:return: Path to config.
"""
test_config_path = environ.get("SHALLOW_BACKUP_TEST_CONFIG_PATH", None)
legacy_config = path.join(get_xdg_config_path(), "shallow-backup.conf")
new_config_path... | The function `safe_create_config` creates a configuration file at a specified path if it doesn't exist, ensuring the directory structure is in place. It sets the file's permissions to 644 (read/write for owner, read for group/others) using `chmod`. The function also checks for an existing config and may prompt updates ... | def safe_create_config() -> None:
"""
Creates config file (with 644 permissions) if it doesn't exist already. Prompts to update
it if an outdated version is detected.
"""
backup_config_path = get_config_path()
# If it doesn't exist, create it.
if not os.path.exists(backup_config_path):
... |
def tree(label, branches=[]):
"""Construct a tree with the given label value and a list of branches."""
if change_abstraction.changed:
for branch in branches:
assert is_tree(branch), 'branches must be trees'
return {'label': label, 'branches': list(branches)}
else:
for br... | The code recursively creates a deep copy of a tree structure, ensuring that modifying the original tree does not affect the copied tree. It duplicates the root label and recursively copies each branch, preserving the entire hierarchical structure. This is specifically for testing purposes to isolate changes in the orig... | def copy_tree(t):
"""Returns a copy of t. Only for testing purposes.
>>> t = tree(5)
>>> copy = copy_tree(t)
>>> t = tree(6)
>>> print_tree(copy)
5
"""
return tree(label(t), [copy_tree(b) for b in branches(t)]) |
def h_header(filename):
s = '#ifndef {}\n'.format(filename.upper().replace('.', '_'))
s += '#define {}\n'.format(filename.upper().replace('.', '_'))
return s
def ndarray_to_var(x, vartype, varname):
body_str = ndarray_to_str(x)
s = "\n{} {}".format(vartype, varname)
arr_size = 1
for z in np... | The code generates a C++ header file from a NumPy array. It constructs a header, converts the array to a `const int` variable declaration, and appends a footer, then writes these components into a `.h` file with the given filename. | def export_header(npa, filename):
header = h_header(filename+".h")
s = ndarray_to_var(npa, 'const int', filename)
footer = h_footer(filename+".h")
with open(filename+".h", 'w') as f:
f.write(header)
f.write(s)
f.write(footer) |
def loadObject(tex=None, pos=LPoint3(0, 0), depth=SPRITE_POS, scale=1,
transparency=True):
obj = loader.loadModel("plane.bam")
obj.reparentTo(render)
obj.setPos(pos.getX(), depth, pos.getY())
obj.setScale(scale)
obj.setBin("unsorted", 0)
obj.setDepthTest(False)
if transparency... | This code initializes a game environment with player controls, score, lives, and visual elements. It sets up a spaceship, background, on-screen text for score/lives, keyboard input handling, and plays a looping background sound. The game mechanics involve movement, shooting, and collision detection, with parameters for... | def __init__(self):
ShowBase.__init__(self)
getModelPath().appendDirectory("data")
self.AST_INIT_VEL = 0.6
self.score = 0
self.lives = 5
self.BULLET_LIFE = 1.5
self.BULLET_SPEED = 15
self.BULLET_REPEAT = .2
self.AST_VEL_SCALE = 1.2
self.dis... |
def updateShip(self, dt):
heading = self.ship.getR()
if self.keys["turnRight"]:
heading += dt * TURN_RATE
self.ship.setR(heading % 360)
elif self.keys["turnLeft"]:
heading -= dt * TURN_RATE
self.ship.setR(heading % 360)
if self.keys["accel"... | The code manages a game loop for an Asteroids-like game, updating the player's ship, handling bullet firing, updating asteroid positions, checking collisions between bullets/asteroids and the ship, managing game over conditions, and respawning asteroids when all are destroyed. It tracks score, lives, and handles entity... | def gameLoop(self, task):
self.gton = 1
dt = globalClock.getDt()
if not self.alive:
return Task.cont
self.updateShip(dt)
self.ss.setText(str(self.score))
self.ll.setText(str(self.lives))
if self.keys["fire"] and task.time > self.nextBullet:
... |
def _fire(self, dt):
# Incrementing delay since last firing time
self.last_firing_delay += dt
# Fire as many laser as needed
while self.last_firing_delay > ALIEN_FIRING_PERIOD_MS:
self.last_firing_delay -= ALIEN_FIRING_PERIOD_MS
# Find all aliens that may fire
... | The main task of the code is to update alien entities in a game by handling their movement, shooting behavior, removal of off-screen aliens, and state changes, using delta time (dt) for smooth animation and timing. | def _update_aliens(self, dt):
self._fire(dt)
self._accelerate()
self._remove_aliens()
self._update_alien(dt) |
def _collide_missile_and_aliens(self):
# If no missile, no collision to check
if not self.spaceship.missile.is_active:
return
# Get rectangle from missile
missile_rect = self.spaceship.missile.rect
# Get each alien rectangle and check collision
for alien in... | This method handles collision checks between various game entities, including missiles and aliens, spaceship and aliens, spaceship and lasers, missiles and lasers, missiles and barricades, lasers and barricades, aliens and barricades, and missiles and saucers, ensuring interactions like damage, destruction, or state ch... | def _collide(self):
self._collide_missile_and_aliens()
self._collide_spaceship_and_aliens()
self._collide_spaceship_and_lasers()
self._collide_missile_and_lasers()
self._collide_missile_and_barricades()
self._collide_laser_and_barricades()
self._collide_alien_and_... |
def _update_aliens(self, dt):
self._fire(dt)
self._accelerate()
self._remove_aliens()
self._update_alien(dt)
def _update_lasers(self, dt):
for laser in self.lasers:
laser.update(dt)
# If laser out of screen, we explode it
if laser.rect.botto... | The code's main task is to handle game updates by playing a looping move sound on the first call, updating alien, laser, and saucer entities using delta time (dt), and resetting aliens if none remain. It manages audio playback, entity behavior, and game state transitions. | def update(self, dt):
# Starting to play the move sound if it's the first update
if self.sound_index == -1:
self.move_sounds[0].play(loops=-1)
self.sound_index = 0
# Updating each inner entity
self._update_aliens(dt)
self._update_lasers(dt)
self.... |
def _get_update_count(self, dt):
# Incrementing the delay since previous update
self.update_time_delay += dt
# Count how many updates should be done. If more than one, a warning is shown
update_count = self.update_time_delay // UPDATE_PERIOD_MS
if update_count > 1:
p... | This code runs a game loop using Pygame, updating game entities based on time intervals, handling collisions, tracking life count, checking game-over conditions, and resetting the game if necessary. It also manages frame rendering to maintain consistent performance. | def play(self):
clock = pygame.time.Clock()
while True:
dt = clock.tick()
update_count = self._get_update_count(dt)
if update_count > 0:
# If game over for too long, reset the game
if self.is_game_over:
self.delay_... |
def get_asset_json_list(
all_asset_path: str = 'data_json/all_assets.json',
save_supply: bool = False) -> list[dict]:
"""
Get list of asset data
:param all_asset_path: path of file with all assets
:param save_supply: save or not `supply` and `base_supply`
:return: list of asset jsons... | The code's main task is to update an on-chain contract with asset data from a JSON file, ensuring only new assets are added by comparing them against the contract's current state. It processes assets in batches, sends transactions via a wallet, and returns transaction results. The function handles error recovery, logs ... | def save_to_contract(
contract_address: str,
lcd_client: LCDClient,
wallet: Wallet,
wallet_address: str,
fee_denom: str,
all_asset_path: str = 'data_json/all_assets.json',
batch_size: int = 128,
gas: int = 24_000_000,
memo: str = 'update assets in ... |
def depthFirstSearch(
self, startNodeIndex: int, targetNodeIndex: int
) -> Tuple[List[int], float, float]:
startTime = time()
visited = [False] * self.smallWorld.numberOfVertices
path = []
distance = []
distance.append(0.0)
self.dfs(
startNodeInde... | The main task of the code is to execute multiple pathfinding algorithms (DFS, BFS, BestFirst, A* Euclidian, A* Manhattan) on a graph, calculating and returning their average execution time and path distance metrics for all origin-destination node pairs. It iterates through each pair, runs each algorithm, aggregates res... | def runAllAlgorithms(self) -> Dict[str, AlgorithmResult]:
algorithmsSubResults = []
for origin, destiny in zip(self.listOfOriginNodes, self.listOfDestinyNodes):
algorithmsSubResults.append(self.depthFirstSearch(origin, destiny))
dfsAlgorithmResult = AlgorithmResult().calculateValues... |
def reprojected(df):
utm = identify_utm_zone(df)
return df.to_crs(f"+proj=utm +zone={utm} +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
def neighbors_with_shared_perimeters(neighbors, df):
"""Construct a graph with shared perimeter between neighbors on the edges.
:neighbors: Adjacency information genera... | This function constructs a NetworkX graph from a geospatial DataFrame by creating nodes for each geographic unit, defining adjacency based on shared edges (Rook neighbors), and adding attributes like population, area, and district assignments to nodes. It handles data reprojection, index setting, boundary perimeter cal... | def construct_graph_from_df(df_unprojected,
id_col=None,
pop_col=None,
area_col=None,
district_col=None,
cols_to_add=None):
"""Construct initial graph from information about neighboring VTDs.
:df: Geopandas dataframe.
:returns: NetworkX Graph.
"""
df = reproje... |
def construct_graph_from_file(filename,
id_col=None,
pop_col=None,
area_col=None,
district_col=None,
cols_to_add=None):
"""Constuct initial graph from any file that fiona can read.
This can load any file format supported by GeoPandas, which is everything
that the fion... | The function constructs a NetworkX graph from diverse data sources (e.g., GeoJSON, shapefiles, JSON, or geopandas DataFrames) by delegating to specialized helper functions. It maps spatial/structured data into graph nodes, incorporating specified columns (e.g., IDs, population, area) and additional attributes. The core... | def construct_graph(data_source,
id_col=None,
pop_col=None,
area_col=None,
district_col=None,
data_cols=None,
data_source_type="fiona"):
"""
Construct initial graph from given data source.
:data_source: Data from which to create graph ("fiona", "geo_data_frame... |
def train(self):
"""
training function
:return:
"""
running_loss = 0
y_true = []
y_pred = []
self.net.train()
for i_batch, sample_batched in enumerate(self.dataloader):
inputs, labels = sample_batched['image'].to(self.device), sample_b... | The code trains a model over multiple epochs, performing training and validation phases each epoch. It tracks metrics like TPR, FPR, and specificity, saves model checkpoints if validation metrics exceed thresholds (TPR > 0.8 and specificity > 0.8), and logs training/validation accuracy/loss. Model states are saved peri... | def start_train(self):
"""
Start the training
:return:
"""
for epoch in range(self.num_epochs):
print(epoch)
running_loss, y_true, y_pred, T_TPR, T_FPR, T_specificity = self.train()
va_loss, v_true, v_pred, V_TPR, V_FPR, V_specificity = self.ev... |
def getModelInput(maze,current,end,moveList):
x,y = tuple(current)
up,down,left,right = getImmediate(maze,x,y,dim)
curr = np.array(current)
e = np.array(end)
diff = curr-e
dist = math.sqrt(np.sum(np.multiply(diff,diff)))
cosTheta = (e[0]-curr[0])/dist
moveSlice = moveList[len(moveList)-1... | This code processes a maze navigation request by using a predictive model to determine a path from a start to an end position. It initializes the maze and positions, iterates through possible moves, validates paths, avoids loops, and adjusts direction based on model predictions or random choices when stuck. The final v... | def getMaze_And_Path(request):
print("Main API called")
# 1.
maze = json.loads(request.data.get("maze"))
maze_copy = np.copy(maze)
# 2.
start = json.loads(request.data.get("start"))
end = json.loads(request.data.get("end"))
d = {0:[-1,0],1:[0,1],2:[1,0],3:[0,-1]}
moveList = [-1]*11... |
def get_seasonal_schedule_daterange_index(hrefs: Sequence[str], date: datetime) -> int:
for i, href in enumerate(hrefs):
dates = get_seasonal_schedule_daterange_from_url(href)
if dates and date.date() >= dates[0].date() and date.date() <= dates[1].date():
return i
return -1
def get_s... | The main task of the code is to parse HTML content from a web response to extract sailing schedules for a given date. It processes both daily and seasonal schedules, handling redirects for seasonal ranges, and returns a structured result with sailings and notes if no sailings are found. | def parse_schedule_html(response: httpx.Response, date: datetime) -> HtmlParseResult:
html = response.text.replace("\u2060", "")
soup = BeautifulSoup(markup=html, features="html.parser")
table_tag = soup.find("table", id="dailyScheduleTableOnward")
daterange_tag = soup.find("div", id="dateRangeModal") ... |
def CAPS_ramtimes(elsdata, starttime, endtime):
ramtimes = []
startslice, endslice = CAPS_slicenumber(elsdata, starttime), CAPS_slicenumber(elsdata, endtime)
for i in np.arange(startslice, endslice, 1):
actuatorangle = elsdata['actuator'][i]
ramangle = caps_ramdirection_azielv(elsdata['times... | The function `CAPS_beamsdata` processes beam data from two instruments ("els" and "ibs") to analyze plasma characteristics. It identifies energy peaks, calculates azimuthal angles relative to heavy ions and spacecraft ram direction, and computes deflections from bulk flow. Data is grouped by flyby, aligned temporally, ... | def CAPS_beamsdata(times_elsdata_pairs, times_ibsdata_pairs):
elspeakslist = []
for elsflyby, times, energypairs, heavymass, heavyprominence, lightprominence, timewindow in times_elsdata_pairs:
if elsflyby in usedflybys:
elsdata = readsav("data/els/elsres_" + filedates[elsflyby] + ".dat")
... |
def display_welcome(self): # void
print(
"\nWelcome to ROBOTS vs DINOSAURS\nMay the best team win!"
)
def battle(self): # void
while (
len(self.herd.dinosaurs) != 0
and len(self.fleet.robots) != 0
):
if self.herd.dinosaurs:
... | The `run_game` method initializes the game by displaying a welcome message, executes a battle loop that continues until one team loses, and then concludes the game by displaying the winning team. | def run_game(self): # void
##*Start the game with a welcome msg
self.display_welcome()
##*run battle while loop until a team loses
self.battle()
##*once team loses end the game and display the winners
self.display_winners() |
def data_classification_2(data):
df = data.copy()
clf = train_classifier()
labels = clf.predict(df['text'])
# Add the predicted labels to data
df['gpt_label'] = labels
return df
def generate_bar_chart(data):
fontcolor = '#262564'
df = data.gpt_label.value_counts().sort_values()
... | The code analyzes input data by classifying it, generating visualizations (bar chart, word cloud), displaying labeled text responses, summarizing textual content, and providing recommendations based on the summary. | def analyze_data(data):
df = data_classification_2(data)
generate_bar_chart(df)
#df = data.copy()
#generate_donut_chart(df['gpt_label'].value_counts())
#st.markdown("#### Data")
df1 = df[['text','gpt_label']].copy()
df1.columns = ['Text Response', 'Label']
st.dataframe(df1)
st... |
def get_document_bounds(image_file_path, feature,direct_content=None):
"""Returns document bounds given an image."""
client = vision.ImageAnnotatorClient(credentials=credentials)
bounds = []
Features = []
if(image_file_path != None):
with io.open(image_file_path, 'rb') as image_file:
... | The code renders document structure by drawing bounding boxes for blocks, paragraphs, and words on an image using different colors, then extracts structured text data into a CSV file. It opens an input image, overlays visual annotations, and saves or displays the result, storing extracted text features globally for fur... | def render_doc_text(filein, fileout):
image = Image.open(filein)
bounds,Features = get_document_bounds(filein, FeatureType.BLOCK)
draw_boxes(image, bounds, 'blue')
bounds,Features = get_document_bounds(filein, FeatureType.PARA)
draw_boxes(image, bounds, 'red')
bounds,Features = get_document_boun... |
def _check_events(self):
"""Respond to keypresses and mouse movements"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown(event)
elif eve... | The `run_game` method initiates the game's main loop, continuously checking for events, updating game elements (character, level, cars) when active, rendering the screen, and maintaining a 60 FPS frame rate via `self.cock.tick(60)`. It ensures real-time interaction and visual updates while the game is active. | def run_game(self):
"""Start the main loop for the game"""
while True:
self._check_events()
if self.game_active:
self.character.update()
self._update_level()
self._update_cars()
... |
def round_key_exp(self, K): #step of key expansion
rk = []
newCK = []
#The constant key used for key expansion is represented as CK,
#where each CK_i (i = 0, ..., 31) is 32 bits long:
for each in CK:
ch = bin(int(each,16))[2:]
for j in range(3... | The code performs encryption and decryption using a custom cipher. It converts the hexadecimal key to a 128-bit binary, generates a round key, encrypts the plaintext by converting it to bits, grouping, and applying encryption operations. The encrypted result is converted to hexadecimal. Decryption reverses this process... | def cypher(self, key, plainText):
key = bin(int(key,16))[2:]
for i in range(128 - len(key)):
key = '0' + key
key = self.round_key_exp(self.key_group(key))
encrypted = ''
decrypted = ''
plain_bits = self.char_to_bit(plainText)
... |
def _write_node(self, f, node: Node):
"""
It writes on the file the facts related to the open street map node.
:param f: The file on which write the fact
:param node: The node of which write the related fact
:return:
"""
node_id = self._generate_node_id_fact(node)... | The main task of the code is to write parsed Open Street Map (OSM) data and generated events into a file at the specified output path. It processes nodes and ways from the input data, writes their facts using helper methods, tracks generated IDs, and logs progress. The function organizes node and way information, ensur... | def write_facts(self, data: ParsingResult, output_path: str):
"""
It writes down the facts, on the given path, from the parsing of open street data and generated events.
:param data: The data from the parsing
:param output_path: The path to store the file
:return:
"""
... |
def download(url, dst):
res = subprocess.run(["curl", "-L", "-C", "-", "-o", dst, url])
if res.returncode != 0:
error('failed downloading ' + url)
def file_matches_checksumfile(filename):
with open(filename + ".sha256", "r") as f:
expected_checksum = f.read().strip()
return expected_chec... | The function downloads a file from a given URL to a specified destination, ensuring its integrity via a SHA-256 checksum. It first downloads the checksum file, checks if the destination file exists and matches the checksum. If it does, the process stops. If not, it notifies the user and redownloads the file, then verif... | def download_with_sha256(url, dst):
download(url + ".sha256", dst + ".sha256")
if os.path.isfile(dst):
if file_matches_checksumfile(dst):
return
notice(f"{dst} exists but does not match the checksumfile; redownloading")
download(url, dst)
verify_via_checksumfile(dst) |
def error(msg):
print("\033[31m" + msg + "\033[0m")
sys.exit(1)
def notice(msg):
print("\033[32m" + msg + "\033[0m")
def verify_via_checksumfile(filename):
if not file_matches_checksumfile(filename):
error(f"checksum for '{filename}' expected to be {expected_checksum} but got {actual_checksum}")... | The main task of the code is to upload a file and its SHA-256 checksum to a GitHub release. It verifies the file's existence, skips if a checksum file is provided, generates a checksum if missing, and uploads both the file and its checksum. Errors are handled during upload, ensuring integrity and proper asset managemen... | def upload_asset_with_checksum(release, filename):
if not os.path.isfile(filename):
error(f"{filename} not found")
if filename.endswith(".sha256"):
notice(f"Skipping provided checksum file {filename}")
return
notice(f"Processing {filename}")
checksum_filename = filename + ".sh... |
def get_input(f, encoding='utf-8'):
with open(f,'r', encoding=encoding) as file:
data = file.read().splitlines()
return data
def solver1(data):
print(sum(is_tls(a) for a in data))
def solver2(data):
b = [is_ssl(a) for a in data]
print(sum(is_ssl(a) for a in data)) | The main task of the code is to read input data from 'input.txt' using the `get_input` function, then process this data by sequentially executing two solver functions, `solver1` and `solver2`, which likely perform specific computations or analyses on the input data. | def main():
data = get_input('input.txt')
solver1(data)
solver2(data) |
def get_lectura_cuant():
try:
lectura=np.asarray(laser.get_data().ranges)
lectura=np.where(lectura>20,20,lectura) #remove infinito
right_scan=lectura[:180]
left_scan=lectura[540:]
front_scan=lectura[180:540]
sd,si,sf=0,0,0
if np.mean(left_scan)< 1.5: si=1
... | The code controls a robot's navigation by calculating its current position and orientation, determining the angle to a target goal, and adjusting movement via turning or forward motion. It uses sensor inputs (si, sd, sf) to decide between eight possible outcomes, returning specific states based on sensor values. The ro... | def execute(self,userdata):
si,sd,sf=get_lectura_cuant()
msg_cmd_vel = Twist()
global angle_to_goal, angle_to_goal1, angle_to_goal_p, xt, yt, zt, inc_x, inc_y, theta
punto_actual = get_coords()
xt = punto_actual.transform.translation.x
print("xt: " + str(xt))
yt =... |
def turn_left(x,y,z,t):
move_base(x,y,z,t)
def turn_right(x,y,z,t):
move_base(x,y,z,t)
def get_coords ():
for i in range(10): ###TF might be late, try 10 times
try:
trans = tfBuffer.lookup_transform('map', 'base_link', rospy.Time())
return trans
except:
... | The code adjusts a robot's orientation and movement based on proximity to a goal. It checks if the robot is within 0.05 meters of the target (inc_x, inc_y). If aligned, it rotates left/right to correct angular deviation (angle_to_goal_p) and enters a loop to move forward. If not aligned, it adjusts orientation using an... | def execute(self,userdata):
rospy.loginfo('Estado Comparacion')
if abs(inc_x) < 0.05 and abs(inc_y) < 0.05:
if ((angle_to_goal_p >= 0 and angle_to_goal_p <np.pi) or (angle_to_goal_p <-np.pi)):
if abs(angle_to_goal_p) > 0.1: turn_left(0.0,0.0,0.12*np.pi,0.1)
el... |
def advanceAndPause(self):
if self.pauseFlow:
return
self.tokenizer.advance()
self.currentToken = self.tokenizer.getCurrentToken()
self.currentTokenType = self.tokenizer.getCurrentTokenType()
self.pauseFlow = True
def saveNextTokens(self, i):
self.passedTokens... | The function `compileClassVarDec` processes class-level variable declarations (static/field) by parsing tokens, defining variables in the symbol table, and generating code. It checks for valid keywords, extracts variable names and types, and recursively handles multiple declarations. The symbol table is updated with ea... | def compileClassVarDec(self):
self.advanceAndPause()
if self.currentToken not in ['static', 'field']:
return
self.saveNextTokens(3) # ('static' | 'field') type varName
self.symbolTable.define(
self.passedTokens[2]['token'],
... |
def advanceAndPause(self):
if self.pauseFlow:
return
self.tokenizer.advance()
self.currentToken = self.tokenizer.getCurrentToken()
self.currentTokenType = self.tokenizer.getCurrentTokenType()
self.pauseFlow = True
def saveNextTokens(self, i):
self.passedTokens... | This function compiles a variable declaration in a programming language. It checks for 'var', saves the type and name, adds the variable to the symbol table, writes code for the variable, and handles multiple declarations recursively. It advances the tokenizer, processes tokens, and manages symbol table entries for loc... | def compileVarDec(self):
self.advanceAndPause()
if self.currentToken != 'var':
return
self.saveNextTokens(3) # 'var' type varName
self.symbolTable.define(self.passedTokens[2]['token'],
self.passedTokens[1]['token'],
... |
def advanceAndPause(self):
if self.pauseFlow:
return
self.tokenizer.advance()
self.currentToken = self.tokenizer.getCurrentToken()
self.currentTokenType = self.tokenizer.getCurrentTokenType()
self.pauseFlow = True
def saveNextTokens(self, i):
self.passedTokens... | The main task of the code is to compile a function/method's parameter list by parsing type and variable name tokens, updating the symbol table with argument entries (including 'this' for methods), and generating code for these parameters. It handles token advancement, symbol table definitions, and writes multi-variable... | def compileParameterList(self):
self.advanceAndPause()
if self.currentToken == ')':
return
self.saveNextTokens(2) # type varName
if self.currentFunctionKind == 'method':
self.symbolTable.define('this', self.currentFunctionType, 'argumen... |
def advanceAndPause(self):
if self.pauseFlow:
return
self.tokenizer.advance()
self.currentToken = self.tokenizer.getCurrentToken()
self.currentTokenType = self.tokenizer.getCurrentTokenType()
self.pauseFlow = True
def writeXmlTag(self, tag):
xml = '<' + tag + ... | The main task of the code is to parse and compile class variable declarations in a Jack compiler. It checks for 'static' or 'field' keywords, writes XML tags for classVarDec, processes variable names and types, handles multiple variables via 'writeMultiVar', and recursively processes additional declarations. The functi... | def compileClassVarDec(self):
self.advanceAndPause()
if self.currentToken not in ['static', 'field']:
return
self.writeXmlTag('classVarDec')
self.writeNextTokens(3) # ('static' | 'field') type varName
self.writeMultiVar()
s... |
def advanceAndPause(self):
if self.pauseFlow:
return
self.tokenizer.advance()
self.currentToken = self.tokenizer.getCurrentToken()
self.currentTokenType = self.tokenizer.getCurrentTokenType()
self.pauseFlow = True
def writeXmlTag(self, tag):
xml = '<' + tag + ... | The main task of the code is to compile a parameter list into XML format. It advances the tokenizer, writes an opening <parameterList> tag, checks for an empty list (closing tag if encountering ')'), writes type and variable name tokens, processes multiple variables with types, and finally closes the </parameterList> t... | def compileParameterList(self):
self.advanceAndPause()
self.writeXmlTag('parameterList')
if self.currentToken == ')':
self.writeXmlTag('/parameterList')
return
self.writeNextTokens(2) # type varName
self.writeMultiVar({'withVar... |
def advanceAndPause(self):
if self.pauseFlow:
return
self.tokenizer.advance()
self.currentToken = self.tokenizer.getCurrentToken()
self.currentTokenType = self.tokenizer.getCurrentTokenType()
self.pauseFlow = True
def writeXmlTag(self, tag):
xml = '<' + tag + ... | The main task of the code is to parse and compile a variable declaration statement in a programming language. It checks for the 'var' keyword, writes XML tags for the declaration, processes the variable type and name, handles multiple variables in a single declaration, and recursively processes subsequent 'var' declara... | def compileVarDec(self):
self.advanceAndPause()
if self.currentToken != 'var':
return
self.writeXmlTag('varDec')
self.writeNextTokens(3) # 'var' type varName
self.writeMultiVar()
self.writeNextTokens(1) # ';'
self.writeXm... |
def saveNextTokens(self, i):
self.passedTokens = []
j = i
if self.pauseFlow == True:
self.saveCurrentToken()
self.pauseFlow = False
j = i - 1
for _ in range(j) :
self.tokenizer.advance()
self.currentToken = self.tokenizer.getCur... | This function compiles a subroutine's body into VM code. It processes variable declarations, writes function metadata, handles constructor/method initialization (allocating memory or adjusting pointers), compiles statements, and manages token tracking. The VM code includes function calls, memory operations, and argumen... | def compileSubroutineBody(self):
self.saveNextTokens(1) # {
self.compileVarDec()
self.vm.writeFunction(self.currentClass + '.' + self.currentFunction, self.symbolTable.getLocalsCount())
if self.currentFunctionKind == 'constructor':
fName = ... |
def writeXmlTag(self, tag):
xml = '<' + tag + '>\n'
self.outputFile.write(xml)
def writeNextTokens(self, i):
j = i
if self.pauseFlow == True:
self.writeCurrentToken()
self.pauseFlow = False
j = i - 1
for _ in range(j) :
self.tokeniz... | The main task of the code is to compile a subroutine's body by generating XML tags for its structure, handling variable declarations, and processing statements. It writes XML tags for 'subroutineBody', processes opening braces, compiles variables and statements, and closes the structure with a closing brace and XML tag... | def compileSubroutineBody(self):
self.writeXmlTag('subroutineBody')
self.writeNextTokens(1) # {
self.compileVarDec()
self.compileStatements()
self.writeNextTokens(1) # }
self.writeXmlTag('/subroutineBody') |
def advanceAndPause(self):
if self.pauseFlow:
return
self.tokenizer.advance()
self.currentToken = self.tokenizer.getCurrentToken()
self.currentTokenType = self.tokenizer.getCurrentTokenType()
self.pauseFlow = True
def saveNextTokens(self, i):
self.passedTokens... | The main task of the code is to compile a subroutine declaration by initializing the symbol table, parsing the function type, name, parameters, and body, and setting up variables for the current function. It processes tokens related to 'constructor', 'function', or 'method' and uses helper methods to handle parameters ... | def compileSubroutineDec(self):
self.symbolTable.startSubroutine()
self.advanceAndPause()
if self.currentToken not in ['constructor', 'function', 'method']:
return
# ('constructor'| 'function' | 'method') ('void' | type) subroutineName '('
self.sav... |
def advanceAndPause(self):
if self.pauseFlow:
return
self.tokenizer.advance()
self.currentToken = self.tokenizer.getCurrentToken()
self.currentTokenType = self.tokenizer.getCurrentTokenType()
self.pauseFlow = True
def writeXmlTag(self, tag):
xml = '<' + tag + ... | The main task of the code is to compile a subroutine declaration (constructor, function, or method) by parsing its type, name, parameters, and body, while generating corresponding XML tags for the output. It handles token validation, writes XML elements, processes parameter lists, and recursively compiles the subroutin... | def compileSubroutineDec(self):
self.advanceAndPause()
if self.currentToken not in ['constructor', 'function', 'method']:
return
self.writeXmlTag('subroutineDec')
# ('constructor'| 'function' | 'method') ('void' | type) subroutineName '('
self.writeNextTok... |
def saveNextTokens(self, i):
self.passedTokens = []
j = i
if self.pauseFlow == True:
self.saveCurrentToken()
self.pauseFlow = False
j = i - 1
for _ in range(j) :
self.tokenizer.advance()
self.currentToken = self.tokenizer.getCur... | The main task of the code is to compile a class declaration by parsing tokens, storing the class name, and recursively handling variable and subroutine declarations, while managing token streams for syntax structure validation. | def compileClass(self):
self.saveNextTokens(3) # 'class' className '{'
self.currentClass = self.passedTokens[1]['token']
self.compileClassVarDec()
self.compileSubroutineDec()
self.saveNextTokens(1) |
def writeXmlTag(self, tag):
xml = '<' + tag + '>\n'
self.outputFile.write(xml)
def writeNextTokens(self, i):
j = i
if self.pauseFlow == True:
self.writeCurrentToken()
self.pauseFlow = False
j = i - 1
for _ in range(j) :
self.tokeniz... | The main task of the code is to compile a class structure in a programming language by generating XML output. It writes XML tags for the class, processes tokens like 'class', className, and '{', compiles class variables and subroutines, writes the closing '}' token, and finally closes the XML tag. This function handles... | def compileClass(self):
self.writeXmlTag('class')
self.writeNextTokens(3) # 'class' className '{'
self.compileClassVarDec()
self.compileSubroutineDec()
self.writeNextTokens(1) # '}'
self.writeXmlTag('/class') |
def initUi(self):
self.button1 = self.add_button(175, 125)
self.button2 = self.add_button(325, 125)
self.button3 = self.add_button(475, 125)
self.button4 = self.add_button(175, 275)
self.button5 = self.add_button(325, 275)
self.button6 = self.add_button(475, 275)
... | The code initializes a class by setting up a UI component (`initUi()`), displaying an 'X' score (`show_x_score()`), and a 'zero' score (`show_zero_score()`), likely for a game or application tracking scores. It inherits from a parent class and stores a `page1` reference for UI context. | def __init__(self, page1):
super().__init__()
self.page1 = page1
self.initUi()
self.show_x_score()
self.show_zero_score() |
def showPage1(self):
self.page1 = Page1(self)
self.addWidget(self.page1)
self.setCurrentWidget(self.page1)
def showPage2(self):
self.page2 = Page2(self.page1)
self.addWidget(self.page2)
def showPage3(self):
self.page3 = Page3(self.page2)
self.addWidget(self.page3)... | The main task of the code is to initialize the user interface for a Tic-Tac-Toe game by setting window properties (size, icon, title, background), displaying three pages, and configuring button click handlers to enable game interactions. | def initUi(self):
self.setFixedSize(800, 600)
self.setWindowIcon(QtGui.QIcon("img/window_icon.png"))
self.setWindowTitle("Tic-Tac-Toe")
self.setStyleSheet(f"background: {self.game_background};")
self.showPage1()
self.showPage2()
self.showPage3()
self.ini... |
def buildMaxHeap(list, size):
len = int(size/2) - 1
while len >= 0:
maxHeapify(list, len, size)
len -= 1
def swap(list, i, j):
get = list[i], list[j]
list[j], list[i] = get
get = list[i].x, list[j].x
list[j].x, list[i].x = get
return list
def maxHeapify(list, i, size):
le... | The code implements the heap sort algorithm by first building a max heap from the list, then repeatedly extracting the maximum element (swapping it with the last unsorted element) and heapifying the remaining elements. The process continues until the list is sorted in ascending order. The final call to 'moveRectangle' ... | def heapSort(list, size):
buildMaxHeap(list, size)
size -= 1
while size:
list = swap(list, 0, size)
maxHeapify(list, 0, size)
size -= 1
moveRectangle(list, 0, 1) |
def _groupby_rating_by_film(self):
self.init_mapping_movies()
top_movies = defaultdict(list)
for film_info in self.rating.read_csv():
top_movies[self.movies_id2name[film_info['movieId']]].append(
float(film_info['rating']))
return top_movies
def mean(values):
if len(values) == 0:
return float('na... | The method returns the top-n movies sorted by average or median ratings (descending), with metric values rounded to 2 decimals. It uses `self._groupby_rating_by_film()` to aggregate ratings, computes the specified metric, sorts results, and returns a dictionary mapping movie titles to their rounded metric scores. If `n... | def top_by_ratings(self, n, metric='average'):
"""
The method returns top-n movies by the average or median of the ratings.
It is a dict where the keys are movie titles and the values are metric values.
Sort it by metric descendingly.
The values should be rounded to 2 decimals.
"""
assert metric in... |
def is_goal_reached(self): # Check if goal is reached.
if (self.x_goal - 0.2 < x_robot < self.x_goal + 0.2) and (self.y_goal - 0.2 < y_robot < self.y_goal + 0.2):
return True
return False
def stop(self):
"""
Method to bring robot to a halt by publishing linear and angular ve... | This code navigates a robot to specified goal points (3,3) by iterating through a list of coordinates. It handles obstacle avoidance, checks for halt gestures, and adjusts movement by rotating toward goals if not aligned. The robot stops upon reaching a goal or encountering obstacles, with fallback to next goals if stu... | def go(self):
"""
Method to go to goal specified irrespective of the current position and orientation
of the robot.
"""
time.sleep(2.0)
print("Navigation for point (3,3) has started.")
#!!!!!!!!!!!!!!!!!!!!!!!!
min_dist = math.inf
min_dist_pos = ... |
def _assign_buckets_1_to_3(self):
'''
Merge the results of the ChEMBL search with the OT data (right join, to keep all OT targets)
Group activity data by target, assign the Max Phase for each targets, and use it to assign buckets 1 to 3
Possible duplication of effort of the OT known_dr... | The method categorizes gene IDs into tractability buckets (1–9) using multiple helper functions, then structures the output DataFrame by selecting, renaming, and sorting relevant columns. It labels categories (e.g., "Clinical_Precedence") based on bucket thresholds, adds derived scores, and ensures integer formatting f... | def assign_buckets(self):
'''
Assigns the supplied list of gene IDs into their corresponding tractability buckets.
:return: A Pandas DataFrame containing the Ensembl gene ID and associated tractability bucket
'''
self._assign_buckets_1_to_3()
self._assign_bucket_4_and_6(... |
def _assess_clinical(self):
'''
Merge the results of the ChEMBL search with the OT data (right join, to keep all OT targets)
Group activity data by target, assign the Max Phase for each targets, and use it to assign buckets 1 to 3
'''
def other_func(x):
return tupl... | The code assigns gene IDs into tractability buckets using multiple criteria (clinical, structural, chemical, etc.), summarizes the results, and classifies genes into categories like "Clinical_Precedence," "Discovery_Precedence," or "Predicted_Tractable" based on their top bucket. It returns a DataFrame with gene IDs, b... | def assign_buckets(self):
'''
Assigns the supplied list of gene IDs into their corresponding tractability buckets.
:return: A Pandas DataFrame containing the Ensembl gene ID and associated tractability bucket
'''
self._assess_clinical()
self._assess_pdb()
self._a... |
def create_points(obj, geometry, material):
if geometry.point is None: return
for point in geometry.point:
if point is None: continue
for i in point:
v = obj.vertex[i]
create_point(v, radiusPoint, material.color())
def create_lines(obj, geometry, material):
if geometr... | The function creates 3D geometry from a given object, applying a specified material. It generates points, lines, and either wireframe or solid faces based on the input geometry and wireframe flag, using helper functions to construct the mesh structure. | def create_geometry(obj, mtl, geometry, wireframe):
if geometry is None: return
material = mtl.material(geometry.material)
create_points(obj, geometry, material)
create_lines(obj, geometry, material)
if wireframe:
create_wire_faces(obj, geometry, material)
else:
create_faces... |
def setRadiusLinePoint(aabbSize):
global radiusLine, radiusPoint
radiusLine = np.linalg.norm(aabbSize) / 1000
radiusPoint = radiusLine
def position_camera(center, size, elevation, zoom, box):
area = [(size[1] * size[2], np.array([1, 0, 0])),
(size[1] * size[0], np.array([0, 0, 1]))]
... | The code loads a 3D model from a file, processes its materials, centers the model at the origin, sets camera/lighting parameters based on the model's dimensions, applies textures, and renders the geometry with optional wireframe visualization. | def load(file, box, wireframe):
obj = WavefrontOBJ()
obj.load(file)
mtl = WavefrontMTL()
mtl.load(obj.mtllib)
center, size = obj.aabb()
obj.translate(-center)
center = np.array([0,0,0])
setRadiusLinePoint(size)
position_camera(center, size, 0.4, 1.5, box)
set_li... |
def get_result_piece(self, result_state):
"""
Returns the piece that would result if the current piece hit the bottom
"""
result_piece = copy.deepcopy(self.current)
result_piece.color = GRAY
while self.valid_space(result_piece, result_state.grid):
result_piec... | The code simulates placing the current game piece into its resulting position, updating the game state by locking the piece's shape and coloring the grid accordingly. It returns a deep copy of the modified state, showing how the grid would appear if the piece fell in its current path. | def result(self):
"""
Returns the resulting state if the current piece was to fall in its current path
"""
result_state = copy.deepcopy(self)
result_piece = self.get_result_piece(result_state)
result_state.locked = lock_shape(result_state.locked, result_piece)
sh... |
def create_grid(locked_positions={}):
"""
Returns an occupancy grid after including occupied (locked) positions
"""
grid = [[BLACK for col in range(COLS)] for row in range(ROWS)]
for i in range(len(grid)):
for j in range(len(grid[i])):
if (j, i) in locked_positions:
... | This function applies a specified action (left, right, rotate, down, hard drop) to the current game state, updating the piece's position/rotation while checking validity. It creates a deep copy of the state, modifies the piece's attributes, reverses invalid moves, handles hard drops by moving down maximally, checks for... | def do_action(self, action):
"""
Applies an action to the current state and returns the resulting state
"""
new_state = copy.deepcopy(self)
new_state.grid = create_grid(new_state.locked)
if action == self.LEFT:
new_state.current.x -= 1
if not self... |
def draw_text_middle(text, size, color, surface):
"""
Draws title at the top
"""
font = pygame.font.SysFont('comicsans', size, bold=True)
label = font.render(text, True, color)
surface.blit(label, (
TOP_LEFT_X + PLAY_WIDTH / 2 - (label.get_width() / 2), TOP_LEFT_Y + PLAY_HEIGHT / 2 - la... | The code provides a menu for selecting an agent type (e.g., human, AI) and configuring game parameters. It handles training agents via trials, loading/saving models with pickle, and running games. The game starts on key press, executing multiple trials/games, then outputs results. It uses argparse for command-line argu... | def main_menu():
"""
Main menu allows the player to press a key when ready to start a game
"""
valid_agents = {
'random': RandomAgent,
'human': HumanAgent,
'hand': HandTunedAgent,
'neural': NNAgent,
'genetic': GeneticAgent
}
parser = argparse.ArgumentPar... |
def sortmonomials(self):
for c,mon in self.plist:
mon.sort(key = lambda tup : tup[0])
def simplifyproducts(self):
newList = []
for c,mon in self.plist:
varGroups = []
gp = []
vCur,dCur,fCur = mon[0]
gp.append((vCur,dCur,fCur))
... | The code initializes a polynomial object by processing a list of polynomials through sorting, simplifying, and compressing monomials and sums, then creating a structured dictionary representation. It sets the polynomial type based on the class name. | def __init__(self,plist):
self.plist = plist
self.sortmonomials()
self.simplifyproducts()
self.sortsum()
self.compresssum()
self.sortmonomials()
self.makemonomialdict()
self.polyType = self.__class__.__name__ |
def get_page(self, url):
# randomise time between requests to avoid reCAPTCHA
time.sleep(random.randint(5, 8))
try:
page = self.session.get(url)
except requests.exceptions.Timeout:
self.logger.exception('Timed out trying to log in')
sys.exit(1)
... | The code fetches apartment ads from a website by iterating through user-defined filters, handling pagination, parsing HTML tables, extracting URLs, and compiling them into a list for further processing or emailing. | def fetch_ads(self, filters):
self.logger.info('Searching filters for new ads, may take a while, depending on how many filters you '
'have set up.')
url_list = list()
for wg_filter in filters:
while self.continue_next_page:
search_results_page... |
def retrieve_email_template(self):
self.logger.info('Retrieving email template...')
template_page = self.get_page('https://www.wg-gesucht.de/mein-wg-gesucht-email-template.html')
soup = BeautifulSoup(template_page.content, 'html.parser')
template_text = soup.find('textarea', {'id': 'us... | The code searches for apartment ads using specified filters, sends email notifications with a template for each ad, logs progress, and recursively repeats the process after a 4-5 minute pause to avoid overuse. It increments a counter to track execution frequency and uses random delays to simulate natural user behavior. | def search(self):
if self.counter < 2:
self.logger.debug('Starting...')
else:
self.logger.info('Resuming...')
template_text = self.retrieve_email_template()
filters_to_check = self.fetch_filters()
ad_list = self.fetch_ads(filters_to_check)
for ... |
def known(words):
"Return the subset of words that are actually in the dictionary."
return {w for w in words if w in COUNTS}
def edits0(word):
"Return all strings that are zero edits away from word (i.e., just word itself)."
return {word}
def edits1(word):
"Return all strings that are one edit away... | The function corrects a word's spelling by generating candidates through zero, one, or two edit distances, then selecting the most frequent valid candidate from a predefined count dictionary to return the best correction. | def correct(word):
"Find the best spelling correction for this word."
# Prefer edit distance 0, then 1, then 2; otherwise default to word itself.
candidates = (known(edits0(word)) or
known(edits1(word)) or
known(edits2(word)) or
[word])
return max... |
def _get_hf_00_w(self, L):
r"""Tuned version of hf_00_{}
"""
wtt, qml, qpl, ls_m, ls_p = self.build_key('ptt', L)
return np.fft.irfft2(wtt)
def _get_hf_10_a_w(self, L, a=0):
r"""Tuned version of real and imaginary part of hf_10_{a} using only rffts
"""
wtt, qml,... | This function computes the N1 lensing gradient-induced bias (for lensing gradient or curl) using multipole L and precomputed harmonic components. It calculates terms involving h_00, h_10, and h_11 maps, combines them with xipp_00/xipp_01 weights, and returns the normalized bias value. If `do_n1mat` is True, it also com... | def get_n1(self, L, do_n1mat=False):
r"""N1 lensing gradient-induced lensing bias, for lensing gradient or curl bias
Args:
L: multipole L of :math:`N^{(1)}_L`
do_n1mat: if set, returns the array :math:`N^{(1)}_{LL'}`
Returns:
gradient-ind... |
def _destroy_key(self, k):
self.l1s = None
self.l2s = None
self.l1_int = None
self.l2_int = None
self._cos2p_sin2p_v1 = None
self._cos2p_sin2p = None
self.Ll1 = None
self.Ll2 = None
self.xy_sym = None
def _build_key(self, k, L, rfft=False, w=0.5, s... | The function computes derivatives of CMB spectra (TT, TE, EE, BB) with respect to parameters, using Fourier transforms and symmetry properties. It constructs matrices for polarization states (T, Q, U), applies complex operations, and accumulates results into dcls. The output, scaled by normalization, provides dn1/dCMBs... | def get_dn1(self, k, L, _optimize=0):
"""Returns matrices dn1 / dCMBspectra for spec TT TE EE BB
For Cpp derivatives, use the get_n1 routine
"""
Tps =['T', 'Q', 'U']
Ts = ['T', 'Q', 'U']
Ss = ['T', 'Q', 'U']
TS = ['TT', 'TQ', 'TU','QT', 'QQ', 'QU', 'UU',... |
def ls(self, rfft=True):
n2y, n2x = np.meshgrid(self.ny_1d ** 2, (self.nx_1d if rfft else self.ny_1d) ** 2, indexing='ij')
return self.rsqd2l(n2y + n2x)
def mode_counts(self):
"""Mode number counts on the flat-sky patch.
Goes roughly like :math:`2\ell + 1` times the sky faction
... | The function computes weighted counts of indices from `self.ls()` using `np.bincount`, adjusting for input shape compatibility. It sums weights across specified dimensions, applies mode counts, and returns aggregated results for data analysis or feature extraction. | def sum_in_l(self, weights):
assert weights.shape in (self.rshape, self.shape), (weights.shape, self.rshape,self.shape)
if weights.shape == self.rshape:
shape = self.shape
rshape = self.rshape
ls = self.ls()
cl = np.bincount(ls[:, 1:rshape[1] - 1].flatten(... |
def _build_key(self, k, L, rfft=False, w=0.5, sgn=1):
"""
Args:
k: quadratic estimator key
L: lensing multipole
rfft: arrays are rfft2 shaped if True fft2 shaped if not
w: the l1 and l2 arrays are l1 = l + L * w, l2 = L (1 - w) - l
... | This function computes the n1 statistic for a given key `k` and length `L`, using optimized Fourier transform methods. It handles different optimization levels (0, 1, 2), performing nested FFT operations, tensor products, and matrix manipulations on polarization components (T, Q, U). The result is scaled by `self.norm`... | def get_n1(self, k, L, do_n1mat=True, _optimize=2, _pyfftw=True):
L = float(L)
if not _pyfftw: self._irfft2 = lambda m : np.fft.irfft2(m,s=self.box.shape)
_rfft = True
n1_mat = None
#if _optimize == 2:
# _optimize = 1 if k == 'p_p' else 2
if _optimize==0: #--... |
def blank_neighbors(self) -> set:
return set(filter(lambda neighbor: neighbor.blank, self.neighbors))
def bombs_remaining(self) -> int:
return self.cell_integer - len(self.bomb_neighbors())
def get_more_to_flag(self) -> set:
pattern_flag: set = set()
for neighbor in self.non_zero_number_... | The function determines which neighboring cells to flag as bombs by comparing the count of blank neighbors to remaining bombs. If they match, it returns those neighbors; otherwise, it recursively finds additional cells to flag. | def get_neighbors_to_flag(self) -> set:
this_blank: set = self.blank_neighbors()
return this_blank if len(this_blank) == self.bombs_remaining() else self.get_more_to_flag() |
def get_number(self) -> int:
if not self.number:
raise NotImplementedError
else:
return self.cell_integer
def bomb_neighbors(self) -> set:
return set(filter(lambda neighbor: neighbor.bomb, self.neighbors))
def blank_neighbors(self) -> set:
return set(filter(lambda... | The function determines whether to reveal neighboring cells in a Minesweeper game. It checks if the current cell's number matches the count of adjacent bombs. If true, it returns True and the list of blank neighbors to reveal; otherwise, it returns False and additional cells to reveal via `get_more_to_reveal`. This aid... | def get_neighbors_to_reveal(self) -> tuple:
if self.get_number() == len(self.bomb_neighbors()):
return True, self.blank_neighbors()
else:
return False, self.get_more_to_reveal() |
def get_cells_to_flag(self) -> set:
to_flag: set = set()
for cell in self.workset:
to_flag |= cell.get_neighbors_to_flag()
return to_flag
def log_action(self, action: str) -> None:
if self.log:
print(self.ACTIONS.get(action, action))
def flag_all(self, to_flag: se... | The code automates a game by iteratively flagging or revealing cells based on available actions. It prioritizes flagging cells, then revealing, and finally random reveals if no other actions are possible. The loop continues until no blank cells remain, with logging of each action. The final infinite loop is a placehold... | def play(self) -> None:
while not len(self.blank) == 0:
to_flag: set = self.get_cells_to_flag()
if not len(to_flag) == 0:
self.log_action('flag')
self.flag_all(to_flag)
else:
to_reveal: set = self.get_cells_to_reveal()
... |
def fp_get_vpn_server(fp):
fp.register(
["nmcli", "connection", "export", fp.any()],
stdout=NMCLI_CONNECTION_EXPORT_HTBCLI,
)
def fp_add_connection(fp, fail_import=False, connection_exists=True):
fp_connect_exists(fp, connection_exists=connection_exists)
if connection_exists:
fp.... | This test verifies that the 'htb vpn connect' command fails correctly by simulating a disconnected state, checking for the expected error output, and ensuring no definitions remain in the test environment after a failed connection attempt. | def test_vpn_connect_fail(fp, runner):
"""Test `htb vpn connect`"""
fp_get_vpn_server(fp)
fp_add_connection(fp)
fp_get_active_connection_name(fp, disconnected=True)
fp_connect_to(fp, success=False)
result = runner.invoke(cli, ["vpn", "connect"])
assert result.output == "[-] Failed to connect... |
def fp_disconnect(fp, success=True):
fp_get_active_connection_name(fp)
if success:
fp.register("nmcli connection down id htbcli".split())
else:
fp.register("nmcli connection down id htbcli", stderr="ERROR")
def fp_get_vpn_server(fp):
fp.register(
["nmcli", "connection", "export",... | (The function tests the failure scenario of the `vpn connect-ra` command by simulating a failed connection attempt. It disconnects, sets up a non-existent connection, and invokes the CLI command to verify the correct error output and state, ensuring no definitions are added upon failure.) | def test_vpn_connect_ra_failed_connection(fp, runner):
"""Test failure of `connect_to` in `vpn connect-ra`"""
fp_disconnect(fp)
fp_get_vpn_server(fp)
fp_add_connection(fp, connection_exists=False)
fp_get_active_connection_name(fp, disconnected=True)
fp_connect_to(fp, success=False)
result = ... |
def fp_disconnect(fp, success=True):
fp_get_active_connection_name(fp)
if success:
fp.register("nmcli connection down id htbcli".split())
else:
fp.register("nmcli connection down id htbcli", stderr="ERROR")
def fp_get_vpn_server(fp):
fp.register(
["nmcli", "connection", "export",... | The test function verifies the 'htb vpn connect -s' command's behavior when connecting to various servers, including successful connections, error handling for invalid servers, failed imports, switch failures, and disconnect issues. It checks output messages and ensures the state of VPN definitions remains correct acro... | def test_vpn_connect_server(fp, monkeypatch, runner):
"""Test `htb vpn connect -s ` to various servers"""
# `vpn connect -s eu-vip-5`, when current is us-vip-7
fp_disconnect(fp)
fp_get_vpn_server(fp)
fp_add_connection(fp)
fp_get_active_connection_name(fp, disconnected=True)
fp_connect_to(fp... |
def fp_get_vpn_server(fp):
fp.register(
["nmcli", "connection", "export", fp.any()],
stdout=NMCLI_CONNECTION_EXPORT_HTBCLI,
)
def fp_add_connection(fp, fail_import=False, connection_exists=True):
fp_connect_exists(fp, connection_exists=connection_exists)
if connection_exists:
fp.... | The main task of the code is to test the 'htb vpn connect' command by setting up a VPN connection environment, invoking the CLI command, and verifying expected output strings ("Local connection," "Current HTB Lab," "Current RA") and ensuring no leftover definitions exist post-execution. | def test_vpn_connect(fp, runner):
"""Test `htb vpn connect`"""
fp_get_vpn_server(fp)
fp_add_connection(fp)
fp_get_active_connection_name(fp)
fp_print_status(fp)
result = runner.invoke(cli, ["vpn", "connect"])
assert "Local connection" in result.output
assert "Current HTB Lab" in result.o... |
def fp_disconnect(fp, success=True):
fp_get_active_connection_name(fp)
if success:
fp.register("nmcli connection down id htbcli".split())
else:
fp.register("nmcli connection down id htbcli", stderr="ERROR")
def fp_get_vpn_server(fp):
fp.register(
["nmcli", "connection", "export",... | This test function verifies the behavior of the 'htb vpn connect-ra' command by disconnecting from a VPN, retrieving server details, adding a connection, and checking that the command output correctly indicates a local connection while ensuring no residual definitions remain in the test environment. | def test_vpn_connect_ra(fp, runner):
"""Test `htb vpn connect-ra`"""
fp_disconnect(fp)
fp_get_vpn_server(fp)
fp_add_connection(fp)
fp_get_active_connection_name(fp, disconnected=True)
fp_connect_to(fp)
fp_print_status(fp, disconnected=True)
result = runner.invoke(cli, ["vpn", "connect-ra... |
def assign_List(self):
""" Create object list. """
if (self.clase != '') and (self.level != ''):
self.list = [self.repo, self.name, self.clase, self.node.lineno,
self.node.end_lineno, self.node.col_offset, self.level]
print("Analyzing: - "+self.list[1],sel... | This method traverses an abstract syntax tree (AST) to locate nodes matching a specified attribute type. When a matching node is found, it initializes tracking variables, updates hierarchical levels, assigns node data to lists/dictionaries, and triggers JSON file reading operations for further processing. | def locate_Tree(self):
""" Method iterating on the tree. """
for self.node in ast.walk(self.tree):
#-- Find attributes
if type(self.node) == eval(self.attrib):
self.level = ''
self.clase = ''
levels.levels(self)
self... |
def check_piece_touch(self):
for other_piece in self.placed_pieces:
for other_tile in other_piece.get_tile_positions():
for active_tile in self.active_piece.get_tile_positions():
if active_tile[0] == other_tile[0] and active_tile[1] + 1 == other_tile[1]:
return True
for acti... | This code handles a game step by moving an active piece based on `x_action`, checking for collisions. If the piece touches the bottom or another piece, it's placed, and a second check triggers game over if still touching. It then processes completed rows, advancing the game state. | def step(self, x_action):
if self.game_over:
return
self.steps += 1
self.active_piece.start = (self.active_piece.start[0] + x_action, self.active_piece.start[1] + 1)
if self.check_piece_touch():
self.mark_active_as_placed()
if self.check_piece_touch():
self.game_over = True... |
def _get_subsection(section, key, section_idx):
"""
An auxiliary function
"""
if isinstance(section, dict):
if key in section:
return section[key], None
if isinstance(section, list):
if section_idx == self.Li... | The function recursively updates a nested data structure (dict/list) by creating or modifying keys based on requested_levels, handling edge cases like missing keys or leaf nodes. It returns a mutated copy of the section and a boolean indicating if changes were made, supporting modes for appending, removing, or overridi... | def update_section(section, requested_levels, scope, section_idx=None):
"""
Main recursion function, returns a mutated copy of section and a boolean indicating a change was made
"""
self._logger.verbose(
"update_section() called",
section=s... |
def __connect_buttons(self) -> None:
self._eq_control_buttons.ResetDialsButton.clicked.connect(lambda: self._eq_widget.eq_dials.__reset_dials())
def __connect_menu_bar_methods(self) -> None: # TODO outsource further
menu_bar: Union[EQMenuBar, QMenuBar] = self.menuBar()
menu_bar.open_file_action... | The main task of the code is to initialize a GUI window with a title, icon, fixed size, menu bar, and central layout containing specific widgets. It sets up the interface structure, connects button and menu actions, displays the window, and triggers an "open" operation. | def __init_gui(self) -> None:
"""Initialize GUI components"""
self.setWindowTitle(WINDOW_TITLE)
self.setWindowIcon(QtGui.QIcon(ICON_PATH))
self.setFixedSize(960, 540)
self.setMenuBar(EQMenuBar(self))
self.setCentralWidget(QWidget())
layout = QVBoxLayout()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.