dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_cursor():
dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL')
connection=cx_Oracle.connect(user='ESPN',password='espn',dsn=dsn_tns)
cursor=connection.cursor()
return cursor
def find_team_name(team_id):
cursor=get_cursor()
sql="select trim(team_name) from team where trim(team_id)=trim(:team_i... | This code retrieves and calculates the number of wins, losses, and draws for a specified cricket team in One Day International (ODI) matches by querying a database, analyzing match outcomes, and updating counters accordingly. | def odi_info(team_id):
cursor=get_cursor()
t_name=find_team_name(team_id)
print('..............................')
print('..............................')
print('team_name= '+t_name)
win={}
lose={}
draw={}
teams=get_all_teams()
for team in teams:
name=team.get('team_name')
print('Alllxxxxxxxxx'+name)
win... |
def get_cursor():
dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL')
connection=cx_Oracle.connect(user='ESPN',password='espn',dsn=dsn_tns)
cursor=connection.cursor()
return cursor
def find_team_name(team_id):
cursor=get_cursor()
sql="select trim(team_name) from team where trim(team_id)=trim(:team_i... | The function calculates the number of wins, losses, and draws for a given T20 team by processing all completed T20 matches. It retrieves match data, determines batting/bowling teams, compares scores, and updates result counters. The output is the win, loss, and draw counts for the specified team. | def t20_info(team_id):
cursor=get_cursor()
t_name=find_team_name(team_id)
print('..............................')
print('..............................')
print('team_name= '+t_name)
win={}
lose={}
draw={}
teams=get_all_teams()
for team in teams:
name=team.get('team_name')
print('Alllxxxxxxxxx'+name)
win... |
def get_cursor():
dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL')
connection=cx_Oracle.connect(user='ESPN',password='espn',dsn=dsn_tns)
cursor=connection.cursor()
return cursor
def get_teams_in_tournament(tournament_id):
dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL')
connectio... | This function retrieves tournament details from a database using the provided tournament ID, processes related data such as team information, top scorers, and player names, and prepares the information for rendering in a web template. It fetches tournament attributes, checks if the tournament has ended, formats specifi... | def user_tournament_details(request,tournament_id):
cursor=get_cursor()
sql="select * from tournament where trim(tournament_id)=trim(:tournament_id)"
cursor.execute(sql,{'tournament_id':tournament_id})
r=cursor.fetchone()
name=r[1]
format_=r[2]
prize_money=r[4]
mott=r[7]
award_money=r[8]
teams=get_teams_in_to... |
def get_cursor():
dsn_tns=cx_Oracle.makedsn('localhost','1521',service_name='ORCL')
connection=cx_Oracle.connect(user='ESPN',password='espn',dsn=dsn_tns)
cursor=connection.cursor()
return cursor
def odi_info(team_id):
cursor=get_cursor()
t_name=find_team_name(team_id)
print('..............................')
pri... | The main task of the code is to retrieve and display detailed information about a specific cricket team based on the provided team ID. It fetches team data from a database, calculates ODI and T20 match statistics (wins, losses, draws), computes total matches played, and renders the results in a template. The function p... | def team_details(request,team_id):
cursor=get_cursor()
sql="select * from team where trim(team_id)=trim(:team_id)"
cursor.execute(sql,{'team_id':team_id})
result=cursor.fetchone()
name=result[1]
type=result[2]
odi_win,odi_lose,odi_draw=odi_info(team_id)
odi_played=odi_win+odi_lose+odi_draw
t20_win,t20_lose,t... |
def parse_args(args):
args = args[1:]
parser = argparse.ArgumentParser(
description='A script to scan a flattened DEPS file using OSV API.'
)
parser.add_argument(
'--flat-deps',
'-d',
type=str,
help='Input flattened DEPS file.',
default=os.path.join(CHECKOUT_ROOT, 'deps_flat... | The code processes command-line arguments, parses OSV vulnerability scans from a dependencies file, converts them into SARIF format for security reporting, and writes the output to a specified file, enabling integration with static analysis tools for vulnerability detection. | def main(argv):
args = parse_args(argv)
osv_scans = parse_deps_file(args.flat_deps)
write_sarif(osv_scans, args.output)
return 0 |
def get_Asvd(self):
'''
Get the action due to Truncated SVD algorithm
'''
U, Sigma, Vt = self.get_U_Sigma_Vt()
X_refilled = np.matmul(np.matmul(U, np.diag(Sigma)), Vt)
# Assign very negative number to items that have been seen by users.
# So that they won't be pi... | The function `fill_A` selects an action from either a greedy policy (`A_greedy`) or a random policy (`A_rand`) using an ε-greedy strategy. With probability `1-eps`, it chooses the greedy action; with probability `eps`, it selects a random action. If `self.only_svd` is active, it uses a precomputed SVD-based action (`A_... | def fill_A(self):
'''
Choose one action from A_greedy and A_rand by chances 1-eps and eps respectively.
'''
if self.only_svd:
A_svd = self.get_Asvd()
self.A = t.IntTensor(A_svd).reshape(-1)
else:
_ = self.get_Agreedy()
A_greedy = pi... |
def quitgame():
pygame.quit()
quit()
def paused():
textFont = pygame.font.SysFont('comicsansms',100)
TextSurf, TextRect = text_objects("kloy 1.0", textFont)
TextRect.center = ((screen_width/2),(screen_width/4))
gameDisplay.blit(TextSurf, TextRect)
while pause:
for event in pygame.ev... | This code implements a game loop for a dodging game where the player controls an object to avoid falling obstacles. It handles user input for movement, updates obstacle positions, checks for collisions, and manages game states like pausing and crashing. The loop renders graphics, tracks dodged obstacles, and adjusts di... | def game_loop():
global pause
x = (screen_width * 0.45)
y = (screen_height * 0.8)
object_width = 100
object_position = 0
thing_x = random.randrange(0, screen_width)
thing_y = -600
thing_speed = 7
thing_width = 100
thing_height = 100
dodged = 0
gameExit = False
... |
def _reset_game_settings(self):
"""Reset the game settings."""
self.settings.initialize_dynamic_settings()
self.level_is_set = False
def _reset_game_stats(self):
"""Reset the game statistics."""
self.stats.reset_stats()
self.stats.game_active = True
se... | This function checks if the play button is clicked (via mouse position) and starts a new game if the game is inactive. It resets game settings, stats, screen, fleet, and ship; hides the mouse cursor; and plays button and background sounds to initiate gameplay. | def _check_play_button(self, mouse_pos=None):
"""Start new game when the player clicks Play."""
if mouse_pos:
button_clicked = self.play_button.rect.collidepoint(mouse_pos)
else:
button_clicked = True
if button_clicked and not self.stats.game_active: ... |
def _fire_bullet(self):
"""Create a new bullet and add it to the bullets group"""
if len(self.bullets) < self.settings.bullets_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
#Shoot sound FX
if self.stats.game_activ... | This function processes keypress events in a Pygame game. It updates ship movement (left/right), triggers bullet firing, exits the game with 'Q', and handles pause/resume logic with 'P'. It also sets a new high score before exiting. The core task is to translate keyboard inputs into game actions, managing player contro... | def _check_keydown_events(self, event):
"""Respond to keypress."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_SPACE:
self._fire_bullet()
... |
def _check_fleet_edges(self):
"""Responds appropiately if any aliens have reached an edge."""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
"""Respond to the ship being hit by an a... | The main task of the code is to update alien positions in a fleet by checking edges, updating their movement, detecting collisions between the player's ship and aliens (triggering a ship hit response), and checking if aliens reach the screen bottom (likely triggering game-over logic). The function manages alien behavio... | def _update_aliens(self):
"""Update the positions of all aliens in the fleet"""
self._check_fleet_edges()
self.aliens.update()
#Look for alien-ship collisions.
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
#Look... |
def _check_keydown_events(self, event):
"""Respond to keypress."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_SPACE:
self._fire_bullet()
... | This function handles keyboard and mouse events in a Pygame application. It exits the game on quit events, processes key presses/releases, and checks mouse clicks on buttons for level selection, play, or help based on the game state. | def _check_events(self):
"""Watch for keyboard and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pyg... |
def _check_events(self):
"""Watch for keyboard and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pyg... | The code runs the game's main loop, handling events, updating on-screen elements when not paused, pausing background music when paused, and rendering the screen repeatedly. | def run_game(self):
"""Start tha main loop for the game"""
while True:
self._check_events()
if not self.is_paused:
self._update_elements_on_screen()
else:
self.sound.pause_background... |
def startHeadlessBrowser(self):
if self.driver == None:
options = webdriver.ChromeOptions()
options.add_argument("headless")
desired_capabilities = options.to_capabilities()
self.driver = webdriver.Chrome(
desired_capabilities=desired_capabilities)... | The code's main task is to scrape category titles and URLs from a Shopee webpage. It launches a headless browser, navigates to the URL, clicks the "next" button in the category section, extracts category elements, and stores their titles and URLs in lists for further processing. | def get_category(self, response):
self.startHeadlessBrowser()
self.driver.get(self.url)
# Implicit wait
self.wait_in_seconds(100)
categoryNextBtn = self.driver.find_element_by_css_selector(
'.section-category-list .shopee-header-section__content .carousel-arrow.carous... |
def create_security_group(self):
SECURITY_GROUP_NAME = 'my-security-group-version-one'
print('Create security group')
try:
sec_groups = self.ec2.describe_security_groups(GroupNames=[ SECURITY_GROUP_NAME ])
self.security_group = sec_groups['SecurityGroups'][0]['GroupId']
... | The main task of the code is to orchestrate the setup of a distributed system by initializing multiple SubClusters in parallel using threads, configuring a load balancer, creating necessary rules, and waiting for all components to become healthy. It ensures synchronized initialization of cluster resources, load balanci... | def setup(self):
self.create_security_group()
threads = []
for cluster_nb, instance_type in enumerate(AmazonManager.INSTANCE_TYPE_LIST):
self.children.append( SubCluster(self, cluster_nb+1, instance_type) )
thread = threading.Thread(target=self.children[cluster_nb].setup... |
def create_instances(self):
print('Create 4 instances')
with open('flask_deploy.sh', 'r') as file:
script = file.read() % self.cluster_nb
tags = [
{ 'Key': 'Name', 'Value': f'{self.parent.batch_name}-{self.cluster_nb}-{self.instance_type}' },
{ 'Key': 'Batch... | (The main task of the code is to configure instances for a load balancer by creating instances, ensuring a target group exists, and registering those instances with the target group using AWS ELBv2. It handles errors by shutting down and re-raising exceptions if any step fails.) | def setup(self):
try:
self.create_instances()
self.create_target_group_if_needed()
# Reference: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.register_targets
targets = [ { 'Id': i... |
def makeClassifierPred(self):
if self.classifierModel is None:
import run_classifier
self.classifierModel = run_classifier
self.classifierModel.load_model(self.classifierName)
classes = self.classifierModel.run_model(self.openImg)
rs = []
for r in cla... | The main task of the code is to process video and image files by organizing them into groups, loading or creating annotations, and enabling user interaction for frame classification. It reads files, manages annotations, displays frames with annotations, and saves data. The script handles video frames, classifies images... | def runThrough(self):
allFiles = os.listdir(self.videosPath)
# get the videos from the files
self.videos = []
priorities = ["jpg", 'png']#"oct", "sep", "Aug", "july", "avi", "jun"]
groups = []
for i in range(len(priorities)+1):
groups += [[]]
... |
def compute_bias_metrics_for_model(dataset,
subgroups,
model,
label_col):
"""Computes per-subgroup metrics for all subgroups and one model."""
records = []
for subgroup in subgroups:
subgroup_rec... | This function computes and saves bias-performance metrics for multiple models on test and synthetic data. It calculates subgroup AUC, BPSN/BNSP AUC, and overall AUC for each model, combines them into final scores, and writes max/average values of these metrics to a text file for comparison analysis. | def bias_metrics_on_file(txt_path, test_df, syn_df, identity_terms, model_names, label_column):
"""
Compute metrics for bias-performance comparison and save them on file
:param txt_path: path to txt file to store results
:param test_df: dataframe containing predictions on test data (columns should corr... |
def compute_bias_metrics_for_model(dataset,
subgroups,
model,
label_col):
"""Computes per-subgroup metrics for all subgroups and one model."""
records = []
for subgroup in subgroups:
subgroup_rec... | The function computes and saves bias-performance metrics (e.g., AUC, subgroup bias) for multiple models on test and synthetic data, comparing their fairness across identity-related attributes (terms/tags). It calculates overall AUC, multimodal bias scores, and final combined metrics for each model, then writes maximum ... | def multilabel_bias_metrics_on_file(txt_path, test_df, syn_df, identity_terms, identity_tags, model_names,
label_column):
"""
Compute metrics for bias-performance comparison and save them on file
:param txt_path: path to txt file to store results
:param test_df: data... |
def compute_bias_metrics_for_model(dataset,
subgroups,
model,
label_col):
"""Computes per-subgroup metrics for all subgroups and one model."""
records = []
for subgroup in subgroups:
subgroup_rec... | The main task of the code is to compute and save bias-performance metrics for multiple models across text and image data using real and synthetic datasets. It calculates subgroup AUC, BPSN, and BNPS metrics, aggregates them into multimodal scores, and writes maximum, minimum, and average values for overall AUC and bias... | def multilabel_bias_metrics_on_file_BO(txt_path, test_df, syn_df, identity_terms, identity_tags, model_names,
label_column):
"""
Compute metrics for bias-performance comparison and save them on file. Deals with nan values generated by synthetic dataset
:param txt_path: p... |
def identity_element_presence(data, Identity_List, label_column):
"""return the elements present in the dataset in input.
Each element in the input list is returned if in the given dataset there are both positive and negative examples for that element"""
elements_present = []
for element in Identity_List:
i... | This function evaluates and compares the bias-performance of multiple models using test and synthetic data across 10 folds. It computes text/image bias metrics, calculates overall AUC, combines multimodal scores, and saves max/min/average results to a text file, handling NaN values and identity terms/tags. | def multimodal_bias_metrics_on_file_10Fold(txt_path, test_df, syn_df, identity_terms, identity_tags, model_names, label_column):
"""
Compute metrics for bias-performance comparison and save them on file. Deals with nan values generated by synthetic dataset
Allow to do deal with 10 fold execution on training... |
def getMNprobs(m,n,X):
MNcompos = composition(m,n)
logX = vlog(np.array(X))
logIs = np.array([0]+[log(k) for k in range(1,n+1)])
#such that log(k) = logIs[k]
Probs = {}
for K in MNcompos:
assert len(K) == len(X)
facKs = np.array([sum(logIs[:k+1]) for k in K])
K = np.array(K)
#print len(K),len(logX),len(fa... | The function calculates the probability of a specific configuration `k` by iterating over all combinations of elements from `X`, normalizing them, and aggregating probabilities from a helper function `getMNprobs`. It sums these probabilities weighted by combination counts and partitions of `k`, returning the normalized... | def getKprob(m,n,X,k,nofreq=False):
xProbs = {} ; Xpool={}
for mi in range(1,m):
for xi in itr.combinations(range(len(X)),r=mi):
x = [X[i] for i in xi]
xa = [X[i] for i in range(len(X)) if i not in xi]
xt = np.array(x+[sum(xa)])
xt = tuple(xt/sum(xt))
... |
def getMNprobs(m,n,X):
MNcompos = composition(m,n)
logX = vlog(np.array(X))
logIs = np.array([0]+[log(k) for k in range(1,n+1)])
#such that log(k) = logIs[k]
Probs = {}
for K in MNcompos:
assert len(K) == len(X)
facKs = np.array([sum(logIs[:k+1]) for k in K])
K = np.array(K)
#print len(K),len(logX),len(fa... | The code calculates the probability distribution for different values of `k` (from 1 to `n`) by iterating over all possible combinations of elements in `X`, normalizing them, and aggregating probabilities using combinatorial partitions. It generates subsets, computes their normalized sums, and uses these to derive prob... | def getFullKprobs(m,n,X):
xProbs = {}
Xpool={}
for mi in range(1,m):
for xi in itr.combinations(range(len(X)),r=mi):
x = [X[i] for i in xi]
xa = [X[i] for i in range(len(X)) if i not in xi]
xt = np.array(x+[sum(xa)])
xt = tuple(xt/sum(xt))
... |
def getPolyDen(spectfile):
g=[]; G=[]
with open(spectfile,'r') as spect:
l=spect.next()
l=l.strip().split('\t')
N=int(l[0]); s=float(l[1]); p=float(l[2])
print('Substitutions: %s ; polymorphisms: %s' %(s,p))
try:
assert s+p == 1
except:
print('s+p= %s + %s... | The function `initialize` processes allele frequency data from a spectrum file to compute log-probability values for different parameters. It reads the spectrum, determines the sample size, and constructs a data structure `Fx` storing log probabilities for each grid point in `xGrid` and `aGrid`. Depending on flags (`no... | def initialize(m,spectfile,xGrid,aGrid,MAF,nofreq,nosub):
#Read spect and get sample size
if nofreq:
print('Only using polymorphism/substitution calls. 0 for substitution, 1 for polymorphism.')
spec,logSpec,N = getPolyDen(spectfile)
#print(spec)
print('Sample size: %s'%(N))
... |
def getSpect(infile,spectfile,nosub=False,MAF=False):
Spect={}; numSites=0
if nosub:
print('Generating spectrum for all polymorphic sites. Substitutions (x=n or x=0) won\'t be considered.')
with open(infile,'r') as sites:
l=next(sites)
for l in sites:
(x,n... | The code processes genetic data by parsing command-line arguments to either generate allele frequency spectra or configuration files, or optimize parameters for likelihood ratio calculations. It reads input files, initializes data grids, and computes likelihood ratios over specified parameter ranges, outputting results... | def main():
#parsing arguments
parser = argparse.ArgumentParser()#usage='python %prog -i <input file> -o <output file> --spect <spect/config file> [--help] [--nofreq] [--nosub] [--MAF] [--getSpect] [--getConfig] [--fixSize] [--physPos] [--rec <recomb rate>] [-w <window size>] [--noCenter] [-s <step size>] [--r... |
def validate_solution(handle, problem_id, deadline):
latest_data = get_latest_submissions(handle, 20)
for submission in latest_data:
if safe_submission(submission):
if (
submission["creationTimeSeconds"] < deadline.timestamp()
and submission["verdict"] == "OK"... | The main task of the code is to validate a user's solution to a programming challenge, update their virtual rating based on the validation result and deadline status, and return whether the validation succeeded. It checks if the challenge is in progress, verifies the solution, retrieves problem details, calculates rati... | def validate_challenge(profile):
if not profile.in_progress:
return False
validate_result = validate_solution(
profile.handle, profile.current_problem, profile.deadline
)
contest_id, index = parse_problem_id(profile.current_problem)
contest_id = int(contest_id)
problem = Probl... |
def get_hardness(self, hardness, dataset, d_remove=None, d_add=None):
temp = dataset.copy()
if d_remove is None and d_add is None:
for pair1 in temp:
for pair2 in temp:
if pair1 != pair2:
hardness = hardness + self.get_similarity(pair1[0], pair2[1])
elif d_remove is not None and d_add is not No... | The code iteratively selects and refines batches of data from a set to maximize a "hardness" metric. It samples batches, adjusts elements to enhance hardness, updates the remaining data, and formats results. If an output file is specified, it saves the processed data as a JSON file. | def solve(self, batch_size, output_file=None):
U = set(self.data)
T = []
while U:
B = random.sample(U, batch_size)
if len(U) > batch_size:
hardness_B = self.get_hardness(0, B)
while True:
d_r = self.get_remove(B, hardness_B)
d_a = self.get_add(B, d_r, U, hardness_B)
hardness_B_tem = s... |
def check_versions(self):
try:
self._game_profile = next(
filter(lambda game_version: game_version.getVersionId() == self.game_version, self.game_versions))
except StopIteration:
print(f'Version {self.game_version} is not installed. You can use one of {self.game_v... | The main task of the code is to initialize a game environment using specified sources and game version, creating a game instance, validating versions, generating an idle world, and configuring target biomes based on command-line arguments. It handles errors related to unsupported versions or invalid sources by exiting ... | def __init__(self, amidst_sources, game_version: str = None):
try:
self.amidst_sources = amidst_sources
self._game_instance = GameInstance()
self.game_version = game_version or cli_arguments.game_version
self.game_versions = self._game_instance.game_versions
... |
def check_user_seeds(self):
for key, seed in enumerate(self._seeds):
try:
result = 'Found looked data!' if self.check_world(seed=seed.game_value) else '-'
self.save_result(iteration=key,
result=result,
... | The method iterates through seed numbers, checking each for valid world generation, saves results, and handles errors. It stops after a specified number of iterations, exiting on memory issues or other exceptions. | def search_seeds(self):
print('Found seeds:')
if self._seeds:
self.check_user_seeds()
return
for i in count():
if i == cli_arguments.amount:
break
try:
result = 'Found looked data!' if self.check_world() else '-'
... |
def encode(self, inputs):
enc = self.encoder(inputs)
if self.encoder_type == 'Nonlinear':
z_mean = self.encoder_mean(enc)
else:
z_mean = self.encoder_mean(inputs)
# Note: encoder_type = 'Linear' only means that z_mean is a linear combination of the input OPs,
... | This function processes input data in batches through a VAE, computes latent representations (z_mean, z_sample), decodes predictions, and saves trajectory results including state population distributions, encoder parameters (if linear), and latent representations. It also stores predicted labels and representations if ... | def save_traj_results(self, inputs, batch_size, path, SaveTrajResults, traj_index=0, index=1):
all_prediction=[]
all_z_sample=[]
all_z_mean=[]
for i in range(0, len(inputs), batch_size):
batch_inputs = inputs[i:i+batch_size].to(self.device)
# pass through VAE
... |
def update_labels(self, inputs, batch_size):
if self.UpdateLabel:
labels = []
for i in range(0, len(inputs), batch_size):
batch_inputs = inputs[i:i+batch_size]
# pass through VAE
z_mean, z_logvar = self.encode(batch_inputs)
... | The function computes and saves evaluation metrics (loss, reconstruction error, KL divergence) for both training and test datasets after model updates. It processes data in batches, aggregates results, and stores them in a NumPy file while logging key parameters and performance metrics to a text file. | def output_final_result(self, train_past_data, train_future_data, train_data_labels, train_data_weights, \
test_past_data, test_future_data, test_data_labels, test_data_weights, batch_size, output_path, \
path, dt, beta, learning_rate, index=0):
with ... |
def calculate_loss(self, data_inputs, data_targets, data_weights, beta=1.0):
# pass through VAE
outputs, z_sample, z_mean, z_logvar = self.forward(data_inputs)
# KL Divergence
log_p = self.log_p(z_sample)
log_q = -0.5 * torch.sum(z_logvar + torch.pow(z_sample-z_mean, 2)
... | The code trains a machine learning model using iterative updates on labeled data, incorporating a custom loss function with reconstruction and KL divergence terms. It dynamically adjusts data labels based on convergence criteria (state population changes) and employs early stopping with a patience threshold. The model ... | def train_model(self, beta, train_past_data, train_future_data, init_train_data_labels, train_data_weights, \
test_past_data, test_future_data, init_test_data_labels, test_data_weights, \
optimizer, scheduler, batch_size, threshold, patience, refinements, output_path, log_interval, \
... |
def read_file(filename):
with open(filename, 'r') as file:
return file.read().strip()
def dc_run_length_encoding_v1(text):
n = len(text)
i = 0
result = ""
while i < n - 1:
count = 1
while i < n - 1 and text[i] == text[i + 1]:
count += 1
i += 1
... | The main task of the code is to demonstrate various data compression algorithms by applying Run-Length Encoding (RLE v1/v2), Lempel-Ziv-Welch (LZW), Huffman coding, and arithmetic coding on text and binary data, using both predefined examples and input files to illustrate their encoding outputs. | def main():
text = read_file("Assignment8d.txt")
print("RLE v1 MLK Speech:", dc_run_length_encoding_v1(text))
text_binary = binary(text)
print("RLE v1 Binary of MLK Speech:", dc_run_length_encoding_v1(text_binary))
text_binary = "0" * 12 + "1" + "0" * 3 + "11" + "0" * 8
print("RLE v2 Binary of ... |
def get_country_population():
url = 'https://www.worldometers.info/world-population/population-by-country/'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
itr = iter(soup.find_all('td'))
dict_countries = {}
while True:
try:
no = next_text(itr)
... | The main task of the code is to retrieve country population data, scrape COVID-19 related data using this information, and generate an HTML file named "Assignment4" containing the results. | def main():
dict_countries_population = get_country_population()
data = covid_scraper(dict_countries_population)
make_html(data, "Assignment4") |
def create_element(tag, content, attributes=None, end_tag=True):
element = "<" + tag
if attributes:
element += " " + attributes
element += ">"
if end_tag:
element += str(content) + "</" + tag + ">"
return element + "\n"
def read_style(file_name="mystyle.css"):
with open(file_name... | This function generates an HTML file with a specified title, tables, and styling. It creates a structured HTML document including metadata, a table of contents (if enabled), formatted tables with validation, and a copyright notice. The file is written to disk and optionally opened in a browser. | def write_html_file_new(file_name, my_title, my_tables, open_file=False, style_sheet=None, do_toc=False):
if style_sheet:
link_attributes = f'rel="stylesheet" href="{style_sheet}"'
style = create_element(TAG_LINK, "", link_attributes, False)
else:
style_sheet = read_style()
style... |
def ed_parity_1d(bits, even=True):
parity_even = (sum([int(b) for b in bits]) % 2) == 0
parity_bit = 0 if parity_even == even else 1
print("ed_parity_1d: ", bits, even, parity_bit)
return parity_bit
def ed_parity_2d(bits, width, even=True):
n = len(bits)
cols = width
rows = n // cols
rec... | The code tests error detection mechanisms using 1D and 2D parity checks, checksums, and CRC on binary data. It compares parity results before and after altering bits, identifies mismatches in rows/columns, and validates error detection methods like checksum and CRC for different bit sequences. | def main():
bits = "0111000110101011"
ed_parity_1d(bits, True)
print()
bits2 = "10101" + "11110" + "01110"
parity_rows, parity_cols = ed_parity_2d(bits2, 5, True)
bits2c = change_bits(bits2, 1)
parity_rows_c, parity_cols_c = ed_parity_2d(bits2c, 5, True)
print()
for i in range(len... |
def clear_last(self, file_path, file = None):
#clears the 'last' instance of an evaluation, aka deletes the given folder and file.
for files in os.listdir(file_path):
if files == '1Frames':
pass
else:
path = os.path.join(file_path, files)
... | The code creates a GUI tab for displaying and managing results. It includes buttons to clear previous results, generate new results with visualizations, and access instructions specific to the results tab. The tab is designed to show a video with all process steps and graphs, facilitating user interaction with result d... | def results_tab(self, window):
#tab to make and show video that has with all steps of the process + graphs
tk.Label(window, text = 'View Complete Results', bg = 'light grey').grid( row = 1, column = 1, padx = 10)
#clears the 'results' file, to indicate overwriting with a new one.
tk.Bu... |
def build_setting(self, window = None, name = 'Directory', variable = None, options = [], column = 1, row= 0, refresh_button = None):
#in 'Settings' tab, shows what curent value is, and allows for choice from a option menu
#or inputting a new value. returns the button with the chosen value, as well as t... | The code creates a GUI settings tab for a project, allowing users to update parameters like project directories, thresholds, crop settings, kernels, and blur. It dynamically replaces widgets with new inputs upon button clicks, links refresh actions to update views, and includes options to save settings or view project ... | def settings(self, window):
#builds the setting tab
tk.Label(window, text = 'Settings', bg = 'light grey').grid(row = 0, column = 1, columnspan= 5, sticky = tk.N, pady = 10)
#make the directory selection component of setting using build_setting
self.dir_refresh = tk.But... |
def update_setting_wdir(self, row, column, window = None):
#checks if a new project has been added, if so, makes the empty folders for it.
if window == None:
window = self.tab3
if len(self.input_dir.get("1.0", 'end-1c'))>2:
self.update_project(self.input_dir.get("1.0", 'e... | The code saves current GUI settings and computed values to a CSV file. It updates parameters from specific GUI elements, constructs a file path, writes settings like thresholds, crop values, kernels, and blur thresholds, then appends frame and damage counts from image processing functions. Exceptions during data retrie... | def save_settings(self):
#saves current settings to a .csv file called settings. First updates all settings so they are current.
self.update_setting_wdir(row= 2, column=1)
self.update_setting_thresh(row=2, column=2)
self.update_setting_crop(row=2, column=3)
self.update_setting_ke... |
def open_file(self,file_types=[("all files","*.*")], prompt = 'select file', start_dir = None):
#returns file path, can specify prompt text and initial directory
if start_dir == None:
start_dir = self.twd.get()
file_path = askopenfile(mode='r', title=prompt, filetypes=file_types, ini... | The main task of the code is to allow users to select a .wmv thermal video file, copy it to a working directory, rename it to "video.wmv", set its path, and trigger a popup for project name and frame spacing input. It handles file duplication errors by renaming or deleting existing files, ensuring the video is ready fo... | def open_vid(self):
#takes the working video, copies it to the working directory. sets the videopath
filepath = self.open_file(prompt = 'Choose a Thermal Image Video with a .wmv format')
if filepath.__contains__('.wmv'):
name_ind = filepath.rfind('/')
file_na... |
def make_folder(self, path, name):
#makes new directory with name at path.
#returns path name, passes even if directory already exists
try:
os.mkdir(path+'/'+name)
new_path = path+'/'+name + '/'
new_path.replace('\\','/')
return new_path
e... | This function adjusts the crop area for a selected damage in the 'Evaluate Single Damage' tab. It removes existing UI elements, generates a new cropped image, and adds interactive widgets (buttons, sliders, radio buttons) to let users adjust the crop size, choose fit methods (linear/quadratic), and decide to apply the ... | def adjust_crop(self, window, number):
#this refreshes the crop on the selected damage in the 'Evaluate Single Damage' tab. The user is then given
#the option to apply the new crop to show results, or just to show the results.
try:
#this throws an error on purpose, because it the var... |
def save_settings(self):
#saves current settings to a .csv file called settings. First updates all settings so they are current.
self.update_setting_wdir(row= 2, column=1)
self.update_setting_thresh(row=2, column=2)
self.update_setting_crop(row=2, column=3)
self.update_setting_ke... | This function automates end-to-end damage detection in videos by processing input video files through a series of steps: extracting frames, cropping regions, generating masks, localizing damage areas, and segmenting damages. It skips redundant steps if intermediate files already exist, saves user settings, and handles ... | def all_in_one(self, window, path = None, video = None):
#performs the entire damage detection process, as long as a video is provided.
#Checks for existing files in the folders, if there are any, then that step is not completed (to save time)
if path == None:
path = self.twd.get() ... |
def make_folder(self, path, name):
#makes new directory with name at path.
#returns path name, passes even if directory already exists
try:
os.mkdir(path+'/'+name)
new_path = path+'/'+name + '/'
new_path.replace('\\','/')
return new_path
e... | This function displays a UI element showing a selected damage image and a slider to adjust crop buffer pixels. It removes previous widgets, loads/resizes the damage image, positions it in the window, and adds a slider and 'Adjust Crop' button for modifying the crop buffer. The layout adapts based on the number of damag... | def show_adjust_crop(self,window,number):
# this function is called when a damage is selected in the 'Evaluate Single Damage' tab. it takes in the number
# of the damage selection, and shows the slider to add the buffer pixels.
try:
#this throws an error on purpose, because it is ref... |
def clear_last(self, file_path, file = None):
#clears the 'last' instance of an evaluation, aka deletes the given folder and file.
for files in os.listdir(file_path):
if files == '1Frames':
pass
else:
path = os.path.join(file_path, files)
... | This code creates a GUI tab in a Tkinter window for damage detection, offering options to run the full detection process or individual steps (e.g., splitting video, masking, segmenting). It includes buttons to clear previous results, execute each component, view intermediate files, and access instructions. The layout o... | def individual(self, window):
#this function takes in a tkinter frame and populates the tab for
#damage detection functions, ie, masking, segmentation ect
#can either be individual, or full detection.
tk.Label(window, text='Perform Entire Damage Detection Process', bg =... |
def load_setting(self):
#loads in the saved settings from the current project. automatic when switching projects
i= 0
self.save_path = os.getcwd()+ '/__resulting__/' + self.twd.get() + '/settings.csv'
try:
file1 = open(self.save_path, 'r', newline='')
r =... | The function populates the 'Evaluate Single Damage' tab with localized frame visuals and evaluation options for multiple damages. It clears existing widgets, loads damage images, creates buttons for each damage, and handles errors if no damages exist or localization is incomplete. | def load_damages(self, window = None):
# populates the 'Evaluate Single Damage' tab. This shows the localized frame, then gives options to evaluate
# each damage. This is a seperate function from making the tab, since in a new project there would be no
# existing localized frame, or counted dam... |
def introduction():
"""
This section explains game rules to the player.
"""
print("_"*70)
print(" " * 8 + "*" * 30)
print("**********WELCOME TO THE HANGMAN GAME *********")
print(" " * 8 + "*" * 30)
print(" " * 8 + "*" * 30)
print(" RULES\n")
print("1. Attenti... | The main task of the code is to execute a game loop that repeatedly runs a hidden word game. It initializes game elements via introduction, rhyme, and player greetings, then enters a loop where hidden_word() determines if the game restarts. The loop breaks when hidden_word() returns False, ending the game. | def main():
introduction()
rhyme()
ready_to_play()
greetings_player(get_name)()
while True:
restart = hidden_word()
if not restart:
break |
def startUDPTrans(self, port):
self.listen = UDPTrans.createServer(port)
def sendSOT(self):
packet = self.createPacket(1)
#print(pprint(vars(packet)))
print("Start of Transmission Packet Sent.")
logging.info("Start of Transmission Packet Sent.")
self.sendPacket(packet)
... | The code initializes UDP transmission, sends a start-of-transmission (SOT) signal, and iteratively sends packets in a sliding window until reaching the configured maximum packet count. It manages acknowledgment (ACK) timing, waits for ACKs, and resets timers as needed. Upon completion, it sends an end-of-transmission (... | def start(self):
self.startUDPTrans(self.config.sender_port)
self.sendSOT()
self.window_count = 0
print("Max Packets to Send: ", self.config.max_packets)
max_string = "Max Packets to Send: " + str(self.config.max_packets)
logging.info(max_string)
while self.packe... |
def insert_response(form_data):
"""
Insert the relevant data from `form_data` into the Reponse
table.
Return the Id of the created Response.
"""
db = get_db()
org_id_query = 'SELECT Id FROM Organisation WHERE Name = ?'
org = query_db(org_id_query, (form_data['name_ddpo'],), one=True)
... | (The function inserts form response data into a database, handling errors. It first inserts into the "Response" table, then into "totals" tables. It processes "boroughs_covered" by inserting into "ResponseBorough" using SQL queries, committing transactions. Errors during insertion are captured and re-raised. The main t... | def process_form(form_data: dict) -> tuple:
"""
Insert form response data into the database.
Return details of any errors that occur in the process.
"""
# Insert into Response table
try:
response_id = insert_response(form_data)
except ValueError as e:
raise e
# Insert i... |
def make_pf_graph(self, population, best_pf, idx=None):
"""
Make population graph with highlighted best Pareto front
:param population: Population
:param best_pf: Best Pareto front
:param idx: Index of generation, None after computation for last Pareto front graph
"""
... | This function saves the best Pareto front (best_pf) by generating visualizations (graphs/GIFs) and exporting individual data to structured directories. It creates folders based on generation index (idx) or experiment labels, stores each individual's information in separate subdirectories, and writes data using `write_i... | def save_best_pf(self, population, best_pf, result_export=None, idx=None):
"""
Save informations about best Pareto front
:param population: Population
:param best_pf: Best Pareto front
:param result_export: Result export info
:param idx: Index of generation
"""
... |
def write_log_prefix(self):
"""
Write prefix into output log
"""
with open(self.directory + "/output.log", "a") as f:
f.write("-------------------------------------------------------------------\n")
f.write(" STARTUP SETTINGS ... | The code's main task is to execute a single step of an evolutionary algorithm, including exploration, exploitation, training of the best Pareto front, and logging. It checks for Pareto graph export requirements, generates visualizations if enabled, and records the best solutions in logs and files. The method also updat... | def evolution(self):
"""
Method controls single steps of evolution
"""
logging.info("Starting evolution...")
self.write_log_prefix()
# If Pareto graphs should be exported, create tmp_pareto_dir for graphs
# Graphs will be used for creating gif
if self.res... |
def add_first_module(self, x):
"""
Add first module into the phase
:param x: Phase input/Model structure
:return: Phase CNN structure with first module
"""
module = layers.phase_layers[0]
return self.choose_layer(x, x, module)
def add_last_module(self, x, phase_in... | The code constructs a CNN model for phase processing based on a given genotype structure. It iterates through predefined connections, adding modules (first, middle, or last) to build the neural network. The function returns the final output layer or the original input if no output module was added, enabling dynamic mod... | def create_phase_model(self, x):
"""
Create CNN for phase from genotype
:param x: Phase input/Model structure
:return: CNN structure for Keras
"""
phase_input = x
phase_output = None
for i in range(len(self.phase_connections) - 1):
if i != self... |
def _listen_for_full_request(client_sock: socket.socket) -> tuple[bytes, Optional[GraphPlot]]:
raw_response = client_sock.recv(4096)
if not raw_response:
raise ConnectionResetError
body, missing_bytes, plot_type = parse_response(raw_response)
if missing_bytes:
bod... | The main task of the code is to handle client connections by receiving and processing data points, validating them, and updating the server's state if valid. It listens for client requests, sends acknowledgment or error messages, and manages disconnections, using the client's color and plot context to record data point... | def handle_client(self, client_sock: socket.socket, client_address: int, client_color: str) -> None:
while True:
try:
request_data, plot = self._listen_for_full_request(client_sock)
except ConnectionResetError:
break
point = parse_data(request... |
def _process_auth_callback(self) -> None:
state = self.get_argument("state")
if state == csrf_cache[self._uid]:
session = requests_oauthlib.OAuth2Session(
self._config.client_id,
scope=self._config.scope,
redirect_uri=self._callback_url,
... | This code handles authentication and request processing by determining the appropriate callback or request method based on the 'is_auth' parameter, constructing URLs, retrieving user information, and delegating to specific processing functions like _process_auth_callback or _process_fetch_request. | def get(self, is_auth):
## FIXME: Do not hard-code the service's name.
self._request_url = f"https://{self.request.host}{self.request.uri}"
self._callback_url = f"https://{self.request.host}{self.request.path}"
self._uid = self.get_current_user()["name"]
if is_auth == "/auth":
... |
def get_gross_profit(self) -> np.ndarray:
revenue = self.get_revenue()
gross_margin = self.get_gross_margin()
gross_profit = revenue * gross_margin
self.output["gross_profit"] = gross_profit
return gross_profit
def get_interest_expense(self) -> np.ndarray:
if not "interes... | The code calculates Selling, General, and Administrative (SGA) expenses by subtracting interest expense, depreciation/amortization, and EBIT margin from gross profit. It ensures required financial data keys exist in `self.output` by calling methods like `get_gross_profit()` and `get_ebit_margin()` if missing. The resul... | def get_sga(self) -> np.ndarray:
if not "gross_profit" in self.output.keys():
self.get_gross_profit()
gross_profit = self.output["gross_profit"]
if not "interest_expense" in self.output.keys():
self.get_interest_expense()
interest_expense = self.output["interest_e... |
def get_net_income(self) -> np.ndarray:
# gross_profit = self.get_gross_profit()
# sga = -1 * self.get_sga()
# dep_amort = self.get_dep_amort()
# int_exp = self.get_interest_expense()
if not "revenue" in self.output.keys():
self.get_revenue()
revenue = self.ou... | The main task of the code is to compute free cash flow (FCF) by combining net income, interest expense, depreciation/amortization, net working capital, and capital expenditures (assuming capex equals depreciation). It ensures prerequisite financial metrics are calculated first, then applies the formula: FCF = net_incom... | def get_free_cashflow(self) -> np.ndarray:
# Calculating net income
if not "net_income" in self.output.keys():
self.get_net_income()
net_income = self.output["net_income"]
# Calculating free cash flow
if not "net_working_capital" in self.output.keys():
s... |
def consolidate_edits(data):
out = copy.deepcopy(data)
for sent in out:
sent['edits'] = associate_spans(sent)
return out
def consolidate_annotations(data):
out = copy.deepcopy(data)
idx = 0
while idx < len(out):
sent = out[idx]
processed = []
successful = True
... | The code loads and preprocesses annotated data from specified files, filtering by batch numbers, excluding corrupted entries, parsing JSON annotations with metadata, realigning sentence IDs to avoid duplicates, and applying preprocessing steps like consolidating edits, annotations, and adding scores if enabled. | def load_data(path, batch_num=None, preprocess=False, realign_ids=True):
data = []
if not 'annotated' in path:
raise Exception('Currently only supports format of \"annotated\" files.')
files = sorted([f'{path}/{x}' for x in os.listdir(path)])
# Only include files of a specified batches
if ... |
def clean(s):
return s.strip().replace('"', r'\"')
def indigenous_name(key, map):
if isinstance(key, str) and key in map:
return '"%s"' % clean(map[key]['indigenous'])
else:
return 'null'
def other_names(key, map):
if isinstance(key, str) and key in map:
names = map[key]['englis... | The main task of the code is to generate a JSON file containing structured language data. It processes input language information, formats it with specific fields (e.g., codes, names, scope), handles optional values, and writes the result to a file at the specified output path. The output is a dictionary mapping langua... | def write_data_out(languages, tl_names, out_path):
rows = map(
lambda linfo:
'"%s":{%s}' % (
linfo['id'],
','.join([
'"code":"%s"' % linfo['id'],
'"reference_name":"%s"' % clean(linfo['name']),
'"indigenous_name":%s' % indigenou... |
def front_version_extractor(vrsn):
vrsn = str(vrsn).split(".")
n_version = ""
for i in range(len(vrsn)-1):
n_version+=vrsn[i]
return n_version
def get_download_version(c_version):
r = requests.get("https://chromedriver.storage.googleapis.com/?delimiter=/&prefix=")
version_info = ET.from... | The code automatically detects the operating system, checks the installed Google Chrome version, and downloads the corresponding chromedriver binary from Google's servers, ensuring version compatibility, handling errors like missing Chrome installations, and managing updates or re-downloads when version mismatches occu... | def chromeDriverDownloader():
if curPlt == 'linux':
print("[+] Detected System: Linux")
if not os.path.exists('./chromedriver'):
try:
todl = subprocess.run(['google-chrome',' --version'], capture_output=True).stdout.decode()
vrsn = (todl.split(" "))[2]
... |
def receive_data(self):
"""Receive data from other nodes."""
print("I try to receive data")
try:
data, addr = self.sock.recvfrom(1024)
return pickle.loads(data), addr
except socket.timeout:
return None, None
def perform_solving(self, grid, arr):
... | The code handles incoming requests by processing Sudoku tasks, splitting them, solving them, timing the process, and coordinating with neighboring nodes. If a 'TASK' is received, it solves the Sudoku, logs the time taken, and requests work from the predecessor. If 'NEEDWORK' is received, it marks the neighbor as free. ... | def handle_request(self, sock, mask):
data, addr = self.receive_data()
if data:
if data['method'] == 'TASK':
start_time = time.time()
possible_solutions = data['range']
# Split the task
self.sudoku = data['sudoku']
... |
def is_terminal_node(grid, config):
# Check for draw
if list(grid[0, :]).count(0) == 0:
return True
# Check for win: horizontal, vertical, or diagonal
# horizontal
for row in range(config.rows):
for col in range(config.columns-(config.inarow-1)):
window = list(grid[row,... | The code implements the minimax algorithm for a game, recursively evaluating optimal moves by alternating between maximizing and minimizing players. It checks terminal states, explores valid moves, and applies a heuristic evaluation (nStepHeuristic) at depth limits or terminal nodes. The function returns the best possi... | def minimax(node, depth, maximizingPlayer, mark, config):
is_terminal = is_terminal_node(node, config)
valid_moves = [c for c in range(config.columns) if node[0][c] == 0]
if depth == 0 or is_terminal:
return nStepHeuristic(node, mark, config)
if maximizingPlayer:
value = -np.Inf
... |
def check_ecs_tasks(account_id, region, profile):
session = Session(profile_name=profile)
client = session.client("ecs", region_name=region)
results = []
cluster_arns = [item for item in paginate(client, "list_clusters")]
for cluster_arn in cluster_arns:
task_arns = [item for item in pagina... | The code's main task is to analyze AWS ECS tasks and ECR images across multiple accounts in the "ap-southeast-2" region. It checks ECS tasks, retrieves ECR image details, filters tasks with image sizes ≥1GB or non-null OS families, and exports results to JSON files. The output includes per-account task data and a conso... | def main():
region = "ap-southeast-2"
# Check ecs tasks, task definitions, container instances;
# and store the data to g_account_tasks and g_images
for account_id, profile in profiles.items():
check_ecs_tasks(account_id, region, profile)
# Retrieve ECR images' info
acc_images_dict = c... |
def clearConsole():
if os.system('cls') == 0: return
os.system('clear')
def employee_menu(emp, store):
emp.store = store
isManager = isinstance(emp, manager.Manager)
while True:
clearConsole()
print(f"{emp.username}")
print("------------------------")
print("1- Leave... | This code runs a bookstore management system, allowing users to log in as employees/customers, handle registration, or quit. It loads a manager from a database, initializes the bookstore, and presents a menu for authentication and operations. Employee/customer menus are accessed upon successful login, with error handli... | def main():
man = bookStore.BookStore.load_manager('database.db')
if man is None:
man = manager.Manager(id=1, name="Alireza", lastname='Kamyab', username='aimlessly', password=123456789,
baseIncome=10000000)
store = bookStore.BookStore(manager=man)
while True:
... |
def check_enable_mode(self, check_string=''):
"""Check if in enable mode. Return boolean."""
self.remote_conn.sendall('\n')
output = self.read_until_prompt()
return check_string in output
def normalize_cmd(command):
"""Normalize CLI commands to have a single trailing newline."""
... | The main task of the code is to transition a network device into "enable mode" by sending commands and verifying the success. It checks if the current mode is already enabled; if not, it sends a normalized command, reads output until a specified pattern is found, then sends a secret (e.g., password) to authenticate. If... | def enable(self, cmd='', pattern='password', re_flags=re.IGNORECASE):
"""Enter enable mode."""
output = ""
if not self.check_enable_mode():
self.remote_conn.sendall(self.normalize_cmd(cmd))
output += self.read_until_prompt_or_pattern(pattern=pattern, re_flags=re_flags)
... |
def check_enable_mode(self, check_string=''):
"""Check if in enable mode. Return boolean."""
self.remote_conn.sendall('\n')
output = self.read_until_prompt()
return check_string in output
def normalize_cmd(command):
"""Normalize CLI commands to have a single trailing newline."""
... | This function exits enable mode by sending a specified command, verifies the exit was successful, and raises an error if still in enable mode. It returns output from the command execution. | def exit_enable_mode(self, exit_command=''):
"""Exit enable mode."""
output = ""
if self.check_enable_mode():
self.remote_conn.sendall(self.normalize_cmd(exit_command))
output += self.read_until_prompt()
if self.check_enable_mode():
raise Value... |
def config_mode(self, config_command='', pattern=''):
"""Enter into config_mode."""
output = ''
if not self.check_config_mode():
self.remote_conn.sendall(self.normalize_cmd(config_command))
output = self.read_until_pattern(pattern=pattern)
if not self.check_co... | The function sends a series of configuration commands over an SSH connection, entering/leaving configuration mode as needed. It iterates through provided commands, sends them with delays, collects output, and returns sanitized results. Error checks ensure valid input, while optional parameters control mode exit, output... | def send_config_set(self, config_commands=None, exit_config_mode=True, delay_factor=.1,
max_loops=150, strip_prompt=False, strip_command=False):
"""
Send configuration commands down the SSH channel.
config_commands is an iterable containing all of the configuration comma... |
def fetch() -> None:
# get instruction from memory
inst = inst_mem[pc]
text = colored('instruction fetched: ✅', 'yellow')
print(text)
print(inst)
def decode() -> None:
print_decoded_inst()
def execute() -> None:
inst = id_ex['IR']
try:
opcode = bin_to_inst_dict[(id_ex['OPCODE'],... | The code simulates a pipeline processor's execution of instructions from a file, handling fetch-decode-execute stages, memory/cache operations, and stalls. It tracks instruction throughput, updates register/file states, and prints results. | def _simulate() -> None:
global pc # skipcq: PYL-W0603
try:
with open('instructions.txt', 'r', encoding='utf-8') as f:
inst_i = 0
for line in f:
inst_mem[inst_i] = line.strip()
inst_i += 1
except FileNotFoundError:
print('file not foun... |
def make_path(path):
if isinstance(path, str):
path = [path]
elif not isinstance(path, list):
raise ValueError(path)
return os.path.abspath(os.path.join(os.path.dirname(__file__), *path))
def write_log(msg):
with open(make_path('archive.log'), mode='a') as f:
f.write(f"{get_date()}| {msg}\n")
def sa... | This function archives a thread by saving its JSON data and associated media files. If the thread is new, it creates a JSON file and saves all media. If the thread exists, it appends new posts and their media. It ensures threads are stored with unique filenames, tracks media counts, and updates existing archives with n... | def archive_thread(board, thread):
thread_filename = f"{board}_{thread['posts'][0]['no']}"
thread_file_path = make_path(['archive', f"{thread_filename}.json"])
if not os.path.isfile(thread_file_path):
write_log(f"Found a new thread.")
save_json(thread, thread_file_path)
count = 0
for postnum, tim... |
def write_log(msg):
with open(make_path('archive.log'), mode='a') as f:
f.write(f"{get_date()}| {msg}\n")
def get_catalog_content(board, filters):
catalog_content = fetch_json(URL.catalog(board))
catalog_content = filter_catalog(catalog_content, filters)
return catalog_content
def get_thread_content(board, ... | The main task of the code is to search specified online forums (boards) using predefined filters, retrieve catalog and thread content, and archive each thread. It iterates through boards in WATCHLIST, logs the search, fetches catalog pages, extracts threads, retrieves thread details, and archives them systematically. | def main():
for board, filters in WATCHLIST.items():
write_log(f"Searching {board} : {filters}")
catalog_content = get_catalog_content(board, filters)
if catalog_content is None: continue
for page in catalog_content:
for thread in page['threads']:
postnum = thread['no']
thread_c... |
def parse_text(text: str, cell_shape):
values = text.split()
field_side = int(np.sqrt(len(values)))
if len(values) != field_side ** 2:
raise ValueError('The field is not square.')
cell_shape, cell_size = get_cell_shape(field_side, cell_shape)
field = np.ones([field_side] * 3, dtype=bool)
... | The code solves Sudoku puzzles by handling various input formats (string, array, list, tuple) and cell shapes. It identifies empty cells (marked by '?' or NaN), applies constraint propagation to reduce possibilities, and generates all valid solutions through backtracking. The function infers cell shapes if unspecified ... | def solve(field: Union[str, np.ndarray, list, tuple], cell_shape: Tuple[int, int] = None) -> Iterable[np.ndarray]:
"""
Solves a sudoku puzzle and yields all possible solutions.
Parameters
----------
field
if array - nan values denote unfilled positions, if str - '?' denotes unfilled positio... |
def get_model(argv):
positive, negative, truthful, deceptive = {}, {}, {}, {}
temp = 1
with open('nbmodel.txt', 'r') as f:
lines = f.readlines()
lines = lines[1:-1]
vocab_total = float(lines[0])
pos_total = float(lines[2])
neg_total = float(lines[4])
truth_total = float... | The main task of the code is to classify text using a pre-trained model. It loads model parameters (positive, negative, truthful, deceptive word counts and totals) from the input file, applies text classification on the same file, and writes the classification results. The process involves loading data, classifying tex... | def main(argv):
positive, negative, truthful, deceptive, pos_total, neg_total, truth_total, decep_total, vocab_total = get_model(argv[0])
output = classify_txt(argv[0], positive, negative, truthful, deceptive, pos_total, neg_total, truth_total, decep_total, vocab_total)
write_output(output) |
def get_data(argv):
text_data, pos_neg_examples, truth_decep_examples = [], [], []
path = argv + "/negative_polarity/deceptive_from_MTurk/"
all_folders = os.listdir(path)
for folder in all_folders:
if folder != '.DS_Store':
path = argv + "/negative_polarity/deceptive_from_MTurk/" + ... | The code trains and saves two text classification models (vanilla and averaged perceptrons) for two tasks: sentiment analysis (positive/negative) and deception detection. It processes input data, initializes weights/biases, trains models with 400 iterations, and exports learned parameters to text files for later use. | def main(argv):
# Gather and clean data
text_data, pos_neg_examples, truth_decep_examples = get_data(argv[0])
text_data = list(dict.fromkeys(text_data))
pos_neg_weights = dict.fromkeys(text_data, 0)
truth_decep_weights = dict.fromkeys(text_data, 0)
pos_neg_bias, truth_decep_bias = 0, 0
vp... |
def get_model(modelfile):
pos_neg_weights, truth_decep_weights = {}, {}
pos_neg_bias, truth_decep_bias = 0, 0
with open(modelfile, 'r') as f:
lines = f.readlines()
lines = lines[1:]
pos_neg_bias = float(lines[0])
lines = lines[2:]
stop = 0
for i in range(len(lines)):
... | The code's main task is to classify text using a pre-trained model. It loads model parameters (weights and biases) from a file specified by `argv[0]`, then applies these parameters to classify the text input from `argv[1]`. The classification results are stored in `output` and written to a file via `write_output(output... | def main(argv):
pos_neg_weights, pos_neg_bias, truth_decep_weights, truth_decep_bias = get_model(argv[0])
output = classify_txt(argv[1], pos_neg_weights, pos_neg_bias, truth_decep_weights, truth_decep_bias)
write_output(output) |
def get_testdata_names(argv):
names1, names2, original_names = [], [], []
with open(argv[0], 'r') as names_data_obj:
names_data = reader(names_data_obj)
for row in names_data:
lst = row[0].split()
original_names.append(row)
for i in range(len(lst)):
... | The main task of the code is to process test name data by splitting input names, building a database of name popularity rankings, predicting potential names using the database, writing results to an output CSV file, and evaluating prediction accuracy. It combines input names with pre-defined name rankings to generate a... | def main(argv):
# Read input test data csv and split the first and seconds parts
names1, names2, original_names = get_testdata_names(argv)
# Create dictionaries of database names and their popularity rankings
male_names, female_names, surnames = get_database_names()
# Create list of predicted name... |
def get_account(self):
'''
retrieve sys_id associated with account from service now table
'''
full_url = f"https://{self.snow_url}/api/now/table/{SNOW_TABLE_NAME}?" \
f"sysparm_query=awsaccountnumber={self.accountid}&sysparm_limit=1"
logger.info(f'Get exist... | This function updates the region table by comparing current and previous region configurations. It adds new regions to the table and removes outdated ones, ensuring synchronization with the latest service integration settings. If the account is not configured, it raises an error. | def update_region(self):
'''
Call this function to update the region table
'''
account_info = self.get_account()
if account_info:
previous_region_list = self.service_integrations['old_properties']['EnableRegions']
to_add = set(self.service_integrations... |
def _build_body(self):
''' Build the request body and headers '''
logger.info("Build the request body for service new api call")
resp_body = {
"awsname": self.snow_account_name,
"awsaccountnumber": self.accountid,
"awsaccesskeyenduser": self.user_keys["SCEndUs... | The main task of the code is to insert SCEndUser and SCSyncUser user keys into Service Now via an API POST request. It constructs a URL, prepares a payload, sends the request, and subsequently adds specified regions to the account by iterating through enabled regions in the service integrations. | def insert_account(self):
'''
Call this function to insert the SCEndUser and SCSyncUser
user keys into service now
'''
logger.info("Add new account in Service Now")
#POST https://XXXX.service-now.com/api/now/table/x_126749_aws_sc_account
full_url = f"https... |
def get_account(self):
'''
retrieve sys_id associated with account from service now table
'''
full_url = f"https://{self.snow_url}/api/now/table/{SNOW_TABLE_NAME}?" \
f"sysparm_query=awsaccountnumber={self.accountid}&sysparm_limit=1"
logger.info(f'Get exist... | The main task of the code is to update an existing Service Now account by sending a PUT request with updated SCEndUser/SCSyncUser xuser keys. It retrieves the sys_id, constructs the API URL, prepares the request body, executes the update, and triggers region data updates. The function returns the response data from the... | def update_account(self):
'''
Call this function to update the SCEndUser and SCSyncUser
xuser keys into service now
'''
#PUT https://XXXX.service-now.com/api/now/table/x_126749_aws_sc_account/{sys_id}
# check for sysid first?
logger.info("Update existing a... |
def press_key(self, key):
pydirectinput.press(key)
time.sleep(self.get_random_delay())
def get_random_delay(self):
return random.uniform(MIN_ACTION_DELAY_SECONDS, MAX_ACTION_DELAY_SECONDS)
def click(self, x, y, times=1, translate=False):
if translate:
x, y = self.translate_coord(x, y)
for _ in range(times)... | The code's main task is to exit a current state by pressing the 'esc' key, wait for a randomized delay to avoid detection, and then re-enter by clicking a predefined safe coordinate with translation enabled, likely to navigate or confirm an action in an application or game. | def exit_and_reenter(self):
self.press_key('esc')
time.sleep(self.get_random_delay())
self.click(*SAFE_CLICK_X_Y, translate=True) |
def load_all(args):
with open(args.commands) as f:
load_commands(json.load(f))
with open(args.constraints) as f:
load_constraints(json.load(f))
with open(args.initial) as f:
load_state(json.load(f))
with open(args.repository) as f:
load_repository(json.load(f))
def preprocess():
global clauses... | The code processes package installation/uninstallation commands, validates constraints, calculates cost, and checks for unsatisfiable constraints. It loads data, iterates through commands to modify the repository state, verifies constraint satisfaction after each step, and reports errors if constraints are violated. Th... | def main():
global commands
global final_constraints
global repository
args = argparser.parse_args()
load_all(args)
preprocess()
if any(c < repo_clauses_count for c in unsat_clauses):
error('invalid initial state; unsat constraint {}'.format(e))
cost = 0
for cmd in commands:
if cmd.action == '... |
def forward(self, X):
# Forward pass
z1 = np.dot(X, self.W1) + self.b1
h = self.activation(z1)
# Dropout
dropout_mask = None
if self.dropout_rate > 0:
dropout_mask = np.random.rand(*h.shape) < self.dropout_rate
h *= dropout_mask / self.dropout_rat... | The code trains a neural network using mini-batch gradient descent over specified epochs, tracking training and validation losses/accuracies. It initializes metrics, performs forward/backward passes for each batch, updates model parameters, and logs performance every 10 epochs. The function returns loss and accuracy hi... | def train(self, X_train, y_train, X_val, y_val, num_epochs, batch_size):
train_losses = []
val_losses = []
train_accuracies = []
val_accuracies = []
# Compute probabilities
_, _, train_probs = self.forward(X_train)
_, _, val_probs = self.forward(X_val)
#... |
def create_file(client_socket):
# name of new file
_ = get_name(client_socket)
# where to create new file ?
file_full_path = get_full_path(client_socket)
# write (or overwrite)
file_to_write = open(file_full_path, "wb")
# getting the size of file
file_len = int.from_bytes(client_socket.... | This function handles file system operations (CREATE, DELETE, MOVE) based on client input. It processes file/folder creation, deletion, and movement, updating the server's tracked files/folders and logging changes with sequence numbers. It also handles edge cases like renaming, path validation, and nested directory ope... | def create_change(client_socket, change_type, seq_num):
# creating a change
change = (change_type, )
# CREATE
if change_type == "6":
# 1 (file), 2 (folder)
file_or_folder = client_socket.recv(1).decode("utf-8", "ignore")
# create FILE
if file_or_folder == "1":
... |
def send_file_name(client_socket, file_name):
# send 1 to client - file
client_socket.send(bytes("1", 'UTF-8'))
# send file name
send_name(client_socket, file_name)
def send_full_path(client_socket, path):
relative_path = os.path.relpath(path, files_and_folders[current_client_identifier][0])
mot... | This function notifies a client of a file or folder deletion by sending a signal ("7"), then transmits the file name and path for files, or the folder path for directories, enabling the client to update its records accordingly. | def update_delete(change, client_socket):
file_or_folder = change[1] # 1 if file, 2 if folder
full_path = change[2] # full path of file/directory
# send 8 to the client - something has been DELETED
client_socket.send(bytes("7", 'UTF-8'))
# FILE
if file_or_folder == "1":
... |
def create_new_file():
# name of a new file
file_name = get_name()
# the path of the new file (where to create)
new_path = get_full_path()
if os.path.exists(new_path):
# open the old file
file = open(new_path, "rb")
# read the old data that in the file
part_of_old_dat... | The function `get_update_from_server` synchronizes local files/folders with a server by receiving commands via a socket. It processes incoming data in a loop, interpreting codes (e.g., "6" for creation, "7" for deletion, "8" for movement, "9" for renaming) to trigger corresponding actions like creating, deleting, movin... | def get_update_from_server():
while True:
option = socket_client.recv(1).decode('UTF-8', "ignore")
# no more changes
if option == "0":
# end of updated from server
break
# created new folder/file
elif option == "6":
option = socket_client.r... |
def update_create(change, client_socket):
file_or_folder = change[1] # 1 if file, 2 if folder
full_path = change[2] # full path of file/directory
mother_path, name = os.path.split(full_path)
# send 6 to the client - something has been CREATED.
client_socket.send(bytes("... | This function processes a client's pending changes by iterating through a list of operations (create, delete, move, rename) identified by their type codes. It applies each change using corresponding update functions, then clears the client's change list and sends a confirmation that no further updates are pending. | def update_client(client_socket, seq_num):
# list of changes. each change is a tuple.
changes_list = clients[current_client_identifier][seq_num]
for change in changes_list:
change_type = change[0]
if change_type == "6":
update_create(change, client_socket)
elif change_... |
def get_update_from_server():
while True:
option = socket_client.recv(1).decode('UTF-8', "ignore")
# no more changes
if option == "0":
# end of updated from server
break
# created new folder/file
elif option == "6":
option = socket_client.r... | The code handles file/folder creation events by notifying a server via TCP. It skips temporary files, checks if the parent directory exists, connects to the server, sends identifiers, and transmits new files/folders. For directories, it recursively sends all contents. It updates a tracking list and closes the connectio... | def on_created(event):
global socket_client
# get the path of the event that created
path = event.src_path
# if the file or folder is already exist
if path in files_and_folders:
return
# get the file/folder name
_, name = os.path.split(path)
# if this temporary file - do not crea... |
def get_update_from_server():
while True:
option = socket_client.recv(1).decode('UTF-8', "ignore")
# no more changes
if option == "0":
# end of updated from server
break
# created new folder/file
elif option == "6":
option = socket_client.r... | The function handles file/folder deletion events by notifying a server via TCP socket. It removes the deleted path from a tracking list, skips temporary files, sends update codes (5, 7, 0) to signal deletion, and transmits file/folder metadata. It connects to a server, sends identifiers, and manages both file removal a... | def on_deleted(event):
global socket_client
# get the path of the event that deleted
path = event.src_path
# get the file/folder name and the mother path
_, name = os.path.split(path)
# if the path has already deleted
if path not in files_and_folders:
return
# if this is a tempor... |
def get_update_from_server():
while True:
option = socket_client.recv(1).decode('UTF-8', "ignore")
# no more changes
if option == "0":
# end of updated from server
break
# created new folder/file
elif option == "6":
option = socket_client.r... | The code handles file/folder move events by notifying a server via TCP socket. It sends identifiers, sequence numbers, and update codes (e.g., '5' for updates, '6' for creations, '8' for moves) to synchronize server records. For external moves, it transmits new files/folders and their contents; for internal moves, it u... | def on_moved(event):
global socket_client
# get the old path of the event that moved
old_path = event.src_path
# get the file/folder name of the source
_, old_name = os.path.split(old_path)
# get the new path of the event that moved
new_path = event.dest_path
# get the file/folder name o... |
def new_client(client_socket):
global current_client_identifier
global files_and_folders
global clients
# new client - create random identifier, clone and then track
identifier = create_id()
current_client_identifier = identifier
client_socket.send(bytes(identifier, 'UTF-8'))
# the cli... | The code sets up a server on a specified port to accept client connections. It distinguishes between new and existing clients by checking received data, assigns sequence numbers, and tracks client data. Global variables manage shared state, while functions handle client identification, cloning, and data tracking. The s... | def serve_clients(port):
global current_client_identifier
global files_and_folders
global clients
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', port))
s.listen(5)
while True:
client_socket, client_address = s.accept()
data = client_socket.recv(CHARACTERS... |
def check_arguments(arr):
# check if the number of arguments valid
if len(arr) != ARGUMENTS_WITHOUT_IS and len(arr) != ARGUMENTS_WITH_ID:
return False
# check if the port is valid
if (int(arr[2]) > MAX_PORT) or (int(arr[2]) < MIN_PORT):
return False
# check if the ip is valid -contai... | The main task of the code is to validate command-line arguments and execute either `track_data_with_id` or `track_data_without_id` based on the number of provided arguments, ensuring correct parameter passing for data tracking functionality. | def main():
# check if arguments valid
if not check_arguments(sys.argv):
sys.exit(-1)
# call track_data function, with or without identifier
if len(sys.argv) == ARGUMENTS_WITH_ID:
track_data_with_id(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
else:
track_... |
def opt_line(obj,resolution):
obj = np.array(obj)
if len(obj[0]) == 2:
opt_obj = []
for i in range(len(obj)-1):
a = sg.LineString(obj[i:i+2]).length
if a > resolution:
p = int(a/resolution)+1
opt_obj.extend(ssample(obj[i:i+2],p)[:-1])
... | The main task of the code is to generate a 3D mesh by sweeping a polygon along a path, morphing between two polygons (poly1 and poly2) with optional twist and scaling. It interpolates the path, creates a series of deformed polygons, and constructs a mesh with vertices and triangular faces, handling closed paths and con... | def sweep(poly1,poly2,path,TwistAngle=0,scale1=None):
path = np.array(path)
resolution = 3
if scale1 == None: scale1 = [1,1]
poly1 = np.round(np.array(poly1),5); poly2 = np.round(np.array(poly2),5)
if poly1.tolist() == poly2.tolist() and (path[0] == path[-1]).all():
if np.count_nonzero(np.co... |
def opt_line(obj,resolution):
obj = np.array(obj)
if len(obj[0]) == 2:
opt_obj = []
for i in range(len(obj)-1):
a = sg.LineString(obj[i:i+2]).length
if a > resolution:
p = int(a/resolution)+1
opt_obj.extend(ssample(obj[i:i+2],p)[:-1])
... | This code generates a 3D mesh by sweeping and morphing between two polygons (poly1 and poly2) along a given path. It interpolates points, maps polygons to 3D space, constructs curves via nearest-neighbor search, and creates a surface mesh with vertices and triangular faces, handling both open and closed paths. The resu... | def sweep(poly1,poly2,path,TwistAngle=0,scale1=None):
path = np.array(path)
resolution = 3
if scale1 == None: scale1 = [1,1]
poly1 = np.round(np.array(poly1),5); poly2 = np.round(np.array(poly2),5)
if poly1.tolist() == poly2.tolist() and (path[0] == path[-1]).all():
if np.count_nonzero(np.co... |
def scan():
cam = cv2.VideoCapture(1)
while True:
#img = Image.open('paperCropped.jpg') # read image
# img = np.asarray(img) # convert to array
cap, img = cam.read() # read camera input
img = img[0:504, 0:504] # get only the top left 500x500 pixels
img = removeShadow(img)... | This code processes a Sudoku puzzle image by detecting its grid structure, extracting numerical data, and solving the puzzle. It uses image scanning to identify squares, locates corners to form a 9x9 grid, converts this into a numerical Sudoku array, and attempts to solve it, printing the grid before and after solving. | def test():
contours, threshold = scan() # scans for squares of a sudoku puzzle, once the squares are found, returns the contours of the squares and a threshold image of the puzzle
cornerGrid = findCorners(contours) # finds the corners of the contours and returns a 2d array of of the corners in a 9x9 sudoku gri... |
def add_components(path, dir_elem):
for name in os.listdir(path):
fullname = os.path.join(path, name)
if os.path.isfile(fullname):
file_elem = dir_elem.find('./{%s}Component/{%s}File[@Name="%s"]' % (XMLNS, XMLNS, name))
if file_elem is None:
comp_elem = SubEle... | The function configures a WiX installer template by updating product metadata, adding components from a source directory, setting up CLI/GUI features with entry points, and ensuring components are included in the default feature. It modifies XML elements for names, descriptions, and file references, then writes the upd... | def configure_wxs(
template=os.path.join(MY_PATH, 'template.wxs'),
output=os.path.join(MY_PATH, NAME + '.wxs'),
source_dir=os.path.join(MY_PATH, 'dist'),
encoding='utf-8'):
# Open the WiX installer template
with io.open(template, 'rb') as f:
document = fromstring(f.read()... |
def process_wall_map(self, wallmap_feature):
floormap = np.atleast_3d(decode_image(wallmap_feature))
# transpose and invert
floormap = 255 - np.transpose(floormap, axes=[1, 0, 2])
return floormap
def process_door_map(self, doormap_feature):
return self.process_wall_map(doormap_fe... | The code loads and preprocesses a dataset for training, handling multi-channel maps (walls, doors, room types), true states, odometry, and observations (RGB/depth). It concatenates map features, rescales them, extracts trajectory data, generates initial particles based on distribution settings, and yields processed bat... | def get_data(self):
"""
The dataset that is maintained has the following dimension
true states: (trajlen, 3)
globalmap: (n, m, ch)
initial particles: (num_particles, 3)
observations: (trajlen, 56, 56, ch)
odometries: (trajlen, 3) -- relative motion i... |
def reset_display():
'''Refresh console display'''
os.system('clear')
print(LOGO)
def login():
'''Log in with username and api key'''
username = get_username()
reset_display()
bpd = get_api_key()
return username, bpd
def show_instructions():
'''Display labeling instructio... | The main task of the code is to initialize the bit.io data labeling tool by resetting the display, welcoming the user, logging in to obtain credentials, displaying instructions, and retrieving initial samples for processing, returning these along with user credentials for subsequent operations. | def init():
'''Login, status, and batch initialization'''
reset_display()
print("Welcome to the bit.io data labeling tool!\n")
username, bpd = login()
show_instructions()
return get_samples(username, bpd), username, bpd |
def _get_username_and_repo(self, username, repo):
'''Retrieves set username and repo if no arguments passed.'''
username = username if username else self.username
if not username:
raise ValueError('Repo username must be initialized or provided as an argument.')
repo = repo if... | This function uploads a Pandas DataFrame to a bit.io table, creating the table if it doesn't exist. It supports appending data (default) or truncating the table first. The data is uploaded in chunks using PostgreSQL's COPY command via psycopg2, with error handling and connection management. The implementation includes ... | def to_table(self, df, table, repo=None, username=None, append=True, chunksize=None):
'''Write a dataframe to a bitdotio table, creating the table if necessary.
One difference from a typical Pandas file operation is that we default to append,
as a safer operation than truncate and insert (requi... |
def reset_display():
'''Refresh console display'''
os.system('clear')
print(LOGO)
def print_hline():
print('********************************************************************')
def get_prompt(num_labels, df):
'''Generates command prompt'''
return f'''
Please enter a command: ... | The code enables interactive labeling of a dataframe (`df`) by navigating through rows with keyboard commands. Users can move up/down (`W/S`), apply labels (`D/A/X` for Positive/Negative/Neutral), upload labels (`U`), or quit (`Q`). It tracks progress with `idx` and `num_labels`, ensuring data is labeled sequentially. ... | def main(df, username, bpd):
idx = 0
num_labels = 0
while True:
reset_display()
row = df.iloc[idx,:]
print(f'Example: {idx + 1}, Current label: {row.manual_label}')
print_hline()
print(row.body)
print_hline()
command = input(get_prompt(num_labels, df))... |
def _get_username_and_repo(self, username, repo):
'''Retrieves set username and repo if no arguments passed.'''
username = username if username else self.username
if not username:
raise ValueError('Repo username must be initialized or provided as an argument.')
repo = repo if... | This code deletes a specified database table by validating the repository and table existence, constructing a fully qualified table name, and executing a SQL DROP TABLE command. It retrieves username/repo details, ensures permissions, and handles the deletion process. The 'limit' parameter is unused in the current impl... | def delete_table(self, table, repo=None, username=None, limit=5):
'''Deletes a table'''
username, repo = self._get_username_and_repo(username, repo)
self._validate_repo_and_table(repo, username, table)
fully_qualified = self._get_fully_qualified(username, repo, table)
self.sql(f'... |
def _get_username_and_repo(self, username, repo):
'''Retrieves set username and repo if no arguments passed.'''
username = username if username else self.username
if not username:
raise ValueError('Repo username must be initialized or provided as an argument.')
repo = repo if... | This function retrieves the maximum row count of a specified table in a database. It validates the repository and table, constructs a fully qualified table name, executes a SQL COUNT(1) query, and returns the result as the row count. | def _get_max_row(self, table, repo, username):
'''Get maximum row number for a table'''
username, repo = self._get_username_and_repo(username, repo)
self._validate_repo_and_table(repo, username, table)
fully_qualified = self._get_fully_qualified(username, repo, table)
sql = f'SEL... |
def _get_username_and_repo(self, username, repo):
'''Retrieves set username and repo if no arguments passed.'''
username = username if username else self.username
if not username:
raise ValueError('Repo username must be initialized or provided as an argument.')
repo = repo if... | This function retrieves data from a specified table in a bitdotio repository, optionally applying a limit and offset to the results by constructing and executing a SQL query. It validates inputs, constructs a fully qualified table name, and returns the queried data using the `read_sql` method. | def _read_table(self, table, repo=None, username=None, limit=None, offset=None):
'''Download from a table from bitdotio with optional limit and offset'''
username, repo = self._get_username_and_repo(username, repo)
self._validate_repo_and_table(repo, username, table)
fully_qualified = se... |
def win_in_row(board: list[list[str]], player: int) -> bool:
"""
Checks if the win condition is meet on all of the rows.
Uses a recursive function to determine that.
:return:
bool
"""
player_symbol = PLAYER_SYMBOL_DICT[player]
for index in range(len(board))... | The function checks if a player has won a game by verifying row, column, and diagonal win conditions on a board. It sequentially evaluates these conditions using helper functions and returns True if any are met, otherwise False. | def win_game(board: list[list[str]], player: int) -> bool:
"""
Wraps all the win condition funcs together to
check if the player won in a certain turn
Avoids doing the checks if the win is not possible
(Can't win on turn 2 if the size is 3)
:return:
... |
def find_missing_item_v1(items: list[int]) -> int:
"""
Iterates on a list of integers and finds
the missing number in the series by comparing the integers' delta to do the
calculated incline.
If there is a mismatch that means we found our missing number
in the... | The code defines a test function that runs multiple test cases for various functions (find_missing_item_v1, find_missing_item_v2, split_list_index, max_sequence, order) by iterating through predefined input lists and string tuples. It prints the function outputs for manual validation, ensuring correctness of implementa... | def test():
"""
A small test function so I can manually check if the expected values are correct
:return:
None
"""
find_missing_items_list = [
[5, 7, 11, 13, 15],
[3, 9, 12, 15, 18],
[6, 2, -2, -6, -10]
]
split_list_items = [
[1, 3, -1, 2, -2, 7],
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.