dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def angle_in_range(angle):
"""Return the angle in the range [-pi, pi].
This range is preferred to center the jets around (0,0).
Parameters
----------
angle : float
Angle in radians.
Returns
-------
angle : float
Angle in radians in the range [-pi, pi].
"""
retu... | The code computes the Jet Rotational Metric (JRM), which quantifies the deviation of a jet's structure from an ideal $ n $-fold symmetric reference jet. It processes input jet data (pT, η, φ), centers the jet, calculates constituent radii, and constructs a symmetric reference jet. The metric is derived by minimizing th... | def JRM(jet, n, kappa=1, beta=1, jet_radius=1, optimizer='L-BFGS-B', opt_restarts=5, return_angle=False):
"""Jet Rotational Metric (JRM) computation.
Parameters
----------
jet : array-like
Jet as an array with columns (pt, eta, phi).
n : int
n-foldedness of the rotational symmetry o... |
def _sorted_checkpoints(args, checkpoint_prefix="checkpoint", use_mtime=False) -> List[str]:
ordering_and_checkpoint_path = []
glob_checkpoints = glob.glob(os.path.join(args.output_dir, "{}-*".format(checkpoint_prefix)))
for path in glob_checkpoints:
if use_mtime:
ordering_and_checkpoi... | The main task of this code is to train or fine-tune a language model (e.g., BERT, RoBERTa) using specified training data, hyperparameters, and configurations. It handles model initialization, distributed training setup, data loading, training loop with masked language modeling (MLM) or standard language modeling, evalu... | def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--train_data_file", default=None, type=str, required=True, help="The input training data file (a text file)."
)
parser.add_argument(
"--stage", default=None, type=str, required=True, help="The... |
def usage(argv):
xcopyright(argv)
nam = argv[0].rfind('/') + 1
name = argv[0][nam:]
print("""
Usage: """+name+""" [-s] <yahoo_web_mail> <output_file>
<yahoo_web_mail>: web mail sent or received
<output_file>: file in mwmail (manipulator) format
-s : if set the email is sent... | The code processes command-line arguments for a Yahoo-related script. It handles options `-h` (display help) and `-s` (send data), validating argument counts. If `-s` is used, it calls `yahoo_sent()` with two arguments; otherwise, it calls `yahoo_received()` after verifying two arguments are provided. | def yahoo_main(argv):
try:
opts, args = getopt.getopt(argv, "sh")
except getopt.GetoptError:
usage(sys.argv)
sys.exit(2)
# process options
for o, a in opts:
# help
if o in ("-h"):
usage(sys.argv)
sys.exit(0)
# sent
if o... |
def getObjectColorHSV(image):
palette = getPalette(image)
vals = []
cols = []
cols_r = []
for i in palette.keys():
vals.append(palette[i])
cols_r.append(i)
cols.append('#%02x%02x%02x' % i[::-1])
plot_vals = np.array(vals)
plot_cols = np.array(cols)
carcolor = co... | The code processes an uploaded car image by extracting features like color (HSV), resolution, and sharpness. It saves the image, reads it with OpenCV, computes HSV color values, image resolution, and sharpness score, then stores these parameters in a list for prediction tasks. | def car_image():
path = ""
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
return "No file found"
user_file = request.files['file']
temp = request.files['file']
if user_file.filename == "":
... |
def get_used_materials():
# Fetch all Orders_used objects
orders_used = Orders_used.objects.all()
# Get unique order_ids
unique_order_ids = set(order.order_id_id for order in orders_used)
# For each unique order_id, get all related schedule_ids
order_schedule_mapping = {}
for order_id in uni... | This code gathers and processes multiple data models (suppliers, materials, BOMs, orders, stocktake records, panels) from a Django database. It transforms, annotates, and aggregates data (e.g., adding supplier names, calculating wastage-adjusted quantities, grouping by material IDs), then compiles all processed data in... | def home(request):
suppliers = Suppliers.objects.all().values()
materials = Materials.objects.all().annotate(supplier_name=F('supplier_id__name')).values()
bom = Bom.objects.all().values()
orders = Orders.objects.select_related('supplier_id').values('order_id', 'datestamp', 'order_status', 'supplier_id_... |
def get_user_name() -> str:
"""Prompt the user for the username."""
client_username = input("Please give yourself an awsome username:")
while not client_username.isalnum():
print("Error: Please enter an alphanumeric username with no special characters\n")
client_username = input("Please give... | The code connects a client to a server by repeatedly prompting for host and port until successful. It sends the client's username, receives the server's username, initializes a game board, and executes game functions before closing the connection. | def run_client() -> None:
"""Run the client's code."""
while True:
try:
host_address = input("Please enter host:\n")
host_port = int(input("Please enter port:\n"))
print("Establishing Connection to server (HOST: {}, Port: {}".format(host_address, host_port))
... |
def make_data(self):
"""With this method i can easliy loop over the data to find regex patterns"""
with open('worklog.csv', 'r') as csv_file:
self.reader = csv.DictReader(csv_file, delimiter='\t')
names_file = open("worklog.csv")
next(names_file)
data = na... | This method repeatedly prompts the user for a regex pattern, validates it against data generated by self.make_data(), and either proceeds with the pattern or triggers an error handler if no match is found, ensuring a valid regex is used for filtering. | def match_filter(self):
"""This method tests if the entry of the regex contains a match"""
while True:
self.pattern_search = input(r"Enter your regex pattern: ")
if re.findall(self.pattern_search, self.make_data()) and self.pattern_search != "":
self.no_pattern_fi... |
def _open_file(self) -> None:
with open(self._in_filename, "rt", encoding="utf-8") as fp:
self._content = fp.read()
def _translate_contents(self) -> None:
self._remove_conflicting_elements()
soup = translate_html(self._translation_obj, self._content)
# Why!?
soup = BeautifulSoup(str(soup), "ht... | The main task of the code is to translate the contents of a specified input file and save the translated result to an output file (or override the input file if no output is specified). It handles file reading, translation processing, and writing operations, raising an OSError if file operations fail. | def translate(self, in_filename: str, out_filename: str = None) -> None:
"""Translates a file
Check out the caveats in the docstring for this class!
Args:
in_filename: The name of the file to translate.
out_filename: The name of the file to write. If unspecified,
default behavior... |
def get_production_order_number_items(filename):
'''
returns number of items in a production order table/file
'''
return len(get_production_order(filename).index)
def get_production_order_item_id(filename,index):
'''
returns a order id from a production order table/file
'''
return get_... | This function loads data from a production order file into a production buffer by extracting and processing specific fields (product ID, reference, type, quantity, service, priority, and calculated production time) for each item. It converts certain values to scalar integers using np.asscalar and appends them as a list... | def load_production_order_into_production_buffer(filename, production_buffer):
'''
loads/appends a production order file into a production buffer list of lists
np.asscalar is used on integer's due to data formats required to handle API process
'''
for item in range(get_production_order_number_items... |
def area(self):
return cv2.contourArea(self.contour)
def center_point(self):
m = self.moments()
x = int(m["m10"] / m["m00"]) if m["m00"] != 0 else 0
y = int(m["m01"] / m["m00"]) if m["m00"] != 0 else 0
return (x, y)
def angle_from_vertical(self):
points = self.rotated_rec... | The code generates a formatted report as a list of strings, detailing properties of a vision target. It includes area, moments, center coordinates, rotation angle, rotated rectangle dimensions/points, and potential left target status. The report is structured with labeled entries for each attribute, enclosed in delimit... | def report(self):
lines = []
lines.append("-------VISION TARGET--------")
lines.append("Area: {}".format(self.area()))
lines.append("Moments: {}".format(self.moments))
lines.append("Center (from moments): {}".format(self.center_point()))
lines.append("Rotation from vertic... |
def fuzzer(self, url):
data = []
dangerous_characters = [
">",
"'",
'"',
"<",
"/",
";"
]
parameters = self.parameters(url)
print(f"[+] {len(parameters)} parameters identified")
for parameter in parame... | This code scans a URL for vulnerabilities by testing payloads against parameters. It fuzzes the URL, filters payloads, sends requests with each payload, checks if the payload appears in the response, and reports vulnerabilities if detected. If no vulnerabilities are found, it returns None. | def scanner(self,url):
#vulnerable_links = []
out = self.fuzzer(url)
# print(out)
for data in out:
for key in data:
payload_list = self.filter_payload(data[key])
#print(f"[+] TESTING THE BELOW PAYLOADS {payload_list}")
for payload in... |
def train_generator(self, train_loader, dev_loader):
best_bleu = 0
best_epoch = 0
# self.load_pretrain_generator(epoch=1, save_dir=self.args.model_dir)
for epoch in range(self.args.generator_pretrain_epoch):
self.pretrain_generator(dataloader=train_loader, epoch=epoch,
... | This code trains a generator and discriminator in a GAN-like framework. It first trains the generator using a loader, then conditionally trains the discriminator if 'ctype' is 'discriminator'. Over 100 epochs, it trains the generator with policy gradient, evaluates it using BLEU-4 scores, and updates the best model if ... | def train(self, train_loader, dev_loader):
# print(self.args.ctype)
self.train_generator(train_loader, dev_loader)
if self.args.ctype != 'discriminator':
return
self.train_discriminator()
best_epoch = -1
best_bleu4 = -1
for epoch in range(100):
... |
def intro(self):
print('INTRO (' + self.directory + ')')
self.play('intro')
while (self.chance(12)):
self.play('intro')
def meat(self):
print('MEAT (' + self.directory + ')')
self.play('meat')
while (self.chance(50)):
while (self.chance(25)): self.... | The code defines a `talk` method that sequentially executes three sub-methods: `intro` (introduction), `meat` (core content), and `outro` (conclusion). Its main task is to structure and deliver a cohesive process or dialogue by organizing these components in order, likely for a presentation, interaction, or procedural ... | def talk(self):
self.intro()
self.meat()
self.outro() |
def transform(self, vertex, translate=(0, 0, 0), scale=(1, 1, 1)):
# returns a vertex 3, translated and transformed
return V3(
round((vertex[0] + translate[0]) * scale[0]),
round((vertex[1] + translate[1]) * scale[1]),
round((vertex[2] + translate[2]) * scale[2])
)
def norm(v0):
v0lengt... | This code loads a 3D model from an OBJ file, applies translation/scale transformations, calculates face normals and lighting intensity based on a light source, and renders each face as triangles with either grayscale shading or texture mapping, depending on the input parameters. | def load(self, filename, translate=(0, 0, 0), scale=(1, 1, 1), texture=None):
model = Obj(filename)
light = V3(0,0,1)
for face in model.vfaces:
vcount = len(face)
if vcount == 3:
f1 = face[0][0] - 1
f2 = face[1][0] - 1
f3 = face[2][0] - 1
a = self.... |
def _find_scenario(self, parameter_type):
scenario_parameter = []
for first in self.scenario[parameter_type].keys():
if 'scenario' in list(self.scenario[parameter_type][first].keys()):
scenario_parameter.append([first, list(self.scenario[parameter_type][first]['scenario'])])
... | The main task of the code is to execute predefined scenarios by checking market, contract, and simulation parameters. It identifies each scenario type using `_find_scenario`, iterates through them, and triggers corresponding methods like `_run_market_scenario` and `_run_simulation_scenario`. The calculation scenario is... | def run_scenarios(self):
# check each of market, contract, calculation, and simulation parameters for scenarios
# check market scenarios
market_scenarios = self._find_scenario('market')
for ms in market_scenarios:
self._run_market_scenario(ms)
... |
def parse_inst(filename, lines, concrete, abstract = 'j1'):
INST_REGEX = mk_inst_regex(abstract, concrete)
result = []
matching = False
for line in lines:
if not(matching):
if re.match(INST_REGEX, line):
line = abstract
matching = True
else:
if not(line.startswith(INDENT_STR)... | The main task of the code is to process multiple instance files in a directory by parsing their contents, extracting settings, applying post-processing, and saving the results. It iterates over files matching a specific pattern, reads each file, parses its data, generates settings, and writes them to output files. Debu... | def main(args):
total = 0
for filename in os.listdir(INSTANCES_DIR):
filepath = os.path.join(INSTANCES_DIR, filename)
match = re.match(INSTANCE_FILE, filename)
if os.path.isfile(filepath) and match:
number = int(match.group('number'))
with open(filepath) as file:
lines = file.readlin... |
def plot_data(file, title, show_essentials=True):
"""
Uses plotly to make pretty graphics and opens in a web browser: https://plot.ly/python/plot-data-from-csv/
Defaults to color based on sold/not sold
"""
csv = pd.read_csv(file)
csv = csv.fillna(0)
hover_data = []
if show_essentials:
... | The main task of the code is to parse and analyze BaT price trend data from a webpage or CSV file, converting it into a structured DataFrame. It extracts listing details, processes timestamps, categorizes sold/not sold items, and outputs sorted CSV files with optional visualization. The script supports URL-based data f... | def main():
parser = ArgumentParser(description='BaT price trend')
action = parser.add_mutually_exclusive_group(required=True)
action.add_argument('-u', type=str, dest='url', help="full url to page with information")
action.add_argument('-p', type=str, dest='csv_file', help="only plot the provided csv f... |
def count_cross():
return sum([cube[3,4][0]=="D",cube[4,3][0]=="D",cube[4,5][0]=="D",cube[5,4][0]=="D"] )
def do_rotations(cc):
for c in cc:
rotate(c)
def is_L_shape():
return ((cube[3,4][0]=="D")+(cube[4,5][0]=="D"))==2 or\
((cube[4,5][0]=="D")+(cube[5,4][0]=="D"))==2 or\
... | The main task of the code is to solve the top cross of a Rubik's Cube by identifying its current state (0, 2, or 4 cross pieces) and applying rotation sequences. It uses conditional checks for L-shape or line patterns, adjusts them, and rotates the cube to complete the cross. The loop continues until four cross pieces ... | def top_cross():
f=["F","L","D","L'","D'","F'"]
while count_cross()!=4:
if count_cross()==0:
do_rotations(f*3)
if count_cross()!=2:
do_rotations(f*2)
elif count_cross()==2 :
if is_L_shape():
make_L_shape_correct()
... |
def make_d2_correct():
d2=np.where(cube=='D2')
y,x=d2[0][0],d2[1][0]
if (y,x)==(3,4):
pass
elif (y,x)==(4,3):
do_rotations(["D",])
elif (y,x)==(5,4):
do_rotations(["D'","D'"])
else:
do_rotations(["D'"])
def count_D_corrected():
return sum([
cube[3,4]=... | The code's main task is to correct the last four edges of the D face of a Rubik's cube by applying specific rotation sequences. It uses conditional checks on the current state of the cube and a counter (`count_D_corrected()`) to determine which rotation patterns (involving moves like "L", "D", "D'", etc.) to execute. T... | def swap_last_edges():
f=["L","D","L'","D","L","D","D","L'","D"]
make_d2_correct()
while count_D_corrected()!=4:
c=count_D_corrected()
c==1 and cube[4,5]=="D8" and do_rotations(f+["D"]+f+["D'"])#2 6 8 4
c==1 and cube[4,5]=="D4" and do_rotations(["D"]+f+["D'"]+f)#2 8 4 6
c==... |
def count_correct_corners():
return sum([
cube[3,3] in ["D1","B7","R9"],
cube[3,5] in ["D3","B9","L7"],
cube[5,3] in ["D7","F9","R7"],
cube[5,5] in ["D9","F7","L9"]
])
def do_rotations(cc):
for c in cc:
rotate(c)
def detect_turn_good_corner():
if cube[3,3] in ["D1... | This code solves a Rubik's Cube's last layer corners by first rotating until four corners are correct, then aligning remaining corners via sequential D/L/U rotations. It checks specific cube positions (e.g., cube[3,3]) and applies rotation sequences to fix each corner's orientation, ensuring all four final corners matc... | def swap_corners():
while count_correct_corners()!=4:
if count_correct_corners()==0:
do_rotations(["D","L","D'","R'","D","L'","D'","R"])
elif count_correct_corners()==1:
detect_turn_good_corner()
while cube[3,3]!="D1":
do_rotations(["D","D"])
do_rota... |
def get_json_of_one_google_file(self, gfile: str = None):
# gfile == Google Drive file/folder ID
# For example:
# https://drive.google.com/drive/folders/16mbbT12343ypAs81234sGyO3u9fgHkkp
service = self.drive_service.service
if not gfile and isinstance(gfile, str):
lo... | The main task of the code is to generate a comprehensive JSON structure containing all relevant information about Google Drive files and folders starting from a specified parent ID. It recursively collects child files/folders, validates the data, logs details, and saves the final JSON file to disk for potential use in ... | def create_full_json(self, parent_id: str = None):
"""Creates a full_json JSON file and saves to disk.
Creating a full_json file should be done as r
Parameters
----------
Returns
-------
list
A list in JSON syntax. Content is all relevant information... |
def get_json_of_one_google_file(self, gfile: str = None):
# gfile == Google Drive file/folder ID
# For example:
# https://drive.google.com/drive/folders/16mbbT12343ypAs81234sGyO3u9fgHkkp
service = self.drive_service.service
if not gfile and isinstance(gfile, str):
lo... | The main task of the code is to build a dictionary of all files and folders under a root ID by recursively retrieving their metadata, validating the root JSON, and saving the structured data as JSON files for permission management. It initializes a parent ID dictionary, populates it with file/folder details, removes a ... | def create_parent_dict(self):
"""Creates a list of parent IDs which then can be used to create full_jsons and revoke
permissions."""
logging.info("### Creating parent_id list")
logging.info("Retrieving root folder as JSON")
root_json = [self.get_json_of_one_google_file(self.conf... |
def parts_by_name_and_cat():
parts_dict = {}
by_category = {}
df = parts_df()
for _, row in df.iterrows():
seq = row['Sequence']
if seq != 'None':
dna = jdna.Sequence(row['Sequence'])
dna.annotate(None, None, row['Part'], color=ColorHash(row['Part'] + row['Annotat... | The function parses a NOR gate name into a genetic sequence by extracting components like homology, promoter, cassette, and marker. It uses predefined dictionaries to map parts, standardizes markers, constructs GRNA if applicable, and returns a pMOD object representing the genetic construct. | def parse_nor_gate_name_to_sequence(name):
parts_dict, _ = parts_by_name_and_cat()
match = parse_NOR_gate(name)
if match is None:
print("No match with '{}'".format(name))
return None
parsed = match.groupdict()
homology_dict = {6: "URA", 8: "HIS", 4: "TRP"}
promoter_dict = {'A':... |
def _init(self, data):
assert isinstance(data, np.ndarray)
assert data.ndim == 2
assert (0 <= data).all() and (data <= 1).all()
I, J = data.shape
K = self.n_components
s = self.smoothness
self.shp_A_IK = s * rn.gamma(s, 1. / s, size=(I, K))
self.rte_A_IK... | This function fits a model by converting input data into a masked array, imputing missing values with zeros, initializing the model, setting fixed parameters, and updating the model with a schedule. It handles masked data, ensures 2D input, and returns the fitted model instance. | def fit(self, data, fix_state={}):
if isinstance(data, np.ndarray):
data = np.ma.core.MaskedArray(data, mask=None)
assert isinstance(data, np.ma.core.MaskedArray)
mask = None if not data.mask.any() else data.mask.copy()
data = data.filled(fill_value=0.0) # missing entries w... |
def get_relevant_items():
work_item_ids = []
for active_item in get_items_by_state("Active"):
work_item_ids.append(active_item.id)
for resolved_item in get_items_by_state("Resolved"):
work_item_ids.append(resolved_item.id)
date_today = date.today()
for closed_item in get_items_b... | The main task of the code is to calculate and optionally update the "age" field of work items based on their history. It retrieves relevant work item IDs, determines their age from history records, and prints the duration. If a trial run flag is unset, it patches the specified field with the calculated age. The code av... | def update_work_item_age():
if trial_run:
print("Trial Run flag is set - will not actually update the items...")
work_item_ids = get_relevant_items()
for work_item_id in work_item_ids:
print("Checking Item {0}".format(work_item_id))
work_item_history = get_work_item_history(work_it... |
def iterate(self, prefixToks, showDots = False):
result = []
self.fixed = self.fillSlotsFromPrefix(prefixToks)
self.slots = csr_matrix((NumberOfBanks, self.V), dtype=float)
result.append(self.fixed.copy())
if self.verbose:
print ("fixed before initialization")
... | This code generates a sequence of tokens by iteratively predicting the next token using frequency analysis of results from an 'iterate' function. It starts with an encoded input string, expands the token list by selecting the most frequent token from generated results until reaching a specified maximum token count, the... | def generate(self, s, maxNumberOfToks=20):
toks = self.tokenizer.encode(s)
while len(toks) < maxNumberOfToks:
f = self.iterate(toks + [None] * self.buffersize)
c = Counter(self.getLastFromResult(f[i]) for i in range(len(f)))
best = c.most_common(1)[0][0]
... |
def iterate(self, prefixToks, showDots = False):
result = []
self.fixed = self.fillSlotsFromPrefix(prefixToks)
self.slots = csr_matrix((NumberOfBanks, self.V), dtype=float)
result.append(self.fixed.copy())
if self.verbose:
print ("fixed before initialization")
... | The main task of the code is to predict and append the most frequently occurring next token in a sequence, given a prefix. It encodes the prefix into tokens, iterates with a buffer, counts frequency of possible completions, selects the most common one, and appends it to the token sequence, then prints the decoded resul... | def test(self, prefix):
toks = self.tokenizer.encode(prefix)
f = self.iterate(toks + [None] * self.buffersize)
if len(f) > 0:
c = Counter(self.getLastFromResult(f[i]) for i in range(len(f)))
best = c.most_common(1)[0]
toks += best[0]
print (f"Resul... |
def get_db(self):
db = self.get_session()
try:
yield db
finally:
db.close()
def generate_user_id(self, role):
prefix = {'admin': 'a', 'patient': 'p', 'doctor': 'd', 'nurse': 'n'}
with self.get_db() as db:
while True:
user_id = p... | The main task of the code is to ensure an admin user exists in the database. If not found, it creates an admin user with a default username 'admin' and hashed password 'admin123', then commits the new record. It handles exceptions during the commit process and prints errors if they occur. | def ensure_admin_user(self):
with self.get_db() as db:
admin_user = db.query(User).filter(User.Username == 'admin').one_or_none()
if not admin_user:
admin_id = self.generate_user_id('admin')
password = self.hash_password('admin123')
new_adm... |
def get_db(self):
db = self.get_session()
try:
yield db
finally:
db.close()
def generate_user_id(self, role):
prefix = {'admin': 'a', 'patient': 'p', 'doctor': 'd', 'nurse': 'n'}
with self.get_db() as db:
while True:
user_id = p... | This function inserts a new user into the database after validating the username's uniqueness, generating a user ID if not provided, hashing the password, and handling exceptions. It returns the user ID on success or an error message with a status code on failure. | def insert_user(self, user):
with self.get_db() as db:
try:
if db.query(User).filter(User.Username == user['Username']).one_or_none():
logging.error('Username already exists')
return jsonify({'error': 'Username already exists'}), 400
... |
def error_handle(self, error, solution):
"""
Standardized error handling for CLI.
Keyword Arguments:
error -- error generated
solution -- recommended solution specific to each error
"""
response = {"error": error, "solution": solution}
retur... | The main task of the code is to create a job script by validating inputs, fetching application data, processing parameters (including user input or defaults), and interacting with an API to generate and optionally submit the job script. It handles error checks, parameter file parsing, dynamic workflow questions, and su... | def create_job_script(
self,
job_script_name,
application_id,
application_identifier,
param_file,
sbatch_params,
fast,
no_submit,
debug,
):
"""
CREATE a Job Script.
Keyword Arguments:
name ... |
def slice_x(input_text):
"""Get the value x"""
x = ""
if command_valid(input_text) is False:
slice_xyf = input_text[6:].split(",")
x = int(slice_xyf[0])
if (isinstance(x, int)) is False:
raise ValueError('Expected interger value')
return x
def slice_y(input_text):
... | This code processes a "place" command by parsing coordinates (x, y) and orientation (f) from input text. It validates the input and checks if the coordinates are within bounds. If valid, it updates the `xyf_list` with the new position and orientation, and appends the orientation to `face_mem` for tracking. | def place(input_text):
"""Execute command place"""
x = slice_x(input_text)
y = slice_y(input_text)
if place_validation(input_text) is True and on_table(x, y) is True:
xyf_list[0] = x
xyf_list[1] = y
xyf_list[2] = slice_f(input_text)
face_mem.append(slice_f(input_text)) |
def handle_success(self, in_payload, success):
'''
Log a success to the appropriate topics.
Arguments:
in_payload (JSON): The payload for which the success occurred.
'''
log_message = self.create_message(in_payload, {"status": "SUCCESS",
... | The code defines a `consume` method that processes incoming messages from a specified topic. It validates the message payload, logs success if valid, and forwards the payload to the `produce` method for further processing. If validation fails, it logs an error and handles the failure. The method ensures message integri... | def consume(self, message):
'''
Call-back method to handle a message on self.consume_topic.
Parses the payload and passes on to the self.produce method for
processing the provided coordinates.
Arguments:
message (JSON): message from self.consume_topic
'''
... |
def add_to_triangle_set(triangle_set, triangle) :
triangle_circum = circumcenter_and_radius(triangle)
triangle_set.append((triangle, triangle_circum[0], triangle_circum[1]))
def euclidean_dist(tup1, tup2) :
return ((tup1[0]-tup2[0])**2 + (tup1[1]-tup2[1])**2)**0.5
def edges_equal(e0, e1) :
if (e0[0] == ... | The code performs Bowyer-Watson Delaunay triangulation on a point set. It initializes a super triangle, iteratively checks if each point lies within existing triangles' circumcircles, removes violating triangles, and replaces them with new triangles connecting the point to the affected edges. The process ensures no poi... | def bowyer_watson_triangulation(point_set) :
super_triangle = ((-0.5, -0.5), (-0.5, 3), (3, -0.5)) # super triangle, triangle part
triangle_set = [] # store as a tuple of 3 items: the tuple of vertices(tuples), the tuple containing the circumcenter position, the radius of the circumcircle
add_to_triangle_s... |
def vert__init__(self, vertices) :
e1 = Edge(vertices[0], vertices[1])
e2 = Edge(vertices[0], vertices[2])
e3 = Edge(vertices[1], vertices[2])
self.edges = [e1, e2, e3]
self.vertices = vertices
temp = Polygon(self.edges, self.vertices)
cc_info = circumcenter_and_r... | This code initializes a graph structure by selecting between three initialization methods based on input parameters: vertices, edges, and first_edge. It uses vert__init__ if no edges or first_edge are provided, vert_and_firstedge__init__ if only first_edge is given, and vert_and_edges__init__ if edges are specified, en... | def __init__(self, vertices, edges=None, first_edge=None) :
if (edges == None) and (first_edge == None) :
self.vert__init__(vertices)
elif (edges == None) :
self.vert_and_firstedge__init__(vertices, first_edge)
else :
self.vert_and_edges__init__(edges, vertice... |
def isStateComposite(self, stateNode):
subStates = stateNode.findall('state')
if len(subStates)>0:
return True
return False
def readSubStates(self, SCXMLMotherState, motherModelState):
#get all states from the top level
states = SCXMLMotherState.finda... | The main task of the code is to parse an SCXML configuration file, validate its structure, extract state machine details (name, initial state, error state), process states and their transitions, and build a hierarchical state model by recursively handling nested states. It reads SCXML content, checks for validity, extr... | def read(self, ConfigPath):
SCXMLFilePath=ConfigPath
#read the content of the file
with open(SCXMLFilePath, 'r',encoding='utf-8-sig') as file:
data = file.read()
#check if this is a valid scxml file
#print(f'signature={scxmlSignature}')
#print(data)
s... |
def parameters_to_weights(self, parameters: Parameters) -> Weights:
"""Convert parameters object to NumPy weights."""
return [self.bytes_to_ndarray(tensor) for tensor in parameters.tensors]
def find_stable(self,
parameters: Parameters,
results: List[Tuple[Weights,... | The function aggregates federated learning model parameters using a weighted average, dynamically adjusting thresholds for parameter updates after round 125, identifying stragglers (slow clients), and adaptively modifying sub-model sizes via p_val thresholds based on straggler performance to optimize convergence and re... | def aggregate_fit(
self,
rnd: int,
results: List[Tuple[ClientProxy, FitRes]],
failures: List[BaseException],
) -> Tuple[Optional[Parameters], Dict[str, Scalar]]:
"""Aggregate fit results using weighted average."""
if not results:
return Non... |
def render_palette_dem(x):
import iio
img_terrain = iio.read("i/DEM_poster.png")
pal_terrain = img_terrain[0][0:256]
return pal_terrain[qauto(x,p=0.1)]
def qauto(x, p=0):
from numpy import float, uint8
if p > 0:
from numpy import percentile
m = percentile(x, p)
M = percentile(x, 100-p)
X = (((x.astype(flo... | The code renders a Digital Elevation Model (DEM) into an 8-bit color image using hillshading, a color palette, and ambient occlusion (SSAO). It combines elevation data with shading and lighting effects to produce a visually enhanced terrain representation, scaling the final output to 8-bit depth for standard image disp... | def render(d):
"""
Render a DEM using simple hillshading and color palette
Input d : a DEM
Output x : a 8-bit color image
"""
from numpy import newaxis, sqrt
d_pal = render_palette_dem(d).astype(float)
d_lam = qauto(render_shading(d)[:,:,newaxis], 5).astype(float)
d_sao = qauto(render_lssao(d,p=1)[:,:,newaxi... |
def similar(old, new):
'''
Determines if two passwords are similar by calculate if 1/2 of the
characters in the new password are different from the old one or if the
distance between them is acceptable
Accepted distance difference is defined by :diff_ok, the number of
characters in the new pass... | The function `VeryFascistCheck` validates a new password against security criteria, including checks for palindromes, simplicity, and similarity to an old password. If an old password is provided, it ensures the new password isn't identical, a rotation, a case-only change, or too similar. It leverages `FascistCheck` fo... | def VeryFascistCheck(new, old=None, dictpath=None):
'''
Behaves like FascistCheck but performs also checks for palindrome and
simple passwords.
If the optional old_password is provided additional checks for minimum
distance between the two passwords, for similarity, for change of case
only and ... |
def makeSpellbookTitle(opt, spellbookChar):
title = 'The ' + lookupDict[spellbookChar] + ' Grimoire'
result = np.ones([opt.pageHeight, opt.pageWidth, 3], dtype=np.float32)
gemStart = int(opt.pageHeight * 0.15)
gemHeight = int(opt.pageHeight * 0.45)
titleStart = int(opt.pageHeight * 0.65)
titl... | The code generates images for a spellbook, saves them as PNGs in a directory, and compiles them into a PDF using FPDF. It creates a title page, table of contents, and individual spell pages, then outputs a named PDF file with the spellbook's content. | def makeSpellbookImages(opt, spellbookChar, spellbook):
baseDir = 'spellbooks/' + spellbookChar + '/'
os.makedirs(baseDir, exist_ok=True)
titleImg = makeSpellbookTitle(opt, spellbookChar)
TOCImg = makeSpellbookTOC(opt, spellbook)
util.saveNPYImgDouble(baseDir + '0.png', titleImg)
util.saveNPYI... |
def create_packet(data, number_of_fragments, fragment_num, message_type):
if isinstance(data, str):
packet = struct.pack('!BHHHH', message_type, len(data), calculate_crc(data.encode()),
number_of_fragments, fragment_num) + data.encode()
else:
packet = struct.pack('!B... | The code implements a UDP-based message transmission system where a client sends a fragmented message with CRC checks. It handles packet corruption by resending damaged fragments, waits for acknowledgments, and ensures all fragments are successfully transmitted. The process involves creating packets, simulating corrupt... | def sending_message(client):
info_packet = create_packet("Message", 1, 0, 7)
client.send(info_packet)
while True:
try:
message, address = client.recvfrom(1024)
client.settimeout(None)
con, check = check_if_right_answer(message)
if not check:
... |
def create_packet(data, number_of_fragments, fragment_num, message_type):
if isinstance(data, str):
packet = struct.pack('!BHHHH', message_type, len(data), calculate_crc(data.encode()),
number_of_fragments, fragment_num) + data.encode()
else:
packet = struct.pack('!B... | The main task of the code is to send a file over a network using UDP by fragmenting it into packets, handling acknowledgment (ACK) responses, and simulating packet corruption for testing. It reads a file, sends its name in fragments, then transmits data fragments with error-checking, retransmitting corrupted packets. T... | def sending_files(client):
while True:
path = input("Path: ")
try:
with open(path, 'rb') as file:
data = file.read()
break
except FileNotFoundError:
print("File not found")
info_packet = create_packet("File", 1, 0, 8)
client.sen... |
def right_crc(message):
if calculate_crc(message[9:]) == int.from_bytes(message[3:5], byteorder='big'):
return True
else:
return False
def create_packet(data, number_of_fragments, fragment_num, message_type):
if isinstance(data, str):
packet = struct.pack('!BHHHH', message_type, len(... | The function receives UDP packets via a server socket, processes them based on their type (5, 7, 8, 4), and performs actions like switching, receiving messages/files, or responding to keepalives. It validates packets with CRC checks, sends appropriate responses, and returns 1 on specific conditions. The loop breaks on ... | def receive_info_packets(server, frag_size):
while True:
try:
message, address = server.recvfrom(frag_size)
server.settimeout(None)
# switch
if int.from_bytes(message[:1], byteorder='big') == 5 and right_crc(message):
server.sendto(create_packe... |
def sending_message(client):
info_packet = create_packet("Message", 1, 0, 7)
client.send(info_packet)
while True:
try:
message, address = client.recvfrom(1024)
client.settimeout(None)
con, check = check_if_right_answer(message)
if not check:
... | The main task of the code is to manage a client socket for sending messages or files via UDP, using a keep-alive thread. It allows user selection between message (1), file (0), or switch (2) modes. Upon selection, it stops the keep-alive thread, sends data, waits for a server response (checking for a specific byte flag... | def main_f(client_socket):
stop_flag_thread = threading.Event()
thread_keep_alive = threading.Thread(target=keep_alive, args=(client_socket, stop_flag_thread))
thread_keep_alive.start()
while True:
m_or_f = int(input("File(0) or message(1) or switch(2): "))
if m_or_f == 1:
st... |
def get_cb_coord(residue, pdb_id, chain):
"""Returns C-beta coord of a residue object. Take pdb_id and chain in case
you can not get Cb of non-Gly residue."""
restype = residue.get_resname()
if restype != 'GLY':
try:
cb_coord = residue['CB'].get_coord()
except:
# ... | This function computes features of the nearest 50 surface points from an opposing protein relative to a residue's CB atom, including distances, angles between CB's carbon vector and points, and dihedral angles involving the backbone (N, CA). It combines these features into a numpy array for analysis, aiding in structur... | def get_n_points(res_obj, surf_dict, pdb_id, chain):
"""Returns features of the nearest surface points from an opposing protein, for a given residue.
Also adds features such as distance and angles."""
# res_obj is a biopython class. Retrieved with: structure[0][chain][k].
# get coordinates of CB atom.
... |
def elapseTime(self, gameState, enemyIndex):
if enemyIndex == self.a:
particles = self.particlesA
else:
particles = self.particlesB
for i in range(self.numParticles):
x, y = particles[i]
# find all legal positions above or below it
n... | The function `chooseAction` selects the optimal next move for a game agent by evaluating all legal actions, choosing those with the highest evaluation value, and randomly selecting one. It updates "scared moves" counters when capsules are consumed, adjusting behavior based on whether the agent or an opponent ate a caps... | def chooseAction(self, gameState):
start = time.time()
pacmanPosition = gameState.getAgentPosition(self.index)
# elapse time
self.elapseTime(gameState, self.a)
self.elapseTime(gameState, self.b)
# ----------------elapse
self.observeState(gameState, self.a)
... |
def _init_actions(self):
self.dbg('_init_actions')
actions = [
self.create_action(
name=self.ACTION_BROWSE,
label='Open in browser',
short_desc='Open in browser, thus showing issues matching the filter.'),
self.create_action(
... | The code's main task is to initialize an application by logging startup, initializing actions, reading configuration settings, and loading icons, likely for a GUI or interactive system. | def on_start(self):
self.dbg('on_start')
self._init_actions()
self._read_config()
self._load_icons() |
def _read_config(self):
kp_settings = keypirinha.settings()
settings = self.load_settings()
app_max_results = kp_settings.get_int("max_results", "gui", 100)
self.idle_time = settings.get_float(
"idle_time", self.CONFIG_SECTION_MAIN,
fallback=self.DEFAULT_IDLE_TIM... | The code handles configuration change events by checking if PACKCONFIG or APPCONFIG flags are set. If so, it logs a message, reloads configuration data via _read_config(), updates icons with _load_icons(), and triggers a catalog rebuild via on_catalog(). The primary task is to rebuild the application's catalog whenever... | def on_events(self, flags):
self.dbg('on_events')
if flags & kp.Events.PACKCONFIG or flags & kp.Events.APPCONFIG:
self.info("Configuration changed, rebuilding catalog...")
self._read_config()
self._load_icons()
self.on_catalog() |
def build_threads_by_month():
for filename in glob.glob('json_months/*/*.json'):
print(filename)
with open(filename) as f:
threads = json.loads(f.read())
regex = "json_months/([0-9]+)/([0-9]+|unknown).json"
matches = re.match(regex, filename)
year, month = matches... | The main task of the code is to generate structured indexes for data organization: building monthly thread records, creating a yearly index, and establishing author-related indices to facilitate efficient data retrieval and analysis. | def main():
build_threads_by_month()
build_years_index()
build_author_indices() |
def preprocess(image):
# get shape and chop off 1/3 from the top
shape = image.shape
# note: numpy arrays are (row, col)!
image = image[int(shape[0]/3):shape[0], 0:shape[1]]
image = cv2.resize(image, (img_cols, img_rows), interpolation=cv2.INTER_AREA)
image = cv2.cvtColor(image, cv2.COLOR_RGB2YU... | The code processes real-time telemetry data from a self-driving car, including steering angle, throttle, speed, and camera images. It preprocesses images, uses a joystick for input, adjusts control outputs (steering/throttle), and displays simulated paths. It collects data (images and steering angles) into lists for po... | def telemetry(sid, data):
# The current steering angle of the car
steering_angle = data["steering_angle"]
# The current throttle of the car
throttle = data["throttle"]
# The current speed of the car
speed = data["speed"]
# The current image from the center camera of the car
imgString = d... |
def reset_state(state):
"""
The function to reset state array to initial values.
Arguments:
state: the array with state variables.
Returns:
The state array with values set to initial ones.
"""
state[0], state[1], state[3], state[4], state[5] = 0, 0, 0, 0, 0
state[2] = math.pi... | The main task of the code is to simulate a cart-two-pole system using a given neural network (ANN) to determine how many time steps it can maintain stability before the system goes out of bounds. The function scales input states, calculates network outputs to determine actions (discrete or continuous), applies these ac... | def run_simulation(net, max_bal_steps=100000, bool_discrete_action=False):
"""
The function to run cart-two-pole apparatus simulation for a
certain number of time steps as maximum.
Arguments:
net: The ANN of the phenotype to be evaluated.
max_bal_steps: The maximum number of time steps t... |
def reset_state(state):
"""
The function to reset state array to initial values.
Arguments:
state: the array with state variables.
Returns:
The state array with values set to initial ones.
"""
state[0], state[1], state[3], state[4], state[5] = 0, 0, 0, 0, 0
state[2] = math.pi... | The function simulates a cart-two-pole system using a neural network controller, evaluating its ability to maintain balance over a maximum number of steps. It scales input states, activates the network to determine actions (discrete or continuous), applies actions to update the system state, and calculates a performanc... | def run_simulation_gruau(net, max_bal_steps=1000, bool_discrete_action=False):
"""
The function to run cart-two-pole apparatus simulation for a
certain number of time steps as maximum.
Arguments:
net: The ANN of the phenotype to be evaluated.
max_bal_steps: The maximum number of time ste... |
def read_config(config_path: str) -> list[Playlist]:
with open(config_path) as f:
config = yaml.safe_load(f)
playlists = []
for p in config['playlists']:
url = p['url'].strip()
tag = p['tag'].strip()
regex = p['pattern']['regex'].strip()
flags_s = p['pattern']['flags... | The code's main task is to monitor YouTube playlists by reading a configuration file, checking for new videos not previously recorded in a history file, notifying users of these new videos, and updating the history with the latest entries. It processes each playlist, stores data in designated folders, and ensures only ... | def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
'-C', '--config',
default='config.yaml',
help='Path to the configuration file. Default %(default)s',
)
args = parser.parse_args(argv)
playlists = read_... |
def _set_states_from_ode_solution(self, ode_sol, save):
"""
Set states from ODE solution vector.
:param ode_sol: ([float]) solution vector from ODE solver
:param save: (bool) whether to save values to state history, i.e. whether solution represents final step
solution or interme... | This function computes the right-hand side of the differential equations governing a dynamic system's state variables, returning concatenated derivatives for attitude, angular velocity, position, velocity, and control inputs. It uses current states, forces/torques, and control setpoints to calculate time evolution of t... | def _dynamics(self, t, y, control_sp=None):
"""
Right hand side of dynamics differential equation.
:param t: (float) current integration time
:param y: ([float]) current values of integration states
:param control_sp: ([float]) setpoints for actuators
:return: ([float]) ... |
def get_states_vector(self, states, attribute="value"):
"""
Get attribute of multiple states.
:param states: ([string]) list of state names
:param attribute: (string) state attribute to retrieve
:return: ([?]) list of attribute for each state
"""
return [getattr(... | The code performs one integration step of a dynamic system using scipy's ODE solver, updating states (attitude, position, velocity) based on actuator commands. It calculates airspeed parameters, updates energy states, and handles constraint violations. The step returns success status and failure reasons, advancing the ... | def step(self, commands):
"""
Perform one integration step from t to t + dt.
:param commands: ([float]) actuator setpoints
:return: (bool, dict) whether integration step was successfully performed, reason for step failure
"""
success = True
info = {}
# R... |
def parse_cli():
""" Parse the command line arguments.
"""
parser = argparse.ArgumentParser(
'CLI options take precedence over settings in the yaml file'
'empty arguments are replaced by settings in the default yaml file')
parser.add_argument('-s',
dest='setting... | The main task of the code is to parse and combine JobMarket configuration settings by loading default YAMLs, integrating command-line arguments, and user-provided settings. It normalizes paths, validates configurations, sets output directories, and prepares runtime parameters like log levels and proxy settings, returni... | def parse_config():
""" Parse the JobMarket configuration settings.
"""
# find the jobfunnel root dir
jobfunnel_path = os.path.normpath(
os.path.join(os.path.dirname(__file__), '..'))
# load the default settings
default_yaml_path = os.path.join(jobfunnel_path, 'config/settings.yaml')
... |
def _nk(self, w, tn):
return w + tn * 2
def _L(self, l, nk):
return nk + l * 2
def _LL(self, L, w):
return (L - w) / 2
def _gm(self, ww, wh, offset_x, offset_y):
return str(int(ww)) + "x" + str(int(wh)) + "+" + str(int(offset_x)) + "+" + str(int(offset_y))
def _init_transparent(self):
... | This code initializes a GUI window with a customizable aiming crosshair or target. It sets up parameters for size, color, and visual elements (outline, center dot, crosshair), positions the window on the screen, creates a canvas for drawing, and initializes transparent rendering and the aiming point. | def __init__(self, length=4, width=1, thickness=2, color_r=0, color_g=255, color_b=255, is_outline=False,
is_center_dot=False, is_crosshair=True, offset_x=0, offset_y=0):
super().__init__()
self.l = length
self.w = width
self.tn = thickness
self.nk = self._nk(sel... |
def _dotted(key):
if isinstance(key, list):
return key
key = key.replace(r'\.', 'PSIOUFJRHPRIUENG')
pieces = key.split('.')
return [x.replace('PSIOUFJRHPRIUENG', '.') for x in pieces]
def _base(path, create_path=False, limit=-1):
return _ensure_path(superglobals(), _dotted(path)[0:limit], c... | The function `hasglobal(key)` checks if a global variable or attribute exists in the current namespace. It splits the input `key` into a path using `_dotted()`, extracts the base component with `_base()`, and verifies existence via `_ohas()` on the base and final path element. It returns `True` if the global variable e... | def hasglobal(key):
"""
hasglobal(name) -> bool
Return whether the global variable `key` exists
>>> hasglobal('builtins.slice') or hasglobal('__builtins__.slice')
True
"""
path = _dotted(key)
base = _base(path)
if base is not None:
return _ohas(base, path[-1]) |
def _dotted(key):
if isinstance(key, list):
return key
key = key.replace(r'\.', 'PSIOUFJRHPRIUENG')
pieces = key.split('.')
return [x.replace('PSIOUFJRHPRIUENG', '.') for x in pieces]
def _base(path, create_path=False, limit=-1):
return _ensure_path(superglobals(), _dotted(path)[0:limit], c... | The function `setglobal` sets a nested key-value pair in a global dictionary using a dotted string path (e.g., "test.deep.global.value"). It creates the necessary nested structure if the path doesn't exist, raises a `TypeError` for invalid paths, and returns the previous value or `None`. It ensures hierarchical keys ar... | def setglobal(key, value):
"""Set `key` from global dictionary
:param key (str): key
:param value (any): value
:raise TypeError: if a heirachical dotted key string's path was invalid
:return any: previous value or None
>>> _ = removeglobal('test')
>>> _ = setglobal('test.deep.global.value'... |
def _dotted(key):
if isinstance(key, list):
return key
key = key.replace(r'\.', 'PSIOUFJRHPRIUENG')
pieces = key.split('.')
return [x.replace('PSIOUFJRHPRIUENG', '.') for x in pieces]
def _base(path, create_path=False, limit=-1):
return _ensure_path(superglobals(), _dotted(path)[0:limit], c... | The main task of the code is to remove a specified key from a global dictionary, handling hierarchical dotted keys. It returns True if the key existed, raises a TypeError if the path doesn't exist, and optionally fails silently. The function uses helper methods to parse the key path and perform deletion. | def removeglobal(key, quiet=False):
"""Remove `key` from global dictionary
:param key (str): key
:param quiet (bool): fail silently
:return: True if the key existed
:raise TypeError: if a heirachical dotted key string's path did not exist
"""
path = _dotted(key)
base = _base(path)
i... |
def hasglobal(key):
"""
hasglobal(name) -> bool
Return whether the global variable `key` exists
>>> hasglobal('builtins.slice') or hasglobal('__builtins__.slice')
True
"""
path = _dotted(key)
base = _base(path)
if base is not None:
return _ohas(base, path[-1])
def _full(pat... | The function `getglobal` retrieves a value from a global dictionary based on a given `path`, returning it if it exists and matches the specified `_type` (if provided). If the key is absent, it returns a `default` value. Optionally, if `_set` is `True`, it sets the `default` value in the global dictionary if the key isn... | def getglobal(path, default=None, _type=None, _set=False):
"""
getglobal(key[, default]) -> value
Return the value for key if key is in the global dictionary, else default.
"""
if hasglobal(path):
result = _full(path)
if _type is None:
return result
if isinst... |
def hasglobal(key):
"""
hasglobal(name) -> bool
Return whether the global variable `key` exists
>>> hasglobal('builtins.slice') or hasglobal('__builtins__.slice')
True
"""
path = _dotted(key)
base = _base(path)
if base is not None:
return _ohas(base, path[-1])
def setglobal... | This function sets a global variable `key` to `value` if it doesn't already exist, then returns the current value of `key`. It ensures the variable is initialized with `value` when unset, and raises an error if the assignment fails. | def defaultglobal(key, value):
"""
defaultglobal(key, value)
Set the value of global variable `key` if it is not otherwise set and
return the new/existing contents of the global variable
"""
if not hasglobal(key):
setglobal(key, value)
result = getglobal(key, _NotFound)
if resul... |
def skip_if_invalid_and_no_renaming(replay_name):
"""
Determines whether or not a replay should be skipped based on its name. If
a replay name cannot be properly printed by Reflex, it must be skipped
:param replay_name: The replay name to be checked
:return: True or False depending on if the replay ... | The code processes replay files in a directory, organizes them into a hierarchical data structure, and renames replays based on game mode and player info. It filters out broken replays, collects metadata like workshop IDs, and recursively explores subfolders to build a nested dictionary of folders, replays, and associa... | def navigate(prev, dirs):
data = {"folders": {}, "replays": [], "ids": [], "info": {}}
dir = os.path.join(cfg["REPLAY_DIR"], *dirs)
entries = os.listdir(dir)
folders = [entry for entry in entries if os.path.isdir(os.path.join(dir, entry))]
replays = [Path(entry).stem for entry in entries if os.pa... |
def read_prev_data():
data_p = cfg["REPLAY_DATA_PATH"]
with open(data_p, "r") as data_f:
data_s_current = data_f.read()
try:
previous_data = lua.decode(re.search(r"replayBrowserTable = ([\s\S]*?);", data_s_current).group(1))
except:
previous_data = {"replays": [... | The code's main task is to compare the original data with a processed version (encoded and decoded) and update the data if they differ. It reads previous data, processes it, checks for changes, and writes the new data if necessary. | def update():
prev = read_prev_data()
data = navigate(prev, [])
if prev != lua.decode(lua.encode(data)):
write_new_data(data) |
def get_hashtag_posts(self, hashtag: str, limit: int, headed: bool):
"""Fetch data about posts that used a specified hashtag and merge with
existing data, if it exists."""
# Define file to store hashtags in and create parent directory
hashtag_file = self.data_dir / hashtag / "posts.json... | The code's main task is to process specified hashtags by scraping posts, generating visual plots, frequency tables, and downloading videos, contingent on command-line flags. It iterates through each hashtag, executing scraping, analysis, and output operations based on the `plot`, `table`, and `download` parameters, wit... | def run(
self,
limit: int,
download: bool,
plot: bool,
table: bool,
number: int,
headed: bool,
):
"""Execute the specified operations on all specified hashtags."""
# Scrape all specified hashtags and perform analyses, depending on if
#... |
def get_nn_input(self, frame):
inputs = self.nnet.get_final_value(
[self.rect.x / screen_width, self.rect.y / screen_height, frame])
self.wall_jump_right = False
self.wall_jump_left = False
if self.block_wall_jump > 0:
self.block_wall_jump -= 1
if input... | This code updates an object's state by conditionally acquiring input (neural network or standard) based on `get_nn_inputs` and `self.is_alive`, then retrieves the current status and triggers an animation frame update. | def update(self, frame):
# self.get_input()
if get_nn_inputs:
if self.is_alive:
self.get_nn_input(frame)
else:
self.get_input()
self.get_status()
self.animate() |
def bit(h, i):
return (indexbytes(h, i//8) >> (i%8)) & 1
def xrecover(y):
xx = (y*y-1) * inv(d*y*y+1)
x = expmod(xx, (q+3)//8, q)
if (x*x - xx) % q != 0: x = (x*I) % q
if x % 2 != 0: x = q-x
return x
def isoncurve(P):
x = P[0]
y = P[1]
return (-x*x + y*y - 1 - d*x*x*y*y) % q == 0 | The main task of the code is to decode a point (x, y) from a string `s` by converting bits of `s` into coordinates, applying a parity check to ensure consistency with the last bit of `s`, and validating that the resulting point lies on an elliptic curve. If the point is invalid, it raises an exception. The function ret... | def decodepoint(s):
y = sum(2**i * bit(s, i) for i in range(0, b-1))
x = xrecover(y)
if x & 1 != bit(s, b-1): x = q - x
P = [x, y]
if not isoncurve(P): raise Exception("decoding point that is not on curve")
return P |
def bit(h, i):
return (indexbytes(h, i//8) >> (i%8)) & 1
def xrecover(y):
xx = (y*y-1) * inv(d*y*y+1)
x = expmod(xx, (q+3)//8, q)
if (x*x - xx) % q != 0: x = (x*I) % q
if x % 2 != 0: x = q-x
return x
def isoncurve(P):
x = P[0]
y = P[1]
return (-x*x + y*y - 1 - d*x*x*y*y) % q == 0 | The function decodes a point from a string 's' by calculating x and y coordinates using bit extraction and recovery, adjusts x based on a parity check, verifies the point lies on the elliptic curve, and returns the valid point [x, y] or raises an error if invalid. | def decodepointcheck(s):
y = sum(2**i * bit(s, i) for i in range(0, b-1))
x = xrecover(y)
if x & 1 != bit(s, b-1): x = q - x
P = [x, y]
if not isoncurve(P):
quit()
raise Exception("decoding point that is not on curve")
return P |
def sc_reduce32(input):
## convert hex string input to integer
int = hex2int(input)
## reduce mod l
modulo = int % (2**252 + 27742317777372353535851937790883648493)
## convert back to hex string for return value
return int2hex(modulo)
def hash_to_scalar(key):
hash = keccak_256(key)
retur... | The code generates a Monero address by creating a secret spend key, deriving a view key, generating public keys from private keys, concatenating network bytes and keys, computing a checksum, and encoding the result with base58. It returns the generated address along with the keys. | def generate_random_address():
## generate 32 bytes (256 bits) of pseudo-random data
seed = hexlify(os.urandom(32))
## reduce random data to make it a valid ed25519 scalar
secret_spend_key = sc_reduce32(seed)
## use a reduced hash of the secret spend key for the deterministic secret view key
s... |
def H(m):
return hashlib.sha512(m).digest()
def bit(h, i):
return (indexbytes(h, i//8) >> (i%8)) & 1
def scalarmult(P, e):
if e == 0: return [0, 1]
Q = scalarmult(P, e//2)
Q = edwards(Q, Q)
if e & 1: Q = edwards(Q, P)
return Q
def encodepoint(P):
x = P[0]
y = P[1]
bits = [(y >> i... | The main task of the code is to generate a public key from a secret key. It hashes the secret key `sk` to derive a value `h`, constructs a scalar `a` by combining bits of `h` with powers of 2, performs scalar multiplication of a base point `B` with `a` to obtain a point `A`, and finally encodes `A` as the public key. T... | def publickey(sk):
h = H(sk)
a = 2**(b-2) + sum(2**i * bit(h, i) for i in range(3, b-2))
A = scalarmult(B, a)
return encodepoint(A) |
def H(m):
return hashlib.sha512(m).digest()
def bit(h, i):
return (indexbytes(h, i//8) >> (i%8)) & 1
def Hint(m):
h = H(m)
return sum(2**i * bit(h, i) for i in range(2*b))
def scalarmult(P, e):
if e == 0: return [0, 1]
Q = scalarmult(P, e//2)
Q = edwards(Q, Q)
if e & 1: Q = edwards(Q, P)... | This function generates a digital signature for a message `m` using a secret key `sk` and public key `pk`. It computes a hash of the secret key, derives a scalar `a`, generates a random value `r`, computes a point `R` via scalar multiplication, and calculates the signature component `S` using modular arithmetic. The ou... | def signature(m, sk, pk):
h = H(sk)
a = 2**(b-2) + sum(2**i * bit(h, i) for i in range(3, b-2))
r = Hint(intlist2bytes([indexbytes(h, j) for j in range(b//8, b//4)]) + m)
R = scalarmult(B, r)
S = (r + Hint(encodepoint(R)+pk+m) * a) % l
return encodepoint(R) + encodeint(S) |
def decodepoint(s):
y = sum(2**i * bit(s, i) for i in range(0, b-1))
x = xrecover(y)
if x & 1 != bit(s, b-1): x = q - x
P = [x, y]
if not isoncurve(P): raise Exception("decoding point that is not on curve")
return P
def decodeint(s):
return sum(2**i * bit(s, i) for i in range(0, b))
def Hint... | This function verifies a cryptographic signature using Ed25519-like logic. It checks the length of the signature (s) and public key (pk), decodes their components, computes a hash (h) from the message and public key, then validates if the scalar multiplication of the base point (B) with the signature's scalar (S) match... | def checkvalid(s, m, pk):
if len(s) != b//4: raise Exception("signature length is wrong")
if len(pk) != b//8: raise Exception("public-key length is wrong")
R = decodepoint(s[0:b//8])
A = decodepoint(pk)
S = decodeint(s[b//8:b//4])
h = Hint(encodepoint(R) + pk + m)
if scalarmult(B, S) != edwa... |
def parse_arg():
parser = argparse.ArgumentParser(description='Test OpenNI2 and NiTE2.')
parser.add_argument('-w', '--window_width', type=int, default=1024,
help='Specify the window width.')
return parser.parse_args()
def init_capture_device():
openni2.initialize(os.path.join(
... | The code captures and visualizes real-time skeleton tracking data from a depth camera (e.g., Kinect) using the NiTE library. It initializes device settings, detects users, tracks their skeletons, processes depth frames, and displays the results. The system adjusts for device-specific parameters, normalizes depth data, ... | def capture_skeleton():
args = parse_arg()
dev = init_capture_device()
dev_name = dev.get_device_info().name.decode('UTF-8')
print("Device Name: {}".format(dev_name))
use_kinect = False
if dev_name == 'Kinect':
use_kinect = True
print('using Kinect.')
try:
user_trac... |
def create_mappings(dataset_path):
entity_counter = Counter()
relation_counter = Counter()
with open(dataset_path, "r") as f:
for line in f:
head, relation, tail = line[:-1].split("\t")
entity_counter.update([head, tail])
relation_counter.update([relation])
... | The code trains a TransE knowledge graph embedding model using specified hyperparameters (embed_dim=50, lr=0.01, margin=1) on FB15K dataset. It loads training/valid/test data, initializes the model with entity/relation mappings, trains for 100 epochs, and evaluates test set performance by calculating 10@hits metric for... | def main():
# for fb15k embed_dim = 50, lr = 0.01, margin = 1, and d = L1
margin = 1
lr = 0.01
embed_dim = 50
batch_size = 512
epochs = 100
entity2id, relation2id = create_mappings('../data/train.txt')
train_loader = load_data('../data/train.txt', batch_size, entity2id, relation2id)... |
def _check_leadership(self, url, timeout, verify):
state_metrics = self._get_master_state(url, timeout, verify)
self.leader = False
if state_metrics is not None:
self.version = map(int, state_metrics['version'].split('.'))
if state_metrics['leader'] == state_metrics['pid... | The code checks a Mesos instance's URL and configuration, collects metrics about frameworks, tasks, resources, and roles from the Mesos master, and reports them as gauges with tags. It validates input, handles timeouts/SSL, and conditionally reports metrics based on leadership status, updating service checks afterward. | def check(self, instance):
if 'url' not in instance:
raise Exception('Mesos instance missing "url" value.')
url = instance['url']
instance_tags = instance.get('tags', [])
default_timeout = self.init_config.get('default_timeout', 5)
timeout = float(instance.get('timeo... |
def _get_config(self, instance):
self.host = instance.get('server', '')
self.port = int(instance.get('port', 0))
self.mysql_sock = instance.get('sock', '')
self.defaults_file = instance.get('defaults_file', '')
user = instance.get('user', '')
password = str(instance.get('... | The code's main task is to check a MySQL instance by retrieving configuration parameters, validating required fields (host, user, or defaults_file), establishing a database connection, and collecting metadata, metrics, and system metrics. It also manages query cache statistics and handles exceptions during the process,... | def check(self, instance):
host, port, user, password, mysql_sock, defaults_file, tags, options, queries, ssl, connect_timeout = \
self._get_config(instance)
self._set_qcache_stats()
if (not host or not user) and not defaults_file:
raise Exception("Mysql host and user a... |
def __train_stepwise(self, ts, exogenous):
"""
Trains the ARIMA model using the step wise algorithms to find the optimal parameters
:param ts: time series
:param exogenous: exogenous variables if any
:return: fit, model
"""
ts, _, _ = self.__power_transformer.tran... | The function fits a stepwise ARIMA model on a time series, splitting data into training and test sets based on `test_ratio`. It trains the model, evaluates performance using RMSE on the test set if provided, and re-trains on the full dataset. It returns the best model, its fit, and the RMSE score, along with seasonalit... | def fit(self, ts, seasonal_period, exogenous=None, test_ratio=0.2):
"""
Fits the step wise ARIMA model on the passed data
:param ts: time series
:param seasonal_period: seasonal span of the series if seasonal, else -1
:param exogenous: exogenous variables if any
:param te... |
def create_buttons():
#Restart button
#Background/shadow
g.screen.create_rectangle(0,5,50,55,fill="#000033", outline="#000033")
g.screen.create_rectangle(0,0,50,50,fill="#000088", outline="#000088")
#Arrow
g.screen.create_arc(5,5,45,45,fill="#000088", width="2",style="arc",outline="white",extent=300)
g.s... | This function initializes a game where a specified algorithm (computer player) competes against another player. It sets up the game interface, configures player roles, updates the board, and triggers a valid computer move to start gameplay. | def playAlgorithmvsGame(alg):
global algorithm
algorithm = alg
g.running = True
g.screen.delete(ALL)
create_buttons()
# Draw the background
drawGridBackground()
markPlayers(alg)
g.set_players(1,0)
g.board = ot.Board(g, g.player1)
g.board.update()
doValidComputerMove() |
def runGame():
""" Start game, create game board, let the player choose gameplay mode
"""
g.screen.delete(ALL)
g.running1 = False
# Title and shadow
g.screen.create_text(250, 203, anchor="c", text="Othello", font=(
"Consolas", 50), fill="dark slate gray")
g.screen.create_text(250, 200, anchor="c", text="Othell... | This function handles player mouse clicks to validate moves, update the game board, switch turns, and initiate computer moves using selected algorithms. It also manages gameplay mode selection, determines player/computer turn order, and triggers game-ending conditions like win detection. | def clickHandle(event):
""" Player's engine - handles click, checks move correctness and switches to computer's turn
If clicked just after begginging chooses gameplay mode.
"""
global player_first
xMouse = event.x
yMouse = event.y
if g.running1:
if g.running2:
if not(g.computerMove):
if xMouse >= 450 a... |
def get_gpu_name(self, vendor, device):
device_vendor_name, device_model_name = self.control_pci_ids(vendor, device, self.mauna_pci_ids)
if device_vendor_name == 0 or device_model_name == 0:
print("device name not found in {} {}:{}".format(self.mauna_pci_ids, vendor, device))
d... | This code gathers GPU information by parsing `lspci` and `glxinfo` outputs, identifies default and additional GPUs, and organizes details like vendor, model, driver, and slot into structured lists. It handles edge cases like single/multiple GPUs, virtual machines, and PCI bus availability, populating `default_gpu`, `ex... | def get_gpu(self):
glx_vendorid = ""
glx_string = ""
glx_driver = ""
pci_bus = True
try:
lspci_command = subprocess.check_output(["lspci", "-n"]).decode("utf-8").strip()
except Exception as e:
print("{}".format(e))
lspci_command = ""
... |
def defineComponents(self):
self.dialog_report_exported = self.builder.get_object("dialog_report_exported")
self.dialog_gathering_logs = self.builder.get_object("dialog_gathering_logs")
self.lbl_distro = self.builder.get_object("lbl_distro")
self.lbl_distro_version = self.builder.get_ob... | This code initializes a GTK application by loading a UI from a Glade file, setting up the main window, connecting signals, and starting background threads to populate GPU and IP information. It also reads system info and prepares the UI for display. | def __init__(self, application):
# Gtk Builder
self.builder = Gtk.Builder()
# Translate things on glade:
# self.builder.set_translation_domain(APPNAME)
# Import UI file:
self.builder.add_from_file(os.path.dirname(os.path.abspath(__file__)) + "/../ui/MainWindow.glade")
... |
def read_int(self, numBytes: int) -> int:
return int.from_bytes(self.read(numBytes), 'big')
def read(self, numBytes: int) -> bytes:
result = self.data[self.pc:self.pc+numBytes]
self.pc += numBytes
return result
def get_arg(self, type) -> int:
print(f'get_arg type = {type}.')
... | This code decodes an opcode from memory. It determines the opcode type, calculates its byte length, adjusts the value using predefined differences, retrieves the opcode definition, and extracts arguments by parsing nibbles from data bytes. It then trims and returns the opcode with its parsed arguments for execution. | def get_opcode(self) -> int:
data = self.data[self.pc]
type = (data & 192) >> 6
numBytes = 1 if type < 2 else 2**(type-1)
print(f"Opcode type: {type} Number of bytes: {numBytes} Opcode: {data}")
code = self.read_int(numBytes) - self.opcode_diffs[type]
opcode = opcode_def... |
def load_from_binary(file_name):
"""
Load integers from a binary file using Huffman coding.
Args:
file_name (str): Path to the binary file.
Returns:
list: List of decompressed integers.
"""
huff = HuffmanCoding()
binaries = pb.read_padded_bytes(file_name)
... | The function decompresses a binary image into RGB channels using pre-trained models. It loads residual data from the binary file, splits them into red, green, and blue components, reconstructs each channel by predicting values with respective models, adjusts residuals, converts to 8-bit integers, combines them into an ... | def decompress_image(bin_path, height, width, save_path):
"""
Decompress an image from a binary file using the models for the RGB channels.
Args:
bin_path (str): Path to the binary file.
height (int): Height of the image.
width (int): Width of the image.
save_path (str): Pat... |
def create_droplet(client: Client, name, ssh_key_name, ssh_public_key):
key_fingerprint = find_or_create_ssh_key(client, ssh_key_name, ssh_public_key)
droplet_creation_request_body = {
"name": name,
"region": REGION,
"size": SIZE,
"image": IMAGE,
"ssh_keys": [key_fingerp... | The main task of the code is to create a DigitalOcean droplet, configure its firewall to allow access to a specified database, and return the droplet's IP addresses. It uses provided credentials, provisions the droplet with SSH keys, retrieves the database ID from the name, and adjusts firewall rules to enable database... | def create_droplet_and_allow_on_firewall(
do_token, name, ssh_key_name, ssh_public_key, db_name
):
client = Client(token=do_token)
created_droplet = create_droplet(client, name, ssh_key_name, ssh_public_key)
db_id = fetch_db_id_from_db_name(client, db_name)
allow_droplet_on_db_firewall(client, cr... |
def get_binance_server_time():
# check server time
response = requests.get('https://api.binance.com/api/v3/time')
# {"serverTime":1621783085061}
jsonObject = json.loads(response.text)
return int(jsonObject['serverTime'])
def sign_sha256(api_secret,text):
h = hmac.new(api_secret, msg=text.encode(), ... | This function creates a trade order on Binance (LIMIT or MARKET type) by constructing signed API requests with parameters like symbol, amount, price, and side. It sends the order, checks for successful execution, and polls until the order is confirmed in the system, returning the order ID upon completion. Error handlin... | def create_order_binance(symbol,amount_coin,price,side,type):
try:
ts = get_binance_server_time()
if type == 'LIMIT':
queryParams = 'symbol='+symbol.upper()+'USDT&side='+side+'&timeInForce=GTC×tamp='+str(ts)+'&type=LIMIT&quantity='+str(amount_coin)+'&price='+str(price)
else:... |
def get_initial_solution(k: int, n: int) -> list:
"""
Return initial randomic solution for the problem by randomly choosing points and adressing it to routes.
Args:
k (int): number of collectors.
n (int): number of points.
Returns:
list: the routes of each collector.
"""
... | This code performs an iterative local search (ILS) to find an optimal solution. It initializes a solution, applies local search to improve it, then repeatedly mutates the solution, re-applies local search, and updates the best solution if improvements are found. The process continues indefinitely, returning the final s... | def ils(k: int, n: int, m: list, x: int, y: int) -> list:
s = get_initial_solution(k, n)
s, min = local_search(s, k, y, m)
while True:
ns = mutate_gap(s, k, m)
ns, n_min = local_search(ns, k, y, m)
if n_min < min:
s = ns
min = n_min
save_solution(s)
print(min)
return s, mi... |
def get_valid_rook_moves(board, coord):
return (get_multi_moves(board, coord, 1, 0) +
get_multi_moves(board, coord, -1, 0) +
get_multi_moves(board, coord, 0, 1) +
get_multi_moves(board, coord, 0, -1))
def get_knight_moves(board, coord):
return (get_single_move(board, coord, 2... | The code retrieves valid moves for a chess piece based on its type using a dictionary. It maps each piece name to a corresponding move-generation function, then returns the result for the given piece or an empty list if the piece is unrecognized. | def switch_moves(piece):
switcher = {
ROOK_NAME: get_valid_rook_moves(board, coord),
KNIGHT_NAME: get_knight_moves(board, coord),
BISHOP_NAME: get_valid_bishop_moves(board, coord),
QUEEN_NAME: get_valid_queen_moves(board, coord),
KING_NAME: get_valid_k... |
def resample(data, w):
dataCopy = pd.DataFrame(index=data.index, columns=data.columns)
cw = []
for i in range(len(w)):
if i == 0:
cw.append(w[i]);
else:
cw.append(cw[i - 1] + w[i]);
for i in range(len(cw)):
index = bisect_left(cw, random.random())
... | This code implements the AdaBoost algorithm using decision trees as weak learners. It iteratively resamples data with weighted probabilities, trains a decision tree, computes classification error, adjusts weights for misclassified instances, normalizes weights, and stores the trees and their corresponding log-weight up... | def adaboost(data, K, target):
n = len(data)
w = np.array([1 / n] * n)
h = []
z = np.array([0.0] * K)
for k in range(K):
data = resample(data, w)
h.append(decisionTree(data, data.columns[:-1], data, 1, target))
error = 0
queries = data.iloc[:, :-1].to_dict(orient="rec... |
def create_population(self):
"""
Create one population
"""
for i in range(self.bot_counts):
self.POPULATION_DICT[i] = self.create_random_route_for_all_cars_on_map()
logging.info(f"Create one bot. Number-{i}: {self.POPULATION_DICT[i]}")
logging.info(f"Creat... | This method executes a genetic algorithm over multiple populations, evolving each generation by selecting the best bots from the previous population to create the next. It initializes the population, evaluates each iteration, updates mutation rates, tracks results, and logs progress. The algorithm stops early if needed... | def run_genetics(self):
"""This method run genetic algorithm"""
time_start = time.time()
logging.info(f"Start algoritmn\n\n{'#'*100}")
start_flag = True
for population in range(self.populations):
if self.NEED_STOP_FLAG == True:
break
if pop... |
def first_layer(cube):
solution = []
cross_colours = {"w": 1, "r": 2, "y": 3, "o": 4}
num_to_colour = {1: "w", 2: "r", 3: "y", 4: "o"}
free_to_move = [1, 2, 3, 4]
for colour in cross_colours:
location = find_edge("g", colour, cube)
broken_cube = 0
while location[2:4] != [cros... | The code solves a Rubik's Cube using the CFOP (Cross, F2L, OLL, PLL) method. It validates the input cube, solves each of the three layers (first, second, third) sequentially, checks for errors, optimizes the solution steps, and returns the combined solution. If any layer fails, it returns an error. The main task is to ... | def CFOP(cube):
print("CFOP INPUT: ", cube)
print()
if len(cube) != 6:
return "INVALID CUBE"
f = first_layer(cube)
s = second_layer(cube)
t = third_layer(cube)
res = [[],[],[]]
if type(f) == str or type(s) == str or type(t) == str:
print("Bad Cube")
return res
... |
def forward(self, inputs):
""" Implementation of the forward pass.
It should accepts the inputs and passing them through the network and return results.
"""
self.inputs = inputs
# Layer 1 1*2, 2*100
self.L1_inp = np.dot(inputs, self.W1)
self.L1_out = sigmoid(self... | This code trains a neural network model by iterating over input data and labels for a specified number of epochs. It performs forward propagation, computes errors, and backpropagates gradients for each data point. Periodic testing is conducted to monitor performance, with a final test after training completes. The core... | def train(self, inputs, labels):
""" The training routine that runs and update the model.
Args:
inputs: the training (and testing) data used in the model.
labels: the ground truth of correspond to input data.
"""
# make sure that the amount of data and label is m... |
def find_edit_distance_recursive(s: str, t: str) -> int:
"""Return the edit distance of s to t recursively."""
if s == "" or t == "":
if s == "":
return len(t)
elif t == "":
return len(s)
else:
if s[len(s) - 1] == t[len(t) - 1]:
return find_edit_di... | The code calculates and compares the edit distance between the strings "bear" and "brie" using both recursive and iterative methods, then executes a function `multiple_trials()` to potentially test or benchmark these approaches. | def main():
print("Recursive:")
print(find_edit_distance_recursive("bear", "brie"))
print("Iterative:")
print(find_edit_distance_iterative("bear", "brie"))
print(multiple_trials()) |
def parse_csv(csv_file):
countries = []
with open(csv_file, 'r') as f:
reader = csv.reader(f, delimiter=',')
next(reader, None) # skip header
for row in reader:
countries.append(Country(
name=row[0],
cases=float(row[1])/SCALE,
... | The code processes a CSV file containing country data, generates grouped bar plots from the data, and exports the results as a 3D object (.obj) file for visualization or further use. | def run(input_file, output_file):
# get data from .csv file
countries = parse_csv(input_file)
# create barplots from data
bar_groups = plot_countries(countries)
# generate final .obj file
save_obj(PATH_OUTPUT + output_file, countries, bar_groups) |
def get_compiled_contracts():
"""
This function returns a dictionary of all the compiled contracts, their ABI and bytecode.
It uses the solcx library to compile the contracts specified in the FILES_TO_COMPILE variable.
The returned dictionary has the
contract name as the key and a dictionary contain... | The main task of the code is to compile smart contracts, deploy them, save their addresses to a file, move related files to a backend, instantiate the deployed contracts, and log the total execution time and final block number. It also includes steps for handling contract deployment outputs and ensuring backend setup. | def main():
"""
The main function
:return:
"""
# os.system('rm logs.log')
start_time = st = datetime.datetime.now()
print("Compiling contracts")
compiled_contracts = get_compiled_contracts()
print("Contracts compiled")
print("Deploying contract")
# f=open('../build/contract_a... |
def tag_region(text):
regionx_found = []
found = regex_region.findall(text)
if(found):
for a in found:
if len(a) > 1:
found = a
info["lokasi"] = found
text = re.sub(found, '<lokasi>', text)
return text
def tag_time(text):
timex_found=[]
found = regex_time_exp1.findall(text)
# print(found)
found... | The code's main task is to tag entities in input text by loading a pre-trained model from a pickle file and sequentially applying region, time, name, and entity tagging functions to identify and annotate relevant information. | def tag(text):
# load pickle file
entity_file = open("db/entity/entity.pkl","rb")
pk = pickle.load(entity_file)
result = tag_region(text)
result = tag_time(result)
result = tag_name(result)
result = tag_entity(pk,result)
return result |
def read_previous_events(date):
""" Attempt to copy the events list from the previous issue. """
EVENTS_START = 'Rusty Events between'
EVENTS_END = 'If you are running a Rust event'
previous_issue = read_previous_issue(date)
events_list = ''
found_events = False
for line in previous_issue.... | The function `create_draft` generates a new issue draft by substituting dynamic parameters into a template. It calculates an end date (28 days after the input date), retrieves or uses a placeholder for previous events, prepares parameters like issue number and dates, reads a template file, and returns the formatted dra... | def create_draft(date):
""" Return a new issue draft based on the template file. """
# Events listing ends on issue_date + 28 days.
end_date = date + datetime.timedelta(28)
try:
events_list = read_previous_events(date)
except Exception as e:
LOG.warning(f'failed to copy previous eve... |
def default_date():
""" Returns a datetime.date, that is the estimated next issue date. """
# If no input date is specified, we assume that this will be run ~7 days
# before the next issue is released. Just in case an issue comes out early
# or late, we'll pick the Wednesday that is between 4 and 10 day... | The main task of the code is to generate a weekly draft article (e.g., "This Week in Rust") with customizable date, output path, and dry-run options. It parses command-line arguments, determines the issue date, constructs a filename, creates draft content, and either prints it to stdout or writes it to a file, with opt... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--date', default=None, metavar='YYYY-MM-DD',
help='draft date (defaults to Wednesday ~7 days away)')
parser.add_argument('--draft-path', default=None, metavar='DIR',
help='directory to write t... |
def _check_keydown_events(self, event):
"""Handles keydown events"""
if event.key == pygame.K_RIGHT:
self.ship.keys['right'] = True
if event.key == pygame.K_LEFT:
self.ship.keys['left'] = True
if event.key == pygame.K_UP:
self.ship.keys['up'] = True
if ... | The main task of the code is to handle user input events in a Pygame application. It checks for quit requests, keyboard key presses/releases, and mouse button clicks. When the mouse is clicked, it retrieves the position and triggers a play button check. The function delegates specific event processing to helper methods... | def _check_events(self):
"""Handle key and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif ... |
def _check_fleet_edges(self):
"""Go through fleet and see if sides have reached ends """
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_dir()
break
def _check_ship_hit(self):
"""Remove a life if ship hit"""
... | The main task of the code is to update the positions of all aliens in the fleet, check if any aliens have reached the screen edges to adjust their movement, detect collisions between the player's ship and aliens, and verify if any aliens have reached the bottom of the screen to trigger game-ending conditions. | def _update_aliens(self):
"""Update all aliens in fleet"""
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._check_ship_hit()
self._check_aliens_bottom() |
def _check_events(self):
"""Handle key and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif ... | The code runs the game loop, checking for events, updating game elements (ship, bullets, aliens) when the game is active, and refreshing the screen repeatedly to maintain gameplay and visuals. | def run_game(self):
while True:
self._check_events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen() |
def scale_pyramid(input_image):
# Generates image pyramid
scaled_images = []
scaled_images.append(F.interpolate(input_image, size=(615, 455), mode='area'))
scaled_images.append(F.interpolate(input_image, size=(619, 459), mode='area'))
scaled_images.append( F.interpolate(input_image, size=(311, 231)... | The code computes a total loss for depth estimation by combining reconstruction loss and disparity smoothness loss. It generates scale pyramids from input images, splits disparities into left/right components, calculates reconstruction loss for each pyramid level, averages them, computes smoothness loss for disparities... | def depth_loss(left_image, right_image, disparity_1, disparity_2, disparity_3, disparity_4):
# Calculate scale pyramids for input images
left_scale_pyramid = scale_pyramid(left_image)
right_scale_pyramid = scale_pyramid(right_image)
# Creating left and right disparity arrays
left_disp = [disparit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.