dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def setup_tables(spark, config: TestConfig, setup_updates_table = False):
"""
(Re)Create delta tables
"""
if config.recreate_setup:
if config.catalog_enabled:
recreate_table(spark, config.table_name, config.table_location)
if setup_updates_table:
recreate_... | (The main task of the code is to test the "optimize table" command's file compaction functionality by inserting multiple small data files, executing optimization, and verifying that new consolidated files are generated. The test checks if optimization reduces file count by consolidating small files into fewer ones, ens... | def test_10_optimize_table(spark, config: TestConfig):
"""
Test optimize table command
Optimize performs multiple ops, including:
- compaction of multiple small files into fewer files (exercized in this test)
- remove logically dropped columns
Setup:
- perform many small insert... |
def nullspace(x):
if not re.compile('^[ \t]+').match(x):
return x
return re.split(r'^[ \t]+', x)[1]
def path(x):
y = x
if not re.compile('^<').match(y):
raise UserWarning(501)
y = re.split(r'^<', y)[1]
y = mailbox(y)
if not re.compile('^>').match(y):
raise UserWarning... | This function processes the "MAIL FROM:" command in an email server. It extracts the sender's email address, applies formatting and validation steps (nullspace, path, CRLF), updates the last command state, and sends a "250 OK" response. The core task is parsing and validating the sender's email address while maintainin... | def mail_from(x, socket):
y = x
y = re.split(r'^MAIL[ \t]+FROM:',y)[1]
y = nullspace(y)
y = path(y)
y = CRLF(y)
global last_command
last_command = "FROM"
output = "From: <" + x.split("<")[1].split(">")[0] + ">\n"
#global content
#content += output
send_message("250 OK", socke... |
def nullspace(x):
if not re.compile('^[ \t]+').match(x):
return x
return re.split(r'^[ \t]+', x)[1]
def path(x):
y = x
if not re.compile('^<').match(y):
raise UserWarning(501)
y = re.split(r'^<', y)[1]
y = mailbox(y)
if not re.compile('^>').match(y):
raise UserWarning... | This function processes the "RCPT TO" command in an email server, parsing the recipient's email address, updating tracking variables (last_command, recipients), and sending a "250 OK" response. It extracts the domain, avoids duplicates in recipients, and formats the To: header for logging. | def rcpt_to(x, socket):
y = x
y = re.split(r'^RCPT[ \t]+TO:',y)[1]
y = nullspace(y)
y = path(y)
y = CRLF(y)
address = x.split("<")[1].split(">")[0]
global last_command
last_command = "TO"
output = "To: <" + address + ">\n"
domain = address.split("@")[1]
#global content
#c... |
def helo(x, socket):
y = x
y = re.split(r'^HELO[ \t]+',y)[1]
y = re.split(r'[ \t\n]',y)[0]
send_message("250 Hello " + y + " pleased to meet you", socket)
def mail_from(x, socket):
y = x
y = re.split(r'^MAIL[ \t]+FROM:',y)[1]
y = nullspace(y)
y = path(y)
y = CRLF(y)
global last_c... | This code parses SMTP commands from input string `x`, validates command sequence using `last_command` state, and executes corresponding functions (helo, mail_from, rcpt_to, data) while handling errors. It specifically checks command validity, enforces order (e.g., MAIL must follow HELO, DATA must follow RCPT), and term... | def parse(x, socket):
#print(x, end = "")
global last_command
if re.compile('^HELO[ \t]+').match(x):
last_command = "DATA"
helo(x, socket)
elif re.compile('^MAIL[ \t]+FROM:.*').match(x):
if not last_command == "DATA":
raise UserWarning(503)
else: mail_from(x, ... |
def send_error(self, id, client, msg):
"""send error to the client"""
self.send_respond(id, client, status="error", msg=msg)
def get_providers(self, name):
"""list of client information of the providers of filename"""
now = time.time()
file_prov = []
providers = list(self... | The function handles a query request by checking if a file exists in the database. If it does, it sends the file's size, secret, and number of parts to the client, followed by providers in 30-item chunks. If the file is not found, it sends an error. The process logs warnings or info based on success or failure. | def _handle_query(self, client, **kwargs):
"""handle query request
Protocol: if filename exists tracker sends information about the file
to the peer first including:
- size
- secret
- parts
and then it will send providers in 30-provider chunks.
... |
def add_provider(self, id: int, client, file: TorFile, checksum=None):
"""Adds peer with id to filename providers
If checksum is not None it will check checksum and if not matches will
send an error to the client."""
if checksum:
file = self.file_db[file.name]
i... | The code handles file sharing requests by either registering a new file's checksum and size or verifying checksum matches for existing files. It adds a provider to the file if shared for the first time or updates the provider list if the file already exists, ensuring data consistency. If the file is new but lacks size,... | def _handle_share(self, client, **kwargs):
"""handle share request
Protocol:
1. If the file is shared for the first time the checksum and size is
registered in the system.
2. If file is shared before checksums must match to add the id to
files provi... |
def add_provider(self, id: int, client, file: TorFile, checksum=None):
"""Adds peer with id to filename providers
If checksum is not None it will check checksum and if not matches will
send an error to the client."""
if checksum:
file = self.file_db[file.name]
i... | The function verifies a downloaded file's checksum and adds it to the database if valid. It retrieves the file's ID, name, and checksum from arguments, checks if the file exists in the database, and either adds the provider with the file or sends an error for non-existent files, logging respective success or warning me... | def _handle_downloaded(self, client, **kwargs):
"""add a client to the DB if it has correct checksum"""
id = kwargs['id']
filename = kwargs['filename']
checksum = kwargs['checksum']
file = self.file_db.get(filename, None)
if file:
self.add_provider(id, client,... |
def fixPicks(picks:list):
newFormat = []
for p, pick in enumerate(picks):
newFormat.append([p+1, pick])
return newFormat
def combinePicks(picks:list):
powerset = powerSet(picks)
listSet = []
for sSet in powerset:
listSet.append(list(sSet))
return listSet
def filterCombination... | The code generates valid pick combinations to open locks by fixing, combining, filtering, and validating Cartesian products of picks against locks, returning all successful solutions. | def solve(locks:list, picks:list):
picks = fixPicks(picks)
combinedPicks = combinePicks(picks)
validCombs = filterCombinations(combinedPicks, locks)
cartesian = cartesianProduct(validCombs)
filtered = filterCartesian(cartesian, locks)
validProducts = checkProduct(filtered, locks)
return vali... |
def getSplitList(str):
str = [x.strip().split(" ") for x in str]
str = [[int(x) for x in y] for y in str]
return str
def valueIteration(mdp):
i=0
V=mdp.state
print("Iteration :",i)
printGrid(V)
while True:
i+=1
# compute the new values (newV) given the old values... | The code reads an MDP configuration from a file, parses parameters like grid size, walls, terminal states, rewards, and transition probabilities, then uses these to create an MDP object. It executes value iteration and policy iteration algorithms to compute optimal policies, printing the results for comparison. | def main():
# reads mdp_input.txt file and stores the values
with open("mdp_input.txt") as fp:
Lines = fp.readlines()
for line in Lines:
print(line)
if(line[0]!='#' and line[0]!='\r' and line[0]!='\n'):
print(line)
valType=line.split(':')[... |
def PluralityValue(examples):
x=examples.groupby(['Result'], sort=False).size().reset_index(name='Count')
max=0
for i in range(0,len(x)-1):
if(x['Count'][i]<x['Count'][i+1]):
max=i+1
else:
max=i
return x['Result'][max]
def sameClassification(examples):
v=examp... | This code constructs a decision tree by recursively selecting the most important attribute to split the dataset, creating nodes for each attribute-value pair, and building subtrees until base cases (empty examples, uniform classification, or no attributes left) are met. The tree is represented with nodes storing attrib... | def DecisionTreeLearning(examples, attribute, parent_examples,depth):
if(examples.empty):
return PluralityValue(parent_examples)
elif(sameClassification(examples)):
return examples['Result'][0]
elif(not attribute):
return PluralityValue(examples)
else:
# A = max((Importan... |
def DecisionTreeLearning(examples, attribute, parent_examples,depth):
if(examples.empty):
return PluralityValue(parent_examples)
elif(sameClassification(examples)):
return examples['Result'][0]
elif(not attribute):
return PluralityValue(examples)
else:
# A = max((Importan... | The code builds a decision tree from a dataset in 'data.csv', trains it using the DecisionTreeLearning algorithm, prints the tree, then prunes it via statistical significance testing and prints the pruned version. It uses pandas for data loading and processes features/columns to generate and refine the decision tree mo... | def main():
global allExamples
a = pd.read_csv('data.csv', names=colnames,skipinitialspace=True)
allExamples=a
colnames.remove('Result')
x=DecisionTreeLearning(a,colnames,a,0)
print("############### Decision Tree ############")
printTree(0,x)
print("\n\n############### Pruned Decision T... |
def prob_mask_like(t, prob):
return torch.zeros_like(t).float().uniform_(0, 1) < prob
def mask_with_tokens(t, token_ids):
init_no_mask = torch.full_like(t, False, dtype=torch.bool)
mask = reduce(lambda acc, el: acc | (t == el), token_ids, init_no_mask)
return mask
def get_mask_subset_with_prob(mask, pro... | The code implements a masked language modeling (MLM) and discriminator training process. It masks input tokens with probability `mask_prob`, replacing some with a mask token or random tokens. The generator predicts masked tokens (MLM loss), while the discriminator distinguishes between original and replaced tokens (bin... | def forward(self, input, **kwargs):
b, t = input.shape
replace_prob = prob_mask_like(input, self.replace_prob)
# do not mask [pad] tokens, or any other tokens in the tokens designated to be excluded ([cls], [sep])
# also do not include these special tokens in the tokens chosen at rando... |
def enforce_max_one_obj_per_pos(self):
"""Exactly one object per position."""
for row in range(self.rows):
for col in range(self.columns):
options = [self.pos[row, col, obj.id] for obj in self.objects]
self.model.Add(sum(options) <= 1)
def enforce_obj_size(sel... | The code evaluates four rules to validate object properties: enforcing a maximum of one object per position, ensuring objects meet size requirements, maintaining object coherence (non-fragmentation), and verifying object linkages. Each rule is applied sequentially through corresponding enforcement methods. | def evaluate_all_rules(self):
### RULE 0 ###
# Every must have maximum one obj
self.enforce_max_one_obj_per_pos()
### RULE 1 ###
# Objects must have a certain size
self.enforce_obj_size()
### RULE 2 ###
# Objects must not be fragmented but one whole
... |
def determine_size(self):
amount_of_positions = 0
for obj in self.objects:
amount_of_positions+=obj.size*2 #Make the field double the object sizes
# amount_of_positions = (len(self.objects)-1)*3 #-1 because link is also considered an "object" #TODO 12 should be used
columns =... | This code initializes a constraint programming model to solve a planning problem using Google OR-Tools. It sets up variables for object positions, defines boolean and integer variables for cost tracking, evaluates constraints/rules, and solves the model to determine an optimal plan. The core task involves configuring a... | def __init__(self, objects):
# Initialisation
self.objects = objects
self.columns, self.rows = self.determine_size()
# Store model
self.model = cp_model.CpModel()
self.pos = self.set_up_model()
self.obj_bool_vars = [] # Keeps track of the cost of if certain eval... |
def getDataLoaders(dataset, fold, embeddor, output_length=25):
train_ids, test_ids = fold
train_torch_dataset = TextDataset(
texts=dataset.iloc[train_ids]['tokens'].reset_index(drop=True),
targets=dataset.iloc[train_ids]['labels'].reset_index(drop=True),
embeddor=embeddor,
outpu... | This function performs cross-validation (CV) over multiple epochs by training and evaluating a model on each fold of the dataset. It collects metrics like loss, precision, recall, AUC, and F1 score for each epoch and fold, using optimal thresholds derived from precision-recall curves. The results are aggregated and ret... | def cv_epoch_stats(max_epoch_number, train_dataset, folds, embeddor, seq_len):
epoch_fold_losses = [[] for _ in range(max_epoch_number)]
epoch_fold_precision = [[] for _ in range(max_epoch_number)]
epoch_fold_recall = [[] for _ in range(max_epoch_number)]
epoch_fold_auc = [[] for _ in range(max_epoch_nu... |
def pausePlay(self):
songProcess = psutil.Process(self.SongID)
timerProcess = psutil.Process(self.TimeID)
if songProcess.status() == psutil.STATUS_SLEEPING:
"""
Halt the execution of play
"""
songProcess.suspend()
timerProcess.suspend(... | This code implements a music control menu that repeatedly prompts the user for commands to control playback (pause/play, loop song/playlist/AB section, seek, stop). It uses a loop that runs while `self.SongID` is not in a "zombie" state (likely a typo/error), toggling loop states via `loopflag` and invoking correspondi... | def menu(self):
while self.SongID != psutil.STATUS_ZOMBIE:
# self.__timer()
print("Enter command : ")
self.MusicControl = int(
input(" (1 : pause/play)\n (2 : loopSong)\n "
"(3 : loopPlaylist)\n (4 : loopAB)\n "
... |
def log(self, *args, **kwds):
if self.verbose:
print(*args, **kwds)
def _entry(self, version, messages):
today = date.today().strftime('%y/%m/%d')
title = 'v%s - %s' % (version, today)
if self.changelog and self.changelog.suffix == '.rst':
self.log_print(title)
... | This method creates a new changelog file at a specified path, checks if it already exists (raising an error if so), logs the creation, writes an initial entry with the version and a message, and updates the instance's changelog attribute to the newly created file path. | def new(self):
changelog = Path(self.changelog or self.root / NAMES[0])
if changelog.exists():
raise ValueError('File %s already exists' % changelog.absolute())
self.log(f'Creating {changelog}:')
with self.printer(changelog) as self._print:
self._entry(self.versi... |
def get_thermal_sensor(self):
temp = SensorStatus.NOREADING
if (self.config['thermal'] >= SensorStatus.DISABLED):
return temp
bp = self.BP
if not self.thread_running:
self.update_thermal_sensor() #run a single read of the thermal sensor
#thread is run... | The main task of the code is to configure sensors and motors by assigning ports, initializing sensor types, handling exceptions, and starting threads for thermal sensors. It sets up thermal, color, ultrasonic, and IMU sensors, checks their availability, applies configuration settings, and limits motor power/speed, mark... | def configure_sensors(self, motorports, sensorports):
bp = self.BP
self.thread_running = False #end thread if its still running
self.rightmotor = motorports['rightmotor']
self.leftmotor = motorports['leftmotor']
self.largemotors = motorports['rightmotor'] + motorports['leftmotor'... |
def get_battery(self):
return self.BP.get_voltage_battery()
def get_colour_sensor(self):
if self.config['colour'] >= SensorStatus.DISABLED:
return "NOREADING"
bp = self.BP
value = 0
colours = ["NOREADING", "Black", "Blue", "Green", "Yellow", "Red", "White", "Brown"]
... | The main task of the code is to aggregate data from various sensors into a dictionary. It initializes an empty dictionary, populates it with sensor values by calling specific methods for battery, color, ultrasonic, thermal, and IMU-related sensors, then returns the compiled dictionary containing all sensor data for cen... | def get_all_sensors(self):
sensordict = {} #create a dictionary for the sensors
sensordict['battery'] = self.get_battery()
sensordict['colour'] = self.get_colour_sensor()
sensordict['ultrasonic'] = self.get_ultra_sensor()
sensordict['thermal'] = self.get_thermal_sensor()
... |
def reSetup(self):
self.paths = []
self.qty = 0
self.new_table = self.table
self.supply = self.ref_supply
self.demande = self.ref_demande
self.costs = self.ref_costs
def debug(self, *args, **kwargs):
if self.use_debug:
print(*args, **kwargs)
def findCe... | The main task of the code is to solve a transportation problem using a specified method (e.g., Vogel's or Northwest Corner). It iteratively identifies cells to adjust, calculates quantities, updates the transportation table, and tracks variables until the table is reduced to a 2x2 form or supply/demand balances reach z... | def solve(self, method):
# find which row, column to delete
self.reSetup()
self.method = method
self.debug("[BUILDING SOLUTION]")
progress = "*"
while self.new_table.shape != (2, 2) and np.sum(self.demande) != 0 and np.sum(self.supply) != 0:
self.findCell()
... |
def is_extra_parameter(arg):
# Checking the correctness of the extra parameter
if arg in ("-u","--underline"):
return "underline"
elif arg in ("-c", "--color"):
return "color"
elif arg in ("-m","--machine"):
return "machine"
else:
#print("The extra parameter is inval... | The function parses command-line arguments for a regex-based file processing tool, validating input format, handling file lists, and extra parameters. It checks argument count, pattern validity, and processes files or text based on flags like -r, --regex, and -f, --files, executing appropriate actions like regex matchi... | def parse_input(argumentList):
''' The function parsing the input arguments '''
if len(argumentList) < 3:
print("Incorrect input - Not enough arguments")
elif len(argumentList[1]) is 0:
print("The pattern is too short")
else:
if not argumentList[0] in ("-r", "--regex"):
... |
def sortByUserButton(self):
self.userButton = tkinter.Button(
self,
text = "Sort by User",
width = 12,
height = 2
)
self.userButton.place(
x = 25,
y = 40
)
self.userButton['command'] = lambda: self.selectUser... | The code initializes a GUI frame with a Listbox for data selection, Scrollbar, and multiple buttons (sort by user, lock, time, and back to menu) to manage and navigate data sorting options in a tkinter application. | def __init__(self, master):
tkinter.Frame.__init__(
self,
master,
height = 300,
width = 500
)
self.master = master
self.dataSelect = tkinter.Listbox(self)
self.confirmSelectButton = tkinter.Button(self)
self.dataSelectScroll... |
def logListingsUser(self):
self.logTable = tkinter.ttk.Treeview(
self,
height = 6,
selectmode = 'none'
)
self.logTable.place(
x = 55,
y = 50
)
self.logTable['columns'] = (
'id',
'date',
... | The code initializes a Tkinter GUI frame with specific dimensions, assigns log data from the master widget, and dynamically selects which log listing method to execute based on the master's logFlag value (user, lock, or date). It then creates buttons for exporting data and navigating back to access logs, setting up the... | def __init__(self, master):
tkinter.Frame.__init__(
self,
master,
height = 300,
width = 500
)
self.master = master
self.selectData = self.master.logSelectData
self.exportFileName = tkinter.StringVar()
if self.master.logFlag... |
def userSelection(self):
if self.master.deleteFlag == 1:
self.userLabel = tkinter.Label(
self,
text = "Select User to Delete",
font = ('Helvetica', 14)
)
else:
self.userLabel = tkinter.Label(
self,
... | This code initializes a Tkinter GUI frame with a user selection interface, setting up a StringVar to store user input, and configuring methods for selection options, a submission button, and a menu navigation button. The frame is sized to 500x300 pixels, and the master window is referenced for integration. | def __init__(self, master):
tkinter.Frame.__init__(
self,
master,
height = 300,
width = 500
)
self.master = master
self.userFullName = tkinter.StringVar()
self.userSelection()
self.selectionButton()
self.backToMenuB... |
def check_lora_region(region):
if region in LORA_REGIONS:
return True
else:
return False
def check_partition(partition):
if PARTITIONS.get(partition) is None:
return False
else:
return True
def print_exception(e):
if DEBUG:
try:
if sys.version_info... | This code defines a function to parse and validate command-line arguments for a Pycom firmware update tool. It handles options like verbosity, device settings, and subcommands for operations such as flashing firmware, reading/writing partitions, configuring WiFi/Sigfox, and managing storage. The function ensures proper... | def process_arguments():
cmd_parser = argparse.ArgumentParser(description='Update your Pycom device with the specified firmware image file\n\nFor more details please see https://docs.pycom.io/chapter/advance/cli.html')
cmd_parser.add_argument('-v', '--verbose', action='store_true', help='show verbose output fro... |
def print_debug(msg):
if DEBUG:
eprint(msg)
def mask_bits_in_memory(self, addr, mask):
self.magic_write(addr, _and=mask)
def reset_pycom_module(self):
# make RC5 an output
self.mask_bits_in_memory(TRISC_ADDR, ~(1 << 5))
# drive RC5 low
self.mask_bits_in_memory(PORTC_A... | This function configures specific microcontroller pins (RA5 and RC0) as outputs and sets them low to prepare the device for programming mode. It optionally performs a reset to ensure the PyCom module enters the correct state for firmware updates, with RC0 kept low to handle potential manual resets during the process. | def enter_pycom_programming_mode(self, reset=True):
print_debug("Entering programming mode with reset={}".format(reset))
# make RA5 an output
self.mask_bits_in_memory(TRISA_ADDR, ~(1 << 5))
# drive RA5 low
self.mask_bits_in_memory(PORTA_ADDR, ~(1 << 5))
# make RC0 an outp... |
def print_debug(msg):
if DEBUG:
eprint(msg)
def mask_bits_in_memory(self, addr, mask):
self.magic_write(addr, _and=mask)
def set_bits_in_memory(self, addr, bits):
self.magic_write(addr, _or=bits)
def reset_pycom_module(self):
# make RC5 an output
self.mask_bits_in_memory(TRIS... | The function exits programming mode by configuring hardware pins (RA5 as output, RC0 as input) to ensure safe operation, optionally resets the PyCom module, and flushes changes. | def exit_pycom_programming_mode(self, reset=True):
print_debug("Leaving programming mode with reset={}".format(reset))
# make RA5 an output
self.mask_bits_in_memory(TRISA_ADDR, ~(1 << 5))
# drive RA5 high
self.set_bits_in_memory(PORTA_ADDR, 1 << 5)
# make RC0 an input
... |
def set_baudrate(self, read=False):
if self.__current_baudrate != self.get_baudrate(read):
try:
self.__current_baudrate = self.get_baudrate(read)
self.esp.change_baud(self.__current_baudrate, self.__resultUpdateList)
except Exception as e:
... | This code writes data to a specified flash memory offset on an ESP device using esptool, handling flash size detection, compression, error retries, and progress tracking. It prepares arguments, validates content size against flash capacity, and executes the write operation with up to three retry attempts, raising error... | def write(self, offset, contents, compress=True, flash_size='detect', std_out=None, ui_label=None, file_name=None, updateList=True, progress_fs=None):
if progress_fs is not None:
self.__progress_fs = progress_fs
args = Args()
args.flash_size = self.__flash_size if flash_size == 'dete... |
def process_arguments():
cmd_parser = argparse.ArgumentParser(description='Update your Pycom device with the specified firmware image file\n\nFor more details please see https://docs.pycom.io/chapter/advance/cli.html')
cmd_parser.add_argument('-v', '--verbose', action='store_true', help='show verbose output fro... | The main task of the code is to program and manage a microcontroller's flash memory and configurations via various commands like flashing firmware, erasing memory, reading/writing partitions, and configuring Wi-Fi/Sigfox settings. It uses a programmer object to handle low-level operations, supports FTDI/PIC modes, proc... | def main():
try:
args = process_arguments()
if args.command == 'list':
list_usbid()
sys.exit(0)
if sys.version_info[0] < 3:
new_stream = BytesIO()
else:
new_stream = StringIO()
old_stdout = sys.stdout
if (args.ftdi):
... |
def print_debug(msg, show=DEBUG):
if show:
eprint(msg)
def int_flash_size(self):
args = Args()
args.flash_size = self.__flash_size
args.flash_mode = FLASH_MODE
args.flash_freq = FLASH_FREQ
args.compress = True
args.verify = False
args.no_stub = False
... | The code erases flash storage (FS) partitions on a device, handling both 8MB and 4MB flash sizes. It divides the 8MB partition into eight sections for erasure, while the 4MB partition is erased as a single block. The function logs the operation's duration and size using time tracking and human-readable formatting, upda... | def erase_fs(self, chip_id=None, ui_label=None, progress_fs=None):
self.__progress_fs = progress_fs
start_time = time.time()
print_debug('self.int_flash_size() = {}'.format(self.int_flash_size()))
print_debug('chip_id = {}'.format(chip_id))
if self.int_flash_size() == 0x800000:
... |
def write(self, offset, contents, compress=True, flash_size='detect', std_out=None, ui_label=None, file_name=None, updateList=True, progress_fs=None):
if progress_fs is not None:
self.__progress_fs = progress_fs
args = Args()
args.flash_size = self.__flash_size if flash_size == 'dete... | This function writes data to flash memory while ensuring it adheres to partition size limits and avoids overwriting the config block. It truncates content if necessary, handles flash parameters, detects flash size, checks for overlaps with the config block, and writes data with padding or modifications to protect the c... | def write_script(self, offset, contents, config_block, overwrite=False, size=None, ui_label=None, file_name=None):
if overwrite or size is None:
self.write(offset, contents, ui_label=ui_label, file_name=file_name)
else:
if (len(contents) > size):
print_debug("Trun... |
def print_debug(msg, show=DEBUG):
if show:
eprint(msg)
def erase_all(self, ui_label=None):
args = Args()
args.flash_size = self.__flash_size
args.flash_mode = FLASH_MODE
args.flash_freq = FLASH_FREQ
args.compress = True
args.verify = False
args.no_stub... | This function executes a script to perform flash memory operations on a device, including erasing and writing data to specific partitions. It processes instructions to handle erase commands for 'fs', 'nvs', or 'all' partitions, writes data based on 'w'/'o' commands, and manages OTA updates. It validates script commands... | def run_script(self, script, config_block=None, erase_fs=False, chip_id=None, ui_label=None, progress_fs=None, erase_nvs=False):
self.__progress_fs = progress_fs
if script is None:
raise ValueError('Invalid or no script file in firmware package!')
if DEBUG:
for instructio... |
def do_episodes(self, number=1, is_learning=True):
all_rewards = []
for _ in range(number):
reward = self._do_episode(is_learning=is_learning)
all_rewards.append(reward)
self.score_agent_window = self._update_window(self.score_agent_window, self.score_agent)
... | This function trains a reinforcement learning agent over multiple epochs, collecting training loss and evaluating performance. It runs episodes_per_epoch per epoch, logs metrics like scores, steps, and epsilon, and saves model weights periodically. For online learning, it tests on diverse initial states; for offline, i... | def do_epochs(self, number=1, episodes_per_epoch=10000, is_learning=True, is_testing=True, episodes_per_test=10000):
for epoch in range(self.curr_epoch, number):
episodes = 0
loss_window = []
while episodes < episodes_per_epoch:
losses = self.do_episodes(numbe... |
def check_data(self, filename):
data = mediainfo(filename).get('TAG',None)
return self.clean_response(data)
def get_data(self, filename):
if not self.ActivateShazam:
return self.clean_response(self.fake_response(filename))
else:
return self.clean_response(self.sha... | The main task of the code is to retrieve or check metadata for a given file. If metadata already exists, it returns it immediately. If not, it attempts to retrieve the data, and if successfully obtained, saves the metadata to the file before returning it. The function ensures metadata availability by either reusing exi... | def __call__(self, filename):
data = self.check_data(filename) # We check if metadata are already present
if data[FILLED]:
print(f"Metadata already exists for file {filename}")
return data # If so, we send it immediately
else:
data = self.ge... |
def phase1(piece):
#So that the player can change their mind on what piece they want
phase0()
#text that will show regardless of piece
squareSelect = Text("freesansbold.ttf",32,(0,0,0),"Then, select the starting square on the board.")
screen.blit(squareSelect.rendered,(850,660))
instruc = T... | Your return
The code executes Phase 2 of a game or simulation, displaying a game piece on the board, rendering a "READY!" button with instructions, and highlighting all viable moves of the piece by coloring their corresponding squares green. It builds on Phase 1's setup, prepares the UI for user interaction, and visu... | def phase2(piece):
#we still want to see the description
phase1(piece)
#we see the piece on a square in the board
displayPiece(piece)
#blue ready button and ready text
screen.fill((0,0,255),(1000,400,210,50))
ready = Text("freesansbold.ttf",50,(255,255,255),"READY!")
screen.bli... |
def init_queries(db):
"""
For sqlite3. A parallel routine will be needed if we add Mariadb support.
Create the db if needed, and create a connection to it.
:param db: The name of the database
:return: None
"""
# Mark these names as referring to the global variables. A python routine
# ... | The main task of the code is to execute three phases: initializing a database with 'ws2000' queries, creating a table structure, and processing a backup file. The function orchestrates these steps sequentially without returning any value. | def main():
"""
Drives the three phases of the program. Create and initialize the database,
create our table in it, and process the backup file.
:return: None
"""
init_queries('ws2000')
create_table()
process_file() |
def env_bind(key, value, env):
return (key, value, env)
def env_new():
return ()
def var_new(id):
return ('Var', id)
def var_eval(var, env):
(_, id) = var
print(">>>> var_eval id =", id, "value =", env_lookup(env, id))
return (env_lookup(env, id), env) | This code tests if evaluating a variable in an environment retrieves the correct value without modifying the environment. It creates an environment with x=100 and y=200, evaluates the variable 'y', and asserts that the result is 200 while the environment remains unchanged. | def var_test():
env1 = env_bind('x', 100, env_bind('y', 200, env_new()))
var1 = var_new('y')
(val, env2) = var_eval(var1, env1)
assert env1 == env2
assert val == 200 |
def env_new():
return ()
def let_new(id, rhs):
return ('Let', id, rhs)
def let_eval(let, env):
(_, id, rhs) = let
(rhsVal, env1) = evaluate(rhs, env)
env2 = env_bind(id, rhsVal, env1)
return (None, env2)
def env_bind(key, value, env):
return (key, value, env) | The code tests the evaluation of a 'let' binding in an environment. It creates a new environment, binds 'x' to 100, evaluates the binding, and verifies that the result is None while ensuring the updated environment correctly contains the binding 'x=100'. The assertions check both the return value and environment state ... | def let_test():
env1 = env_new()
let1 = let_new('x', 100)
(val, env2) = let_eval(let1, env1)
assert None == val
assert env_bind('x', 100, env_new()) == env2 |
def env_new():
return ()
def if_new(cond, conseq, alt):
return ('If', cond, conseq, alt)
def if_eval(ifExpr, env):
(_, cond, conseq, alt) = ifExpr
(condVal, env1) = evaluate(cond, env)
if condVal:
return evaluate(conseq, env1)
return evaluate(alt, env1) | This code tests the evaluation of an if-expression. It creates an environment, evaluates an if-statement with condition True and values 100/200, then verifies the result is 100 and the new environment matches a fresh environment, confirming correct evaluation without unintended side effects. | def if_test():
env1 = env_new()
if1 = if_new(True, 100, 200)
(val, env2) = if_eval(if1, env1)
print(val, env2)
assert 100 == val
assert env_new() == env2 |
def env_new():
return ()
def seq_new(exprs):
return ('Seq', exprs)
def let_new(id, rhs):
return ('Let', id, rhs)
def seq_eval(seqExpr, env):
(_, exprs) = seqExpr
res = None
for expr in exprs:
(res, env) = evaluate(expr, env)
return (res, env)
def env_bind(key, value, env):
return (key, value, env) | The code tests the evaluation of a sequence of variable bindings in an environment. It creates a sequence with two let bindings (x=100, y=200), evaluates it in a new environment, and verifies that the result is None while the updated environment correctly contains both bindings with their assigned values. | def seq_test():
env1 = env_new()
seq1 = seq_new((let_new('x', 100),
let_new('y', 200)))
(res, env2) = seq_eval(seq1, env1)
assert None == res
assert env_bind('y', 200, env_bind('x', 100, env_new())) == env2 |
def env_new():
return ()
def fun_new(param, body):
return ('Fun', param, body)
def if_new(cond, conseq, alt):
return ('If', cond, conseq, alt)
def var_new(id):
return ('Var', id)
def app_new(abstr, arg):
return ('App', abstr, arg)
def app_eval(app, env):
(_, abstr, arg) = app
(abstrVal, env1) = evalua... | The code tests a conditional function's behavior by evaluating two applications with different boolean arguments. It creates a function `fun1` that returns 100 or 200 based on the truth value of its parameter `x`. The test asserts that applying `fun1` with `True` yields (100, ()) and with `False` yields (200, ()), veri... | def app_test():
env0 = env_new()
fun1 = fun_new('x', if_new(var_new('x'), 100, 200))
app1 = app_new(fun1, True)
res = app_eval(app1, env0)
assert (100, ()) == res
app2 = app_new(fun1, False)
res = app_eval(app2, env0)
assert (200, ()) == res |
def predict_general_dominance(self):
general_dominance=[]
l=list(self.dominance_stats().index)
for index,i in enumerate(l):
general_dominance.append({"Predictors":i,"Dominating":l[index+1:]})
return pd.DataFrame(general_dominance)[['Predictors','Dominating']]
def predict_conditional_dominance(self):
... | The main task of the code is to combine three dominance prediction results (general, conditional, and complete) into a unified DataFrame. It renames columns for clarity, merges them on 'Predictors' using left joins, and fills missing values with empty strings to produce a consolidated dominance analysis table. | def dominance_level(self):
gen_dom=self.predict_general_dominance()
condition_dom=self.predict_conditional_dominance()
comp_dom=self.predict_complete_dominance()
gen_dom.rename(columns={'Dominating':'Generally Dominating'},inplace=True)
condition_dom.drop('Conditional Dominance',inplace=True,axis=1)
condit... |
def valid_signatures(self, qc, tc):
validity = True
#dont check for genesis validity
if qc is None or tc is None or qc.vote_info.round == -1 or tc.round == -1:
return validity
#Validate signature of qc author
validity = validity and self.verify_msg_signature(qc.autho... | The main task of the code is to generate a vote message (`VoteMsg`) when conditions are met, including validating signatures, ensuring safety to vote, updating QC/vote rounds, and structuring the vote with `VoteInfo`, `LedgerCommitInfo`, and a cryptographic signature. It returns the vote message if valid, otherwise `No... | def make_vote(self, b, last_tc):
qc_round = b.qc.vote_info.round if b.qc else -1
if b is not None and self.valid_signatures(b.qc, last_tc) and self.__safe_to_vote(b.round, qc_round, last_tc):
self.__update_highest_qc_round(qc_round) # Protect qc round
self.__increase_highest_vot... |
def load_video(self, file):
# Open the video file
self.video_capture = cv2.VideoCapture(file)
self.video_capture_preview = cv2.VideoCapture(file)
# Create a variable to store the current frame of the video
self.current_frame, self.current_timestamp = 0, 0
# Create a var... | This code initializes a video player GUI with features like video display, timeline control, preview, and play/pause functionality, setting up the interface and video processing components for a specified MP4 file. | def __init__(self, root, folder, file_name='cheeky-cornflower-setter-01b256a7cfb9-20220717-131452.mp4'):
root.geometry("1500x900")
self.folder = folder
self.current_file = folder + file_name
self.load_video(self.current_file)
width = self.video_capture.get(cv2.CAP_PROP_FRAME_WI... |
def get_field_type(typ: Instance, primitive: bool = False) -> Type:
if primitive:
return typ.args[1]
else:
return typ.args[0]
def get_drf_metadata(info: TypeInfo) -> Dict[str, Any]:
return info.metadata.setdefault('drf', {})
def is_autogenerated_primary_key(sym: SymbolTableNode) -> bool:
... | This function generates a TypedDict type representing the fields of a Django REST Framework serializer. It processes the serializer's MRO to collect field types, handles model fields from the base model, and uses fallback types for unresolved references. The result is a TypedDict with required keys and a dict fallback ... | def get_corresponding_typeddict(serializer_type: Instance,
api: CheckerPluginInterface,
use_primitive_types: bool = False) -> Type:
typeddict_items = OrderedDict() # type: OrderedDict[str, Type]
for base in serializer_type.type.mro:
for na... |
def _add_head(self) -> None:
"""Add an empty list head for self."""
new_tree = CompressedPrefixTree(self.weight_type)
new_tree.value = self.value
new_tree._leaf_sum = self._leaf_sum
new_tree._leaf_count = self._leaf_count
new_tree.weight = self.weight
new_tree.sub... | (The code inserts a value into a CompressedPrefixTree with a specified weight and prefix. If the value already exists in the tree, it adds the given weight to the existing entry. The method ensures the value is associated with the provided prefix sequence and adheres to preconditions that the weight is positive and the... | def insert(self, value: Any, weight: float, prefix: List) -> None:
"""Insert the given value into this CompressedPrefixTree.
The value is inserted with the given weight, and is associated with
the prefix sequence <prefix>.
If the value has already been inserted into this prefix tree
... |
def _add_head(self) -> None:
"""Add an empty list head for self."""
new_tree = CompressedPrefixTree(self.weight_type)
new_tree.value = self.value
new_tree._leaf_sum = self._leaf_sum
new_tree._leaf_count = self._leaf_count
new_tree.weight = self.weight
new_tree.sub... | The code's main task is to generate autocomplete suggestions by returning up to `limit` matches for a given `prefix`, ordered by non-increasing `weight`. It temporarily adds a "head" node to the structure, invokes the `_autocomplete` method to retrieve matches, then removes the head. The result is a list of `(value, we... | def autocomplete(self, prefix: List,
limit: Optional[int] = None) -> List[Tuple[Any, float]]:
"""Return up to <limit> matches for the given prefix.
The return value is a list of tuples (value, weight), and must be
ordered in non-increasing weight. (You can decide how to bre... |
def _add_head(self) -> None:
"""Add an empty list head for self."""
new_tree = CompressedPrefixTree(self.weight_type)
new_tree.value = self.value
new_tree._leaf_sum = self._leaf_sum
new_tree._leaf_count = self._leaf_count
new_tree.weight = self.weight
new_tree.sub... | This method removes all values in the structure that match the given prefix by first adding a head marker, then removing elements matching the prefix, and finally removing the head marker to maintain structure integrity. | def remove(self, prefix: List) -> None:
"""Remove all values that match the given prefix.
"""
if self.value != []:
self._add_head()
self._remove(prefix)
self._remove_head() |
def _get_soup(url=None, html=None, request_args=None):
if html:
return BeautifulSoup(html, 'lxml')
request_args = request_args if request_args else {}
headers = dict(GeneratedAutoScraper.request_headers)
if url:
headers['Host'] = urlparse(url).netloc
heade... | The main task of the code is to parse HTML content (via `url` or provided `html`) into a soup object, then extract and return two types of results: `similar` and `exact` values derived from the parsed data. The function delegates parsing to `_get_soup` and uses `get_result_similar`/`get_result_exact` to process the sou... | def get_result(self, url=None, html=None, request_args=None):
soup = self._get_soup(url=url, html=html, request_args=request_args)
similar = self.get_result_similar(soup=soup)
exact = self.get_result_exact(soup=soup)
return similar, exact |
def _get_soup(url=None, html=None, request_args=None):
if html:
return BeautifulSoup(html, 'lxml')
request_args = request_args if request_args else {}
headers = dict(AutoScraper.request_headers)
if url:
headers['Host'] = urlparse(url).netloc
headers = requ... | The main task of the code is to parse HTML content (via `soup`), extract specific elements (`wanted_list`), collect and deduplicate results (`result_list`), and validate them. If valid, it returns the unique results and tracks their hierarchical paths (`stack_list`). If invalid, it returns `None`. | def build(self, url=None, wanted_list=None, html=None, request_args=None):
self.url = url
soup = self._get_soup(url=url, html=html, request_args=request_args)
result_list = []
stack_list = []
for wanted in wanted_list:
children = self._get_children(soup, wanted)
... |
def _get_soup(url=None, html=None, request_args=None):
if html:
return BeautifulSoup(html, 'lxml')
request_args = request_args if request_args else {}
headers = dict(AutoScraper.request_headers)
if url:
headers['Host'] = urlparse(url).netloc
headers = requ... | The main task of the code is to parse HTML content (via `url`, `html`, or `request_args`) using BeautifulSoup, then extract two types of results: "similar" and "exact" data from the parsed HTML. It returns these results as a tuple, enabling the retrieval of both precise matches and related/approximate data from web pag... | def get_result(self, url=None, html=None, request_args=None):
soup = self._get_soup(url=url, html=html, request_args=request_args)
similar = self.get_result_similar(soup=soup)
exact = self.get_result_exact(soup=soup)
return similar, exact |
def calculateProst(self,patient):
wpMask = os.path.join(patient[1], 'wp_bt.nii.gz') # path join patient path + mrn_with_date + wp_bt.nii.gz
[headers, prost_data] = self.calculateRadiomics(patient, "wp", wpMask)
return [headers, prost_data]
def getVOIlist(self, patient):
voi_list = []
... | The code processes patient data by calculating radiomics features for the prostate, segments, and lesions. It reads a CSV file containing patient MRNs and file paths, iterates through each patient, computes features using helper methods, and appends results to a new CSV file. The first patient's data includes headers f... | def calculate(self):
#errors = []
#voi_list = []
"""
## INITIALIZE NEW CSV FILE ##
# Note: Single row of info needs to be in double brackets or each character will get its own cell
headers = [['MRN', '']]
# open csv file in 'a+' mode to append
file = open... |
def train_model(self,
model, loss_func, optim,
train_dataset, valid_dataset,
save_best_metric="UA", save_after=10):
best_metric = -np.inf
for epoch in range(self.epochs):
if self.verbose:
print(f... | This function performs cross-validation by iterating over specified folds, training a model on each training set, evaluating it on the test set, and saving results. It generates a timestamped filename, prepares datasets, initializes model/optimizer, trains, tests, logs outcomes, and stores experiment data for analysis. | def make_cross_validation_experiment_one_out(self, dataset, folds, experiment_note):
# file corresponding to the experiment
file_name = datetime.datetime.now().strftime("%c").replace(" ", "_").replace(":", "-")
for fold in folds:
# preparing the dataset
tra... |
def show_token(self, index: int):
print(colored(self.tokens.tokens[index].token, "green"))
def show_mem(self):
pprint(self.vars_in_mem)
def parse_item(self):
token = self.tokens.get().token
# Starts with print
if token == TokenType.PRINT:
self.parse_print()
... | This code parses a sequence of tokens by iterating through them, with optional debugging output based on the execution mode. It displays tokens and memory states conditionally using mode checks, calls `parse_item()` for each token, and finalizes with a memory display if in DEBUG mode (excluding STEP_THROUGH_DEBUG). | def parse(self):
index = 0
while index < len(self.tokens.tokens):
if self.mode >= RunType.VERBOSE:
self.show_token(index)
if self.mode >= RunType.STEP_THROUGH_DEBUG:
self.show_mem()
self.parse_item()
index += 1
i... |
def unpack_data(data):
config = data['config']
nodes = data['nodes']
partitions = data['partitions']
return config,nodes,partitions
def parse_line_multi(line,keepers=None):
'''parse_line_multiple will return a dictionary with keys and
values for a line from a slurm conf, with variables expected ... | The function processes a block of configuration data to parse and update node settings in a global nodes dictionary. It extracts the 'NodeName' from the first line, checks if the node should be processed, aggregates subsequent lines into node settings, and updates the nodes dictionary with these settings, adding partit... | def parse_node_block(data):
'''line should be the first line popped that has 'NodeName'
and config is the entire config following that. The new node
entry is added to the global nodes.
'''
config, nodes, partitions = unpack_data(data)
line = parse_line_multi(config.pop(0))
if "NodeNa... |
def unpack_data(data):
config = data['config']
nodes = data['nodes']
partitions = data['partitions']
return config,nodes,partitions
def parse_line_multi(line,keepers=None):
'''parse_line_multiple will return a dictionary with keys and
values for a line from a slurm conf, with variables expected ... | This function parses a partition block from configuration data, extracts the partition name, processes node assignments, updates the nodes' partition lists, and adds the new partition to the global partitions dictionary. It handles multi-line entries with escaped continuation characters, updates partition attributes, a... | def parse_partition_block(data):
'''line should be the first line popped that has 'PartitionName'
and config is the entire config following that. The new partition
entry is added to the global partitions. The next line (non partition)
is returned.
'''
config, nodes, partitions = unpack_data(data... |
def read_file(file_name, clean=True, join=False):
'''read in a file, with optional "clean up" to remove
comments (lines starting with #) and empty lines)
'''
with open(file_name,'r') as filey:
content = filey.readlines()
if clean is True:
content = [c.strip('\n')
... | The main task of the code is to parse a configuration file into a structured dictionary containing machine details. It processes lines to extract cluster names, partitions, nodes, features, and defaults, organizing them under a "default" cluster. The function handles different blocks (e.g., PartitionName, NodeName) usi... | def parse_config(config_file):
'''parse a config file to return a complete list of machines
'''
machines = dict()
config = read_file(config_file)
data = {'partitions':{},
'nodes': {},
'config':config}
# If the configuration file doesn't have a cluster
cluster = "... |
def get_parser():
parser = argparse.ArgumentParser(
description="convert slurm.conf to machines.json")
parser.add_argument("--input", dest='input',
help='''one or more slurm config files, separated by commas.''',
type=str, default=None)
parser.add_argu... | The main task of the code is to parse Slurm configuration files, optionally exclude specified partitions, aggregate cluster data into a dictionary, and output the results as JSON or update an existing file, with checks for input validity, file existence, and overwrite permissions. | def main():
parser = get_parser()
try:
args = parser.parse_args()
except:
sys.exit(0)
# User must specify a slurm.conf
if args.input == None:
parser.print_help()
message('Please supply a slurm.conf with --input.', args.quiet)
sys.exit(1)
if os.path.exi... |
def _bind_keys(self):
self.bind('<Escape>', self._quit)
self.bind('q', self._quit)
self.bind('f', self._toggle_fullscreen)
def _toggle_fullscreen(self, event):
g = self.geometry()
self.geometry(self._geometry)
self._geometry = g
def plot_graph(self):
now = UTCDate... | This code initializes a Tkinter GUI application for visualizing seismic data using matplotlib. It sets up the window title, size, position, and fullscreen mode, creates a matplotlib figure canvas, and initializes attributes for data streams, events, and plotting parameters. The main task is to create an interactive sei... | def __init__(self, stream=None, events=None, myargs=None, lock=None,
trace_ids=None, *args, **kwargs):
tkinter.Tk.__init__(self, *args, **kwargs)
self.wm_title("seedlink-plotter {}".format(myargs.seedlink_server))
self.focus_set()
self._bind_keys()
args = myargs
... |
def mergeConfigs(config_dict, configs_path=''):
if not isinstance(config_dict, dict):
with open(os.path.join(configs_path, config_dict), 'r') as stream:
config_dict = yaml.safe_load(stream)
if 'base' in config_dict.keys():
base_config = mergeConfigs(config_dict.pop('base'), config... | The main task of the code is to merge a provided configuration dictionary with settings from a specified path, then update the merged configuration with loss and optimizer-specific parameters before returning the finalized configuration object. | def getConfig(config_dict, configs_path=''):
config = mergeConfigs(config_dict, configs_path)
updateLossConfig(config)
updateOptimizerConfig(config)
return config |
def find_candidate_edge_sets(final_overlap_graph: FinalDirectedGraph, original_len, vertices_list, vertex_to_index):
"""
:param vertex_to_index: A hash, for a given vertex find the index of it in the vertices list
:param vertices_list: A list of vertices indexed.
:param final_overlap_graph: A graph hold... | The function generates candidate edge sets with n-1 edges and at most one edge per vertex from a directed graph, filters them to valid paths, and converts these paths into string candidates representing potential original strings. It returns these strings or None if no candidates exist, handling edge cases with zero or... | def create_guesses(final_directed: FinalDirectedGraph, original_str_len):
global list_of_candidates
"""The function finds the candidate edge sets that have n-1 edges and at most one edge from each vertex,
and filters out any set that isn't a path between the vertices in final_directed graph :param final_di... |
def hit_test(self, px, py):
newheight = self.rect.height - self.head
pitchx = (self.rect.width) // 7;
pitchy = newheight // 6;
py2 = int(py) - self.head
#print("px", px, "pitchy", pitchy)
return int(px) // pitchx, py2 // pitchy
def get_daydat(self, ddd):
arr = []... | The code handles calendar menu actions: adding/editing entries (cnt=1/2), deleting entries (cnt=3), and editing days (cnt=4). It uses hit testing to identify calendar cells, manages a dialog for entry input, and confirms deletions before invalidating the display. | def menucb(self, txt, cnt):
#print (" txt cnt", txt, txt)
xxx = self.menu.event.x; yyy = self.menu.event.y
if cnt == 1:
#print("New entry")
if self.popped:
try: self.tt.destroy()
except: pass
self.popped = False
... |
def message_to_screen(msg,color,y_displace = 0 , size = "small"):
textSurf , textRect = text_objects(msg,color,size)
textRect.center = (display_width / 2) , (display_height / 2) + y_displace
gameDisplay.blit(textSurf,textRect)
def pause():
paused = True
while paused:
for event in pygame.even... | The main task of the code is to implement a game loop for a tank-based game, handling user input for tank movement and turret rotation, rendering game elements, managing game states (running/game over), and controlling the frame rate. It processes keyboard events to adjust tank position and turret angle, updates the di... | def gameLoop():
gameExit = False
gameOver = False
mainTankX = display_width * 0.9
mainTankY = display_height * 0.9
tankMove = 0
currentTurPos = 0
changeTur = 0
FPS = 20
while not gameExit:
while gameOver == True:
gameDisplay.fill(aquamarine)
m... |
def generate_feasible(self):
return np.random.uniform(self.lower, self.upper, self.dim)
def sort_population(self, population, energy, sigma):
sorted_ind = np.argsort(energy)
sorted_population = population[sorted_ind]
sorted_energy = energy[sorted_ind]
sorted_sigma = sigma[sorted_... | This code initializes an evolutionary optimization algorithm with parameters for population recombination, selection, and convergence checking. It sets up a parent population, configures strategy parameters (e.g., sigma, tau), and prepares for iterative optimization. The algorithm generates children, evaluates them, se... | def __init__(self,
func,
dim,
seed,
children_recomb='D',
sigma_recomb='I',
select='NE',
mu=20,
l_mul=7,
e=0.01,
omega=0.5,
limit=(-50... |
def choosingBias(df_to_Bias,Variables,E2_values=None):
global prime
dfBiasChosen=df_to_Bias.copy()
dfBiasChosen['VarBias']=""
for var in Variables:
dfBiasChosen['VarBias']=dfBiasChosen['VarBias']+var+dfBiasChosen[var].astype(str)
dfBiasChosen['VarBias']=dfBiasChosen['VarBias'].str.encod... | The main task of the code is to process datasets with varying bias combinations, evaluate model performance using stratified cross-validation (Qini, UpliftAt10, AUUC metrics), generate visualizations, and save results in CSV/log files. It iterates through variable combinations, applies biasing, runs evaluations, and ag... | def startProcess(data,B,Algorithm,ListOfCombinationOfVars,datasetName,X):
global var
global prime
path = "./"+dataPath+"_"+var+"_"+prime+"_"+AlgorithmName+"_Bias"+BiasGenre+"_DA"+domain_ada+"/"
if not os.path.exists(path):
os.mkdir(path)
print("Directory " , path , " Created ")
else... |
def create_sphere(radius, n_features=1000, trunc=False, method='xyz'):
#theta_phi = np.zeros((n_features,2))
theta_phi = []
alpha = 4.0*np.pi/n_features
d = np.sqrt(alpha)
m_theta = int(np.ceil(np.pi/d))
d_theta = np.pi/m_theta
d_phi = alpha/d_theta
count = 0
for m in range (0,m... | The function generates optimized points on a sphere's surface by first creating initial spherical coordinates, then optimizing their angular positions (ThetaPhi) using a specified method. It converts optimized angles to 3D Cartesian coordinates and optionally reports statistical metrics of point spacing before and afte... | def create_optimized_points(sphere_radius, n_features, verbose=False, method = 'local'):
original_ThetaPhi, original_points = create_sphere(sphere_radius, n_features, trunc = True)
optimized_ThetaPhi = optimize_ThetaPhi(original_ThetaPhi, sphere_radius, method = method)
optimized_points = ThetaPhi2xyz(optim... |
def parse_args():
"""
Parse the command line arguments.
:return: The parsed args.
"""
parser = argparse.ArgumentParser()
parser.add_argument('fasta', help='File path with list of sequences (e.g. seqs_ATTA.fasta)')
parser.add_argument('seed', help='Guess for the motif (e.g. ATTA)')
parser... | The main task of the code is to train a Hidden Markov Model (HMM) using the Baum-Welch algorithm on DNA sequences to identify motifs. It initializes transition and emission matrices, iteratively updates parameters until convergence, and outputs motif profiles (with exponential transformations) and their positions in se... | def main():
args = parse_args()
# build transitions
trans = transition(args.p, args.q, len(
args.seed) + EXTERNAL_STATES)
# build emissions
ems = initial_emissions(args.alpha, args.seed)
# load fasta
seq_lst = get_seq(SeqIO.parse(open(args.fasta), 'fasta'))
prev_iter = np.NIN... |
def strB(n, base=10):
#make the digits from base 2 - 26
if base > 26 or base < 2:
return ('invalid number')
base_change = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E' \
'F','G','H','I','K','L','M','N','O','P']
if(n <= 0): #base
return str("")
else: #recursive
r... | The code tests three functions: (1) `strB` for base conversion (26, 16, 8, 2, 27) with validation against expected outputs and error detection, (2) `cnk_m` for computing combinations (n choose k) with multiple test cases, and (3) `make_pairs` for zipping two lists into tuples, handling cases with mismatched lengths or ... | def main():
#part b
c1 = strB(495625, base=26)
testif(c1 == '1254D', 'base 26 test', "success on base conversion from 26", "fail on base conversion from 26")
c2 = strB(495625, base=16)
testif(c2 == '79009', 'base 16 test', "success on base conversion from 16", "fail on base conversion from 16")
... |
def advance(self) -> str:
c = self.source[self.current]
self.current += 1
return c
def add_string(self):
while self.peek() != '"' and not self.is_at_end():
self.advance()
if self.is_at_end():
raise ValueError("Unexpected string", self.line)
self.... | This function scans and tokenizes input characters into specific token types (e.g., braces, brackets, commas) while handling edge cases like line breaks, whitespace, strings, and numbers. It identifies numbers following '-', validates syntax, and raises errors for unexpected characters, ensuring proper lexical analysis... | def scan_token(self):
c = self.advance()
match c:
case "{":
self.tokens.append(Token(TokenType.LEFT_BRACE, c))
case "}":
self.tokens.append(Token(TokenType.RIGHT_BRACE, c))
case "[":
self.tokens.append(Token(TokenType.LE... |
def calculate_complete_path_length(data):
# Function to calculate the sum of distances within a group
def sum_of_distances(group):
distances = np.sqrt(np.diff(group['x_pose'])**2 + np.diff(group['y_pose'])**2)
return pd.Series({'distance': distances.sum()})
# Grouping data by Experiment_ID ... | The main task of the code is to generate a comprehensive PDF report analyzing navigation benchmark results by comparing different controllers and planners. It processes experimental data from a CSV file, computes metrics like success rates, execution time, CPU/memory usage, path deviation, and recovery counts. The repo... | def main():
# Get the name of config file of the current experiment
specs = os.environ['PARAMS_FILE']
# Open config file and extact data
with open(specs, 'r') as file:
robot_specs = yaml.safe_load(file)
controller_type=robot_specs['controller_type']
planner_type=robot_specs['plan... |
def initial_pose(x,y,yaw):
_initial_pose = PoseStamped()
_initial_pose.header.frame_id = 'map'
_initial_pose.pose.position.x = x
_initial_pose.pose.position.y = y
_initial_pose.pose.orientation.x = 0.0
_initial_pose.pose.orientation.y = 0.0
_initial_pose.pose.orientation.z = np.sin(yaw/2)... | The main task of the code is to generate navigation trajectories based on the specified type (user-defined or auto-generated). It processes user-defined paths by extracting waypoints and initializes robot states, while auto-generated trajectories involve creating random paths, extracting pose data, and storing initial/... | def trajectory_generator():
trajectories = []
if robot_specs['trajectory_type'] == 'user_defined':
x=robot_specs['user_defined_trajectories'][0]["spawn_pose"]["x"]
y=robot_specs['user_defined_trajectories'][0]["spawn_pose"]["y"]
yaw=robot_specs['user_defined_trajectories'][0][... |
def handle_keyboard(data, conn, conn_index):
global chat_num
msg_text = data.decode("utf-8").split(": ")[1]
if msg_text.startswith(client_commands.EXIT):
leave(conn)
return 1
elif msg_text.startswith(client_commands.MEMBERS):
conn.send(get_members(chatrooms[conn_index]).encode("u... | The code handles incoming data from a client connection, processes it using `handle_keyboard`, and manages exceptions by either recording data or disconnecting the client. It continuously receives data, checks the connection index, and terminates the loop if `handle_keyboard` signals completion or upon errors like deco... | def handle(conn):
global chat_num
while True:
try:
# Handling requests
data = conn.recv(1024)
conn_index = connections.index(conn)
ret = handle_keyboard(data, conn, conn_index)
if ret:
break
except (UnicodeDecodeError, I... |
def filter_state_dict(state_dict):
from collections import OrderedDict
if 'state_dict' in state_dict.keys():
state_dict = state_dict['state_dict']
new_state_dict = OrderedDict()
for k, v in state_dict.items():
if 'sub_block' in k:
continue
if 'module' in k:
... | The main task of the code is to load pre-trained neural network models (e.g., WideResNet, ResNet) for datasets like CIFAR10, CIFAR100, and ImageNet, based on the specified `model_name`. It configures model parameters, applies normalization, and sets the model to evaluation mode. The function then invokes `Adaptive_Auto... | def main(flag,model_name, ep=8./255,random=True, batch_size=128, average_number=100):
stime = datetime.datetime.now()
print(f"{flag} {model_name}")
data_set="cifar10"
Lnorm="Linf"
if model_name=="TRADES":
from models.CIFAR10.TRADES_WRN import WideResNet # TRADES_WRN
ep = 0.031
... |
def calculate_cumulative_indexes(self):
# Linear Interest - Liquidity index
cumulated_liquidity_interest = self.calculate_linear_interest(self.liquidity_rate, self.last_updated_timestamp, self.current_timestamp)
new_liquidity_index = rayMul(cumulated_liquidity_interest, self.liquidity_index)
... | This function processes a deposit by updating the user's balance, calculating cumulative indexes and interest rates, and increasing the a_tokens supply by the deposited amount. It prints the updated a_tokens value after the deposit. | def deposit(self, user_address, amount):
print("=====DEPOSIT=====")
self.calculate_cumulative_indexes()
self.calculate_interest_rates(amount, 0)
self.cumulate_balance(user_address, amount)
new_a_tokens = self.a_tokens + amount
print("aUSDC after deposit: ", new_a_tokens)
... |
def cumulate_balance(self, user_address, amount):
balance_increase = self.get_current_principal_balance(user_address) - self.previous_principal_balance
new_principal_balance = self.previous_principal_balance + balance_increase
# Mint tokens
new_a_tokens = self.a_tokens + balance_increase... | The code's main task is to process a token redemption request by verifying sufficient funds, updating the user's balance, adjusting the available token count, and recalculating cumulative indexes and interest rates. It ensures the user cannot redeem more than the available a_tokens, subtracts the redeemed amount from t... | def redeem(self, user_address, amount):
print("=====REDEEM=====")
if(amount > self.a_tokens):
return "No sufficient funds"
self.cumulate_balance(user_address, amount)
new_a_tokens = self.a_tokens - amount
print("aUSDC after redeem: ", new_a_tokens)
self.a_toke... |
def create_session_manager(app: Flask) -> SessionManager:
mgr = SessionManager(DynamoDbSessionInstance, **session_manager_configuration(app))
mgr.null_session_class = FlaskNullSessionInstance
return mgr
def _cookie_name(self, app: Flask) -> str:
if not app.config.get('SESSION_DYNAMODB_OVERRIDE_COOKI... | This code saves a session in a Flask application, updating its expiration time if accessed. It checks if the session is new or modified to determine if it should be saved. If the session is cleared, it deletes the cookie. Depending on app configuration, it stores the session ID in a header or cookie, ensuring proper se... | def save_session(self, app: Flask, session: SessionMixin, response: Response):
""" Saves a session, depending on if it was used now or in the past.
A session is `new` if a record was not found during `open_session`. We only save if it was also modified.
Sessions that are not new are always sav... |
def lottie_local(filepath: str):
with open(filepath, "r") as f:
return json.load(f)
def convert_to_room_data(generated_content):
rooms = []
# Split the generated content by newlines
lines = generated_content.split('\n')
for line in lines:
# Check if the line starts with "Room:"... | The code creates a Streamlit app for "Archi Bot," a chatbot that generates and validates house layouts. It handles user input, processes prompts with Gemini API, updates room data in session state, and displays chat history and layout data. Features include layout generation, validation checks, and sidebar controls for... | def main():
st.set_page_config(page_title="Archi Bot",page_icon=":book:")
st.title("Archi Bot")
# About section
with st.sidebar:
anim = lottie_local('animation.json')
st_lottie(anim,
speed=1,
reverse=False,
loop=True,
heigh... |
def toTensor(image, size):
trans = transforms.Compose([
transforms.Resize(size),
transforms.CenterCrop(size),
transforms.ToTensor()
])
return trans(image)[:3].unsqueeze(0)
def process(self, x, nLayer, nSubLayer,
lr, iterations, nOct, octZoom):
... | This code generates a dream-like image by converting the input image to a tensor, processing it through specified neural network layers and optimization parameters (size, learning rate, iterations), and then converting the processed result back to a PNG image for output. | def dream(self, image, size=256, nLayer=0, nSubLayer=41,
lr=0.001, iterations=40, nOct=2, octZoom=2):
x = self.toTensor(image, size)
dream = self.process(x, nLayer, nSubLayer,
lr, iterations, nOct, octZoom)
return self.toPNG(dream) |
def toPNG(tensor):
return transforms.ToPILImage()(tensor[0])
def toTensor(image, size):
trans = transforms.Compose([
transforms.Resize(size),
transforms.CenterCrop(size),
transforms.ToTensor()
])
return trans(image)[:3].unsqueeze(0)
def dream(self, ima... | The code blends a dream-generated color image with the original image's structure using luminosity blending and color/sharpness enhancements, then returns a stylized composite image with adjustable parameters for size, contrast, and layer complexity. | def lsd(self, image, size=400, blendFactor=0.9, nLayer=0, nSubLayer=18, iterations=10, lr=0.01, nOct=3):
sizedImage = self.toPNG(self.toTensor(image, size=size))
colors = self.dream(image, size=size, nLayer=nLayer,
nSubLayer=nSubLayer, iterations=iterations, lr=lr, nOct=nOct)... |
def init_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
"--inputfile",
help="location of the input file",
metavar="FILE",
type=lambda x: is_valid_file(parser, x),
)
parser.set_defaults(feature=True)
return parser
def file_to_scratchcards(file) -> Li... | The main task of the code is to process scratchcard data from an input file by parsing command-line arguments, reading scratchcards, calculating their total value, and counting the number of scratchcards, then printing both results. | def main(argv) -> None:
""" """
parser = init_parser()
args = parser.parse_args(argv)
scratchers = file_to_scratchcards(args.inputfile)
print(sum_scratchcards_value(scratchers))
print(count_scratchcards(scratchers))
return |
def init_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
"--inputfile",
help="location of the input file",
metavar="FILE",
type=lambda x: is_valid_file(parser, x),
)
parser.set_defaults(feature=True)
return parser
def sum_valid_game_numbers(file) -> ... | The main task of the code is to process an input file containing game data, calculate and print the sum of valid game numbers, then reset the file pointer to reprocess the same file and compute the sum of game power values. The code handles two distinct calculations from the same input file in sequence. | def main(argv) -> None:
""" """
parser = init_parser()
args = parser.parse_args(argv)
print(sum_valid_game_numbers(args.inputfile))
args.inputfile.seek(0) # reset the file handler for pt2
print(sum_game_power(args.inputfile))
return |
def vline( self, aStart, aLen, aColor ) :
'''Draw a vertical line from aStart for aLen. aLen may be negative.'''
start = (clamp(aStart[0], 0, self._size[0]), clamp(aStart[1], 0, self._size[1]))
stop = (start[0], clamp(start[1] + aLen, 0, self._size[1]))
#Make sure smallest y 1st.
if (stop[1] < start... | This code draws a line between two points (aStart and aEnd) using a specified color. It delegates vertical/horizontal lines to vline/hline methods, while diagonal lines are rendered via a Bresenham-like algorithm, calculating pixel positions iteratively to plot the line. The function handles axis-aligned cases separate... | def line( self, aStart, aEnd, aColor ) :
'''Draws a line from aStart to aEnd in the given color. Vertical or horizontal
lines are forwarded to vline and hline.'''
if aStart[0] == aEnd[0]:
#Make sure we use the smallest y.
pnt = aEnd if (aEnd[1] < aStart[1]) else aStart
self.vline(pnt, ... |
def placeholder(self):
#Initialize the placeholders for the visible units
self.vu = tf.compat.v1.placeholder(shape=[None, self.n_visible], dtype="float32")
def data_pipeline(self):
#Define the data pipeline
self.batch_size = tf.compat.v1.placeholder(tf.int64)
se... | This code generates a computational graph for a machine learning model, initializing data pipelines, parameters, and Gibbs sampling protocols. It sets up an Adam optimizer to minimize a loss function derived from visible unit activations, using a learning rate adjusted by minibatch size. The graph integrates RBM module... | def generate_graph(self):
#Call the different RBM modules to generate the computational graph
log.info("Creating the computational graph")
print("Creating the computational graph")
self.placeholder()
self.data_pipeline()
self.init_parameters()
log.info("... |
def init_training_session(self, xtr):
#Initialize the TF session on training data
self.sess.run(
self.iter.initializer,
feed_dict={self.vu: xtr, self.batch_size: self.minibatch},
)
self.sess.run(tf.compat.v1.tables_initializer())
def gibbs_protocol(self, ... | The code trains a model using minibatch Gibbs sampling, initializing a session, iterating over epochs, and tracking training RMSE. It processes user-item interactions (xtr), masks non-zero entries, and updates the model via batch training, logging RMSE at specified intervals for performance monitoring. | def fit(self, xtr):
#Main component of the algo; once instantiated, it generates the computational graph and performs model training
self.seen_mask = np.not_equal(xtr, 0)
n_users = xtr.shape[0]
num_minibatches = int(n_users / self.minibatch)
self.init_training_session(... |
def generate_graph(self):
#Call the different RBM modules to generate the computational graph
log.info("Creating the computational graph")
print("Creating the computational graph")
self.placeholder()
self.data_pipeline()
self.init_parameters()
log.info("... | This code initializes a multinomial Restricted Boltzmann Machine (RBM) for collaborative filtering, configuring hyperparameters like hidden units, learning rate, and batch size. It sets up a TensorFlow graph, initializes rating lookup tables, and prepares GPU resources. The RBM models user-item interactions using possi... | def __init__(
self,
possible_ratings,
visible_units,
hidden_units=500,
keep_prob=0.7,
init_stdv=0.1,
learning_rate=0.004,
minibatch_size=100,
training_epoch=20,
display_epoch=10,
sampling_protocol=[50, 70, 80, 90, 100],
debu... |
def get_output_layers(self):
layer_names = self.net.getLayerNames()
output_layers = [layer_names[i - 1] for i in self.net.getUnconnectedOutLayers()]
return output_layers
def process_detections(self, outs, Width, Height, CONF_THRESHOLD):
class_ids = []
confidences = []
box... | The code performs object detection on an input image using a pre-trained neural network. It resizes the image, converts it into a blob, processes it through the network, extracts detected objects' class IDs, confidences, and bounding boxes, applies non-max suppression to remove overlapping boxes, and draws the detected... | def detectObjects(self, img, track):
img = cv2.resize(img, (448, 256))
Height, Width = img.shape[:2]
scale = 1/255
blob = cv2.dnn.blobFromImage(img, scale, (448, 256), (0,0,0), True, crop=False)
self.net.setInput(blob)
outs = self.net.forward(self.get_output_layers())
... |
def _get_accounts(email_template, accounts):
ret = []
for name, config in accounts.items():
ret.append(Account.create(email_template, name, config))
return ret
def initialize(region, email_template):
lambda_name = "terraform"
account_id = _create_separate_account("terraform4", email_templat... | The main task of the code is to generate Terraform configuration files for managing multiple AWS accounts, initialize cloud resources, build and push a Docker image to ECR, create an AWS Lambda function, and invoke it. It loads configuration from a YAML file, sets up Terraform backend and provider settings, dynamically... | def main():
with open("config.yaml", "r") as config_fh:
config = yaml.safe_load(config_fh)
accounts = _get_accounts(config["email_template"], config["accounts"])
region = config["region"]
resources = initialize(region, config["email_template"])
code = Code()
terraform = code.child("ter... |
def create_hyperlink(link: Link):
# <w:hyperlink w:id="rID123">
# <w:r>
# <w:rPr>
# <w:rStyle w:val="aa"/>
# </w:rPr>
# <w:t>Description</w:t>
# </w:r>
# </w:hyperlink>
# create external link relationship
rel_id = create_rela... | This function appends content to a paragraph by handling various data types: recursively processing lists/tuples, directly adding XML elements, converting Links to hyperlinks, Text objects to formatted text records, and strings to basic text records, ensuring all content is properly embedded within the paragraph struct... | def append_content(paragraph, content: Any):
if isinstance(content, list) or isinstance(content, tuple):
for c in content:
append_content(paragraph, c)
elif isinstance(content, etree._Element):
paragraph.append(content)
elif isinstance(content, Link):
# add link rec... |
def mkdir_parent(path):
return Path(path).parent.mkdir(parents=True, exist_ok=True)
def compress_image(path):
max_img_size = 500 # KB
min_width = 400
min_height = 250
attempts = 5
img_size = os.path.getsize(path) / 1024
if img_size <= max_img_size:
return
try:
while at... | The code processes files by copying and compressing images, handling markdown pages, and organizing content. It copies non-MD files, compresses images, and processes MD files into Page objects with tags, metadata, and related content. Pages are sorted by date, and tags are organized with related pages based on common t... | def handle_files(self):
print("Handle files..")
shutil.copytree(self.tmpls + "/to_copy/", self.dist + "/")
for fn in self.files:
file_ext = fn.split(".")[-1]
if not fn.endswith('.md') and file_ext in ["jpg", "jpeg", "png"]:
dst = self.dist + fn[len(self.co... |
def get_pagination_amount(page_amount):
if page_amount <= 6:
return 1
pagination_amount = page_amount // 6
if page_amount % 6 != 0:
return pagination_amount + 1
return pagination_amount
def mkdir_parent(path):
return Path(path).parent.mkdir(parents=True, exist_ok=True)
def write(pa... | This code generates paginated HTML listings for a blog, creating index pages with proper navigation links. It filters pages, calculates pagination, builds context data including page numbers and URLs, renders templates with minified HTML, and writes files to the specified path while handling directory creation and pagi... | def write_listing(self, path, pages, tag, url):
pages = [page for page in pages if not page.nolist]
page_amount = get_pagination_amount(len(pages))
mkdir_parent(path)
pages_set = pages[0:6]
context = dict(
tag=tag,
blog=self,
pages=[p for p in ... |
def build(blog):
shutil.rmtree(blog.dist, ignore_errors=True, onerror=None)
blog.handle_files()
mkdir(blog.dist)
blog.write_sitemap()
blog.write_pages()
blog.write_listing(
f"{blog.dist}/index.html",
blog.pages,
None,
f'{blog.host}/',
)
for tag in blog.t... | The code defines a CLI interface to manage a static blog generator. It parses command-line arguments using `docopt`, executes build tasks, and optionally starts a local server. If the 'start' command is used, it ensures required directories exist, creates executable scripts for building the blog, and sets up a developm... | def cli():
a = docopt(doc, version='staticviking.py 0.1')
print(a)
if a['build']:
build(Blog(a['<content>'], a['<dist>'], a['--tmpls'], a['--host']))
elif a['buildserve']:
build(Blog(a['<content>'], a['<dist>'], a['--tmpls'], a['--host']))
os.system(f"cd {a['<dist>']} && python3 ... |
def mkdir(path):
return Path(path).mkdir(parents=True, exist_ok=True)
def get_template(self, name):
return self.env.get_template(name)
def write(path, data):
with open(path, 'w') as f:
return f.write(data)
def write_page_aliases(self, page):
for alias in page.aliases:
alias_p... | The main task of the code is to generate HTML pages from markdown content. It processes each page by converting its markdown body to HTML, creating destination directories, rendering templates with blog/page data, and writing minified HTML files. The function also handles alias generation for each page. | def write_pages(self):
print("Writing pages..")
for page in self.pages:
page.body_html = self.markdown(page.body)
print(page.dst)
mkdir(page.dst)
template = self.get_template(page.template)
write(
f'{page.dst}/index.html',
... |
def _prepare_block(self):
"""
Convert all available fields to bytes.
"""
self._previous_bytes = to_bytes(self.previous, 32)
self._source_bytes = to_bytes(self.source, 32)
self._balance_bytes = self._to_balance(self.balance)
self._destination_bytes = self._to_ve... | The code serializes a Block object into continuous bytes by concatenating validated hash-fields, signature, and work data. It checks for valid signature and work, then constructs bytes based on the block type (open/send/receive/change/state), appending signature and work bytes finally. | def _pack(self):
"""
Pack a Block class to continuous bytes.
Packed fields: hash-fields, signature and work.
"""
self._prepare_block()
self._validate_fields()
if not self._signature_bytes:
raise ValueError('can not pack with a None signature')
... |
def _to_block_hash_bytes(self, data):
"""
Convert data to 32 bytes hash if legal, return bytes.
"""
return to_bytes(data, 32)
def _get_db_names(self):
"""
return the names of all databases/tables.
"""
db_names = []
with self.env.begin() as txn:
... | The function searches for a given key across all databases, retrieves corresponding values, and returns them in a dictionary with database names as keys and hex-encoded values. It converts the key to bytes, iterates through database names, fetches data, and collects non-empty results for debugging purposes. | def _search_key(self, key):
"""
for debug purpose: get the key, in all db.
"""
key_bytes = self._to_block_hash_bytes(key)
db_list = self._get_db_names()
db_dict = {}
for db_name in db_list:
value = self._get_data(db_name, key_bytes)
if va... |
def _to_signing_key(self, data):
"""
Convert data to signing key if legal, return bytes.
"""
return to_bytes(data, 32)
def _to_verifying_key(self, data):
"""
Convert data to verifying key if legal, return bytes.
"""
vk = to_bytes(data, 32)
if not... | The function prepares an account by generating and validating verifying_key/address from provided signing_key, verifying_key, or address. It ensures consistency between these components, raises errors on mismatches, and sets the genesis flag if the verifying key matches the genesis key. | def _prepare_account(self):
"""
If signing_key is given, generate verifying_key/address from signing_key.
If not, generate address/verifying_key from each other.
"""
if not self.signing_key and not self.verifying_key and not self.address:
raise Exception('signing_key... |
def delete_from_internal_node(self, node, i):
t = self.t
if len(node.c[i].keys) > t - 1:
node.keys[i] = self.delete_predecessor(node.c[i])
elif len(node.c[i + 1].keys) > t - 1:
node.keys[i] = self.delete_successor(node.c[i + 1])
else:
self.fix_by_merge... | This code implements the deletion of a key `k` from a B-tree node. It handles leaf nodes by directly removing the key, while internal nodes trigger recursive deletion in children. The code ensures structural integrity by checking if child nodes have insufficient keys, then either borrowing from siblings via `fix_by_sib... | def delete(self, node, k):
t = self.t
i = 0
while i < len(node.keys) and k > node.keys[i]:
i += 1
if (node.leaf):
if i < len(node.keys) and k == node.keys[i]:
node.keys.pop(i)
return
elif i < len(node.keys) and k == node.keys[i... |
def define(word):
if word in dictionary:
return dictionary[word]
else:
return None
def freq_index(word, all_words):
for i in range(len(all_words)):
if all_words[i] == word:
return i
return -1
def wsd(sent, word):
return lesk(sent, word)
def get_synonyms(word):
entry = define(wo... | The function identifies the simplest synonym for a word in a tagged sentence by checking frequency, part-of-speech compatibility, and contextual similarity, returning the most frequent and contextually appropriate synonym if available, otherwise the original word. | def easiest_synonym(tagged_sent, i, all_words):
word = tagged_sent[i][0]
basic_form = word
d = define(word)
if d:
basic_form = d['word']
fi = freq_index(basic_form, all_words)
if fi < 10000:
return word
elif word.isalpha() and i > 0 and i < len(tagged_sent) and word.istitle()... |
def send_error(conn: socket, error_msg: str = ERROR_MSG):
"""
Send error message with given message
Receives: socket, message error string from called function
"""
build_and_send_message(conn, chatlib.PROTOCOL_SERVER["error_msg"], error_msg)
logging.error(error_msg)
def handle_logout_message(con... | The function routes incoming client messages based on the command (cmd) to the appropriate handler functions, managing user authentication, session tracking, and error responses. It processes commands like signup, login, logout, score retrieval, and question fetching, dispatching data to specific handlers and handling ... | def handle_client_message(conn: socket, cmd: str, data: str):
"""
Gets message code and data and calls the right function to handle command
Recieves: socket, message code and data
"""
global logged_users
if cmd is None and data is None:
send_error(conn)
handle_logout_message(conn... |
def load_more_questions():
"""
Loads more questions from an API and adds them to the trivia database.
- Retrieves the current highest question ID.
- Calls 'API_handler.load_question_with_api' to get new questions.
- Filters out questions that are already in the database.
- Adds the new question... | This function handles server management commands in a separate thread, accepting user inputs like 'load', 'kick', or 'shutdown'. It executes corresponding actions: loading questions, kicking users, or shutting down the server. On shutdown, it closes the connection, waits for threads to finish, and exits the thread via ... | def handle_server_manager_commands(server_conn: socket):
"""
Functionality to handle server management commands.
This function runs in a separate thread.
Raises:
- SystemExit: Raised to close the current thread.
"""
global threads
while True:
# Your logic to handle server manage... |
def build_send_recv_parse(conn: socket, code: str, data: str = "") -> (str, str):
"""
Parses and send the message using build_and_send_message to a given socket,
and returns the response of the server to that message.
Returns: cmd (str) and data (str) of the received message.
If error occurred, will... | The function `play_question` handles retrieving and processing a question from a server via a socket connection. It sends a request for a question, checks for availability or errors, parses the received question data, displays it to the user, collects their answer (1-4), sends the answer to the server, and provides fee... | def play_question(conn: socket):
"""
Question case handler.
"""
code, data = build_send_recv_parse(conn, chatlib.PROTOCOL_CLIENT["get_question_msg"])
if code == chatlib.PROTOCOL_SERVER["no_quest_msg"]:
print("no available question at this moment, do you want to try anything else?")
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.