dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_examples(input_json, set_type):
with open(input_json, "r", encoding="utf-8") as reader:
input_data = json.load(reader)["data"]
is_training = set_type == "train"
examples = []
for entry in tqdm(input_data):
title = entry["title"]
for paragraph in entry["paragraphs"]:
... | The main task of this code is to preprocess the SQuAD and BioASQ datasets for question-answering tasks. It loads datasets, converts them into model-ready features using a tokenizer, and saves these features as pickle files for future training/evaluation. The code handles both training/validation splits of SQuAD and con... | def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model_type",default='roberta',type=str)
parser.add_argument("--model_name_or_path",default='roberta-base',type=str)
parser.add_argument("--tokenizer_name",default="",type=str)
parser.add_argument("--cache_dir",default="",type=str... |
def _get_document_for_url(self, url):
content = self._get_content_for_url(url)
return lxml.html.document_fromstring(content)
def _get_auth_data(self):
result = self._get_request_for_url(
parse.urljoin(
self.BASE_URL_SECURE,
'/user/auth_token'
... | This method authenticates a user by submitting login credentials to a secure URL, extracting necessary tokens from the HTML response, and handling authentication validation. It sends a POST request with username, password, and security tokens, checks for login errors, and stores authentication data and user metadata if... | def _login(self):
login_url = parse.urljoin(self.BASE_URL_SECURE, self.LOGIN_PATH)
document = self._get_document_for_url(login_url)
authenticity_token = document.xpath(
"(//input[@name='authenticity_token']/@value)[1]"
)[0]
utf8_field = document.xpath(
"(/... |
def _get_document_for_url(self, url):
content = self._get_content_for_url(url)
return lxml.html.document_fromstring(content)
def _get_url_for_exercise(self, date, username):
return parse.urljoin(
self.BASE_URL,
'exercise/diary/' + username
) + '?date=%s' % (
... | This method retrieves exercise data for a specified date. It accepts either a datetime/date object or three integers (year, month, day) to construct the date. Using the date and username, it fetches a document from a URL, extracts exercise goals from the document, and returns the exercise data. | def get_exercise(self, *args, **kwargs):
if len(args) == 3:
date = datetime.date(
int(args[0]),
int(args[1]),
int(args[2]),
)
elif len(args) == 1 and isinstance(args[0], datetime.date):
date = args[0]
else:
... |
def _get_document_for_url(self, url):
content = self._get_content_for_url(url)
return lxml.html.document_fromstring(content)
def _get_url_for_measurements(self, page=1, measurement_id=1):
return parse.urljoin(
self.BASE_URL,
'measurements/edit'
) + '?page=%d&type... | The function retrieves and filters measurements of a specified type (e.g., 'Weight') between given date bounds. It handles default date ranges, adjusts for user input order, fetches data from a URL, identifies the measurement ID, paginates through results, and filters entries to include only those within the specified ... | def get_measurements(
self, measurement='Weight', lower_bound=None, upper_bound=None
):
""" Returns measurements of a given name between two dates."""
if upper_bound is None:
upper_bound = datetime.date.today()
if lower_bound is None:
lower_bound = upper_bound... |
def _get_document_for_url(self, url):
content = self._get_content_for_url(url)
return lxml.html.document_fromstring(content)
def _get_url_for_measurements(self, page=1, measurement_id=1):
return parse.urljoin(
self.BASE_URL,
'measurements/edit'
) + '?page=%d&type... | This function updates a user's measurement data (e.g., weight) on MyFitnessPal by constructing and submitting a POST request with the appropriate parameters. It validates input, retrieves required IDs from parsed HTML, formats data with dynamic keys, and handles errors for missing measurements or failed requests. | def set_measurements(
self, measurement='Weight', value=None
):
""" Sets measurement for today's date."""
if value is None:
raise ValueError(
"Cannot update blank value."
)
# get the URL for the main check in page
# this is left in bec... |
def _get_document_for_url(self, url):
content = self._get_content_for_url(url)
return lxml.html.document_fromstring(content)
def _get_url_for_measurements(self, page=1, measurement_id=1):
return parse.urljoin(
self.BASE_URL,
'measurements/edit'
) + '?page=%d&type... | The main task of the code is to retrieve and return a list of measurement IDs by fetching a document from a specific URL, extracting measurement type identifiers from the document, and returning them as a list. | def get_measurement_id_options(self):
""" Returns list of measurement choices."""
# get the URL for the main check in page
document = self._get_document_for_url(
self._get_url_for_measurements()
)
# gather the IDs for all measurement types
measurement_ids = s... |
def _get_document_for_url(self, url):
content = self._get_content_for_url(url)
return lxml.html.document_fromstring(content)
def _get_url_for_date(self, date, username):
return parse.urljoin(
self.BASE_URL,
'food/diary/' + username
) + '?date=%s' % (
... | The main task of the code is to create a `Day` object by either accepting a pre-defined `datetime.date` instance or three integers (year, month, day) to construct a date. It fetches associated data (meals, goals, completion status) from a document, retrieves additional information (notes, water) via lazy-loaded lambda ... | def get_date(self, *args, **kwargs):
if len(args) == 3:
date = datetime.date(
int(args[0]),
int(args[1]),
int(args[2]),
)
elif len(args) == 1 and isinstance(args[0], datetime.date):
date = args[0]
else:
... |
def find_airplane_details(self) -> Dict[AnyStr, AirplaneDetails]:
df: DataFrame = pd.read_csv(self.__PATH_TO_FUEL_CONSUMPTION_CSV + ".csv", delimiter=';') # Read in fuel consumption and flight speed depending on flight level
return {
int(row[self.FLIGHT_LEVEL_KEY]): AirplaneDetails(
... | The code initializes a problem setup for a flight optimization task, defining parameters like problem size (small/medium/big) and cost type (random or data-based). It gathers airplane details, climate costs per voxel, and flight data to prepare for solving the problem, printing configuration details during initializati... | def __init__(self, problem_size: Literal['small', 'medium', 'big'] = 'small', random_cost: bool = False):
self.__problem_size: Literal['small', 'medium', 'big'] = problem_size # Define problem size (small: 6 x 6 x 1 for one flight; medium: 6 x 6 x 3 for two flights; big: full problem set)
print(f'Runni... |
def find_distance(self, voxel_a: Voxel, voxel_b: Voxel) -> float:
return np.sqrt(
np.power(voxel_a.longitude_meter - voxel_b.longitude_meter, 2)
+ np.power(voxel_a.latitude_meter - voxel_b.latitude_meter, 2)
+ np.power(voxel_a.flight_level_meter - voxel_b.flight_level_meter, ... | This function calculates the total climate cost for a flight path between two voxels by determining the distance between them, identifying the flight direction (descent, climb, cruise), and summing the climate costs computed for the start and end voxels using their respective cost parameters. | def calculate_cost(self, voxel_start: Voxel, voxel_end: Voxel, cost_start_voxel: float, cost_end_voxel: float) -> float:
distance: float = self.find_distance(voxel_start, voxel_end) # Find distance between voxels
flight_direction: str = self.find_flight_direction(voxel_start.flight_level_meter, voxel_... |
def find_horizontal_distance(self, voxel_a: Voxel, voxel_b: Voxel) -> float:
return np.sqrt(
np.power(voxel_a.longitude_meter - voxel_b.longitude_meter, 2)
+ np.power(voxel_a.latitude_meter - voxel_b.latitude_meter, 2)
)
def find_vertical_distance(self, voxel_a: Voxel, voxel_b: V... | This function calculates and stores the climate cost between neighboring voxels (same time) that are within specified horizontal and vertical distance thresholds, returning a dictionary mapping each voxel's index to its connected neighboring voxel indices and their corresponding costs. | def find_cost_for_neighbouring_voxels(self) -> Dict:
cost_between_neighbouring_voxels = {}
for time_voxel_start, cost_start in self.cost_by_voxels.items():
cost_between_neighbouring_voxels[time_voxel_start.voxel.index] = {}
for time_voxel_end, cost_end in self.cost_by_voxels.item... |
def parse_bags(data):
bags = []
for line in data:
regex_search = re.search(BAG_PATTERN, line)
color, inside_bags = regex_search.group(1), regex_search.group(2)
bag = get_or_create_bag(bags, color)
if inside_bags != "no other bags":
current_bags = {}
for... | The code processes input data by parsing it into a structured format (bags) and computes two distinct solutions (part1 and part2) based on this data. The main task involves reading input lines, converting them into a bag structure, and returning the results of two problem-solving functions applied to these bags. The fu... | def solve(f):
bags = parse_bags(f.readlines())
return part1(bags), part2(bags) |
def isLeaf(self):
return len(self.children) < self.nr_actions
def expand(self):
new_child = MonteCarloTreeSearchNode(self.params)
self.children.append(new_child)
def simulate_with_rollout(self, generative_model, action, depth):
return self.simulate_action(generative_model, action, depth,... | The code performs a recursive simulation in a decision tree, handling leaf node expansion, action selection via Q-values, and reward accumulation with discounting. It terminates at the horizon depth, uses a generative model for step transitions, and combines immediate rewards with future estimates via gamma discounting... | def simulate(self, generative_model, depth):
if depth >= self.horizon:
return 0
if self.isLeaf():
self.expand()
selected_action = len(self.children) - 1 # Select action that leads to new child node
_, reward, _, _ = generative_model.step(selected_action)
... |
def isLeaf(self):
return len(self.children) < self.nr_actions
def expand(self, state):
prior_probs, value = self.rl_function(state)
self.children.append(SimpleAlphaZeroNode(self.params, prior_probs, value))
def select(self, Q_values, action_counts, prior_probs):
return PUCB(Q_values, act... | This code performs a simulation step in a Monte Carlo Tree Search (MCTS) algorithm. It recursively explores the search tree, expanding leaf nodes by generating new states via a generative model, selecting actions based on Q-values, visit counts, and prior probabilities, and calculating rewards with discounting. The fun... | def simulate(self, generative_model, depth):
if depth >= self.horizon:
return 0
if self.isLeaf():
self.expand(generative_model.state())
selected_action = len(self.children) - 1 # Select action that leads to new child node
_, reward, _, _ = generative_model... |
def read_string(io):
return read_bytes(io).decode('utf8')
def read_value(io):
typ = read_varint(io)
return {0: lambda _: None,
1: lambda _: False,
2: lambda _: True,
3: read_list,
4: read_dict,
5: read_bytes,
6: read_string,
... | The code reads a dictionary from an input stream by reading a variable-length integer indicating the number of key-value pairs, then deserializing each key (as a string) and value (as a generic value) from the stream, constructing a dictionary from these pairs. | def read_dict(io):
return dict((read_string(io), read_value(io))
for _ in range(read_varint(io))) |
def gentreebydepth(self, rootn, turnplayer, depth):
currnode = rootn
# print('X:', currnode.xpos, ' O:', currnode.opos)
if depth > 0:
childl = self.calc_moves(
currnode, turnplayer) # calculates children
if childl:
for m in childl:
... | The code's main task is to determine the best move for a game-playing agent by generating a game tree (either depth-limited or complete) from the given board state. It uses depth-limited search if a depth is specified, otherwise constructs the full game tree. The best move is calculated using `calcbestmove` on the gene... | def makemove(self, boardstate, depth=-1):
# calc tree on player's first turn
re = Node([], [])
# depth-limited search
if depth > 0:
self.rootn = self.gentreebydepth(boardstate, self.xo, depth)
re = self.calcbestmove(self.rootn)
# complete tree search
... |
def get_coco_dataset(self):
# COCO Dataset
annotation_file = self.Original_Path + '/annotations/captions_train2014.json'
PATH = self.Original_Path + '/train2014/'
# Read the json file
with open(annotation_file, 'r') as f:
annotations = json.load(f)
... | This method processes image-caption datasets (COCO or Flickr8k) by loading data, extracting image features if needed, tokenizing captions, splitting into training/validation sets, and returning prepared datasets, tokenizer, and training parameters for model training. | def call(self):
if(self.dataset_name=='coco'):
train_captions, img_name_vector = self.get_coco_dataset()
if(self.feature_extracted==False):
self.extract_image_features(img_name_vector)
img_name_train, img_name_val, cap_train, cap_val,tokenizer,max_length = sel... |
def cons(x,y):
return [x] + y
def maiordalinha(vals):
if vals == []:
return []
else:
if quantidade(vals) == 1:
return car(vals)
else:
if car(vals) > car(cdr(vals)):
return maiordalinha(cons(car(vals),cdr(cdr(vals))))
else:
... | The function `maioresdaslinhas` recursively processes a list of lists (`vals`), extracting the maximum value from each sublist using `maiordalinha`, and constructs a new list of these maximums. If `vals` is empty, it returns an empty list. The result is a list containing the maximum element of each sublist in `vals`.) | def maioresdaslinhas(vals):
if vals == []:
return []
else:
return cons(maiordalinha(car(vals)),maioresdaslinhas(cdr(vals))) |
def car(x):
return x[0]
def somarlinhasMatriz(vals):
if vals == []:
return []
else:
return cons(somalinha(car(vals)),somarlinhasMatriz(cdr(vals)))
def cdr(x):
return x[1:] | The main task of the code is to recursively compute the sum of the first elements of each sublist in a nested list structure. It processes the input list `vals` by summing the first element of each sublist using `car(somarlinhasMatriz(vals))` and then recursively adding the result of the remaining elements via `somarLi... | def somarListadeSomas(vals):
if vals == []:
return 0
else:
return car(somarlinhasMatriz(vals)) + somarListadeSomas(cdr(vals)) |
def win(game):
if(game[0][0] ==' x ' and game[0][1]==' x ' and game[0][2]==' x ' or game[1][0]==' x ' and game[1][1] ==' x 'and game[1][2]==' x ' or game[2][0] ==' x 'and game[2][1] ==' x 'and game[2][2] ==' x 'or game[0][0]==' x ' and game[1][1] ==' x 'and game[2][2]==" x "):
showboard(game)
print("Hurray ! You w... | The code implements a turn-based game loop where the user and bot alternate turns. It displays the game board, checks for a win condition, and alternates control between the user (via userchance()) and the bot (via bot()) using a counter. The loop continues indefinitely, toggling turns until a win is detected, though t... | def main():
user=1
chance=1
while True:
win(game)
showboard(game)
if(user==1):
print("\n> Your chance ......\n")
userchance()
user-=1
chance+=1
#print(game)
else:
bot()
#showboard(game)
user+=1
chance+=1 |
def __add_task_to_queue(task,*args,**kwargs):
queue = __get_queue()
queue.enqueue(task,*args,**kwargs)
def __sheduled_tasks_count(queue_name='default'):
queue = __get_queue()
return queue.count
def __finished_tasks():
conn = __get_redis_con()
queue = __get_queue()
job_ids=queue.finished_job_... | The main task of the code is to handle a task parameter from an HTTP request, add it to a task queue if provided, and render an HTML template with real-time status data including queue count, completed tasks, and the task parameter. It updates a data dictionary with these values before passing it to the template for di... | def index_func():
data={'title':'index'}
task_param = request.form.get("task_param")
if task_param is not None:
__add_task_to_queue('tasks.simple_task',task_param)
else:
task_param='None'
data={'title':'index',
'queue_count':__sheduled_tasks_count(),
'completed':l... |
def check_download_folder(self):
"""
Check the existence of the download folder or prompt the user for the selection of a new one.
:return: True in case it exists
:rtype: bool
"""
# Check the download folder
if os.path.exists(self.download_folder_path)... | This function adds a WFS layer to QGIS's table of contents using a QML file. It splits input data to extract layer name and EPSG code, checks a download folder, downloads the specified QML file, and invokes addWfs with parameters including the downloaded QML path to render the layer in QGIS. | def addWfsQML(self, name, url, data, qml_url):
"""
# Slot for exposing the same-name function to Javascript. #
Add the WFS with its *.qml to the QGis TOC.
:param name: The name
:type name: str
:param url: The WFS URL
:type url: str
... |
def check_download_folder(self):
"""
Check the existence of the download folder or prompt the user for the selection of a new one.
:return: True in case it exists
:rtype: bool
"""
# Check the download folder
if os.path.exists(self.download_folder_path)... | This function adds a PostgreSQL database table to QGIS's Table of Contents (TOC) with associated QML styling. It processes input parameters to extract port/SSL settings, table name/SQL filter, downloads the specified QML file, and delegates to add_postgres_layer to create the layer with styling. | def addTabellaQML(self, name, host, port, database_name, username, schema, table, geom_col, id_col, qml_url):
"""
# Slot for exposing the same-name function to Javascript. #
Add the database table in the QGis TOC and apply its associated QML.
:param name: The name
... |
def pull_data(self, filename=None):
if filename is None:
filename = datetime.today().strftime('%d%m%y')
key = self.connection.get(LAST)
logging.info("{}=>{}".format(key, filename))
if key and key[2:-4] == filename:
logging.info("Arleady in DB {0}.".format(filename... | The main task of the code is to retrieve and process data from a connection based on a given key or name. It handles cases where the key is unspecified by fetching the last recorded key, checks for data existence, loads JSON data, and returns either sorted results (by default) or filtered results by name. Error logging... | def get_data(self, key=None, record=10, name=None):
if key is None:
key = self.connection.get(LAST)
if key is None:
self.pull_data()
data = self.connection.get(key)
if data is None:
logging.error("Record not found '{}'.".format(key))
... |
def fDno(p):
y = ((ros+fRs(p)*rgs)/fBo(p))/144
return y
def fphi(p):
y = phi_ref*np.exp(cr*(p-p_ref))
return y
def fBo(p):
y = interpolate(Pfl, Bo, p)
return y
def fRs(p):
y = interpolate(Pfl, Rs, p)*1000/5.6146
return y
def fBw(p):
x = Cw*(p-Pw_ref)
y = Bw_ref/(1+x+(x*x/2))
... | The main task of the code is to compute initial oil, gas, and water in place (OOIP, OGIP, OWIP) in a 3D reservoir model. It calculates pressure distribution iteratively using Newton-Raphson, initializes 3D pressure and saturation arrays, and aggregates volumes by summing contributions from each grid cell using fluid pr... | def initial():
global Pg3d, Sw3d, dltx, dlty, dltz, vb, tpx, tpy, tpz, ooip, ogip, owip
dltx = Dx/Ngx
dlty = Dy/Ngy
dltz = Dz/Ngz
vb = dltx*dlty*dltz
tpx = 6.3283*(10**(-3))*kx*dlty*dltz/dltx
tpy = 6.3283*(10**(-3))*ky*dltx*dltz/dlty
tpz = 6.3283*(10**(-3))*kz*dlty*dltx/dltz
# menc... |
def deriv(sws, swn, ps, pn, dz, ijkw, ijko, pgeo):
global dT, fTw, fTo
pmid = 0.5*(pn+ps)
if ijkw == 1:
Krwn = fkrw(swn)
dKrwn = fdkrw(swn)
else :
Krwn = fkrw(sws)
dKrwn = 0
if ijko == 1:
Kron = fkro(swn)
dKron = fdkro(swn)
else:
Kron = fk... | The code computes the Jacobian matrix for a 3D grid system, calculating flux contributions from six neighboring directions (b, c, d, e, f, g) using a derivative function. It accumulates these fluxes and adjusts them with source terms and pressure-saturation derivatives to form the Jacobian entries (Ja) for each grid ce... | def jacob():
global Ja, Jb, Jc, Jd, Je, Jf, Jg, Fw, Fo
Ja = np.zeros((Ngx, Ngy, Ngz, 4), dtype=float)
Jb = np.zeros((Ngx+1, Ngy, Ngz, 4), dtype=float)
Jc = np.zeros((Ngx+1, Ngy, Ngz, 4), dtype=float)
Jd = np.zeros((Ngx, Ngy+1, Ngz, 4), dtype=float)
Je = np.zeros((Ngx, Ngy+1, Ngz, 4), dtype=float... |
def probability_a(majority, n, p_s, p_w):
prob = 0
nr_strong = precompute_s_k(n, majority) # for efficiency only compute higher than majority
for i, k in enumerate(range(majority, n+1)):
s_occur = nr_strong[i]
res = (comb(n, k)-s_occur) * np.power(p_w, k) * np.power(1 - p_w, n - k - 1) * (1... | The main task of the code is to execute different functions based on the input mode. If the mode is 'a', it calculates a probability using probability_a(); for 'b', 'c', or 'd', it runs corresponding functions run_b(), run_c(), or run_d(). If the mode is invalid, it prompts the user to select from 'a', 'b', 'c', or 'd'... | def main(mode):
if mode == 'a':
return probability_a(6, 11, 0.8, 0.6)
elif mode == 'b':
return run_b()
elif mode == 'c':
return run_c()
elif mode == 'd':
return run_d()
return 'Choose one of the following: a,b,c,d' |
def get_srv_list():
"""Gets active services list"""
srv_list = rosservice.get_service_list()
return srv_list
def get_robot_servo_set(srv_list):
"""Gets set of servos by parsing the list of available services"""
new_servo_set = set()
for srv in srv_list:
srv = srv.split("/")
if s... | The function `register_servo_dict` creates a dictionary mapping servo identifiers to ROS service proxies for `set_float` operations. It uses a provided or default servo set, checks if corresponding services exist, and returns the proxy dictionary alongside the servo set for controlling robotic servos via ROS. | def register_servo_dict(new_servo_set = None):
"""Returns a dict with name - set_position proxy pairs"""
new_proxy_dict = {}
if new_servo_set is None:
srv_list = get_srv_list()
new_servo_set = get_robot_servo_set(srv_list)
for servo in new_servo_set:
srv_name = servo2srv(servo)... |
def drawing():
for i in range(len(Vars["orientation"])):
for j in range(len(Vars["orientation"][0])):
if Vars["orientation"][i][j]==1:
pygame.draw.rect(Window,Vars["color"],[Vars["pos"][0]+(Vars["square"][0]*j),Vars["pos"][1]+(Vars["square"][1]*i),(Vars["square"][0])-2,(Vars["squ... | The code checks if a game piece (shape) can move downward in a grid-based game (likely Tetris). It iterates through the shape's orientation matrix to verify if the target position in the game grid is empty. If valid, it updates the piece's position and redraws it; otherwise, it locks the piece into the grid and generat... | def move():
test=True
num=0
for i in range(len(Vars["orientation"])-1):
for j in range(len(Vars["orientation"][0])):
if Vars["xy"][1]+len(Vars["orientation"])<20:
if Vars["orientation"][i][j]==1 and Vars["orientation"][i+1][j]==0:
if Vars["structure"][... |
def assumptions_check(self):
configs = self.configs
k, d, n1, n2, nT, c, delta, rho = configs.get("k"), configs.get("d"), configs.get("n1"), configs.get("n2"), configs.get("nT"), configs.get("c"), configs.get("delta"), configs.get("rho")
C = 1.0
n1_bound = C * rho**4 * (d + np.log(nT / d... | The main task of the code is to initialize a simulation by generating source and target tasks based on specified parameters. It checks assumptions, configures representation and specialization parameters, and either creates new tasks or updates existing ones using provided configurations. The function prints task gener... | def instantiate(self, num_experiments, initial=True, new_experiment:dict=None):
"""
instantiate the simulation
"""
self.assumptions_check()
print(f"Experiment: A4.1 {self.A1}, A4.2 {self.A2}, A4.3 {self.A3}, A4.4 {self.A4}")
self.B = self.representation()
... |
def printCurrentConfigurationToFile(self):
with open(self._out_file, 'a') as file:
file.write("\n--------------\n")
file.write('State: ' + str(self._state) + " ")
file.write('Index: ' + str(self._index) + "\n")
file.write('Working stack: ' + str(self._working_stac... | This function performs descent recursive parsing on a sequence by managing input and working stacks. It processes the sequence step-by-step, expanding non-terminals, advancing when symbols match, and backtracking as needed. The parser transitions between states ('q' for parsing, 'b' for backtracking), handling success,... | def parsingStrategy(self, w):
"""
Parse a sequence using descendent recursive parsing
:param w: sequence to be parsed
:return:
"""
print("SEQUENCE: ", self._sequence)
w = self._sequence
while self._state != 'f' and self._state != 'e':
self.pr... |
def remove_special_characters(text):
regex = r'[^a-zA-Z0-9\s]'
text = re.sub(regex,'',text)
return text
def pos_tagging(text):
pos_tag = nltk.pos_tag(text.split())
pos_tagged_noun_verb = []
for word,tag in pos_tag:
if tag == "NN" or tag == "NNP" or tag == "NNS" or tag == "VB" or tag == "... | The code calculates a sentence's importance score by summing TF-IDF values of its processed words. It removes stopwords, special characters, and digits, then lemmatizes remaining words to compute their TF-IDF contribution using the provided frequency dictionary and list of sentences. | def sentence_importance(sentence,dict_freq,sentences):
wordlemmatizer = WordNetLemmatizer()
Stopwords = set(stopwords.words('english'))
sentence_score = 0
sentence = remove_special_characters(str(sentence))
sentence = re.sub(r'\d+', '', sentence)
pos_tagged_sentence = []
no_of_sentenc... |
def remove_special_characters(text):
regex = r'[^a-zA-Z0-9\s]'
text = re.sub(regex,'',text)
return text
def lemmatize_words(words):
wordlemmatizer = WordNetLemmatizer()
lemmatized_words = []
for word in words:
lemmatized_words.append(wordlemmatizer.lemmatize(word))
return lemmatized_w... | The code extracts and summarizes key information from a webpage by computing TF-IDF scores for sentences, selecting the top 7 most important sentences to form a concise summary, and returning both the summary and sentence-score mappings. | def runTFIDF(url):
Stopwords = set(stopwords.words('english'))
wordlemmatizer = WordNetLemmatizer()
stemmer = PorterStemmer()
ssl._create_default_https_context = ssl._create_unverified_context
scraped_data = urllib.request.urlopen(url)
article = scraped_data.read()
parsed_article = bs.Beaut... |
def r_type(opcode):
# R_type,add,sub,sll,slt,sltu,xor,srl,sra,or,and,
if opcode[0] == "add":
return "0000000" + dec2bin(opcode[3], 5) + dec2bin(opcode[2], 5) \
+ "000" + dec2bin(opcode[1], 5) + "0110011"
elif opcode[0] == "sub":
return "0100000" + dec2bin(opcode[3], 5) + dec2b... | This function identifies RISC-V instruction types based on the opcode and delegates the conversion to corresponding helper functions (r_type, i_type, etc.) to generate machine code. It handles R-type, I-type, S-type, B-type, J-type instructions, and recursively processes opcodes with adjusted positions for specific enc... | def riscv2machine(opcode, list_of_label):
# R_type,add,sub,sll,slt,sltu,xor,srl,sra,or,and,
if (opcode[0] == "add") or (opcode[0] == "sub") or (opcode[0] == "sll") \
or (opcode[0] == "slt") or (opcode[0] == "sltu") or (opcode[0] == "xor") \
or (opcode[0] == "srl") or (opcode[0] == "sra")... |
def read_origin():
""" Read origin station index from user
If user enters an invalid station index, report to user and
continuously ask until a valid index is entered.
Return origin station index (int)
:param: Nothing
:return: int
"""
while True :
origin = int(in... | The function `reserve` manages train seat reservations by reading user-specified origin and destination stations, checking available seats, and handling reservations. If seats are available, it displays ticket prices for each class, lets the user select a seat, reports the price, and updates the seat list. If no seats ... | def reserve(train_seats, train_seat_classes, station_indexes, station_fees):
""" Function reserve does the followings:
1. read origin and destination station indexes from user
2. find available seats between origin and destination station indexes
3. if there are available seats,
... |
def read_canceled_seat(train_seats):
""" Read the canceled seat from user
Receive dictionary of seats as function input.
If user enters an invalid seat, report to user and
continuously ask until a valid seat is entered.
Note that the canceled seat may or may not have the cancele... | The function 'cancel' manages seat ticket cancellation by reading user inputs for the seat, origin, and destination stations. It displays existing tickets for the specified seat, attempts to remove the ticket, and updates the display if successful. If the ticket doesn't exist, it notifies the user. The function modifie... | def cancel(train_seats, station_indexes):
""" Function cancel does the followings:
1. read the canceled seat from user
2. read the origin and destination station index of canceled ticket
3. display tickets reserved under the canceled seat
3. if ticket removal is successful, \
... |
def get_booking_by_date(booking_table, num_floors, num_rooms, _date):
""" From the given booking data from file, create 2 nested lists. Each
nested list has size = num_floors x num_rooms
The first nested list shows which hotel room is booked on _date.
Value = 1 if the room is booked. Otherwise,... | This function provides a menu-driven interface to manage hotel bookings, displaying booking details, available rooms, and revenue data based on user choices. It handles queries by date, floor, guest name, and date ranges, retrieving and printing booking information or revenue statistics in Baht. | def operate(booking_table, num_floors, num_rooms, choice):
if choice == 1:
current_date = int(input('Enter date: '))
curr_booking, curr_guests = get_booking_by_date(booking_table,
num_floors, num_rooms,
... |
def get_arguments():
parser = argparse.ArgumentParser(
description='Simulate AZ failure: associate subnet(s) with a Chaos NACL that deny ALL Ingress and Egress traffic - blackhole',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--region', type=str, required=True,
... | The main task of the code is to execute post-rollback operations or initiate a run based on command-line arguments. If `post_rollback` is enabled, it performs cleanup tasks like removing chaos configurations and rolling back EKS AZ settings. If disabled, it triggers a run function with parameters such as region, AZ, VP... | def entry_point():
args = get_arguments()
#args = get_arguments_test()
print(args)
if(args.post_rollback):
print('post rollback enabled')
if(post_rollback(args.region)) is True:
print('Post Rollback Success')
if(post_delete_chaos_nacl(args.region)) is True:
... |
def RetrieveTickets(self):
self.send_response(200)
self.send_header("Content-Type","application/json")
self.end_headers()
db = TicketsDB()
tickets = db.getAllTickets()
self.wfile.write(bytes(json.dumps(tickets),"utf-8"))
def RetrieveOneTicket(self):
parts = self.p... | This code handles HTTP GET requests by routing based on the URL path. If the path is "/tickets", it retrieves all tickets; if it starts with "/tickets/", it retrieves a specific ticket. Otherwise, it handles the request as not found. | def do_GET(self):
#self.loadCookie()
print("The path is",self.path)
if self.path == "/tickets":
self.RetrieveTickets()
elif self.path.startswith("/tickets/"):
self.RetrieveOneTicket()
else:
self.handleNotFound() |
def handleNotAuthorized(self):
self.send_response(401, "Error, Unable to Authenticate")
self.end_headers()
self.wfile.write(bytes("Did not work", "utf-8"))
def end_headers(self):
self.sendCookie()
self.send_header("Access-Control-Allow-Origin",self.headers["Origin"])
self... | This method retrieves a specific sport event by ID from the database if the user is authorized. It checks for user authentication, extracts the event ID from the request path, queries the database, and returns the event data as JSON with a 200 status if found. If unauthorized or not found, it triggers respective error ... | def RetrieveOneEvent(self):
if "userid" not in self.session:
self.handleNotAuthorized()
return
parts = self.path.split("/")
sports_id = parts[2]
db = SportEventsDB()
sport = db.getOneSportEvent(sports_id)
if sport != None:
... |
def handleNotAuthorized(self):
self.send_response(401, "Error, Unable to Authenticate")
self.end_headers()
self.wfile.write(bytes("Did not work", "utf-8"))
def end_headers(self):
self.sendCookie()
self.send_header("Access-Control-Allow-Origin",self.headers["Origin"])
self... | This function handles updating a specific sport event in a database. It checks user authorization, retrieves the event by ID, parses the request body for new data, updates the database, and sends a 200 response. If unauthorized or the event is not found, it triggers appropriate error handlers. | def handleUpdateOneEvent(self):
if "userid" not in self.session:
self.handleNotAuthorized()
return
parts = self.path.split("/")
sports_id = parts[2]
db = SportEventsDB()
sport = db.getOneSportEvent(sports_id)
if sport != None:
... |
def handleNotAuthorized(self):
self.send_response(401, "Error, Unable to Authenticate")
self.end_headers()
self.wfile.write(bytes("Did not work", "utf-8"))
def end_headers(self):
self.sendCookie()
self.send_header("Access-Control-Allow-Origin",self.headers["Origin"])
self... | The main task of the code is to delete a specific sport event by ID after verifying user authorization. It checks if the session contains a user ID, retrieves the sport event from the database using the ID from the request path, deletes it if found, and returns a 200 OK response with JSON content type. If unauthorized ... | def HandleDeleteOneEvent(self):
if "userid" not in self.session:
self.handleNotAuthorized()
return
parts = self.path.split("/")
sport_id = parts[2]
db = SportEventsDB()
sport = db.getOneSportEvent(sport_id)
if sport != None:
... |
def loadSession(self):
self.loadcookie()
# if session ID is in the cookie
if "sessionId" in self.cookie:
sessionId = self.cookie["sessionId"].value
# save the session int self.sessin for use later
self.session = SESSION_STORE.getSession(sessionId)
... | This code handles HTTP GET requests by routing based on the request path. It loads a session, checks if the path is "/sports" to retrieve all sports events, or starts with "/sports/" to fetch a specific event. If the path doesn't match, it returns a not-found response. | def do_GET(self):
self.loadSession()
if self.path == "/sports":
self.RetrieveSportEvents()
elif self.path.startswith("/sports/"):
self.RetrieveOneEvent()
else:
self.handleNotFound() |
def loadSession(self):
self.loadcookie()
# if session ID is in the cookie
if "sessionId" in self.cookie:
sessionId = self.cookie["sessionId"].value
# save the session int self.sessin for use later
self.session = SESSION_STORE.getSession(sessionId)
... | This code handles HTTP POST requests by routing them to specific methods based on the URL path. It loads a session, then checks the path to call either create sport events, create users, verify a session, or return a not-found response. | def do_POST(self):
self.loadSession()
if self.path == "/sports":
self.handleCreateSportEvents()
elif self.path == "/users":
self.handleCreateUsers()
elif self.path == "/sessions":
self.handleVerifyUser()
else:
self.handleNotFound() |
def loadSession(self):
self.loadcookie()
# if session ID is in the cookie
if "sessionId" in self.cookie:
sessionId = self.cookie["sessionId"].value
# save the session int self.sessin for use later
self.session = SESSION_STORE.getSession(sessionId)
... | The code handles PUT requests by first loading a session. If the request path starts with "/sports/", it updates a specific event using `handleUpdateOneEvent()`. Otherwise, it responds with a "Not Found" error via `handleNotFound()`. The primary task is routing PUT requests to either update a sports-related event or re... | def do_PUT(self):
self.loadSession()
if self.path.startswith("/sports/"):
self.handleUpdateOneEvent()
else:
self.handleNotFound() |
def loadSession(self):
self.loadcookie()
# if session ID is in the cookie
if "sessionId" in self.cookie:
sessionId = self.cookie["sessionId"].value
# save the session int self.sessin for use later
self.session = SESSION_STORE.getSession(sessionId)
... | This code handles DELETE requests by checking the request path. If the path starts with "/sports/", it deletes a specific event using HandleDeleteOneEvent(). Otherwise, it returns a 404 Not Found response via handleNotFound(). The method first loads the session before processing the request. | def do_DELETE(self):
self.loadSession()
if self.path.startswith("/sports/"):
self.HandleDeleteOneEvent()
else:
self.handleNotFound() |
def handle_join_message(
self_socket: socket.socket,
join_data: JoinMessageData
) -> None:
if join_data["id"] in MemberList:
# already in the member list (should not happen)
LOGGER.log(
f"Member {join_data['id']} already in the member list",
verbosity=2
)
... | The function continuously receives and processes network messages via UDP, handling JOIN, LEAVE, and GOSSIP commands. It simulates message drops, maintains node online status, logs events, and uses timeouts for periodic checks. | def handle_receiving_message(self_socket: socket.socket) -> None:
while True:
if not SelfNode["IsOnline"]:
time.sleep(T_UPDATE)
continue
try:
data, address = self_socket.recvfrom(CONNECTION_BUFFER_SIZE)
if random.random() < MESSAGE_DROP_RATE:
... |
def xticks(self, tick_values):
self.ax2.tick_params(axis="x", which="minor", bottom=True)
def xlim(self, tick_values):
pass
def yticks(self):
fig = self.fig
logy_min, logy_max = log10_bounds(self.err_min, self.err_max)
ax1, ax2 = self.ax1, self.ax2
ax1.set_yticks(
... | The main task of the code is to finalize a plot by configuring axes labels, titles, tick values, and layout. It sets x/y-axis ticks, limits, labels, and title using provided parameters, defaults to stored tick values if none are given, and applies `tight_layout()` to optimize spacing. | def finalize(self, title_params, ylabel_params, tick_values=None):
plt.figure(self.fig.number)
if tick_values is None:
tick_values = self.tick_values
# plt.minorticks_off()
self.xticks(tick_values)
self.xlim(tick_values)
self.yticks()
self.ylim()
... |
def header(self, all_labels):
n = len(all_labels)
header = "".join(
[
"\\begin{{tabular}}{{r\n",
n * " S[table-format=3.2e2]r\n",
"}}\n",
"\\toprule\n",
"N & ",
" & ".join(n * ["\n... | The main task of the code is to generate a convergence table by combining a header (from labels), content (from errors, rates, and resolutions), and a footer into a single string. It processes input arrays of errors, convergence rates, and resolutions to format them into a structured table representation for analysis o... | def __init__(self, all_errors, all_rates, resolutions, all_labels):
"""Create a convergence table from the provided data.
Both `all_errors` and `all_rates` are lists of the columns, e.g.
all_errors = [np.array([2e-2, 5.0e-3, 1.25e-3]), np.array([2.0e-2, 1.0e-2, 5.0e-3])]
all_ra... |
def establishConnection():
mqtt_client.connect(mqtt_broker)
notifyWorker("Device Online", datetime.now())
def readRFID():
global operation_active
RFIDReader = MFRC522()
previous_scan = datetime.timestamp(datetime.now()) - 3
while operation_active:
if datetime.timestamp(datetime.no... | The code initializes an RFID reader by setting up a GPIO interrupt for a stop button, prompts the user to place a card, establishes a connection, reads RFID data, and then closes the connection. | def executeRFIDReader():
GPIO.add_event_detect(stopButton, GPIO.FALLING, callback=handleButtonInterrupt, bouncetime=200)
print('Place the card close to the reader.')
establishConnection()
readRFID()
endConnection() |
def parse_input(filename):
with open(filename) as f:
input_data = f.read().split("\n")
curr_dir = ""
dir_sizes = defaultdict(lambda: 0)
for line in input_data:
args = line.split(" ")
if args[0] == COMMAND and args[1] == MOVE:
curr_dir = move(curr_dir, args[2])
... | The main task of the code is to execute problem-solving logic based on an environment variable. It reads input data from 'input.txt', determines which part (part1/part2) to process using the 'part' environment variable, applies the corresponding solution function (solve_part1 or solve_part2), and prints the result. The... | def main():
part = environ.get('part')
input_data = parse_input('input.txt')
if part == 'part1':
res = solve_part1(input_data)
else:
res = solve_part2(input_data)
print(f"Result: {res}") |
def parse_input(filename):
with open(filename) as f:
input_data = f.read().split("\n")
input_data = [[int(col) for col in row] for row in input_data]
return input_data
def solve_part1(input_data):
counter = 0
for row_nr in range(len(input_data)):
for col_nr in range(len(input_data[0]... | The main task of the code is to execute either part 1 or part 2 of a problem-solving script based on an environment variable. It reads input data from 'input.txt', processes it using the corresponding solver function (solve_part1 or solve_part2), outputs the result, and measures the execution time in milliseconds for p... | def main():
part = environ.get('part')
start = time.time()
input_data = parse_input('input.txt')
if part == 'part1':
res = solve_part1(input_data)
else:
res = solve_part2(input_data)
end = time.time()
print(f"Result: {res}")
print(f"Time: {round((end - start)*1000, 4)}ms"... |
def receive_user_input(cursor):
global input_type
print(
"Welcome! This app lets you to Recognise the License Plates from either several Videos or Images \n\n"
)
done=True
input_type = str(
input(
"you want to add Video or Image?(for image wirte -> Img, for vide... | The main task of the code is to perform license plate recognition (LPR) using a YOLO model. It connects to a database, receives user input, initializes the YOLO function, predicts license plates from input data, displays the detected plates, deletes temporary functions, and clears specified folders containing processed... | def main():
cursor = evadb.connect().cursor()
cursor = receive_user_input(cursor)
cursor = Creating_LPR_YOLO_Function(cursor)
result, cursor = YOLO_Predict_Function(cursor)
Display_Plates(result)
Del_Func(cursor)
Clear_Func(video_folder_path)
Clear_Func(image_folder_path) |
def receive_user_input(cursor):
global input_type
print(
"\n\nWelcome! This app lets you to Recognise the License Plates from either several Videos or Images \n\n"
)
done=True
input_type = str(
input(
"you want to add Video or Image?(for image wirte -> Img, for ... | The main task of the code is to perform License Plate Recognition (LPR) using a YOLO model for detection and character recognition. It connects to a database, processes user input, detects license plates in images/videos, displays results, loads a character model, recognizes plate numbers, stores recognized plates, and... | def main():
cursor = evadb.connect().cursor()
cursor = receive_user_input(cursor)
cursor = Creating_LPR_YOLO_Function(cursor)
result, cursor = YOLO_Predict_Function(cursor)
Display_Plates(result)
Character_Model_Load()
Plate_Number_Recognition(result)
print("Recognised plates:\n",... |
def parse_contents(contents):
content_type, content_string = contents.split(',')
global df_edge
global df_node
global default_node_threshold
global default_edge_threshold
global actual_max_node_size
global actual_min_node_size
decoded = base64.b64decode(content_string)
try:
#... | This function handles dynamic data processing in a Dash app by determining the trigger source (e.g., file upload or filter input), applying default thresholds if needed, and returning parsed data or filtered elements accordingly. It updates global thresholds for edge/node filters or processes uploaded element/color dat... | def update_elements(edge_number, node_number, element_contents):
global default_edge_threshold
global default_node_threshold
edge_number = default_edge_threshold if edge_number is None else edge_number
node_number = default_node_threshold if node_number is None else node_number
ctx = dash.callback_c... |
def parse_input(input_rows: list[str], add: int):
matching_indexes = []
pattern_indexes = []
patterns = []
pattern = []
for row in input_rows:
if ''.join(row).strip() == '':
matching_indexes.append(pattern_indexes)
patterns.append(pattern)
pattern = []
pattern_indexes = []
e... | The main task of the code is to process input rows by identifying vertical and horizontal patterns, calculate intersections between them, and compute a total value based on these patterns. It parses input, separates patterns into vertical and horizontal groups, transposes vertical patterns, and aggregates results using... | def run(input_rows: list[str]):
add = 1
matching_indexes, patterns = parse_input(input_rows, add)
vertical_patterns = []
horizontal_matching_indexes = []
horizontal_patterns = []
for i, matches in enumerate(matching_indexes):
if len(matches) > 0 and count_intersections(matches, patterns[i]) == len... |
def common_shooting(self):
self.create_laser(1, self.center_x)
def double_shooting(self):
self.create_laser(0.8, self.center_x - 30)
self.create_laser(0.8, self.center_x + 30)
def triple_shooting(self):
self.common_shooting()
self.double_shooting() | The code defines a `shooting` method that selects and executes different shooting behaviors based on the `shoot_mode` attribute. If `shoot_mode` is 1, it calls `common_shooting`; if 2, `double_shooting`; otherwise, it uses `triple_shooting`. The primary task is to dynamically switch between shooting strategies dependin... | def shooting(self):
if self.shoot_mode == 1:
self.common_shooting()
elif self.shoot_mode == 2:
self.double_shooting()
else:
self.triple_shooting() |
def add_to_index(self, url, soup):
if self.is_indexed(url):
return
print('Indexing ' + url)
# Get individual words
text = self.get_text_only(soup)
words = self.seperate_words(text)
# Get the URL ID (add if not exist)
url_id = self.get_entry_id('URL... | This code implements a web crawler that recursively extracts and indexes content from web pages up to a specified depth. It fetches pages, parses HTML with BeautifulSoup, collects links, validates URLs, and stores them in a database while avoiding duplicates. The crawler iterates through pages at each depth level, ensu... | def crawl(self, pages, depth=2):
http = urllib3.PoolManager()
for i in range(depth):
new_pages = set()
for page in pages:
try:
r = http.request('GET', page)
except:
print("Could not get %s" % page)
... |
def find_max_score(score_matrix):
final_points = []
last_row = score_matrix[-1]
last_column = get_column(score_matrix, len(score_matrix[0]) - 1)
max_in_last_row = max(last_row)
max_in_last_column = max(last_column)
max_score = max([max_in_last_row, max_in_last_column])
for j in range(len(la... | This code performs a semi-global alignment of two protein sequences using dynamic programming. It calculates alignment scores and directions for each position in the matrices, selects the maximum score path, backtracks to determine the optimal alignment, and generates the aligned sequences. The process uses a PAM250 sc... | def semi_global_alignment_algorithm(protein1, protein2, score_matrix, direction_matrix):
protein1_arr = list(protein1)
protein2_arr = list(protein2)
for i in range(1, len(score_matrix)):
for j in range(1, len(score_matrix[0])):
char_p1 = protein1_arr[i - 1]
char_p2 = protein... |
def find_order_sequence(seqs):
distance_matrix = calculate_distance_matrix(seqs)
# print(distance_matrix)
new_distance_matrix = np.array(distance_matrix)
sum_rows = new_distance_matrix.sum(axis=1)
center_index = (-sum_rows).argsort()[0]
order_sequences = new_distance_matrix[center_index]
# p... | The code implements the C* algorithm for multiple sequence alignment (MSA). It starts with a central sequence, iteratively aligns each input sequence to the current center using global alignment, updates the MSA with aligned sequences and a new center, and returns the final MSA and center index. | def cstar_algorithm(sequences):
center_index, order_sequences = find_order_sequence(sequences)
MSA = {center_index: sequences[center_index]}
for seq_index in order_sequences:
aligned_seq, new_center_seq, score = global_align(sequences[seq_index], MSA[center_index])
MSA = update_MSA_with_gap... |
def initialize_search_graph(self):
self.vertices.append(self.start)
self.orientations.append((0, 0, 0))
self.edges.append([])
self.parent.append([])
self.tree_size += 1
def random_sample(self):
x = random.randint(self.x_limits[0], self.x_limits[1])
y = random.rand... | The code implements the Rapidly Exploring Random Tree (RRT) algorithm to build a collision-free path toward a goal. It iteratively samples random points, finds the nearest tree node, generates new nodes with random orientations, checks for collisions using a Can object, and updates the tree if collision-free. If the go... | def build_RRT(self):
can = Can(self.fig, self.ax)
self.initialize_search_graph()
while self.tree_size < self.max_tree_size:
sample = self.random_sample()
index, nearest, new_prime = self.find_nearest(sample)
roll = random.randint(0, 90)
pitch = ran... |
def preprocess(desc, questionaire):
desc = translate(desc)
input_text = f"Description: {desc}, Questionaire: {questionaire}"
return input_text
def spam_detection(input_text):
return spam_detector(input_text)[0]['label'] == 'clean'
def sentiment(feedback):
try:
#response = model.generate_cont... | The code classifies input text by first detecting spam. If non-spam, it analyzes sentiment (positive/negative/neutral) and identifies a department. Positive/negative results use zero-shot classification. If spam, it returns a predefined "Spam" response. The main task is text classification into sentiment categories and... | def pipeline(desc, questionaire):
input_text = preprocess(desc, questionaire)
if spam_detection(input_text):
sent = float(sentiment(input_text))
dept = which_department(input_text)
if sent > 0:
return str(sent), positive_zero_shot(input_text), dep... |
def get_new_env_name(env_name, n_sample, env_version):
new_env_name = env_name
if env_version == 1 or env_version == 2:
if "_SP" in env_name and "-v0" in env_name:
n_sample_training = env_name.split("_SP")[1].split("-v0")[0]
n_sample_training = int(n_sample_training)
... | This function evaluates a model's performance on a custom environment, compares it to previous best metrics (average episode return and standard deviation), and saves the model if it outperforms the previous best. It logs results, updates tracked metrics, and leverages logging tools to store the best model state and ev... | def eval_and_save_best_model(
best_eval_AverageEpRet, best_eval_StdEpRet,
eval_logger, train_logger, eval_progress_logger, tb_logger,
epoch, env_name, env_version, env_input,
target_arcs, get_action, render=False, n_sample=5000,
num_episodes=50, seed=0, save_all_eval=False
):
... |
def build_edges():
global edges
edges = {} # edgeid: [(n1,n2), color]
for n1, (_, adjacents, _, _) in enumerate(graph):
for n2 in adjacents:
eid = edge_id(n1, n2)
if eid not in edges:
edges[eid] = [(n1, n2), grey]
def draw_graph():
global graph, screen, ed... | This code implements a Breadth-First Search (BFS) algorithm visualization using Pygame. It initializes a graph with nodes and edges, then performs BFS starting from node 0, dynamically updating node and edge colors to represent discovery (red), processing (yellow), and completion (blue) states. The visualization waits ... | def run():
global screen, edges, clock
# add start colors to graph
for element in graph:
element.extend([grey, black])
build_edges()
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((display_width, display_height))
draw_graph() # initial
update()
... |
def welcome():
message = """
Welcome to Houdini Compare Tool!!
Please select an option:
"""
buttons = ("Create Source", "Select Source", "Cancel")
selection = hou.ui.displayMessage(message, buttons=buttons, close_choice=3)
if selection == 0:
source = create_source()
elif selec... | The main task of the code is to load scene data and JSON data from a file, compare them to identify differences, and mark discrepancies between the two datasets. | def main():
# Load scene data and JSON data
json_file_path = welcome()
scene_data = current()
# Load JSON data from the file path
json_data = get_json(json_file_path)
if json_data:
print(f"JSON data loaded from {json_file_path}")
# Compare scene data with JSON data... |
def get_all_genes(cur):
"""Memory store of gene name/chrom combinations already in db"""
cur.execute('SELECT id, name, chromosome, strand FROM gene;')
return {(name, chrom, strand): gene_id for (gene_id, name, chrom, strand) in cur}
def dataset_exists(name, cur):
cur.execute('SELECT * FROM dataset WHER... | This function imports GTF data into a database, parsing genes, transcripts, and exons. It checks if a dataset with the given name exists, skips duplicates for reference datasets, and inserts new entries. It tracks parsed/inserted counts and prints statistics with elapsed time. | def import_gtf(f, name, is_ref=False):
tic = timer()
cur = _con.cursor()
all_genes = get_all_genes(cur)
parse_count = {'gene': 0, 'tx': 0, 'ex': 0}
insert_count = {'gene': 0, 'tx': 0, 'ex': 0}
if dataset_exists(name, cur):
print('Dataset with that name already exists')
return
... |
def import_gtf(f, name, is_ref=False):
tic = timer()
cur = _con.cursor()
all_genes = get_all_genes(cur)
parse_count = {'gene': 0, 'tx': 0, 'ex': 0}
insert_count = {'gene': 0, 'tx': 0, 'ex': 0}
if dataset_exists(name, cur):
print('Dataset with that name already exists')
return
... | The code populates a database with genomic annotations and expression data by importing GTF files (Isoform_annotations_4281_knownCells.gtf and gencode.v33lift37.annotation.gtf.gz) and expression values from a text file. It processes these files to generate exon models and store reference annotations, likely for bioinfo... | def populate_db(data_dir='data'):
with open(f'{data_dir}/Isoform_annotations_4281_knownCells.gtf') as f:
import_gtf(f, 'final')
with gzip.open(f'{data_dir}/gencode.v33lift37.annotation.gtf.gz', 'rt') as f:
import_gtf(f, 'gencode.v33lift37', is_ref=True)
generate_model_exons()
with ope... |
def get_boot_mac():
"""Return the mac address of the booting interface."""
cmdline = read_file('/proc/cmdline')
cmdline = cmdline.split()
try:
bootif = [
option
for option in cmdline
if option.startswith('BOOTIF')
][0]
except IndexError:
... | The main task of the code is to configure a system's boot environment by validating required inputs (target, fstab, boot interface), writing fstab and GRUB configurations, installing GRUB, applying SELinux relabeling, handling cloud configurations, and setting up networking. It ensures all prerequisites are met before ... | def main():
state = util.load_command_environment()
target = state['target']
if target is None:
print("Target was not provided in the environment.")
sys.exit(1)
fstab = state['fstab']
if fstab is None:
print("/etc/fstab output was not provided in the environment.")
sy... |
def get_parameters():
"""
gets the parameters from cmd and checks if they are valid.
:return: tuple containing the parameters.
"""
num_params = len(sys.argv) - 1 # without program name
k = 0
eps = EPSILON
max_iter = MAX_ITER
input_file_name = ""
goal = None
# get parameters ... | This code processes input data for clustering or matrix computations based on the specified goal. It handles k-means++ with spectral preprocessing (SPK), Jacobi eigen-decomposition for symmetric matrices, and generates specific matrices (WAM, DDG, LNORM). It validates inputs, computes results, and prints centroids or t... | def main():
k, max_iter, eps, goal, input_file_name = get_parameters()
data_points_df = read_input_file(input_file_name)
N = data_points_df.shape[0]
d = data_points_df.shape[1]
data_points = data_points_df.values.tolist() # convert data points to 2D list
# kmeans option
if goal == Goal.SPK... |
def generate_key(self):
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+/,.<>?;:[]{}|\\=-"\'`~'
key = ''
for i in range(0, self.encryption_level):
key += random.choice(chars)
return key
def write_key(self, key):
# TODO: Se... | This code performs a ransomware attack by generating an encryption key, encrypting all files in a directory, displaying ransom demands via alerts, and threatening file deletion if payment isn't made within 24 hours. It uses threading for timed deletion and requires Bitcoin payment for decryption. | def start(self):
self.key = self.generate_key()
self.write_key(self.key)
self.files = self.get_files()
for file in self.files:
self.encrypt(file)
pyautogui.alert('What happened to your files?', 'Axis')
pyautogui.alert('Your files have been encrypted ... |
def _read_stats(st):
# convert 'mode' to something like '0755'
# convert times to ints from floats
return (oct(st.st_mode)[-4:], st.st_size,
int(st.st_mtime), int(st.st_atime))
def _scp_send_time(channel, mtime, atime):
channel.sendall('T{0} 0 {1} 0\n'.format(mtime, atime))
_scp_read_res... | The function sends directory metadata (mode, name, and timestamps if specified) over an SCP channel to prepare for file transfer, then waits for a response to confirm the operation. | def _scp_send_pushd(channel, directory, preserve_times):
(mode, size, mtime, atime) = _read_stats(_os.stat(directory))
basename = _os.path.basename(directory)
if preserve_times:
_scp_send_time(channel, mtime, atime)
channel.sendall('D{0} 0 {1}\n'.format(mode, basename))
_scp_read_response(ch... |
def empty_cell_if_two_in_a_row(player, board):
coordinates_of_empty_cell_in_row = search_rows(player, board)
if coordinates_of_empty_cell_in_row is not None:
return coordinates_of_empty_cell_in_row
coordinates_of_empty_cell_in_column = search_columns(player, board)
if coordinates_of_empty_cell_i... | The function determines the AI's next move in a game by prioritizing: 1) completing a winning line, 2) blocking opponent's win, 3) taking the center, 4) choosing a corner, and 5) selecting a random empty cell if no other options exist. It simulates strategic decision-making in a turn-based game like Tic-Tac-Toe. | def get_ai_move(player, board):
time.sleep(1)
winning_coordinates = empty_cell_if_two_in_a_row(player, board)
if winning_coordinates is not None:
return winning_coordinates
winning_coordinates_2 = empty_cell_if_two_in_a_row_for_enemy(player, board)
if winning_coordinates_2 is not None:
... |
def get_ai_move(player, board):
time.sleep(1)
winning_coordinates = empty_cell_if_two_in_a_row(player, board)
if winning_coordinates is not None:
return winning_coordinates
winning_coordinates_2 = empty_cell_if_two_in_a_row_for_enemy(player, board)
if winning_coordinates_2 is not None:
... | The function `ai_turn` executes the AI's move in a game by selecting a position on the board, marking it with the current player's symbol, and displaying the updated board. It checks if the player has won or if the board is full, then prints the result and terminates the game accordingly. | def ai_turn(player, board):
row_col = get_ai_move(player, board)
mark(board, row_col, player)
print_board(board)
if has_won(board, player):
print_result(player)
exit()
if is_full(board):
print_result()
exit() |
def human_turn(player, board):
row_col = get_move(player, board)
mark(board, row_col, player)
print_board(board)
if has_won(board, player):
print_result(player)
exit()
if is_full(board):
print_result()
exit()
def change_player(player):
if player == 'X':
pl... | This code alternates between human and AI turns in a game, modifying the board each time. It repeatedly calls human_turn and ai_turn functions, switching the current player after each move, until the game concludes. The loop continues indefinitely, relying on the turn functions to handle game-ending conditions like win... | def play_human_vs_ai(player, board):
while True:
human_turn(player, board)
player = change_player(player)
ai_turn(player, board)
player = change_player(player) |
def ai_turn(player, board):
row_col = get_ai_move(player, board)
mark(board, row_col, player)
print_board(board)
if has_won(board, player):
print_result(player)
exit()
if is_full(board):
print_result()
exit()
def change_player(player):
if player == 'X':
pl... | The code alternates between AI and human turns on a board. It repeatedly calls `ai_turn`, switches the player, then `human_turn`, and switches again, creating an infinite loop for turn-based gameplay. | def play_ai_vs_human(player, board):
while True:
ai_turn(player, board)
player = change_player(player)
human_turn(player, board)
player = change_player(player) |
def n_m_function(file):
n,m = file[:-4].split("_")
return int(n), int(m)
def prop_calc(n,m):
dr = dr_calc(n, m)
if sys.argv[1] == "C":
r = 1.418 / 10
circumference = (np.sqrt(3) * r * np.sqrt((n**2 + m**2 + n*m)))
diameter = circumference / np.pi
radius = dia... | The main task of the code is to process files in a directory based on a command-line argument ("C" or "BN"), calculate nanotube properties (diameter, radius, unit cell parameters), and save results as CSV files. It reads input files, computes values using helper functions, and writes structured data to output CSVs with... | def main():
try:
if sys.argv[1] == "C":
path = "path/SWNT_xyz/CNT/"
output_path = "path/SWNT_xyz/CNT/data/"
elif sys.argv[1] == "BN":
path = "path/SWNT_xyz/BNNT/"
output_path = "path/SWNT_xyz/BNNT/data/"
except IndexError:
print("Enter comm... |
def get_filename(full_filepath: str) -> str:
return os.path.splitext(os.path.split(full_filepath)[-1])[0]
def load_n_preprocess(filename: str) -> Tuple[np.ndarray, int]:
y, fs = torchaudio.load(filename)
return preprocess(y.numpy(), fs)
def remove_silence(
y: np.ndarray, c: List[Tuple[int, int]], margin... | The main task of the code is to split an audio file into segments, optionally removing silence and applying a low-frequency cut, then saving each segment as a separate WAV file in the specified output folder. | def split_single_file_no_caption(
full_filepath: str,
output_folder: str,
should_remove_silence: bool = False,
low_cut_freq: Optional[int] = None,
):
filename = get_filename(full_filepath)
y, fs = load_n_preprocess(full_filepath)
if should_remove_silence:
y = remove_silence(y, get_cl... |
def get_filename(full_filepath: str) -> str:
return os.path.splitext(os.path.split(full_filepath)[-1])[0]
def load_n_preprocess(filename: str) -> Tuple[np.ndarray, int]:
y, fs = torchaudio.load(filename)
return preprocess(y.numpy(), fs)
def remove_silence(
y: np.ndarray, c: List[Tuple[int, int]], margin... | The code splits an audio file into segments, removes silence if specified, and generates Chinese captions using an ASR model. It saves each audio segment as a WAV file in the output folder and writes a corresponding list file containing the file path, caption, language code, and recognized text. The task involves audio... | def split_single_file_with_caption(
generate_caption_for: str,
full_filepath: str,
output_folder: str,
should_remove_silence: bool = False,
low_cut_freq: Optional[int] = None,
):
filename = get_filename(full_filepath)
y, fs = load_n_preprocess(full_filepath)
if should_remove_silence:
... |
def _get_next_line(self) -> t.Union[str, bytes]:
curr_offset = self._filehandle().tell()
line = self._filehandle().readline(MAX_LINE_SIZE)
if self._full_lines:
if self.binary and not line.endswith(self.new_line or os.linesep):
self._filehandle().seek(curr_offset)
... | This function retrieves the next line from a file, handling end-of-file scenarios and log rotation. It updates the offset based on the configured mode ('paranoid', 'every', or 'endfile'), closes and reopens files when rotated, and ensures proper offset tracking for continued reading. | def next(self):
"""
Return the next line in the file, updating the offset.
"""
try:
line = self._get_next_line()
except StopIteration:
# we've reached the end of the file; if we're processing the
# rotated log file or the file has been renamed,... |
def _segments_from_variant_playlists(self, m3u8_file: m3u8.M3U8, baseurl: Union[str, None]) -> None:
print("m3u8 playlists listed inside m3u8 file:")
resolution_bandwidth_sum = []
for i, m3u8_playlists in enumerate(m3u8_file.data["playlists"]):
total_digit_sum = 0
... | This method parses m3u8 content from a given URL, extracts segment lists, handles variant playlists by calling internal methods, processes media playlists for audio/subtitle streams, and returns the resulting segments. It uses headers/http client for fetching, manages exceptions, and separates main content from additio... | def parse_m3u8(self, parsed_links: Tuple[str, str]) -> m3u8.SegmentList:
"""parse m3u8 segments from parsed links
Args:
parsed_links (Tuple[str, str]): [description]
Returns:
m3u8.SegmentList: segments object
Note:
for seperate audio and sub... |
def readSeats():
with open("data.txt", 'r') as f:
return f.read().splitlines()
def part1(seats):
maxVal = 0
for seat in seats:
seatID = getSeatID(seat)
if seatID > maxVal:
maxVal = seatID
return maxVal
def part2(seats):
unseen = list(range(part1(seats) + 1))
... | The main task of the code is to read seating data, compute results for two parts of a problem using the seat information, and print the outcomes. The `main()` function orchestrates this workflow by calling `readSeats()` to load data, then executing `part1()` and `part2()` with the seats as input, finally displaying the... | def main():
seats = readSeats()
print(f"Part 1: {part1(seats)}\nPart 2: {part2(seats)}") |
def download_list(url):
http = urlopen(url)
# TODO: error handling
charset = http.headers.get_content_charset()
if charset is None:
charset = 'utf-8' # Best guess
items = set()
for line in http:
line = line.rstrip()
m = re.match(CIDR_REGEX, line.decode(charset))
i... | The main task of the code is to update IP sets in iptables by iterating through provided ipsets, downloading each associated list, creating an ipset with a configured prefix and key, and adding corresponding iptables rules. It dynamically configures network filtering rules based on external lists and structured naming ... | def update_ipsets(ipsets):
for k, v in ipsets.items():
blacklist = download_list(v)
prefix = conf['ipset']['prefix']
set_ipset(f'{prefix}.{k}', blacklist)
iptables_rule_add(k) |
def process_ports_db(url):
db = download_ports_db(url)
ports = dict()
for p in {i['protocol'] for i in db}:
ports[p] = [i for i in db if i['protocol'] == p]
ports[p].sort(key = lambda i: i['frequency'], reverse = True)
return ports
def create_ipsets():
prefix = conf['reactive']['ipse... | The main task of the code is to configure firewall rules using iptables by downloading and processing common port data, creating ipsets, updating TCP/UDP port rules, and adding iptables rules to match/block traffic based on the processed data. | def setup():
# Download and process data on common ports
db = process_ports_db(conf['reactive']['nmap-services_url'])
# Create and populate the ipsets
create_ipsets()
update_ports('tcp', db)
update_ports('udp', db)
# Create the iptables rules to match & block
iptables_add_rules() |
def getIncrementTimestamps():
path = maya.cmds.file(q=True, sn=True)
if not path:
return {}
basename = os.path.splitext(os.path.basename(path))[0]
folder = incrementalSaveDir()
if not os.path.exists(folder):
return {}
return { int(incNumberRE.search(f).... | The function `printRecentNotes` retrieves and displays the last three incremental notes from a script editor, along with their timestamps. It checks for existing notes, prints each note's content and associated time, and outputs the file's last modified time. If no notes exist, it informs the user. | def printRecentNotes(oldest=-3):
''' Shows the last three notes in the script editor.
'''
timestamps = getIncrementTimestamps()
notes = getOrderedNotes(oldest)
if not notes:
print('No incremental notes have been made for this file')
return
for key, val in notes.ite... |
def weight_convert(self, base_threshold=400):
""" Weights the option for ship conversion """
# Calculating the threshhold
threshold = base_threshold + 1000 * (len(self.player.shipyards) // 3)
# 1. If they are no shipyards left
no_shipyards = len(self.player.shipyards) == 0
... | The function `weight_moves` evaluates and assigns weights to potential moves in a game, considering ships, shipyards, and halite distribution. It prioritizes defending shipyards, distributing or attacking enemy ships, and encourages movement based on halite values. Mining weights are adjusted by comparing cell halite l... | def weight_moves(self):
""" This is the main function and runs other helper functions within the module to to weight the different moves that could be taken. """
# Weight the CONVERT option
self.weight_convert()
# See if any of the shipyards need defending
self.shipyard... |
def weight_convert(self, base_threshold=600):
""" Weights the option for ship conversion. """
# Calculating the threshhold
threshold = base_threshold + 1000 * (len(self.player.shipyards) // 3)
# 1. If they are no shipyards left
no_shipyards = len(self.player.shipyards) =... | The main task of the code is to evaluate and weight potential moves for a ship in a game, considering factors like proximity to ships, shipyards, halite resources, and strategic priorities. It avoids collisions, handles enemy threats, encourages resource collection, and adjusts move priorities using weighted values der... | def weight_moves(self):
"""
This is the main function and runs other helper functions within the module to to weight the different moves that could be taken.
The weightings will take numerous considerations into account (halite, closeness to shipyard, etc.) yet there are going to be
... |
def weight_moves(self):
""" This is the main function and runs other helper functions within the module to to weight the different moves that could be taken. """
# Weight the CONVERT option
self.weight_convert()
# See if any of the shipyards need defending
self.shipyard... | The code determines the next action for a ship by calculating directional weights, applying eliminations, sorting them, and selecting the highest-weighted non-eliminated action. If none qualify, it defaults to mining. Your return | def determine(self):
""" Returns next action decided for the ship based on the observations that have been made. """
self.weight_moves() # Calculate the weights for main four directions
self.round() # Round the weights
self.apply_elimination() # Apply the eliminations
# Sort ... |
def weight_moves(self):
"""
This is the main function and runs other helper functions within the module to to weight the different moves that could be taken.
The weightings will take numerous considerations into account (halite, closeness to shipyard, etc.) yet there are going to be
... | The code determines the next action for a ship by calculating and prioritizing movement directions based on weighted values. It rounds weights, applies eliminations, sorts valid actions by priority, and selects the highest-weighted non-eliminated action. If no valid actions remain, it defaults to mining. | def determine(self):
""" Returns next action decided for the ship based on the observations that have been made. """
self.weight_moves() # Calculate the weights for main four directions
self.round() # Round the weights
self.apply_elimination() # Apply the eliminations
# Sort ... |
def requestDirectory(self, dirNodeIP, dirNodePort):
# connect to the directory node
self.directorySocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
try:
self.directorySocket.connect((dirNodeIP, dirNodePort))
except:
if self.debug:
... | The code establishes a secure communication chain by connecting to a directory node, selecting a subset of nodes, setting up a chain of encrypted connections between them, negotiating keys, and transmitting encrypted messages through the established tunnel. It handles node selection, connection establishment, key negot... | def run(self, dirNodeIP, dirNodePort, n):
# get the directory from the directory node
directory = self.requestDirectory(dirNodeIP, dirNodePort)
if n > len(directory):
print(
"Number of nodes requested is greater than the number of nodes in the directory")
... |
def opState0(variabel):
if (isVariable(variabel) or isNumber(variabel)):
state = 1
elif(variabel == "++" or variabel =="--"):
state = 9
else:
state = 100
return state
def opState1(variabel):
if (variabel == "=" or variabel == ">" or variabel == "<" or variabel == "=... | This function processes an operator string by splitting it into tokens and sequentially applying state transition functions (opState0 to opState9) to each token. It tracks state changes in a list, checks for terminal states (3, 6, 7), and returns True if any of these are reached, or False if an invalid state (100) is e... | def checkOperator(operator):
operatorlist = operator.split()
state = 0
listState = []
for i in range(len(operatorlist)):
if (state == 0):
state = opState0(operatorlist[i])
print(state)
listState.append(state)
elif (state == 1):
state = opSt... |
def _get_obs(self):
return {"agent": self._agent_location, "target": self._target_location}
def _get_info(self):
return {
"current_state": self.current_state,
"next_state": self.next_state,
"current_location": self._current_location,
"next_location": self.... | This code resets the environment by initializing the agent's position to the bottom-left corner, setting the target to the top-right corner, and preparing the initial state for a new episode. It seeds the random number generator, updates the agent's path, and returns the observation and environment information. | def reset(self, seed=None, options=None):
# We need the following line to seed self.np_random
super().reset(seed=seed)
self._path = []
# We reset the agent to the bottom left corner
self._agent_location = np.array([0, 0, 0])
self.current_state = self._agent_location[0] ... |
def get_reward(self, action):
direction = self._action_to_direction[action]
reward = 0
for obstacle in self._obstacles:
if np.array_equal(self._agent_location, obstacle):
return True, -20, False
elif np.linalg.norm(
self._agent_location - o... | The code implements a step function for an environment where an agent moves in a grid based on an action. It maps the action to a direction, checks if the agent has reached the target (terminating the episode), updates the agent's position with boundary clipping, computes the next state, tracks the path, and returns th... | def step(self, action):
# Map the action (element of {0,1,2,3,4}) to the direction we walk in
direction = self._action_to_direction[action]
# We use `np.clip` to make sure we don't leave the grid
# An episode is done iff the agent has reached the target
terminated, reward, reach... |
def get_terms(active_only=True):
url = 'https://app.testudo.umd.edu/soc/'
r = www.get(url)
terms = []
for e in r.html.find('#term-id-input option'):
terms.append(e.attrs['value'])
return terms
def get_departments():
url = 'https://app.testudo.umd.edu/soc/'
r = www.get(url)
depts ... | The code's main task is to fetch course data for each term and department, then save each course as a JSON file in a structured directory hierarchy under 'data'. It iterates through terms, departments, and courses, creating necessary directories and writing formatted JSON files with course details. | def main():
for term in get_terms():
print("getting term %s" % term)
for dept in get_departments():
print("getting courses in %s for %s" % (term, dept['id']))
for course in get_courses(dept, term):
json_file = os.path.join('data', term, dept['id'], course['id'... |
def mainMenuRun(self): # Running the main menu and adding functions for all it's buttons.
self.mainMenu.run()
if self.mainMenu.playButton.clicked:
self.gameState = 'mainGame'
if self.mainMenu.optionsButton.clicked:
self.gameState = "settingsMenu"
if self.mainMenu.quitButton.clicked:
self.runnin... | The code manages a game loop that handles different game states (main menu, settings, main game) by updating the screen, processing events, and maintaining a 60 FPS frame rate. It checks for quit events, clears the screen, and executes state-specific functions before rendering the display. | def run(self): # Handing all the different game states.
while self.running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
self.screen.fill('#000000')
if self.gameState == 'mainMenu':
self.mainMenuRun()
if self.gameState == "settingsMenu":
self.optionsMenu... |
def get_continents_names(text=None):
"""
Parameters
----------
text :
(Default value = None)
Returns
-------
"""
if text is None:
text = get_eval_text()
gc = geonamescache.GeonamesCache()
continent = gc.get_continents()
continent_keys = list(continent.key... | The function adds geographic information (continent, country, city) to a DataFrame by extracting matching terms from the 'Evaluation Statement' column using predefined lists. It reads data from an Excel file if none is provided, processes text to identify geographic terms, appends new columns with these terms, and save... | def add_geo_info_to_df(data=None):
"""
Parameters
----------
data :
(Default value = None)
Returns
-------
"""
if data is None:
data = pd.read_excel(file_path, engine='openpyxl')
data.dropna(axis=0, subset=['Evaluation Statement'], inplace=True)
continent... |
def load_categories(display: bool = False):
"""
Load the categories from the config file
"""
global categories
global page_order
categories = {}
debug(f'loading categories from {app_options.categories_path}')
table = Table('Page', 'Category', 'Patterns')
with open(app_options.categ... | The code processes financial statements to extract and filter expenses. It loads categories, processes the provided statement (or all statements if none is given), sorts expenses and non-spendable funds (NSFs) by date, applies filters to remove visa debit corrections and NSF entries, then returns the cleaned list of ex... | def get_expenses(statement: str):
"""
Get the expenses for the given statement(s)
"""
load_categories()
if len(statement) == 0:
statement_expenses, statement_nsfs = process_statements()
else:
path_item = pathlib.Path(statement)
statement_expenses, statement_nsfs = proce... |
def display_report(report_data):
"""
Display the generated report
"""
monthly_pages = [
'Housing and Utilities',
]
totals = {}
table = Table(
'Year',
'Page',
'Category',
'Vendor',
'Date',
Column(header='Amount', justify='right'),
... | The code defines a `report` function that generates and displays a report based on input statement files. It retrieves expenses using `get_expenses`, processes them into a report with `generate_report`, and displays the result via `display_report`, fulfilling the task of creating and presenting financial or data report... | def report(statement: str = ''):
"""
Generate a report for the given statement files
"""
display_report(
generate_report(
get_expenses(statement)
)
) |
def export_report(report_data):
"""
Export the generated report to excel
"""
global page_order
monthly_pages = [
'Housing and Utilities',
]
month_names = [calendar.month_abbr[m] for m in range(1, 13)]
totals = {}
for year, pages in report_data.items():
workbook = ... | The code's main task is to export a report by processing a given statement. It retrieves expenses using `get_expenses(statement)`, generates a report with `generate_report()`, and then exports the final report via `export_report()`, facilitating data analysis or documentation workflows. | def export(statement: str = ''):
"""
Export a report for the given statement files
"""
export_report(
generate_report(
get_expenses(statement)
)
) |
def get_product_id(listing_id: str) -> str:
return base64.b64encode(bytes(f'StayListing:{listing_id}', 'utf-8')).decode('utf-8')
def get_raw_listing(self, listing_id: str) -> dict:
url = self.__get_url(listing_id)
return self._api_request(url)
def __parse_listing_contents(self, data: dict, listi... | The function retrieves and processes listing data by fetching raw information, parsing it with cached data, geography, and reviews, then enriching the result with the product ID, source identifier, and current timestamp for tracking updates. | def get_listing(self, listing_id: str, data_cache: dict, geography: dict, reviews: dict) -> dict:
product_id = self.get_product_id(listing_id)
response = self.get_raw_listing(listing_id)
return self.__parse_listing_contents(response, data_cache[listing_id], geography, reviews) | {
'p... |
def get_file_size(file):
file.seek(0, os.SEEK_END)
file_size = file.tell()
file.seek(0)
return file_size
def displayPDF(file):
# Opening file from file path
with open(file, "rb") as f:
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
# Embedding PDF in HTML
pdf_display = ... | The main task of the code is to create a Streamlit web application that allows users to upload a PDF file, process its content into embeddings, and interactively chat with the PDF's content. It displays file details, previews the PDF, generates embeddings, and enables users to ask questions about the document, with res... | def main():
st.markdown("<h1 style='text-align: center; color: blue;'>Chat with your PDF 🦜📄 </h1>", unsafe_allow_html=True)
st.markdown("<h3 style='text-align: center; color: grey;'>Built by <a href='https://github.com/AIAnytime'>AI Anytime with ❤️ </a></h3>", unsafe_allow_html=True)
st.markdown("<h2 sty... |
def valid_permutation(perm: IntegerPermutation) -> bool:
"""
Return true if ``perm`` represents a valid arrangement of the 15 puzzle.
:param perm: A permutation that maps each position to the tile occupying it.
:type perm: IntegerPermutation
"""
return all(k < 17 and k > 0 for k in perm.unfixed... | This code implements an interactive game for the fifteen puzzle, allowing users to scramble pieces, display permutations, and make moves (U/D/L/R). It validates input, updates the puzzle state, and provides feedback on each move while maintaining the game's current configuration and display settings. | def play_puzzle(arrangement: IntegerPermutation | None = None) -> None:
"""Present iteractive game."""
if arrangement is not None and not valid_permutation(arrangement):
raise ValueError(
"Permutation does not represent a valid arrangement of the fifteen puzzle."
)
if arrangement... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.