dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def getAllSubs(v):
verbNegated = isNegated(v)
subs = [tok for tok in v.lefts if tok.dep_ in SUBJECTS and tok.pos_ != "DET"]
if len(subs) > 0:
subs.extend(getSubsFromConjunctions(subs))
else:
foundSubs, verbNegated = findSubs(v)
subs.extend(foundSubs)
return subs, verbNegated
... | This function extracts subject-verb-object (SVO) triples from a list of spaCy tokens, considering negation. It identifies verbs (excluding auxiliaries), finds their subjects and objects, and constructs triples with negation markers if either the verb or object is negated. The result is a list of (subject, verb[obj], ob... | def findSVOs(tokens):
svos = []
verbs = [tok for tok in tokens if tok.pos_ == "VERB" and tok.dep_ != "aux"]
for v in verbs:
subs, verbNegated = getAllSubs(v)
# hopefully there are subs, if not, don't examine this verb any longer
if len(subs) > 0:
v, objs = getAllObjs(v)
... |
def getAllSubs(v):
verbNegated = isNegated(v)
subs = [tok for tok in v.lefts if tok.dep_ in SUBJECTS and tok.pos_ != "DET"]
if len(subs) > 0:
subs.extend(getSubsFromConjunctions(subs))
else:
foundSubs, verbNegated = findSubs(v)
subs.extend(foundSubs)
return subs, verbNegated
... | The code extracts subject-verb-object (SVO) triples from tokenized text, handling negation and adjectives. It identifies verbs (excluding auxiliaries), collects their subjects and objects, checks for negation, and generates compound forms for subjects and adjective descriptions for objects. The result is a list of tupl... | def findSVAOs(tokens):
svos = []
verbs = [tok for tok in tokens if tok.pos_ == "VERB" and tok.dep_ != "aux"]
for v in verbs:
subs, verbNegated = getAllSubs(v)
# hopefully there are subs, if not, don't examine this verb any longer
if len(subs) > 0:
v, objs = getAllObjsWith... |
def view_tickets():
print_header("DAFTAR TIKET TERSIMPAN")
if not_empty(tickets):
print_data(all_data=True)
else:
print("MAAF BELUM ADA TIKET TERSIMPAN")
input("Tekan ENTER untuk kembali ke MENU")
def add_ticket():
print_header("MENAMBAHKAN TIKET BARU")
judul = input("JUDUL \t: ")
jam = input("JAM \t: ")
ta... | The code defines a function `check_user_input` that processes a user's character input. It converts the input to uppercase and triggers corresponding actions: 'Q' exits the program, while '1'–'6' call functions for viewing, adding, finding, deleting, updating tickets, or displaying application info. The function centra... | def check_user_input(char):
char = char.upper()
if char == "Q":
print("BYE!!!")
return True
elif char == "1":
view_tickets()
elif char == "2":
add_ticket()
elif char == "3":
find_ticket()
elif char == "4":
delete_ticket()
elif char == "5":
update_ticket()
elif char == "6":
about_application() |
def sort_edge(self):
self.graph = sorted(self.graph, key=lambda item: item[2])
def find(self, i, parent_arr):
if parent_arr[i] == i:
return i
return self.find(parent_arr[i], parent_arr)
def union(self, x, y, parent_arr, rank_arr):
# find the two of 2 element
x_root = ... | This function implements Kruskal's algorithm to find the Minimum Spanning Tree (MST) of a graph. It initializes Union-Find structures, sorts edges by weight, and iteratively selects edges, avoiding cycles, to construct the MST. The total weight of the MST and its edges are returned. | def kruskal_mst(self):
mst = [] # store the result minimum spanning tree of Graph
edge_ind = 0 # use for indicating element in sorted edges of Graph
mst_ind = 0 # use for indicating index in result mst (to make sure all vertices is accounted for)
parent_arr = []
rank_arr ... |
def parse(argv):
return get_parser().parse_args(argv)
def parse_tasks(conf):
tasks = {}
root = ET.parse(conf).getroot()
for task in root.findall("tasks"):
name = task.attrib["name"]
tasks[name] = set()
for i in task.findall("includesfile"):
tasks_sets = parse_list(i.t... | The main task of the code is to process command-line arguments, parse configuration files to extract tasks, and either execute or validate these tasks based on the 'validate' flag. It handles argument parsing, task configuration loading, and conditional task execution/verification. | def main(argv=None):
if argv is None:
argv = sys.argv[1:]
args = parse(argv)
tasks = parse_tasks(args.conf)
if not args.validate:
return run_tasks(tasks, args)
return validate_tasks(tasks, args) |
def re_draw(self):
self.canvas.delete("all")
# self.canvas = tk.Canvas(self.master, width=self.width + 2, height=self.height + 2)
if self.use_image:
self.canvas.create_image(((self.width + 2) / 2, (self.height + 2) / 2), image=self.tkimage)
self.canvas.create_text(180, 80,
... | This code handles keyboard events to manipulate a graphical map/diagram. It allows users to undo edges ('u'), save/load maps ('s'/'o'), toggle between edge/vertex modes ('e'/'v'), enable/disable vertex appending ('a'/'z'), create new vertices ('c'), and detect/draw cycles ('p') using NetworkX. The function updates the ... | def key(self, event):
# print("pressed", repr(event.char))
if event.char == 'u':
print("pressed u")
if len(self.edges) > 1:
self.edges.pop()
self.previousPoint = self.edges[len(self.edges)-1][1]
elif len(self.edges) == 1:
... |
def make_dataset(self, root_dir, extensions, class_to_idx):
"""creates a list of paths to data in root data directory
Args:
root_dir (string): root directory with subdirectory containing .npy files of eeg readings class 1-4.
extensions: extensions allowed.
class_to_i... | This code initializes a dataset class for EEG data classification, loading .npy files from a directory. It organizes data into 3D tensors (17x39x11) and binary targets (direction or confidence classification). It applies transformations, handles 3D convolution, and encodes subject IDs, preparing data for ML models. | def __init__(self, root_dir, threeD = False, transform=None, device = None):
"""
Args:
direction (bool): True if classifying direction. Otherwise classify confidence.
root_dir (string): root directory with subdirectory containing .npy files of eeg readings class 1-4.
... |
def is_game_over(self):
return self.is_full() or self.is_winner('X') or self.is_winner('O')
def move(self, row, col):
if row < 0 or row > 2 or col < 0 or col > 2:
print('Invalid move')
return False
if self.board[row][col] != ' ':
return False
self.boar... | The code's main task is to run a game loop where the human player ('X') and AI alternately make moves on a board until the game ends. It prints the board state, takes user input for 'X's moves, uses the AI's decision-making to determine its moves, updates the board, and finally displays the winner once the game conclud... | def play(self):
while not self.is_game_over():
print(self.board)
if self.player == 'X':
row = int(input('Enter row: '))
col = int(input('Enter col: '))
self.move(row, col)
else:
move = self.ai.move(self.board)
... |
def get_pretty_suite(self, test: 'TestSerialisation') -> str:
if len(self.suites) > 1 and test.suite:
rv = TestHarness.split_suite_string(test.suite[0])[0]
s = "+".join(TestHarness.split_suite_string(s)[1] for s in test.suite)
if s:
rv += ":"
retur... | The code executes a series of tests, handling parallel processing via ThreadPoolExecutor, logging results, and reporting statistics. It runs tests repeatedly based on the 'repeat' option, processes outcomes, and manages directory contexts and log files. | def run_tests(self, tests: T.List['TestSerialisation']) -> None:
executor = None
futures = [] # type: T.List[T.Tuple[conc.Future[TestRun], int, int, T.List[TestSerialisation], str, int]]
test_count = len(tests)
name_max_len = max([len(self.get_pretty_suite(test)) for test in tests])
... |
def get_tests(self) -> T.List['TestSerialisation']:
if not self.tests:
print('No tests defined.')
return []
if self.options.include_suites or self.options.exclude_suites:
tests = []
for tst in self.tests:
if self.test_suitable(tst):
... | The main task of the code is to execute a set of tests once, ensuring the test harness is not reused, and return the total number of test failures. It first checks if the harness has already been used; if so, it raises an error. If no tests are present, it returns 0. Otherwise, it runs the tests and returns the count o... | def doit(self) -> int:
if self.is_run:
raise RuntimeError('Test harness object can only be used once.')
self.is_run = True
tests = self.get_tests()
if not tests:
return 0
self.run_tests(tests)
return self.total_failure_count() |
def get_tests(self) -> T.List['TestSerialisation']:
if not self.tests:
print('No tests defined.')
return []
if self.options.include_suites or self.options.exclude_suites:
tests = []
for tst in self.tests:
if self.test_suitable(tst):
... | The code runs user-specified tests (e.g., "under gdb 1000 times") if a full run hasn't occurred, executes the tests, and returns the total failure count. It prevents re-running after a full execution by raising an error if `self.is_run` is True. | def run_special(self) -> int:
'''Tests run by the user, usually something like "under gdb 1000 times".'''
if self.is_run:
raise RuntimeError('Can not use run_special after a full run.')
tests = self.get_tests()
if not tests:
return 0
self.run_tests(tests)
... |
def pass_through_blocks(self, x, molecule_type):
return [block(x) for block in self.blocks[molecule_type]]
def format_block_outputs(self, seq_outs):
if seq_outs[0].shape == 2:
seq_outs[0] = seq_outs[0][0].unsqueeze(0).unsqueeze(2)
return seq_outs
def flatten_block_outputs(self, block... | The code processes RNA and protein inputs through separate block sequences, formats their outputs, concatenates them, and applies dense layers to generate a final output. | def forward(self, rna, prot):
rna_outs = self.pass_through_blocks(rna, 'rna')
rna_outs = self.format_block_outputs(rna_outs)
prot_outs = self.pass_through_blocks(prot, 'prot')
prot_outs = self.format_block_outputs(prot_outs)
out = self.flatten_block_outputs(*rna... |
def create_parameters(newParameters, config):
'''create parameters from config file'''
newParameters = copy.deepcopy(newParameters)
for category, items in DICT_OVERVIEW.items():
# Category iterates over setup and parameterBox
for key, value in items.items():
print(category, ... | The function updates parameters, genomes, and replicates based on the provided config file, processes the 'multiFasta' string into a list, retrieves the alignment file ('xmfa') from the config, and returns these updated values along with the processed multiFasta list. | def handle_config_file(parameters, config, genomes, replicates):
'''update parameter, genomes, replicate values regarding the given config file'''
parameters = create_parameters(parameters, config)
# save multiFasta string as list
multiFasta = config['multiFasta'].split(',')
# upd... |
def readMasterTable(path) -> tuple[dict, set]:
'''read MasterTable and return as JSON. Return also a set of unique TSS'''
data_per_genome = {}
tss_unique = set()
with open(path, 'r') as f:
# Parse Header
header = f.readline().rstrip().split('\t')
# get indices of relevant columns... | The function processes TSSpredator analysis results to enhance visualization by copying configuration files, parsing genomic data, aggregating TSS positions, generating CSV files for interactive tools like Gosling.js, and saving structured JSON data in the specified output directory. | def process_results(tempDir, resultsDir):
"""
Process the results of TSSpredator analysis for a better visualization.
The results are stored in the resultsDir directory.
Args:
tempDir (str): The path to the temporary directory containing the analysis files.
resultsDir (str): The path ... |
def nn_chain_kron(op, op_I, qubit_num, qubit_state_num):
# nearest neighbour kron: e.g. xxii + ixxi + iixx
op_list = ['I'] * (qubit_num - 2)
op_list = ['OP', 'OP'] + op_list
a_all = np.zeros([qubit_state_num ** qubit_num, qubit_state_num ** qubit_num])
for ii in range(qubit_num - 1):
if op... | The function generates components for quantum simulation, including control Hamiltonians (Hops), the system's initial Hamiltonian (H0), an identity initial unitary (U0), and a target unitary (U, typically a Hadamard gate). It sets up parameters for qubit interactions, defines state spaces, and prepares operators for po... | def generate_spin_func(qubit_num):
# Choose optimizing State transfer or Unitary gate
state_transfer = False
# Choose whether include intermediate state evolution as part of the graph optimization
use_inter_vecs = False
# Defining H0
qubit_state_num = 2
freq_ge = 0 # GHz
g = 2 * np.p... |
def get_common_psf(fitsfiles):
""" common psf for the list of fits files """
beams = []
bmajes = []
bmines = []
bpas = []
for f in fitsfiles:
ih = fits.getheader(f)
bmajes.append(ih['BMAJ'])
bmines.append(ih['BMIN'])
bpas.append(ih['BPA'])
beam = Beam.from... | The main task of the code is to create a mosaic image from multiple radio astronomy data files by convolving them with a common PSF, applying primary beam correction, cropping, and reprojecting. It combines corrected and uncorrected images using weighted coaddition, inserts PSF and unit metadata into the FITS header, a... | def main(images, pbimages, reference=None, pbclip=0.1, output='mosaic.fits',
clean_temporary_files=True, rmnoise=False, logger=None):
if logger is None:
logger = logging.getLogger('amos')
common_psf = get_common_psf(images)
corrimages = [] # to mosaic
uncorrimages = []
pbweights = ... |
def projects_data(file_path):
data_extractor = DataExtractor()
data = data_extractor.read_csv(fpath=file_path)
if data.empty:
return
# Clean and transform the dataframe
# Note: too many NaNs if we check row count to just remove.
# Do not remove NaNs until further instruction is receive... | The main task of the code is to load and process three CSV datasets—projects, donations, and resources—from a specified directory. It constructs file paths for each dataset and passes them to corresponding functions (`projects_data`, `donations_data`, `resources_data`) for further processing. The code does not execute ... | def main():
# What are the data files provided?
data_path = os.path.join(os.getcwd(), "datasets")
# Projects data
file_path = os.path.join(data_path, "projects.csv")
projects_data(file_path)
# Donations data
file_path = os.path.join(data_path, "donations.csv")
# file_path = os.path.joi... |
def kill_bs(bit):
get_all_bs()
for i in bs_hwnd:
if bit == 64 and any(str(64) in s for s in i["cmd"]):
print("Killing BlueStacks 64-bit with ID", i["hwnd"])
get_process(i["hwnd"]).kill()
elif bit == 32 and all(str(64) not in s for s in i["cmd"]):
print("Killin... | The code launches a specified mobile application (Clash of Clans, Soul Land, or ILLUSION CONNECT) in BlueStacks emulator based on the provided bit version (32/64), terminates existing instances, starts the app, minimizes its window, retrieves window handles, and returns the handle for further processing. | def start_app(name, bit):
cc32 = r'"C:\Program Files\BlueStacks\HD-RunApp.exe" ' \
r'-json "{\"app_icon_url\":\"\",\"app_name\":\"Clash of Clans\",\"app_url\":\"\",' \
r'\"app_pkg\":\"com.supercell.clashofclans\"}"'
cc64 = r'"C:\Program Files\BlueStacks\HD-RunApp.exe" ' \
r'-jso... |
def flip_antimeridian(ds, to='Pacific', lonn='lon'):
"""
# https://git.iac.ethz.ch/utility_functions/utility_functions_python/-/blob/regionmask/xarray.py
Flip the antimeridian (i.e. longitude discontinuity) between Europe
(i.e., [0, 360)) and the Pacific (i.e., [-180, 180)).
Parameters:
- ds (x... | This code initializes a data generator for training a model, preprocessing forecast (fct) and verification (verif) datasets. It adjusts data based on the specified region (global/Europe), applying coordinate flips, slicing, padding, and transposing. Parameters like batch size, shuffling, and RAM loading are configured.... | def __init__(self, fct, verif, region='global',
batch_size=32, shuffle=True, load=False):
"""
Parameters
----------
fct: DataSet, global preprocessed fields, coordinates: latitude, longitude, forecast_time
verif: DataSet, global preprocessed fields, coordinates: ... |
def create_complex_constant_plain(self, const, encoder):
"""Creates a plaintext containing a constant value.
Takes any constant, and turns it into a plaintext.
Args:
const (float): Constant to encode.
encoder (CKKSEncoder): Encoder.
Returns:
Plainte... | The code evaluates the exponential function on an encrypted value, computing $ e^{\text{const} \cdot m} $ where $ m $ is the plaintext message. It scales the constant, applies a Taylor series approximation, and iteratively squares the result while rescaling to manage noise growth, using homomorphic operations and a rel... | def exp(self, ciph, const, relin_key, encoder):
"""Evaluates the exponential function on the ciphertext.
Takes an encryption of m and returns an encryption of e^(const * m).
Args:
ciph (Ciphertext): Ciphertext to transform.
const (complex): Constant to multiply cipherte... |
def multiply_matrix(self, ciph, matrix, rot_keys, encoder):
"""Multiplies the ciphertext by the given matrix quickly.
Returns a ciphertext for the matrix multiplication using the Baby-Step Giant-Step algorithm
described in the CKKS paper.
Args:
ciph (Ciphertext): Ciphertext... | This function transforms encrypted polynomial coefficients in a ciphertext into two encrypted vectors of plaintext slots. It uses rotation keys, conjugation, matrix multiplication, and scaling to split and encode the coefficients into two ciphertexts (ciph0 and ciph1) for CKKS encoding, enabling homomorphic operations ... | def coeff_to_slot(self, ciph, rot_keys, conj_key, encoder):
"""Takes a ciphertext coefficients and puts into plaintext slots.
Takes an encryption of t(x) = t_0 + t_1x + ... and transforms to
encryptions of (t_0, t_1, ..., t_(n/2)) and (t_(n/2 + 1), ..., t_(n-1))
before these vectors are... |
def raise_modulus(self, ciph):
"""Raises ciphertext modulus.
Takes a ciphertext (mod q), and scales it up to mod Q_0. Also increases the scaling factor.
Args:
ciph (Ciphertext): Ciphertext to scale up.
Returns:
Ciphertext for exponential.
"""
# ... | The code performs bootstrapping on a ciphertext to refresh its modulus, reducing noise and maintaining encryption accuracy. It raises the modulus, transforms coefficients to slots, computes exponential and sine operations via complex arithmetic, scales results, and converts back to coefficient form. The output is a new... | def bootstrap(self, ciph, rot_keys, conj_key, relin_key, encoder):
"""Evaluates the bootstrapping circuit on ciph.
Takes a ciphertext (mod q), that encrypts some value m, and outputs a new
ciphertext (mod Q_0) that also encrypts m, via bootstrapping.
Args:
ciph (Ciphertext)... |
def initialize_connection(self, mode:str = "cluster"):
"""Initializes the connection with a redis node or cluster
Args:
mode: String that indicates whether to connect to a cluster or node
Returns:
True if connection is initialized, else False
"""
try:
... | The main task of the code is to edit JSON data stored in a sorted set by searching for a matching UUID. It converts the input object to a JSON dictionary, replaces the existing entry with the new data, and updates the database. If conversion fails or no match is found, it returns False. | def edit(self, name:str, obj:object, id:str=None) -> bool:
"""Edits the json contents based on uuid value"""
self.initialize_connection(mode=self.mode)
print(name)
# Get all elements in the sorted set and determine if there are any matching the input uuid
sorted_set_data = self.g... |
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def Downsample(dim, dim_out = None):
return nn.Conv2d(dim, default(dim_out, dim), 4, 2, 1)
def Upsample(dim, dim_out = None):
return nn.Sequential(
nn.Upsample(scale_factor = 2, mode = 'nearest'),
nn... | This code defines a UNet-like neural network architecture for image generation, specifically tailored for diffusion models. It initializes convolutional layers, ResNet blocks with time embeddings, attention mechanisms, and downsampling/upsampling paths. The model processes input channels multiplied by a bit depth facto... | def __init__(
self,
dim,
init_dim = None,
dim_mults=(1, 2, 4, 8),
channels = 3,
bits = BITS,
resnet_block_groups = 8,
learned_sinusoidal_dim = 16
):
super().__init__()
# determine dimensions
channels *= bits
self.chann... |
def is_valid(grid):
# Check rows
for row in grid:
if not is_valid_row(row):
return False
# Check columns
for column_index in range(9):
if not is_valid_column(grid, column_index):
return False
# Check subgrids
for row_index in range(0, 9, 3):
for ... | The code solves a Sudoku puzzle using backtracking. It checks if the input grid is valid, then recursively fills empty cells (0s) with numbers 1-9, ensuring each placement is valid. If a valid number is found, it proceeds recursively; if no solution is found, it backtracks. The function returns the solved grid or None ... | def solve(grid):
# Check if the grid is valid
if not is_valid(grid):
return None
# Create a copy of the original grid to avoid modifying the input
grid_copy = copy.deepcopy(grid)
for row in range(0,9):
for column in range(0,9):
if grid_copy[row][column] == 0:
... |
def get_required_fields(self) -> set:
self._require_fields({'transactionType'})
key = TransactionType(self['transactionType'])
if key is TransactionType.CHARGE:
key = ChargeTransactionType.REC_TOKEN if self.get('recToken') else ChargeTransactionType.NO_REC_TOKEN
return set(RE... | This method prepares required fields for a request by excluding 'merchantSignature', validates the remaining fields, and generates a signature using the provided merchant key for authentication. | def prepare(self, merchant_key: str):
required_fields = self.get_required_fields()
required_fields -= {'merchantSignature'}
self._require_fields(required_fields)
self['merchantSignature'] = self._generate_signature(merchant_key) |
def init_logging():
"""
Initialize the logging system using the logging level provided by the calling
'environment' and return a logger
"""
level = parameter_read('AWS_TEA_CONFIG_LOG_LEVEL', default_value='INFO')
logging.basicConfig(format="%(name)s - %(module)s - %(message)s",level=level)
l... | The code generates a TEA configuration by validating input parameters (provider ID and CMR token) from an API request, retrieving environment settings, and invoking a TEA processor. It returns the configuration in YAML format with metadata like CMR URL, token, provider, and request timing. | def generate_tea_config(event, context):
"""
Lambda function to return a TEA configuration. Requires that event contain
the following:
* CMR must be configured with an env variable
* Path Parameter named 'id' with CMR provider name
* HTTP Header named 'Authorization' with a CMR compatible token
... |
def init_logging():
"""
Initialize the logging system using the logging level provided by the calling
'environment' and return a logger
"""
level = parameter_read('AWS_TEA_CONFIG_LOG_LEVEL', default_value='INFO')
logging.basicConfig(format="%(name)s - %(module)s - %(message)s",level=level)
l... | The main task of the code is to collect and return structured debug information about an AWS environment, including event data, context details, environment variables (with sensitive fields redacted), and configuration parameters. It logs initialization, timestamps execution, and formats the output into an HTTP respons... | def debug(event, context):
""" Return debug information about AWS in general """
logger = init_logging()
logger.info("Debug have been loaded")
start = datetime.datetime.now()
body = {
'context': context.get_remaining_time_in_millis(),
'event': event,
'clean-header': lowerca... |
def get_test_data(self, video_name, path):
X_test = []
X_test_filename = []
for i in path:
filename = i.split('.')[0]
f = np.load(os.path.join('C:/Users/Rasika/Django/VQA_11/data/features_dir', video_name + '.npy'))
X_test.appe... | The code processes test video data by decoding sequences into text using a model, iterating through each test sample to generate and print decoded sentences, then returning the last decoded result. It reshapes input data, applies decoding functions, and resets probability tracking for each sample. | def test(self, video_name,a):
X_test, X_test_filename = self.get_test_data(video_name, a)
print(len(X_test), len(X_test_filename))
# generate inference test outputs
for idx, x in enumerate(X_test):
decoded_sentence = self.decode_sequence2bs(x.reshape(-1,... |
def get_gl_entries(filters):
order_by_statement = "order by reference_doc, account"
gl_entries = frappe.db.sql(
"""
select name as gl_entry, posting_datetime, account, voucher_type, reference_doc, debit, credit, reason
from `tabGL Entry` {conditions} {order_by_statement}
""".for... | The code retrieves general ledger entries based on filters, processes them with opening/closing balances, and formats the result as a list for output. | def get_data(filters):
gl_entries = get_gl_entries(filters)
data = get_data_with_opening_closing(filters, gl_entries)
result = get_result_as_list(data, filters)
return result |
def validate_filters(filters):
if filters.from_date > filters.to_date:
frappe.throw(_("From Date must be before To Date"))
def get_columns(filters):
columns = [
{
"label": _("GL Entry"),
"fieldname": "gl_entry",
"fieldtype": "Link",
"options": "GL ... | The code defines a function `execute` that processes input filters to retrieve and return structured data. It initializes empty lists for columns and data, validates the filters, fetches column definitions and dataset rows using the filters, then returns them as a tuple. The core task is to dynamically generate report ... | def execute(filters=None):
columns, data = [], []
validate_filters(filters)
columns = get_columns(filters)
data = get_data(filters)
return columns, data |
def set_download_params(self, date, forecast, variables, verify=True):
self._download_params = {'date':date,
'forecast': forecast,
'variables': variables}
out_fld = self.output_path + f'/{self.source}-{self.model}-{date}-{forecast}'
... | The main task of this code is to continuously stream and download data files from a model (e.g., EC) based on dynamic parameters like date, forecast, and variables. It logs operations, checks available files, manages transitions between forecasts/days, converts/deletes files as specified, and restarts streaming on erro... | def stream(self):
#global catch all for now
try:
#initially set to starting stream params
p = self.stream_params
day = p['startdate']
forecast = p['startforecast']
vars = p['variables']
convert = p['convert']
delete = p[... |
def _load_generated_captions_into_evaluator(self, cap_file, sample_num, org_dir=None):
'''
Meant to save time so imid_to_objects does not always need to be recomputed.
'''
#Read in captions
self.caps, imids, self.metrics = load_generated_captions(cap_file, org_dir=org_dir)
... | The code evaluates generated captions for hallucinations by comparing predicted objects against ground truth, calculating metrics like CHAIRs (hallucination rate per caption) and CHAIRi (proportion of hallucinated words). It processes captions, identifies mismatched terms, and aggregates statistics on hallucination fre... | def compute_chair(self, cap_file, sample_num, gpt_process=False, org_dir=None):
'''
Given ground truth objects and generated captions, determine which sentences have hallucinated words.
'''
self._load_generated_captions_into_evaluator(cap_file, sample_num, org_dir=org_dir)
imi... |
def check_age_gender(user):
DB_FILE="pref.db"
db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops -- you will use cursor to trigger db events
female = list(c.execute("SELECT female FROM pref WHERE user =?", (user,)).fetchone())[0]
ma... | The code retrieves user preferences and profile data from databases, filters potential matches based on criteria like height, gender, and optional filters (star sign, MBTI), calculates compatibility scores using metrics such as shared hobbies, height alignment, and a love calculator API, then returns matches sorted by ... | def match(user):
matches = {}
DB_FILE="pref.db"
db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops -- you will use cursor to trigger db events
#matches_sorted = {}
#user preference information:
use_star_sign = list(c.execut... |
def _update_container_yaml(self, container):
container["env"] = [
*self._get_kubernetes_job_operator_envs(),
*container.get("env", []),
*self._get_kubernetes_env_list(),
]
def _update_main_container_yaml(self, container: dict):
if self.command:
con... | This function updates Kubernetes resource specifications by modifying container configurations, adding volume mounts from predefined secrets, and managing image pull secrets. It recursively processes nested dictionaries to apply these changes, ensuring no duplicate image pull secrets and correctly formatting volume mou... | def _update_override_params(self, o: dict):
if "spec" in o and "containers" in o.get("spec", {}):
containers: List[dict] = o["spec"]["containers"]
if isinstance(containers, list) and len(containers) > 0:
for container in containers:
self._update_contai... |
def _validate_job_runner(self):
if self._job_runner is not None:
return
self._job_runner = self.create_job_runner()
assert isinstance(self._job_runner, JobRunner), KubernetesJobOperatorException(
"create_job_runner method must return a value of type JobRunner"
)
d... | (This method prepares for job execution by validating the job runner, loading Kubernetes configurations, preparing the job body, updating override parameters, and delegating to the parent class's pre_execute method to ensure proper Airflow operator functionality.) | def pre_execute(self, context):
"""Called before execution by the airflow system.
Overriding this method without calling its super() will
break the job operator.
Arguments:
context -- The airflow context
"""
self._validate_job_runner()
self._job_is_ex... |
def _reset_deck(self):
self.current_deck = [*self.card_list]
def _shuffle_deck(self):
random.shuffle(self.current_deck)
def get_attacks(self, base_attacks: List[int]) -> List[Tuple[int, Set[str]]]:
"""Get a final attack values from a list of base attacks
Args:
- base_attacks... | The code simulates a sequence of attacks by processing each input in `base_attacks` (either a list or generator). If `fresh` is True, it resets and shuffles the deck before processing. It applies `get_attacks` to each input, collects results in a list, and returns them. The main task is to generate attack outcomes whil... | def simulate(
self,
base_attacks: Union[List[List[int]], Generator[List[int], Any, Any]],
fresh: bool = True,
) -> List[int]:
if fresh:
self._reset_deck()
self._shuffle_deck()
res = []
for attacks in base_attacks:
res.append(self.g... |
def update_hash(self):
"""
Generates a hash / integer value of the current position using the Zobrist hashing algorithm
"""
self.zobrist_hash = 0
"""
1. Pieces
"""
for i, piece in enumerate(self.board):
if piece:
self.zobrist_h... | This method executes a chess move by updating the board state, handling pawn promotions, en passant captures, castling, and updating game state variables. It checks move legality, updates piece positions, manages special rules, and detects game-ending conditions like checkmate, stalemate, or draw by repetition. | def move(self, old: int, new: int, promote_to=None):
"""
Move a piece and update the current position
"""
if old not in self.legal_moves or new not in self.legal_moves[old]:
return MoveResults.ILLEGAL
elif self.game_result:
return MoveResults.GAME_ALREAD... |
def coordinate_to_i(coor: str):
if len(coor) != 2 or coor[0] not in "abcdefgh" or not 1 <= int(coor[1]) <= 8:
raise ValueError(f"invalid coordinate \"{coor}\"")
return ord(coor[0]) - ord("a") + (8 - int(coor[1]))
def update_hash(self):
"""
Generates a hash / integer value of the current... | This function parses a FEN string to initialize a chessboard's state. It decodes piece placement from the board string, sets active color, castling rights, en passant target, halfmove clock, and move number. It validates input format, constructs the board array, and updates internal game state attributes like hash, pie... | def load_fen(self, fen: str):
board_raw, turn, castling_rights, en_passantable, halfmove_clock, move_num = fen.split()
# 1. Piece placement on board
decoded_board = []
rows = board_raw.split("/")
if len(rows) != 8:
raise ValueError(f"board string consists of {rows} ... |
def load_fen(self, fen: str):
board_raw, turn, castling_rights, en_passantable, halfmove_clock, move_num = fen.split()
# 1. Piece placement on board
decoded_board = []
rows = board_raw.split("/")
if len(rows) != 8:
raise ValueError(f"board string consists of {rows} ... | This code initializes a chess position object, setting up standard properties like the board, turn, move count, castling rights, en passant, and legal move generation. It also tracks game state elements such as piece positions, Zobrist hash for position uniqueness, check status, pinned pieces, and repetitions. The cons... | def __init__(self, fen=None, load_from=None):
""""""
"""
Standard FEN chess position properties
"""
self.board = []
self.turn = True # True: white's turn, False: black's turn
self.move_num = 1
self.halfmove_clock = 0
self.en_passantable = -1
... |
def __read_basic(self, reading: dict):
reading['processor_use'] = round(psutil.cpu_percent(interval=None))
cpu_temp = None
if sys.platform != "win32":
lavg = os.getloadavg()
reading['load_1'] = round(lavg[0], 2)
reading['load_5'] = round(lavg[1], 2)
reading['load... | This method collects data into a dictionary based on three flags: if 'basic' data is included, directory sizes are read, or network interfaces are read. It conditionally calls private methods to populate the dictionary and returns the aggregated data. | def read_data(self):
reading = {}
if self.__is_include_basic:
self.__read_basic(reading)
if self.__is_read_dirs:
self.__read_dir_sizes(reading)
if self.__is_read_net_ifaces:
self.__read_net_ifaces(reading)
return reading |
def end_of_file(self, line):
if "" == line:
if self.case_started:
self.current_case.add_error('Error. Unexpected EOF')
return True
return False
def line_is_correct(self, line, args_amount, line_num):
if len(line) == args_amount:
for arg in line... | This code parses a file line by line to extract coffee shop data and optimal positions. It tracks line numbers, processes cases, validates lines, and updates case status. When a case starts, it adds coffee shops or optimal positions based on line structure. After processing all distances, it resets counters. If no case... | def parse(self, name):
file = open(name, 'r')
line_num = 0
coffee_shop_num = 1
distance_num = 1
while True:
line = file.readline()
if self.end_of_file(line):
break
if not line.strip():
continue
li... |
def update_mini_batch(self, mini_batch, eta):
"""Update the network's weights and biases by applying
gradient descent using backpropagation to a single mini batch.
The ``mini_batch`` is a list of tuples ``(x, y)``, and ``eta``
is the learning rate."""
nabla_b = [np.zeros(b.shape)... | The code implements mini-batch stochastic gradient descent (SGD) to train a neural network. It iterates over epochs, shuffles training data, divides it into mini-batches, and updates weights using the `update_mini_batch` method. It tracks training loss and, if test data is provided, evaluates accuracy on both training ... | def SGD(self, training_data, epochs, mini_batch_size, eta,
test_data=None):
"""Train the neural network using mini-batch stochastic
gradient descent. The ``training_data`` is a list of tuples
``(x, y)`` representing the training inputs and the desired
outputs. The other non... |
def _is_supported_file(document: workspace.Document) -> bool:
"""Checks if the given document is supported by this tool."""
if document.path:
file_path = pathlib.Path(document.path)
return file_path.exists()
return False
def log_always(message: str) -> None:
"""Logs messages with notifi... | This function performs linting on a document if it's supported. It runs a tool, logs output, retrieves settings, parses the tool's output into diagnostics using regex, and returns them. If unsupported or errors occur, it returns an empty list or logs errors. | def _linting_helper(document: workspace.Document) -> list[lsp.Diagnostic]:
try:
if not _is_supported_file(document):
log_always(f"Skipping linting for {document.uri} skipped: not supported")
return []
result = _run_tool_on_document(document, use_stdin=False)
if resul... |
def _run_tool(extra_args: Sequence[str], settings: Dict[str, Any]) -> utils.RunResult:
"""Runs tool."""
code_workspace = settings["workspaceFS"]
cwd = get_cwd(settings, None)
use_path = False
use_rpc = False
if len(settings["path"]) > 0:
# 'path' setting takes priority over everything.
... | The main task of the code is to check and log the version of a linter (e.g., flake8) against a minimum required version for each workspace configuration. It runs the linter's `--version` command, extracts the version string from the output, compares it with `MIN_VERSION`, and logs a warning/error if the installed versi... | def _log_version_info() -> None:
for value in WORKSPACE_SETTINGS.values():
try:
from packaging.version import parse as parse_version
settings = copy.deepcopy(value)
result = _run_tool(["--version"], settings)
code_workspace = settings["workspaceFS"]
... |
def log_to_output(
message: str, msg_type: lsp.MessageType = lsp.MessageType.Log
) -> None:
"""Logs messages to Output > Flake8 channel only."""
LSP_SERVER.show_message_log(message, msg_type)
def _update_workspace_settings(settings):
if not settings:
key = utils.normalize_path(GLOBAL_SETTINGS.ge... | The main task of the code is to initialize an LSP server by logging the current working directory, system paths, and configuration settings from the initialization parameters. It updates global and workspace settings, then logs these settings in JSON format for debugging, along with version information. | def initialize(params: lsp.InitializeParams) -> None:
"""LSP handler for initialize request."""
log_to_output(f"CWD Server: {os.getcwd()}")
paths = "\r\n ".join(sys.path)
log_to_output(f"sys.path used to run Server:\r\n {paths}")
GLOBAL_SETTINGS.update(**params.initialization_options.get("glob... |
def get_optimizer_state(config: TrainingConfig,
params: ArrayTree,
) -> optax.OptState:
'''Get the optimizer state.'''
optimizer = get_optimizer(config)
opt_state = optimizer.init(params)
opt_state_n = hk.data_structures.tree_size(opt_state)
opt_state_... | The main task of the code is to train a machine learning model by either loading a configuration file or a checkpoint. It initializes model parameters, optimizer state, and processes data batches. The function supports saving checkpoints, logging training metrics to CSV, and controlling training iterations. It handles ... | def cli_train(config_path: Optional[Path],
load_from: Optional[Path],
save_path: Optional[Path],
save_frequency: int,
log_frequency: int,
csv_path: Optional[Path],
stop_at: Optional[int],
seed: ... |
def tryMoveCurrent(self, direction, x, y):
return self.tryMove(self.currentShape, direction, x, y)
def mergePiece(self):
for x, y in self.currentShape.getCoords(self.currentDirection, self.currentX, self.currentY):
self.backBoard[x + y * BoardData.width] = self.currentShape.shape
se... | The main task of the code is to attempt to move the current game piece downward. If successful, it updates the piece's position; if not, it merges the piece, removes any completed lines, creates a new piece, and returns the count of removed lines. This logic is typical in grid-based games like Tetris for handling piece... | def moveDown(self):
lines = 0
if self.tryMoveCurrent(self.currentDirection, self.currentX, self.currentY + 1):
self.currentY += 1
else:
self.mergePiece()
lines = self.removeFullLines()
self.createNewPiece()
return lines |
def tryMoveCurrent(self, direction, x, y):
return self.tryMove(self.currentShape, direction, x, y)
def mergePiece(self):
for x, y in self.currentShape.getCoords(self.currentDirection, self.currentX, self.currentY):
self.backBoard[x + y * BoardData.width] = self.currentShape.shape
se... | This function moves a game piece down until it can't, merges it into the grid, removes any completed lines, generates a new piece, and returns the count of removed lines. | def dropDown(self):
while self.tryMoveCurrent(self.currentDirection, self.currentX, self.currentY + 1):
self.currentY += 1
self.mergePiece()
lines = self.removeFullLines()
self.createNewPiece()
return lines |
def calcStep1Board(self, d0, x0):
board = np.array(BOARD_DATA.getData()).reshape((BOARD_DATA.height, BOARD_DATA.width))
self.dropDown(board, BOARD_DATA.currentShape, d0, x0)
return board
def calcNextDropDist(self, data, d0, xRange):
res = {}
for x0 in xRange:
if x0 no... | This function determines the optimal Tetris piece movement by evaluating all valid rotations and positions for the current and next shapes. It calculates scores for each possible configuration, prioritizing the strategy with the highest score to maximize gameplay efficiency. | def nextMove(self):
t1 = datetime.now()
if BOARD_DATA.currentShape == Shape.shapeNone:
return None
currentDirection = BOARD_DATA.currentDirection
currentY = BOARD_DATA.currentY
_, _, minY, _ = BOARD_DATA.nextShape.getBoundingOffsets(0)
nextY = -minY
... |
def create_image_from_text(parameters):
# '''
endpoint_name = os.environ['IMAGE_CREATE_ENDPOINT']
runtime = boto3.client('runtime.sagemaker')
#
parameters = json.loads(parameters)
print("Call endpoint: ", endpoint_name)
print("With parameters: ", parameters)
request_parameters = {}
... | The code is a Lambda function handling API Gateway requests to perform image operations. It processes incoming JSON parameters, executes actions like `create`, `modify`, or `inpaint` via corresponding functions, and returns a structured response with a generated image URL or error details. The function logs parameters,... | def handler(event, context):
"""Sample pure Lambda function - use for education when you add your extension
Parameters
----------
event: dict, required
API Gateway Lambda Proxy Input Format
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-inte... |
def get_length(shape, avg_shape_size, use_tuples=None):
if shape == 'rectangle':
length = get_rect_len(avg_shape_size)
elif shape == 'circle':
length = get_circle_len(avg_shape_size)
else:
length = get_triangle_len(avg_shape_size, use_tuples)
return length
def get_note_length_pro... | The main task of the code is to generate a sequence of note lengths based on parameters like shape, average size, sequence length, and playfulness. It creates uniform or variable-length notes, applies playful variations, handles triangular shapes with special logic (e.g., lag effects), and optionally extends the last n... | def generate_length_sequence(shape, avg_shape_size, seq_length, playfulness=0.5, structure=None, extend_last=True):
lag_flag = False
if shape is 'triangle' and not CONST.exclude_tuples:
use_tuples = random_choice([True, False], p=[0.5, 0.5])
else:
use_tuples = None
if CONST.uniform_lengt... |
def obf_file(base_path, sfname):
try:
with open(base_path, 'r', encoding='utf-8', errors='ignore') as file:
f_content = file.read()
obfuscated_content = obfuscator(f_content)
with open(f"{sfname}-obf.py", 'w') as file:
file.write(obfuscated_content)
excep... | This code packages a Python script into an executable, creates a virtual environment, generates a startup shortcut, and cleans up temporary files, ultimately deploying the application with a success message. | def injector(startup_path, base_path, sfname, logopath):
obf_file(base_path, sfname)
virtual_env()
exe(sfname, logopath)
shortcut(startup_path, sfname)
remove(f"{sfname}-obf.py")
rmtree(f"{getcwd()}\\packages")
clear()
Write.Input(f"""{r}> File succefuly created ! (C:\ProgramData\{sfname... |
def obf_file(base_path):
try:
with open(base_path, 'r', encoding='utf-8', errors='ignore') as file:
f_content = file.read()
obfuscated_content = obfuscator(f_content)
os.remove(base_path)
with open(base_path, 'w') as file:
file.write(obfuscated_content)
ex... | The code's main task is to obfuscate a file, rename it, generate an executable, create a startup shortcut, and display success messages. It likely automates malicious payload deployment by hiding files, ensuring execution via startup shortcuts, and cleaning traces. The use of colored output and input prompts suggests a... | def injector(startup_path, base_path, sfname, r, logopath):
obf_file(base_path)
rename(base_path, f"{sfname}.py")
exe(sfname, logopath)
shortcut(startup_path, sfname)
clear()
Write.Print(r, Colors.red, interval=0)
Write.Input(f"\n-> File succefuly created in C:\ProgramData\{sfname} ! \n-> Sh... |
def cx_freeze_checker(r):
try:
import cx_Freeze
except:
error("CX_Freeze not installed !")
clear()
slp(1)
Write.Print(r, Colors.red, interval=0)
Write.Print("\nCX_Freeze installation started..\n", Colors.red, interval=0.0025)
try:
sys("pip inst... | The code's main task is to inject a malicious payload (RAT) into a Python script by taking user inputs for the RAT's name, file path, and icon, then generating a disguised executable with a shortcut in the startup folder. It includes input validation, path sanitization, error handling, and displays ASCII art with color... | def main():
characters = """ '," """
r= """ ██╗███╗ ██╗ ██╗███████╗ ██████╗████████╗ ██████╗ ██████╗
███║████╗ ██║ ██║██╔════╝██╔════╝╚══██╔══╝██╔═████╗██╔══██╗
╚██║██╔██╗ ██║ ██║█████╗ ██║ ██║ ██║██╔██║██████╔╝
██║██║╚██╗██║██ ██║██╔══╝ ██║ ██║ ████╔╝██║██╔══██╗
██║██║ ╚... |
def hideall():
for obj in bpy.data.objects:
obj.hide_set(True)
def exportone(objname):
global s_sli
global s_vol
print("Exporting " + objname)
obj = bpy.data.objects.get(objname)
if obj is None:
print("Skipping " + objname)
return
belliesToMake = body[objname]["Bel... | The main task of the code is to clean an output directory by removing existing files, process enabled 3D objects from a list, export them using `exportone()`, concatenate results into global strings with separators, and finally write these aggregated data into files via `writefiles()`, ensuring organized data output in... | def main():
global folder
global datafolder
global s_vis
global s_cc
global s_bt
global s_at
hideall()
folder = os.path.dirname(bpy.data.filepath) + "\\" + outputdir
if not os.path.exists(folder):
os.makedirs(folder)
datafolder = os.path.dirname(bpy.data.filepath) + "\\"... |
def _create_posting(self, target_posting):
post_response = self.make_post_request(target_posting, payload_encoding=None, content_type_header=None)
assert post_response.status_code == 201 # Created
return post_response.json()
def get_delete_request_headers(self, posting):
overwriting_de... | The function `make_multiple_delete_requests` either executes multiple delete requests using provided requirements or generates these requirements by testing various header combinations. It creates postings, forms headers, makes delete requests, and updates requirements based on response codes. It tracks whether the tar... | def make_multiple_delete_requests(self, target_posting, delete_requirements=None):
if delete_requirements:
posting_to_delete_exists = False
for r in delete_requirements:
if not posting_to_delete_exists:
posting_to_delete = self._create_posting(target_p... |
def read_file_content(serach_str_1, search_str_2, search_regex):
#search_str_1 = 'STARTED_xxxx_SENSOR_AT:'
#search_str_2 = 'COMPLETED_xxxx_SENSOR_AT:'
#search_regex = '_INCIDENT_SENSOR_AT:'
logs_list = []
with open(sensor_logs_file_path, "r+") as sensor_logs:
sensor_data = sensor_logs.readli... | The code monitors sensor logs (INCIDENT_SENSOR or PENDING_SENSOR) by parsing timestamps from log files, calculating the time difference between the latest log entry and the current time, and triggering a sensor restart based on this difference. It reads specific log entries, formats dates, computes the difference in mi... | def monitor_sensor_logs(sensor_type):
if sensor_type == 'INCIDENT_SENSOR':
logs_list = read_file_content('STARTED_INCIDENT_SENSOR_AT:', 'COMPLETED_INCIDENT_SENSOR_AT:', '_INCIDENT_SENSOR_AT:')
if sensor_type == 'PENDING_SENSOR':
logs_list = read_file_content('STARTED_PENDING_SENSOR_AT:', 'COMPLE... |
def compare_active_sensors():
sensor_name = ""
sensor_process_list = []
process_list = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
execute_sensors_command = subprocess.Popen(['grep', 'sensor'], stdin=process_list.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)... | The main task of the code is to monitor registered sensors by querying a StackStorm API, compare them with active sensor processes, and restart services if discrepancies are found. It retrieves enabled sensor names, checks against running processes, logs status, and triggers a restart if registered sensors do not match... | def register_sensor_list():
registered_sensors = []
#If below api key is not working create a new api key by using below command
#st2 apikey create -k -m '{"test_key": "test api key"}'
api_key = "API_KEY"
sensor_parameters = "ref,pack,name,enabled"
stackstorm_ip_port = "127.0.0.1:9101"
senso... |
def _load_file(self):
if path.exists(self.file_path):
with open(self.file_path) as f_r:
json_data = json.load(f_r)
return json_data
else:
return None
def upd_more_config(self, config_data):
file_path = f'{self.dir_atlas}/{sample_json}'
... | This function updates the 'host' field in the 'postgres' section of a specified JSON configuration file with the instance's IP address, saves the modified configuration, and handles file not found errors. It loads the JSON data, modifies the 'postgres' entry, applies additional configuration updates, and writes the cha... | def _setup_address(self, json_file=None):
self.file_path = f'{self.dir_atlas}/{json_file}'
print(f'Update ipaddress file {json_file}')
config_json_data = self._load_file()
if config_json_data:
config_data = deepcopy(config_json_data)
if config_data.get('postgres')... |
def get_onehot(data, var_cont, var_cate, y):
value_sets = {}
dummy_rules = {}
for variable in var_cate:
value_set = sorted(list(set(data[variable])))
if len(value_set) <= 1 or len(value_set) > 10:
continue
value_sets[variable] = value_set
dummies = np.identity(len... | This function builds a decision tree using neural networks for regression. It recursively splits data based on continuous or categorical variables, determining optimal splits via statistical tests and model residuals. The tree grows by fitting neural networks at nodes, handling small datasets with heteroscedasticity, a... | def grow_tree(data, var_cont, var_cate, y, split_dims, leaf_dims, p_value = 0.05,
Nmin = 1000, split_num = 10, num_epochs = 1000, batch_size = 64,
lr = 0.01, train_prop = 0.8, set_seed = 42, index = [1], region_info = 'All Data'):
dummy_rules, data_onehot = get_onehot(data, var_cont... |
def get_opts():
""" Return an argparse object. """
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--verbose', default=logging.INFO, action='store_const',
const=logging.DEBUG, help='enable debug logging')
p... | The main task of the code is to execute a script that processes command-line options, disables signals if specified, cleans resources if requested, creates all necessary components, and logs the script's completion time. It initializes logging, handles optional configurations, and ensures proper setup or cleanup operat... | def main():
""" script entry point """
opts = get_opts()
logging.info('Starting script')
if opts.disable_signals:
disconnect_signals()
if opts.clean:
clean()
start_time = datetime.datetime.now()
end_time = datetime.datetime.now() - start_time
create_all()
logging.... |
def state_string_to_list(state_string: str) -> list:
state_list = []
idx = 0
while idx < len(state_string):
s = state_string[idx]
if s == '1':
state_list.append(1)
elif s == '0':
state_list.append(0)
idx += 1
return state_list
def convert_states_to... | The code updates the current state and actions based on predicted classifications. It initializes the state if empty, calculates suggested actions from state changes, updates cumulative confidence, checks for completed actions, and advances the frame. | def update(self, pred: list, frame_n: int):
self.frame_n = frame_n
if len(pred) != 0:
pred_class, pred_conf = pred[0][0], pred[0][1]
# determine which step changes are predicted to have occurred
pred_state_str = categories[int(pred_class)]
pred_state = s... |
def print_board(board):
print(board[0] + "|" + board[1] + "|" + board[2])
print("-+-+-")
print(board[3] + "|" + board[4] + "|" + board[5])
print("-+-+-")
print(board[6] + "|" + board[7] + "|" + board[8])
print()
def board_not_full(board):
return ' ' in board
def select_move(letter, board):
... | The function `play_game` manages a Tic-Tac-Toe game loop, alternating between player and computer turns, checking for a win or tie after each move, and prompting the user to replay the game if desired. It handles move selection, board updates, win detection, and game continuation logic. | def play_game(player_letter, computer_letter, board):
print_board(board)
letter_to_move = 'X'
while board_not_full(board):
if letter_to_move == player_letter:
move = select_move(letter_to_move, board)
else:
move = computer_selects_move(letter_to_move, board)
i... |
def get_grid_image_coord(xy_coord_grid):
return topo_shape[1] - xy_coord_grid[1] - 1, xy_coord_grid[0]
def get_grid_xy_coord(xy_coord_raw):
return int(xy_coord_raw[0] / grid_size_in_cm), int(xy_coord_raw[1] / grid_size_in_cm)
def turn_car_forward():
global car_facing_dir
movements = [None, None, move_le... | The code's main task is to navigate a car through a mapped environment by scanning surroundings, updating a topological map, using A* pathfinding, and visualizing progress. It initializes the car's position, iteratively scans for obstacles, updates the map, computes a path to a target, visualizes the map, and navigates... | def main():
print('starting main thread')
global car_grid_image_coord, car_coord_raw, car_facing_dirar
# generate numpy array
car_grid_image_coord = get_grid_image_coord(get_grid_xy_coord(car_coord_raw))
topo_map[car_grid_image_coord] = 3
servo.set_angle(START_ANGLE)
iter = 0
# while ite... |
def _get_ph_country_id(self):
res = self._scraper.post(COUNTRIES_URI, data={'regionId': APAC_REGION_ID}, verify=False)
print("country")
print(res.text)
countries = res.json()['Countries']
ph_country_id_list = [ country['Id'] for country in countries \
... | The execute method retrieves a country ID, fetches associated sites, updates a JSON file with the sites, and handles exceptions by printing error details. | def execute(self):
try:
ph_country_id = self._get_ph_country_id()
sites = self._get_sites(ph_country_id)
self._update_sites_json(sites)
except Exception as ex:
print("{}: {}".format(type(ex).__name__, ex)) |
def become_follower():
global timer
global state
global voted
voted = False
state = State.FOLLOWER
print_whoami()
if timer is None:
timer = Timer(timer_interval, become_candidate)
timer.start()
else:
reset_timer()
def print_to_console(msg):
print("From server ... | The main task of the code is to implement the Raft consensus algorithm's RequestVote RPC. It sends vote requests to all nodes (except itself), handles term updates if a higher-term response is received, counts votes, and transitions to leader status if a majority of votes are obtained. | def send_request_vote():
for addr in nodes.values():
if addr == nodes[id]:
continue
channel = grpc.insecure_channel(addr)
stub = pb2_grpc.RaftServiceStub(channel)
response = None
global term_number
global state
try:
response = stub.Requ... |
def print_to_console(msg):
print("From server " + id + ": " + msg)
def print_whoami():
if state == State.FOLLOWER:
print_to_console("I am a follower. Term " + str(term_number))
if state == State.CANDIDATE:
print_to_console("I am a candidate. Term " + str(term_number))
if state == State.L... | The function transitions a node to CANDIDATE state when a leader timeout occurs. It increments the term, self-votes, and initiates a request for votes from other nodes to gain majority support for leadership. This is part of a consensus algorithm where nodes compete to become leaders upon detecting leader failure. | def become_candidate():
global state
global voted
global votes
global term_number
global timer
if timer.finished and state.FOLLOWER:
print_to_console("The leader is dead")
state = State.CANDIDATE
term_number += 1
print_whoami()
votes[term_number] =... |
def define_logger(file_name):
# create a file handler and set the logging level
handler = logging.FileHandler(
f'files/logs/{file_name}.log')
handler.setLevel(logging.DEBUG)
# create a formatter and add it to the handler
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s : ... | The main task is to read data from SQL Server based on the provided company and endpoint arguments, process it, and insert it into a data warehouse (dw). The code handles different endpoints with specific logic: some use 'entry_no' or 'no' columns, while others delete existing records before insertion. The process incl... | def main():
date_time = datetime.now()
# date_time = date_time - timedelta(days=1)
if (len(sys.argv) == 3):
company_short = sys.argv[1]
endpoint = sys.argv[2]
logger = define_logger(
f"04_read_send_to_sql_{company_short}_{endpoint}")
logger.debug(f'-------- Exec... |
def define_logger(file_name):
# create a file handler and set the logging level
handler = logging.FileHandler(
f'files/logs/{file_name}.log')
handler.setLevel(logging.DEBUG)
# create a formatter and add it to the handler
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s : ... | The main task of the code is to read data from a SQL database based on specified endpoints and company codes, adjust the date to the previous day, and either insert or update records in a data warehouse. It uses command-line arguments for company and endpoint parameters, logs execution details, and processes data diffe... | def main():
date_time = datetime.now()
date_time = date_time - timedelta(days=1)
if (len(sys.argv) == 3):
company_short = sys.argv[1]
endpoint = sys.argv[2]
logger = define_logger(
f"04_read_send_to_sql_{company_short}_{endpoint}")
logger.debug(f'-------- Execut... |
def define_logger(file_name):
# create a file handler and set the logging level
handler = logging.FileHandler(
f'{file_name}.log')
handler.setLevel(logging.DEBUG)
# create a formatter and add it to the handler
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s : %(message)s... | The main task of the code is to read data from a SQL Server database based on command-line arguments (company_short and endpoint), log execution details, and insert the retrieved data into a data warehouse (DW) using predefined table mappings and parameters. It utilizes logging for tracking execution, fetches records f... | def main():
date_time = datetime.now()
if (len(sys.argv) == 3):
company_short = sys.argv[1]
endpoint = sys.argv[2]
logger = define_logger(
f"04_read_send_to_sql_{company_short}_{endpoint}")
logger.debug(f'-------- Executing 04 read_send_to_sql ---------')
lo... |
def defineCVParams(cv_params):
cv_seed = cv_params['cv_seed'] if "cv_seed" in cv_params else 1
n_folds = cv_params['n_folds'] if "n_folds" in cv_params else 10
cv_metric = cv_params['cv_metric'] if "cv_metric" in cv_params else "loglikelihood"
search_iters = cv_params['search_iters'] if "search_iters" ... | The function `crossValidate` performs cross-validation for a Cox proportional hazards model. It splits the training data into folds, trains the model on each fold, and evaluates performance using either log-likelihood or C-index. The results are aggregated and returned as an array of cross-validation scores. | def crossValidate(x_train, ytime_train, ystatus_train, model_params = dict(),search_params = dict(),cv_params = dict(), verbose=False):
cv_seed, n_folds, cv_metric, search_iters, L2_range = defineCVParams(cv_params)
N_train = ytime_train.shape[0]
cv_likelihoods = numpy.zeros([n_folds], dtype=numpy.dtype("... |
def defineCVParams(cv_params):
cv_seed = cv_params['cv_seed'] if "cv_seed" in cv_params else 1
n_folds = cv_params['n_folds'] if "n_folds" in cv_params else 10
cv_metric = cv_params['cv_metric'] if "cv_metric" in cv_params else "loglikelihood"
search_iters = cv_params['search_iters'] if "search_iters" ... | The function `L2Profile` performs cross-validation to evaluate a Cox proportional hazards model with varying L2 regularization strengths. It iterates over a range of L2 values, trains the model on training data, combines training and validation data, and computes either log-likelihood or C-index metrics based on the sp... | def L2Profile(x_train, ytime_train, ystatus_train, x_validation, ytime_validation, ystatus_validation, model_params = dict(),search_params = dict(),cv_params = dict(), verbose=False):
cv_seed, n_folds, cv_metric, search_iters, L2_range = defineCVParams(cv_params)
N_train = ytime_train.shape[0]
likeliho... |
def create_species_card(species_name):
image_filename = species_name.replace(" ", "_") + '.jpg'
image_path = os.path.join('data/species/', image_filename)
url_path = f'/species/{format_species_name_for_url(species_name)}'
return dbc.Card(
dbc.CardBody([
dbc.Button([
d... | The code updates a Dash UI based on user interactions (button clicks, selections) by returning dynamic layouts, visibility states, and content. It handles navigation between species cards, trail displays, and pagination, adjusting UI elements like buttons, cards, and text styles conditionally. | def update_ui(n_clicks_next, n_clicks_prev, selected_species, species_btn_clicks, back_click):
ctx = dash.callback_context
if not ctx.triggered:
raise PreventUpdate
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if 'back-btn' in button_id:
# Reset to the default view with all s... |
def get_samplesheet_header_dict(samplesheet: SampleSheet) -> Dict:
"""
This function retrieves the header information from a given SampleSheet object and returns it as a dictionary.
Parameters:
samplesheet (SampleSheet): The SampleSheet object from which to retrieve the header information.
Returns... | The function converts a version 1 SampleSheet object into a structured JSON dictionary, incorporating header data, read configurations, BCLConvert settings, and cloud workflow parameters. It dynamically adds TSO500L-specific adapter settings and sample data if CTTSO samples are detected, ensuring compatibility with DNA... | def v1_samplesheet_to_json(samplesheet: SampleSheet) -> Dict:
"""
This function converts a version 1 SampleSheet object into a JSON format.
Parameters:
samplesheet (SampleSheet): The version 1 SampleSheet object to be converted.
Returns:
Dict: A dictionary representing the JSON format of the S... |
def number_of_black_squares_at(self, x,y):
# Add Up all Black Squares in a 3x3 Square around Restriction Number
amount_of_squares = 0
for i in range(0, 9):
pos = number_to_9x9(i)
_x = x + pos[0]
_y = y + pos[1]
if self.get_solution_at(_x, _y) == 1:... | This function restricts possible free box fields in a 9x9 grid by checking if nearby cells' black square counts match their values. If so, it marks adjacent empty cells (-1) to enforce constraints, returning whether any restrictions were applied. | def solve_restrict(self):
made_change = False
x = 0
# Restricts possible free box fields, if a nearby number is already satisfied
for row in self.original_board:
y = 0
for col in row:
num_squares = self.number_of_black_squares_at(x,y)
... |
def number_of_white_squares_at(self, x,y):
# Add Up all White Squares in a 3x3 Square around Restriction Number
amount_of_squares = 0
for i in range(0, 9):
pos = number_to_9x9(i)
_x = x + pos[0]
_y = y + pos[1]
if self.get_solution_at(_x, _y) == 0:... | This code fills the constructed_solution grid with black squares (1s) in positions surrounding cells where the required number of filled fields matches the available white spaces, updating the grid and returning whether any changes were made. | def solve_fill(self):
made_change = False
x = 0
# Whenever a number demands x amount of fields to be filled and it has exactly that amount of possible free room, we fill the entire room with black squares
for row in self.original_board:
y = 0
for col in row:
... |
def number_of_restricted_squares_at(self, x,y):
# Add Up all Restricted Squares in a 3x3 Square around Restriction Number
amount_of_squares = 0
for i in range(0, 9):
pos = number_to_9x9(i)
_x = x + pos[0]
_y = y + pos[1]
if self.get_solution_at(_x,... | This function decides whether to restrict or fill surrounding squares at (x,y) based on the ratio of restricted vs. black squares. With a 20% chance, it reverses the decision. If restricting, it marks surrounding squares as restricted; otherwise, it fills them as black. Finally, it marks the clue as picked by storing t... | def pick_clue_at(self, x,y):
# Negative number means this clue is already picked
if self.clues[x][y] < 0:
return
# Get Amount of Restricted boxes
restricted = self.number_of_restricted_squares_at(x, y)
# Get Amount of Black boxes
blacks = self.number_of_black... |
def set_black(self, x, y):
# Deprecated
# Check for Legality first:
# We can not set a block to black twice
already_black = self.get_solution_at(x,y)
if already_black:
return False
# If square surrounding this Black box already has a Restriction of 0 (they wo... | This code recursively solves a puzzle by placing blocks at coordinates (x,y), validating constraints, and counting unique solutions. It backtracks invalid moves, checks for duplicate solutions using a hash, and returns the number of valid solutions found or -1 if multiple solutions exist. | def solve_step(self, x,y, depth):
# Deprecated
# Occupy Block at x,y
valid = self.set_black(x,y)
# If the operation was not valid, nothing has been changed and we can safely return to upper recursion level
if not valid:
return 0
#print("Set " + str(x) + " ... |
def solve_restrict(self):
made_change = False
x = 0
# Restricts possible free box fields, if a nearby number is already satisfied
for row in self.original_board:
y = 0
for col in row:
num_squares = self.number_of_black_squares_at(x,y)
... | The main task of the code is to repeatedly apply solving steps (solve_restrict and solve_fill) to iteratively refine a solution until no further changes occur, then validate the final solution. The loop continues as long as either solving method makes a change, ensuring the solution meets constraints. The function retu... | def iterate_solution(self):
iterate = True
while iterate:
iterate = False
change = self.solve_restrict()
change = change or self.solve_fill()
iterate = change
return self.valid_solution() |
def get_unchosen_clue(self, border_discouragement):
# Border Discouragement gradually decreases from 1 to 0
# At 1, the entire board can be chosen from
# At 0, only the middle is taken into consideration
# The higher Board Wave is, the move we move inward
border_wave = 1 - bord... | The code selects a clue position on a board by randomly evaluating multiple unchosen positions, choosing the one with the lowest combined count of black and white squares. It then picks that clue if valid, returning True, or False otherwise. | def choose_good_clue_position(self, border_discouragement):
# Picks x Random Positions on the board and evaluates their maximum and minimum Number value
amount_of_picks = random.randint(3,6)
start_clue = self.get_unchosen_clue(border_discouragement)
start_value = self.number_of_black_... |
def update_board_clues(self):
x = 0
for row in self.clues:
y = 0
for col in row:
# Get Amount of White boxes
whites = self.number_of_white_squares_at(x,y)
# Get Amount of Black boxes
blacks = self.number_of_black_squ... | The code generates a puzzle board with strategically placed clues to ensure no 9x9 area is clue-free. It initializes a grid, adds random clues while maintaining coverage rules, and adjusts the clues matrix for proper formatting and validation. | def create_board(self, amount_of_clues, seed = 0):
self.constructed_solution = [[0 for j in range(self.board_size)] for i in range(self.board_size)]
self.clues = [[0 for j in range(self.board_size)] for i in range(self.board_size)]
#random.seed(seed)
self.update_board_clues()
... |
def expand_node(node, to_play, actions,network_output):
node.to_play = to_play
node.hidden_state = network_output.hidden_state
node.reward = network_output.reward
policy = {a: math.exp(network_output.policy_logits[:,a]) for a in actions}
policy_sum = sum(policy.values())
for action, p in policy.... | This function plays a game using Monte Carlo Tree Search (MCTS) with a neural network. It initializes a game, iteratively expands search nodes, applies MCTS to select actions, and updates the game state until termination or max moves. The neural network provides initial inferences, and exploration noise is added. The p... | def play_game(config, network, render = False):
game = config.new_game(render = render)
while not game.terminal() and game.len_history() < config.max_moves:
# At the root of the search tree we use the representation function to
# obtain a hidden state given the current observation.
ind... |
def show_start_screen(self):
self.display_surf.fill(Config.COLORS['black'])
start_screen_rect = self.start_screen_text.get_rect(center=(Config.WINDOW_WIDTH // 2, Config.WINDOW_HEIGHT // 2))
self.display_surf.blit(self.start_screen_text, start_screen_rect)
pygame.display.update()
... | The code's main task is to manage a game loop by first displaying a start screen, then repeatedly running the game until `run_game()` returns False, at which point it shows a game over screen. The loop ensures continuous gameplay until the game ends, handling transitions between screens and maintaining the game state. | def run(self):
self.show_start_screen()
while True:
if not self.run_game():
self.show_game_over_screen() |
def parse_config(config_file_name: str) -> dict:
with open(config_file_name) as file:
config = yaml.safe_load(file)
print("load settings...")
pprint.pprint(config)
print()
return config
def load_template() -> tuple[str, str, str]:
# Load jinja2 template files.
pkg = importlib.resourc... | The main task of the code is to convert markdown files into HTML using a template and CSS based on a configuration file. It parses the config, loads the template and CSS, prepares output directories, converts markdown content, and writes static assets like CSS to the specified output paths. | def main(config_file_name: str):
config = parse_config(config_file_name)
template, css = load_template()
markdown_files = load_markdown_files(config)
make_output_dirs(markdown_files)
convert(markdown_files, config, (template))
write_css(css, config)
write_static(config) |
def parse_command_line_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="mdsite: Minimal Static Site Generator."
)
parser.add_argument("--version", action="store_true", help="Show mdsite version.")
parser.add_argument("--config", help="Specify YAML file.", default="mds... | The code defines an entrypoint function that parses command-line arguments, checks for a version flag, and either prints the version or executes the main function with a specified configuration. | def entrypoint():
args = parse_command_line_args()
if args.version == True:
print_version()
else:
main(args.config) |
def get_missed_data_in_percents(data_with_na, name='', show=True):
if show:
print("Data information for {}:".format(name))
table_length = data_with_na.shape[0]
if show:
print("Table samples number - {}".format(table_length))
missed_data = data_with_na.isnull().sum() / table_length * 100
... | The code evaluates various data cleaning and imputation methods (mean, regression, hot-deck, interpolation) on a dataset. It analyzes missing data percentages, compares cleaned data, applies linear regression for prediction, and tests imputation effectiveness by filling missing values with different techniques. The goa... | def start():
get_missed_data_in_percents(data, 'input data')
cleaned = clean_data(data, row=True)
get_missed_data_in_percents(cleaned, 'cleaned data')
# show_plots(cleaned)
print_comparision_information(cleaned['horsepower'], isDataset=False, name='cleaned')
# linear regression
linear_regre... |
def initialize_edges(self, nodes):
edges = set()
for node_from in nodes:
for node_to in nodes:
if node_from != node_to:
edges.add((node_from, node_to))
return edges
def edge_selection_based_on_adjacencies(self, data, edges):
separation_set ... | This function infers the skeleton structure of a probabilistic graphical model by iteratively selecting edges based on adjacencies and d-separation criteria, then orienting unshielded triples using separation sets. It refines the edge set through two rounds of edge selection and orientation to determine the underlying ... | def infer_skeleton(self):
edges = self.initialize_edges(list(self.data.keys()))
edges, separation_set = self.edge_selection_based_on_adjacencies(self.data, edges)
edges = self.orient_unshield_triples(edges, separation_set)
edges, separation_set = self.edge_selection_based_on_possible_d_... |
def initialize_edges(self, nodes):
edges = set()
for node_from in nodes:
for node_to in nodes:
if node_from != node_to:
edges.add((node_from, node_to))
return edges
def edge_selection_based_on_adjacencies(self, data, edges):
separation_set ... | The main task of the code is to infer a causal graph skeleton using bootstrapping. It repeatedly resamples data, infers edges via adjacency and d-separation checks, counts edge frequencies across samples, and retains edges meeting a threshold. This robust approach aggregates results to identify stable causal relationsh... | def bootstrap_infer_skeleton(self, bootstrap_samples=100, bootstrap_sample_ratio=1.0, bootstrap_edge_threshold=0.95):
edge_counts = {}
for i in range(bootstrap_samples):
print('Inferring bootstrap sample no.', i)
sample_indices = np.random.choice(self.sample_count, size=int(self... |
def jump(self):
self.bird_velocity = self.jump_strength
def update(self):
if not self.game_over:
self.bird_velocity += 1
self.bird_y += self.bird_velocity
self.generate_pipes()
self.move_pipes()
if self.pipes:
if self.pipes[0]... | This code runs a game loop that handles events (like quitting or jumping), updates game state, renders graphics, and maintains a consistent frame rate using Pygame. | def run(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
self.jump()
s... |
def total_paintable_area(rooms: list[list[tuple[float, float]]], windows_doors: list[tuple[str, list[float]]]) -> int:
'''
Returns the total area of paintable surface.
Calls room_paint_area() for each room.
'''
#total_room_area = sum(rect_area(length, height) for room in rooms for length, height... | The main task of the code is to test paint requirement calculations using default room and window/door parameters. It computes total paintable area, required paint volume, cans needed, and cost, then verifies results against expected values (1 can, £50 cost, 115m² area) via assertions. | def test_paint_required(rooms=[], windows_doors=[]):
if not rooms:
print("No rooms entered. Settings Default Values of 2 Rooms, 4 Walls Each, 2 Windows/Doors Each")
rooms = [
[(5, 5)], # Room 1: 4 walls
[(10, 10)] # Room 2: 4 walls
]
windows_doors... |
def print_welcome():
print(f"""
Hi, welcome to {store_name}!
I'll help you calculate the amount of paint you need to buy.
You will need to enter the dimensions of the rooms and windows/doors.
You can enter as many rooms and windows/doors as you like.
You can enter the... | The main task of the code is to calculate the total paintable area, required paint volume, number of cans, and cost for a room painting project. It uses user inputs for room dimensions, windows/doors, and paint type, then computes results, including the optimal paint option. The function prints detailed outputs like ar... | def run_room_painter():
print_welcome()
rooms = get_rooms()
windows_doors = get_windows_doors()
paint_type = get_paint_type()
try:
total_area = total_paintable_area(rooms, windows_doors)
total_volume = total_paint_volume(total_area, paint_type)
cans_needed, total_cost = to... |
def total_paint_area(rooms: list[list[tuple[float, float]]], windows_doors: list[tuple[str, list[float]]]) -> int:
'''
Returns the total area of paintable surface.
Calls room_paint_area() for each room.
'''
total_area = 0
for room in rooms:
total_area += room_paint_area(room, windows... | This function calculates and displays the total paint required for given rooms, considering windows/doors. It uses default room dimensions if none are provided, computes area, volume, cans needed, and cost using premium paint, then prints detailed results including coverage rate, liters per can, and total expenses. | def test_paint_required(rooms=[], windows_doors=[]):
if not rooms:
print("No rooms entered. Settings Default Values of 2 Rooms, 4 Walls Each, 2 Windows/Doors Each")
rooms = [
[(5, 5)], # Room 1: 4 walls
[(10, 10)] # Room 2: 4 walls
]
windows_doors... |
def print_welcome():
print(f"""
Hi, welcome to {store_name}!
I'll help you calculate the amount of paint you need to buy.
You will need to enter the dimensions of the rooms and windows/doors.
You can enter as many rooms and windows/doors as you like.
You can enter the... | The main task of the code is to calculate the total area to be painted, required paint volume, number of cans, and total cost based on user inputs for room dimensions, windows/doors, and paint type. It uses predefined functions to compute values like coverage rate, volume per can, and cost, then prints detailed results... | def run_room_painter():
print_welcome()
rooms = get_rooms()
windows_doors = get_windows_doors()
paint_type = get_paint_type()
total_area = total_paint_area(rooms, windows_doors)
total_volume = total_paint_volume(total_area, paints[paint_type]['coverage_rate'])
cans_needed, total_cost = tot... |
def total_paint_area(rooms: list[list[tuple[float, float]]], windows_doors: list[tuple[str, list[float]]]) -> int:
'''
Returns the total area of paintable surface.
Calls room_paint_area() for each room.
'''
total_area = 0
for room in rooms:
total_area += room_paint_area(room, windows... | The code tests paint requirement calculations by defining room dimensions, window/door sizes, and paint type. It computes total paint area, volume, and required cans/cost, verifying results against expected values (3 cans, $150, 2.28L) using assertions. | def test_paint_required():
rooms = [
[(10, 8), (10, 8), (12, 8), (12, 8)], # Room 1: 4 walls
[(15, 8), (15, 8), (20, 8), (20, 8)] # Room 2: 4 walls
]
windows_doors = [
('door', [2, 6]), # Door: 2x6
('window', [2, 2]), # Window: 2x2
('window', [2, 2]) # Wi... |
def parking_datasets(self, fn_yaml):
with open(fn_yaml, 'r') as stream:
parking_data = yaml.load(stream)
return parking_data
def get_parking_info(self, parking_data):
parking_contours = []
parking_bounding_rects = []
... | The main task of the code is to process a video frame to detect available parking spots. It loads parking configuration data, extracts contours and masks, applies image processing kernels, and uses the `main` method to analyze parking status. The function returns the detected available spots as a tuple of results. | def process_frame(self, fname):
car = self.car
#if os.path.exists(".\storage\config\id1.yml"):
#if os.path.exists(".\\storage\\config\\" + fname):
#parking_data = self.parking_datasets(".\storage\config\id1.yml")
parking_data = self.parking... |
def conn_to_smb(user, pwd, server, ip, domain):
client_machine_name = 'client' # as well any random name
server_name = server
conn = SMBConnection(user, pwd, client_machine_name, server_name, domain, use_ntlm_v2=True,
is_direct_tcp=True)
conn.connect(ip, 445)
shares = conn.li... | The main task of the code is to connect to an SMB server, retrieve usernames from file metadata in non-special shares, and save unique usernames to a text file. It skips system shares like 'NETLOGON' and 'SYSVOL', lists files in each share, collects author metadata, and stores results. If successful, it confirms saving... | def main(user, pwd, server, ip, domain):
print(colored("\n[*] Trying to retrieve usernames from files' metadata.", 'blue'))
authors_res = []
conn, shares = conn_to_smb(user, pwd, server, ip, domain)
cnt = 0
for share in shares:
if not share.isSpecial and share.name not in ['NETLOGON', 'SYSVO... |
def predict_viewpoint(self, predict_start_idx, predict_end_idx):
predicted_viewpoints = self.fov_traces_obj.predict_6dof(
self.current_viewing_frame_idx, predict_start_idx, predict_end_idx,
self.history_viewpoints)
return predicted_viewpoints
def calculate_probability_to_be_viewe... | The main task of the code is to update the buffer's tile sizes by predicting future viewpoints, calculating viewing probabilities, estimating bandwidth, and applying algorithm-specific methods (e.g., KKT, RUMA) to determine optimal tile rates. It adjusts buffer content based on predicted bandwidth and FoV accuracy, log... | def update_tile_size_in_buffer(self):
self.update_step += 1
##################### predict viewpoint #######################
if params.PROGRESSIVE_DOWNLOADING:
update_start_idx = self.current_viewing_frame_idx + params.TIME_GAP_BETWEEN_NOW_AND_FIRST_FRAME_TO_UPDATE * params.FPS + 1
... |
def background_load(screen_surf) -> tuple[pygame.Surface, pygame.Surface, pygame.Surface, pygame.Surface]:
# Called only once, at the beginning of game_loop()
bg_size = screen_surf.get_size()
# The background object
background = return_surface(
size=bg_size, init_color=globe.Window.background, m... | This function manages a game loop using Pygame, handling user input, game state transitions, and rendering. It initializes game assets, listens for events like quitting, starting via spacebar, and window resizing. When active, it updates game elements, checks for success/death status, and redraws the screen at a set FP... | def game_loop():
# utility globals
init_pos = globe.Squirrel.cur_pos
bg_size = screen_surf.get_size()
background, coin_surf, tree_surf, squirrel_surf = background_load(
screen_surf)
started = False
dead = False
bool_running = True
while bool_running:
# This is importan... |
def get_bounded(graph: DiGraph) -> Tuple[Any, Any]:
first = None
last = None
for node in graph.nodes:
if not nx.ancestors(graph, node):
first = node
break
for node in graph.nodes:
if not graph.adj[node]:
last = node
break
return (firs... | The main task of the code is to find a complement node in a directed graph by checking if any other node satisfies specific conditions: its maximum common successor (mcs) equals the graph's maximum value and its minimum common interval (mci) equals the graph's minimum value. If such a node exists, it is returned; other... | def get_complement(graph: DiGraph, node: Any) -> Optional[Any]:
minimum, maximum = get_bounded(graph)
for _node in graph.nodes:
if node == _node:
continue
mcs = get_mcs(graph, node, _node)
mci = get_mci(graph, node, _node)
if mcs == maximum and mci == minimum:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.