dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def getServer(self):
server = f"https://api.hypixel.net/status?key={self.apiKey}&uuid={self.uuid}"
a = self.getInfo(server)
if a['session']['online'] == False:
return None
else:
return (str(a['session']['gameType'])).replace('_','')
def getAchievementsFromCur... | The function formats and returns a string listing the player's tiered and one-time achievements from the current server, handling "LEGACY" servers differently by iterating through changes, updating achievements, and using tabulate to structure tables. It checks for empty achievements and returns appropriate messages, e... | def formatNicerLol(self):
self.playerAchievementsOneTime = None
self.playerAchivementsTiered = None
server = self.getServer()
if self.currentServer != server:
self.currentServer = server
returnString = ""
if self.currentServer == "LEGACY":
... |
def reset():
update_X(0)
update_Y(0)
update_Z(0)
# set scaler to rest value [0,0,0]
scl_Xvalue.set(0)
scl_Yvalue.set(0)
scl_Zvalue.set(0)
def update_X (val):
xpos.set(float(val))
update()
def update_Y (val):
ypos.set(float(val))
update()
def update_Z (val):
zpos.set(float(val))
update() | The function `load_best()` resets the system and applies the previously recorded optimal X, Y, Z values from `rmsdisplay` to both the display and sliders (`scl_Xvalue`, `scl_Yvalue`, `scl_Zvalue`), effectively restoring the best solution found during an optimization process. | def load_best():
reset()
update_X(rmsdisplay.best_x)
update_Y(rmsdisplay.best_y)
update_Z(rmsdisplay.best_z)
scl_Xvalue.set(rmsdisplay.best_x)
scl_Yvalue.set(rmsdisplay.best_y)
scl_Zvalue.set(rmsdisplay.best_z) |
def shrink(train):
# shrinkage of big classes
if train.flatten().shape[0] > shrink_size:
k = int(np.ceil(train.flatten().shape[0] / 750))
tmp_train = []
for j in range(train.shape[0]):
shrunken = np.random.choice(train[j], replace=False, size=30 // k)
tmp_train.ap... | The code splits input data into training and test sets per class, dividing tracks into 80% training and 20% test subsets. It applies transformations, normalization, and optional augmentation to training data, while test data undergoes transformations and normalization. Data is organized by class, with labels assigned, ... | def split_data(x):
test_x, test_y = [], []
train_x, train_y = [], []
# loop over classes
for c in range(len(x)):
n = x[c].shape[0]
# loop over tracks and form tracks list
tracks = []
for j in range(n // 30):
tracks.append(x[c][j * 30:(j + 1) * 30])
tra... |
def usage():
print("USAGE:")
print("\tpython mono.py --zipcode=X\n\t\twith X being 0, 1, 2 or 3\n")
sys.exit(1)
def loading():
try:
bio_data = pd.read_csv("solar_system_census.csv", dtype=np.float64)[['weight', 'height', 'bone_density']].values
citizens = pd.read_csv("solar_system_census... | The main task of the code is to parse a command-line zipcode argument, validate it as an integer between 0-3, load data using the `loading()` function, and execute computations with the `compute()` function while enabling graphics. Error handling ensures proper input format and value constraints. | def main():
try:
opts, _ = getopt.getopt(sys.argv[1:], "", ['zipcode='])
if len(opts) != 1 or opts[0][0] != '--zipcode':
usage()
zipcode = int(opts[0][1])
except getopt.GetoptError as inst:
print(inst)
usage()
except ValueError:
print("zipcode mus... |
def get_list(input, chara):
base_data = data_setup.readInCom(input, chara)
return base_data
def cross_validate(dataset, scramBool):
global num_classes
backup_data = copy.copy(dataset)
test_results = []
stats = []
full_set_stats = []
if scramBool:
dataset = ten_percent_scrambler(d... | The code performs cross-validation on both unscrambled and scrambled datasets to evaluate model performance. It sets a global class count (num_classes=6), loads data, and runs 10-fold cross-validation on the original data, followed by a scrambled version, comparing results for analysis. | def work_it():
global num_classes
data = get_list('1', '?') # We don't have any way of programatically finding the number of classes
num_classes = 6
unscrambled_data = copy.copy(data)
'''Uncomment this line to perform cross-validation on the base data'''
print("Tests with unscrambled data")
... |
def SchDtRange(FundDt,FirstDt,NPER,PaymentFrequency):
D1 = FundDt
D2 = FirstDt
Freq = PaymentFrequency
# earliest period after fund date (D1)
# number of initial units peirods
results = FindStartDate(D1,D2,Freq)
FirstIntitalDt = results[0]
IntialPerCnt = results[1]
# build schedule... | The code generates and prints an amortization schedule. It creates a date range, builds an amortization table, applies interest rate calculations, and iterates through periods to display details like principal, interest, and payments, along with the total number of periods and interest rate. | def PrintAmortSch(D1,D2,NPER,freq,P,I,A):
results = SchDtRange(D1,D2,NPER,freq)
rng = results['DateRange']
dAMORT = BuildAmort(rng)
dAMORT = AmortizeIR(P,I,A,dAMORT)
print(NPER)
for x in range((NPER)):
print(x, dAMORT[x])
print(I) |
def SchDtRange(FundDt,FirstDt,NPER,PaymentFrequency):
D1 = FundDt
D2 = FirstDt
Freq = PaymentFrequency
# earliest period after fund date (D1)
# number of initial units peirods
results = FindStartDate(D1,D2,Freq)
FirstIntitalDt = results[0]
IntialPerCnt = results[1]
# build schedule... | This code calculates a loan's payment schedule, adjusted APR, and financial metrics. It determines the monthly payment amount ensuring the resulting APR does not exceed the target, computes the actual interest rate (IR), finance charge, and outputs payment details including first payment date, total periods, and final ... | def Main(LoanAmount,MaxTargetAPR,MaxTargetTerm,freq,FundDt,NextPayDt):
# input variables
A = LoanAmount
I = MaxTargetAPR
NPER = MaxTargetTerm
freq = freq
D1 = FundDt
D2 = NextPayDt
D1 = du.parser.parse(D1)
D2 = du.parser.parse(D2)
# payment schedule inputs
results = SchDtRan... |
def load_images(tar, basename, rows):
image_list = []
for i, row in enumerate(rows):
image_list.append(loadImagePairFromRow(tar, basename, row))
return np.array(image_list)
def loadLabelsFromRow(r):
if (len(r) == 3):
return 1
else:
return 0
def crop_and_downsample(originalX... | The code loads and processes the LFW dataset, converting a compressed file into a tar archive, then reads image pairs from 'pairs.txt'. It preprocesses images (cropping, downsampling), reshapes them, and computes embeddings using a pre-trained TensorFlow model. Finally, it returns the extracted embeddings and correspon... | def load_lfw_pairs():
basename = '/home/hy/Dataset/face/LFW/lfw-deepfunneled'
pair_txt = '/home/hy/Dataset/face/LFW/pairs.txt'
tgz_filename = "{}.tgz".format(basename)
tar_filename = "{}.tar".format(basename)
tar_subdir = "lfw-deepfunneled"
# it will be faster to decompress this tar file all a... |
def get_kafka_connection_details(config_path) -> KafkaConnectionDetails:
"""Load the kafka connection details from the configuration path and the kubernetes secrets stored in the cluster"""
kafka_cfg = get_app_config(config_path).get("kafka")
service_uri = kafka_cfg["service_uri"]
secret = kafka_cfg["cr... | The function `get_producer_config` retrieves Kafka, application, and PostgreSQL configurations from a specified path, fetches monitored URLs from a database, validates them, and returns a `MonitoringProducerConfig` object containing these configurations and valid URLs. It exits early if sanity checks fail. | def get_producer_config(config_path: str, id: int) -> MonitoringProducerConfig:
"""Prepares and returns all the required configuration for the monitoring producer"""
kafka_config = get_kafka_connection_details(config_path)
app_config = get_monitoring_config(config_path)
conn = get_pg_connection(config_p... |
def get_tables_optional_arguments(
soup, html_element, html_element_id,
html_element_index, html_element_class):
tables = []
# if html element is tr
if html_element == 'tr':
tables = get_tables_from_tr_opt_arg(
soup, html_element, html_element_id,
html_element... | The code scrapes data from a webpage by parsing HTML tables or iframes based on command-line arguments (URL, sport, and optional HTML selectors). It validates inputs, fetches the page, extracts relevant data, and outputs the results in JSON format. | def main():
# collecting named arguments with ArgumentParser
parser = argparse.ArgumentParser()
parser.add_argument('--url')
parser.add_argument('--sport')
parser.add_argument('--html_element')
parser.add_argument('--html_element_id')
parser.add_argument('--html_element_index', type=int)
... |
def place_bet(self, player):
while True:
try:
if player == self.dealer:
bet = self.pot # Match the player's bet
else:
bet_str = input("Enter your bet: > $")
if bet_str == '':
bet = 0
... | This function manages a card game loop, handling player/dealer actions, betting, splitting, double-down mechanics, and determining winners based on hand totals. It updates scores, money, and game state, with visual feedback on table status, and allows replay or quitting. | def play_game(self):
play_flag = True
double_down_flag = False
double_down_flag2 = False
while play_flag:
self.player.total = 0
self.dealer.total = 0
os.system(refresh)
# print(self.deck) # <= PRINTS THE WHOLE DECK AT START OF PLAY
... |
def has_data_onDate(expected_date, page_source):
soup = BeautifulSoup(page_source, 'html.parser')
input_element = soup.find('input', {'id': 'ctl00_ContentPlaceHolder1_txtFloorsheetDateFilter'})
selected_date = input_element.get('value')
if selected_date == expected_date:
tabl... | The function scrapes data from a web application for a specified range of dates, handling pagination and exceptions. It inputs dates, searches for data, checks for existence, extracts total pages/records, navigates through pages, and processes data. It recursively adjusts parameters to handle duplicates, incomplete dat... | def scrape_data_for_date_range(date_array_toscrap, page_number=0, target_value=0,actual_count=None):
for date_str in date_array_toscrap:
try:
print(f"Getting data from {date_str}")
print(f"getting data from {date_str}")
# Find the input element by its ... |
def check_dns(userId):
dnsEntry = f"{userId}.{os.environ['ROOT_DOMAIN']}." # must include trailing '.'
response = ROUTE53.list_resource_record_sets(
HostedZoneId = os.environ['HOSTED_ZONE_ID'],
StartRecordName = dnsEntry,
StartRecordType = 'A',
MaxItems = '1'
)
print("DNS... | The main task of the code is to retrieve content from an S3 bucket based on user and project parameters. If `stepFile` is 'game', it checks DNS status and either returns "show_game_page" or decrements the user's step count. For other cases, it fetches a filename using `check_groups`, reads the corresponding S3 object, ... | def get_content(projectId, userId, stepFile, project):
if stepFile == 'game': # Temp behavior to be replaced by actual template
if check_dns(userId):
return "show_game_page"
decrement_user_step_count(userId, projectId, project)
return "wait"
bucket = project.get('bucket') or ... |
def check_project(projectId):
print(projectId)
bucket = os.environ['BUCKET']
filename = 'project_master_list.json'
projectList = S3.Object(bucket, filename).get()['Body'].read().decode('utf-8')
print(projectList)
projectList = json.loads(projectList)
for project in projectList.get('projects'... | This Lambda function processes API requests by validating project and user IDs from query parameters. It retrieves user-specific content, checks permissions, sends messages via SNS if configured, and returns dynamic HTML content or errors. The core task is to serve personalized project data while enforcing access contr... | def lambda_handler(event, context):
print(event)
host = event.get('headers').get('Host')
print('Host: ', host)
qs = event.get('queryStringParameters', dict())
UserId = None
projectId = qs.get('projectId', None)
project = check_project(projectId)
userId = qs.get('userId', None)
if pr... |
def encoder_block(input, num_filters):
x = SqueezeAttentionBlock(input, num_filters)
max_pool = MaxPooling2D((2, 2))(x)
avg_pool = AveragePooling2D((2, 2))(x)
cat = Concatenate()([max_pool, avg_pool])
output = Conv2D(num_filters, (1, 1), padding='same')(cat)
return x, output
def SqueezeAttention... | The code constructs a UNet-like model named "SD-UNet" for image segmentation. It uses encoder blocks with increasing filters (32→256), a SqueezeAttentionBlock, a DenseASPP block for multi-scale features, and decoder blocks with skip connections to upscale features. The output is a 1-channel segmentation map via a sigmo... | def build_model(input_shape):
inputs = Input(input_shape)
skip1, out1 = encoder_block(inputs, 32)
skip2, out2 = encoder_block(out1, 64)
skip3, out3 = encoder_block(out2, 128)
skip4, out4 = encoder_block(out3, 256)
out5 = SqueezeAttentionBlock(out4, 512)
aspp_output = dense_aspp(out5, 256)
... |
def filter_format_data(data, positive_patterns, negative_patterns, patterns_to_remove):
text_lst = [post['text'] for post in data]
text_lst = remove_patterns(text_lst, patterns_to_remove)
return [seq for seq in text_lst if
not any(re.search(pattern, seq, flags=re.I) for pattern in negative_patte... | The code preprocesses input data and awards by sampling the data to a fixed size, applying filtering rules from a JSON file to remove or modify content, and preparing both data and awards for similarity analysis through specific pattern-based transformations, returning filtered posts and processed awards/posts for furt... | def preprocess(data, awards):
n = 175000
if len(data) > n:
data = random.sample(data, n)
with open(f'{os.path.dirname(__file__)}/../patterns/nominee_patterns.json', 'r') as f:
patterns = json.load(f)
posts = filter_format_data(
data,
patterns["preprocess_positive_pattern... |
def preprocess(data, awards):
n = 175000
if len(data) > n:
data = random.sample(data, n)
with open(f'{os.path.dirname(__file__)}/../patterns/nominee_patterns.json', 'r') as f:
patterns = json.load(f)
posts = filter_format_data(
data,
patterns["preprocess_positive_pattern... | The function identifies true nominees for specific awards in a given year by preprocessing input data, generating potential nominees, and filtering them based on the specified year and awards. | def find_nominees(data, awards, year):
posts, preprocessed_awards, preprocessed_posts = preprocess(data, awards)
possible_nominees = get_possible_nominees(awards, preprocessed_awards, posts, preprocessed_posts)
true_nominees = get_true_nominees(year, awards, possible_nominees)
return true_nominees |
def has_presenter_words(t_split):
result = []
if 'presented' in t_split:
result.append('presented')
if 'presents' in t_split:
result.append('presents')
if 'presenting' in t_split:
result.append('presenting')
if 'present' in t_split:
result.append('present')
return... | This function identifies presenters of awards from social media data by analyzing text for presenter-related keywords, matching them to awards, and linking presenters to specific awards, then returning parsed results. It processes tweets to extract presenters, filters out uncertain cases, and uses award-specific data t... | def find_presenters(data, awards_official, year):
# get awards and award_no_stop
awards = [[awards_official[i], utilities.remove_stop_words(awards_official[i])] for i in range(len(awards_official))]
and_odds = dict()
# TODO: get winners
winners_dict = dict()
award_dict = dict()
for award in... |
def has_keyword_words(t_split, wordlist):
result = []
for word in wordlist:
if word in t_split:
result.append(word)
return result
def no_uncertain_words(t_split):
return all(['should' not in t_split, 'wish' not in t_split, 'would' not in t_split])
def find_matched_awards(awards, t_sp... | The code identifies winners from social media posts by detecting win-related keywords (e.g., 'won', 'winner'), matching them to official awards, and compiling results for a specific year. It processes text to filter relevant tweets, maps keywords to awards, and uses helper functions to extract and structure winner data... | def find_winners(data, awards_official, year):
# get awards and award_no_stop
awards = [[awards_official[i], utilities.remove_stop_words(awards_official[i])] for i in range(len(awards_official))]
and_odds = dict()
# TODO: get winners
winners_dict = dict()
award_dict = dict()
for award in aw... |
def BuildInstruments(K,mat):
#Dividing swap rate because we have to evaluate each of swap inst on whole vector of spine point
swap1 = lambda P0T: IRSwap(OptionTypeSwap.PAYER,1,K[0],0.0,0.0,mat[0],4*mat[0],P0T)
swap2 = lambda P0T: IRSwap(OptionTypeSwap.PAYER,1,K[1],0.0,0.0,mat[1],4*mat[1],P0T)
swap3 = la... | The code constructs a yield curve from swap instruments using optimization and cubic interpolation, then calculates the sensitivity (delta) of an off-market swap's price to each market instrument's rate via finite differences. It perturbs each rate, rebuilds the curve, re-prices the swap, and computes deltas as price c... | def mainCode():
# Convergence tolerance
tol = 1.0e-8
# Initial guess for the spine points
r0 = np.array([0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01])
# Interpolation method
method = cubic_interpolation #we can change the interpolation part and see the change in greeks i.e delta
# C... |
def CountCellisTrue(x, y, cl): #Dem so o BLUE xung quang o(x,y)
count = 0
for k in range(9):
tx = hx[k] + x
ty = hy[k] + y
if tx >= 0 and ty >= 0 and tx < m and ty < n:
if cl[tx][ty] == True:
count = count + 1
return count
def isColorin... | The main task of the code is to solve a graph coloring problem using the A* algorithm. It checks for a valid coloring configuration, enforces a 10-minute runtime limit, and recursively explores solutions by updating the color matrix. If no solution is found or the time limit is exceeded, it returns an error code; other... | def AStar(start, colr):
cur_time = time.time()
if (cur_time - start_time)/60 > 5:
f.write("Run time is too large (> 10 minutes).")
print("Run time is too large (> 10 minutes).")
return -1
for i in range(m): #Dem so o mau xanh lien ke voi o (i,j)
... |
def concatNumber(num):
global calc
global lastAnswer
if calc == "0" or calc == str(lastAnswer):
calc = str(num)
else:
calc = calc + str(num)
return calc
def evAC():
global calc
calc = "0"
def evAdd():
global calc
if checkCalcString():
calc = calc + " " + ope... | This function handles calculator button clicks. It processes numeric inputs, triggers arithmetic operations (+, -, x, ÷), clears the display (AC), or calculates results (=). It updates the display text and stores the final result in 'lastAnswer' for subsequent calculations. | def evClick(text):
global calc
global lastAnswer
try:
buttonClicked = int(text)
display['text'] = concatNumber(buttonClicked)
except ValueError:
if text == "AC":
evAC()
display['text'] = calc
elif text == "+":
evAdd()
displ... |
def create_writers(self, fps=10):
if not os.path.exists(join(self.hyperparams['data_files_dir'], 'vids')):
os.makedirs(join(self.hyperparams['data_files_dir'], 'vids'))
rgb_path = join(self.hyperparams['data_files_dir'], 'vids', "rgb_sample_{0:03d}.mp4".format(self.vid_seqname))
rgb_... | The main task of the code is to execute a given policy in a simulated environment, collect a trajectory sample by interacting with the environment over a fixed number of steps (T), and return the resulting Sample object. The function resets the environment, applies noisy actions (if enabled), enforces safety constraint... | def sample(self, policy, condition, verbose=True, save=True, noisy=True):
"""
Reset and execute a policy and collect a sample.
Args:
policy: A Policy object.
condition: Which condition setup to run.
verbose: Unused for this agent.
save: Whether or ... |
def count_bits(l, mask_length):
ones = [0]*mask_length
zeros = [0]*mask_length
for i in l:
for j in range(0, mask_length):
is_set = test_bit(i, j)
idx = mask_length - 1 - j
ones[idx] += is_set
zeros[idx] += not is_set
return ones, zeros
def most_co... | The code processes binary numbers from a file to calculate two values: the power consumption (gamma rate × epsilon rate) and the life support rating (O₂ generator rating × CO₂ scrubber rating). It converts binary strings to integers, determines bit frequencies, computes gamma/epsilon rates, and filters lists to find O₂... | def main():
l = file2list("./3/input.txt")
length = len(l[0])
l = [int(x, 2) for x in l]
ones, zeros = count_bits(l, length)
mc = most_common(ones, zeros)
lc = [not x for x in mc]
gamma = to_num(mc)
epsilon = to_num(lc)
print(gamma*epsilon)
o2 = get_o2(l, length)
co2 = get_... |
def load_features():
feature_order = get_feature_orders()
with open('features.json') as file:
all_possible = json.load(file)
features = {feature: all_possible[feature]
for feature in feature_order}
return features
def get_input_data():
listing = {}
features = ... | This function handles a web request to predict a listing's price. It loads features, processes POST input data, updates features, saves the listing to a database, uses a model to predict the price, and renders a template displaying the predicted rate. | def predict_one():
features = load_features()
predict_message = "Enter your listing's details"
if request.method == "POST":
listing = get_input_data()
features = update_default_features(listing)
DB.session.add(Listing(id=randint(0, 100_000), **listing))
... |
def grid(self):
self.initial_color = 'lime green'
self.response = True
self.castle_white_short = False
self.castle_white_long = False
self.castle_black_short = False
self.castle_black_long = False
self.n = 0
letter_list = ["a","b","c","d","e","f","g","h"]... | The code initializes a chess game GUI using Tkinter, setting up the main window, game grid, images, winner display, menu, time tracking, rapid game mode, and starts a thread for receiving data, then enters the main event loop to run the application. | def __init__(self):
self.root = Tk()
self.root.title("Chess Game")
self.grid()
self.image()
self.winner()
self.menu()
#self.block()
self.time_grid()
self.game_mode_rapid()
start_new_thread(self.receive,())
self.root.mainloop() |
def search_date():
"""Search work logs by exact date."""
logs = store_logs()
date_log_list = []
date_list = []
for line in logs:
if line['task_date'] not in date_list:
date_list.append(line['task_date'])
# Order the list of dates
dt_list = []
for date in date_list:
... | The main task of the code is to present users with search options for log entries, validate input, and direct them to corresponding search functions. It checks for existing logs, displays menu choices (e.g., exact date, date range, regex), handles selections by calling specific search functions, and allows returning to... | def search_menu():
"""Give user search options."""
clear_screen()
while True:
log_length = store_logs()
if len(log_length) == 0:
clear_screen()
return_to_menu = input("There are no logs in the system. " +
"Press 'Enter' to return to ... |
def parse_args(args):
if len(args) == 1:
print_help()
exit(1)
input_file = args[1]
output_prefix = DEFAULT_OUTPUT_PREFIX
orf_len = DEFAULT_ORF_LENGTH
try:
for i in range(2, len(args), 2):
if args[i] == '-l':
orf_len = int(args[i + 1])
... | The main task of the code is to parse a GenBank input file, extract open reading frames (ORFs) of a specified minimum length, and save the identified proteins to output files with a given prefix. It processes command-line arguments, retrieves sequence data, identifies ORFs, and stores results efficiently. | def main():
input_file, orf_len, output_prefix = parse_args(sys.argv)
data = parse_genbank(input_file)
print('Parsed input file, searching ORFs...')
orfs = get_orfs(data, orf_len)
print('Found {} proteins of min length {}, saving them...'.format(len(orfs), orf_len))
save_orfs(orfs, output_prefix... |
def parse_args(args):
output_file = DEFAULT_OUTPUT_FILE
error = DEFAULT_ERROR_THRESHOLD
blast_result = None
if len(args) == 1:
print_help()
exit(1)
fasta = args[1]
try:
for i in range(2, len(args), 2):
if args[i] == '-f':
fasta = args[i + 1]
... | The main task of the code is to process a FASTA file by performing a BLAST search against a database, interpret the results, and save them to an output file. It parses command-line arguments, retrieves the FASTA sequence, executes BLAST, extracts relevant results based on error thresholds, and stores the findings in th... | def main():
filename, error, blast_in_file, output_file = parse_args(sys.argv)
print('Parsed arguments, getting FASTA string...')
fasta = get_fasta(filename)
print('Got FASTA, performing BLAST...')
blast_record = perform_blast(fasta, blast_in_file)
print('Performed BLAST, interpreting BLAST...')... |
def parse_args(args):
input_file = DEFAULT_INPUT_FILE
output_file = DEFAULT_OUTPUT_FILE
if len(args) == 1:
print_help()
exit(1)
pattern = args[1]
try:
for i in range(2, len(args), 2):
if args[i] == '-o':
output_file = args[i + 1]
elif... | The main task of the code is to process BLAST results by parsing command-line arguments, reading input data, searching for hits matching a specified pattern, and saving the results to an output file. The script provides progress updates and is designed for bioinformatics analysis, particularly in identifying sequence a... | def main():
pattern, input_file, output_file = parse_args(sys.argv)
print('Parsed arguments, reading input file...')
blast_results = read_blast(input_file)
print('Input file read, searching for hits...')
hits = search_hits(pattern, blast_results)
print('Found {} hits, saving results...'.format(l... |
def download_metadata():
global current_request
current_request = requests.get(SWISS_PROT_DB_METADATA, allow_redirects=True, stream=True)
data = download_request().decode('utf8')
close_request()
return data
def current_metadata():
try:
with open(LOCAL_METADATA, 'r') as f:
... | The function `new_metadata` compares the date of newly downloaded metadata with the existing metadata. If the existing metadata is absent or the new data's date is more recent, it returns the new data; otherwise, it returns `None` to indicate no update is needed. | def new_metadata():
data = download_metadata()
old_data = current_metadata()
if old_data is None:
return data
date = extract_date_from_metadata(data)
old_date = extract_date_from_metadata(old_data)
if date > old_date:
return data
return None |
def parse_args(args):
output_file = DEFAULT_OUTPUT_FILE
should_print_results = DEFAULT_PRINT_RESULTS
muscle_exe = None
if len(args) == 1:
print_help()
exit(1)
input_file = args[1]
skip = 0
try:
for i in range(2, len(args)):
if skip > 0:
s... | The main task of the code is to perform a local multiple sequence alignment (MSA) using the `align` function, either printing the results if specified, saving them to an output file, and confirming completion. It parses input arguments, executes alignment, conditionally prints results, saves alignments to the output fi... | def main():
input_file, should_print_results, output_file, muscle_exe = parse_args(sys.argv)
print('Parsed arguments, performing local MSA{}...'.format(' and saving results' if muscle_exe is not None else ''))
if muscle_exe is None:
alignments = align(input_file, output_file, muscle_exe)
pr... |
def new_metadata():
data = download_metadata()
old_data = current_metadata()
if old_data is None:
return data
date = extract_date_from_metadata(data)
old_date = extract_date_from_metadata(old_data)
if date > old_date:
return data
return None
def download_database():
gl... | The main task of the code is to update or build a BLAST database. It checks for a new database version, downloads and processes it if available, then unzips and builds the database using the provided filepath. If no updates are found, it skips the process and confirms the database is up to date. | def main():
if len(sys.argv) < 2:
print('Expects the makeblastdb filepath as only argument')
exit(1)
print('Downloading database metadata...')
metadata = new_metadata()
if metadata is not None:
print('New database version found, downloading...')
database = download_datab... |
def intra_industry_rank(x: pd.Series, industry: pd.Series):
"""
Computes intra-industry cross-sectional ranks for a signal.
Parameters:
x (pd.Series): Series of the signal to calculate intra-industry ranks for.
industry (pd.Series): Series indicating the industry of each observation.
R... | The function calculates industry-neutral Z-scores for a ranked signal to ensure dollar-neutrality. It first ranks the input signal within each industry, then computes Z-scores for these ranks across industries. A check verifies that the sum of Z-scores within each industry is approximately zero, ensuring neutrality. Th... | def intra_industry_ranked_signal_z_score(x: pd.Series, industry: pd.Series):
"""
Calculates industry-neutral Z-scores for a ranked signal and ensures dollar-neutrality.
Parameters:
x (pd.Series): Series of the signal to calculate Z-scores for.
industry (pd.Series): Series indicating the ind... |
def _standardize(self) -> None:
"""
Demean or add intercept to feature.
"""
# Compute mean of feature
self.X_mean = np.mean(self.X, axis=0)
# Demean feature
self.X_demeaned = self.X - self.X_mean
# Add intercept if applicable, otherwise ... | The main task of the code is to fit a linear regression model by standardizing features, computing closed-form ordinary least squares (OLS) coefficients (beta), calculating residuals, and generating regression summary statistics. This process estimates model parameters, evaluates fit accuracy, and provides statistical ... | def fit(self) -> None:
# Preprocess feature
self._standardize()
# Compute closed-form OLS beta
self.beta = self._beta()
# Compute residuals
self.residuals = self._residuals()
# Compute summary statistics
self._regression_statistics() |
def calc_pelvis_scale_factors(ll, unitscale, offset=True):
# Get customised model landmarks.
cust_lasis = _get_cust_landmark(ll.models['pelvis'], 'pelvis-LASIS',
offset)
cust_rasis = _get_cust_landmark(ll.models['pelvis'], 'pelvis-RASIS',
... | This function generates a list of OpenSim::Scale objects for each body in a model, defining scaling factors. It calculates specific factors for pelvis, femurs, and tibias, then uses their average for other bodies (torso, talus, calcaneus, toes) if enabled. The output is a list of Scale objects for model scaling. | def calc_scale_factors_all_bodies(ll, unit_scaling, scale_other_bodies=True):
"""
Builds and returns a list of OpenSim::Scale objects, one for each Body in
the Model. Scale objects describe the scale_factors to be used for scaling
the Model.
inputs
------
ll:
unit_scaling:
scale_oth... |
def seek(self, frame):
self.framen = frame
# self.current_depth = None
self.current = self._read_frame(self.framen)
def eof(self):
return self.framen > self.max_frame
def is_valid(self, frame_types=['Color', 'Depth']):
for t in frame_types:
if self.current[t] is None:... | This code advances to the next valid frame by seeking forward until a frame with both 'Color' and 'Depth' data is found, then returns the current frame if valid; otherwise, returns False when reaching the end of the file. | def next(self):
self.seek(self.framen + 1)
while not self.eof() and not self.is_valid(['Color', 'Depth']):
# print(f'missing frame={self.current_frame}',end='\r')
self.seek(self.framen + 1)
# if self.eof():
# self.current_color = None
# self.curr... |
def set_rb(words):
# create an rb tree
rb_tree = RBTree()
# read the file
file2 = open(words, "r")
line = file2.readline()
# while loop to read all lines in file
while line:
# each word is added to the tree
new_word = line.rstrip().lower()
rb_tree.insert(new_word)
... | The code allows users to select a tree type (Red Black, AVL, or BTree), constructs the chosen tree from a word file, prints the tree structure, searches for anagrams of specific words, counts anagrams, and identifies the word with the most anagrams, displaying results for the selected tree type. | def main():
print("What kind of tree do you want?")
print("Type the number.")
kind_of_tree = input("1. Red Black Tree\n2. AVL Tree\n3. BTree\n")
if kind_of_tree == '1':
rb_tree = set_rb("words.txt")
print("Red Black Tree:")
print_tree(rb_tree.root)
print()
print("... |
def search_a_recipe(self, input_text):
print("inside search_a_recipe")
input_text = input_text.strip()
input_text = re.sub("[^A-Za-z0-9 ]+", "", input_text)
input_text = input_text.split(" ")
tmp_all_strings = all_recipes_names.copy()
for single_string in input_text:
... | The main task of the code is to parse user input text to determine recipe-related actions. When no recipe is selected, it searches for recipes, handles "select:" or "url:" commands, or prompts for recipe searches. When a recipe is selected, it focuses on changing recipes or splitting input into question types. The func... | def parse_text(self, input_text: str):
# Do it here
if self.recipe_selected == False:
search_regex = self.regex_match_recipe(input_text)
if search_regex:
return self.search_a_recipe(search_regex)
if input_text.startswith("select:"):
ret... |
def subnet_24(ip)-> list:
subnet = []
max_val = ip[3] + 255
while(ip[3] <= max_val):
subnet.append([ip[0],ip[1], ip[2], ip[3]])
ip[3] += 1
subnet.append([255,255,255,255])
subnet.append([0,0,0,0])
return subnet
def loadP(singlepacket, counter):
custom_packet = Pigget(singlepacket, counter)
retur... | The main task of the code is to analyze packets from a pcap file, generate unique Snort rules, count their occurrences, append nmap scan rules, and return the rules, counts, SID start, packet list, and a print flag. It processes each packet, creates rules via RuleMaker, tracks duplicates, integrates nmap findings, and ... | def run_pcap(pcap):
global subnet
subnet = subnet_24(Network_IP)
counter = 1
snort_rules = []
occurences = []
global SID_START
for packet in pcap:
packet = loadP(packet, counter)
rule_list = []
rule_list = RuleMaker(packet)
for rule in rule_list:
if rule not in snort_rules:
r... |
def is_venv() -> bool:
"""Whether in a virtual environment(also work for poetry)"""
return hasattr(sys, "real_prefix") or (
hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
)
def check_call(cmd: str) -> bool:
r = _run_shell(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
... | The main task of the code is to execute Python unit tests using pytest with coverage analysis, generating a report while omitting test files. It dynamically adjusts the command to use Poetry for dependency management if the environment lacks a virtual environment or coverage tool, and supports a dry-run mode to only pr... | def test(
dry: bool = Option(False, "--dry", help="Only print, not really run shell command"),
):
"""Run unittest by pytest and report coverage"""
cmd = 'coverage run -m pytest -s && coverage report --omit="tests/*" -m'
if not is_venv() or not check_call("coverage --version"):
sep = " && "
... |
def getUniqueDevices():
#######################################################################
## gets all of the unique devices ##
## PARAMETERS: ##
## Return: ... | The main task of the code is to update the `dataFraction` field in the `Devices` database table for all unique devices. It retrieves unique device serial numbers, calculates their daily data fractions using `updateDataFractionForToday()`, prepares SQL `UPDATE` statements, and applies the updates in bulk via `executeman... | def updateAllDataFraction():
sns = getUniqueDevices()
list = []
for sn in sns:
list.append(updateDataFractionForToday(sn))
mydb = connect()
mycursor = mydb.cursor()
query = "UPDATE Devices SET dataFraction = %s WHERE sn = %s"
mycursor.executemany(query, list)
mydb.commit() |
def tokenise_ad(self, job_ad):
tokens = []
sent_text = nltk.sent_tokenize(job_ad)
for line in sent_text:
tokens.extend(self.clean_sentence(line.strip()))
return tokens
def get_ad_score(self, tokens, bag_of_words):
# existing words and vectors for some bias
bia... | The code computes gender and age bias scores for input text by comparing tokenized words against predefined word lists (masculine, feminine, old, young). It calculates scores using `get_ad_score`, applies smoothing, and generates synonyms and vectors. The function returns gender (fem/masc), age (old/young) scores, and ... | def compute_ad(self, inp, synonyms_outfile, img_outfile):
self.synonyms_outfile = synonyms_outfile
self.inp = inp
start = time.time()
self.tokens = self.tokenise_ad(inp)
end = time.time()
print(f"Time to tokenize input: {end-start}")
#TODO: right now, score is j... |
def load_bag_of_words(path):
with open(path, 'r') as f:
return [x.strip() for x in f.readlines()]
def get_ad_score(tokens, bag_of_words):
bias_words, bias_vectors = get_vectors(bag_of_words, False) #existing words and vectors for some bias
ad_words, ad_vectors = get_vectors(tokens, False) #existing... | The code computes and visualizes the distribution of gender bias scores in job advertisements using preloaded masculine and feminine word bags, generating histograms to compare bias tendencies across ads. | def plot_things():
masculine = load_bag_of_words(masculinebias)
feminine = load_bag_of_words(femininebias)
overall_m_scores = [get_ad_score(tokenise_ad(ad), masculine) for ad in job_ads]
overall_f_scores = [get_ad_score(tokenise_ad(ad), feminine) for ad in job_ads]
fig, axs = plt.subplots(1, 2, sh... |
def cli_args():
"""Summary
Returns:
TYPE: Description
"""
parser = argutil.get_parser(
"fulc_postgre.py"
"move signal Preventive Maintenance work orders from fulcrum to postgresql database",
"--last_run_date",
"--replace"
)
args = parser.parse_args()... | The main task of the code is to synchronize data between Fulcrum and a PostgreSQL database via pgRest. It retrieves and processes Fulcrum form records, aligns them with existing pgRest data, prepares payloads for upsert operations, and executes the sync with an option to replace existing records. The function returns t... | def main():
"""Summary
Returns:
TYPE: Description
"""
args = cli_args()
fulcrum = fc.Fulcrum(key=key)
forms = fulcrum.forms.search(url_params={"id": form_id})
col_names = get_col_names(fulcrum, form_id)
records = get_fulcrum_records(fulcrum, form_id)
records = interpre... |
def get_job_id(job_name: str) -> list:
"""Returns job info based on the job name. Returns a summary
of every job with the matching name.
:param job_name: Name of the Flink job.
"""
url = f'http://{FLINK_CLUSTER}/v1/jobs/overview'
response = requests.get(url).json()
matching_jobs = []
... | This function upgrades a job by stopping its current instance and re-uploading it with updated configurations. It checks the job's state, creates savepoints for stateful updates (if needed), and restarts the job using the new configuration. The function handles both stateful and stateless updates, logs errors for inval... | def upgrade_job(config: dict) -> None:
"""Upgrades a job by stopping and re-uploading the job.
:param config: job request.
"""
# Gets the running job, there should only be one.
#TODO: Error handling on multiple running jobs.
jobs = get_job_id(config['name'])
for job in jobs:
if ... |
def check_uploads(job_name: str,
job_id: str=None,
invalid_status: list=['FINISHED', 'CANCELED', 'FAILED'],
retries: int=5) -> bool:
"""Checks if a job has successfully been submitted to
the cluster.
:param job_name: Name of the submitted job.
:... | The main task of the code is to submit and manage Flink jobs by processing a list of operations (CREATE, UPDATE, STOP, SAVEPOINT, SKIP) on pipelines. It checks job existence, handles state transitions (e.g., creating jobs if not existing, updating running jobs, stopping jobs with savepoints), and logs errors for invali... | def submit_jobs(pipelines: list) -> None:
"""Submit pipelines to the Flink cluster.
:param pipelines: List of job create/upload/delete requests.
"""
upgrade_types = ['STATEFUL_UPDATE', 'STATELESS_UPDATE']
for command in pipelines:
# Check if the job is already running
exists = c... |
def run_job_server(jar_path: str, flink_cluster: str) -> typing.Type[subprocess.Popen]:
"""Starts up a job server using a local jar file. By default, the job service
will be started on localhost:8099.
:param jar_path: Local path to the job server jar file.
:param flink_cluster: Address of the Flink clu... | The function initializes a Flink job service, waits for it to start successfully within a timeout, submits specified Apache Beam pipelines to the cluster, and then terminates the service, logging progress and errors as needed. | def run_upload_process(pipelines: dict) -> None:
"""Starts a job service and uploads Apache Beam
pipelines to a Flink cluster.
:param pipelines: List of job create/upload/delete requests.
"""
x = run_job_server(JAR_PATH, FLINK_CLUSTER)
timeout = 300
t = time.time()
while True:
... |
def init_path(save_path):
save_path = save_path
train_path = os.path.join(save_path, "train")
gallery_path = os.path.join(save_path, "gallery")
query_path = os.path.join(save_path, "query")
paths = [train_path, gallery_path, query_path]
create_folder(save_path)
for path in paths:
c... | The main task of the code is to prepare training and validation datasets based on a configuration. It creates directory structures, generates training data using specified scene durations, constructs validation data, and splits the validation set into gallery and query subsets for evaluation. The function handles file ... | def main(cfg: DictConfig) -> Tuple[dict, dict]:
print("START")
try:
os.makedirs("data")
except FileExistsError:
pass
save_path = os.path.join(cfg.paths.data_dir, cfg.data_type.dataset_name)
# create dataset folder
train_path, gallery_path, query_path = init_path(save_path)
... |
def report_vm_list(self):
logger.info(line)
logger.info("Printing VMs name list")
logger.info(line)
for vm in self.rs.windows_vms:
logger.info(f"{vm.Name}")
for vm in self.rs.linux_vms:
logger.info(f"{vm.Name}")
def report_windows_vms(self):
if len... | The main task of the code is to generate comprehensive reports by sequentially invoking specialized reporting methods for virtual machines (VMs), including Windows, Linux, SQL, Azure SQL, and AKS. Each method likely compiles specific data or metrics related to its designated VM type or service, aggregating them into a ... | def report(self):
self.report_vm_list()
self.report_windows_vms()
self.report_linux_vms()
self.report_sql_vms()
self.report_sql_mi()
self.report_azure_sql()
self.report_aks() |
def check_if_won(self):
for i in range(self.row_count):
for j in range(self.column_count - self.req_to_win + 1):
value = self.square_values[i][j]
for k in range(1, self.req_to_win):
if value != self.square_values[i][j + k]:
... | The code handles mouse input to update a grid-based game state, toggling players and marking squares. It checks for winning sequences in rows, columns, and diagonals, dynamically expanding the grid when the board fills. If the grid exceeds screen size, it reduces square dimensions. The function also manages game logic,... | def update(self):
mouse_pos = pygame.mouse.get_pos()
mouse_pressed = pygame.mouse.get_pressed()[0]
if mouse_pressed - self.mouse_pressed == 1:
if mouse_pressed:
if self.pos[0] < mouse_pos[0] < self.pos[0] + self.square_width * self.column_count and self.pos[1] < \
... |
def sort_open_based_on_keys(self):
# change this based on version of python
# refer to https://stackoverflow.com/questions/5213033/sort-a-list-of-lists-with-a-custom-compare-function/46320068#46320068
self.OPEN = sorted(self.OPEN, key = cmp_to_key(lambda state1, state2: self.compare_keys(state... | The code implements a path comparison and improvement algorithm (CIP) for graph traversal. It iteratively sorts and processes nodes in the OPEN list, comparing their costs to the start node. When a node's current cost (g) exceeds its potential cost (rhs), it updates the node's state, propagates changes to predecessors,... | def cip(self):
'''
cip == Compare or Improve Path
'''
self.sort_open_based_on_keys()
while self.compare_keys(self.OPEN[0], self.start) == 1 or self.start.rhs != self.start.g:
print('inside loop')
self.sort_open_based_on_keys()
s = self.OPEN... |
def keys(self, s):
'''
Returns key(s) function as mentioned in the algorithm
'''
if self.g(s) > self.rhs(s):
keys = [self.rhs(s) + self.epsilon * self.hueristic(self.start, s), self.rhs(s)]
else:
keys = [self.g(s) + self.hueristic(self.start, s), self... | This code implements a path planning algorithm by initializing start/goal nodes with heuristic values, setting up priority queues (OPEN, CLOSED), and executing the 'cip' method to compute an optimal path. It then retrieves and visualizes the path while handling exceptions for unreachable goals or obstacles. | def main(self):
'''
Main function
'''
try:
self.start.g = np.Infinity
self.start.rhs = np.Infinity
self.goal.s = np.Infinity
self.goal.rhs = 0
self.nodes.append(self.start)
self.nodes.append(self.goal)
... |
def random_policy(nodedict):
policy = {}
keys = nodedict.keys()
decisions = {}
for i in keys:
iNode = nodedict[i]
if iNode.decision or iNode.chance:
decisions[i] = nodedict[i]
if iNode.decision:
policy[i] = random.choice(iNode.children) # might nee... | The function `get_situated` generates a random policy and associated decision indices, equations, and checks policy existence in a dataframe. It initializes components for a system using a node dictionary and returns the policy, decisions, indices, and equations for further processing or analysis. | def get_situated(nodedict,df):
policy,decisions = random_policy(nodedict)
indices = index(nodedict,decisions)
equations = initialize(nodedict)
check_policy_exists(nodedict,policy,df,indices,equations)
return policy,decisions,indices,equations |
def get_situated(nodedict,df):
policy,decisions = random_policy(nodedict)
indices = index(nodedict,decisions)
equations = initialize(nodedict)
check_policy_exists(nodedict,policy,df,indices,equations)
return policy,decisions,indices,equations
def simulate_improve(nodedict,policy,maximize,df,decision... | The function `ideal_policy` iteratively refines a decision-making policy by simulating improvements until changes fall below a specified tolerance or a maximum number of iterations is reached. It initializes policy parameters, updates them via simulation, reinitializes equations each iteration, and outputs the optimize... | def ideal_policy(nodedict,tolerance,iterations,maximize,df):
policy,decisions,indices,equations = get_situated(nodedict,df)
max_diff = 10e9
i = 0
# print(indices)
while max_diff > tolerance and i < iterations:
policy,max_diff,expectations = simulate_improve(nodedict,policy,maximize,df,decisi... |
def handle_parent(nodedict,parents,rootstr):
parent = get_parent(nodedict,rootstr)
return handle_children(parent,nodedict,parents,rootstr)
def handle_nonedge_description(nodedict,leaves,rootstr):
try: # leaf
nodedict,leaves = handle_leaf(nodedict,leaves,rootstr)
except ValueError: # probability ... | This function processes a node description (internal or leaf) from a file, updating data structures (nodedict, parents, leaves) based on the root string. It handles internal nodes via handle_parent or leaf/probability entries via handle_nonedge_description, then reads the next line from the file, returning updated para... | def handle(nodedict,parents,leaves,rootstr,f):
if rootstr != "" and rootstr[0] != "#":
try: # internal node
nodedict,parents = handle_parent(nodedict,parents,rootstr)
except ValueError: # leaf or probability description
nodedict,leaves = handle_nonedge_description(nodedict,le... |
def log(self, message):
if self.log_level:
log_level = str(self.log_level).lower()
debug_timestamp = datetime.datetime.now().isoformat()[0:19]
debug_filename = os.path.basename(inspect.stack()[1][1])
debug_function_name = inspect.stack()[1][3]
debug_l... | The code initializes a bot with configurable parameters like deafness, muteness, wake word, and language. It sets up a speech recognizer, configures text-to-speech if enabled, initializes a microphone if not deaf, and loads skills. Logging is used to track initialization steps, ensuring the bot is ready for interaction... | def __init__(self, **kwargs):
self.deaf = kwargs.get("deaf", False)
self.dumb = kwargs.get("dumb", False)
load_skills = kwargs.get("load_skills", True)
self.log_level = kwargs.get("log_level", False)
self.wake_word = kwargs.get("wake_word", "Eliza")
self.voice_language =... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def load_and_cache_examples(args, task, tokenizer, evaluate=False, percentage=100):
if args.local_rank not in [-1, 0] and not evaluate:
... | The code defines a script for training and evaluating a pre-trained model on a sequence classification task (e.g., GLUE benchmarks). It parses arguments for data paths, model configuration, training parameters, and task-specific settings. The script initializes the model, tokenizer, and training setup, supports distrib... | def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--data_dir",
default=None,
type=str,
required=True,
help="The input data dir. Should contain the .tsv files (or other data files) for the task.",
)
parser.add_argument(... |
def random_noise_image(w,h):
random_image = Image.fromarray(np.random.randint(0,255,(w,h,3),dtype=np.dtype('uint8')))
return random_image
def random_gradient_image(w,h):
array = gradient_3d(w, h, (0, 0, np.random.randint(0,255)), (np.random.randint(1,255), np.random.randint(2,255), np.random.randint(3,128))... | The code optimizes a neural network model to generate images aligned with specified text and image prompts. It initializes latent variables (z) using input images, noise, or random embeddings, then iteratively adjusts z via optimization (e.g., Adam, AdamW) to minimize losses derived from CLIP-encoded prompts. The proce... | def iterate_func():
cut_size = perceptor.visual.input_resolution
f = 2**(model.decoder.num_resolutions - 1)
make_cutouts = MakeCutouts(cut_size, args.cutn, cut_pow=args.cut_pow)
toksX, toksY = args.size[0] // f, args.size[1] // f
sideX, sideY = toksX * f, toksY * f
if gumbel:
e_dim = ... |
def random_lp_vector(shape, ord, eps, dtype=tf.float32, seed=None):
"""
Helper function to generate uniformly random vectors from a norm ball of
radius epsilon.
:param shape: Output shape of the random sample. The shape is expected to be
of the form `(n, d1, d2, ..., dn)` where `n` is the number... | The code generates adversarial examples using Projected Gradient Descent (PGD) by iteratively applying Fast Gradient Sign Method (FGSM) steps, projecting perturbations into a norm ball (e.g., L∞), and clipping results to specified input bounds. It supports targeted/untargeted attacks, random initialization, and sanity ... | def pgd_generate(x, model, eps=0.3,eps_iter=0.05, nb_iter=10, y=None, ord=np.inf, clip_min=None, clip_max=None, y_target=None,
rand_init= True, rand_init_eps= 0.3, clip_grad=False, sanity_checks=True):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's s... |
def get_source_variable_from_wave(self, variable):
""" Check if there is a map for the source id.
"""
source_variable = self.get_source_variable(variable)
return (self.create_variable_names(source_variable, self.fu_prefix, self.fu_suffix))
def valid_row_value(variable, row, ignore_values... | The function parses person data from a row, extracting gender and birth year. It prioritizes direct variables; if unavailable, it infers birth year from age and a reference date. Validations ensure data integrity, raising errors for missing info. Finally, it constructs and executes an SQL query to insert the person's d... | def parse_person(self, row):
""" Parse the person information from the row.
"""
sex_source_variables = self.get_source_variable_from_wave(GENDER)
sex_source_variable = None
for source_variable in sex_source_variables:
if self.valid_row_value(source_variable, row):
... |
def get_source_variable(self, variable):
""" Check if there is a map for the source id.
"""
return self.source_mapping[variable][SOURCE_VARIABLE] if variable in self.source_mapping else None
def valid_row_value(variable, row, ignore_values=[], validation=None, limit=None):
""" Validate i... | The function processes dataset rows by mapping source IDs to person IDs, parsing records, handling visit data with prefixes/suffixes, and tracking processed/skipped records. It validates source IDs, updates existing person records, inserts new ones, and transforms rows into visits. Errors are logged, and progress is re... | def transform_rows(self, iterator, start, limit):
""" Transform each row in the dataset
"""
id_map = {}
processed_records = 0
skipped_records = 0
id_source_variable = self.get_source_variable(SOURCE_ID)
if not id_source_variable:
print("No source id va... |
def _draw(self):
self.screen.fill(self.colors.BACKGROUD_COLOR)
self.map.draw()
img = self.font.render('SCORE: '+str(round(self.max_score,1)), True, (255,255,255))
self.screen.blit(img, (20, 20))
def rayCast(self, car, lines):
first_line = lines[0]
second_line = lines[1]
... | This code evaluates neural networks (genomes) using NEAT by simulating car control in a game. It initializes cars, processes sensor inputs via neural networks to steer, updates fitness scores based on survival and collisions, and runs a game loop to assess each genome's performance. | def fitness(self,genomes,config):
self.max_score = 0
for _,g in genomes:
net = neat.nn.FeedForwardNetwork.create(g,config)
self.nets.append(net)
self.cars.append(Car(self.screen,self.dir_path,self.width//2,self.height-self.height//5))
g.fitness = 0
... |
def load_dataset(dataset):
X_data = []
y_data = []
for i in dataset:
iegm_seg = i['IEGM_seg'].flatten()
label = i['label']
X_data.append(iegm_seg)
y_data.append(label)
return np.array(X_data), np.array(y_data).reshape(-1,1), np.array(extract_labels(dataset))
def extract_f... | The main task of the code is to train and evaluate a Decision Tree Classifier (DTC) on a dataset of IEGM signals. It loads training/test data, extracts features using specified hyperparameters (sigma, window, depth), trains the DTC, and evaluates performance via confusion matrices, false positive/negative rates, F-beta... | def main(args):
# Hyperparameters
SIZE = args.size
path_data = args.path_data
path_indices = args.path_indices
hyper_param = {}
hyper_param["sigma"] = args.sigma
hyper_param["window"] = args.window
hyper_param["depth"] = args.depth
#sigma = args.sigma
#window = args.window
... |
def _reset_robot(self):
twist, _, _ = self._compute_twist(0, 0, 0)
self.twist_pub.publish(twist)
if not self.continuous:
self._perform_sim_steps(10)
self._open_gripper()
self._set_table_params(0.01)
self._setLoad(mass=0, load_inertia=list(np.eye(3).flatten(... | The main task of the code is to reset the robotic simulation environment, initialize robot parameters, and attempt a successful object grasp. It repeatedly resets the robot and tries grasping until success or 10 retries, then computes table height and returns observations/info. The method handles message synchronizatio... | def reset(self, seed=None, options=None):
super().reset(seed=seed)
self._reset_robot()
success = False
self.last_command = None
self.sim_steps = options['sim_steps']
self.max_episode_steps = options['max_steps']
self.noop_counter = 0
self.cont... |
def _reset_env(self, options):
restart_counter = 0
success = False
while not success:
obs, info = self.env.reset(options=options)
success = info['info']['success']
if not success:
print('Resetting Env unsuccessful. Restarting...')... | This code trains a reinforcement learning agent using curriculum learning to perform a task (e.g., object placement) by gradually increasing environmental difficulty parameters (gap size, angle range). It collects experiences, updates a policy network via optimization, and adjusts task complexity based on test performa... | def train(self):
for episode in range(self.START_EP+1, self.START_EP + self.N_EPOCHS+1):
sampled_gap = np.random.uniform(0.002, self.gapsize)
obs, info = self._reset_env(options={'gap_size' : sampled_gap, 'testing' : False, 'angle_range' : self.angle_range, 'sim_ste... |
def fetch_tail_numbers():
tail_number_tmp = {}
did_objects_id_tmp = {}
tail_number_ter_type_tmp = {}
rfterm_type_tmp = {}
response_sattle = requests.get(API_IDIRECT_SATTLE, auth=pulse_auth)
sattle_data = response_sattle.json()['data']
for sattle in sattle_data:
did = sattle['... | The main task of the code is to aggregate data from multiple servers by calling the loggingServices function, process the results with append_beams, and return a consolidated dictionary of server-specific data. It fetches global variables (tail_numbers, rftermtype__numbers) first, iterates through servers, transforms s... | def tpaGetAllList(options=None):
result = {}
global tail_numbers
global rftermtype__numbers
########## DON'T DELETE THIS ################
tail_numbers, rftermtype__numbers = fetch_tail_numbers()
#############################################
for server in servers:
server_key = serve... |
def generatePopMap():
population_map = {}
populations = []
with open(popfile,'r') as popF:
lines = popF.readlines()
for line in lines:
line = line.split()
sample = str(line[0])
samplePop = str(line[1])
population_map[sample] = samplePop
... | The main task of the code is to process a VCF file into ARP format for population genetic analysis. It generates a population map, splits output into contig-specific ARP files if specified, or writes a single ARP file for the entire VCF. The code warns against computational challenges with large datasets and uses `buil... | def main():
#TODO: parse popFile and find location of sample in chromLine:
popMap,popList = generatePopMap()
print("[STDOUT]: Your populations are:",list(popList))
print("[STDOUT]: Your population map indicates the following mapping:",popMap)
if args.splitContigs:
contigList = findContigs()
... |
def show_month_balance_label(self):
month, year = self.get_date()
self.list_month = self.analizer.get_month(self.controler.expenses, month, year)
balance_month = self.analizer.get_balance(self.list_month)
balance_month = balance_month / 100
self.balance_of_month.config(text=balan... | The code's main task is to display and calculate monthly balance information by calling three methods: showing a month balance label, calculating total balance before a specific month, and determining the total balance after the specified month. It aggregates financial data for a given month, providing a summary of bal... | def view_month_balance(self):
self.show_month_balance_label()
self.total_balance_before_specific_month()
self.total_balance_after_month() |
def get_title_list(list_url):
with urllib.request.urlopen(list_url) as response:
return response.read().decode("utf-8")
def get_title_data(self, url):
with urllib.request.urlopen(url) as response:
return ET.fromstring(response.read().decode("utf-8"))
def process_title(self, title... | The main task of the code is to fetch and process title data from a web API. It constructs URLs using a base endpoint and a dynamic title number, retrieves a list of titles, parses XML data, and iterates through each title to fetch and process its specific content using `get_title_data` and `process_title` methods. The... | def update(self):
list_url = "https://glen.le.utah.gov/code/list/" + self.api
data_url_template = "https://glen.le.utah.gov/code/{}/" + self.api
title_list_data = self.get_title_list(list_url)
if title_list_data:
title_data_root = ET.fromstring(title_list_data)
... |
def getInput(self, message, type_inp, default_value):
inp = input(message)
inp = inp.strip()
if inp == '':
inp = default_value
if type_inp == 'int':
try:
val = int(inp)
if val > -1:
return val
e... | This code generates a dictionary of all possible character combinations based on user-specified parameters like word length, character sets (letters, numbers, symbols), and saves it to a file for pentesting. It calculates total combinations, handles input validation, and writes results to a text file, ensuring no exist... | def __init__(self):
print
'- WHK Dictionary Maker 1.0, for pentesting purposes.';
# self.user_min_longitude = self.getInput('- Enter min longitude of word [0] : ', 'int', '0')
self.user_max_longitude = self.getInput('- Enter max longitude of word [4] : ', 'int', '4')
... |
def get_all_sockets():
all_sockets = [sys.stdin]
for addr, sock in SOCKET_LIST.items():
all_sockets.append(sock)
return all_sockets
def add_user(server_socket):
new_socket, new_addr = server_socket.accept()
new_socket.settimeout(30)
SOCKET_LIST[new_addr] = new_socket
all_users = ""... | This code sets up a TCP server to handle multiple client connections using I/O multiplexing. It initializes a socket, binds it to a host/port, and uses `select.select` to monitor sockets for incoming data. When a new connection arrives, it adds the client to the socket list. For existing connections, it receives and pr... | def server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
# Server socket has the key 'Host'
SOCKET_LIST['Host'] = server_socket
print("\nChat... |
def new_stim(self, protocol_listed):
# Set up a condition for making a new stimulation protocol
StimConstructor.StimConstructor(tk.Toplevel(self.window),protocol_listed, self.colors,pi=self.pi)
def stim_constructor_setup(self, protocol_listed,callFrame):
## Sets up the command window for using saved .pi files
# Fi... | This code updates a GUI interface based on selected protocol mode. It destroys existing widgets, then configures either a "stim constructor" mode with stimulus creation or a traditional protocol mode with command sending and history tracking. It manages dynamic UI elements like buttons, frames, and scrollable history d... | def prot_specs(self,protocol_listed,pi):
# Establish a frame with the option to send commands
# Clear out the old ones
map(lambda entry: entry.destroy(), self.command_entries)
map(lambda label: label.destroy(), self.command_labels)
self.mode_box.destroy()
## Make sure that the old "New stimulus" button is ... |
def _create_ui_elements(self, params):
def _create_str_var(text):
str_var = tk.StringVar()
str_var.set(text)
return str_var
def _create_label(text):
str_var = _create_str_var(text)
return tk.Label(self.root, textvariable=str_var)
def ... | The code initializes and runs a graphical user interface (GUI) for a guitar training application by creating UI elements, drawing a guitar neck diagram, updating note visualization circles, and starting the GUI event loop to display the interface. | def run(self, params: GuitarTrainerGuiRunParams):
self._create_ui_elements(params)
self._draw_neck(params)
self._update_note_circles(params)
self.root.mainloop() |
def getChipId(ser, req):
print("MESSAGE: Get Chip ID")
resp = struct.pack('>BI', 0, 0x0000b686)
sendMessage(ser, 0x33, resp)
def readRAM(ser, req):
addr, len = struct.unpack("<IH", req)
print("MESSAGE: Read RAM addr={:08x} len={:04x}".format(addr, len))
resp = struct.pack('>B', 0)
resp... | The main task of the code is to process serial communication by reading message headers (length and type), parsing data payloads, and executing specific functions based on message types (e.g., chip ID retrieval, RAM read/write, flash operations) to interact with a hardware device through a serial port. | def main():
ser = serial.Serial('COM6', baudrate=38400, timeout=1)
while True:
data = ser.read(2)
if not data:
continue
msglen, msgtype = struct.unpack('BB', data)
print()
print("Message length: " + str(msglen))
print("Message type: {:02x}".format(ms... |
def check(cond, errmsg):
if not cond:
raise RuntimeError(errmsg)
def getChipId(ser):
print("Requesting Chip ID")
resp = sendRequest(ser, 0x32, b'')
status, chipId = struct.unpack('>BI', resp)
print("Received chip ID {:08x} (Status={:02x})".format(chipId, status))
check(status == 0, "Wro... | The main task of the code is to flash firmware onto an NXP JN5169 device using either a serial port or a remote server. It parses command-line arguments, validates input, reads the firmware file, establishes a connection, retrieves the device's MAC address, prepares the device, erases its flash memory, writes the firmw... | def main():
# Parse command line arguments
parser = argparse.ArgumentParser(description="Flash NXP JN5169 device")
parser.add_argument("-p", "--port", help="Serial port")
parser.add_argument("-s", "--server", help="Remote flashing server")
parser.add_argument("-f", "--file", required=True, help="Fi... |
def compute_polar_distance(n_gram_vec_1, n_gram_vec_2):
distance = 2 * np.arccos((np.dot(n_gram_vec_1, n_gram_vec_2) / np.sqrt(np.dot(n_gram_vec_1, n_gram_vec_1) * np.dot(n_gram_vec_2, n_gram_vec_2)))) / np.pi
return distance
def getHalfPoint(scores):
values = [x[1] for x in scores]
total = sum(values) * 3 / 4
c... | This function divides a specified cluster into two sub-clusters by removing distinguishing features, computing pairwise distances, and iteratively splitting vectors based on distance metrics. It updates cluster assignments, identifies new cluster IDs, calculates distinguishing features using chi-square tests, and recor... | def divide(vectors, clusters, distinguishing_features, clusters_info, cluster_id, whole_distances, k, len_vectors):
myLogger.info('Dividing cluster %d' % cluster_id)
distinguishing_feature = [f for idx, features in distinguishing_features[cluster_id] for f, score in features]
selected_vector_idx = np.where(clus... |
def ngrams_to_vectors(n_gram_1, concatenated_set):
counter_ngram_1 = Counter(n_gram_1)
n_gram_vec_1 = np.asarray([(counter_ngram_1[n]) for n in concatenated_set])
return n_gram_vec_1
def compute_polar_distance(n_gram_vec_1, n_gram_vec_2):
distance = 2 * np.arccos((np.dot(n_gram_vec_1, n_gram_vec_2) / np.sqrt(n... | This code performs divisive clustering on ngram vectors by iteratively splitting clusters based on pairwise distances, maximizing modularity and silhouette scores. It initializes clusters, computes distances, and recursively divides the largest cluster until reaching the target number of clusters, returning final clust... | def divisive_clustering(ngrams, concat_set, n_clusters, k, target = []):
vectors = np.asarray([ngrams_to_vectors(ngram, concatenated_set=concat_set) for idx, ngram in enumerate(ngrams) if idx in target])
clusters = np.asarray([1 for vector in vectors])
distinguishing_features = {1: []}
len_vectors = len(vect... |
def clone_git_repository(url, target_path):
os.chdir(target_path)
git_clone_command = "git clone " + url
print("Cloning repository from :{} into {}".format(url, target_path))
p = subprocess.Popen(git_clone_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ""
for lin... | The code clones a GitHub repository, extracts commit logs, selects snapshots based on a time threshold, and downloads specified commits. It checks if the repo is already cloned, extracts logs if needed, lists commits, filters selected ones, exports them, and downloads the corresponding snapshots for analysis or archivi... | def main():
repository_url = "https://github.com/objectcomputing/OpenDDS.git"
repo_target_path_root = "C:\\Users\\C5265284\\mona"
cloned = 1 # 0 if not cloned yet, else 1
log_extracted = 1 # 0 if not log is not extracted yet, else 1
if cloned == 0:
clone = clone_git_repository(url=reposi... |
def check_det_bboxes(gt_bboxes, det_bboxes, iou_threshold):
gt_bboxes = gt_bboxes.copy()
det_bboxes = det_bboxes.copy()
gt_bboxes["Match"] = False
det_bboxes["Correct"] = False
det_bboxes.sort_values("Score", ascending=False, inplace=True)
for det_bbox in det_bboxes.itertuples():
cor... | This function calculates object detection evaluation metrics for a specified class by comparing ground truth and detected bounding boxes. It filters boxes by class, matches them using IoU threshold, computes true positives, false positives, and false negatives, then derives precision, recall, and average precision. It ... | def calc_metrics(gt_bboxes, det_bboxes, class_, iou_threshold):
taget_gt_bboxes = gt_bboxes[gt_bboxes["Label"] == class_]
taget_det_bboxes = det_bboxes[det_bboxes["Label"] == class_]
# print(det_bboxes)
# print(taget_gt_bboxes)
# raise
taget_gt_bboxes, taget_det_bboxes = check_det_bboxes(
... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--gt_path", type=Path, required=True,
help="txt path containing ground truth bounding boxes.")
parser.add_argument("--det_path", type=Path, required=True,
help="txt path containing detec... | The main task of the code is to evaluate object detection performance by calculating metrics (e.g., precision, recall) for each class using ground truth and detection bounding boxes. It aggregates results, plots PR curves per class, and saves metrics to a CSV file. The code parses input arguments, loads data, computes ... | def main():
args = parse_args()
gt_bboxes = load_gt_bboxes(args.gt_path)
det_bboxes = load_det_bboxes(args.det_path)
classes = gt_bboxes["Label"].unique()
results = []
for class_ in classes:
result = calc_metrics(gt_bboxes, det_bboxes, class_, iou_threshold=args.iou)
# print(r... |
def demoji(string, *, replacement='', isemojiclean=_unicode_emoji_context()):
"""
# Destroy emojis and most sequences found in the &string.
"""
# Iterate through the string segments that end with VS-16.
i = 0
while i < len(string):
eos = string.find('\uFE0F', i)
if eos == -1:
# No sequences to process
... | The code processes input lines by applying a series of filters and transformations, including emoji stripping, text filtering, and function-based filtering, then outputs the processed results. It uses configuration settings to determine which filters to apply, merges recognition data, and writes the final processed con... | def main(inv:process.Invocation) -> process.Exit:
config = {
'title-strip-emoji': False,
'text-filters': [],
'function-false-filters': [],
'function-true-filters': [],
}
ev = recognition.legacy(restricted, required, inv.argv)
remainder = recognition.merge(config, ev)
efilter = str
if config['title-strip-... |
def set_weights(self):
"""
Computes all vertex degrees. Also computes the maximal vertex degree
:return: Nothing. Vertex degree is stored in the 'weight' attribute of all nodes, maximal vertex degree in
the 'alpha' attribute of the graph
"""
weightlist = []
for v... | This function implements a stack-based variant of Wilson's algorithm to generate a random spanning tree on a graph. It uses exponential killing time parameter q to control node elimination, processes active nodes, and manages edge hiding. The algorithm handles loop detection, trajectory pruning, and root renumbering, a... | def stack_version_of_wilson(self, q, active_nodes: set = 'all', renumber_roots_after_finishing=False,
start_from_scratch=False, roots=None):
"""
Stack version of Wilson's algorithm
:param q: parameter of exponential killing time
:param active_nodes: Set of... |
def convert_values_to_np_array(self):
"""
computes numpy array with all the values. The order of the vertices is defined by their 'node_number'
:return: numpy-array of shape (n,) filled with the values of the vertices of the graph
"""
n = len(self.nodes)
value_vector = np... | This function reconstructs a signal by solving a system of linear equations involving Laplacian matrices and the Schur complement. It updates node values in-place using exponential decay parameter q, combining root and non-root components through sparse solvers to compute the final signal configuration. | def reconstruction_operator(self, q, L_Schur=None):
"""
reconstructs the signal (changes the values in-place)
:param q: parameter for exponential killing time
:param L_Schur: Schur complement. If not provided it will be computed.
"""
f_ana = self.convert_values_to_np_arra... |
def convert_values_to_np_array(self):
"""
computes numpy array with all the values. The order of the vertices is defined by their 'node_number'
:return: numpy-array of shape (n,) filled with the values of the vertices of the graph
"""
n = len(self.nodes)
value_vector = np... | This function reconstructs a signal by solving linear systems involving the Schur complement and Laplacian matrices of a graph, updating node values in-place while ignoring detailed nodes. It computes approximate signal values for roots and non-root nodes using sparse solvers, combining results from Schur complement ca... | def reconstruction_operator_without_detail_nodes(self, q, L_Schur=None):
"""
reconstructs the signal but only taking into account the approxmative vertices (changes the values in-place)
:param q: parameter for exponential killing time
:param L_Schur: Schur complement. If not provided it ... |
def choose_random_neighbor(self, node):
"""
Choose random neighbor according to weights
:param node:
:return: id of chosen node
"""
if not self.weights_are_set:
self.set_weights()
nodeweight = self.nodes[node]['weight']
temp = 0
r = nod... | This function processes an activated node in a coupled random forest structure by following non-hidden edges until a loop or another root is encountered. If a loop is detected, it removes the loop, reprocesses the tree rooted at the activated node, and updates edges. If another root is found, it updates the structure a... | def _process_activated_node(self, x, q2):
"""
Process activated node when we couple random forests and compute forest with new parameter q2<q_old
:param x: activated node
:param q2: new parameter
:return: number of reprocessed vertices
"""
number_of_reprocessed_no... |
def _initialise_panel(self) -> None:
self._panel = wx.Panel(self)
def _initialise_text_box(self) -> None:
self._text_box = wx.StaticText(self._panel, label="EORI IS VALID??")
font = self._text_box.GetFont()
font.PointSize += 2
font = font.Bold()
self._text_box.SetFont(fon... | This method initializes UI components for a wxPython application by creating a vertical layout with a BoxSizer, setting up text and input boxes, menu bars, and status bars, then assigning the sizer to the panel to manage widget arrangement and sizing. | def _initialise_widgets(self) -> None:
self._initialise_panel()
self._sizer = wx.BoxSizer(wx.VERTICAL)
self._initialise_text_box()
self._initialise_user_input_box()
self._initialise_top_menu_bar()
self._initialise_status_bar()
self._sizer.SetSizeHints(self._pane... |
def set_durations(self):
p = subprocess.Popen(
['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1',
self.get_file_path()],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output, errors = p.communic... | The code initializes an audio processing object by setting up file path attributes, temporary storage parameters, and audio specifications like duration, channels, frame rate, and sample width (fixed at 2 bytes). It prepares the object for handling audio data operations, likely for playback or analysis, by configuring ... | def __init__(self, file_path, **kwargs):
self.file_path = file_path
self.use_tmp = False
self.tmp_file = None
self.tmp_dir = None
self.base_name = os.path.basename(self.file_path)
self.wave_reader = None
self.set_durations()
self.set_channels()
sel... |
def get_config_env() -> Mapping[str, str]:
global _cfg
if not _cfg:
_cfg = {}
for key, value in os.environ.items():
if key.startswith("LSSLM_"):
_cfg[key[len("LSSLM_"):]] = value
return _cfg
def get_use_tls() -> bool:
cfg = get_config_env()
return cfg.g... | The main task of the code is to synchronize a Git repository with the latest versions of a package from FTP mirrors, using TLS if configured. It filters mirrors, downloads newer versions, handles errors, and pushes updates to the remote repository unless the --nopush flag is specified. The process continues until a val... | def main():
cfg = get_config_env()
repo = cfg["GIT_REPO"]
tls = get_use_tls()
push = True
if len(sys.argv) > 1 and sys.argv[1] == "--nopush":
push = False
mirrors = LIBRESSL_FTP_MIRRORS
if tls:
print("Using TLS mirrors only")
mirrors = list(
filter(
... |
def validate_http_request(request):
""" Check if request is a valid HTTP request and returns TRUE / FALSE and the requested URL """
#match = re.match('(GET)\s(.*)\s(HTTP/\d\.\d\r\n)',request)
if re.match('(GET)\s(.*)\s(HTTP/\d\.\d\r\n)',request):
match = re.match('(GET)\s(.*)\s(HTTP/\d\.\d\r\n)',req... | The function `threaded_handle_client` processes client requests by receiving HTTP data, validating it, and handling GET/POST requests. It checks request validity, sends 500 errors for invalid requests, processes valid ones using appropriate handlers, and closes the connection upon errors or completion. | def threaded_handle_client(client_socket):
""" Handles client requests: verifies client's requests are legal HTTP, calls function to handle the requests """
while True:
# Receiving client request
try:
print ('Wait for data recieve')
client_request = client_socket.recv(102... |
def _decode_mapping(code, buf):
dictid = struct.unpack('>I', buf[0:4])[0]
info = _parse_monmapinfo(buf[4:].decode('us-ascii'))
status = 'server-id' if code == '=' else \
'user-path-id' if code == 'd' else \
'user-info-id' if code == 'i' else \
'log-auth-id' if code == 'u' else \
... | The function `_decode_packet` decodes a packet by parsing its 8-byte header, validating length, and processing payload data based on the header code. It returns parsed values (stod, pseq) and payload-specific data, or error details if the packet is too short, has length mismatch, or contains an unrecognized code. | def _decode_packet(buf):
## Valid messages have an 8-byte header.
if len(buf) < 8:
return (stod, pseq, 'too-short', { 'unparsed': buf, })
## Decode the header.
code = buf[0:1].decode('ascii')
# if code not in '=dfgiprtux':
# return
pseq = int(buf[1])
plen = struct.unpack('>H... |
def _decode_packet(buf):
## Valid messages have an 8-byte header.
if len(buf) < 8:
return (stod, pseq, 'too-short', { 'unparsed': buf, })
## Decode the header.
code = buf[0:1].decode('ascii')
# if code not in '=dfgiprtux':
# return
pseq = int(buf[1])
plen = struct.unpack('>H... | The main task of the code is to process incoming network packets by decoding them, managing peer records (creating/updating based on timestamp comparisons), and performing periodic maintenance such as clearing expired identities, releasing old events, and writing statistics to a data store. It also includes error handl... | def record(self, addr, buf):
now = time.time()
try:
## TODO: Check if addr[0] is in permitted set.
## Parse the packet.
#stod, pseq, status, parsed
stod, pseq, status, data = _decode_packet(buf)
## Locate the peer record. Replace with a new ... |
def get_excellent_students(students):
excellent_students = []
for student in students:
if get_is_student_excellent(student):
excellent_students.append(student)
return excellent_students
def get_most_excellent_classroom(students_per_classroom):
best_classroom = None
best_classroom... | The main task of the code is to generate a comprehensive report summarizing student performance. It aggregates all students, identifies excellent students, determines the classroom with the most excellent students, finds the classroom with the highest average scores, and lists students requiring catch-up assignments. T... | def full_report(students_per_classroom):
all_students = []
for classroom in students_per_classroom:
for student in students_per_classroom[classroom]:
all_students.append(student)
print("----- Report -----")
print("Excellente studenten:")
excellent_students = get_excellent_studen... |
def generate_fake_students(self, amount):
students = []
for i in range(amount):
students.append(self.generate_fake_student())
return students
def write_as_python_file(self, students):
filename = f"{self.base_file}.py"
with open(filename, "w") as file:
file... | The main task of the code is to generate fake educational data containing multiple classes with randomly created student lists, then save this structured data either as a Python file or JSON file based on the write_as_python parameter. | def generate_fake_file(self, write_as_python=True):
classes = {}
for i in range(self.number_classes):
class_name = f"{self.class_prefix}1{string.ascii_uppercase[i]}"
students = self.generate_fake_students(self.number_students)
classes[class_name] = students
if... |
def get_highest_occup(n, id):
m = 0
while(id > get_sum(n, m)):
m += 1
return m
def get_sum(n, m):
if (n == 0):
return 1
if (m == 0):
return 0
if (m == 1):
return n
s = 0
for i in range(n):
s += get_sum(n-i,m-1) + 1
return s | This function recursively calculates the highest occupation number for a given level `n` and index `id`, adjusting for hierarchical offsets. It uses a helper function `get_highest_occup` and `get_sum` to determine positions in a multi-level structure. If `m` is not specified, it defaults to the maximum occupation value... | def get_highest_occup_number(n, id, m = None):
if(id == 0 and (m == None or m == 0)):
return n
if(id == 0 and m != 0):
return 0
max_occup = get_highest_occup(n,id)
offset_id = id - get_sum(n,max_occup-1) - 1
occup = 0
if(m == None or max_occup == m):
occup = 1
if(m ==... |
def get_highest_occup_number(n, id, m = None):
if(id == 0 and (m == None or m == 0)):
return n
if(id == 0 and m != 0):
return 0
max_occup = get_highest_occup(n,id)
offset_id = id - get_sum(n,max_occup-1) - 1
occup = 0
if(m == None or max_occup == m):
occup = 1
if(m ==... | The function `get_basis` computes the coefficients of a number's representation in a custom basis determined by recursive decomposition. It uses helper functions to find the highest occupied number and partial sums, iteratively adjusting indices and recursively solving subproblems to construct an array of coefficients.... | def get_basis(n,id):
mn = get_highest_occup_number(n,id)
mid = get_highest_occup(n,id)
ret = np.zeros(mid + 1)
ret[mid] = mn
if (n == 1):
return ret
if (mid == 0):
return ret
mxid = 0
while id >= get_partial_sum(n,mid,mxid+1):
mxid += 1
nid = id - get_partia... |
def L1(t,tau,k, n, x, dx, ddx, f):
xt_tau = x(t)-x(tau)
xt_tau = xt_tau[:,:,0].T
rotdxtau = dx(tau)[:,:,0].T@np.array(((0,-1),(1,0)))
nrmxt_tau = np.sqrt(np.sum(xt_tau**2,axis = 1))
v = k/(2*np.pi)*np.sum(rotdxtau*xt_tau,axis = 1)*J_1(k*nrmxt_tau)/nrmxt_tau
diagv,si = Ldiag(t,tau,k, n, x, dx, dd... | The function `getK` computes two complex matrices, `K1` and `K2`, by combining results from functions `L1`, `L2`, `M1`, and `M2` with a damping factor `eta`. It generates angular parameters `tau`, processes input vectors `t` and `tau` to align dimensions, constructs `K1` and `K2` as complex-valued matrices, and reshape... | def getK(t,k, n, x, dx, ddx, f,eta):
tau = np.linspace(0,2*n-1,2*n)*np.pi/n
t,tau,s = make_param_vecs(t,tau)
K1 = L1(t,tau,k, n, x, dx, ddx, f)+1j*eta*M1(t,tau,k, n, x, dx, ddx, f)
K2 = L2(t,tau,k, n, x, dx, ddx, f)+1j*eta*M2(t,tau,k, n, x, dx, ddx, f)
K1 = K1.reshape(s)
K2 = K2.reshape(s)
r... |
def create_board():
return(np.zeros((3, 3)))
def random_place(board, player):
selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return board
def possibilities(board):
l = []
for i in range(len(board)):
for j in range(len(board)):
... | This code implements a turn-based game where Player 1 makes random moves while Player 2 uses a minimax algorithm with depth 9 to select optimal moves. The game loop alternates turns, updates the board state, checks for a winner, and displays the result (win or tie) using message boxes. | def play_game():
board, winner, counter = create_board(), 0, 1
while winner == 0:
if counter % 2 != 0:
board = random_place(board, 1)
else:
best_score = float('-inf')
best_move = None
for move in possibilities(board):
board_copy = b... |
def empty_cells(board):
# Find all empty cells in the board
cells = []
for i in range(3):
for j in range(3):
if board[i][j] == 0:
cells.append((i, j))
return cells
def game_over(board):
# Check if the game is over
if wins(board, HUMAN) or wins(board, COMP):
... | The code implements the AI's turn in a game by using the minimax algorithm to determine the optimal move. It checks if the game is over, applies the AI's move to the board, updates the UI, and triggers the end game if the AI wins or the board is full. | def ai_turn(self):
depth = len(empty_cells(board))
if depth == 0 or game_over(board):
return
move = minimax(board, depth, COMP)
x, y = move[0], move[1]
set_move(x, y, COMP)
self.buttons[x][y]["text"] = self.c_choice
if wins(board, COMP):
... |
def update_buttons(board):
for i in range(3):
for j in range(3):
button_text = ""
if board[i][j] == 1:
button_text = "X"
elif board[i][j] == 2:
button_text = "O"
buttons[i][j].config(text=button_text, state="disabled")
def evalu... | This function handles a player's move in a game (likely Tic-Tac-Toe) by updating the board when a button is clicked. It checks if the selected cell is empty, places the player's mark (1), updates the UI, evaluates the game state, and displays win/tie messages or invalid move alerts. It ensures valid moves and manages g... | def on_button_click(row, col):
if board[row][col] == 0:
board[row][col] = 1
update_buttons(board)
winner = evaluate(board)
if winner == 0:
play_game()
elif winner == -1:
messagebox.showinfo("Game Over", "It's a tie!")
else:
messageb... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.