dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def confirm_val(self, index: int, num: int, vuln_field: str) -> requests.Response:
condition: str = self.gen_condition(num, index, operator="=")
payload = self.payload(condition)
resp = self.send_payload(payload, vuln_field)
return resp
def send_val(self, index: int, num: int, vuln_field... | This function performs a binary search to determine the correct ASCII character at a specific index by iteratively testing mid-values. It uses `true_func` to validate responses, narrowing the search range until the correct value is found or an exception is raised if no valid value exists. | def bsearch(self, index: int, left: int, right: int, vuln_field: str, true_func: Callable[[requests.Response], bool]) -> int:
#print("bsearching", left, right)
if left == right - 1:
resp = self.confirm_val(index, left, vuln_field)
if true_func(resp):
return left
... |
def setDestinations(app):
if app.timeElapsed % 1200 == 0:
for person in app.people:
tableNumber = random.randint(0, len(app.surfaces) + 2)
if tableNumber >= len(app.surfaces):
person.destX = random.randint(app.roomX0, app.roomX1)
person.destY = random.... | The code simulates a time step in an application by setting destinations, advancing the time, moving people, infecting them, and updating each person's state and color. It manages dynamic interactions and visual updates within the simulation. | def doStep(app):
setDestinations(app)
app.timeElapsed += app.timeStep
movePeople(app)
infectPeople(app)
for person in app.people:
person.update(app.people)
person.updateColor() |
def get_set_of_distinct_third_party_cookies_by_visit_id_and_site_url ():
query = "SELECT id, jc.visit_id, site_url, expiry, host, name, value FROM javascript_cookies AS jc INNER JOIN site_visits AS sv ON jc.visit_id = sv.visit_id WHERE record_type='added-or-changed' AND jc.visit_id={VISIT_ID} AND host NOT LIKE '%{SI... | The function categorizes third-party cookies into advertiser, tracker, or unknown categories by analyzing domains and blocking rules. It aggregates counts per site, generates categorized lists, and exports results to CSV files for detailed analysis of cookie distribution and categorization. | def categorize_third_party_cookies ():
result = {ADVERTISE: [], TRACKING: [], UNKNOWN: []}
cookies_list = get_set_of_distinct_third_party_cookies_by_visit_id_and_site_url()
advertisement_cookies_by_fp_url = {}
trackers_cookies_by_fp_url = {}
unknown_cookies_by_fp_url = {}
distinct_sites = set()
for cookie in coo... |
def get_overall_frequency_of_third_party_cookies ():
third_party_cookies = get_set_of_distinct_third_party_cookies_by_visit_id_and_site_url()
unique_third_party_cookie_domains = set()
repeated_third_party_cookie_domains = []
# cookie structure ([0]id, [1]visit_id, [2]site_url, [3]expiry, [4]host, [5]name, [6]valu... | The code calculates and returns statistics on the expiry dates of third-party cookies grouped by their host domains. It categorizes expiry durations into ranges (1 month–1 year, 1–5 years, >5 years, and "9999" infinite expiry) relative to a crawl date, aggregating counts per domain. | def get_expiry_dates_statistics_for_every_third_party_cookie_host_domain ():
third_party_cookie_count_list = get_overall_frequency_of_third_party_cookies()
third_party_cookies = get_set_of_distinct_third_party_cookies_by_visit_id_and_site_url()
expiry_dates_dict = {}
for cookie in third_party_cookie_count_list:
... |
def _determine_shortcut_sizes(self, num_regex_lines):
"""Empirically the following returns the best value"""
return [14, 10, 6, 4]
def _get_all_shortcut_url_maps(self, lines):
all_shortcut_url_maps = []
for shortcut_size in self.shortcut_sizes:
pat = re.compile(r'[\w\/\=\.\-\... | This code initializes a parser map by loading regex patterns from a file or provided list, configuring shortcut sizes for efficient processing, and generating mappings between shortcuts and parsers. It sets up FastHash instances for hashing, processes regex lines into URL and parser maps, and handles remaining regex pa... | def __init__(self, regex_file=None, regexes=None, shortcut_sizes=None, print_maps=False, support_hash=False):
"""Initializes the shortcut to Parser map"""
if regex_file is None:
regex_lines = regexes
else:
with open(regex_file) as f:
regex_lines = f.readli... |
def readfq(fp): # this is a generator function
# From https://github.com/lh3/readfq/blob/master/readfq.py
last = None # this is a buffer keeping the last unprocessed line
while True: # mimic closure; is it a bad idea?
if not last: # the first record or a record following a fastq
for ... | The code processes a masked superstring from a FASTA or text file, minimizing the number of contiguous '1' runs in the mask using specified parameters (kmer size, mask usage). It loads the input, counts initial runs, optimizes the mask, and outputs the result in FASTA or text format, depending on input type. | def main():
parser = argparse.ArgumentParser(
description=
"Program for minimizing the number of runs of 1s in the mask")
parser.add_argument(
'-k',
metavar='int',
dest='k',
type=int,
required=True,
help='kmer size',
)
parser.add_argumen... |
def create_weekly_dataframe_15_mins(self, start_date, end_date, types: tuple = (0, 1, 2, 3, 4, 5)):
""" create a dataframe for the activities in the database for a period of time based on 15 minutes intervals """
# Get all activities in the interval
activities = self.get_activities_by_set_of_typ... | The main task of the code is to generate a timetable-style calendar visualization for a given date range, displaying hours as rows and days of the week as columns. It creates a DataFrame based on predefined time intervals (15 mins, 30 mins, or hourly), renders it as a matplotlib table with adjustable cell sizes, sets f... | def visualize_calendar(self, start_date, end_date):
""" Visualize the calendar for the interval of start_date to end_date and save it as an image.
It needs to be in a timetable format. (Columns should be days of the week and rows should be hours of
the day)
The rows need title of each ho... |
def index_search(query, index, idf, doc_norms):
results = []
q_tokens = tokenize(query.lower())
q_tfidf = {}
qnorm = 0
for word in set(q_tokens):
if word in idf:
q_tfidf[word] = q_tokens.count(word) * idf[word]
qnorm += ((q_tokens.count(word) * idf[word]) ** 2)
... | The code retrieves top recipes matching a query, filters out those containing allergens (including singular/plural variations), calculates recipe costs, and ranks results by query-title length ratio, returning the top 5 allergen-free recipes. | def top_ten(query, allergens):
allergens_l = []
for a in allergens:
if a in common_allergens.keys():
allergens_l += common_allergens[a]
if a[-1] == 's':
allergens_l.append(a[:-1])
allergens_l.extend(allergens)
# for a in allergens:
# #al = lemmatizer.lemm... |
def set_seed(seed=24):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def get_model_class(args):
if args.TASK == 'seq':
return BertForSequenceClassificati... | The code trains and evaluates a model for event detection, supporting sequence classification (seq), token classification (ner), or bilevel detection. It uses BERT with optional CRF, handles multi-task learning, and includes training loops with gradient accumulation, learning rate scheduling, and model saving. | def main():
# config
parser = argparse.ArgumentParser()
parser.add_argument(
"--data_dir",
default='data/ner',
type=str,
help="The input data dir. Should contain the event detection data",
)
parser.add_argument(
"--model_type",
default='bert-base-case... |
def grip_data(benchmark):
benchmarks[benchmark] = {}
benchmarks[benchmark]['tests'] = []
# tot =30
with open(benchmark + "/universe.txt", "r") as f:
tests = f.readlines()
grip_one_test(benchmark, tests[0], False)
for test in tests:
# tot-=1
# if(tot<0): br... | The main task of the code is to process benchmark data by iterating through directories, selecting test cases based on prioritization and coverage criteria, and saving the results to text files. It generates files for each benchmark, prioritization method, and criterion combination, including additional coverage tests.... | def main():
for benchmark in directory:
print(benchmark)
grip_data(benchmark)
# random and total coverage
for prioritization in prioritizations:
for criteria in criterias:
selected = select_test(benchmark, prioritization, criteria)
with op... |
def user_requests():
user_cmd = input()
while(not validate_user_cmd(user_cmd.strip().split())):
print('Invalid user command, please input a valid one:')
user_cmd = input()
return user_cmd.strip().split()
def format_request(user_cmd: list[str]):
# Binary representation of the instruction ... | This code implements a File-Transfer Protocol (FTP) client using IPv6 sockets. It connects to a server, processes user commands (like file upload/download), sends requests, transfers files in binary format, handles responses, and manages errors. It supports 'put' (upload) and 'get' (download) operations, encoding/decod... | def run_client():
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
try:
s.connect((HOSTNAME, PORT))
print('Client connected...')
print('File-Transfer Protocol client active...')
while(True):
print('\nEnter FTP commands:')
... |
def _getZipFileFromRelease(self, release):
# download and verify zipfile from the release package
zipball = release.get('zipball_url', None)
if (zipball == None):
raise Exception('Invalid release package: no zipball')
self.logger.debug('Downloading zip file: %s' % zipball)
zipdata = urlopen(zipball).read... | The main task of the code is to install a plugin by extracting a ZIP archive from a release into a temporary directory. It verifies plugin metadata, ensures the extraction path is clean, extracts files, and calls an installation method. The process includes logging steps, handling directory cleanup, and validating the ... | def _installRelease(self, release):
tmpdir = tempfile.gettempdir()
self.logger.debug('Workspace: %s' % tmpdir)
# the zipfile is held in memory until we extract
zipfile = self._getZipFileFromRelease(release)
pInfo = self._readPluginInfoFromArchive(zipfile)
self._verifyPluginInfo(pInfo)
# the top level d... |
def checkadminuser(self):
if self.debugextra:
self.logger.debug(u'check Admin User called')
try:
admin = False
for dev in indigo.devices.itervalues('self.BlueIrisServer'):
if dev.enabled:
if bool(dev.states['admin']):
... | The main task of the code is to download recent server log messages from a BlueIris system, filter them by time (last 30 seconds), and store unique new messages in a list. It first verifies admin privileges, retrieves logs from the last 20 seconds, checks for download errors, and updates internal logs while debugging. ... | def downloadMsgs(self):
self.logger.debug(u'downloadMsgs Called')
if self.checkadminuser() == False:
self.logger.info(u'BlueIris Server User is not admin, Checking BI Server Log not possible.')
return
timetoget = int(t.time()) - 20
logmsgs = self.sendccommand('l... |
def checkadminuser(self):
if self.debugextra:
self.logger.debug(u'check Admin User called')
try:
admin = False
for dev in indigo.devices.itervalues('self.BlueIrisServer'):
if dev.enabled:
if bool(dev.states['admin']):
... | This method runs a concurrent thread to periodically update system components like messages, devices, users, and camera configurations. It checks admin privileges, triggers updates at timed intervals, logs status, and handles errors. The loop continues until the plugin is instructed to shut down, ensuring continuous mo... | def runConcurrentThread(self):
try:
while self.pluginIsShuttingDown == False:
self.prefsUpdated = False
self.sleep(0.5)
updateCams = t.time() + 5
updateServer = t.time() +2
updateMsgs = t.time() +10
upda... |
def _patch(endpoint, json, params=None):
"""Performs a PATCH request to the Zoom API."""
headers = {
'authorization': "Bearer {}".format(TOKEN),
'content-type': "application/json"
}
response = requests.patch(
"https://api.zoom.us/v2" + endpoint,
headers=headers,
json=json,
params=params)
print(... | This function creates or updates a meeting by validating the password length, checking if a meeting with the given ID exists, and either updating existing settings via PATCH or creating a new meeting with specified configurations via POST. It handles settings like waiting room, video options, and authentication, then s... | def create_or_update_meeting(
unique_id, user_email, topic, start_time, password,
duration, waiting_room):
if len(password) > 10:
raise ValueError("password length must be <10")
if meeting_json_exists(unique_id):
meeting_id = read_meeting_json(unique_id)['id']
settings = {
"topic": topic,
"start_time"... |
def personal_best_update(self, node: Node):
if node:
f_n = self.func(node.particle.x)
if f_n < node.particle.best_solution:
if np.shape(node.particle.x):
node.particle.best_solution = f_n
for child in node.children:
self.per... | The main task of the code is to implement the H-PSO algorithm with a tree-structured particle swarm. It iteratively updates personal/local best solutions, swaps particles based on performance, adjusts velocities, and terminates early if swarm diversity falls below a threshold. The tree hierarchy influences weight dynam... | def _run_hpso(self, num_runs: int = 100):
"""
This is a basic implementation of the H-PSO-Algorithm. It's derived from PSO
and has a tree-object. I figure this can be done way more elegantly, but then again:
it's just for illustration. Most of the main-functions are called in recursive
... |
def fetch_and_combine_data(keyword):
new_df = fetch_news_to_dataframe(keyword)
new_df["keyword"] = keyword
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client.mydatabase
all_data_collection = db["all_data"]
data_list = list(all_data_collection.find())
saved_df = pd.DataFra... | The main task of the code is to process data related to a given keyword by fetching and combining it, analyzing sentiment and generating summaries, adding the keyword as a metadata column, and then clustering and saving the processed data. The function handles empty data checks and allows optional clustering based on t... | def main(keyword, number=0):
df = fetch_and_combine_data(keyword)
#df = combined_df
if not df.empty:
sentinemental_df = apply_sentiment_and_summary(df)
sentinemental_df["keyword"] = keyword
cluster_and_save(sentinemental_df, number) |
def getUserPreferences(self, setting):
if os.path.isfile("settings.json"):
with open("settings.json", "r") as f:
data = json.load(f)
try:
preferred_setting = data[setting]
return preferred_setting
except KeyError... | The code applies a user-selected theme by checking their preferences. If the "theme-settings" preference is set to "light" or "dark," it enables the corresponding theme. If unspecified or invalid, it defaults to the classic theme. | def applyUserTheme(self):
if self.getUserPreferences("theme-settings") != "":
theme = self.getUserPreferences("theme-settings")
if theme == "light":
self.enableLightTheme()
elif theme == "dark":
self.enableDarkTheme()
else:
... |
def applyUserTheme(self):
if self.getUserPreferences("theme-settings") != "":
theme = self.getUserPreferences("theme-settings")
if theme == "light":
self.enableLightTheme()
elif theme == "dark":
self.enableDarkTheme()
else:
... | This code initializes a Qt GUI application with dark/light themes, sets up a main window, connects UI elements (buttons, combo box) to functions, and loads previous user settings for directory and show selection. It configures menu actions for theme switching and application control. | def __init__(self):
super().__init__()
self.app = QtWidgets.QApplication(sys.argv)
self.lightTheme = qdarkstyle.load_stylesheet(palette=qdarkstyle.LightPalette)
self.DarkTheme = qdarkstyle.load_stylesheet(palette=qdarkstyle.DarkPalette)
self.applyUserTheme()
self.MainWind... |
def read_calib_file(filepath):
""" Read in a calibration file and parse into a dictionary.
Ref: https://github.com/utiasSTARS/pykitti/blob/master/pykitti/utils.py
"""
data = {}
with open(filepath, "r") as f:
for line in f.readlines():
line = line.rstrip()
if len(line)... | The function converts 3D ground truth bounding boxes from camera coordinates to Velodyne coordinates using KITTI calibration data. It reads calibration matrices, processes each box by transforming its 3D points via camera-to-velodyne conversion, extracts six points from the eight-point box, and returns the resulting ve... | def get_velo_from_cam(filename, basefilename="./data/"):
'''
The filename needs to be a string wihout any extension (ex. 000000)
The function return mxnx3 numpy array with the velodyne coordinates of gt_boxes
Here m is number of gt_boxes and n is 8
Put the paths carefully for each fi... |
def get_8points_from_6points(point_list):
x_min = point_list[0]
y_min = point_list[1]
z_min = point_list[2]
x_max = point_list[3]
y_max = point_list[4]
z_max = point_list[5]
eight_points = np.empty((8, 3))
eight_points[0] = [x_min, y_min, z_min]
eight_points[1] = [x_min, y_min, z_ma... | The function reads KITTI detection proposals from a file, converts 6-point bounding boxes to 8-point representations, projects 3D detections to 2D image coordinates using given parameters, and optionally returns both 6-point boxes and projected 2D coordinates. It processes each line, filters valid boxes, and outputs im... | def read_proposals(proposals_file, P, V2C, R0, isplot=False):
""" Reads a KITTI detection proposal file.
Output:
dets: list of detections
"""
with open(proposals_file, 'r') as f:
lines = f.readlines()
dets = [line.split(',') for line in lines]
boxes_6_points = []
... |
def read_calib_file(filepath):
""" Read in a calibration file and parse into a dictionary.
Ref: https://github.com/utiasSTARS/pykitti/blob/master/pykitti/utils.py
"""
data = {}
with open(filepath, "r") as f:
for line in f.readlines():
line = line.rstrip()
if len(line)... | This code processes KITTI dataset files by loading calibration matrices, ground truth 2D boxes, and two sets of 3D-to-2D projected boxes. It overlays these boxes (proposals and ground truth) on corresponding images with distinct colors for visualization, displaying each result in a window. The task involves evaluating ... | def test():
for i in range(100):
filename = '%06d' % i
calib = read_calib_file("KITTI/training/calib/{}.txt".format(filename))
P = calib['P2']
P = np.reshape(P, [3,4])
V2C = calib['Tr_velo_to_cam']
V2C = np.reshape(V2C, [3,4])
R0 = calib["R0_rect"]
R0... |
def read_calib_file(filepath):
""" Read in a calibration file and parse into a dictionary.
Ref: https://github.com/utiasSTARS/pykitti/blob/master/pykitti/utils.py
"""
data = {}
with open(filepath, "r") as f:
for line in f.readlines():
line = line.rstrip()
if len(line)... | The function retrieves and processes pixel coordinates of object proposals and ground truth boxes from KITTI dataset files. It reads calibration data, converts ground truth boxes from camera to velocity coordinates, refines them, and combines two proposal sets (from pcl and open3d) after refining. It returns the concat... | def get_pixel_coordinates(filename, basefilename="./data/"):
'''
The filename needs to be a string wihout any extension (ex. 000000)
The function returns two numpy arrays with the pixel coordinates of proposals and gt_boxes repectively
Put the paths carefully for each file
'''
c... |
def read_calib_file(filepath):
""" Read in a calibration file and parse into a dictionary.
Ref: https://github.com/utiasSTARS/pykitti/blob/master/pykitti/utils.py
"""
data = {}
with open(filepath, "r") as f:
for line in f.readlines():
line = line.rstrip()
if len(line)... | The function retrieves 2D pixel coordinates of object proposals and ground truth boxes from KITTI dataset files, converts them to 3D coordinates using calibration matrices, combines multiple proposal sources, and returns both 2D/3D coordinates arrays for proposals and ground truth boxes, with optional plotting adjustme... | def get_pixel_coordinates_and_3d(filename, basefilename="./data/", isplot=False):
'''
The filename needs to be a string wihout any extension (ex. 000000)
The function returns two numpy arrays with the pixel coordinates of proposals and gt_boxes repectively
Put the paths carefully for ea... |
def get_all_links_from_course(self, url):
html, soup = self.get_html_and_soup(url)
all_links = []
for section in soup.find_all('ol', attrs={'class': 'course-part-summary__list-content'}):
links = [self.base_url + link.get('href') for link in section.find_all('a')]
all_lin... | The main task of the code is to scrape course content from a given URL by retrieving all relevant links, aggregating the HTML content of the course, and converting the final HTML into a PDF document for storage or distribution. | def scrap_course(self, course_url):
links = self.get_all_links_from_course(course_url)
course_html = self.get_all_courses_as_html(links)
self.convert_courses_as_pdf(
self.get_final_html(course_url, course_html)
) |
def get_best_dem(y_min,y_max,x_min,x_max,demName=None):
driver = ogr.GetDriverByName('ESRI Shapefile')
shpdir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, "config"))
# Read in the DEM list
dem_list = []
myfile = os.path.join(shpdir,"get_dem.py.cfg")
with open(myfile) as... | This function downloads and processes a Digital Elevation Model (DEM) within specified geographic bounds, reprojects it to a target coordinate system, and saves the result. It handles DEM selection, tile downloading, coordinate validation, resampling, buffer adjustments, and output formatting, using GDAL for raster ope... | def get_dem(x_min,y_min,x_max,y_max,outfile,post=None,processes=1,demName=None,leave=False):
if demName == 'VISNAV':
resampleAlg = 'near'
else:
resampleAlg = 'cubic'
if post is not None:
logging.info("Snapping to grid at posting of %s meters" % post)
if y_min < -90 or y_max > 90:
... |
def next_field(self, i,j):
if j == 8:
next_i = i+1
next_j = 0
else:
next_i = i
next_j = j+1
try:
while(self.field[next_i][next_j].fixed):
next_i, next_j = self.next_field(next_i,next_j)
finally:
retur... | This code implements a brute-force algorithm to solve a Sudoku puzzle by iteratively testing possible numbers in each cell, backtracking when a conflict arises, and counting the number of trials until the puzzle is solved. | def brute_force(self):
# Solve brute force
i = 0 # row iterator
j = 0 # col_iterator
while self.field[i][j].fixed: i,j = self.next_field(i,j)
counter = 0
while 1:
counter += 1
if i == 9: break
else:
found_possible = Fals... |
def try_row(self, cand, row, col, pos=False):
# check for occurences of candidate in row
# pos = False check for numbers, pos = True check for possibles
check = False
for j in [x for x in range(9) if x != col]:
if pos:
if self.field[row][j].num is None and can... | This function identifies "hidden single" candidates in a Sudoku grid. It iterates through each empty cell, checking if a candidate number can only fit in that cell within its row, column, or 3x3 box. If so, it sets the number and triggers a new solving step. The method uses `try_row`, `try_col`, and `try_box` to valida... | def hidden_single(self):
for i in range(9):
for j in range(9):
if self.field[i][j].num is None:
for cand in self.field[i][j].pos:
if not self.try_row(cand, i, j, pos=True):
self.new_solve(cand, i, j, "hidden sing... |
def conv2d(self, input, stride, padding, \
filter_size=[3, 3, 16, 32], dilations=[1, 1, 1, 1], activation="relu", name=""):
# strides=[N, H, W, C], [1, stride, stride, 1]
# filter_size=[ksize, ksize, num_inputs, num_outputs]
self.weights, self.w_names, weight = self.variable_maker(var_b... | The code defines a discriminator network that processes an input through multiple convolutional layers with increasing filter sizes, followed by max-pooling operations to reduce spatial dimensions. The output is flattened and passed through a fully connected layer with a sigmoid activation, producing a binary classific... | def discriminator(self, input, ksize=3):
print("Discriminator-1")
conv1_1 = self.conv2d(input=input, stride=1, padding='SAME', \
filter_size=[ksize, ksize, self.channel, 16], activation="elu", name="dis_conv1_1")
conv1_2 = self.conv2d(input=conv1_1, stride=1, padding='SAME', \
... |
def make_dir(path):
try: os.mkdir(path)
except: pass
def generate_static_mask(x, height, width):
h_d, w_d = height//3, width//3
h_s, w_s = height//2 - h_d//2, width//2 - w_d//2
h_e, w_e = h_s + h_d, w_s + w_d
m = np.zeros_like(x)
m[:, h_s:h_e, w_s:w_e, :] = 1
return m
def save_img(con... | This code trains a neural network for a specified number of epochs using masked inputs, computes reconstruction and adversarial losses, logs training metrics, saves model checkpoints, and visualizes training progress by generating comparison images of inputs, masked outputs, restorations, and differences. | def training(sess, saver, neuralnet, dataset, epochs, batch_size, normalize=True):
print("\nTraining to %d epochs (%d of minibatch size)" %(epochs, batch_size))
summary_writer = tf.compat.v1.summary.FileWriter(PACK_PATH+'/Checkpoint', sess.graph)
make_dir(path="training")
start_time = time.time()
... |
def encoder(self, input, ksize=3):
print("Encode-1")
conv1_1 = self.conv2d(input=input, stride=1, padding='SAME', \
filter_size=[ksize, ksize, self.channel, 16], activation="elu", name="conv1_1")
conv1_2 = self.conv2d(input=conv1_1, stride=1, padding='SAME', \
filter_siz... | The code builds a model with an encoder-decoder structure and a discriminator. It processes input data through an encoder to generate latent features, applies a channel-wise fully connected layer, decodes to reconstruct input (x_hat), and uses a discriminator to evaluate both original input (d_real) and reconstructed o... | def build_model(self, input, mask, ksize=3):
with tf.name_scope('encoder') as scope_enc:
latent = self.encoder(input=mask, ksize=ksize)
with tf.name_scope('chan_wise_fc') as scope_cw:
cw_fc = self.channel_wise_fully_connected(input=latent)
with tf.name_scop... |
def get_query_from_event(event):
return event.get("queryStringParameters", {}).get("q", "")
def is_search_audio_request(query):
return query.lower() == "searchaudio"
def convert_speech_to_text():
# Placeholder for speech to text conversion logic
return "converted text"
def extract_labels_from_lex(query)... | The main task of this code is to process a user query by converting audio to text if needed, extract labels using Lex, and retrieve related image paths from Elasticsearch. It logs events, handles audio queries, and returns image paths, labels, and the user query in a structured response. | def lambda_handler(event, context):
logger.info(f"Received event: {json.dumps(event)}")
user_query = get_query_from_event(event)
if is_search_audio_request(user_query):
user_query = convert_speech_to_text()
labels = extract_labels_from_lex(user_query)
if not labels:
... |
def __md5(fname: str) -> str:
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def convert_itis(itis: sqlite3.Connection, itis_md5: str, graph: jsonstreams.Object):
# "$schema": "h... | (The code converts an SQLite database file (`ITIS-042721.sqlite`) into a structured JSON file (`ITIS-042721.json`) and a DOT graph file (`ITIS-042721.dot`). It calculates the MD5 hash of the input database, connects to the SQLite file, and uses `convert_itis` to populate the JSON graph structure. Finally, `convert_to_d... | def main():
INPUT_DB = 'ITIS-042721.sqlite'
OUTPUT_JSON = 'ITIS-042721.json'
OUTPUT_DOT = 'ITIS-042721.dot'
input_path = os.path.join('data', INPUT_DB)
md5 = __md5(input_path)
# itis_disk = sqlite3.connect(input_path)
# itis = sqlite3.connect(':memory:')
# itis_disk.backup(itis)
# ... |
def generate_node(self, node_embedding, Layer_num):
global layer_result
input = tf.reshape(node_embedding, [-1, args.embedding_dim])
for l in range(Layer_num):
self.biase = self.biases[l]
# self.weight = tf.clip_by_norm(self.weights[l], args.w_clip) # weight clipping
... | This code initializes a graph neural network model for node embedding and training. It sets up node embeddings, defines a multi-layer perceptron (MLP) with Xavier initialization, computes node scores, and formulates a loss function (AsyPreser_loss) to preserve graph structure. The model uses placeholders for node IDs a... | def __init__(self, graph, Layer_num, node_embed_init=None):
self.n_node = graph.number_of_nodes()
self.n_edge = graph.number_of_edges()
args.num_of_gra = self.n_node
self.node_emd_init = node_embed_init
with tf.variable_scope('graph_forward_pass'):
if self.node_emd_i... |
def normalize(df):
max_value = max(df)
return 1 / max_value * df
def logRegressionGradientDescent(X, Y, theta, eta, iters):
"""
Performs gradient descent optimization on a set of data
X: Features matrix
Y: Output matrix
theta: matrix of variable weights
eta: learning rate
iters: num... | The code implements logistic regression from scratch using gradient descent to predict smoking behavior (target 'H4TO5') from merged longitudinal dataset features. It preprocesses data by normalizing features, handling missing values, and optionally balancing classes. The model's accuracy is evaluated against scikit-le... | def logistic_regression(features, eta, iters, threshold):
if 'AID' not in features:
features.append('AID')
df1 = pd.read_csv('data/wave_1/21600-0001-Data.tsv', sep='\t', header=0, low_memory=False,
usecols=wave_one_features)
df2 = pd.read_csv('data/wave_2/21600-0005-Data.tsv', ... |
def create_initial_population(self):
'''Creates a population of solutions of size pop_size
returns: population created'''
population = []
for i in range(self.pop_size):
genome = list(np.random.choice(self.all_features, size = self.cluster_size, replace = False))
... | The code evolves decision tree parameters using an evolutionary algorithm over multiple generations. It initializes a population, iteratively improves it, records the best-performing model, evaluates its ROC AUC and recall on test data, and returns the best model's fitness, parameters, metrics, and training/test data s... | def evolve_dtree_params(self):
self.population = self.create_initial_population()
for i in range(self.num_gens):
self.evolve_one_generation_dtree_params()
self.record_best(i)
roc_auc, recall= calc_rocauc_recall(self.best.tree, self.best.x_test, self.best.y_test)
r... |
def read_param_file():
with open('params.json') as j:
table_dict = json.load(j)
return table_dict
def read_config_file(config_name):
parser = ConfigParser()
parser.read('config_data.ini')
# Read user input from 'config_data.ini' file.
if config_name == "sql_config":
config = pars... | The function synchronizes data from SQL Server to HDFS using Sqoop, based on partitioning configurations. It calculates the delta between the latest HDFS partition and SQL Server's maximum value for 'dayid' partitions, iteratively importing missing days. For non-'dayid' partitions, it performs a single import. On succe... | def delta_to_landing():
try:
# Reading config file to get hive table details
table_dict = read_param_file()
hive_config = read_config_file("hive_tables_config")
base_landing_path = hive_config['base_landing_path']
region_name = hive_config['region_name']
for i in rang... |
def join_df():
# looks not good, but working
try:
df_crime = clean_crime_df()
df_offense_codes = clean_offense_codes_df()
df = df_crime.join(df_offense_codes,
df_crime['OFFENSE_CODE'] == df_offense_codes['code'],
'inner')
retu... | The main task of the code is to aggregate crime data by district, compute statistics (counts, averages, and frequent crime types), and join these results with a top-3 frequent crime types dataset. It prepares a consolidated DataFrame with aggregated metrics, including crime frequency, spatial coordinates, and cleaned c... | def aggregate_df():
# add columns for aggregate table
df = join_df().withColumns({'counter': lit(1),
'crimes_total': lit(1),
'crimes_monthly_count': lit(1),
'crimes_monthly': lit(1),
'... |
def aggregate_stop_count(self, date: str) -> Tuple[dict, dict]:
"""
Aggregate all stop count (including that of child stations) for all the parent stations for the selected date.
:param date: the selected date
:return: dict of all the parent stations and the corresponding aggregated stop... | This method assigns aggregated stop counts for a given date to parent stations from `all_stations_ids.json`, either initializing new data or updating existing entries. It loads prior counts if `initial` is False, aggregates new stop data, merges it with parent station IDs, and saves the updated counts to `final-station... | def assign_stop_count(self, date: str, initial: bool):
"""
Step 3 of the GolemioApiDonwloader. Assign the aggregated already downloaded all stop counts for the selected
date to all the parent stations from `all_stations_ids.json`,
and save into json file named `final-stations_with_count... |
def _build_corpus(sentences):
split_tokens = [sentence.token.split() for sentence in sentences]
dictionary = Dictionary(split_tokens)
return [dictionary.doc2bow(token) for token in split_tokens]
def summarize_corpus(corpus, ratio=0.2):
#% INPUT_MIN_LENGTH
hashable_corpus = _build_hasheable_corpus(co... | The function generates a summary by selecting key sentences from the input text based on a specified ratio or word count. It processes the text into sentences, checks for validity, builds a corpus, identifies important sentences, sorts them by original order, and returns the formatted result. Edge cases like empty inpu... | def summarize(text, ratio=0.2, word_count=None, split=False):
sentences = _clean_text_by_sentences(text)
# If no sentence could be identified, the function ends.
if len(sentences) == 0:
logger.warning("Input text is empty.")
return [] if split else u""
# If only one sentence is presen... |
def diff(content1: str, content2: str):
return difflib.SequenceMatcher(None, content1, content2)
def get_title(content):
return content.split('\n')[0]
def get_content(content):
return content.replace(get_title(content), '').strip()
def has_deleted_item(diff):
for operation, *_ in diff.get_opcodes():
... | The main task of the code is to sanitize a PDF by comparing consecutive pages' content and titles. It checks if the title or content has changed significantly (based on given ratios) and adds the previous page to the output PDF only if changes exceed thresholds. This filters out redundant or unchanged pages, retaining ... | def sanitize(pad_input: PyPDF2.PdfFileReader, pdf_output: PyPDF2.PdfFileWriter, title_ratio: float, content_ratio: float):
prev_page = pad_input.getPage(0)
nb_pages = pad_input.getNumPages()
for i in range(1, nb_pages):
progress_with_message('Sanitizing pdf ...', i / nb_pages)
current_page =... |
def initializeFilter(self,size, scale = 1.0):
stddev = scale/np.sqrt(np.prod(size))
return np.random.normal(loc = 0, scale = stddev, size = size)
def initializeWeight(self,size):
return np.random.standard_normal(size=size) * 0.01
def Gradient_Descent(self,batch,y, num_classes, lr, dim, n_c, beta... | The code trains a convolutional neural network (CNN) with two convolutional layers and two dense layers using gradient descent. It initializes filters/weights, processes data in batches, updates parameters over epochs, and saves trained parameters and cost history. The model is optimized with specified learning rate, m... | def train(self,train_data, Y, num_classes = 3, lr = 0.001, beta1 = 0.95, beta2 = 0.99, img_dim = 224, img_depth = 3, f = 3, num_filt1 = 32, num_filt2 = 64, batch_size = 32, num_epochs = 20, save_path = 'params.pkl'):
f1, f2, w3, w4 = (num_filt1 ,img_depth,f,f), (num_filt2 ,num_filt1,f,f), (128,774400)... |
def register_player_in_db(self):
"""
Takes all the needed information from the view to create an object type Player, save it to db and returns
the saved player
:return: the player that has been registered
"""
player_chess_id = self.view.input_player_chess_id()
pla... | The `run` method manages the main menu loop of the program, handling user input to execute actions like registering players, creating/resuming tournaments, or generating reports. It continuously prompts the user until they select the exit option (5), at which point it terminates the loop. The method returns errors if a... | def run(self):
"""
run manages the logical running of the main menu of the program, it returns error if there is during the
execution of the program
"""
running = True
while running:
menu_selection = self.view.input_main_menu()
if menu_selection ==... |
def Gradient_Descent(X, Y, theta, m, alpha):
new_theta = []
constant = alpha / m
for j in range(len(theta)):#For each theta, the partial differential
CFDerivative = Cost_Function_Derivative(X, Y, theta, j, m, alpha)
new_theta_value = theta[j] - CFDerivative
new_theta.append(new_theta... | This function performs logistic regression using gradient descent to optimize parameters (theta) over num_iters iterations. It updates theta iteratively, computes the cost function every 100 steps to monitor convergence, and prints theta and cost values. Finally, it declares a "winner" based on the optimized theta, lik... | def Logistic_Regression(X, Y, alpha, theta, num_iters):
m = len(Y)
for x in range(num_iters):
new_theta = Gradient_Descent(X, Y, theta, m, alpha)
theta = new_theta
if x % 100 == 0:
# here the cost function is used to present the final hypothesis of the model in the same form ... |
def isExpired(self, d):
if d is None or 'expiration_date' not in d or time.time() > d['expiration_date']:
return True
else:
return False
def getAcctStatus(self):
if self.isExpired(self.acctStatus) is False:
return self.acctStatus
tokens = self.getToke... | This method retrieves and updates vehicle status data by checking if the current car status is expired. If expired, it fetches fresh status from Volkswagen's API using account tokens, stores results in `carStatus`, and adds an expiration timestamp. It returns a copy of `carStatus` excluding the expiration date, ensurin... | def getCarStatus(self):
if self.isExpired(self.carStatus) is True:
self.carStatus = {}
acctStatus = self.getAcctStatus()
for vehicle in acctStatus['data']['vehicleEnrollmentStatus']:
vehicleId = vehicle['vehicleId']
tokens = self.getTokens()
... |
def recv_envelope(self, conn: socket) -> Envelope:
data = conn.recv(1024)
envelope = pickle.loads(data)
return envelope
def __commands_handle(self, conn: socket, envelope: Envelope) -> None:
with ChatServer.std_out_lock:
print('~~ Oh, this mesagge for me!')
command = ... | This function handles incoming socket connections by receiving message envelopes, checking if the message starts with a recognized command, and either processing commands or routing messages to the correct recipient. It logs sent messages with sender, receiver, and content details. | def __handle_connection(self, conn: socket) -> None:
while True:
envelope = self.recv_envelope(conn)
first_word = str(envelope.load).split(' ')[0]
if first_word in ChatServer.avail_commands:
self.__commands_handle(conn, envelope)
else:
... |
def count_dots(self):
self.update()
self.check_dots_north()
self.check_dots_east()
self.check_dots_south()
self.check_dots_west()
self.total_dot_list.append(len(self.num_of_dots_N_list))
self.total_dot_list.append(len(self.num_of_dots_E_list))
self... | The code moves an object based on its direction (N/S/E/W) by adjusting its coordinates, checks if it stays within boundaries, and updates its state. | def move(self):
self.count_dots()
if self.direction == "N" :
self.y-=self.vel
if self.direction == "S":
self.y+=self.vel
if self.direction == "E":
self.x+=self.vel
if self.direction == "W":
self.x-=self.vel
self.check_bor... |
def intialise_session_variables():
st.set_page_config(layout="wide")
with st.spinner("Intialising Session variables"):
if 'all_data' not in st.session_state:
st.session_state.all_data = ''
if 'symbol' not in st.session_state:
st.session_state.symbol = ''
if ... | The main task of the code is to process historical stock market data by initializing session variables, checking data availability, generating descriptive statistics, and performing stock market predictions. If no data is available, it informs the user; otherwise, it executes analysis and prediction functions on the pr... | def main():
intialise_session_variables()
historical_df = intializations()
if len(historical_df) == 0:
st.info('Data for the company is currently not available :( ')
else:
descriptive_statistics(historical_df)
stock_market_prediction(historical_df) |
def tile_to_numbers(tile):
return (
#Top
binary_array_to_numbers(tile[0,:]),
#Right
binary_array_to_numbers(tile[:,tile_size-1]),
#Bottom
binary_array_to_numbers(tile[tile_size-1,:]),
#Left
binary_array_to_numbers(tile[:,0])
)
def find_connecting_t... | This function processes a row of tiles by aligning each tile to its right neighbor. It identifies the correct connecting tile based on the current tile's right side, adjusts it to match orientation, updates the tile matrix with the aligned tile, and prints intermediate results for debugging. The main task is to correct... | def fix_a_row(i):
# loop through the row
for j in range(11):
current_tile = tiles[tile_matrix[i, j]]
tile_to_numbers(current_tile)
# Right side
#print(tile_to_numbers(current_tile))
right = tile_to_numbers(current_tile)[1]
# find connecting tile to the right
... |
def _copy_constructor(self, other:BIDSPath):
self._set(**other.fields)
self.path = Path(other.path)
self.metadata = copy.deepcopy(other.metadata)
def _filepath_parser_constructor(self,
filepath:str,
metadata:dict=None):
... | This code initializes a BIDSPath object by either copying an existing instance, parsing a file path from a root directory, or constructing a new path using components like subject, task, suffix, and extension. It handles different input scenarios to flexibly create or replicate BIDS-compliant file paths with optional m... | def __init__(self,
root: Union[str,BIDSPath], sub:str=None, task:str=None, ext:str=None,
suffix:str=None, derivative:str=None, ses:str=None, acq:int=None, run:int=None,
rjust:int=2, metadata:dict=None) -> None:
if isinstance(root, BIDSPath):
self.... |
def should_post(prompt, post_count=3):
if re.search(r"\[POST [a-z0-9]{19}\]", prompt) is None:
return True
message = f"Should we post another photo, dont post more than {post_count} times per day? the current time and date are {datetime.now().strftime('%A, %B %d, %H:%M')}. Answer with just 'yes or 'no'"... | The main task of the code is to determine if a social media post should be made based on a prompt and post count. If so, it prepares the post, uploads it to Instagram, updates the prompt with response data, archives the image, and handles errors. If not posting, it updates metrics and saves the prompt for future use. | def main_job(project_name, post_count):
prompt = open(f"accounts/{project_name}/prompt.txt", "r").read()
if should_post(prompt, post_count): # and there are images in the queue
print(f"Posting - {project_name}")
prompt = update_metrics(prompt)
prompt, post_content, image_path = start_pos... |
def start_round(self):
self.bets()
if self.openings() == "blackjack":
return self.curr_player
self.plays()
while self.curr_idx < 3:
self.curr_player.make_bet()
print(f"{self.curr_player.name} betted ${self.curr_player.bet}")
self.... | The start_game method runs a loop that repeatedly executes start_round, reset, and update_players until the game ends (when game_over becomes True), then prints "game over" to signal termination. | def start_game(self):
while not self.game_over:
self.start_round()
self.reset()
self.update_players()
print("game over") |
def getAllPromptIds():
container = connectToContainer('quiplashDB', 'prompts')
prompt_ids = []
for item in container.query_items(
query='SELECT * FROM prompts',
enable_cross_partition_query=True):
prompt_ids.append(int(item['id']))
return prompt_ids
def ge... | The function retrieves a specified number of random prompts. It first obtains all prompt IDs, then either selects `n` random IDs (if possible) to fetch their corresponding prompts or returns all prompts if `n` exceeds the available count. | def getNRandomPrompts(n: int):
allPrompts = getAllPromptIds()
output = []
if n <= len(allPrompts):
random_ids = random.sample(allPrompts, n)
for id in random_ids:
output.append(getPromptWithId(id))
else:
output = getAllPrompts()
return output |
def form_cropped_arrays_for_all_ROIs(
self, final_arrays_to_mixer: list[np.ndarray]
) -> list[np.ndarray]:
"""
Form cropped arrays for all regions of interest (ROIs).
"""
for roi_tuple in self.ui.rois:
self.get_roi_mask(roi_tuple)
if self.inner:
... | The main task of the code is to update regions of interest (ROIs) in images by forming cropped arrays for all ROIs, synchronizing them, updating components, and mixing images. It conditionally executes these steps if `use_ROI` is enabled, logs ROI updates, assigns cropped Fourier data to image objects, synchronizes ROI... | def updateROI(self, roi_tuple: tuple) -> None:
"""
This method updates the regions of interest (ROIs) in the images based on the
provided ROI tuple. It forms cropped arrays for all ROIs, synchronizes the ROIs,
updates the components, and mixes the images.
"""
if not self.... |
def cbf_recommender(self):
top_n = list()
rated_items = self.input_dict.keys()
candidate_items = [iid for iid in self.movies.keys() if iid not in rated_items]
for candidate in candidate_items:
predicted_r = self.cbf_predict(candidate)
top_n.append((candidate, pred... | The code's main task is to select and execute the appropriate recommendation algorithm based on the `self.recommender` value. It dispatches to either content-based filtering (`cbf`), singular value decomposition (`svd`), or a hybrid approach, returning recommended items. If an invalid recommender is specified, it issue... | def recommend_items(self):
if self.recommender == 'cbf':
recommended_items = self.cbf_recommender()
return recommended_items
elif self.recommender == 'svd':
recommended_items = self.svd_recommender()
return recommended_items
elif self.recommender =... |
def mapper(self):
iid_uri_dict = dict()
uri_iid_dict = dict()
with open('Dataset/Item_DBpedia_Mappings.csv', 'r') as f:
lines = f.readlines()
for line in lines:
if line != None and line != '':
uri, iid = line.split('::')[0], line.split(... | This code initializes a recommendation system by loading movie embeddings, metadata, and a pre-trained SVD model. It sets parameters for the recommender type, item count, and metadata mappings, while preparing data structures for generating recommendations using content-based or collaborative filtering approaches. | def __init__(self, recommender='cbf', exp_pattern='basic', nb_po=3, nb_rec=1, input_dict=None, alpha=0.5, beta=0.5):
self.recommender = recommender
self.exp_pattern = exp_pattern
self.nb_po = nb_po
self.nb_rec = nb_rec
self.input_dict = input_dict
self.alpha = alpha
... |
def detect_vechicle(tfnet_yolo, imgcv):
result = tfnet_yolo.return_predict(imgcv)
vehicles = []
for det in result:
if (det['label'] in ['car','bus']):
vehicles.append(det)
return vehicles
def scan_vehicles(vehicles, imgcv, wpod_net, lp_threshold):
#
# Adds a fake detection with the full image if no vehicle... | The function `run_all` detects vehicles in an image using YOLO, identifies license plates (LPs) via WPOD-Net, applies OCR on the detected LPs, and saves the OCR results along with processed images to a specified directory. It returns the list of OCR-extracted license plate texts. | def run_all(tfnet_yolo, imgcv, wpod_net, lp_threshold, tfnet_ocr, outputdir, rootname):
#
# Find cars
#
result = detect_vechicle(tfnet_yolo, imgcv)
#result = [{'label': 'car', 'confidence': 1, 'topleft': {'x': 1, 'y': 1}, 'bottomright': {'x': imgcv.shape[1], 'y': imgcv.shape[0]}}]
#
# Find LPs
#
platelist,... |
def fileContainers_create(self):
operation = "/fileContainers"
logger.debug(f"fileContainer_create: POST {operation}")
url = self.prism_endpoint + operation
headers = {"Authorization": "Bearer " + self.get_bearer_token()}
r = requests.post(url, headers=headers)
log_ela... | The main task of this code is to load a file into a file container by either creating a new container or using an existing ID. It validates the file's existence, constructs an API request with authentication, uploads the file via POST, and returns the container ID on success. Errors result in logging and returning None... | def fileContainers_load(self, fileContainerID, fqfn):
# Do a sanity check and make sure the fqfn exists and
# has a gzip extension.
if not os.path.isfile(fqfn):
logger.critical("file not found: {fqfn}")
return None
# Create the file container and get the ID. We... |
def explore(self,
n_retained,
next_dsl_name="dsl",
*,
exploration_timeout,
program_size_limit,
eval_timeout,
eval_attempts,
max_diff,
max_conn):
max_novel_representatio... | The main task of the code is to execute a multi-phase process involving neural network training, model compression, and exploration of representations. It initializes exploration if no prior representations exist, evaluates each representation's performance on training/evaluation sets, retains top-performing models, di... | def run(self,
train,
eval,
target_dim,
max_conn,
device,
batch_size,
iterations,
epochs_per_iteration,
perf_metric,
smoothing_factor,
use_scheduler,
root_dsl_name,
... |
def combine(columns: Sequence[Column], joiners: Sequence[str] = ()) -> Column:
'''Takes one list of strings or more and joins them line by line with the specified joiners.
Args:
columns (Sequence[Column]): [['a', ...], ['b', ...], ...]
joiners (Tuple[str, ...]): ['─', ...]
Returns:
... | The function `left` constructs a column representation of left-aligned nodes by combining input columns with appropriate connectors. It takes a sequence of columns, splits them into a head and tail, then merges the head with connectors and the tail's branches to form a structured output. The result is a new column feat... | def left(columns: Sequence[Column]) -> Column:
'''Draws given columns as left nodes.
Args:
columns (Sequence[Column]): [['a', ...], ['b', ...], ...]
Returns:
Column: [' ┌─┬─, ...', ' a b ...', ...]
'''
head, *tail = columns
return combine(
[link(Connectors.LCORNER, head... |
def combine(columns: Sequence[Column], joiners: Sequence[str] = ()) -> Column:
'''Takes one list of strings or more and joins them line by line with the specified joiners.
Args:
columns (Sequence[Column]): [['a', ...], ['b', ...], ...]
joiners (Tuple[str, ...]): ['─', ...]
Returns:
... | The function generates a right-aligned tree structure by combining input columns with specific connectors, creating a visual representation of nodes and edges for tree diagrams. | def right(columns: Sequence[Column]) -> Column:
'''Draws given columns as right nodes.
Args:
columns (Sequence[Column]): [['a', ...], ['b', ...], ...]
Returns:
Column: ['..., ─┬─┐ ', '... y z ', ...]
'''
*head, tail = columns
return combine(
[branches(head), link(Connec... |
def asset_exists(asset_name):
"""Check if an asset exists."""
try:
ee.data.getAsset(asset_name)
return True
except ee.ee_exception.EEException:
return False
def delete_asset(asset):
"""Delete an asset in Earth Engine and print a notification."""
rich.print(f"[yellow]Deleting ... | This script uploads a new Snazzy styles table to Earth Engine, checks for existing assets, and manages old styles by overwriting, renaming, or deleting them based on user confirmation. It ensures the new styles are active, shared, and handles edge cases like first-time uploads or aborted operations. | def main():
"""This script uploads a new Snazzy styles table to an Earth Engine asset and removes the old styles."""
ee.Initialize()
if asset_exists(NEW_STYLE_ASSET):
if Confirm.ask(f"[red]Asset '{NEW_STYLE_ASSET}' already exists. Overwrite?[/]"):
delete_asset(NEW_STYLE_ASSET)
e... |
def get_sequencing_stats(self):
"""
Populate the self.metrics_dict with the stats
"""
self.get_trimming_qc_stats()
# Uncomment to reenable the mapping stats
# self.get_mapping_stats()
self.get_duplication_stats()
def get_cell_stats(self):
# Try to read in ... | The main task of the code is to generate metrics by retrieving sequencing statistics, cell statistics, and writing the collected data into a CSV file for output. | def generate_metrics(self):
self.get_sequencing_stats()
self.get_cell_stats()
self.write_out_dict_to_csv() |
def get_preds_not_smooth(model, vid_path, cutoff = None):
right_labels, left_labels = [], []
cap = cv2.VideoCapture(vid_path)
i = 0
while (cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
if ret == True:
boxes = model(frame).pred[0]
labels... | The code processes a video using a pre-trained YOLOv5 model to detect and smooth tool usage labels (left/right), then saves the annotated video. It loads a custom model, infers predictions, applies label smoothing, and generates output with `save_vid`, while commented sections suggest potential integration with ground ... | def main(vid_path):
print(vid_path)
#true_labels_right = []
#true_labels_left = []
#with open(f"/home/student/HW1/datasets/HW1_dataset/tool_usage/tools_left/{vid_path[:-4].split('/')[-1]}.txt") as f:
# for line in f.readlines():
# start, fin, lab = line.split()
# lab = int(l... |
def compute_lambda(self, support, query, y_s):
"""
inputs:
support : torch.Tensor of shape [n_task, s_shot, channels, H, W]
query : torch.Tensor of shape [n_task, q_shot, channels, H, W]
y_s : torch.Tensor of shape [n_task, s_shot]
updates :
self.l... | The code processes a task by extracting support/query data, transferring tensors to a GPU, initializing model weights via `compute_lambda` and `init_weights`, executing adaptation with `run_adaptation`, and returning logs from `get_logs`. The main task involves adapting a model to a new task using few-shot learning, le... | def run_task(self, task_dic, shot):
# Extract support and query
y_s, y_q = task_dic['y_s'], task_dic['y_q']
x_s, x_q = task_dic['x_s'], task_dic['x_q']
# Transfer tensors to GPU if needed
support = x_s.to(self.device)
query = x_q.to(self.device)
y_s = y_s.long()... |
def init_weights(self, support, query, y_s, y_q):
"""
inputs:
support : torch.Tensor of shape [n_task, s_shot, feature_dim]
query : torch.Tensor of shape [n_task, q_shot, feature_dim]
y_s : torch.Tensor of shape [n_task, s_shot]
y_q : torch.Tensor of shape... | The code processes a task by extracting support/query features, initializing prototypes, adapting the model using support/query data, and returning adaptation logs. It transfers features to a GPU, initializes weights with support data, performs adaptation based on the shot number, and retrieves logs for analysis. | def run_task(self, task_dic, shot):
# Extract support and query
y_s, y_q = task_dic['y_s'], task_dic['y_q']
x_s, x_q = task_dic['x_s'], task_dic['x_q']
# Extract features
z_s, z_q = extract_features(model=self.model, support=x_s, query=x_q)
# Transfer tensors to GPU if ... |
def get_table(self, url, content_index):
status_code = None
while status_code != 200:
try:
res = requests.get(url)
status_code = res.status_code
content = BeautifulSoup(res.content, features='html.parser')
content = content.find... | The code concatenates multiple dataframes by first retrieving tables from pages using `get_table`, converting them into dataframes with specified columns via `dataframe`, and finally combining all resulting dataframes into a single dataframe using `pd.concat` with `sort=False`.) | def concatenate(self, content_index, cols):
df = [self.get_table(x, content_index) for x in self.page()]
df = [self.dataframe(x, cols) for x in df]
df = pd.concat(df, sort=False)
return df |
def dec_to_hex(value, size=0):
""" size=0: 12648430 -> ['c0', 'ff', 'ee'] ; (255, 255) -> ['ff', 'ff'] ; (256 * 256 - 1, 10) -> ['ff', 'ff', '0a'] """
if type(value) in (list, tuple):
return [item for sub in [dec_to_hex(item) for item in value] for item in sub] # flatten
else:
s = '{:02x}'.... | The function generates a PCAP file header by concatenating a magic number, version, time offset, frame length, and link layer type, all converted from decimal to hexadecimal and then to bytes, based on the provided link_layer_id. | def pcap_header(link_layer_id):
magic_number = (212, 195, 178, 161)
magic = [dec_to_hex(item)[0] for item in magic_number]
res = bytes(hex_to_dec(magic))
res += bytes(hex_to_dec(pcap_version()))
res += bytes(hex_to_dec(pcap_time_offset()))
res += bytes(hex_to_dec(pcap_frame_length()))
res +=... |
def extract_data(line):
if len(line) < 18 or line.count('\x00') > 0:
return None, None
line = line.replace('\r', '').replace('\n', '').replace(' *', '')
if '[' in line and ']' in line: # timestamp is human-readable datetime within brackets
ts = line[line.index('[') + 1:line.index(']')]
... | This function processes a line of data to format it into a pcap-compatible packet structure by converting timestamps and frame data into appropriate byte representations, then concatenates these components into a byte string for output. | def pcap_data(line):
t, data = extract_data(line)
if t is None:
return None, bytes([])
ts, fr = pcap_timestamp(t), chunk(data, 2)
tl = len(fr)
fr = bytes(hex_to_dec(fr))
fl = pcap_frame_length(len(fr))
rec = bytes(hex_to_dec(ts))
rec += bytes(hex_to_dec(fl))
rec += bytes(hex_... |
def convert(fn):
if fn.lower().endswith('.dcf'): return lambda s : daintree_to_plain(s)
if fn.lower().endswith('.isd'): raise NotImplementedError()
if fn.lower().endswith('.psd'): raise NotImplementedError()
return lambda s : s
def extract_data(line):
if len(line) < 18 or line.count('\x00') > 0:
... | The main task of the code is to process files from `src` by extracting timestamps, storing valid files in a dictionary, and passing them to `process()` if any timestamps are found. It attempts up to two reads per file to extract valid timestamps, sorts the files by timestamp, and returns `True` if successful, `False` o... | def main(src, dst, period, link):
files = {}
for item in src:
conv = convert(item)
found = 2 # max two attempts to find timestamp
f = open(item, 'r')
while found > 0:
found -= 1
s = f.readline()
ts, _ = extract_data(conv(s))
if ts ... |
def extract_info_intraday(company_list):
"""
Calls the extract and save functions above for each input company.
--------
:param <company_list>: List ; list of publicly traded companies' tickers
"""
try:
for company in company_list:
save_intraday(company)
print(f"{company}: intraday market data retrieved s... | The main task of the code is to extract financial data (intraday, daily, and options) for a list of publicly traded companies, either concurrently using multiprocessing or sequentially. It also performs a short-term analysis on a specific company ("GS"). The function handles both parallel and single-threaded execution ... | def main(company_list, concurrency = False):
"""
Main function call.
--------
:param <company_list>: List ; list of publicly traded companies' tickers
"""
#Concurrent running
if concurrency:
try:
process_1 = Process(target = extract_info_intraday, args=(company_list,))
process_1.start()
process_2 = P... |
def valid_forward(self, model, sample, reduce=True):
"""Compute the loss for the given sample.
Returns a tuple with three elements:
1) the loss
2) the sample size, which is used as the denominator for the gradient
3) logging outputs to display while training
"""
... | The code computes the loss for a given sample using a weighted loss function, updates model parameters via backpropagation, and adjusts weights (w) using gradients from validation data. It returns the loss, sample size, and logging outputs while training, incorporating gradient updates and maintaining model states. | def forward(self, model, sample, valid_sample=None, all_w=None, alpha=None, optimizer=None, reduce=True):
"""Compute the loss for the given sample.
Returns a tuple with three elements:
1) the loss
2) the sample size, which is used as the denominator for the gradient
3) logging o... |
def ones_comp(bin_value):
new_num=''
for i in range(len(bin_value)):
if bin_value[i]=='0':
new_num+='1'
else:
new_num+='0'
return new_num[::1]
def append_zeros(number,count):
new_num=''.join(('0'*count,number))
return new_num
def twos_comp(bin_value,one):
first_stage=ones_comp(bin_value)
second_stage=b... | The main task of the code is to compute and print the one's and two's complement of a given binary number. It takes a binary input, calculates its one's complement by inverting bits, then computes the two's complement by adding 1 to the one's complement. The code also attempts to adjust the length of the '1' string to ... | def main():
print("Program to print the one's and two's complement of a binary value -->")
bin_value=input("Enter the binary number : ")
print("One's complement value is :",ones_comp(bin_value))
one='1'
one=append_zeros(one,len(bin_value)-len(one))
print("Two's complement value is :",twos_comp(bin_value,one)) |
def append_zeros(number,count):
new_num=''.join(('0'*count,number))
return new_num
def twos_comp(bin_value,one):
first_stage=ones_comp(bin_value)
second_stage=bin_addition(first_stage[::-1],one[::-1])
return second_stage
def bin_addition(num_1,num_2):
new_num=''
carry='0'
for i in range(len(num_1)):
if i==(le... | The code performs binary subtraction using two's complement. It converts the second number to its two's complement (negative equivalent), adds it to the first number, and handles carry-over. If the result is positive, it omits the carry; if negative, it re-applies two's complement to the result. The output displays the... | def subtract(dnum_1,dnum_2,num_1,num_2):
one='1'
one=append_zeros(one,len(num_2)-len(one))
#Two's complement of number 2
num2_tc=twos_comp(num_2,one)
#Addition of tc and num_1
diff=bin_addition(num_1[::-1],num2_tc[::-1])
print("Difference -->")
#Carry case
if dnum_1>dnum_2:
omit_carry=''
for i in range(1,... |
def binary(number):
bin_value=''
while(number>0):
bin_value+=str(number%2)
number=number//2
if number==1:
bin_value+='1'
break
return bin_value[::-1]
def equateLength(num_1,num_2):
if (len(num_1) < len(num_2)):
num_1=append_zeros(num_1,len(num_2)-len(num_1))
if (len(num_2) < len(num_1)):
num_2=appe... | The code performs binary subtraction by converting two decimal numbers to binary, equalizing their lengths, and then executing the subtraction operation. It takes user inputs, converts them to binary equivalents, aligns their bit lengths, and computes the result using a dedicated subtraction function. | def main():
print("Program to perform binary subtraction between two numbers-->")
dnum_1=int(input("Enter number 1 : "))
dnum_2=int(input("Enter number 2 : "))
num_1=binary(dnum_1)
num_2=binary(dnum_2)
num_1,num_2=equateLength(num_1,num_2)
print("Number :",dnum_1,":: Binary Equivalent :",num_1)
print("Number :"... |
def init_glut(argv):
"""glut initialization."""
glutInit(argv)
glutInitWindowSize(*WINDOW_SIZE)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
glutCreateWindow(argv[0].encode())
glutReshapeFunc(reshape)
glutDisplayFunc(display)
glutKeyboardFunc(keyboard)
glutMouseFunc(mo... | The main task of the code is to initialize a GLUT-based OpenGL application by setting up the GLUT library, textures, OpenGL context, 3D objects, and display lists, then entering the GLUT main loop to handle rendering and event processing. | def main(argv=None):
if argv is None:
argv = sys.argv
init_glut(argv)
init_texture()
init_opengl()
init_object()
generate_list()
return glutMainLoop() |
def init_glut(argv):
"""glut initialization."""
glutInit(argv)
glutInitWindowSize(*WINDOW_SIZE)
glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH)
glutCreateWindow(argv[0].encode())
glutReshapeFunc(reshape)
glutDisplayFunc(display)
glutKeyboardFunc(keyboard)
glutMouseFunc(mouse)
glutMotionFunc(motion)
... | The main task of the code is to initialize a GLUT-based OpenGL application by setting up program configurations, textures, and 3D objects, then entering the main rendering loop to display the graphics. It handles command-line arguments, initializes GLUT, OpenGL context, and starts the event loop for rendering and inter... | def main(argv=None):
if argv is None:
argv = sys.argv
init_glut(argv)
init_program()
init_texture()
init_opengl()
init_object()
return glutMainLoop() |
def load_metadata():
conn = None
metadata = []
try:
params = config()
conn = psycopg2.connect(**params)
cur = conn.cursor()
cur.execute("SELECT id, title, url, description FROM ecommerce_metadata.metadata;")
metadata = cur.fetchall()
cur.close()
except (Ex... | The code's main task is to load metadata and a BERT model, generate embeddings from the data, update a database with these embeddings, and recommend datasets related to "women's fashion" using the model. It serializes embeddings into the database and leverages the BERT model for contextual dataset recommendations. | def main():
metadata = load_metadata() # Load metadata
tokenizer, model = load_bert_model() # Load BERT tokenizer and model
serialize_embeddings_and_update_db(metadata, tokenizer, model) # Update database with embeddings
recommend_datasets("women's fashion", tokenizer, model) |
def get_csv_writer(solution_name, multi_year):
log_file_name = get_log_file_name(solution_name, multi_year)
log_file = open(log_file_name, "w")
csv_writer = csv.writer(log_file)
write_header(csv_writer)
return csv_writer
def storage_one_year_varying_epochs(solution_name, csv_writer):
for epoch_p... | The main task of the code is to calculate and log storage costs for two models (SEEMLESS and PARAKEET) under two scenarios: one year with varying epochs and multiple years. It uses CSV writers to save results, distinguishing scenarios via a boolean parameter. The code executes cost calculations for both models in each ... | def main():
# Calculate and log storage costs over one year.
seemless_csv_writer = get_csv_writer(SEEMLESS, False)
parakeet_csv_writer = get_csv_writer(PARAKEET, False)
storage_one_year_varying_epochs(SEEMLESS, seemless_csv_writer)
storage_one_year_varying_epochs(PARAKEET, parakeet_csv_writer)
... |
def load_data():
vocab = Counter()
documents = []
inverted_index = {}
directory = Path('Qdatalc/')
file_names = [
directory / 'indexlc.txt',
directory / 'Qindexlc.txt',
]
data_directory = directory / 'data'
file_names.extend(data_directory.rglob('*'))
for filename ... | The main task of the code is to check if required TF-IDF-related files exist, generate them if missing via `load_data()`, then load and return the vocabulary, documents, and inverted index from these files for further processing. | def load_and_process_data():
if not os.path.exists('tf-idf_lc/vocab_lc.txt') or not os.path.exists('tf-idf_lc/idf-values_lc.txt') or not os.path.exists(
'tf-idf_lc/documents_lc.txt') or not os.path.exists('tf-idf_lc/inverted-index_lc.txt'):
load_data()
vocab_idf_values = load_vocab()
doc... |
def load_data():
vocab = Counter()
documents = []
inverted_index = {}
directory = 'Qdatalc/'
file_names = []
file_names.append(os.path.join(directory, 'indexlc.txt'))
file_names.append(os.path.join(directory, 'Qindexlc.txt'))
for root, dirs, files in os.walk(os.path.join(directory... | The main task of the code is to check if required TF-IDF-related files exist, loading data if missing, then retrieving and returning the vocabulary with IDF values, document data, and inverted index for text processing or search applications. | def load_and_process_data():
if not os.path.exists('tf-idf_lc/vocab_lc.txt') or not os.path.exists('tf-idf_lc/idf-values_lc.txt') or not os.path.exists(
'tf-idf_lc/documents_lc.txt') or not os.path.exists('tf-idf_lc/inverted-index_lc.txt'):
load_data()
vocab_idf_values = load_vocab()
doc... |
def display_card_string(hand: list, position: int) -> str:
"""Displays the card's position hand, value, and suit
Args: hand, position
"""
return "Card(value='" + hand[position][0] + "', suit='" + hand[position][1] + "')"
def player_draw_another(hand: list, deck: list) -> bool:
"""Draws another card... | This function simulates a Blackjack game where the player and computer draw cards from a deck. It allows an optional "unlimited cards" mode, lets the player decide to draw more cards, calculates card totals, and determines the winner. The function returns True if the player wins, False otherwise. | def play_game():
"""play one game of blackjack
playerHand: list of cards in the player's hand
compHand: list of cards in the computer's hand
unlimitedMode: flag to set the game to unlimited cards
Returns:
bool: True if the player wins
"""
deck = []
playerHand = []
... |
def trim(seq):
if len(seq) == 0:
return seq
else:
for i in range(len(seq) - 1, -1, -1):
if seq[i] != 0:
break
return seq[0:i+1]
def divPoly(N, D):
N, D = list(map(frac, trim(N))), list(map(frac, trim(D)))
degN, degD = len(N)-1, len(D)-1
if(degN >= degD... | The code implements the extended Euclidean algorithm for polynomials. It computes the greatest common divisor (GCD) of two polynomials `a` and `b`, along with coefficients `s` and `t` such that `a*s + b*t = gcd`. The algorithm iteratively divides polynomials, tracks remainders, and calculates `S` and `T` arrays for the... | def extEuclidPoly(a, b):
print("inside extEuclid")
switch = False
a = trim(a)
b = trim(b)
if len(a) <= len(b):
a1, b1 = a, b
else:
a1, b1 = b, a
switch = True
Q, R = [], []
while b1 != [0]:
[q, r] = divPoly(a1, b1)
Q.append(q)
R.append(r)
... |
def randomSolution(cars):
cities = list(range(len(establishments)))
for i in range(10):
for car in cars:
randomCity = cities[random.randint(1, len(cities) - 1)]
inspect = float(establishments[randomCity].inspec_duration)
dist = float(distances[car.place][int(... | The code implements a hill-climbing algorithm to optimize car routes by minimizing the maximum travel time. It starts with a random or greedy initial solution, evaluates each car's time, and iteratively improves routes by exploring neighboring solutions. The algorithm updates routes if a better neighbor is found, aimin... | def hillClimb(cars, choice):
if choice:
randomSolution(cars)
else:
greedy(cars)
b = cars[0].time
for car in cars:
if car.time > b:
b = car.time
print("Initial time: " + str(b/3600))
for car in cars:
car.time = routeTime(car.route)
neighbours = ... |
def getSortedRouts(best_solution):
sol = list(enumerate(best_solution))
sol = sorted(sol, key= lambda x : routeTime(x[1]))
res = []
sorted_solution = []
res.append(sol[0][0])
sorted_solution.append(sol[0][1])
for i in range(1,len(best_solution)):
res.append(sol[i][0])
sorted... | The function generates neighboring solutions for a given route configuration using insertions and swaps, evaluates their costs, and returns the best non-tabu neighbor with lower cost. It avoids revisiting recent solutions via a tabu history and iteratively explores 100 potential neighbors by modifying customer position... | def get_tabu_neighbors(solution, size, tabu_history):
num_neighbors = 100
best_neighbor = solution
best_neighbor_cost = INF
changeableSolution = deepcopy(solution)
#this sets are to make sure we are not testing
insertedSet = set()
swapSet = set()
#get the sorted list of solutions so... |
def randomSolution(cars):
cities = list(range(len(establishments)))
for i in range(10):
for car in cars:
randomCity = cities[random.randint(1, len(cities) - 1)]
inspect = float(establishments[randomCity].inspec_duration)
dist = float(distances[car.place][int(... | This code implements a Tabu Search algorithm to optimize vehicle routing by minimizing time. It initializes solutions via random or greedy methods, iteratively explores neighbors while avoiding tabu (recent) solutions, updates the best route, and assigns optimized routes and times to vehicles. | def tabu_search(cars, is_random):
tabu_history = {}
num_iterations = 1000
tabu_limit = 10
if(is_random):
randomSolution(cars)
else:
greedy(cars)
b = 0
for car in cars:
if b < car.time:
b = car.time
print("Initial time: " + str(b/3600))
curre... |
def handle_file(user, parent, f):
audio = f.get('audio')
if not audio:
return
store_audio(user, parent, f, audio)
return
def handle_folder(user, d):
child_count = d['folder'].get('childCount')
if not child_count:
return []
token = get_token(user)
driveitem_id = d.get('i... | The code recursively traverses a hierarchical structure, processing each item as a file or folder. It prints the number of children, handles files via `handle_file`, and recursively processes sub-folders by fetching their children via `handle_folder`, continuing the traversal. | def walk(user, parent, children):
print(f"Walking {len(children)} children...")
if not children:
return
for item in children:
if item.get('file'):
handle_file(user, parent, item)
elif item.get('folder'):
children = handle_folder(user, item)
walk(... |
def validate_url_scheme(url) -> str:
# Check if URL starts with "http" or "https"
if not url.startswith('http'):
msg = "The URL must begin with http:// or https://"
exit_code = 1
url = ""
else:
msg = "URL Scheme Validated"
exit_code = 0
url = standardise_url(u... | This code creates a Streamlit-based custom search engine that ingests a website's sitemap, allows users to set similarity thresholds and scraping parameters, regenerates vector embeddings if needed, processes queries against the knowledge base, and displays AI-generated answers. It includes UI controls for configuratio... | def main():
# Streamlit app title and expander for defining or updating the knowledge base
input_url = st.sidebar.text_input("Enter the Sitemap URL of the knowledge base")
st.title("Custom Search Engine")
similarity_threshold = st.sidebar.slider("Enter the similarity threshold (%)",min_value=0, max_valu... |
def _readLine(self,c):
return [self._readPointType(c,'Start'),self._readPointType(c,'End')]
def _getCoords(self,text):
crds = text.split()
return [float(crds[1]),float(crds[0])]
def _arcCoords( self, coords, arctype, length=0.0, radius=0.0, centre=None ):
cw = (arctype == 'cw')
x... | The main task of the code is to read curve coordinates from input data, detect arc parameters (center and rotation type) if present, and return adjusted arc coordinates using `_arcCoords`. If arc data is invalid or missing, it defaults to returning the original coordinates. | def _readCurve(self,c):
crds=self._readLine(c)
try:
cntel=c.find("%sCenter"%(self._ns))
centre=self._getCoords(cntel.text)
arctype=c.get('rot')
return self._arcCoords(crds,arctype,centre=centre)
except:
return crds |
def _setupPointRef(self,stpid):
if self._setups is None:
ns=self._ns
self._setups={}
setups=self._data.findall("%sSurvey/%sInstrumentSetup"%(ns,ns))
for stp in setups:
id=stp.get('id')
pt=stp.find("%sInstrumentPoint"%(ns))
... | The main task of this code is to parse an observation element (obsel) to extract measurement data, including handling both straight lines and arcs. It processes attributes like monument names, distances, azimuths, equipment, and dates, converting azimuth formats and generating arc coordinates if needed. The parsed data... | def _readObservation(self, obsel ):
try:
ptreffrom=self._setupPointRef(obsel.get('setupID'))
ptfrom=self._getPoint(ptreffrom)
mntfrom=self._monumentName(ptreffrom) or 'unnamed'
ptrefto=None
elto=obsel.find("%sTargetPoint"%(self._ns))
if e... |
def _getTag(self,element):
return element.tag.replace(self._ns,'')
def _readLine(self,c):
return [self._readPointType(c,'Start'),self._readPointType(c,'End')]
def _readIrregularLine(self,c):
crds = []
pts = c.find(self._ns + 'PntList2D')
dim = 2
if pts == None:
... | This function processes a CoordGeom element to construct a multipolygon coordinate array by parsing Line, IrregularLine, and Curve elements. It identifies polygon rings by coordinate continuity, distinguishes outer/inner rings via area sign, and organizes them into a structured MultiPolygon or MultiLineString geometry,... | def _readCoGo(self,cogo):
''' Read a CoordGeom element to build a multipolygon coord array.
Assumes that:
rings are identifiable by difference between endpoint of one segment
and startpoint of the next
segments of rings are in order
inner rings immediately... |
def set_x(self, x):
self.rect[0] = x
self.text_x = self.set_text_x()
def set_y(self, y):
self.rect[1] = y
self.text_y = self.set_text_y()
def set_text_x(self):
large_text = pygame.font.Font('freesansbold.ttf', self.font_size)
text_width = text_objects(self.name.upper(), l... | The main task of the code is to set the x and y coordinates of an object using `set_x` and `set_y` methods, then generate corresponding text values for `text_x` and `text_y` by calling `set_text_x` and `set_text_y`. This likely updates positional data and associated text representations in a graphical or data-processin... | def set_xy(self, x, y):
self.set_x(x)
self.set_y(y)
self.text_x = self.set_text_x()
self.text_y = self.set_text_y() |
def message_display(text, x, y, inp_color, font_size, screen):
large_text = pygame.font.Font('freesansbold.ttf', font_size)
text_surf, text_rect = text_objects(text, large_text, inp_color) # Text.width is calculated here
text_rect = (x, y)
screen.blit(text_surf, text_rect)
return text_surf
def get_... | This function renders a node as an ellipse with its name, handles dragging by updating its position when clicked within its bounds, and optionally draws a debug hitbox. It uses Pygame to visualize the node and its interactive state. | def display_node(self, screen, mouse_pos, mouse_clicked, debug):
pygame.draw.ellipse(screen, self.color, self.rect)
message_display(self.name.upper(), self.text_x, self.text_y, self.text_color, self.font_size, screen)
while self.get_x() + self.get_width() > mouse_pos[0] > self.get_x() \
... |
def init_nodes(self):
rv = {}
for node in self.graph.nodes:
rv.update({node.name: VisualNode(node, random.randint(self.node_width, self.display_width - self.node_width),
random.randint(self.node_width, self.display_height - self.node_width), self.node_width)}... | This code initializes a Pygame-based GUI for visualizing graph traversal algorithms. It sets up a window, loads a graph structure, creates nodes/edges, and prepares for pathfinding (defaulting to Dijkstra). It initializes UI elements, including buttons, and enters a main loop for rendering and interaction, with FPS deb... | def __init__(self, graph):
pygame.init()
pygame.display.set_caption('Searching.exe')
self.display_width = 1075
self.display_height = 600
self.window_display = pygame.display.set_mode((self.display_width, self.display_height))
self.clock = pygame.time.Clock()
self... |
def handle_interface_class(self):
for path, path_info in self.api_data['paths'].items():
for method, method_info in path_info.items():
method_name = get_method_name(path)
method_description = get_method_description(method_info)
parameters = get_paramet... | The main task of the code is to generate Python code by creating an 'output' directory, processing interface classes, handling reference schemas, and writing the interface class to disk. | def generate_python_code(self):
os.makedirs("output", exist_ok=True)
self.handle_interface_class()
self.handle_ref_schemas()
self.write_interface_class() |
def _ellipse__handle_img(img, radiusX, radiusY, maxTransparency):
if img is None:
shape = _ellipse__shape(radiusX, radiusY)
img = np.zeros(shape, dtype=type(maxTransparency))
centerX, centerY = _ellipse__center(radiusX, radiusY)
else:
centerX, centerY = int(floor(img.shape[0]/2))... | The function draws a hollow ellipse on an image by creating an outer ellipse and subtracting an inner ellipse (defined by the border width), leaving only the border. It handles edge cases for zero or large borders, ensures proper transparency, and returns the modified image with the hollow shape. | def hollow_ellipse(radiusX, radiusY, border, maxTransparency=np.float32(1.0), img=None):
"""
Similar to draw_ellipse. But you set the border width here.
Parameters
----------
radiusX : scalar float or int
radius in x-direction.
radiusY : scalar float or int
radius in y-direction... |
def DetectAruco_FindVertices(ArucoVideoFrame):
BottomVertices = []
TopVertices = []
axesPoint = np.float32([[0, 0, 0],
[0.25, 0, 0],
[0, 0.25, 0],
[0, 0, 0.25]])
GrayImage = cv2.cvtColor(ArucoVideoFrame,cv2.COLOR_BGR2GRAY)
ArucoDict = aruco.Dictionary_get(aruco.DICT_6X6_50)
Parameters = aru... | The code processes multiple video streams, detecting Aruco markers in the first frame to determine spatial coordinates. It resizes frames, overlays subsequent video feeds onto the first frame using detected marker positions, and displays the combined result in real-time. The loop continues until all videos are read or ... | def main():
# Dictionary - DICT_6X6_50 is used.
# Reading video
CapList = [cv2.VideoCapture(0),#'Videos/ArucoVideo1.avi'),
cv2.VideoCapture('Videos/Video1.avi'),
cv2.VideoCapture('Videos/Video2.avi'),
cv2.VideoCapture('Videos/Video3.avi'),
cv2.VideoCapture('Videos/Video4.avi'),
cv2.Vide... |
def pick_expansion_vertex(self):
""" Based on the net force on each vertex, picks a vertex where higher net forces correspond
to higher expansion probability.
By default, if for whatever reason somehow P doesn't reach zero, returns first vertex.
"""
graph = self._graph_di... | The code's main task is to generate a new vertex at a specified expansion point, ensuring it is not within distance 'r' of existing vertices. If proximity is detected, it creates an edge instead. The function recursively checks validity, risking Python's recursion depth limit if excessive calls occur. | def make_new_vertex(self):
""" Spawns a new vertex, one that is not within r of any other vertex."
If this new vertex is within r of another vertex, it will instead
simply create a new edge from the growth vertex to that vertex.
Big issue here: If it calls itself too many tim... |
def _make_word_file_name(self, image_file: str) -> str:
return self._get_file_rootname(image_file) + '.docx'
def _read_images_from_file(self, image_filename: str):
print('Reading', image_filename)
if self._filetype_is_pdf(image_filename):
return self._convert_pdf_to_images(image_file... | The code converts an image or PDF file into a Word document by reading images from the input file, creating a new Word document, inserting text sections, adding images, and cleaning up temporary image files if the input is a PDF. It saves the final document with the specified output name. | def _convert_image_to_word(self, filename: str):
original_image_file = f'{self.input_folder}/{filename}'
word_file = f'{self.word_folder}/{self._make_word_file_name(filename)}'
doc = docx.Document()
images, image_files = self._read_images_from_file(original_image_file)
self._wri... |
def cd(path):
"""
A context manager to move to a certain directory to execute
code that will read/write files
"""
old_dir = os.getcwd()
os.chdir(path)
yield
os.chdir(old_dir)
def _make_directory(self, directory: str):
if not os.path.exists(directory):
os.mkdir(directo... | The code's main task is to convert image and PDF files from the `recipes_to_convert` directory into Word (.docx) files, saving them in the `converted_recipes` directory. It identifies valid file types, processes each file, and issues warnings for unsupported formats. The process involves creating output directories, ch... | def run(self):
"""
Finds all the image and pdf files in the `recipes_to_convert` directory
and parses the strings out of the image files, then writes
docx files with the strings and images into the `converted_recipes` directory
"""
with cd(os.path.expanduser(self.converte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.