dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def readTOIProperties( ipath='toiProperties.pkl', SMFlag='TSM' ):
"""
"""
ifile = open( ipath, 'rb' )
z0 = pickle.load( ifile )
ifile.close()
z = z0['allVals']
z = Utils.fixAnomalousRpRs( z )
planetName = z['planetName']
RA = z['RA_deg']
RAhr = RA*(24/360.)
Dec = z['Dec_deg']... | The function generates and saves visualizations of unconfirmed Transiting Exoplanet Survey Satellite (TESS) candidates (TOIs), plotting radius-temperature grids with top-ranked planets per cell. It applies RA/Dec filters, survey-specific cuts, and formatting options (wide/narrow format, ASCII output, heatmaps). Output ... | def gridTOIs( ipath='toiProperties.pkl', wideFormat=True, \
addSignature=False, survey={}, \
RAMin_hr=None, RAMax_hr=None, \
DecMin_deg=None, DecMax_deg=None, \
SMFlag='TSM', onlyPCs=False, ASCII=False, HeatMap=False ):
"""
TOIs that have not been confirme... |
def readConfirmedTESSProperties( publishedMasses=True, SMFlag = 'TSM' ):
"""
Returns properties of confirmed TESS planets.
"""
ifile = open( 'confirmedProperties.pkl', 'rb' )
z0 = pickle.load( ifile )
ifile.close()
z = z0['allVals']
z = Utils.fixAnomalousRpRs( z )
planetName = z['pla... | This function generates and saves a grid plot of confirmed TESS planets' radius vs. equilibrium temperature, filtering by star size and mass data status. It creates a visualization highlighting top-ranked planets in each cell, with options to标注 mass estimation methods and format outputs. The plot is saved as PDF with d... | def gridTESS( publishedMasses=True, wideFormat=True, addSignature=False, SMFlag = 'TSM' ):
"""
Confirmed TESS planets without published mass.
Currently unused, may be out of date
"""
surveyName = '' #This variable is used below but undefined, this is added as a placeholder definition
showGrid =... |
def readConfirmedProperties( ipath='confirmedProperties.pkl', SMFlag='TSM' ):
"""
Returns properties for all confirmed planets. For planets with
available radius but no mass measurement, an empirical relation
is used to estimate the mass. This has been done for the purpose
of identifying targets for... | The main task of the code is to generate and save visualizations of confirmed exoplanet data, including radius-temperature scatter plots and grid plots, applying survey-specific filters and formatting. It creates multiple plot versions with/without SM cuts, TESS indicators, and grid overlays, saving outputs as PDF/PNG ... | def gridConfirmed( ipath='confirmedProperties.pkl', wideFormat=True, \
survey={}, addSignature=False, showGrid=True, \
showNeptuneRadius=False, showJupiterRadius=False, \
SMFlag='TSM', HeatMap=False, ASCII=False ):
"""
"""
z, dateStr = readConfir... |
def gridTOIs( ipath='toiProperties.pkl', wideFormat=True, \
addSignature=False, survey={}, \
RAMin_hr=None, RAMax_hr=None, \
DecMin_deg=None, DecMax_deg=None, \
SMFlag='TSM', onlyPCs=False, ASCII=False, HeatMap=False ):
"""
TOIs that have not been confirme... | The main task of the code is to generate ASCII files containing top-ranked exoplanet candidates (TOIs) from survey data, including their properties like TICID, magnitudes, and stellar/planetary parameters. It processes input data, sorts candidates by declination, integrates external exofop data, estimates missing magni... | def CreateASCII_TOIs( ipath='toiProperties.pkl', survey={}, SMFlag = 'TSM', onlyPCs=False, \
topFivePredicted=False, multTIC=False, forceDownloadExoFOP=False ):
Tgrid, Rgrid = survey['gridEdges']( survey['surveyName'] )
ifile = open( ipath, 'rb' )
z0 = pickle.load( ifile )
ifi... |
def get_vault_kv_path(path):
assert VAULT_TOKEN, "VAULT_TOKEN env var is required, see README for how to get it"
return json.loads(subprocess.check_output([
'vault', 'kv', 'get', '-format=json', f'kv/{path}'
], env={
**os.environ,
'VAULT_ADDR': VAULT_ADDR,
'VAULT_TOKEN': VAUL... | This function retrieves secret values by resolving templates, vault entries, or server file paths. If the input is a dictionary, it reads a template file, replaces placeholders with resolved values (recursively), and returns the processed template. For 'vault:' prefixes, it fetches values from a vault; for 'server:', i... | def get_secret_value(value, key=None, app_name=None):
if isinstance(value, dict):
assert key and app_name
type_ = value.get('type') or 'template'
assert type_ == 'template'
template_filename = value.get('template_filename') or f'{key}.template'
with open(f'apps/{app_name}/{te... |
def ssh(*args, check_output=False):
hostname = ssh_init()
cmd = [
'ssh', '-t', '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'LogLevel=ERROR', '-o', 'IdentitiesOnly=yes',
'-i', f'{ETC_DFC_DOCKER}/id_ed25519', f'ubuntu@{hostname}', *args
]
if check_output:
... | The function copies secret files and environment-specific files from an application configuration to a remote directory. It creates temporary files, processes secrets using `get_secret_value`, and transfers them via `scp` to `~/apps/.new.{app_name}/secrets`, handling both regular files and `.env` files with key-value p... | def copy_secrets(app_conf, app_name, stats):
if 'x-secrets' in app_conf:
ssh(f'mkdir -p ~/apps/.new.{app_name}/secrets')
with TemporaryDirectory() as tmp_dir:
all_file_names = set()
for file_name, value in app_conf['x-secrets'].get('files', {}).items():
all_fi... |
def ssh(*args, check_output=False):
hostname = ssh_init()
cmd = [
'ssh', '-t', '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'LogLevel=ERROR', '-o', 'IdentitiesOnly=yes',
'-i', f'{ETC_DFC_DOCKER}/id_ed25519', f'ubuntu@{hostname}', *args
]
if check_output:
... | This function deploys a Docker Compose application by copying configuration files, managing remote directories, and executing deployment steps. It checks for --skip-deploy, validates the compose.yaml file, transfers files via SCP, moves the new app directory, runs pre-deploy commands, deploys services, and triggers fil... | def deploy_app(app_name, *args):
skip_deploy = '--skip-deploy' in args
assert os.path.exists(f'./apps/{app_name}/compose.yaml')
with open(f'./apps/{app_name}/compose.yaml') as f:
app_conf = yaml.safe_load(f)
ssh(f'rm -rf ~/apps/.new.{app_name}')
stats = {
'all_changed_files': set()
... |
def take_entries(self, line):
if self.current != "rules":
if self.current == "entries":
msg = "Only one line for initial facts allowed"
else:
msg = "You cannot insert initial facts here, respect the order : " \
+ "Rules => Initial f... | The code parses input content by removing whitespace, splitting into lines, and processing each line to extract entries, queries, or rules based on their starting character (=, ?, or others). It skips comments and empty lines, updates counters, and prints parsed data including line count, nodes, rules, entries, queries... | def parsing(self, content):
content = content.replace(" ", "")
content = content.replace("\t", "")
lines = content.split("\n")
for line in lines:
self.line += 1
if '#' in line:
line = line[:line.index('#')]
if line == "":
... |
def forward_pro(x, W, b):
a = [None] * len(layer_sizes)
z = [None] * len(layer_sizes)
a[0] = x[0].T
for l in range(1, len(a)):
z[l] = weighted_sum(W[l], a[l-1], b[l])
a[l] = sigmoid(z[l])
return (a, z)
def back_prop(a, z, W, y):
delta = [None] * len(layer_sizes)
end_node =... | This function performs one iteration of backpropagation on a neural network. It computes forward passes, calculates gradients via backpropagation, accumulates gradients across samples, updates weights/biases using gradient descent with learning rate η, and returns updated parameters along with the mean squared error. | def backPropagation_iter(X, y, W, b, eta):
y_pred = [None] * len(y)
for i in range(n):
a, z = forward_pro(X[i,:], W, b)
y_pred[i] = np.max(a[-1])
delta = back_prop(a, z, W, y[i])
W_grad, b_grad = calc_gradient(W, b, a, delta, eta)
if i == 0:
W_grad_sum = W_... |
def Energy(W, X):
Y = np.asmatrix(X)
test = Y @ W
E = - 0.5 * (Y @ W)@Y.T
return E
def Update(W, x):
xnew = x @ W
return Thresh(xnew)
def Thresh(x):
if IsScalar(x):
val = 1 if x>0 else -1
else:
val = np.ones_like(x)
val[x<0] = -1.
return val | The code performs iterative updates on a network's state (x) to minimize energy, either synchronously (all nodes updated together) or asynchronously (nodes updated randomly). It returns the final state, number of iterations, and final energy. The synchronous version updates all nodes in sequence, while the asynchronous... | def Iterate_Network( W, x_orig, isSync):
if isSync:
x = copy.deepcopy(x_orig)
e = [1000,]
e_new = Energy(W,x)
n_iters = 0
while e_new < e:
x_new = Update(W, x)
#print(Hamming(x, x_new))
e = e_new
e_new = Energy(W,x_new)
... |
def sigma(self, t):
return self.sigma0 * np.exp(-t / self.lam)
def plot_som_topology(som):
font = {'family': 'serif',
'color': 'darkred',
'weight': 'normal',
'size': 16,
}
k = 0
plt.figure(figsize=(20,20))
x,y = get_x_y(som)
plt.scatter(x,y)
... | This code trains a Self-Organizing Map (SOM) by iteratively updating neuron weights to represent input data. It initializes the SOM, selects random data points, identifies the best matching unit (BMU), and updates the SOM's weights toward the data point using a time-dependent learning rate (sigma(t)). The process conti... | def train(self, data, L0, lam, sigma0, initializer=np.random.rand, frames=None):
self.L0 = L0
self.lam = lam
self.sigma0 = sigma0
self.som = initializer(*self.shape)
self.data = data
for t in itertools.count():
if frames != None:
frames.appe... |
def get_backup_timestamps(stg_client, bucket, db_name):
# Returns a sorted list of the timestamps for the backups for the DB.
keys = get_keys_for_db(stg_client, bucket, db_name)
timestamps = calc_timestamps(db_name, keys)
return (keys, timestamps)
def calc_timestamps_to_delete(backup_timestamps):
# ... | The function `cleanup_old_backups` identifies and deletes outdated backups from a specified storage bucket. It retrieves backup timestamps, calculates which ones to remove, and executes the deletion using helper functions. Parameters include a storage client, bucket name, and database name. The task ensures storage eff... | def cleanup_old_backups(stg_client, bucket, db_name):
keys, backup_timestamps = get_backup_timestamps(stg_client, bucket, db_name)
timestamps_to_delete = calc_timestamps_to_delete(backup_timestamps)
delete_backups(stg_client, bucket, db_name, keys, timestamps_to_delete) |
def select_target_pg_host(pg_host, pg_port, pg_database, pg_user, pg_password):
target_replica = query_replicas(pg_host, pg_port, pg_database, pg_user, pg_password)
if target_replica:
logging.info("Target replica is %r", target_replica)
return target_replica
logging.info("No target replica s... | This function performs a PostgreSQL database backup, including dumping the database and associated Kubernetes resources to a specified storage bucket. It initializes an S3-compatible storage client, generates a storage key base, executes the database dump, backs up Kubernetes objects, and cleans up old backups. The tas... | def postgres_db_backup(
db_name, users, namespace, bucket,
pg_host, pg_port, pg_database, pg_user, pg_password,
stg_endpoint, stg_tls_verify, stg_acces_key, stg_secret_key):
target_pg_host = select_target_pg_host(
pg_host, pg_port, pg_database, pg_user, pg_password)
logging.inf... |
def adjust_learning_rate(optimizer, epoch, gammas, schedule):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr
assert len(gammas) == len(schedule), "length of gammas and schedule should be equal"
for (gamma, step) in zip(gammas, schedule):
if (epoch >= st... | The code trains a neural network model over multiple epochs using stochastic gradient descent (SGD) with learning rate adjustments. It validates the model on a test set each epoch, tracks training and validation metrics (accuracy, loss), logs progress, and saves checkpoints for the best-performing model. The function a... | def train(model, train_loader, test_loader, criterion, start_epoch, total_epoches, log):
optimizer = torch.optim.SGD(model.parameters(), args.lr, momentum=args.momentum,
weight_decay=args.decay, nesterov=True)
if args.use_cuda:
torch.cuda.empty_cache()
model.cuda()
recorder = ... |
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every args.decay_epoch_step epochs"""
lr = args.lr * (0.1 ** (epoch // args.decay_epoch_step))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def train_epoch(train_l... | This code trains a deep learning model using distributed data parallelism, adjusting learning rates over epochs. It performs training and validation phases, logs metrics, updates a recorder for accuracy/loss tracking, saves checkpoints, and returns the optimized model. Key steps include optimizer setup, CUDA handling, ... | def train(model, train_loader, test_loader, train_sampler, criterion, start_epoch, total_epoches, log, optimizer=None):
if optimizer is None:
optimizer = torch.optim.SGD(model.parameters(), args.lr, momentum=args.momentum,
weight_decay=args.decay, nesterov=True)
if args.use_cuda:
t... |
def get_train_subset_in_memory(train_loader_subset):
sub_inputs = []
sub_targets = []
for _, (input, target) in enumerate(train_loader_subset):
if args.use_cuda:
target = target.cuda(non_blocking=True)
input = input.cuda(non_blocking=True)
sub_targets.append(target)
... | The main task of the code is to iteratively prune convolutional layers of a neural network to reduce computational cost (FLOPs) while maintaining performance. It evaluates baseline accuracy, calculates initial FLOPs, and iteratively selects the most effective pruning method (e.g., l1norm, l2norm) for each layer to achi... | def prune(model, train_loader, loader_subset, test_loader, criterion, log):
sub_inputs, sub_targets = get_train_subset_in_memory(loader_subset)
with torch.no_grad():
val_acc_top1, val_acc_top5, val_loss = validate(test_loader, model, criterion)
print_log("Val Acc@1: %0.3lf, Acc@5: %0.3lf, Los... |
def get_train_subset_in_memory(train_loader_subset):
sub_inputs = []
sub_targets = []
for _, (input, target) in enumerate(train_loader_subset):
if args.use_cuda:
target = target.cuda(non_blocking=True)
input = input.cuda(non_blocking=True)
sub_targets.append(target)
... | The code performs iterative layer-wise pruning on a neural network to reduce computational cost (FLOPs) while maintaining performance. It evaluates pruning methods (e.g., L1/L2 norm, cosine similarity), selects the method minimizing validation loss, and prunes filters iteratively until a target FLOP reduction is achiev... | def prune(model, train_loader, train_sampler, loader_subset, test_loader, criterion, log):
sub_inputs, sub_targets = get_train_subset_in_memory(loader_subset)
with torch.no_grad():
val_acc_top1, val_acc_top5, val_loss = validate(test_loader, model, criterion)
print_log("Val Acc@1: %0.3lf, Acc@... |
def print_log(print_string, log, display=True):
if display:
print("{}".format(print_string))
log.write('{}\n'.format(print_string))
log.flush()
def train(model, train_loader, test_loader, criterion, start_epoch, total_epoches, log):
optimizer = torch.optim.SGD(model.parameters(), args.lr, momen... | The main task of the code is to train, prune, or evaluate a neural network on CIFAR-10 or CIFAR-100 datasets. It initializes logging, datasets, data loaders, and a model based on user-specified arguments. Depending on the mode (`prune`, `train`, or `eval`), it either trains a model from scratch or a pre-trained checkpo... | def main():
# Init logger
if not os.path.isdir(args.save_path):
os.makedirs(args.save_path)
log = open(os.path.join(args.save_path, 'log_seed_{}.txt'.format(args.manualSeed)), 'w')
print_log('save path : {}'.format(args.save_path), log)
state = {k: v for k, v in args._get_kwargs()}
pr... |
def validate(self):
''' Return true if list start and ends with points
and has pt_of_I for midpoints. PC and PT must be in order'''
pl = self.pointList
if not isinstance( pl[0], point ):
return False
if not isinstance( pl[-1], point ):
return False
... | The code initializes an object with a name and a point list, validating the input structure (start/end with "named point tuples", midpoints as "named pi tuples"). If valid, it generates two lists: `self.pog` (named pc/pt tuples) and `self.set` (named segment tuples) using helper methods, while printing validation and p... | def __init__(self, name, pointList ):
''' ProG are defined with a list.
The list must start and end with a "named point tuple"
midpoints must be "named pi tuples"
Once the input is validated two lists are created
self.pog = list of "named pc and pt tuples"
self.set = l... |
def pawn_moves(self, square: Square, en_passant_square: Square):
piece = square.attached_piece
row = np.argwhere(self.board == square)[0][0]
col = np.argwhere(self.board == square)[0][1]
range_of_motion = []
direction = 1 if piece.color == Piece.BLACK else -1
for i in r... | This function determines all possible moves for a chess piece on a given square. It checks the type of piece (pawn, knight, etc.) and delegates move generation to the corresponding method, returning a list of valid moves. Special handling for pawns includes en passant logic. | def piece_moves(self, square: Square, en_passant_square=None):
piece = square.attached_piece
if piece == None: return []
if piece.piece == Piece.PAWN: return self.pawn_moves(square, en_passant_square)
elif piece.piece == Piece.KNIGHT: return self.knight_moves(square)
eli... |
def generateWorkspace(self):
self.codeGenMkdir('pySys')
self.codeGenMkdir('pySys/'+str(self.yourname))
self.codeGenMkdir('pySys/designLog')
if self.codeGenFloader:
floaderList = str(self.codeGenFloader).split()
for singleFloader in floaderList:
sel... | The main task of the code is to generate a standard Python package structure by creating essential files and directories, including __init__.py, main.py, requirements.txt, setup.py, .gitignore, README, LICENSE, and MANIFEST.in within the 'pySys/' directory, along with a workspace setup. | def generateSys(self):
self.generateWorkspace()
self.generateInitPy('pySys/'+str(self.yourname)+'/')
self.generateMainPy('pySys/')
self.generateRequirements('pySys/')
self.generateSetup('pySys/')
self.generateGitIgnore('pySys/')
self.generateReadme('pySys/')
... |
def singleFit(df, fun, p0=None, bUp=None, bLow=None, colX=0, colY=1, ax=None, typeList=['auto0;;auto0'], labelList=['Fit'], multPoint=10, fitList=None, plotData=True, showPlot=True):
"""
Curve fitting returning parameter values and errors + plotting the fitting graph together with data if requested. Axis object... | The `multiFit` function performs multiple dataset fitting using a specified function (`fun`), handling inputs as either a dictionary of dataframes (`dfd`) or a groupby object (`dfg`). It applies `singleFit` to each dataset, extracts fitting parameters, and plots them on provided axes (`axList`), with options for error ... | def multiFit(colX, colY, fun, p0=None, bUp=None, bLow=None, dfg=None, dfd=None, axList=[], axPrimer=[], paramList=[], xLabel=[], yLabel=[], xyAx=None, valList=[], plotData=True, plotErrType=None, plotType='marker', showPlot=True):
"""
Multiple data set fitting. The input is either a dictionary of dataframe (dfd... |
def check_radius_ip():
atRadiusIpChange = "265" # Hard Coding everything else, why not this.
c.site_id = "x28yoxh6" # Hard coding Worker Center until I figure out a better way.
device = check_get_device_stat("24:5a:4c:98:9f:49")
if device[0]['connect_request_ip'] != "192.168.3.11": # Hard coding IP addree for the c... | The code's main task is to check Radius IP settings, iterate through UniFi Controller sites, verify Autotask company data via site ID, and process unarchived alerts and fixed tickets for each site, excluding ignored sites. It ensures site-company mappings exist in Autotask and triggers alert/ticket management actions w... | def main():
check_radius_ip()
# Loop through all sites in the UniFi Controller
for site in c.get_sites():
if site['desc'] not in unifi_ignore:
c.site_id = site['name']
filter_field = at.create_filter("contains", "UniFi Site ID", site['name'], 1)
company = at.get_companies(filter_field)
if not compan... |
def _add_edge(self, p, c):
self.c[p].append(c)
self.p[c] = p
def _get_node_index(self, node_index_or_name):
if node_index_or_name not in self._node_names:
node_index_or_name = self._mapped_name_to_node_name(node_index_or_name)
return self._node_names.index(node_index_or_name)
def _save(self):
... | The code adds an edge between two nodes (p and c) by converting them to indices, then calls _add_edge to establish the connection and _save to persist the change. | def add_edge(self, p, c):
self._add_edge(self._get_node_index(p), self._get_node_index(c))
self._save() |
def _save(self):
if self._data_path is None:
return
data = {"node_names": self._node_names, "edges": self.get_all_edges()}
with open(self._data_path, "w") as fout:
json.dump(data, fout)
def _create_node_by_index(self, node_i):
# create children and parent
if not node_i in self.c:
s... | The code loads data from a file, initializes node names, creates nodes, and adds edges. If the data path is invalid, it creates a default "master" node and saves it. It reads JSON data, populates node names, generates nodes for each entry, and adds edges from the loaded data to construct a graph structure. | def _load(self):
if self._data_path is None:
return
if not os.path.exists(self._data_path):
self._node_names.append("master")
self._save()
with open(self._data_path) as fin:
data = json.load(fin)
self._node_names = data["node_names"]
for node_i, node_name in enumerate(se... |
def date_range(start, end, delta):
curr = start
while curr < end:
yield curr
curr += delta
yield end
def create_tweet_query(screen_name=None,
maxTweets=None,
since=None,
until=None,
querySearch='',
... | The main task of the code is to generate a list of tweet collection tasks based on input queries, date ranges, and search parameters. It processes each query to create combinations of search criteria (e.g., keywords, locations, user profiles) and date intervals, then constructs tasks for each combination. These tasks a... | def create_tasks(queries, saveParam, days_interval=3):
tweet_tasks = []
profiles = []
for q in queries:
maxTweets = q.get('maxTweets', None)
topTweets = q.get('topTweets', None)
recursion = q.get('recursion', 0)
a = []
if 'querySearch' in q:
a.append([('q... |
def _is_enabled_for_request(self, request):
return self.enabled and 'dont_proxy' not in request.meta
def _clear_dns_cache(self):
# Scrapy doesn't expire dns records by default, so we force it here,
# so client can reconnect trough DNS failover.
dnscache.pop(urlparse(self.url).hostname, N... | This method handles connection errors by clearing the DNS cache and introducing a custom delay when encountering ConnectionRefusedError or ConnectionDone exceptions, specifically to mitigate issues caused by Crawlera service downtime during web scraping tasks. | def process_exception(self, request, exception, spider):
if not self._is_enabled_for_request(request):
return
if isinstance(exception, (ConnectionRefusedError, ConnectionDone)):
# Handle crawlera downtime
self._clear_dns_cache()
self._set_custom_delay(requ... |
def _is_enabled_for_request(self, request):
return self.enabled and 'dont_proxy' not in request.meta
def _get_slot_key(self, request):
return request.meta.get('download_slot')
def _restore_original_delay(self, request):
"""Restore original delay for slot if it was changed."""
key, slot =... | This method processes a response to handle bans and track statistics. It checks if the request is enabled, restores original delays, increments ban counters if the response status matches a ban code, closes the spider if bans exceed a limit, sets custom delays from 'retry-after' headers, and updates statistics for bann... | def process_response(self, request, response, spider):
if not self._is_enabled_for_request(request):
return response
key = self._get_slot_key(request)
self._restore_original_delay(request)
if response.status == self.ban_code:
self._bans[key] += 1
if se... |
def _parse_settings(setting_map_path):
settings_map = None
with open(setting_map_path, 'r') as stream:
try:
settings_map = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
# __validate_settings(settings_map)
return settings_map
def _getMetaData(s... | The code executes a secure multi-party computation (MPC) workflow by parsing settings, processing data, distributing it across parties, compiling a secure program, and running the MPC protocol (mpSPDZ) to perform privacy-preserving computations. | def run(setting_map_path):
# Path to settings file
# print("parsing settings")
settings_map = _parse_settings(setting_map_path)
# print("validating settings")
# validate_settings(settings_map)
# print("processing data and retrieving its metadata")
metadata = _getMetaData(settings_map)
... |
def keydown(self, key):
""" Update velocities based on key pressed
Arguments:
key: pygame key
"""
if key == pygame.K_UP: # set forward velocity
self.set_velocities(for_back_vel = S)
elif key == pygame.K_DOWN: # set backward velocity
self.set_... | The code controls a Tello drone by connecting to it, setting speed, managing video streaming, and using Pygame for input handling. It processes real-time video frames with TensorFlow for object detection, displays the feed, updates flight data, and adjusts drone movement based on keyboard/joystick inputs. The loop runs... | def run(self):
if not self.tello.connect():
print("Tello not connected")
return
if not self.tello.set_speed(self.speed):
print("Not set speed to lowest possible")
return
# In case streaming is on. This happens when we quit this program without t... |
def update(self):
if self.mode == "Auto":
self.hover()
self.mode = "Seek"
elif self.mode == "Seek":
self.hover()
self.target = []
self.seek_target()
elif self.mode == "Track":
self.hover()
self.PID_control([self.... | The code controls a Tello drone via Pygame and OpenCV, capturing real-time video, processing frames to detect a specific target (via contour analysis and shape recognition), switching to tracking mode when detected, and displaying the processed video with a tracking marker. It handles user input, maintains the video st... | def run(self):
if not self.tello.connect():
print("Tello not connected")
return
if not self.tello.set_speed(self.speed):
print("Not set speed to lowest possible")
return
# In case streaming is on. This happens when we quit this program without t... |
def __add_location(self, record, oclc_number):
"""
Add a location based on call number or 852$b
:param record:
:param oclc_number:
:return:
"""
# No location mapping for online records
if self.is_online(record):
return
fields = record.... | The code's main task is to update a MARC record according to a plugin's policy by adding location, inventory, funds, and item policy data, fixing duplicate 100 fields, adding local notes, and removing obsolete 035 and 9xx fields. It processes the record using the provided OCLC identifier to ensure compliance with catal... | def execute(self, record, identifier):
"""
Executes the record update policy for this plugin.
:param record: pymarc record
:param identifier: the OCLC identifier
:return:
"""
self.__add_location(record, identifier)
self.__add_inventory(record)
self... |
def __replace_with_oclc_001_003(record, oclc_number):
"""
Add 001 and 003 fields to a record. Use to guarantee this
information is in every record.
:param record: pymarc record
:param oclc_number: OCLC number
"""
record.remove_fields('001')
record.remove_... | The code replaces OCLC-specific fields (001, 003, leader) in a record with values from the OCLC API response. It applies a defined replacement strategy—either replacing existing fields or adding new ones—to update control and data fields based on OCLC data. The function tracks updates to 001, 003, and leader fields, en... | def replace_fields(self, oclc_001_value, record, oclc_response):
"""
Handles all OCLC field replacements
:param oclc_001_value: the 001 value from OCLC
:param record: the record node
:param oclc_response: the response from OCLC
:return:
"""
if not self.rep... |
def __get_field_text(self, field, oclc_response):
"""
Gets value for the requested field text.
:param field: field tag
:param oclc_response: OCLC marcxml or root node
:return: field value
"""
oclc_field = self.__get_oclc_element_field(field, oclc_response)
... | This method processes a MARC record using OCLC API data, updating fields based on title match accuracy. It logs errors for missing OCLC identifiers, inserts records into a database if requested, and writes XML responses. Depending on match quality (perfect vs. fuzzy), it updates records, labels them, and writes to diff... | def __process_oclc_match(self, record, oclc_response, oclc_search_id, add_to_database):
"""
Primary method for updating a single record with OCLC data.
Does record processing based on class properties. Reports
the result to console.
:param record: pymarc record to be modifed
... |
def _atoms(self):
"""
Create atoms dictionary.
"""
# Calculate numbers of c, h, n, o, mg, si, fe.
nelem = {'nc': 6, 'nh': 1, 'nn': 7, 'no': 8, 'nmg': 12, 'nsi': 14, 'nfe': 26}
dnelem = dict.fromkeys(nelem)
for key in dnelem.keys():
dnelem[key] = [len... | This function calculates and returns the composition breakdown of fitted PAHs, including counts of solo, duo, trio, etc., PAHs, pure PAH fractions, average carbon count (Nc), and uncertainty. It checks for required data (database, weights) and handles flux-based calculations with integration. The result is a dictionary... | def getbreakdown(self, **keywords):
"""
Retrieves the breakdown of the fitted PAHs.
"""
if not self.pahdb:
message('VALID DATABASE NEEDED TO GET CLASSES')
return None
# Set atom dictionary if it doesn't exist.
if not self.atoms:
self... |
def _isDecisionOrRewardAt(self, position):
"""Returns true if the location is a decision point,
or reward point"""
return self._getCellAt(position) in "DG"
def _logMaze(self, position, direction, showLog = (logging.getLogger().level is logging.DEBUG) ):
"""Log a maze - with an X at the p... | This function identifies the next decision point or reward in a maze by moving from the current position in the given direction. It uses caching to avoid redundant computations, checks for walls, and adjusts direction when obstacles are encountered. The loop continues until a decision/reward is found, logging the maze ... | def _findNextDecision(self, position, direction, _cache = {}):
"""Find a decision point based on the current position and direction.
position: a 2-d coord Point
direction: a 2-d direction Point
returns: a 2-d coord Point
"""
orig = (hash(position), hash(direction))
... |
def _logMaze(self, position, direction, showLog = (logging.getLogger().level is logging.DEBUG) ):
"""Log a maze - with an X at the position given"""
if showLog:
logging.debug("**** MAZE:")
playerDir = {self._north: "^",
self._south: ",",
... | The code evaluates the fitness of a genotype (sequence of movement genes) in a maze by simulating the path from a starting point. It penalizes wall collisions and revisiting decision points, rewards reaching new decision points and the goal, and returns a fitness score. The score balances penalties/rewards to guide evo... | def testIndividual(self, genes):
"""Given a genotype (set of NSEW genes),
try them from the starting point in the maze
and return the fitness score"""
position = self._start
fitness = 0
visitedDecisionPoints = [self._start]
logging.info("Testing genes %s", repr(ge... |
def get_all_datafiles_paths(self, dir_path):
for path in os.listdir(dir_path):
if os.path.isfile(os.path.join(dir_path, path)):
self.datafile_paths.append(dir_path + "\\" + path)
else:
self.get_all_datafiles_paths(os.path.join(dir_path, path))
def create_d... | The main task of the code is to initialize an object by either creating a database from data files (if provided) or connecting to an existing database (if no arguments are given). It checks for input datafiles, creates the database structure, and establishes a connection if the database already exists. | def __init__(self, *args):
if len(args) != 0:
self.get_all_datafiles_paths(r'data')
self.create_database()
else:
if self.does_database_exists():
self.__establish_connection() |
def get_next_item(items, items_info, cur_time, next_new_item_idx):
"""
Finds the next item to be presented based on their activation.
Arguments:
items -- the items to be considered when choosing the next item
items_info -- the map, containing each item's information
cur_time ... | The code simulates a learning process by simulating encounters with items (e.g., words) across multiple sessions. It tracks item activations, adjusts model parameters (alpha values) based on whether items are guessed, and updates encounter data. The function returns the start time of the learning process, while iterati... | def learn(items, items_info, sesh_count, sesh_length):
"""
Simulates the learning process by adding new encounters of words.
Arguments:
items -- the items which need to be learned
items_info -- the information related to each item
sesh_count ... |
def get_next_item(items_seen, items_new, cur_time):
"""
Finds the next item to be presented based on their activation.
Arguments:
items_seen -- a dictionary of items, which the user HAS encountered before, but still hasn't learned
items_new -- a list of items, which the user HASN'T encount... | The function `learn` simulates a learning session by iterating through items (new and previously seen), tracking encounter results, updating item-specific alpha values based on recall outcomes, and returning updated item lists after the session duration. It manages timing, item selection, encounter logging, and adaptiv... | def learn(items_seen, items_new, session_length):
"""
Goes through a single learning session.
Arguments:
items_seen -- a dictionary of items, which the user HAS encountered before, but still hasn't learned
items_new -- a list of items, which the user HASN'T encountered before, but ... |
def get_next_item(items, items_info, cur_time, next_new_item_idx, cached):
"""
Finds the next item to be presented based on their activation.
Arguments:
items -- the items to be considered when choosing the next item
items_info -- the map, containing each item's information
c... | The function simulates a learning process by processing encounters of items across multiple sessions, adjusting item-specific parameters (like alpha) based on recall outcomes, and tracking performance metrics. It calculates activation and recall probabilities, updates item information, and manages caching strategies. T... | def learn(items, items_info, sesh_count, sesh_length, cached, immediate_alpha_adjustment, alpha_adjust_value, cache_update, inter_sesh_time, use_real_alphas, encounter_outcomes):
"""
Simulates the learning process by adding new encounters of words.
Arguments:
items -- the items whi... |
def initialize_avg_items_info(items):
avg_items_info = {}
for item in items:
avg_items_info[item] = Bunch(avg_enc_count = 0.0,
avg_perc_incorr = 0.0,
avg_alpha = 0.0)
return avg_items_info
def reset_items_info(items_in... | The code conducts multiple learning sessions to calculate average metrics (duration, encounter count, alpha error, alpha bias) and item-specific statistics. It resets session data, runs the learning process, accumulates results over `learn_count` iterations, computes averages, and prints comparisons between cached/unca... | def test_learning(items, items_info, sesh_count, sesh_length, learn_count):
"""
Gets average values for learning both when using the cached and the uncached activations for each encounter
Prints a comparison between the two averages.
learn_count -- how many times should learning sessions be conducted ... |
def initialize_avg_items_info(items):
avg_items_info = {}
for item in items:
avg_items_info[item] = Bunch(avg_enc_count = 0.0,
avg_perc_incorr = 0.0,
avg_alpha = 0.0)
return avg_items_info
def reset_items_info(items_in... | The main task of the code is to compute and print average metrics (duration, encounter count, alpha error, and bias) of learning sessions over multiple trials, comparing cached and uncached activation scenarios. It runs `learn_count` sessions, accumulates statistics, normalizes them, and outputs item-specific and overa... | def test_learning(items, items_info, sesh_count, sesh_length, learn_count, cached, immediate_alpha, alpha_adjust_value, cache_update, inter_sesh_time):
"""
Gets average values for learning both when using the cached and the uncached activations for each encounter
Prints a comparison between the two averages... |
def reset_items_info(items_info):
for item in items_info:
items_info[item].alpha_model = model_params["alpha_d"]
items_info[item].encounters = []
items_info[item].incorrect = 0
def learn(items, items_info, sesh_count, sesh_length, cached, immediate_alpha_adjustment, alpha_adjust_value, ca... | The function evaluates learning session outcomes using three configurations: real alphas without caching, model alphas without caching, and model alphas with caching. It compares encounter histories, calculates average index offsets and biases between sessions, and prints item-specific and session-wide metrics to analy... | def test_encounter_history(items, items_info, sesh_count, sesh_length, inter_sesh_time):
"""
Gets the encounter-specific results of learning sessions when using:
- the real alphas and the original implementation of the algorithm
- the model's alphas and the original implementation of the al... |
def get_angle_range(prev_state):
prev_angle, prev_point, prev_poly = prev_state
end_angle = dir_to_angle(prev_point[0])
radius = prev_point[1]
dis = get_dis(np.array([0, 0]), prev_point[0])
angle_range = ANGLE_SEARCH_MAX_RANGE
if dis > radius:
angle_range = min(angle_range, get_angle_dis... | This function determines the optimal angle for a cut by iteratively narrowing a search range within a geometric sector. It splits a contour using rays, intersects polygons, and evaluates midpoints to refine the angle. The loop reduces the search range by 1/3 each iteration, selecting the midpoint with better evaluation... | def angle_search_last_cut(last_contour, prev_state):
prev_angle, prev_poiont, prev_poly = prev_state
start_angle, end_angle, angle_range = get_angle_range(prev_state)
# Cut everything to this range
start_ray = dir_to_ray(angle_to_dir(start_angle + 0.05))
end_ray = dir_to_ray(angle_to_dir(end_angle ... |
def get_angle_range(prev_state):
prev_angle, prev_point, prev_poly = prev_state
end_angle = dir_to_angle(prev_point[0])
radius = prev_point[1]
dis = get_dis(np.array([0, 0]), prev_point[0])
angle_range = ANGLE_SEARCH_MAX_RANGE
if dis > radius:
angle_range = min(angle_range, get_angle_dis... | This function determines the optimal next cutting angle for two contours by iteratively narrowing a search range. It evaluates candidate angles using geometric intersections and selects the angle with the best evaluation metric. The process updates the previous state with the new angle, a split point, and a spiral poly... | def angle_search_next_cut(cur_contour, next_contour, prev_state):
prev_angle, prev_point, prev_poly = prev_state
start_angle, end_angle, angle_range = get_angle_range(prev_state)
print(start_angle, end_angle, angle_range)
# Cut everything to this range
start_ray = dir_to_ray(angle_to_dir(start_angl... |
def normalize(self, x):
"""Standardization (Z-score Normalization) to
have zero mean & unit variance"""
return (x - np.mean(x, axis=0)) / np.std(x, axis=0)
def shuff_adjust(self, x, y):
"""shuffle dataset and assign to mini batches.
if dataset size is not a multiple of mini batch... | The code implements a training loop for a machine learning model using mini-batch gradient descent. It normalizes input data if specified, initializes weights with random values, and iterates over epochs to update model parameters. In each epoch, data is shuffled, split into batches, and weights are adjusted via the `w... | def fit(self, x, y, norm=False):
"""Fit training data.
Args:
x (array): shape = [n_examples, n_features]
Training vectors, where n_examples is
the number of examples and n_features is
the number of features.
y ... |
def fillList(self, store, n):
i = 0
while i < n:
store.append(i)
i += 1
return
def checkSol(self, a, n):
if self.totalHits(a, n) == 0:
return True
return False
def hitsMinConflict(self, b, n, index):
hits = 0
t = 0
i = 0... | The code implements the Min-Conflict algorithm to solve the N-Queens problem. It iteratively selects random columns, adjusts queen positions to minimize conflicts, and tracks moves until a valid solution is found. The algorithm resets the board if maximum steps are reached, ensuring a solution within specified iteratio... | def minConflict(self, b, n, iterations):
store = []
self.fillList(store, n)
randomCount = 0
movesTotal = 0
movesSolution = 0
row = 0
maxSteps = iterations
# The maximum steps that can be allowed to find a solution with this algorithm
while not self... |
def fillList(self, store, n):
i = 0
while i < n:
store.append(i)
i += 1
return
def isSolution(self, a, n):
if self.totalCollisions(a, n) == 0:
return True
return False
def collisionsMinConflict(self, b, n, index):
collisions = 0
... | The main task of this code is to solve the N-Queens problem using the Min-Conflict algorithm. It iteratively selects a random column, evaluates conflict-minimizing row positions for its queen, and updates the board until a valid solution is found. The algorithm tracks total moves, solution-related moves, and steps, ter... | def minConflict(self, b, n, iterations):
# This array list is for storing the columns from which a random column will be selected
# store = ArrayList()
store = []
self.fillList(store, n)
randomCount = 0
movesTotal = 0
movesSolution = 0
row = 0
maxS... |
def fillList(self, store, n):
i = 0
while i < n:
store.append(i)
i += 1
return
def isSolution(self, a, n):
if self.totalCollisions(a, n) == 0:
return True
return False
def collisionsMinConflict(self, b, n, index):
collisions = 0
... | This code implements the Min-Conflict algorithm without restarts to solve the N-Queens problem. It iteratively selects random columns, evaluates conflicts, and adjusts queen positions to minimize conflicts until a valid solution is found. It tracks total moves, solution-related moves, and prints the board configuration... | def minConflictwithoutrestart(self, b, n, iterations):
# This array list is for storing the columns from which a random column will be selected
store = []
self.fillList(store, n)
randomCount = 0
movesTotal = 0
movesSolution = 0
global successmoves, failuremoves,c
... |
def _sort_files_in_path(self, path: str) -> dict:
sorted_files: dict = {}
extensions = self.extensions_to_folders()
for p in get_all_files_in_path(path):
the_file: pathlib.Path = pathlib.Path(p)
parent_folder: pathlib.Path = the_file.parent
grouped_folder = ex... | This function recursively sorts files and subdirectories within a given path, collecting results into a dictionary. It processes the specified directory, sorts its contents, and if levels > 0, recursively applies the same operation to subfolders with reduced depth, stopping when levels reach zero. | def _sort(self, path: str, levels: int = 0) -> dict:
sorted_files: dict = {}
if os.path.exists(path) and os.path.isdir(path):
sorted_files.update(self._sort_files_in_path(path))
# Base case so we stop going thorugh folders at some point
if levels != 0:
... |
def extensions_to_folders(self) -> dict:
if self._extensions_to_folders is None:
self._extensions_to_folders = _make_extension_to_folder_object(
self.extensions
)
return self._extensions_to_folders
def _create_config_file(contents=DEFAULT_EXTENSIONS) -> None:
... | The main task of the code is to organize extensions by their associated folders, store this mapping in a configuration file using `_create_config_file`, and subsequently reload the extensions. It groups extensions into folder-specific lists, writes the structure to a config file, and triggers a reload to apply the upda... | def _save_extensions(self) -> None:
data = defaultdict(list)
for ext, folder in self.extensions_to_folders().items():
data[folder].append(ext)
_create_config_file(data)
self._reload_extensions() |
def run_tests():
ex1 = [["R75","D30","R83","U83","L12","D49","R71","U7","L72"],
["U62","R66","U55","R34","D71","R55","D58","R83"]]
ex2 = [["R98","U47","R26","D63","R33","U87","L62","D20","R33","U53","R51"],
["U98","R91","D20","R16","D67","R40","U7","R15","U6","R7"]]
assert find_closest... | The main task of the code is to process input from a file containing wire movement commands, split them into paths, and compute two results: (1) the closest collision point between two wires and (2) the collision point requiring the fewest steps to reach. The code reads the input twice—once for each part—executing sepa... | def main():
# Run examples provided in question
run_tests()
print("Part 1")
with open("03_crossed_wires/input.txt", "r") as f:
lines = [line.split(",") for line in f]
print(find_closest_collision(lines))
print("Part 2")
with open("03_crossed_wires/input.txt", "r") as f:
... |
def run_tests():
assert increasing_with_adjacent_digits(111111) == True
assert increasing_with_adjacent_digits(223450) == False
assert increasing_with_adjacent_digits(123789) == False
assert increasing_with_adjacent_digits(112233) == True
assert increasing_with_distinct_adjacent_digits(112233) == T... | The code processes a range of numbers from an input file to count valid passwords based on digit patterns. In **Part 1**, it counts numbers with **non-decreasing digits** and at least one adjacent pair (e.g., 11234). In **Part 2**, it counts numbers with **non-decreasing digits** and **exactly one pair of adjacent equa... | def main():
# Run examples provided in question
run_tests()
print("Part 1")
with open("04_secure_container/input.txt", "r") as f:
num_passwords = 0
range_start, range_end = tuple(f.read().split("-"))
for i in range(int(range_start), int(range_end)):
if increasing_wit... |
def run_tests():
assert run_intcode([1, 0, 0, 0, 99]) == [2, 0, 0, 0, 99]
assert run_intcode([2, 3, 0, 3, 99]) == [2, 3, 0, 6, 99]
assert run_intcode([2, 4, 4, 5, 99, 0]) == [2, 4, 4, 5, 99, 9801]
assert run_intcode([1,1,1,4,99,5,6,0,99]) == [30,1,1,4,2,5,6,0,99]
def run_intcode(intcode):
idx = 0
... | The main task of the code is to execute two parts of a "Program Alarm" problem. Part 1 reads input data, modifies specific values (noun/verb) to fix error code 1202, and runs an intcode program to output a result. Part 2 reads the same input, searches for noun/verb pairs that produce the target output 19690720, and pri... | def main():
# Run examples provided in question
run_tests()
print("Part 1")
with open("02_program_alarm/input.txt", "r") as f:
intcode = list(map(int, f.read().split(",")))
# Dealing with Error Code 1202
intcode[1] = 12
intcode[2] = 2
print(run_intcode(intcode)[0... |
def isvalid (self , IPString) :
i=0
for x in IPString.split('.') :
i += 1
if not 255 > int(x) >= 0 :
return False
if i == 4 and x == 0 :
return False
return True
def __iter__ (self) :
self.cache = self.start if self.cache == None else self.cache
return self
def __next__ (self) :
register = ... | This code initializes an object to iterate through IP address ranges. It validates Start/End inputs, splits them into integer components, sets up iterators for each octet, and adjusts the last octet's range if the first three octets differ. It prepares for generating IP addresses in the specified range by configuring i... | def __init__(self, Start , End):
if not (self.isvalid(Start) and self.isvalid(End)) :
raise ValueError
self.start = [int(x) for x in min(Start , End).split ('.')]
self.end = [int(x) for x in max(Start, End ).split ('.')]
self.used = set({})
self.iterlist = [None,None,None,None]
self.cache = None
self.E... |
def _get_request_element_list(self, request_string):
"""@brief Get a list of request elements.
@param request_string The string containing the HTTP request.
@return A list of strings that compose the HTTP request."""
return request_string.split()
def is_get_request(self, request_el... | This code handles HTTP client requests by parsing GET/POST requests, serving appropriate files (e.g., HTML pages), processing WiFi configuration data from POST requests, and triggering a reboot when new WiFi settings are saved. It manages client connections, reads request headers/body, validates data, writes configurat... | def _serve_client(self, reader, writer):
self._uo.debug("Client connected")
reboot = False
request_line = await reader.readline()
# Get a list of the elements in the HTTP request.
request_elements = self._get_request_element_list(request_line.decode())
self._uo.debug("r... |
def _scroll_output(self, direction):
"""Scroll the output pad.
Args:
direction: _SCROLL_REFRESH, _SCROLL_UP, _SCROLL_DOWN, _SCROLL_HOME or
_SCROLL_END
Raises:
ValueError: On invalid scroll direction.
"""
if not self._output_pad:
# No output pad is present. Do nothing.
... | This function displays a list of candidates (e.g., tab-completion options) as formatted, wrapped text on multiple lines. It refreshes the screen if needed, limits the number of displayed lines, and positions the candidates vertically on the screen using calculated row offsets and text wrapping to fit the available widt... | def _display_candidates(self, candidates):
"""Show candidates (e.g., tab-completion candidates) on multiple lines.
Args:
candidates: (list of str) candidates.
"""
if self._curr_unwrapped_output:
# Force refresh screen output.
self._scroll_output(self._SCROLL_REFRESH)
if not cand... |
def _scroll_output(self, direction):
"""Scroll the output pad.
Args:
direction: _SCROLL_REFRESH, _SCROLL_UP, _SCROLL_DOWN, _SCROLL_HOME or
_SCROLL_END
Raises:
ValueError: On invalid scroll direction.
"""
if not self._output_pad:
# No output pad is present. Do nothing.
... | This method handles keypress events in a text box, translating certain keys (like Enter/Tab) into termination signals to exit editing. It manages screen scrolling (PgUp/PgDown, Home/End), command history navigation (Up/Down arrows), and terminal resize responses by refreshing layouts. It updates internal state for comm... | def _on_textbox_keypress(self, x):
"""Text box key validator: Callback of key strokes.
Handles a user's keypress in the input text box. Translates certain keys to
terminator keys for the textbox to allow its edit() method to return.
Also handles special key-triggered events such as PgUp/PgDown scrollin... |
def _screen_create_command_textbox(self, existing_command):
"""Create command textbox on screen.
Args:
existing_command: (str) A command string to put in the textbox right
after its creation.
"""
# Display the tfdbg prompt.
self._stdscr.addstr(self._max_y - self._command_textbox_heig... | The code implements a command-line UI loop that continuously processes user input, manages command history, handles tab completion, and dispatches commands. It retrieves existing commands from history or pending input, captures user input with terminators (e.g., Enter, Tab), and returns an exit token upon command dispa... | def _ui_loop(self):
"""Command-line UI loop.
Returns:
An exit token of arbitrary type. The token can be None.
"""
while True:
# Enter history command if pointer is in history (> 0):
if self._command_pointer > 0:
existing_command = self._active_command_history[-self._command_p... |
def _screen_launch(self):
"""Launch the curses screen."""
curses.noecho()
curses.cbreak()
self._stdscr.keypad(1)
self._screen_create_command_window()
def _dispatch_command(self, command):
"""Dispatch user command.
Args:
command: (str) Command to dispatch.
Returns:
An exit... | This method initializes and runs a Curses-based CLI interface, executing an optional startup command, setting a customizable title with color, entering the main interaction loop, and returning an exit token after terminating the screen. | def run_ui(self, init_command=None, title=None, title_color=None):
"""Run the Curses CLI.
Args:
init_command: (str) Optional command to run on CLI start up.
title: (str) Optional title to display in the CLI.
title_color: (str) Optional color of the title, e.g., "yellow".
Returns:
A... |
def download(
url: typing.Union[str, urllib.request.Request], output_path: PathLike, force=False
) -> http.client.HTTPResponse:
"""Download a file from `url` and save to `output`.
Parameters
----------
url : str or `urllib.request.Request`
URL from which to download.
output_path : Path-... | The function `bed_to_fasta_to_one_hot` converts BED files (positive and negative reads) into one-hot encoded sequences. It downloads BED files, filters reads by length, extracts sequences using a reference genome, and avoids overlaps between positive and negative datasets. The output is two `_ProcessingOutput` objects ... | def bed_to_fasta_to_one_hot(
dataset_dir: PathType,
positive_bed_url: str,
negative_bed_url: str,
reference_genome_fasta: PathType,
max_read_length: int,
new_read_length: int,
alphabet="ACGT",
nonsense_letters="N",
bedtools_exe: PathType = "bedtools",
) -> typing.Tuple[_ProcessingOut... |
def direct_fetch(article_id):
"""
Requirement # 1 : Fetch an article by its identifier
:param article_id:
:return:
"""
return fetch_by_id(article_id)
def search_index(word):
"""
Search the index that we have built
:param word:
:return: A list of article Id's matching the word
... | The main task of the code is to process a query by checking if the first word is a typo in 'article' (Requirement #1), directly fetching results for the second word if so. Otherwise, it searches each query word, aggregates results, and ranks them. The function handles typo correction and result aggregation/ranking for ... | def build_results(query):
query_words = query.split(' ')
results_from_index = []
for i, word in enumerate(query_words):
if i == 0 and word in typo_dict['article']:
# Requirement # 1
return direct_fetch(query_words[1])
results_from_index.append(search_index(word))
... |
def data_preprocessing():
df = data()
for i in df.index:
# Recode Target Variable
df.loc[i, 'Survived'] = -1 if df.loc[i, 'Survived'] == 0 else 1
# Recode Gender Covariate
df.loc[i, 'Sex'] = 0 if df.loc[i, 'Sex'] == 'male' else 1
# Drop Name Covariate
df.drop(columns = 'N... | The code evaluates the performance of a classifier (likely AdaBoost-like) by varying the number of weak learners (M). It computes accuracy and error for each M, stores results in a DataFrame, and plots error vs. M. The final predictions for the largest M are returned. | def predict(self):
y, X = data_preprocessing()
M_arr = [5, 10, 20, 50, 100]
accs = pd.DataFrame(index = range(len(M_arr)), columns = ['M', 'Accuracy', 'Error'])
for M, i in zip(M_arr, range(len(M_arr))):
# Fit Stump Classifiers
clfs, errors = self.fit(M)
... |
def __calculate_transition(self, action):
if self.is_done():
return self.__state
# 1. change the state to reflect the move by the agent,
# 2. merge same value tiles
# swipe to left
if action == Action.Left:
self.__state = self.swipeToLeft(self.__state)
... | The code defines a `step` method that executes an action, updates the environment's internal state, checks if the episode is done, calculates the reward based on the new state, and returns the observation, termination status, reward, and optional info. | def step(self, action):
old_state = self.__state
# state after agent action
self.__state = self.__calculate_transition(action)
observation = self.__state # environment is fully observable
done = self.is_done()
reward = self.get_reward(self.__state)
info = {} # o... |
def determinant(m: list):
if(len(m) == 1):
return m[0][0]
else:
det = 0.0
for i in range(0, len(m[0])):
minor = []
minor = m
getMinor(minor, 0, i)
det += pow(i, -1)*m[0][i]*determinant(minor)
def cofactors(m: list, cof: list):
zeroes(co... | The code computes the inverse of a matrix using the adjugate method. It calculates the determinant, checks for invertibility, computes cofactors, transposes them to form the adjugate matrix, and scales it by the reciprocal of the determinant to obtain the inverse matrix, storing the result in `minv`.) | def inverseMatrix(m: list, minv: list):
print("Iniciando calculo de inversa...")
cof, adj = []
print("Calculo de determinante..")
det = determinant(m)
if(det == 0):
exit()
print("Iniciando calculo de cofactores...")
cofactors(m, cof)
print("Calculo de adjunta...")
transpose(c... |
def input(self):
"""Process all our inputs"""
self.events = pygame.event.get()
self.keys = pygame.key.get_pressed()
for event in self.events:
if event.type == pygame.QUIT:
self.isRunning = False
if event.type == pygame.KEYDOWN:
if ... | The code defines a game loop that runs while `isRunning` is true. It calculates delta time for frame-rate independence, processes input, updates game logic, and renders the game state in each iteration, ensuring smooth and consistent gameplay. | def run(self):
"""Run our game app"""
while self.isRunning:
self.deltaTime = self.clock.tick() / 1000
self.input()
self.update()
self.draw() |
def run_filter(img, filt):
if filt == "grayscale":
filt_img = grayscale(img)
elif filt == "binthres":
filt_img = binthres(img)
elif filt == "otsu":
filt_img = otsu(img)
else:
filt_img = img
return filt_img
def easyocr_text_pred(img, hths, wths):
reader = easyocr.R... | The main task of the code is to process an image by rescaling, applying a filter, detecting text regions using EasyOCR, reconstructing coordinates, adjusting for slant and scale, and returning final text coordinates. It combines image processing, OCR, and geometric adjustments to locate and refine text positions in the... | def get_coordinates(img_path, filt, hths, wths, slant):
scale = 2
im = cv2.imread(img_path)
im = rescale(im, scale, scale)
filt_img = run_filter(im, filt)
height, width, _ = im.shape
eocr_pred_set = easyocr_text_pred(filt_img, hths, wths)
coords_eocr = recons_eocr_coords(eocr_pred_set, wid... |
def flip(is_on_auto):
return not is_on_auto
def sp(pp):
if debug is True:
global spnum
spnum = int(spnum) + 1
print(pp)
print(". . . . . . . . . . . . .")
else:
pass
def measure_average():
# This function takes 3 measurements and
# returns the average.
dis... | The code toggles an "automode" state, enabling or disabling autonomous obstacle avoidance. When enabled, it continuously measures distance; if too close, the robot stops, randomly turns left/right, and retreats. If distance is too far, it moves forward. The function switches automode status and updates feedback message... | def automodeon():
global is_on_auto
is_on_auto = flip(is_on_auto)
if is_on_auto is True:
var.set("Automode disabled!")
sp("Automode disabled!")
else:
var.set("Automode enabled!")
sp("Automode enabled!")
while is_on_auto is False:
avgdistance = 0
... |
def _validate_schema(self, schema):
required_fields = ["type", "title", "description"]
for field in required_fields:
if getattr(schema, field) is None:
raise ValidationError(field, schema)
if schema.type == "array":
if not schema.item_schema:
... | This function converts a schema object into markdown documentation by generating headings, info blocks, example code blocks, and a property table. It validates the schema, logs progress, and structures content using markdown elements like tables and admonitions for clarity and documentation purposes. | def schema_object_to_md(self, schema, md, queue):
n = len(schema.raw_properties)
self.logger.info(f"Building '{schema.path}' ({n} {'property' if n==1 else 'properties'})")
self._validate_schema(schema)
md.push_heading(2, schema.title, id=self._schema_fragment(schema, section=True))
... |
def _validate_schema(self, schema):
required_fields = ["type", "title", "description"]
for field in required_fields:
if getattr(schema, field) is None:
raise ValidationError(field, schema)
if schema.type == "array":
if not schema.item_schema:
... | This function converts a JSON schema's `oneOf` definitions into a markdown table, handling special cases where entries are constants or single-property objects. It validates schemas, logs progress, and structures the output with headings, info blocks, and tables, appending results to the markdown document. | def schema_oneOf_to_md(self, schema, md, queue):
n = len(schema.oneOf)
self.logger.info(f"Building '{schema.path}' ({n} oneOf entries)")
self._validate_schema(schema)
md.push_heading(2, schema.title, id=self._schema_fragment(schema, section=True))
info_block = self._info_block(... |
def _validate_schema(self, schema):
required_fields = ["type", "title", "description"]
for field in required_fields:
if getattr(schema, field) is None:
raise ValidationError(field, schema)
if schema.type == "array":
if not schema.item_schema:
... | The code converts a JSON schema file into Markdown documentation by traversing schema elements via a queue, handling different schema types (e.g., `oneOf`, `object`), adding metadata, and writing the generated Markdown to a file if an output path is provided. | def render_md(self, schema_path, output_path, title=None):
self.logger.info(f"Processing schema '{schema_path}'")
schema_path = Path(schema_path)
self.schema = JSONSchema.from_file(schema_path)
self.blocks = Queue()
self.visited = set()
md = MDWriter()
schema_... |
def turtle_tracks(n,p,tw,s,l):
turtle.ht()
for i in range (n+1):
turtle.penup()
turtle.goto(s,p)
turtle.pendown()
turtle.fd(l)
p=p-tw
def start_line(x,y,l):
turtle.ht()
turtle.penup()
turtle.goto(x,y)
turtle.rt(90)
turtle.pendown()
turtle.fd(l)
def... | This code simulates a multi-turtle racing game using Python's turtle module. It sets up a race track with start/finish lines, creates 'n' turtles with random colors, positions them, and animates their movement until they cross the finish line. The code calculates screen dimensions, handles turtle scaling, and manages r... | def race(n,l):
xwin=1500
ywin=xwin/2
tw=24
b=4
ax=0
ay=0
lt=l+3*tw
s=-(lt/2)+tw
fin=lt/2-2*tw
y=tw*(n/2)
yr=y-(tw/2)
sq=tw/b
ls=n*tw
lf=int(n*tw/sq)
st=s-tw
xworld_base=l+b*tw+tw
yworld_base=n*tw+tw
if (xworld_base/xwin)>(yworld_base/ywin):
... |
def world_scale(xwin,ywin,xworld_base,yworld_base):
if (xworld_base/xwin)>(yworld_base/ywin):
xworld=xworld_base
C_yworld=(xworld/xwin)-(yworld_base/ywin)
yworld=yworld_base+C_yworld*ywin
elif (xworld_base/xwin)<(yworld_base/ywin):
yworld=yworld_base
C_xworld=(yworld/ywin... | This function creates an interactive turtle racing game where users control a turtle against AI opponents. It sets up tracks, start/finish lines, and randomizes AI movement based on difficulty. The game displays rankings, adjusts difficulty dynamically, and includes a replay option with yes/no buttons. | def race(turtle_name,racer_color,n,l,difficulty):
turtle.colormode(cmode=255)
turtle.delay(0)
turtle.speed(0)
xwin=1500
ywin=xwin/2
tw=24
b=4
ntot=n+1
lt=l+3*tw
s=-(lt/2)+tw
fin=lt/2-2*tw
y=tw*ntot
yr=y-(tw/2)
ax=0
ay=y+2*tw
y_title=ay+1.5*tw
sq=tw/b
... |
def _get_timestamp() -> str:
timestamp = datetime.now()
return timestamp.strftime('%d_%m_%Y_%H_%M')
def _get_schedules(self, urls: list[str], check_new_matches: bool, timestamp: str = None):
self._matches.clear()
print(f"Start parsing {len(urls)} pages of schedules...")
self._mat... | The code retrieves schedule data and statistics based on parameters. It fetches URLs for schedules (either all or last updates) and uses them to get schedule details. If matches are found, it retrieves statistics for those matches. The `use_timestamp` determines timestamp inclusion, while `update_only` controls whether... | def get(self, use_timestamp: bool = True, update_only: bool = False):
timestamp = self._get_timestamp() if use_timestamp else None
if update_only:
urls = self._url_maker.get_last_schedule_urls()
else:
urls = self._url_maker.get_schedule_urls()
self._get_schedules... |
def get_connections(tiles):
edges = {name: set(frozenset((edge,edge[::-1])) for edge in get_edges(tile))
for name, tile in tiles.items()}
conn = dict()
for tile in edges:
for other in edges:
if len(edges[tile] & edges[other]) == 1:
conn[tile] = conn.get(tile, set()) | {ot... | The code stitches together tiles into a larger image by connecting them based on edge compatibility. It starts with one tile, iteratively finds and attaches adjacent tiles using orientation permutations, and tracks their positions. After aligning all tiles, it trims borders and combines them into a grid, returning the ... | def stitch(tiles):
tiles = {n:tuple(map(tuple, tile)) for n, tile in tiles.items()}
conn = get_connections(tiles)
done = [next(iter(tiles))]
pos = {(0,0): done[0]}
for tile in done:
todo = {other for other in conn[tile] if other not in done}
own_edges = get_edges(tiles[tile])
x, y ... |
def stitch(tiles):
tiles = {n:tuple(map(tuple, tile)) for n, tile in tiles.items()}
conn = get_connections(tiles)
done = [next(iter(tiles))]
pos = {(0,0): done[0]}
for tile in done:
todo = {other for other in conn[tile] if other not in done}
own_edges = get_edges(tiles[tile])
x, y ... | The code's main task is to count the number of monster patterns in a stitched grid across all possible orientations, then subtract this count from the grid's size. It stitches input data into a complete grid, generates all possible monster positions, checks each orientation of the grid for monster matches, and returns ... | def part_2(data):
complete = stitch(data)
size = max(len(complete), len(complete[0]))
monster = get_monster()
monsters = [{complex(i,j) + x for x in monster}
for i in range(size) for j in range(size)]
count = 0
for perm in orient(complete):
if count: break
grid = to_grid(per... |
def question_visit_recurse(start, link_count):
global visited
visited.append(start)
if link_count == 0:
yield [start]
if start in data_properties_by_subject_by_predicate.keys():
for p in data_properties_by_subject_by_predicate[start]:
yield [start, p]
else:
... | This function generates natural language questions from entity-predicate chains by recursively traversing linked data. It constructs questions by alternating entities and predicates, handling inverse relationships and chain length constraints. The output includes both the generated question and the underlying data chai... | def question_generation_wrapper(start_node, link_count):
global visited
visited = []
for question_chain in question_visit_recurse(start_node, link_count):
question = 'What '
i = len(question_chain) - 1
if len(question_chain) <= 1:
# one chains are pointless, we just us... |
def copy_genotypes(self, genotypes):
"""
Copies a set of genotypes
"""
copys = []
for genotype in genotypes:
copys.append(genotype.copy())
return copys
def get_profiles(self, genotypes):
profiles = [genotype.profile for genotype in genotypes]
r... | The main task of the code is to calculate the fitness values for a set of genotypes by processing them in batches. It copies genotypes, slices models into G-code files using external tools, and queries fitness scores from an HCI interface. The function returns a list of fitness values corresponding to the input genotyp... | def ascertain_fitness(self, genotypes):
"""
Gets the fitnesses for a set of genotypes
"""
num_models = len(self.model_paths)
copy_genotypes = self.copy_genotypes(genotypes)
fitnesses = []
path_to_print_exe = '/examples/print_gcode_file.py'
while len(copy_g... |
def dump(self) -> None:
echo("")
m = self.measures
for key in sorted(m):
echo(f"{key}:{m[key]}")
echo("")
return
def bom(self) -> None:
jl = self.measures["jamb.length"]
js = self.measures["jamb.side"]
jt = self.measures["jamb.thickness"]... | This code initializes an object with given measures, setting up a model by sequentially executing methods like dump(), bom(), build(), and others to process and construct components such as jamb parts and ribs. | def __init__(self,measures) -> None:
self.model = None
self.measures = measures
self.dump()
self.bom()
self.build()
self.jamb_broad()
self.jamb_small()
self.jamb_jig()
self.rib_short()
return |
def _create_resourcegroup(cli_ctx, resource_group_name, subscription_id, location, delay=2):
# Create RG
hook = cli_ctx.get_progress_controller(True)
hook.add(message='Waiting for create resource group', value=0, total_val=1.0)
logger.info('Waiting for create resource group')
for x in range(0, 10):
... | The main task of the code is to create an Azure resource group, a virtual network (VNet), and assign two role assignments ("ARO v4 Development Subnet Contributor") to specified client IDs for subnet management within the VNet. It returns `True` if all operations succeed, otherwise `False`. The function sets up infrastr... | def _create_vnet_resourcegroup(cli_ctx, cluster_name, resource_group_name,
subscription_id,
location,
provider_client_id,
cluster_client_id,
delay=2):
#az group ... |
def _get_rg_location(ctx, resource_group_name, subscription_id=None):
groups = cf_resource_groups(ctx, subscription_id=subscription_id)
# Just do the get, we don't need the result, it will error out if the group doesn't exist.
rg = groups.get(resource_group_name)
return rg.location
def _create_vnet_reso... | This function creates an OpenShift cluster with specified configurations, handling VNET creation/validation, default parameter setup, and deploying via Azure client. It validates subnets, sets defaults for CIDRs, VM sizes, and worker counts, then constructs an OpenShiftCluster object to initiate deployment. | def aro_preview_create(cmd, client, resource_group_name, resource_name,
client_id,
client_secret,
pod_cidr=None,
service_cidr=None,
master_vm_size=None,
worker_vm_size=None,
... |
def clear():
print ('\n')
input ('Tekan enter untuk kembali ke menu utama!!!')
def lis_menu ():
daftar = ("""
1. \t Tambah barang
2. \t penjualan barang
3. \t melihat data
4. \t menghapus barang
""")
print (daftar)
def tambah_data():
os.s... | The main task of the code is to provide a menu-driven interface for managing data operations, including adding data, processing sales and payments, viewing records, deleting entries, and exiting. It loops until the user selects option 5, which displays a summary and terminates the program, while invalid inputs trigger ... | def menu_utama():
while True:
clear()
lis_menu()
menu = int(input('masukkan menu yang kalian pilih: '))
if menu == 1:
tambah_data()
elif menu == 2:
penjualan()
rekap_pembayaran()
elif menu == 3:
show()
elif menu ... |
def get_data(context, data):
valid_contracts = [contract for contract in context.contracts
if contract.start_date <= get_datetime() - pd.Timedelta(days=SLOW_MA+2)
and contract.end_date >= get_datetime()]
hist = data.history(valid_contracts,
... | The code processes trading signals by generating entries, rolls, and stops, then concatenates them into a signals DataFrame. It processes these signals to determine positions and stops, optimizes the portfolio if signals exist, and executes trades based on the optimized portfolio and stops. | def handle_data(context, data):
get_data(context, data)
# generate and process trading signals
entries = get_entries(context)
rolls = get_rolls(context)
stops = get_stops(context)
signals = pd.concat([entries, rolls, stops])
positions, stops = process_signals(context, signals)
# optimi... |
def create_music_db():
"""Creates the music database and all of its tables"""
# Open a connection to the database.
con = sqlite3.connect(db_path)
# Get a Cursor object that can be used to run SQL queries on the database.
cur = con.cursor()
# Define an SQL query that creates a table... | The main task of the code is to create a music database with tables and populate it with sample data, including albums, songs, and playlists, to establish a structured music library for further operations. | def main():
# Create the database and its tables
create_music_db()
# Add some data to the DB
populate_albums()
populate_songs()
populate_playlists()
return |
def fCount(Y):
countItem1 = 0
countItem2 = 0
item1Label = None
item2Label = None
if len(Y) != 0:
item1Label = Y[0]
for item in Y:
if item == item1Label:
countItem1 += 1
else:
countItem2 += 1
if item2Label == None:
... | This function recursively builds a decision tree by selecting the feature with maximum information gain to split data, creating left/right child nodes, and assigning class labels to leaf nodes when further splitting isn't needed. | def buildBranch(self, X, Y, curr_node, depth):
item1Count, item2Count, item1Label, item2Label = fCount(Y)
if depth >= 1 and item2Count != 0:
curr_node.left = DecisionTreeNode(None)
curr_node.right = DecisionTreeNode(None)
maxBenefit = 0
... |
def setup():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(MOTOR1_F, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(MOTOR1_B, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(MOTOR2_F, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(MOTOR2_B, GPIO.OUT, initial=GPIO.LOW)
print("Finished set up...")
def lcd_init():
# Initialize... | The main task of the code is to initialize hardware components (LCD display and GPIO pins) and activate two motors to move forward by setting specific GPIO outputs to HIGH/LOW, while printing status messages to the console and displaying "MOTOR forward" on the LCD. | def main():
print("Start...")
setup()
# Initialize lcd display
lcd_init()
# lcd_string("Hello", LCD_LINE_1)
# lcd_string(" RPC", LCD_LINE_2)
# time.sleep(2)
# lcd_string("Provided by", LCD_LINE_1)
# lcd_string("PICason", LCD_LINE_2)
# time.sleep(2)
GPIO.output(MOTOR1_B, GPIO.LOW)
GPIO.output(MOTOR2_B, GPIO... |
def initializeExperiment(ser, expLength, expVolt, logFile=None,
timeFmtStr='%m/%d/%Y %H:%M:%S.%f'):
"""Initializes the experiment on the DStat.
Correctly handles experimental times that are too long for DStat.for
VARIABLES:
ser: Serial port object for the DStat
expLength: ... | This function runs an experiment using a DStat device by initializing parameters, collecting current data over time, and logging results. It writes experimental settings and real-time measurements to a file, periodically reporting averaged current values. The process continues until the DStat sends a completion signal,... | def runExperiment(ser, expLength, gain, expVolt, logFile=None,
dataFile='Test', rptTime=300,
timeFmtStr='%m/%d/%Y %H:%M:%S.%f'):
"""Runs the experiment, specifically, it runs the experiment
initialization, and gathers data until the completion code is sent
by ... |
def getUri(self, file_name, root_dir = '*', sub_dir = '',
app_name = '', volume = 'external'):
fileUri = None
try:
if api_version < 29 and root_dir.lower() in ['downloads',
'download']:
return None
... | The code retrieves a file's path based on API version. For API >28, it constructs a URI and retrieves it. For older APIs, it locates the file directly, copies it to a new path if found, and returns the new location. The function handles file retrieval differently depending on the system's API level and storage configur... | def retrieve(self, file_name, root_dir = '*', sub_dir = '',
app_name = '', volume = 'external'):
result = ""
if api_version > 28:
uri = self.getUri(file_name, root_dir, sub_dir, app_name, volume)
result = self.retrieveUri(uri)
else:
# don't n... |
def delete(self, file_name, root_dir = '*' , sub_dir = '',
volume = 'external'):
success = False
try:
fileUri = self.getUri(file_name, root_dir, sub_dir, '', volume)
if fileUri:
context = mActivity.getApplicationContext()
context.get... | This method inserts a file into Android storage, handling API version differences. It deletes existing files, determines MIME type and directory paths, and uses MediaStore to insert the file. For API 29+, it uses RELATIVE_PATH; for older versions, it uses DATA field. It copies the file, updates media storage, and retur... | def insert(self, file_path, root_dir = '*', sub_dir = '',
volume = 'external'):
success = False
try:
volume = volume.lower()
if volume not in ['internal', 'external']:
volume = 'external'
if not exists(file_path) or not isfile(file_path)... |
def prepare_img_224(img_path):
img = load_img(img_path, target_size=(224, 224))
x = img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
return x
def car_categories_gate(img_224, model):
print("Validating that this is a picture of your car...")
out = model.predict(img_224)... | The code processes uploaded car images using a pre-trained model to classify damage types, calculate repair costs, and validate input. It checks for database errors, verifies images are of cars, handles classification errors, and logs results with timestamps, location data, and calculated prices into a database. | def engine(db , db_err):
csv_path = "./model/class_dict.csv" # path to class_dict.csv
model_path = "./model/EfficientNetB3-instruments-94.99.h5"
img_path = "./uploads/temp_image"
response = {
'created_at': None,
'updated_at': None,
'deleted_At': None,
'error': None,
... |
def vm_remove_attached_disks(vm_name):
disks = attached_disks_UUIDs(vm_name)
if not disks:
return None
uuids=[]
hdd_keys=[]
pattern = r'(.*?)\(UUID:\s*(.+)\)$'
for k,v in disks.items():
match = re.match(pattern, v)
if match:
uuids.append(match.groups()[1])
... | The code deletes a VirtualBox VM named `vm_name` by first removing its attached disks, then unregistering the VM with `VBoxManage`. If `delete_disk` is True, it also deletes the associated disks. The function returns the command output. | def vm_delete(vm_name, delete_disk):
vm_remove_attached_disks(vm_name)
cmd = f'VBoxManage unregistervm --delete {vm_name}'
output = execute(cmd)
if delete_disk:
output = disk_delete(vm_name)
return output |
def vm_list(name=None):
if None == name:
cmd_all = f'vboxmanage list vms'
cmd_running = f'vboxmanage list runningvms'
output_all = execute(cmd_all)
output_running = execute(cmd_running)
vms_all = output_all.split('\n')
vms_running = output_running.split('\n')
... | This code defines a command-line interface (CLI) tool for managing VirtualBox VMs. It parses arguments like VM name, OS type, disk size, and action (create/list/delete/start/stop/modify) to execute corresponding VM operations. The tool interacts with VirtualBox via functions like vm_create, vm_list, and vm_modify, enab... | def main():
parser = argparse.ArgumentParser(description="Create VirtualBox VM")
parser.add_argument('--name','-n', default=None)
parser.add_argument('--ostype', default='Ubuntu_64')
parser.add_argument('--vb_folder', default='/data/jmurray/virtualboxvms')
parser.add_argument('--size', default=vm_si... |
def linear_regression(X_train_pca, X_test_pca, y_train_pca, y_test_pca):
linear_regress_pca = LinearRegression()
linear_regress_pca.fit(X_train_pca,y_train_pca)
y_pred_pca = linear_regress_pca.predict(X_test_pca)
res_val_pca = []
for p, a in zip(y_pred_pca, y_test_pca):
res_val_pca.append([... | The code trains three regression models (linear regression, neural network, decision tree) on PCA-transformed features from a dataset to predict 'walltime', splitting data into training and test sets, then returns the trained models in a dictionary. | def train(dataset: str):
df_pca = dataset
feature_cols_pcs = [str(i) for i in range(0,12)]
label_pca='walltime'
X_pca = df_pca[feature_cols_pcs] # Features
y_pca = df_pca[label_pca] # Target variable
X_train_pca, X_test_pca, y_train_pca, y_test_pca = train_test_split(X_pca, y_pca, test_size=0.... |
def linear_regression(X_train_pca, X_test_pca, y_train_pca, y_test_pca):
linear_regress_pca = LinearRegression()
linear_regress_pca.fit(X_train_pca,y_train_pca)
y_pred_pca = linear_regress_pca.predict(X_test_pca)
res_val_pca = []
for p, a in zip(y_pred_pca, y_test_pca):
res_val_pca.append([... | The code trains multiple regression models (linear, neural network, decision tree) on PCA-transformed features from a dataset, splits data into training/test sets, evaluates models, and returns a dictionary of trained models along with a DataFrame containing evaluation metrics. | def train(dataset):
df_pca = dataset
pca_number = -1
for key in df_pca.keys():
if key.isnumeric():
pca_number = max(pca_number, int(key))
feature_cols_pcs = [str(i) for i in range(0, pca_number + 1)] #NOTE MADE THIS DYNAMIC WITH PCA VALUE
targrt_column_list= ['epochs_times_one', ... |
def adjust_m1_m2(one, two):
if one[10] < two[10]:
model1 = one
model2 = two
else:
model1 = two
model2 = one
return (model1, model2)
def get_better_model(model1, model2):
# 0-UPP 1-MAE 2-MSE 3-MAPE
# 0-APP 1-TD 2-RM 3-VA 4-BVE 5-UPP 6-MAE 7-MSE... | The function identifies the optimal model for each application by comparing performance metrics across different TDS configurations, split values, and RM types. It iteratively selects better models at three levels: per TDRM combination (S1), per RM (S2), and overall (S3), updating a result DataFrame with flags indicati... | def better_model_per_application(PMsMain, TD_LIST, SPLIT_LIST, RM_List):
PMs = PMsMain.copy()
PMs_RES = PMs.copy()
PMs_RES["S1"] = ['-']*PMs.shape[0]
PMs_RES["S2"] = ['-']*PMs.shape[0]
PMs_RES["S3"] = ['-']*PMs.shape[0]
# print(PMs_RES.head())
PMs_level1 = []
better_va_perTDRM = []
f... |
def better_model_per_application(PMsMain, TD_LIST, SPLIT_LIST, RM_List):
PMs = PMsMain.copy()
PMs_RES = PMs.copy()
PMs_RES["S1"] = ['-']*PMs.shape[0]
PMs_RES["S2"] = ['-']*PMs.shape[0]
PMs_RES["S3"] = ['-']*PMs.shape[0]
# print(PMs_RES.head())
PMs_level1 = []
better_va_perTDRM = []
f... | The main task of the code is to select the optimal model by comparing a baseline model (trained on full-scale data) with a pipeline model (trained on filtered data splits). It filters data, evaluates models using specified splits and algorithms, compares their performance, and returns the better-performing model. The f... | def model_selector(dataframe):
dataframe = dataframe[dataframe['TDS']!="FS"] #without full scale
TD_LIST=["SD", "SD+n%FS"]
SPLIT_LIST=[10, 20, 25, 30, 40, 50] #TODO include all splits
RM_List=["NNR", "SLR", "DTR", "SVM"] #TODO change to model names
pipeline_r, res_gr = better_model_per_applica... |
def read_file(file_name):
""" Opens and reads the file. Returns the title, left-hand axis label and
the data values in the file.
Args:
file_name (str): File containing the data.
Raises:
FileNotFoundError: If file not found or is not readable, this exception is raised
Return:
... | The main task of the code is to read data from a file, process it into a dictionary, and generate a Sankey diagram visualization using the processed data. It handles input via command-line arguments or user input, validates file existence, processes data structure, and draws the graph in a window. Errors like invalid f... | def main():
# DO NOT EDIT THIS CODE
input_file = ""
args = sys.argv[1:]
if len(args) == 0:
input_file = input("Please enter the name of the file: ")
elif len(args) > 1:
print('\n\nUsage\n\tTo visualise data using a sankey diagram type:\
\n\n\tpy... |
def valid_cell(self, row, col):
""" Check if the desired cell is within the board's boundary and selected cell is empty """
if (0 <= row < self.row_size) & (0 <= col < self.col_size) & (self.board[row][col] == EMPTY):
return True
else:
return False
def check_movements(sel... | This function attempts to perform a player's move in a board game (likely Othello/Reversi) during the Minimax algorithm. It validates the move's coordinates, checks if the move is legally possible, executes the move by flipping opponent pieces, and switches turns if the opponent still has valid moves. It handles errors... | def move(self, row, col): # this function is only called in the Minimax class
""" Try to perform a movement to given cell
used only in Minimax algorithm
"""
player_ch = BLACK if self.turn == Player.BLACK.value else WHITE
opponent_ch = WHITE if self.turn == Player.BLACK.value ... |
def init_generation(self):
""" Generate initial generation (first population)
first generation is randomly selected """
for i in range(TOTAL_POPULATION):
random_list = [randint(MIN_WEIGHT, MAX_WEIGHT) for i in range(NUM_OF_FEATURES - 1)]
random_list.append(randint(MI... | The code runs a game across multiple generations, logs each generation's gene data, evolves to the next generation iteratively, and ultimately identifies and prints the optimal gene (best weight list) from the final generation. | def run(self):
""" runs the game for all desired generations
and prints the best gene in the final generation(the gene we are looking for)
logs each generation genes to a file
"""
# select the initial population
self.init_generation()
while self.gener... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.