dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def readMenuAndGetInput(options):
saySomething('Here are your available options.')
for option in options:
saySomething(option)
choice = getUserInput('Please choose an option.')
return choice
def readMailFromInbox():
saySomething("Please wait while we load your mails from the inbox.")
ski... | This function provides an interactive menu for managing inbox emails, allowing users to read emails, search by sender address, or return to the previous menu. It handles user input, retrieves and displays email details, and exits the application if 'quit' is selected. | def inbox():
options = [
'Read Mail',
'Search Mail',
'Go Back',
]
while True:
choice = readMenuAndGetInput(options)
if (choice == 'read mail'):
readMailFromInbox()
elif (choice == 'search mail'):
from_address = getUserInput('Please prov... |
def CreateDeb(output,
data,
preinst=None,
postinst=None,
prerm=None,
postrm=None,
config=None,
templates=None,
conffiles=None,
**kwargs):
"""Create a full debian package."""
extrafiles = {}
... | The main task of the code is to generate a Debian package (.deb) and its associated .changes file using command-line arguments. It leverages parameters like output path, package metadata (name, version, maintainer), dependencies, and file configurations to construct the package and metadata file through CreateDeb and C... | def main(unused_argv):
CreateDeb(
FLAGS.output,
FLAGS.data,
preinst=GetFlagValue(FLAGS.preinst, False),
postinst=GetFlagValue(FLAGS.postinst, False),
prerm=GetFlagValue(FLAGS.prerm, False),
postrm=GetFlagValue(FLAGS.postrm, False),
config=GetFlagValue(FLAGS.config, False),
... |
def calc_amount_of_moves(self):
return sum([len(element[0]) for element in self.calc_all_moves()])
def get_turn(self):
return False if self.turn_count % 2 == 0 else True
def _move_validation(self, unit, dest):
#check turn, lastmovedcolor and possible move
if self.get_turn() == unit.playe... | This function handles a unit's movement on a board, validates the move, updates game state, checks win conditions (if a unit reaches the top/bottom row), and manages turn progression. It skips turns if no moves are possible and ends the game when a winning condition is met. | def move(self, unit=None, dest=None):
if self.game_over:
return False
#skips turn if unit stuck
if self.calc_amount_of_moves() == 0:
unit = [u for u in self.units[self.get_turn()] if u.color_index == self.last_moved_color][0]
self.last_moved_color = self.boa... |
def get_cash_value(self) -> float:
return self._value_helper(False)
def _get_volume(self, orders: OrderList) -> int:
volume = 0
for o in orders:
volume += o.num_shares
return volume
def _get_price(self, orders: OrderList) -> float:
price = 0
volume = self._get... | The function calculates the purchasing power by subtracting the total value of open orders (volume multiplied by price) from the available cash value, returning the result as a float. | def get_purchasing_power(self) -> float:
open_orders = list(filter(lambda o: o.order_status == _OrderStatus.OPEN, self.orders))
return self.get_cash_value() - (self._get_volume(open_orders) * self._get_price(open_orders)) |
def initialPopulation(popSize, cityList):
population = []
for i in range(0, popSize):
population.append(createRoute(cityList))
return population
def nextGeneration(currentGen, eliteSize, mutationRate):
popRanked = rankRoutes(currentGen)
selectionResults = selection(popRanked, eliteSize)
... | This code implements a genetic algorithm (GA) to optimize a route, likely for a Traveling Salesman Problem (TSP). It initializes a population, iterates through generations to evolve solutions using elitism and mutation, and outputs the best route found. The final best route and its inverse distance metric are written t... | def GA(inFile, population, popSize, eliteSize, mutationRate, generations):
pop = initialPopulation(popSize, population)
# print("Initial distance: " + str(1 / rankRoutes(pop)[0][1]))
for i in range(0, generations):
pop = nextGeneration(pop, eliteSize, mutationRate)
# print("Final dista... |
def import_places_csv_file(filepath):
if os.path.isfile(filepath):
with open(filepath, 'r') as file:
print('-' * 77)
print("Places list from file: " + filepath)
print('-' * 77)
csvreader = csv.reader(file)
next(csvreader)
places.clear()... | The code's main task is to handle command-line parameters for processing geographical data. If no argument is provided, it loads a fixed 'places.csv' file and calculates great-circle distances. If an integer argument is provided, it loads the same CSV, selects that many random places, and calculates distances. Invalid ... | def main():
argv = sys.argv[1:]
if len(argv) == 0:
print('No parameter found. System will parse the places.csv from fixed location.')
import_places_csv_file('places.csv')
calculate_great_circle_distance()
else:
try:
argument = int(argv[0])
print('Param... |
def is_youtube_url(url):
hostname = get_hostname(url)[0]
yt_hostnames = ["youtube", "youtu.be"]
for yt_hostname in yt_hostnames:
if yt_hostname in hostname:
return True
else:
return False
def get_yt_object(url):
hostname = get_hostname(url)[0]
if "spotify" in hostname... | The main task of the code is to download music from a given URL, convert it to MP3 format, extract metadata (duration, artist), store it in a database, and return the file path and metadata. It checks for existing downloads, handles YouTube and other sources, converts audio, and logs progress/errors. | def download_music(url):
try:
logging.info(f"Working directory - [{os.getcwd()}]")
m_info = dbHelper.MusicInfo()
logging.info(f"url [{url}]")
m_info.url = url
# check if we have already downloaded from this url
p_file_meta = dbHelper.is_music_present_in_db(url)
... |
def simulate_system_model(model, debug=0):
output_data = []
index_t_sens_delay = index_delta_get(model.delay)
s_pole_1 = -1/model.tau1
s_pole_2 = -1/model.tau2
s_zero_1 = -1/(model.dynamic_skew*(model.tau2 - model.tau1) + model.tau1)
if(debug):
print("s_pole_1: " + str(s_pole_1))
... | The code's main task is to optimize a refrigeration system model using Simulated Annealing by fitting parameters (delay, tau1, tau2, etc.) to reference data from a CSV file. It reads input data, runs optimization iterations with temperature adjustments, and outputs best-fit parameters and visualizations if debug mode i... | def main():
parser = argparse.ArgumentParser(
prog = 'System_Model_Calculator',
description = 'Calculate a refrigeration system model based on functional data',
epilog = 'Text at the bottom of help')
parser.add_argument('-i', '--input_file', default = ... |
def generate_list(self):
"""Generate the list of pages."""
f = StringIO()
# Sort and reverse the list of dates, so we have the newest
# first.
dates = self.output_files.keys()
dates.sort()
dates.reverse()
f.write('<ul class="paged_output_pages">\n')
for date in dates:
fn = self.output_files[date... | The function generates an output file by populating a template with dynamic content, including article data, item counts, and calendar information, then writes and renames the file. It retrieves template bits, fills them with values from `self.f`, article counts, and generated lists, applies the template, writes the re... | def write_output(self, rawdog, config):
"""Write out the current output file."""
bits = rawdog.get_main_template_bits(config)
bits["items"] = self.f.getvalue()
bits["num_items"] = str(len(rawdog.articles.values()))
bits["dated_output_pages"] = self.generate_list()
bits["dated_output_calendar"] = self.gener... |
def write_rss(self, rawdog, config, articles):
doc = Document()
rss = doc.createElement('rss')
rss.setAttribute('version', "2.0")
rss.setAttribute('xmlns:dc', "http://purl.org/dc/elements/1.1/")
rss.setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom')
doc.appendChil... | The code's main task is to generate and write three types of output files (RSS, FOAF, OPML) using the provided `rawdog`, `config`, and `articles` data. It delegates this to three separate methods (`write_rss`, `write_foaf`, `write_opml`) and returns `True` to indicate successful completion of the output writing process... | def output_write(self, rawdog, config, articles):
self.write_rss(rawdog, config, articles)
self.write_foaf(rawdog, config)
self.write_opml(rawdog, config)
return True |
def _get_domain(self, domain: str) -> Any:
"""Get mapping of domain to the strata results."""
strata_var = "_strata_var_mod"
# create key form population file
pop = self.pop_data[[strata_var, domain]]
aggregated = pop.groupby(strata_var)[domain].agg(list)
domain_key = a... | This function generates domain-specific estimates (e.g., means, totals) with uncertainty measures (variance, CV, SE, CI) from a previously run statistical model. It handles robust or standard variance estimation, aggregates results by domain, and returns a structured DataFrame containing estimates, sample sizes, and un... | def get_estimates(
self,
domain: str = "",
uncertainty_type: str = "CV",
variance_type: str = "robust",
return_type: str = "unbiased",
) -> pd.DataFrame:
"""Get estimates for previously run model within strata or domains. Variance and CV estimates are returned for eac... |
def _global_avg(inputs, pool_size, strides, padding='valid', name='global_avg'):
return tf.layers.average_pooling2d(inputs, pool_size, strides,
padding=padding, data_format='channels_last', name=name)
def _fully_connected_layer(inputs, units, name="fc", activation=None, use_bi... | This function implements a Squeeze-and-Excitation (SE) block for channel-wise feature recalibration. It compresses input spatial dimensions via global average pooling, generates channel-wise weights through two fully connected layers with ReLU6 and hard sigmoid activations, then reshapes and multiplies these weights wi... | def _squeeze_excitation_layer(input, out_dim, ratio, layer_name, is_training=True, reuse=None):
with tf.variable_scope(layer_name, reuse=reuse):
squeeze = _global_avg(input, pool_size=input.get_shape()[1:-1], strides=1)
excitation = _fully_connected_layer(squeeze, units=out_dim / ratio, name=layer_... |
def is_training(self):
"""Returns true if the model is built for training mode"""
return self.mode == 'train'
def hard_swish(x, name='hard_swish'):
with tf.variable_scope(name):
h_swish = x * tf.nn.relu6(x + 3) / 6
return h_swish
def _make_divisible(v, divisor=8, min_value=None):
if ... | The code constructs a BiSeNet model for semantic segmentation by integrating spatial and contextual feature paths. It builds a spatial path with convolutions and depthwise separable layers, a context path via a frontend builder, and combines them using Attention Refinement Modules (ARM) and a Feature Fusion Module (FFM... | def build_bisenet_custom(self, reuse=False):
"""
Builds the BiSeNet model.
Arguments:
reuse: Reuse variable or not
Returns:
BiSeNet model
"""
### The spatial path
### The number of feature maps for each convolution is not specified in the pap... |
def build_inputs(self):
"""Input fetching and batching
Outputs:
self.images: image batch of shape [batch, hz, wz, 3]
labels: image batch of shape [batch, hx, wx, num_classes]
"""
if self.mode in ['train', 'validation', 'test']:
# Put data loading and prep... | This code creates TensorFlow operations for training and evaluation, setting up model architectures (Bisenet or custom), loss calculations, and summaries across multiple GPUs. It handles variable reuse, device placement, and mode-specific tasks like prediction, while initializing the global step for training. | def build(self, num_gpus=1, reuse=False):
"""Creates all ops for training and evaluation"""
with tf.name_scope(self.mode):
if self.mode in ['train', 'validation', 'test']:
tower_losses = []
for i in range(num_gpus):
self.build_inputs()
... |
def year_range():
# Creating a list and acquiring the search criteria (A start year and an ending year)
book_list = []
start_year = get_typed_input("Enter beginning year of search: ", 'int')
end_year = get_typed_input("Enter end year of search: ", 'int')
# Finding books that were bestsellers betwee... | The main task of the code is to display a menu-driven user interface for data lookup options (year range, month/year, author, title) and route user selections to corresponding functions. It handles input validation, executes chosen actions, and returns True/False to control program flow, with "Q" exiting the program. | def print_dashboard():
# Printing the user interface
print("""
Please choose an option
1: Look up year range
2: Look up month/year
3: Search for author
4: Search for title
Q: Quit
""")
# Obtaining what function the user wants to input
user_selection = input(" ")
... |
def sum_and_average():
print("Please enter two numbers")
# Obtaining the variables (num1 and num2)
num1 = get_typed_input("First Number: ", "float")
num2 = get_typed_input("Second Number: ", "float")
# Calculating the sum and the average of the numbers
sum_numbers = (num1 + num2)
average =... | The main task of the code is to display a menu of functions for user selection, handle input choices, and execute corresponding operations like calculating sums, averages, max/min values, geometric properties, or string info. It returns True to continue the loop or False to exit, with error handling for invalid inputs. | def print_dashboard():
# Printing the user interface
print("[1] Sum and Average of Two Numbers")
print("[2] Maximum and Minimum of 5 Numbers")
print("[3] Area and Perimeter of a Rectangle")
print("[4] Sum and Product of first N Natural Number")
print("[5] String Info")
print("[6] Calculator"... |
def get_car_info():
make = get_typed_input("What make is the car?", 'str')
model = get_typed_input("What model is the car?", 'str')
year = get_typed_input("What year is the car?", 'int')
license_plate = get_typed_input("What is the license plate?", 'str')
car_info = f'{make}/{model}/{year}/{license_... | The code defines a function `print_dashboard()` that displays a menu for a car management system, allowing users to add a car, list cars, find a car, or exit. It captures user input, executes corresponding actions, and returns `True`/`False` based on the selection. | def print_dashboard():
# Printing the user interface
print("""
==============================
Choose 1-4 or 0 to exit
------------------------------
[1] Add Car
[2] List Cars
[3] Find Car
[0] Exit
==============================
""")
# Obtaining what function the user wan... |
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
data = data.view(data.size(0),28*28)
# normal loss
optimizer.zero_grad()
loss... | The code trains a neural network model using stochastic gradient descent, evaluates its performance on standard and adversarial test sets, and saves the model with the highest adversarial accuracy. It iterates over epochs, printing training loss/accuracy and adversarial loss/accuracy, while updating the model if advers... | def train_model():
model = Net().to(device)
################################################################################################
## Note: below is the place you need to edit to implement your own training algorithm
## You can also edit the functions such as train(...).
######... |
def checkLevelEnd(self):
for door in self.doors:
if door.update(self.player.rect()):
self.end = True
if self.end == True:
self.transition += 1
if self.transition > 30:
self.level = min(self.level + 1, len(os.listdir("data/maps")) - 1)
... | This code runs a game loop that initializes audio, handles player physics with gravity, scrolls the camera based on player movement, renders game elements (tilemap, enemies, projectiles, particles), applies visual effects (screenshake, transitions), and updates the display at 60 FPS. It also manages sound, collision ch... | def run(self):
pygame.mixer.music.load("data/music.wav")
pygame.mixer.music.set_volume(0.5 * self.sound_factor)
pygame.mixer.music.play(-1)
self.sfx["ambience"].play(-1)
while True:
self.checkLevelEnd()
player = self.gravity.setGravity(self.frame, self.pla... |
def target_update(self):
self.target_model.set_weights(self.online_model.get_weights())
def choose_act(self, state, epsilon=0.01):
nn_input = np.array(state)[None]
q_value = self.online_model(nn_input, training=False)
if random.random() <= epsilon:
return random.randint(0, se... | This function trains a reinforcement learning agent for one episode by interacting with the environment, collecting experiences, and updating the model using a replay buffer. It accumulates rewards, renders the environment if enabled, and periodically saves the model once the replay buffer reaches a threshold. The agen... | def train_episode(self, env, task: Task, epsilon=0.0):
if self.global_step == 0:
self.target_update()
done, score, state = False, 0, env.reset()
while not done:
action = self.choose_act(state, epsilon)
next_state, reward, done, _ = env.step(action)
... |
def eatAll(x,ls):
for i in range(0,1):
if len(x) == 0:
return ""
while x[-i] in ls:
if i == 0:
x = x[1:]
else:
x = x[:-1]
if len(x) == 0:
return ""
return x
def boolIt(x):
if str(... | The main task of the code is to generate a Python function definition string from input data. It processes a list of key-value pairs, normalizes them into a dictionary, and constructs a return statement using these values. The function builds a dynamically generated function that incorporates the processed data into it... | def mkReturnls(ls):
name,sgName,ls = ls
n,js = '',{}
for i in range(0,len(ls)):
spl = fun.mkLs(ls[i].replace(' =','=').replace('= ','=').split('='))
js[eatAll(spl[0],['"',"'"])] = ""
if '=' in ls[i]:
js[eatAll(spl[0],['"',"'"])] = boolIt(spl[1])
n = mkJsReturn(n,s... |
def new_word(self):
"""
Generates a new random word. The length of the word is based on the number of the players.
The more the players are, the longer the word is.
"""
for case in Game.min_letters_map:
if len(self.player_list) <= int(case):
self.choos... | The main task of the code is to coordinate the game loop, handle user input, update game state, render graphics, and manage player turns, win/loss conditions, and score tracking in a hangman game using Pygame, with FPS control and event processing for letters, exits, and restarts. | def main_loop(self, fps):
"""
Coordinates everything that happens during the game and calls all the
functions responsible for drawing, text, input, and scores.\n
@param fps: The number of Frames Per Second.
"""
self.new_word()
self.gallow.pre_load_gallow_parts()
... |
def __make_files_section(self):
_r = self.read
_dbd = _r.readfile
_dbd['__files'] = []
_r.write(_dbd)
def __make_files_section_server(self):
_dbd = self.__CRead()
_dbd['__files'] = []
self.__CWrite(_dbd)
def getFile(self, _filter:dict={}, returnType:str='dict'):
'''
... | The code removes a file from a local or cloud database using a filter (name or filename). It checks the host type, ensures the files section exists, locates the file, removes it from the database, and writes changes. If no filter is provided, all files are deleted. | def removeFile(self, _filter:dict):
'''
Remove a file from db
removing using `name`:
>>> db.files.removeFile({'name': 'Logo'}) # "name" is A name was given when appending the file
removing using `filename`:
>>> db.files.removeFile({'filename': 'logo.png'}) # must add extension
... |
def listen():
for events in pygame.event.get():
if events.type == pygame.QUIT:
return("quit")
if events.type == pygame.MOUSEBUTTONDOWN:
return("clicked")
def intro_page(win, listen_out):
win.fill(BLACK)
intro_text = TEXT_FONT.render('How would you like to play?', True... | The code runs a game loop where players or AI take turns placing marks on a board, checking for wins/ties, and displaying results. It initializes game settings, alternates turns, uses AI for optimal moves, detects player clicks, and shows intro/ending screens. | def main():
run = True
min_player = None
over = False
turn = 1
while run:
listen_out = listen()
if min_player is None:
min_player = intro_page(WIN, listen_out)
if min_player == 1: max_player = 2
elif min_player == 2: max_player = 1
else:
... |
def _database_found(self):
return len(self.databases) > 0
def _get_database_metadata(self):
response = self._get_subscriptions()
if "subscriptions" not in response:
return
for subscription in response["subscriptions"]:
if self._database_found():
re... | The code fetches and updates database metrics by checking if the database is found or if a refresh interval is reached. If not found or after interval, it retrieves metadata, resets counters, and updates the database list. It increments a fetch counter and returns the latest database statistics. | def fetch_database_metrics(self):
if not self._database_found():
self._get_database_metadata()
elif self.fetch_count > REFRESH_STAT_INTERVAL:
self.fetch_count = 0
self.databases = []
self._get_database_metadata()
self.fetch_count += 1
retur... |
def input(self, events):
self.frameAdvance = False
for event in events:
if event.type == QUIT:
sys.exit(0)
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
sys.exit(0)
if self.gameState == 'playing':
... | The code implements a game loop that handles input, updates game state, renders graphics, and calculates FPS. It maintains a constant frame rate (60 FPS), processes events, manages game states (playing, exploding, paused), updates sprites, checks scores, and displays relevant UI elements like the score and FPS for debu... | def playGame(self):
clock = pygame.time.Clock()
frameCount = 0.0
timePassed = 0.0
self.fps = 0.0
# Main loop
while True:
# calculate fps
timePassed += clock.tick(60)
frameCount += 1
if frameCount % 10 == 0: # every 10 fr... |
def regexClean(self,value):
value = re.sub(":\([0-9]\):",":0\1:",value)
value = re.sub("-\([0-9]\):","-0\1::",value)
value = re.sub("Times.*","Times",value)
value = value.replace('\r', '')
return value
def firstrow(self,row):
feature_dict = dict()
is_first = False... | The code reads a CSV file (or provided contents) to parse and process data about people, mentors, and mentees. It cleans the input, extracts features from the first row, populates a data structure (`peopleHash`) with entries, and calculates a target group size based on the mentor-mentee ratio. The main task is to parse... | def readfile(self,filename,contents=None):
self.peopleHash = {}
self.num_mentors = 0
is_first = True
spamreader = contents
# If we have the contents of the file instead of the filename, convert file to something we can use
if contents is None:
csvfile = ope... |
def find_target_size_clusters(self,pasttries=[]):
str_time = None
key = None
clusters = []
for g in self.graph.keys():
possible_times = self.graph[g]
for e in possible_times:
nodes = [n for n in e["PeopleAvailiable"] if n.isOpen == True]
m... | The code optimizes group formation using a generational algorithm, iteratively finding clusters in a graph to create groups of target size. It employs a greedy approach, pruning the search space, and stopping when scores plateau or a generation cap is reached. The best group configuration is identified, updated, and ou... | def run(self,generation_cap=500,mentors_per_group=1,web=False):
print(self.uw,self.gsw,self.ngw,self.fw )
# Lets use a greedy approach at the beginning in order to find groups. We will look for the largest clusters
# in the graph and remove them.
# First, we need to define a condition t... |
def hidden_out(feature, center, delta):
m, n = shape(feature)
m1, n1 = shape(center)
hidden_out = mat(zeros((m, m1)))
for i in range(m):
for j in range(m1):
#gaus
hidden_out[i, j] = exp(-1.0 * (feature[i, :] - center[j, :]) * (feature[i, :] - center[j, :]).T / (
... | This code trains a radial basis function (RBF) neural network by iteratively updating hidden layer centers (center), widths (delta), and output weights (w) using gradient descent. It initializes parameters with scaled random values, computes hidden layer outputs, predicts labels, calculates errors, and adjusts paramete... | def bp_train(feature, label, n_hidden, maxCycle, alpha, n_output):
m, n = shape(feature)
center = mat(random.rand(n_hidden, n))
center = center * (8.0 * sqrt(6) / sqrt(n + n_hidden)) - mat(ones((n_hidden, n))) * (
4.0 * sqrt(6) / sqrt(n + n_hidden))
delta = mat(random.rand(1, n_hidden))
... |
def __delta_process(a: float, b: float, c: float) -> float:
return (b * b) - (4 * a * c)
def __opti_fraction(number: float) -> str:
sign = "" if number > 0 else "- "
number = abs(round(number, 5))
number2 = 10
for i in range(len(str(number)[str(number).find('.'):]) - 1):
number2 *= 10
nu... | This function solves a quadratic equation $ ax^2 + bx + c = 0 $ by computing its discriminant (delta). It returns the roots based on delta's value: complex roots when delta < 0, a single real root when delta = 0, and two real roots when delta > 0. The results are formatted as strings, with optimized fractions and round... | def __find_complexe_solution(a: float, b: float, c: float):
delta = __delta_process(a, b, c)
if delta < 0:
sol1 = f"(- {b} - i√{delta}) / {2 * a}"
sol2 = f"(- {b} + i√{delta}) / {2 * a}"
print(f"Delta = {delta} < 0 so there's two solutions.\nThe solutions of the equation are : X1 = {sol1... |
def __check_degree(tokens_list: List[PolyRows]):
for token in tokens_list:
if token.degree > 2 or token.degree < 0 or "." in str(token.degree):
token.create_term(token.position)
raise ParserError(
f"The degree must be inferior or equal to 2, here : {token.degree} in t... | The main task of the code is to parse a list of polynomial terms (`tokens_list`), extract coefficients (`a`, `b`, `c`) based on their degree (quadratic, linear, or constant), and determine whether to solve a quadratic equation (if `a ≠ 0`) or a simpler equation (if `a = 0`). It returns the coefficients `[a, b, c]` for ... | def resolver(tokens_list: List[PolyRows]) -> list:
__check_degree(tokens_list)
a = 0
b = 0
c = 0
for token in tokens_list:
if token.degree == 2:
a = token.coef if token.operator == "+" else -1 * token.coef
elif token.degree == 1:
b = token.coef if token.operat... |
def __print_row_equation(message: str, token_equations: List[PolyRows], argv, end=" = 0.0"):
if not __change_equation(token_equations) or "-d" not in argv:
return
color = ['\033[0m', '\033[91m', '\033[92m', '\033[94m']
if end == "red":
end = color[1] + " = 0.0"
print(color[3] + f"{messag... | The main task of the code is to process and simplify a polynomial equation by filtering out zero coefficients, applying arithmetic operations (multiplication/division first, then addition/subtraction), moving all terms to one side, sorting tokens by degree, and resolving the simplified equation. It prints intermediate ... | def process_equation(tokens_list: List[PolyRows], argv):
__print_row_equation("Red for modification and green for the movement of the token.\nThe full equation refactored", tokens_list, argv, "")
tokens_list = [token for token in tokens_list if token.coef != 0]
tokens_list = __reset_position(tokens_list)
... |
def deck_open_spaces(self):
open_spaces = []
for i in range(len(self.cards)):
if np.equal(self.cards[i], 1):
open_spaces.append(i)
return open_spaces
def board_open_spaces(self):
open_board_spaces = []
for i in range(5):
for j in range(5):
... | The code implements a game step where an agent selects a card from the deck and places it on the board. It validates the move, updates the game state, calculates rewards for valid moves or penalties for invalid ones, and checks if the game is complete. The function returns the updated observation, reward, termination s... | def step(self, action: list):
# set a max turn count
self.reward = 0
action[0] = max(0, min(action[0], len(self.deck_open_spaces())-1))
action[1] = max(0, min(action[1], len(self.board_open_spaces())-1))
card = self.deck_open_spaces()[action[0]]
grid_space = self.board_... |
def get_enemy(player):
if player == 10:
return 20
else:
return 10
def get_player_positions(board, player):
pos = []
for r in range(8):
for i in range(8):
if get_player(board[get_index(r, i)]) == player:
pos += [get_index(r, i)]
return pos
def get_p... | The main task of the code is to determine if a specified position on a board is under threat from any of the enemy player's pieces. It checks each enemy piece's potential moves (pawn captures or general legal moves) to see if they can attack the given position, returning `True` if threatened, otherwise `False`.)> | def is_position_under_threat(board, position, player):
enemy = get_enemy(player)
for p in get_player_positions(board, enemy):
if get_piece(board[p]) == get_piece_value("PAWN"):
pos = get_pawn_capture_moves(board, p)
else:
pos = get_piece_legal_moves(board, p)
for ... |
def get_piece(space):
return space % 10
def gen_board():
board = [0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
... | This function calculates a piece's mobility factor by comparing its current legal moves on the board to its maximum potential moves on a standard board configuration, returning the ratio of actual moves to possible moves. | def get_piece_mobility_factor(board, position):
piece = get_piece(board[position])
b_board = gen_board()
b_board[get_index(3, 3)] = piece + 10
max_moves = get_piece_legal_moves(b_board, get_index(3, 3))
moves = get_piece_legal_moves(board, position)
return len(moves) / len(max_moves) |
def get_player_positions(board, player):
pos = []
for r in range(8):
for i in range(8):
if get_player(board[get_index(r, i)]) == player:
pos += [get_index(r, i)]
return pos
def get_player_value(name):
if name == "WHITE":
return 10
if name == "BLACK":
... | The main task of the code is to evaluate a game board's score by summing the weighted values of all white pieces and their mobility, while subtracting the weighted values of all black pieces and their mobility. This provides a strategic assessment of the board state, favoring positions with higher material value and gr... | def eval_board_2(board):
white_pos = get_player_positions(board, get_player_value("WHITE"))
black_pos = get_player_positions(board, get_player_value("BLACK"))
score = 0
for pos in white_pos:
score += get_piece_weight(get_piece(board[pos])) + 0.1 * len(get_piece_legal_moves(board, pos))
for p... |
def get_player_positions(board, player):
pos = []
for r in range(8):
for i in range(8):
if get_player(board[get_index(r, i)]) == player:
pos += [get_index(r, i)]
return pos
def get_piece_legal_moves(board, position):
pos = []
player = get_player(board[position])
... | The code generates all legal moves for a player's pieces on a board and separates those that do not leave the player's pieces under threat. It returns two lists: one with non-losing moves (safe positions) and another with all possible legal moves. | def get_player_moves_list(board, player):
pos = get_player_positions(board, player)
non_losing_moves = []
all_moves = []
for source in pos:
moves = get_piece_legal_moves(board, source)
for move in moves:
all_moves += [[source, move]]
if not (is_position_under_thre... |
def get_player_positions(board, player):
pos = []
for r in range(8):
for i in range(8):
if get_player(board[get_index(r, i)]) == player:
pos += [get_index(r, i)]
return pos
def get_piece(space):
return space % 10
def get_piece_value(name):
if name == "PAWN":
... | The function checks if a player's king is in checkmate by verifying if all of the king's legal moves are under threat, returning True if no escape is possible and False otherwise. | def is_checkmate(board, player):
positions = get_player_positions(board, player)
for p in positions:
if get_piece(board[p]) == get_piece_value("KING"):
if is_position_under_threat(board, p, player):
for move in get_piece_legal_moves(board, p):
if not is_po... |
def get_player_positions(board, player):
pos = []
for r in range(8):
for i in range(8):
if get_player(board[get_index(r, i)]) == player:
pos += [get_index(r, i)]
return pos
def get_player_value(name):
if name == "WHITE":
return 10
if name == "BLACK":
... | The main task of the code is to evaluate a board's score by calculating the weighted sum of piece mobility factors for white and black players. It adds mobility-adjusted values for white pieces and subtracts them for black pieces, returning the net score to assess positional advantage. | def eval_board_1(board):
white_pos = get_player_positions(board, get_player_value("WHITE"))
black_pos = get_player_positions(board, get_player_value("BLACK"))
score = 0
for pos in white_pos:
piece = get_piece(board[pos])
score += get_piece_mobility_factor(board, pos) * (piece + 10)
f... |
def get_player_moves_list(board, player):
pos = get_player_positions(board, player)
non_losing_moves = []
all_moves = []
for source in pos:
moves = get_piece_legal_moves(board, source)
for move in moves:
all_moves += [[source, move]]
if not (is_position_under_thre... | The function identifies the best non-losing move for a player by evaluating each possible move's resulting board state. It iterates through non-losing moves, simulates each move, scores the board, and selects the move yielding the highest score using a max selection strategy. The goal is to choose the optimal immediate... | def gen_reflex_agent_move(board, player):
non_losing_moves, all_moves = get_player_moves_list(board, player)
best = -float("inf")
move = []
for source, target in non_losing_moves:
score = eval_board_2(make_test_board(board, source, target))
best, move = get_max_or_min(best, score, move, ... |
def get_enemy(player):
if player == 10:
return 20
else:
return 10
def get_player_moves_list(board, player):
pos = get_player_positions(board, player)
non_losing_moves = []
all_moves = []
for source in pos:
moves = get_piece_legal_moves(board, source)
for move in m... | The function builds a game tree up to a specified depth by recursively generating all possible game states for a player and their opponent. It starts with the current player's moves, creates child nodes for each move's resulting board state, and alternates to the enemy player for deeper levels. The recursion stops at l... | def build_game_tree(player, game_tree: Tree, levels):
if levels == 3:
return True
else:
enemy = get_enemy(player)
board = game_tree.get_val()[0]
non_losing_moves, all_moves = get_player_moves_list(board, player)
for move in all_moves:
game_tree.add_child([make... |
def get_player_moves_list(board, player):
pos = get_player_positions(board, player)
non_losing_moves = []
all_moves = []
for source in pos:
moves = get_piece_legal_moves(board, source)
for move in moves:
all_moves += [[source, move]]
if not (is_position_under_thre... | The function checks if a chess game is a draw by verifying if both players have no available moves and neither is in checkmate, returning True if conditions are met, otherwise False. | def is_draw(board):
if 0 == len(get_player_moves_list(board, get_player_value("WHITE"))) == \
len(get_player_moves_list(board, get_player_value("BLACK"))) and not \
is_checkmate(board, get_player_value("WHITE")) and not is_checkmate(board, get_player_value("BLACK")):
return True
... |
def get_enemy(player):
if player == 10:
return 20
else:
return 10
def get_player_value(name):
if name == "WHITE":
return 10
if name == "BLACK":
return 20
def is_checkmate(board, player):
positions = get_player_positions(board, player)
for p in positions:
i... | This function implements the minimax algorithm for a game tree, determining the optimal move for a player by recursively evaluating all possible future moves. It checks terminal states (leaf nodes, checkmate, draw) and calculates scores using `eval_board_2`. For non-terminal nodes, it selects the best child node based ... | def minimax(node: Tree, player):
enemy = get_enemy(player)
is_max = player == get_player_value("WHITE")
if node.is_leaf() or is_checkmate(node.get_val()[0], player) or is_checkmate(node.get_val()[0], enemy) or is_draw(
node.get_val()[0]):
max_score = eval_board_2(node.get_val()[0])
... |
def loadTestData():
fileinput = str(input("Enter Test File Path:"))
# READ noMeal data
dfDataNoMeal = pd.DataFrame();
dfDataTemp = pd.read_csv(fileinput, usecols=[i for i in range(30)],
header=None)
dfDataNoMeal = dfDataNoMeal.append(dfDataTemp, ignore_index='true')... | The main task of the code is to perform batch predictions using multiple pre-trained models on scaled test data. It loads four models from pickle files, applies each to the scaled test features, saves the predicted labels as CSV files, and prints model details and results. The process involves data loading, scaling, fe... | def prediction_method():
dfTestData = loadTestData()
scaledTestData = stdScale(dfTestData)
scaledTestDataDF = pd.DataFrame(data=scaledTestData)
XTest = calcFeaturesDF(scaledTestDataDF, scaledTestData)
for index in range(4):
clf=""
with open("model"+str(index)+".pkl", 'rb') as f... |
def _compute_loop(self):
"""
Compute the coordinates of the coronal loop based on the current slider values.
"""
loop, self.loop_length = semi_circle_loop(self.radius, self.height, self.theta0, self.phi0, self.el, self.az,
int(self.sample... | The code initializes a `CoronalLoopBuilder` class to create and visualize semi-circular solar coronal loops. It sets default parameters (radius, height, angles) and stores them as attributes. It computes loop coordinates, plots them on provided axes using dummy maps, and initializes interactive sliders/toggle buttons f... | def __init__(self, fig, axs, dummy_maps, **kwargs):
"""
Initialize the CoronalLoopBuilder with given parameters and create the initial visualization.
Parameters:
- fig: The figure object.
- axs: The axes object.
- dummy_maps: Dummy maps for demonstration.
- radiu... |
def _print_text_primary(self, x, y, text, color=None):
self._print_text(self.font_primary, x, y, text, color)
def _draw_secondary(self):
# secondary text
text = "Earlier feeding times are:"
x_line, y_line = self._secondary_text_location_x, self._secondary_text_location_y
self._pr... | This method displays a confirmation prompt on the screen to erase the most recent feeding time, showing the time to be erased and requiring the user to press LCTRL+Z to confirm. If confirmed, it triggers the erasure and briefly pauses execution. | def erase_most_recent_feeding_time_with_confirmation(self) -> None:
self.screen.fill(self.black)
text = "Erasing most recent feeding time"
x_line, y_line = self._warning_text_location_x, self._warning_text_location_y
self._print_text_primary(x_line, y_line, text, color=self.red)
... |
def save_feeding_time(self, feeding_time: datetime) -> None:
pass
def get_past_feeding_times(self) -> List[datetime]:
"""return past few feeding times in sorted order"""
pass
def calculate_next_feeding_time(self, last_time: datetime) -> datetime:
pass
def erase_most_recent_feeding_time_w... | The code runs a Pygame loop to manage a feeding schedule interface. It captures user inputs (QUIT, ESC, SPACE, LCTRL) to exit, log feeding times, erase recent entries, and display data. It fetches past feeding times, calculates the next scheduled time, and updates the screen with visual elements. The loop continuously ... | def run(self):
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
self.screen.fill((0, 0, 100))
sys.exit()
... |
def remove_from_pool(self,transactions_list):
seen = set()
for t in transactions_list:
seen.add(t.make_hash().hexdigest())
temp_pool = []
for t in self.transaction_pool:
if t.make_hash().hexdigest() not in seen:
temp_pool.append(t)
self.transaction_pool = temp_pool
def process_transaction(... | The function `receive_block` validates a newly received block against the last block in the chain using specified difficulty. If valid, it processes transactions by returning unmined ones to the pool, removes duplicates, executes transactions while checking for errors, and appends the block to the chain. If invalid, it... | def receive_block(self):
last_block = self.chain[-1]
block = self.new_block
validated = block.validate_block(last_block,self.difficulty)
if validated == 0:
#put unmined transactions back to pool
print("validated")
self.curr_block.listOfTransactions.reverse() #must be placed back with the orde... |
def mine_block(self):
#mine the current block
nonce = 0
prefix = '0'*self.difficulty
solved = False
while not self.block_received:
self.curr_block.set_nonce(nonce)
h = self.curr_block.make_hash()
if h.startswith(prefix):
solved = True
print("Block mined: ",h)
break
# nonce = random.... | The code's main task is to continuously mine blocks by processing transactions from the transaction pool, handling received blocks, and maintaining the blockchain. It checks if the current block is full, initiates mining, appends valid blocks to the chain, broadcasts them, updates UTXOs, and creates new blocks iterativ... | def mining_loop(self):
# self.create_new_block(self.chain[-1])
while True:
if not self.block_received:
if len(self.curr_block.listOfTransactions) == self.capacity:
print("DAEMON:starting mining..")
res = self.mine_block()
if res == 0:
self.chain.append(self.curr_block)
... |
def drawRadar(self):
for x in range(self.radarSize, 0, -100):
self.drawArcFromBottom(x, x)
for x in range(0, 180+1, 30):
self.drawLineFromBottom(x, self.radarSize / 2, "white", 1)
self.drawTextFromBottom(x, self.radarSize / 2, str(x)+u"\u00b0")
def drawNeedle(self):... | The main task of the code is to continuously update a graphical interface by clearing the canvas, redrawing radar elements, a needle, and data, then rescheduling itself using `after()` to create an animation loop at specified intervals. | def update(self):
Canvas.clearCanvas(self.myCanvas)
self.drawRadar()
self.drawNeedle()
self.drawData()
self.root.after(self.refreshInterval, self.update) |
def get_scope(args):
if args.scope is None:
print ('--scope required for parse_scope')
exit(1)
return read_scope_file(args.scope)
def get_pt_domains(ip_or_ips_list):
if isinstance(ip_or_ips_list,list):
#domains = [get_pt_domains_single_ip(ip) for ip in ip_or_ips_list]
... | This code defines a command-line tool with multiple modes for processing domains and IPs. The main task is to parse scope files, resolve domains to IPs, filter results based on scope, generate HTTP URLs for testing tools like dirsearch/ffuf, and strip subdomains from domain names. The tool uses argparse for input handl... | def main():
modes = ['parse_scope','reverse','resolve','build_http','strip_domains']
parser = argparse.ArgumentParser()
parser.add_argument("mode", help="mode - one of %s"%str(modes), choices= modes)
parser.add_argument("-s","--scope", help = "scope file")
parser.add_argument("-d","--domains", he... |
def read_inputs(features_filename, targets_filename):
# Read regression features
with h5py.File(features_filename, 'r') as Xs_file:
Xs = np.array(Xs_file['responses'])
# Read regression targets
with h5py.File(targets_filename, 'r') as y_file:
y = np.array(y_file['feats'])
# Normalize BOLD data
Xs = (Xs - ... | The code tests a linear model by loading its weights and bias, making predictions on test data, handling convolution artifacts if present, trimming predictions, and evaluating performance metrics both before and after inducing sparsity by zeroing negative values. | def test_linear(model_filename, features_filename):
""" Tests a linear model."""
print('Testing model', model_filename[:-3])
# Read features and targets
X_test, y_test = read_inputs(features_filename, 'test_feats.h5')
# Read model
with h5py.File(model_filename, 'r') as model_file:
weights = np.array(model_fi... |
def read_inputs(features_filename, targets_filename):
# Read regression features
with h5py.File(features_filename, 'r') as Xs_file:
Xs = np.array(Xs_file['responses'])
# Read regression targets
with h5py.File(targets_filename, 'r') as y_file:
y = np.array(y_file['feats'])
# Normalize BOLD data
Xs = (Xs - ... | The function tests a neural network model by loading its weights and biases, making predictions on test data, and evaluating performance. It handles convolutional models by deconvolving predictions using estimated SNR from training data, trims outputs to avoid artifacts, and reports metrics before/after inducing sparsi... | def test_neural_network(model_filename, features_filename):
""" Test the neural network models. """
print('Testing model', model_filename[:-3])
# Read features and targets
X_test, y_test = read_inputs(features_filename, 'test_feats.h5')
# Read model
with h5py.File(model_filename, 'r') as model_file:
weights_... |
def get_stim_data(stim_path: StimPathOrDataset, **kwargs) -> h5py.File | dict:
if isinstance(stim_path, h5py.File):
return stim_path
if isinstance(stim_path, Mapping): # ie. from pkl file
return dict(stim_path)
path = npc_io.from_pathlike(stim_path)
if path.suffix in (".hdf5", ".h5"):
... | This function calculates the estimated times (in seconds) when `getInputData()` was called during a psychopy experiment, relative to the experiment's start. It uses either cumulative frame intervals (if no sync data is provided) or preceding vsync times (if sync data is given) to generate a timestamp array. The output ... | def get_input_data_times(
stim: StimPathOrDataset,
sync: npc_sync.SyncPathOrDataset | None = None,
) -> npt.NDArray[np.float64]:
"""Best-estimate time of `getInputData()` in psychopy event loop, in seconds, from start
of experiment. Uses preceding frame's vsync time if sync provided"""
stim = get_st... |
def get_stim_data(stim_path: StimPathOrDataset, **kwargs) -> h5py.File | dict:
if isinstance(stim_path, h5py.File):
return stim_path
if isinstance(stim_path, Mapping): # ie. from pkl file
return dict(stim_path)
path = npc_io.from_pathlike(stim_path)
if path.suffix in (".hdf5", ".h5"):
... | This function estimates the time of the `flip()` call at the end of a Psychopy event loop, in seconds from the experiment's start, using vsync synchronization data. It processes stimulus frame intervals from an HDF5 file, either calculating flip times directly from frame intervals when no sync data is provided or lever... | def get_flip_times(
stim: StimPathOrDataset,
sync: npc_sync.SyncPathOrDataset | None = None,
) -> npt.NDArray[np.float64]:
"""Best-estimate time of `flip()` at end of psychopy event loop, in seconds, from start
of experiment. Uses frame's vsync time sync provided."""
stim = get_stim_data(stim)
a... |
def get_stim_data(stim_path: StimPathOrDataset, **kwargs) -> h5py.File | dict:
if isinstance(stim_path, h5py.File):
return stim_path
if isinstance(stim_path, Mapping): # ie. from pkl file
return dict(stim_path)
path = npc_io.from_pathlike(stim_path)
if path.suffix in (".hdf5", ".h5"):
... | (This function calculates the best-estimate timing of monitor updates for visual stimuli. If synchronization data is provided, it uses photodiode signals for precise timing; otherwise, it returns basic frame times. It processes HDF5 stimulus files, asserting valid data types and structure, then returns an array of floa... | def get_vis_display_times(
stim: StimPathOrDataset,
sync: npc_sync.SyncPathOrDataset | None = None,
) -> npt.NDArray[np.float64]:
"""Best-estimate time of monitor update. Uses photodiode if sync provided. Without sync, this equals frame times."""
stim = get_stim_data(stim)
assert isinstance(stim, h5... |
def naivBaies(fileName, type, additiveType, a):
# init
hamTestNr = 0
spamTestNr = 0
falseNeg = 0
falsePoz = 0
nr = 0
f = open(fileName, 'r')
# train
for line in f:
wordsNrDict.clear()
pHamDict.clear()
pSpamDict.clear()
nr+=1
line = line.stri... | The main task of the code is to execute multiple experiments using a Naive Bayes implementation ("naivBaies") on training/test datasets with varying configurations: different smoothing parameters (0, 1, 0.1, 0.01) and model types ("train" vs. "additiv"). It also performs 5-fold cross-validation on the training data and... | def main():
naivBaies("train.txt", 'TRAIN', 'train', 0)
naivBaies("test.txt", 'TEST', 'train', 0)
naivBaies("train.txt", 'TRAIN', 'additiv', 1)
naivBaies("test.txt", 'TEST', 'additiv', 1)
naivBaies("train.txt", 'TRAIN', 'additiv', 0.1)
naivBaies("test.txt", 'TEST', 'additiv', 0.1)
naivBaies(... |
def checkGameStatus(board):
if any(2048 in row for row in board):
return 1
elif not any(0 in row for row in board) and not checkMovesExist(board):
return -1
return 0
def best_move(board):
all_moves = [left, up, down, right]
results = []
for move in all_moves:
board1, move... | The code automates playing the 2048 game by repeatedly applying the best move strategy until the game is won (reaching 2048) or lost (no valid moves). It tracks the number of moves, checks game status after each move, and displays the board and result when the game ends. | def play2048(board):
won = checkGameStatus(board)
moves = 0
while won == 0:
saved_borad = board.copy()
moves += 1
board = best_move(board)
won = checkGameStatus(board)
if won == 1:
print("Congratulations! Moves: ", moves)
printBoard(board)
... |
def exists(val):
return val is not None
def default(val, d):
if exists(val):
return val
return d() if is_lambda(d) else d
def cast_tuple(t, l = 1):
return ((t,) * l) if not isinstance(t, tuple) else t
def Downsample(
dim,
dim_out = None,
factor = 2
):
dim_out = default(dim_out, d... | This code defines a neural network model combining CNN and Transformer components for image processing. It initializes layers for image transformation, downsampling/upsampling with ResNet blocks, attention mechanisms, and a Vision Transformer (ViT) in the middle. The model handles input/output transformations, dimensio... | def __init__(
self,
dim,
init_dim = None,
out_dim = None,
dim_mults = (1, 2, 4, 8),
downsample_factor = 2,
channels = 3,
vit_depth = 6,
vit_dropout = 0.2,
attn_dim_head = 32,
attn_heads = 4,
ff_mult = 4,
resnet_block... |
def default(val, d):
if exists(val):
return val
return d() if is_lambda(d) else d
def q_sample(self, x_start, times, noise = None):
noise = default(noise, lambda: torch.randn_like(x_start))
log_snr = self.log_snr(times)
log_snr_padded = right_pad_dims_to(x_start, log_snr)
... | This function computes the loss for a diffusion model during training. It generates noise, samples data and log-SNR values, predicts model outputs, and calculates a mean squared error loss against targets (noise or 'v' parameters). The loss is weighted by SNR (signal-to-noise ratio) and adjusted based on the prediction... | def p_losses(self, x_start, times, noise = None):
noise = default(noise, lambda: torch.randn_like(x_start))
x, log_snr = self.q_sample(x_start = x_start, times = times, noise = noise)
model_out = self.model(x, log_snr)
if self.pred_objective == 'v':
padded_log_snr = right_p... |
def num_to_groups(num, divisor):
groups = num // divisor
remainder = num % divisor
arr = [divisor] * groups
if remainder > 0:
arr.append(remainder)
return arr
def save(self, milestone):
if not self.accelerator.is_local_main_process:
return
data = {
's... | The code trains a machine learning model using gradient accumulation and distributed training via Accelerate. It processes data batches, computes loss, performs backpropagation with gradient clipping, and updates the optimizer. The EMA (Exponential Moving Average) is maintained for model stability. Periodically, it gen... | def train(self):
accelerator = self.accelerator
device = accelerator.device
with tqdm(initial = self.step, total = self.train_num_steps, disable = not accelerator.is_main_process) as pbar:
while self.step < self.train_num_steps:
total_loss = 0.
for... |
def _close_game(self):
"""Save high score and exit"""
saved_high_score = self.stats.save_high_score()
if self.stats.high_score > saved_high_score:
with open('high_score.json', 'w') as f:
json.dump(self.stats.high_score, f)
sys.exit()
def _fire_bullet(self):
... | This function handles keyboard input events in a Pygame game. It enables player movement (left/right), quits the game (Q), fires bullets (Spacebar), and starts/pauses the game (P). Each key press triggers specific actions: setting ship movement flags, closing the game, firing bullets, or initiating game start based on ... | def _check_keydown_events(self, event):
"""Responds to keystrokes"""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
self._close_game()
el... |
def _check_fleet_edges(self):
"""Reacts to the alien reaching the edge of the screen"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
"""Handles the collision of a ship with an ali... | The function `_update_aliens` updates alien positions, checks for collisions between aliens and the player's ship, and verifies if aliens have reached the screen's bottom edge. It triggers collision responses via `_ship_hit()` and bottom-edge logic via `_check_aliens_bottom()`, ensuring game mechanics like movement, co... | def _update_aliens(self):
"""Updates the positions of all aliens in the fleet"""
self._check_fleet_edges()
self.aliens.update()
# Checking for "alien — ship" collisions
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
# Check if the ... |
def _check_keydown_events(self, event):
"""Responds to keystrokes"""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
self._close_game()
el... | The main task of the code is to handle user input events in a Pygame application. It processes events such as quitting the game, key presses (keydown/up), and mouse clicks. For each event, it delegates specific actions to helper methods like `_check_keydown_events`, `_check_keyup_events`, and `_check_play_button`, whic... | def _check_events(self):
"""Handles keystrokes and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.... |
def _check_events(self):
"""Handles keystrokes and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.... | The code defines the game's main loop, maintaining the frame rate, checking events, updating game elements (ship, bullets, aliens) when active, and redrawing the screen repeatedly to sustain gameplay until termination. | def run_game(self):
"""Game's main cycle"""
while True:
self.clock.tick(self.FPS)
self._check_events()
# The screen is redrawn every time the cycle passes
if self.stats.game_active:
self.ship.update()
self._update_bullets()
... |
def save_wasted():
df = pd.read_csv('./ooglorp-master/monthly_tomatoes_ooglorp.csv')
x = list(df['ds'])
dates = []
y = list(df['y'])
for date in x:
s = date.rstrip()
print(s)
dates.append(datetime.datetime.strptime(s, "%m/%d/%Y").date())
#date = s.strftime("%Y%m%d")
... | The code processes a POST request to update apple orders, predicts next month's optimal order and wastage using CSV data, applies random adjustments, and renders the 'stats.html' template with calculated values. If no data is submitted, it displays an input prompt for users to enter their current month's order for esti... | def stats(request):
template_name = 'stats.html'
plt.clf()
save_wasted()
plt.clf()
save_ordered()
plt.clf()
#if an image is uploaded
if(request.method == 'POST' and request.POST['apple'] is not None):
apple= int(request.POST['apple'])
update_csv('ooglorp-master/monthly_to... |
def get_moves(self):
"""Creates a list of moves for battle. The moves are random
assignments from all available moves in the api"""
response_json = self.api_call(self.pokemon_url)
num_of_moves = len(response_json['moves'])
# randomly selects 8 out of all moves available
#... | The main task of the code is to retrieve a Pokémon's battle-ready attributes by gathering moves, types, and factors, using multithreading to efficiently fetch move details, then filtering out non-damaging moves to prepare for combat. | def get_attrs(self):
"""Retrieves all the pokemons attributes to prepare for battle"""
self.get_moves()
self.poke_types()
self.factors()
# self.move_info
with concurrent.futures.ThreadPoolExecutor() as executor:
executor.map(self.get_move_info, self.moves)
... |
def battle_turn1(self, quicker_mon, slower_mon):
print("Go", quicker_mon.name, "!")
for i, x in enumerate(quicker_mon.moves):
print(
i+1, x, f"--- does {quicker_mon.move_dict[x]['power']} damage")
print('\n')
index = self.input_validation("Pick a move: ")
... | The code initializes a Pokémon battle by displaying both Pokémon's names and types. It determines the faster Pokémon to set attack order, then simulates turns where the quicker Pokémon attacks first, followed by the slower one. The battle continues until one Pokémon's health reaches zero, at which point the function an... | def commence_battle(self):
print('\n')
print("-----POKEMON BATTLE-----")
print("Pokemon 1:", self.pokemon1.name)
print("TYPE/", self.pokemon1.types)
print("\nVS\n")
print("Pokemon 2:", self.pokemon2.name)
print("TYPE/", self.pokemon2.types, '\n')
# evaluate ... |
def v (mu, muj, phij):
E_val = Ej(mu,muj,phij)
return 1/(g(phij)**2 * E_val * (1 - E_val))
def g (phi):
return 1/np.sqrt(1 + 3*phi**2 / np.pi**2)
def Ej (mu, muj, phij):
return 1/(1 + np.exp(-g(phij) * (mu-muj)))
def iterSigPr (sig, delta, phi, vi, tau, eps=1e-6):
a = np.log(sig**2)
A = a
if... | The code updates the ratings, rating deviations (RD), and volatility of two players (id1 and id2) in a DataFrame based on the outcome of a match, using a probabilistic model. It transforms ratings into mu and phi values, calculates deltas using expected outcomes and volatility, updates volatility parameters, and revert... | def update_ratings (id1, id2, t1win, df, ot=False):
table = df
tau = 0.2
r1 = table[table.id == id1]['rating'].values[0]
rd1 = table[table.id == id1]['rd'].values[0]
sig1 = table[table.id == id1]['volatility'].values[0]
mu1 = (r1 - 1500)/173.7178
phi1 = rd1/173.7178
r2 = table[table.id... |
def fetch_file_type_name(self):
self.file_name = pathlib.Path(self.file).stem
if "stock" in self.file_name.lower():
self.file_type = "SS"
else:
self.file_type = "PW"
def extract_medicine_line(self):
self.lines = re.findall('(?:[A-Z]+)(?:.*?)(?:\d+|-)\n', self.tex... | The main task of the code is to process a document by extracting and cleaning text, identifying medicine-related lines and functions, and generating an Excel file. It sequentially performs text extraction, space cleanup, file metadata retrieval, medicine line detection, function identification, and Excel creation to or... | def main(self):
extract_text(self)
remove_unnecessary_space(self)
self.fetch_file_type_name()
self.extract_medicine_line()
self.detect_functions()
self.create_excel() |
def get_outgoing_paths_to_targets(self, *, source_node, start_nodes,
target_nodes: Set[URIRef], target_invalid_node,
max_hops):
all_paths = []
for start_node in start_nodes:
temp_target_nodes = target_nodes
... | The function `forecast_effect_reverse_predictions` predicts reversed property relationships by analyzing paths from effects to causes using similar cases and inductive forecasts. It processes input triples to identify target properties and entities, then computes path statistics (counts, precision, success rates) for p... | def forecast_effect_reverse_predictions(
self, *,
prop_forecasts: Dict[URIRef, Dict[URIRef, float]],
dummy_target_uri: URIRef,
triples_for_inductive_forecast: List[Tuple[URIRef, URIRef, URIRef]],
similar_case_effects: List[SimilarCauseEffectChoices],
... |
def collect_similar_events_with_target_relation(self, dummy_target_uri: URIRef, target_relation: URIRef, initial_candidate_limit: int = None) -> \
List[URIRef]:
'''
For a given target entity, return a sorted list of the most similar entities present in the
knowledge graph. The return... | The main task of the code is to predict potential future effects (entities) based on historical cause-effect patterns in a knowledge graph. It identifies similar past cases to a target entity, extracts relevant paths between causes and effects, evaluates path validity and precision, and aggregates probabilistic forecas... | def forecast_effects(self, *,
triples_for_inductive_forecast: List,
dummy_target_uri: URIRef,
forecast_relations: List[URIRef],
max_hops: int = 3, sample_case_count: int = 5, sample_case_cov_count: int = 5,
... |
def initialize_runtime_variables(self):
#variables to set once the node is initialized
#The reason these variables cannot be set in the constructor is because
#their values can only be determined after the node is initialized
self.angle_offset = abs(self.laser_msg.angle_min + self.tau) ... | The main task of the code is to initialize runtime variables, move backward for 10 steps using a Twist command, then continuously monitor laser scan data to detect obstacles. If the minimum range is less than 1.0 meters, it triggers wall-following; if greater than 2.0 meters, it moves forward safely. The loop runs unti... | def main_loop(self):
self.initialize_runtime_variables()
for i in range(10):
twist_cmd = Twist()
twist_cmd.linear.x = -0.5
self.vel_pub.publish(twist_cmd)
self.rate.sleep()
while not rospy.is_shutdown():
ranges = self.laser_msg.ranges
... |
def to_discard(self,ori_board):
previous_score = ori_board.score
board = ori_board.clone()
board.falling = board.next
score = []
temp_board = None
for i in range(0,4):
if temp_board is None:
board_to_rotate = board.clone()
... | The main task of the code is to determine the optimal sequence of actions (rotations, horizontal movements, and drops) for a falling game piece on a board by evaluating all possible rotations (up to 4) and horizontal positions, calculating scores for each configuration, selecting the highest-scoring move, and returning... | def choose_action(self, board):
if board.falling is None:
return Direction.Down
elif board.falling is not None:
discard = self.to_discard(board)
if discard is True and board.discards_remaining > 0:
return Action.Discar... |
def get_person_bbox(self,image_path):
image = cv2.imread(image_path)
# keep the original height and width for resizing of bounding boxes
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# apply the image transforms
transformed_image = self.transform(image)
# convert to torc... | The code processes an image by detecting person bounding boxes and reference face locations. It crops and saves the person's region if the face is predominantly within the person's bounding box (over 80% overlap), using OpenCV for image manipulation and file output. | def process_file(self,img_path):
person_bboxes = self.get_person_bbox(img_path)
face_bbox = self.get_reference_face_locations(img_path)
for bbox in person_bboxes:
bbox_within = percentage_of_bbox_within(face_bbox,bbox)
if bbox_within > 80:
img... |
def get_random_point_set(self,n_points=11,width=6,height=6):
return np.array([
[
-width/2+np.random.random()*width/2,
-height/2+np.random.random()*height/2,
0
]
for _ in range(n_points)
])
def get_dots(self,points):
... | The code's main task is to animate a windmill-like geometric process by generating random points, creating a rotating line (windmill), identifying pivot points, and visualizing the rotation around these pivots. It initializes points, constructs a windmill line, highlights a pivot, calculates the next pivot and rotation... | def construct(self):
points=self.get_random_point_set(16)
dots=self.get_dots(points)
line=self.get_windmill(points)
dot_pivot=self.get_pivot_dot(line)
next_pivot,angle=self.next_pivot_angle(line)
self.play(
LaggedStartMap(Create,dots)
)
self.pl... |
def extract_AXp(self, inst, seed=set()):
lbounds = inst.copy()
ubounds = inst.copy()
candidate, drop, pick = set(self.hypos), set(), set()
for i in seed:
self.free_attr(i, inst, lbounds, ubounds, candidate, drop)
potential = list(filter(lambda l: l not in seed, self.h... | The main task of the code is to generate abductive and/or contrastive explanations for an instance based on model predictions. It creates logical condition strings (e.g., "IF feature=x THEN label=pred") for each explanation type, tracks explanation sizes, and returns structured outputs including the predicted label, ex... | def explain(self, inst):
self.hypos = list(range(len(inst)))
pred = self.model.predict([inst])[0]
self.time = {'abd': 0, 'con': 0}
self.exps = {'abd': [], 'con': []}
if self.options.xnum not in (-1, 'all'):
if self.options.xtype in ['abd', 'abductive']:
... |
def env_step(env: Env, action: Action) -> tuple[Env, Reward, Done]:
col = action
row = jnp.argmax(env.board[:, col] == 0) # find the first empty row in the column
invalid_move = env.board[row, col] != 0 # if the column is full, the move is invalid
# Place the player's piece in the board only if the mo... | The function processes an environment step using the given action and embedding, computes rewards, discounts, policy logits, and values, then returns these along with the updated environment state. | def recurrent_fn(params, rng_key, action, embedding) -> tuple[mctx.RecurrentFnOutput, Env]:
env = embedding
env, reward, done = env_step(env, action)
recurrent_fn_output = mctx.RecurrentFnOutput(
reward=reward,
discount=jnp.where(done, 0, -1).astype(jnp.float32),
prior_logits=policy_... |
def return_tune_and_chromaticity(self, beam=1):
"""Returns the tune and chromaticity for the requested beam."""
if beam == 1:
return self.tw_b1["qx"], self.tw_b1["dqx"], self.tw_b1["qy"], self.tw_b1["dqy"]
elif beam == 2:
return self.tw_b2["qx"], self.tw_b2["dqx"], self.t... | The function generates a string summarizing collider observables (tune, chromaticity, coupling, momentum compaction, Twiss parameters, and luminosity) for two beams at specific interaction points. It optionally writes this summary to a file if a path is provided, returning the formatted string for use or further proces... | def output_check_as_str(self, path_output=None):
"""Summarizes the collider observables in a string, and optionally to a file."""
# Check tune and chromaticity
qx_b1, dqx_b1, qy_b1, dqy_b1 = self.return_tune_and_chromaticity(beam=1)
qx_b2, dqx_b2, qy_b2, dqy_b2 = self.return_tune_and_chr... |
def get_time_sliced_df(self, start_date=None, end_date=None):
"""
gets time sliced data between start date and end date
Parameters
----------
start_date: start date of the slice to be extracted
end_date: end date of the slice to be extracted
Returns
----... | The function `plot_light_curve` generates light curve plots for one or more astronomical bands, customizing appearance via parameters like color mappings, date ranges, and markers. It handles error bars, labels, and maximum flux markers, plotting data points or curves based on input settings. The output is a matplotlib... | def plot_light_curve(
self,
color_band_dict,
band_map=None,
fig=None,
band=None,
start_date=None,
end_date=None,
plot_points=False,
mark_label=True,
mark_maximum=True,
label_postfix="",
clip_xlims=None,
markers={},
... |
def report_status(self, name):
self.status.set_status_by_name(name)
self.send_pickle(self.status)
def to_pickle(self, data):
return pickle.dumps(data, protocol=pickle.HIGHEST_PROTOCOL)
def send_pickle(self, obj):
self.conn.sendall(self.to_pickle(obj)) | This code serializes an object into a byte stream, splits it into 4096-byte packets, and sends them sequentially over a network while tracking packet count and reporting transfer status. The method converts the object to a pickled byte array, divides it into chunks, transmits each chunk, and resets counters upon comple... | def send_object(self, obj):
print("Begin sending packet")
self.report_status("BEGIN_TRANSFER")
p_obj = self.to_pickle(obj)
p_obj_list = memoryview(p_obj).tolist()
print(f"Packet size {len(p_obj_list)}")
print("Sending packets...")
while len(p_obj_list):
self.packets += 1
... |
def report_status(self, name):
self.status.set_status_by_name(name)
self.send_pickle(self.status)
def to_pickle(self, data):
return pickle.dumps(data, protocol=pickle.HIGHEST_PROTOCOL)
def send_pickle(self, obj):
self.conn.sendall(self.to_pickle(obj)) | This code serializes an object into bytes, splits it into 4096-byte packets, and sends them sequentially while tracking packet count and transfer status. It uses memoryview for efficient slicing, reports transfer start/end, and resets counters after completion. | def send_object(self, obj):
print("Begin sending packet")
self.report_status("BEGIN_TRANSFER")
p_obj = self.to_pickle(obj)
p_obj_list = memoryview(p_obj).tolist()
print(f"Packet size {len(p_obj_list)}")
print("Sending packets...")
while len(p_obj_list):
self.packets += 1
... |
def load_db(self):
#print("loading db", self.tables_path)
if not self.tables_path:
print("No database tables path provided. Update ``self.tables_path``")
return
tables = json_read(self.tables_path, object_hook = self.hook)
#print("TABLES",tables)
setattr(self, 'tables', tables)
#prin... | The code initializes a server by loading a database from a specified path, setting up a JSON object hook for data processing, configuring socket server parameters (host, port), starting the server to listen for connections, and initiating a loop to manage client connections. It also initializes variables to track serve... | def __init__(self):
# the name of the database
self.tables_path = _config.tables_path
# the json object hook
self.hook = lambda d: SimpleNamespace(**d)
# load the database
self.load_db()
# the connection
self.conn = None
# host and port for the socket server
self.host = _confi... |
def the_of(sentence, start_id, end_id, mathArr):
matcher = Matcher(nlp.vocab)
pattern = [{"LOWER": "the"}, {"IS_ASCII": True, "OP": "*"}, {"LOWER": "of"}]
matcher.add("FUNC_complex", None, pattern)
doc = nlp(sentence)
count = len(doc)
for match_id, start, end in matcher(doc):
# gets the ... | The main task of the code is to identify and extract mathematical definitions from a sentence by detecting patterns like "is defined by/on/via". It uses NLP tokenization and matching to locate the definition structure, distinguishing between simple and complex subjects (e.g., "the X of Y"). If a match is found, it prin... | def find_complex_definition(sentence, mathArr, sentence_id):
matcher = Matcher(nlp.vocab)
# three patterns we are searching for in the sentence
pattern = [{"LOWER": "is"}, {"LOWER": "defined"} ,{"LEMMA": "by"}]
pattern2 = [{"LOWER": "is"}, {"LOWER": "defined"} ,{"LEMMA": "on"}]
pattern3 = [{"LOWER":... |
def the_of(sentence, start_id, end_id, mathArr):
matcher = Matcher(nlp.vocab)
pattern = [{"LOWER": "the"}, {"IS_ASCII": True, "OP": "*"}, {"LOWER": "of"}]
matcher.add("FUNC_complex", None, pattern)
doc = nlp(sentence)
count = len(doc)
for match_id, start, end in matcher(doc):
second_sub_... | The function `find_complex_definition` identifies definitions in a sentence using spaCy's Matcher to detect patterns like "is defined by/on/via". It extracts the subject and definition parts, handling cases where the subject spans multiple tokens. If a match is found, it prints the subject and definition, returning 1; ... | def find_complex_definition(sentence, mathArr, sentence_id):
matcher = Matcher(nlp.vocab)
pattern = [{"LOWER": "is"}, {"LOWER": "defined"} ,{"LEMMA": "by"}]
pattern2 = [{"LOWER": "is"}, {"LOWER": "defined"} ,{"LEMMA": "on"}]
pattern3 = [{"LOWER": "is"}, {"LOWER": "defined"} ,{"LEMMA": "via"}]
matche... |
def is_active(self):
return self.active and self.quantity > 0
def set_quantity(self, quantity):
self.quantity = quantity
if self.quantity <= 0:
self.quantity = 0
self.deactivate()
def deactivate(self):
if self.is_active():
self.active = False
e... | The main task of the code is to enable purchasing a product by validating the transaction (checking product activation status, positive quantity, and sufficient stock), deducting the purchased quantity from the product's stock, deactivating the product if stock reaches zero, and returning the total price. | def buy(self, quantity):
if not self.is_active():
raise Exception("The product is currently deactivated.")
if quantity <= 0:
raise Exception("Please provide a positive quantity to purchase.")
if quantity > self.quantity:
raise Exception("Insufficient quantit... |
def convert_action_to_direction(action):
if action == 0:
return 'U'
elif action == 1:
return 'L'
elif action == 2:
return 'D'
elif action == 3:
return 'R'
def move_snake(self):
# Convert snake direction char to vector
dx, dy = convert_direction_to_vector(s... | The main task of the code is to process a directional action (0-3) to update the snake's movement direction, execute the movement, track game state (steps, collisions, food), and return the new state, reward, termination status, and optional info for reinforcement learning. The action adjusts the snake's direction rela... | def step(self, action):
"""
:param action:
0 --> Go Up
1 --> Go Left
2 --> Go Down
3 --> Go Right
Need to take a rotation action, perpendicular to your current movement
Rotation action uses level as a base frame. So when you execute... |
def best_attribute(self, data_interval, entropy):
best_parameter, best_gain = '', 0
information_gains = self.information_gains(data_interval, entropy)
for parameter in information_gains.keys():
if information_gains[parameter] > best_gain:
best_gain = information_gains... | This function recursively constructs a decision tree by selecting the best attribute to split the data, creating nodes for each attribute and its states, and handling leaf nodes when no further splitting is possible. It uses sampling to determine the best attribute, tracks node counters, and builds a graph structure wi... | def build_tree(self, data_interval, parent=None, attribute_state=None):
classes = data_interval['class'].unique().tolist()
data_len = len(data_interval)
attribute = (self.best_attribute(
DataFrame(random.sample(data_interval.values.tolist(), k=random.randint(int(data_len / 3), data_l... |
def _get_device_settings(self, extract, body, retry=False):
device_id = body["device_id"]
device_data = {
"device_settings" :{
"networks": {},
"port_usages": {},
"port_config": {}
},
"name": "",
"model": "",
"role": ""
}... | The function retrieves device and site settings by validating input parameters, extracting authentication data, fetching device/site configurations, generating network details, and compiling structured response data including device info, site settings, and network configurations. | def get_device_settings(self, body):
body = self.get_body(body)
if not "site_id" in body:
return {"status": 500, "data": {"message": "site_id missing"}}
if not "device_id" in body:
return {"status": 500, "data": {"message": "device_id missing"}}
extract = self.ext... |
def _unset_port_conf(self, port:dict, mist_device_settings:dict):
port_name = port["port"]
# only useful when there are port configuration at the device level
if "port_config" in mist_device_settings:
# if a dedicated entry exists for this switchport, remove it from the config
... | The function processes port configurations from the input body to update device settings. It groups ports by their AE UUID, extracts usage profiles, and constructs a new AE configuration. For each AE UUID, it applies configuration changes to the device settings using helper methods, handling both ports with and without... | def _mutate_device_settings(self, body, mist_device_settings):
new_ae_config = {}
for port in body["port_config"]:
if port.get("ae_uuid"):
ae_uuid = port["ae_uuid"]
ae_profile = port.get("device", {}).get("usage")
if not ae_profile:
... |
def load_data():
for transformer, file in transformers:
transformer.load_results(os.path.join(root, file), None, False)
def delete(key):
delete_files(key)
for transformer, file in transformers:
delete_from(key, transformer.text_fragments)
def save():
for transformer, file in transformers... | The main task of the code is to process data by loading it, deleting an entry associated with the provided key, saving the modified data, rebuilding the structure, and printing "done!" to indicate completion. | def main(key):
load_data()
delete(key)
save()
build()
print ('done!') |
def has_fragment(title):
'''returns true if the title is in the list of fragments'''
to_search = title.strip()
if not to_search.startswith('# '):
to_search = '# ' + to_search
for fragment in text_fragments:
if fragment.title == to_search:
return True
return False
def get_... | This function processes data fragments by rendering primary and non-primary components, extracting interface parts, and collecting generated files. It iterates through project fragments, skips missing ones if specified, retrieves components, renders code, extracts service and used component interfaces, and logs file na... | def process_data(root_path, writer):
for fragment in project.fragments:
if ONLY_MISSING and has_fragment(fragment.full_title):
continue
components = component_lister.get_components(fragment.full_title)
if len(components) > 0:
file_names = [] # keep track of the file ... |
def get_user(asana_user_id: str) -> User:
'''get user and all their values'''
user: Union[User, None] = detabase.get(key=__get_key(asana_user_id))
return user
def __webhook_active(user: User, project_index: int) -> bool:
return "is_active" in user["projects"][project_index] and user["projects"][project_... | This function increments a project's task counter in Asana if the webhook is active and the task isn't already numbered. It retrieves the user's project, checks conditions, updates the counter, saves changes, and returns the new number or None if ineligible. | def next_task_number(asana_user_id: str, project_gid: str, task_gid: str) -> Union[int, None]:
'''increment task number id in project'''
user: User = get_user(asana_user_id)
project: asana.ProjectWithWebhook = None
for pro in user["projects"]:
if pro["gid"] == project_gid:
project = ... |
def bbox(A, B, C):
xs = sorted([int(A.x), int(B.x), int(C.x)])
ys = sorted([int(A.y), int(B.y), int(C.y)])
a = V2(int(xs[0]), int(ys[0]))
b = V2(int(xs[2]), int(ys[2]))
return a, b
def barycentric(A, B, C, P):
cx, cy, cz = cross(V3(B.x - A.x, C.x - A.x, A.x - P.x), V3(B.y - A.y, C.y - A.y, A... | This code rasterizes a triangle by iterating over its bounding box, calculating barycentric coordinates for each pixel, applying Gouraud shading with light and normals, handling textures via interpolated UV coordinates, and using a z-buffer for depth testing to determine visible pixels. | def triangle(self, A, B, C, lucecita, color=None, texture=None, texture_coords=(), intensity = 1, normals_coords = ()):
#Se calculan los valores maximos y minimos de x y y que contienen al triangulo
bbox_min, bbox_max = bbox(A,B,C)
#Recorremos a partir de los valores minimos y maximos la caja qu... |
def loadModelMatrix(self, translate=(0,0,0),scale=(1,1,1),rotate=(0,0,0)):
#translate = V3(*translate)
#scale = V3(*scale)
#rotate = V3(*rotate)
translate_matrix = [
[1,0,0,translate[0]],
[0,1,0,translate[1]],
[0,0,1,translate[2]],... | This code loads a 3D model from an .obj file with optional material (.mtl) and texture support. It applies transformations (translate, scale, rotate), computes face normals, calculates lighting intensity, and renders triangles using grayscale, material colors, or textures based on input parameters. | def glLoad(self, filename, mtl=None ,textura=None, translate=(0,0,0), scale=(1,1,1), rotate =(0,0,0)):
#Se realiza la lectura del archivo .obj
self.loadModelMatrix(translate,scale,rotate)
self.glmatrizFinal()
if not mtl:
modelo3D = ArchivoObj(filename)
mod... |
def cached_complete(request_sizes, **kwargs):
model_name = kwargs.get("engine", None) or kwargs.get("model", None)
should_cache = kwargs.get("temperature", 0) == 0
if should_cache:
kwargs_copy = kwargs.copy()
inputs = kwargs_copy.pop("prompt")
cache_base_keys = list(kwargs_copy.valu... | The code handles OpenAI API completions with request throttling, splitting large requests into batches when necessary, and utilizing persistent caching. It calculates token usage, cost, and logs requests if enabled, ensuring efficient API interaction while adhering to rate limits and optimizing resource usage. | def _complete(self, **kwargs):
"""Request OpenAI API Completion with:
- request throttling
- request splitting
- persistent caching
"""
model_name = self.name
kwargs["model"] = model_name
request_sizes = [
len(self.tokenizer.encode(prompt)) fo... |
def _flatten_multiple_choice_examples(self, inputs, targets):
flat_idx = []
flat_inputs = []
flat_choices = []
for example_id, (example_input, choices) in enumerate(zip(inputs, targets)):
for choice_id, choice in enumerate(choices):
flat_idx.append((example_id... | The function computes conditional log probabilities of target sequences given input sequences in a multiple-choice setup. It processes batches of inputs/targets, generates model completions, extracts target token log probabilities, and normalizes scores (if specified) by subtracting log-sum-exp for each example. The re... | def cond_log_prob(self, inputs, targets, absolute_normalization=False):
"""Get conditional log probability of targets given inputs."""
if isinstance(targets, str):
targets = [targets]
if isinstance(inputs, str):
inputs = [inputs]
targets = [targets]
... |
def load_bio(data_path=None):
if data_path is None:
_bio_path = Path(CURRENT_DIRECTORY, '../..', 'data', 'subtask4-token', 'en-train.txt').resolve()
assert _bio_path.is_file()
data_path = _bio_path
_bio_data = bio_read(data_path)
_bio_data = [(sent[1:], tag[1:]) for sent, tag in _bio... | The main task of the code is to initialize a class that preprocesses and loads data for a model, using a BERT tokenizer. It checks if preprocessed data exists, generates it if not, loads the data, sets the device (CPU/GPU), and initializes the tokenizer. The code ensures data is ready for model training or inference by... | def __init__(self, tokenizer=None, preprocessed_data_path=None, max_length=138):
if preprocessed_data_path is None:
preprocessed_data_path = Path(CURRENT_DIRECTORY, 'preprocessed_data.json')
if not preprocessed_data_path.is_file():
bio_data = load_bio()
coref_data = l... |
def get_all_relations(type_, id):
"""
Will return a list with all the relations of the SW object.
Args:
type_ (string): films/people/vehicles/starships/species/planets
id (int): id of object
Returns:
[type]: [description]
"""
j = retrieve_source('https://swapi.dev/api/'+... | This function populates a Postgres database with Star Wars API data starting from Luke Skywalker, recursively collecting all his connections and their relations using a breadth-first approach. It avoids redundant entries by tracking inserted items and relationships, inserting entities and their links into the database ... | def six_degrees_from_luke():
"""[Main function that will populate the Postgres Database]
- This function will populate the Database starting with Luke Skywalker and then
- adding all his connections plus their connections and so on.
- This way we do not need to have access to the hosts data... |
def load_shapes_modified(self ,files):
shapes = []
ni_values = [5, 20] # List of n_i values. Adjust as needed.
for idx, file in enumerate(files):
# Check if the file is a path or a file-like object (uploaded file)
if isinstance(file, str) and file.endswith('.pdf'):
... | The main task of the code is to optimize the placement of loaded shapes on an A4 canvas using a new strategy. It initializes the canvas, loads shapes, computes their properties (e.g., `ri`), places them optimally, and displays the final arrangement. If no shapes are loaded, it outputs an error message. The function ret... | def main_new_approach(self ,files):
# Initialize an A4 canvas
A4_WIDTH, A4_HEIGHT = CANVAS_SIZES['A4']
# Load shapes
shapes = self.load_shapes_modified(files)
if shapes:
print("it goes here ")
self.compute_ri(shapes)
# Use the new strategy to pl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.