dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_node_queries():
node_data = {
"Complaint": ["ComplaintId", "DateReceived", "SubmittedVia",
"DateSentToCompany", "Tags", "ConsumerComplaintNarrative"],
"Company": ["Company", "State", "ZipCode"],
"Product": ["Product", "SubProduct"],
"Issue": ["Issue",... | The main task of the code is to import data from a CSV file into a Neo4j graph database by generating and executing Cypher queries to create nodes. It connects to a Neo4j instance using credentials, processes predefined node structures, and applies them to the CSV data to populate the graph database with nodes. | def main():
csv_file = 'resources/complaints_100'
driver = GraphDatabase.driver(uri, auth=(username, password))
with driver.session() as session:
node_data = create_node_queries()
for node, properties in node_data.items():
cypher_query = create_node_cypher(node, properties)
... |
def listar_operaciones():
for c in COMANDOS:
print(c)
def camino_mas(aeropuertos, vuelos, filtro, origen, destino):
peso = 0
if filtro == "barato":
peso = 1
minimo = ()
for a_origen in aeropuertos[origen]:
for a_destino in aeropuertos[destino]:
dist, padre = camin... | The function `ejecutar_comandos` processes a command array to dispatch operations on airport and flight data. It routes commands like "listar_operaciones", "camino_mas", "centralidad", etc., to corresponding functions, parsing parameters from the input array. The main task is to act as a dispatcher, executing specific ... | def ejecutar_comandos(comando_arr, aeropuertos, vuelos):
if comando_arr[0] == "listar_operaciones":
return listar_operaciones()
datos = (" ".join(comando_arr[1:])).split(",")
if comando_arr[0] == "camino_mas":
return camino_mas(aeropuertos, vuelos, datos[0], datos[1], datos[2])
if comand... |
def basicParams(self):
self.verify(info[1])
self.verify(info[2])
for i in range(3,len(info)):
self.verify(info[i])
def getUrl(self):
check = self.browser.find_element_by_xpath('//input[@class="reqString"]')
return check.get_attribute('value')
def customParams(self):
... | The code initializes a headless Chrome browser, navigates to a URL, retrieves data, processes parameters, and uploads the data to Baidu using BosClient. It automates data fetching, parameter handling, and cloud storage upload in a streamlined workflow. | def __init__(self):
self.options = Options()
self.options.add_argument('--headless')
self.browser = webdriver.Chrome(chrome_options=self.options)
self.browser.get('http://querybuilder.flurry.com/')
self.bos_client = BosClient(bos_sample_conf.config)
self.basicParams()
... |
def setParams(self):
self.table = self.setTable()
self.time = self.setTimeGrain()
self.setDimensions()
self.setMetrics()
self.setDateRange()
self.setSort()
self.setFilter()
self.setHavings()
self.url+=self.token
def requestData(self):
d = r... | The code initializes a class to fetch data from the Flurry Metrics API using a token, processes the data with `setParams()`, retrieves it via `requestData()`, and uploads the result to Baidu's Bos cloud storage using `uploadBaidu()` for data storage and management. | def __init__(self):
self.url = 'https://api-metrics.flurry.com/public/v1/data'
self.token='' #FlurryKey
self.bos_client = BosClient(bos_sample_conf.config)
self.setParams()
self.data = self.requestData()
self.uploadBaidu() |
def get_random_via_points(end_point):
# + 2 because start and end points:
d1_points = np.ndarray((num_via_points + 2,))
theta2_points = np.ndarray((num_via_points + 2,))
theta3_points = np.ndarray((num_via_points + 2,))
theta4_points = np.ndarray((num_via_points + 2,))
# XYZ values for target p... | The code generates trajectories for robotic arm joints (d1, theta2, theta3, theta4) and Cartesian positions by calculating time-based kinematic parameters from randomized via points, then returns interpolated paths and coordinates. It uses distance-weighted time allocation and resolution-based sampling to ensure smooth... | def do_trajectory_planning(end_point, res=20):
d1_points, theta2_points, theta3_points, theta4_points, P_coordinates = \
get_random_via_points(end_point)
# calculate distance between two points position
dist = np.sqrt(np.sum((P_coordinates[1:] - P_coordinates[:-1]) ** 2, axis=1))
t_tot = 25 # ... |
def load_game(self):
"""Loads the game from a pre-determined file."""
try:
with open("game_data.dat","rb") as file:
print("Loading game... ")
self.myHero,self.MyEnvironment,self._count,self._difficulty = load(file)
except FileNotFoundError:
... | The main task of the code is to run a game loop where the player chooses to load a saved game or start new, then controls a hero moving through an environment. The hero's health decreases each turn, the environment updates, and the game checks for a win condition. The loop continues until the player wins, with turn cou... | def play(self):
"""Main function for playing the game."""
#First prompts the user whether they want to load from the last saved file or start a new game.
print("Hello World! Press L to load from your last game, or any other key to start a new game... ")
start = getch().upper()
... |
def get_available_locations(board):
valid_locations = []
for col in range(BOARD_COLUMNS):
if available_location(board, col):
valid_locations.append(col)
return valid_locations
def is_terminal_node(board):
return check_win(board, PLAYER_PIECE) or check_win(board, AI_PIECE) or len(get_... | This code implements the Minimax algorithm for a turn-based game, recursively evaluating all possible moves up to a given depth. It determines the optimal column for the AI to play by maximizing its score while assuming the opponent minimizes it. Terminal states (win/loss/draw) are scored, and non-terminal states use a... | def minimax(board, depth, maximizingPlayer):
# https://en.wikipedia.org/wiki/Minimax
available_locations = get_available_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if check_win(board, AI_PIECE):
return (None, 1... |
def matrix_filling ():
#first partial product
for i in range(pp_parallelism+3):
partial_matrix[0][i] = dot
#intermediate partial products
for j in range(1,levels_number-1):
partial_matrix[j][2*j-2] = dot
for i in range(2*j, pp_parallelism+2*j+2):
if i < da... | This code implements the Dadda multiplier algorithm to reduce partial product matrices using full/half adders. It processes the matrix through iterative row reductions, tracks adder counts, and generates VHDL output for hardware synthesis, finalizing two data signals from the computed result. | def dadda(pp_parallelism):
matrix_filling()
#print the recap of what will be done
print_header()
#print the matrix
print("Initial partial product matrix:\n")
print_matrix(len(partial_matrix))
#steps of the reduction of the rows
for i in elements_in_level:
empty_line = ... |
def prep_nltk():
print("[prep_nltk] Downloading wordnet...")
nltk.download('wordnet')
def create_processed_docs(data_dir):
docs_path = Path(data_dir + "/processed_docs.pkl")
if docs_path.exists():
print("Found stored processed docs file. Loading...")
with open(docs_path, 'rb') as pkl_fil... | The main task of the code is to generate a text dataset by creating a directory if it doesn't exist, preprocessing documents, building a dictionary of terms, and converting processed text into a document-term matrix. It handles directory management, text normalization, vocabulary creation, and matrix generation for tex... | def create_dataset(data_dir="data"):
data_path = Path(data_dir)
if not data_path.exists():
print("Creating directory ", data_dir)
data_path.mkdir()
prep_nltk()
processed_docs = create_processed_docs(data_dir)
dictionary = create_dictionary(data_dir, processed_docs)
retur... |
def write_version_py(filename='pywt/version.py'):
cnt = """
# THIS FILE IS GENERATED FROM PYWAVELETS SETUP.PY
short_version = '%(version)s'
version = '%(version)s'
full_version = '%(full_version)s'
git_revision = '%(git_revision)s'
release = %(isrelease)s
if not release:
version = full_version
"""
FULLVERS... | The main task of the code is to configure and build the PyWavelets Python package, including generating version files, defining metadata (name, description, dependencies, classifiers), handling Cython extensions for compilation, and preparing setup parameters for installation. It ensures compatibility with Python 3.7+,... | def setup_package():
# Rewrite the version file everytime
write_version_py()
metadata = dict(
name="PyWavelets",
maintainer="The PyWavelets Developers",
maintainer_email="naovq@example.com",
url="https://github.com/PyWavelets/pywt",
download_url="https://github.com/P... |
def print_board(self):
for row in self.state:
print(" ".join(["X" if cell == 1 else "O" if cell == -1 else "-" for cell in row]))
def make_move(self, row, col, val):
if 0 <= row < 3 and 0 <= col < 3 and self.state[row][col] == 0:
self.state[row][col] = val
return True... | The main task of the code is to enable a human player to interactively play a Tic-Tac-Toe game against a computer. It repeatedly prints the game board, takes user input for their move, checks if the move ends the game (win/tie), and if not, lets the computer make a move. The loop continues until the game concludes, dis... | def play_game(self):
while True:
self.print_board()
row = int(input("Enter the row (0, 1, 2) for your move: "))
col = int(input("Enter the column (0, 1, 2) for your move: "))
if self.make_move(row, col, -1):
if self.terminal_node(self.state)["game_... |
def create_reference_paths_dict(base_path):
reference_dict = {}
for identity_dir in tf.gfile.ListDirectory(base_path):
image_paths = []
full_identity_dir = os.path.join(base_path, identity_dir)
for image_path in tf.gfile.ListDirectory(full_identity_dir):
image_paths.append(image_path)
identity... | The main task of the code is to prepare training and validation datasets for a GAN (generator-discriminator model) by loading real and masked images, applying transformations (resizing, normalization), pairing them with reference images, and batching data. It also processes validation images, generates masked versions,... | def main():
train_reference_path = os.path.join(DATASET_TRAIN_PATH, "reference")
train_reference_paths_dict = create_reference_paths_dict(train_reference_path)
# Make a Dataset of file names including all the PNG images files in
# the relative image directory.
real_dataset = tf.data.Dataset.list_files(os.... |
def create_reference_paths_dict(base_path):
reference_dict = {}
for identity_path in os.list_dir(base_path):
image_paths = []
full_identity_dir = os.path.join(base_path, identity_dir)
for image_path in os.list_dir(full_identity_dir):
image_paths.append(image_path)
identity = identity_dir.split... | This code prepares training and validation datasets for a generative adversarial network (GAN) by loading real and masked images, applying transformations (resizing, normalization), and pairing them with reference images. It constructs TensorFlow datasets, shuffles, batches, and zips them for training. Validation data ... | def main():
train_reference_path = os.path.join(DATASET_TRAIN_PATH, "reference")
train_reference_paths_dict = create_reference_paths_dict(train_reference_path)
# Make a Dataset of file names including all the PNG images files in
# the relative image directory.
real_filenames_dataset = tf.data.Dataset.list_f... |
def generate_images(model1, model2, test_input, tar, epoch, save_path):
if model2 is not None:
prediction1 = model1(test_input, training=True)
prediction2 = model2(prediction1, training=True)
else:
prediction2 = model1(test_input, training=True)
plt.figure(figsize=(15, 15))
disp... | The code evaluates a dual-generator model's performance on a test dataset by generating images, calculating per-pixel accuracy, room ratio, and FID (Fréchet Inception Distance) metrics, then saving these quantitative results to a file. It loads pre-trained models, processes test images in batches, compares real/fake ou... | def main():
# loading test files (we're testing loss right now, if we're not testing loss we
# can switch to another dataset without desired output)
test_data_dir = '2bedroom_data'
test_dataset = tf.data.Dataset.list_files(test_data_dir + '/TEST/*.png')
test_dataset = test_dataset.map(load_image_tes... |
def _check_result_exists(self, model_id, data_id, train_ids, test_ids, tag):
"""check if result already exists"""
filename = self._get_res_filename(model_id, data_id, train_ids, test_ids, tag)
my_file = Path(filename)
if my_file.is_file():
return pd.read_csv(filename, index_c... | The main task of the code is to perform prediction using a specified machine learning model on given training and test data. It checks for existing results, loads or prepares data, trains the model, executes predictions, processes outputs (e.g., converting probabilities to class labels), and saves results to a CSV file... | def qpredict(self, model_id, data_id, data=None, ids=None, tag='', save_result=True, save_model=False, force=False):
if ids is not None:
train_ids, test_ids = ids
res = self._check_result_exists(model_id, data_id, train_ids, test_ids, tag)
if res is not None and not force:
... |
def parse_kabsch_transform_dump(dump_path):
transform = open(dump_path, "rb")
rot = pickle.load(transform)
c_curr = pickle.load(transform)
c_goal = pickle.load(transform)
return (rot, c_curr, c_goal)
def calib_row(row, back_face_tfm, face_ref_curr_tfm):
tgt = parse_target(row)
com = parse_... | The main task of the code is to calibrate and compute 3D gaze angles from an input dataset using AprilTag markers and Kabsch transformations. It processes reference and current marker positions, applies coordinate transformations, calculates gaze vectors, converts them to spherical coordinates (elevation/azimuth), upda... | def orchestrate_fg(apriltag, anglesId, refBack, refFace):
print("Calib")
FACE_OUTPUT_PICKLE = "./output/Curr_Face.pickle"
print("Running calibration once on AprilTag CSV file, store to {}".format(
FACE_OUTPUT_PICKLE))
CalibrationOnce.calib(apriltag, FACE_OUTPUT_PICKLE)
BACK_FACE_REF_TFM_O... |
def closest_city(cities):
path = []
current = cities.pop(0)
path.append(current)
while (cities):
min = float("inf")
next = current
for city in cities:
newDistance = distance(current, city)
if newDistance < min:
min = newDistance
... | The main task of the code is to solve a Traveling Salesman Problem (TSP) by reading city coordinates from an input file, finding an initial path using the closest city heuristic, optimizing it with the 2-opt algorithm, calculating the total distance, and writing the optimized path and distance to a `.tour` file, while ... | def begin():
inputfilename = sys.argv[1]
startT = time.time()
cities = []
with open(inputfilename, "r") as inputFile:
num = int(inputFile.readline())
for l in range(num):
line = inputFile.readline()
var = line.split()
city = []
for item in ... |
def createElement(self,tag):
tagName = self.getNodeTagName(tag)
className = tagName.capitalize()
#if there's not an implemented class, continues
if not hasattr(svg, className):
return None
# creates a instance of 'element'
return getattr(svg, className)(tagN... | This code processes SVG tags to construct a tree structure by creating elements, adding them to the root if not Defs, or handling modifiers for Defs elements. | def createTree(self,fileSVG):
for tag in fileSVG:
element = self.createElement(tag)
if(element == None):
continue
if(isinstance(element, Defs)):
self.createModifiers(tag)
else:
self.root.addChildDrawable(element)
... |
def plot_daily_results(df, ax, title=""):
"""
plot trial result across a single day
params
------
df : DataFrame
full protocol df thats n_done_trials for a day in length
with "trial" and "result", columns
ax : matplotlib.axes
axis to plot to
title : str, (default =... | The main task of the code is to generate a comprehensive daily analysis plot for a specific animal and date, combining multiple subplots (e.g., trial results, poke summaries, water delivery) into a single figure. It checks for existing files, creates a custom layout, and saves the plot with optional overwriting, using ... | def make_daily_spoke_stage_plot(df, overwrite=False, date=None, animal_id=None):
# if we don't get date/animal id values assume we are working
# with a groupby df and grab the first dow
if date is None:
date = df.date.iloc[0]
if animal_id is None:
animal_id = df.animal_id.iloc[0]
fi... |
def drop_sessions(
protocol_data, parsed_events_hist, trials, sess_ids, dates, sess_to_keep
):
inputs = [protocol_data, parsed_events_hist, trials, sess_ids, dates, sess_to_keep]
assert (
len({len(i) for i in inputs}) == 1
), "all inputs need to be of the same length!"
# TODO log drops
... | The code fetches and consolidates trial data across multiple animal sessions from a database. It processes session details, filters valid trials, reconciles data structures, and generates a unified DataFrame containing parsed events and trial metrics for all specified animals. | def fetch_trials_table(animal_ids=None):
animal_ids = ANIMAL_IDS if animal_ids is None else animal_ids
assert type(animal_ids) == list, "animal ids must be in a list"
animals_dfs = []
bdata = dj.create_virtual_module("bdata", "bdata")
for animal_id in animal_ids:
subject_session_key = {"r... |
def dictonary(puzzle):
dct = {}
for i in range(9):
for x in range(9):
if puzzle[i][x] == 0:
pos = []
sq = square(puzzle,i,x)
for t in sq:
if row(puzzle, i, t) and column(puzzle, x, t):
pos.append(t)
... | The code solves a Sudoku puzzle by iteratively deducing numbers for empty cells. It uses a dictionary to track possible values for each cell, updating the puzzle and the dictionary as cells are filled. The algorithm first fills cells with single possible values, then handles cells with two options by checking constrain... | def sudoku(puzzle):
"""return the solved puzzle as a 2d array of 9 x 9"""
dct = dictonary(puzzle)
while True:
print(dct)
b = True
for k, v in dct.items():
print(k, v)
x, y = map(int, k.split(','))
if len(v) == 1:
b = False
... |
def random_swap_context(words, n, answer):
new_words = words.copy()
for _ in range(n):
new_words = swap_word_context(new_words, answer)
return new_words
def random_deletion_context(words, p, answer):
answer_list = answer.split(' ')
#obviously, if there's only one word, don't delete it
if len(words) == 1:
ret... | This function performs contextual data augmentation on a sentence by applying three operations: random word swap, random deletion, and random duplication, while preserving the answer's context. It splits the input sentence into words, calculates modification counts based on alpha parameters, applies transformations seq... | def eda_context(sentence, answer, alpha_rs=0.1, alpha_rdu=0.1, p_rd=0.1):
words = sentence.split(' ')
num_words = len(words)
n_rs = max(1, int(alpha_rs*num_words))
n_rdu = max(1, int(alpha_rdu*num_words))
a_words = random_swap_context(words, n_rs, answer)
a_words = random_deletion_context(a_words, p_rd, answer)
... |
def extract_positions(self, joint, arm_name, joint_kin=None):
arm_name = arm_name.lower()
if arm_name=="ecm": joint_kin = self.ecm_kin
elif arm_name =="psm1" : joint_kin = self.psm1_kin
elif arm_name =="psm2" : joint_kin = self.psm2_kin
pos = []... | The function computes the optimal camera (ECM) joint angles for a surgical view by analyzing the positions of two surgical tools (PSM1/PSM2), their gripper states, and camera information. It adjusts the camera's orientation and zoom level to align with the tools' midpoint and deadzone, ensuring proper visualization dur... | def compute_viewangle(self, joint, cam_info, pos_track):
kinematics = lambda name: self.psm1_kin if name == 'psm1' else self.psm2_kin if name == 'psm2' else self.ecm_kin
clean_joints = {}
try:
joint_names = joint.keys()
for j in joint_names:
clean_joints[... |
def create_population(self) -> List[List[float]]:
return [self.create_individual() for _ in range(self.population_size)]
def sort_cur_gen_by_fitness(self):
self.cur_gen_scores = self.calc_scores(self.population_main)
ans = [i for i in sorted(zip(self.cur_gen_scores, self.population_main), revers... | This code executes a genetic algorithm (GA) to evolve a population over multiple generations. It resumes from a saved generation if available, otherwise initializes a new population. Each generation involves selection, crossover, mutation, and evaluation to create offspring, updating the population and tracking the bes... | def run_ga(self) -> List[float]:
# continue from current_generation
f = open('current_generation.txt', 'r')
gen_idx = int(f.read())
f.close()
if gen_idx == 0:
# If no saved generations, start from beginning
print("Creating initial population...")
... |
def getSession(self, year: int, gp:int, ses: str):
if type(year) is not int:
return {"error": "year should be integer"}
if type(ses) is not str:
return {"error": "Session should be string"}
print(type(gp))
keyVal = f"{year}_{gp}_{ses}"
if keyVal in self.lo... | The main task of the code is to retrieve and process fastest lap telemetry data for specified drivers in a race session, generate a plot of their performance, and optionally return a track visualization. It checks a cache for session data, fetches driver-specific telemetry, extracts fastest lap details, and returns vis... | def getFastestLap(self, year: int, gp:str, ses: str, drivers: list, fast, track):
keyVal = f"{year}_{gp}_{ses}"
if keyVal not in self.localCache.keys():
self.getSession(year, gp, ses)
driversData, _ = self.getDrivers(year, gp, ses, drivers)
driversDict = {}
... |
def mat2graph(mat):
rows = len(mat)
cols = len(mat[0])
graph = defaultdict(list)
for x in range(rows):
for y in range(cols):
if mat[x][y] == True:
for dx, dy in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
if 0 <= x+dx < rows and 0 <= y+dy < cols and mat[x+... | The code generates a maze using Prim's algorithm, applies the A* pathfinding algorithm with specified priority, measures execution time and expansion metrics, and logs results including path length, node expansion count, and time efficiency into a CSV file for experimental analysis. | def main(size, priority, exp_num):
start = (0, 0) # start <= (size, size)
destination = (size, size)
obj = PrimsMaze(size)
mat = obj.create_maze(start).tolist()
# plt.figure(figsize=(10, 5))
#
# plt.subplot(1, 2, 1)
# plt.imshow(mat, interpolation='nearest')
#... |
def configure_for_fedora(d):
make_m4(hpc=False, win=False,usear=True)
#d.infobox("aclocal", width=0, height=0, title="configure")
build_configure_all()
mpi_include="-I/usr/include/openmpi-x86_64/ -I/usr/include/MUMPS/ -L/usr/lib64/openmpi/lib/"
os.system("cd gpvdm_core;./configure CPPFLAGS=\"-I/usr/include/suitesp... | This function detects the Linux distribution and chipset, prompts user confirmation, then configures the system using distribution-specific settings. If successful, it builds the configuration; otherwise, it notifies the user of unsupported platforms. | def configure_autodetect(d):
import distro
plat=distro.linux_distribution(full_distribution_name=False)[0].lower()
chipset=os.uname().machine
configured=False
if d.yesno("Configure for "+plat+" "+chipset) == d.CANCEL:
return
if plat=="fedora":
configured=True
configure_for_fedora(d)
elif plat=="debian":
... |
def build_configure_all():
build_configure("gpvdm_core")
build_configure("gpvdm_gui")
build_configure("gpvdm_data")
def make_all(d):
if d.yesno("Run make clean") == d.OK:
os.system("cd gpvdm_core;make clean >../log.txt 2>../log.txt ;cd ../gpvdm_gui; make clean >../log.txt 2>../log.txt ;cd ../gpvdm_data; make clea... | The code presents a menu for selecting Linux distributions, checks if the user is root, and executes build/configure scripts tailored to each OS (e.g., Fedora, Debian, Raspberry Pi). It handles specific build steps, logs output, and triggers compilation via `make_all`, with distinct workflows for ARM, 32-bit, and 64-bi... | def select_distro_menu(d):
if os.geteuid() == 0:
d.msgbox("Don't do a build as root")
return
code, tag = d.menu("build for:",
choices=[("(back)", "back"),
("(fedora)", "fedora (x86_64)"),
("(debian)", "debian (x86_64)"),
("(raspberry)", "Raspberry (ARM)"),
("(cento... |
def huffman( counts , verbose=0 ) :
"""
Takes in a list of counts.
Runs the huffman algorithm, and optionally sorts and prints the resulting tree.
>>> c = huffman([0.5, 0.25, 0.125, 0.125],1) # doctest: +NORMALIZE_WHITESPACE
#Symbol Count Codeword
1 (0.5) 1
2 (0.25)... | The code demonstrates Huffman encoding and decoding using a simple example. It generates a Huffman tree from symbol counts [1,2,3,4], encodes the sequence [1,2,3,4,3,2,1] into a binary string, then decodes it back to verify accuracy. The test confirms that the encoded string "10010111011101100" correctly reconstructs t... | def easytest():
"""
This test routine demonstrates use of the huffman function, which takes
a list of simple counts as its input. It uses the encode function
to encode a sequence of symbols, [1,2,3,4,3,2,1]. It then uses
decode to recover the original sequence.
>>> easytest()
1001011101110... |
def get_workflow_parent_context(self):
return copy.deepcopy(self._parent_ctx)
def get_workflow_input(self):
return copy.deepcopy(self._inputs)
def log_errors(self, errors, task_id=None, route=None, task_transition_id=None):
for error in errors:
self.log_error(
error,
... | This method initializes the workflow state by creating a WorkflowState instance, merging rendered inputs and variables into the initial context, handling errors by logging and failing the workflow if present, and setting up initial execution routes and staged tasks for root nodes if no errors occur. | def workflow_state(self):
if not self._workflow_state:
self._workflow_state = WorkflowState(conductor=self)
# Set any given context as the initial context.
init_ctx = self.get_workflow_parent_context()
# Render workflow inputs and merge into the initial context.... |
def get_workflow_status(self):
return self.workflow_state.status
def get_workflow_terminal_context(self):
if self.get_workflow_status() not in statuses.COMPLETED_STATUSES:
raise exc.WorkflowContextError('Workflow is not in completed status.')
wf_term_ctx = {}
term_tasks = s... | The main task of the code is to generate and persist workflow outputs when the workflow is completed. It checks if the workflow status indicates completion, merges terminal context with state data, renders outputs using the workflow specification, stores non-empty outputs, logs any rendering errors, and marks the workf... | def _render_workflow_outputs(self):
wf_status = self.get_workflow_status()
# Render workflow outputs if workflow is completed.
if wf_status in statuses.COMPLETED_STATUSES and not self._outputs:
workflow_ctx = self.get_workflow_terminal_context()
state_ctx = {'__state': s... |
def get_workflow_status(self):
return self.workflow_state.status
def get_task(self, task_id, route):
try:
task_ctx = self.get_task_initial_context(task_id, route)
except ValueError:
task_ctx = self.get_workflow_initial_context()
state_ctx = {'__state': self.workf... | The main task of the code is to determine and return the next tasks in a workflow, handling both regular and remediation tasks. It checks the workflow status, filters relevant tasks, evaluates their actions, and manages errors during task rendering. If errors occur, it logs them, marks the workflow as failed, and retur... | def get_next_tasks(self):
fail_on_task_rendering = False
staged_tasks = self.workflow_state.get_staged_tasks()
remediation_tasks = []
next_tasks = []
# Identify remediation tasks if workflow failed.
if self.get_workflow_status() == statuses.FAILED:
remediatio... |
def getPawnMoves(self,r,c,moves):
piecePinned = False
pinDirection=()
for i in range(len(self.pins)-1,-1,-1):
if self.pins[i][0] == r and self.pins[i][1] == c:
piecePinned = True
pinDirection=(self.pins[i][2],self.pins[i][3])
self.pi... | This function generates all possible moves for the current player by iterating through the board, checking each piece's color against the turn, and calling specific methods for each piece type (pawn, rook, king, queen, knight, bishop) to collect valid moves into a list, which is then returned. | def getPossibleMoves(self):
moves=[]
for r in range(len(self.board)):
for c in range(len(self.board[r])):
turn = self.board[r][c][0]
if (turn =="w" and self.white_to_move) or (turn=="b" and not self.white_to_move):
piece= self.board[r][c][1... |
def checkforChecksAndPins(self):
inCheck = False
pins = []
checks = []
if self.white_to_move:
enemyColor="b"
allyColor="w"
startRow=self.whiteKingLocation[0]
startCol=self.whiteKingLocation[1]
else:
enemyColor="w"
... | This function generates legal moves for the current player, considering check and pin scenarios. It identifies the king's position, checks if the king is in check, and filters valid moves to avoid leaving the king in check. If in check, it handles single or double checks by blocking or moving the king, removing invalid... | def getLegalMoves(self):
moves=[]
self.inCheck,self.pins,self.checks=self.checkforChecksAndPins()
if self.white_to_move:
KingRow=self.whiteKingLocation[0]
KingCol=self.whiteKingLocation[1]
else:
KingRow=self.blackKingLocation[0]
KingCol=sel... |
def filename_filter(fn):
return ''.join((filter(lambda x: x not in ['(', ')'], fn)))
def info(msg):
log(msg, 'I')
def rename(old_f, new_f, msg):
if old_f == new_f:
return old_f
elif DRYRUN:
info('Dry run: would rename [{}] {} to {}'.format(msg, old_f, new_f))
else:
try:
... | This function renames files in a specified directory by removing unwanted characters like parentheses from filenames. It iterates through each file, generates a cleaned filename using `filename_filter`, and renames the file if changes are detected. If in dry-run mode, it logs the intended renaming without executing it;... | def clean_filenames(parent_d):
"""
Rename all files in the dir to remove parenthesis, etc
"""
for f in os.listdir(parent_d):
old_f = os.path.join(parent_d, f)
new_f = os.path.join(parent_d, filename_filter(f))
if old_f != new_f:
if DRYRUN:
info('Dry ru... |
def clean_album_name(name, spaces=False):
for k in ALBUM_NAME_REPLACEMENT.keys():
name = name.replace(k, ALBUM_NAME_REPLACEMENT[k])
if spaces:
name = name.replace(' ', '')
return name
def error(msg, exc=None, exc_info=None):
log(msg, 'E', exc, exc_info)
def rename(old_f, new_f, msg):
... | The function reads metadata from a JSON file, extracts the album title, cleans it, renames the directory using the cleaned name, and returns the new path. If metadata errors occur, it skips renaming and returns the original directory path. | def rename_album_dir(parent_d, d):
"""
Read metadata.json, rename the dir, and return the new name
"""
mf = os.path.join(parent_d, d, METADATA)
try:
with open(mf) as f:
md = json.load(f)
name = clean_album_name(md['albumData']['title'].encode('utf-8'))
# T... |
def info(msg):
log(msg, 'I')
def delete(f, msg):
if DRYRUN:
info('Dry run: would be deleting [{}] {}'.format(msg, f))
else:
try:
if os.path.isdir(f):
shutil.rmtree(f)
else:
os.remove(f)
info('Deleted [{}] {}'.format(msg, f))... | The main task of the code is to process a non-album directory by deleting its metadata file, renaming and moving all files to a designated "NO_ALBUM_DIR" with a standardized naming format, and finally deleting the original directory. This involves cleaning filenames, organizing non-album content, and removing unused me... | def process_nonalbum_dir(parent_d, d):
old_dir = os.path.join(parent_d, d)
new_dir = os.path.join(parent_d, NO_ALBUM_DIR)
info('--- Process non-album dir {}'.format(old_dir))
delete(os.path.join(old_dir, METADATA), 'useless') # delete metadata.json
# move all files to NO_ALBUM_DIR
for f in os.... |
def is_image(f):
"""
Only flag JPEG and PNG. GIFs don't support EXIF and HEIC are guaranteed to have timestamps.
"""
if os.path.splitext(f)[1].lower() in ['.jpg', '.jpeg', '.png']:
return True
else:
return False
def is_exif_set(f):
devnull = open(os.devnull, 'wb')
run = '{} "... | The main task of the code is to recursively traverse directories, identify image files with unset EXIF DateTimeOriginal metadata, extract timestamps from metadata, and update the EXIF data accordingly. The function processes each file in the directory tree, applies timestamp updates where needed, and recursively repeat... | def walk_dir(root_d):
"""
Recursively walk all directories and update EXIF DateTimeOriginal from metadata
"""
for f in os.listdir(root_d):
ff = os.path.join(root_d, f)
if os.path.isfile(ff) and is_image(ff) and not is_exif_set(ff):
timestamp = get_metadata_timestamp(ff)
... |
def info(msg):
log(msg, 'I')
def rename_album_dir(parent_d, d):
"""
Read metadata.json, rename the dir, and return the new name
"""
mf = os.path.join(parent_d, d, METADATA)
try:
with open(mf) as f:
md = json.load(f)
name = clean_album_name(md['albumData']['title']... | The main task of the code is to process an album directory by renaming it, removing obsolete metadata files, and cleaning filenames by eliminating parentheses. The function takes a parent directory and a subdirectory name, constructs the full path, logs the process, renames the directory, deletes the metadata.json file... | def process_album_dir(parent_d, d):
this_d = os.path.join(parent_d, d)
info('--- Process album dir {}'.format(this_d))
new_d = rename_album_dir(parent_d, d)
# Delete metadata.json that's no longer needed
delete(os.path.join(new_d, METADATA), 'no longer needed')
# Remove parens from all files ... |
def info(msg):
log(msg, 'I')
def is_album(name):
if re.match(NON_ALBUM_DATE_REGEX, name) or re.match(NON_ALBUM_HANGOUT_REGEX, name):
return False
else:
return True
def file_move(parent_d, f, type):
old_f = os.path.join(parent_d, f)
if type == 'album':
new_f = os.path.join(par... | The function `move_files` processes all top-level files in a given directory, moving each file to either the 'album' or 'non-album' subdirectory based on the `is_album` check. It does not delete files but organizes them into designated folders according to their classification. | def move_files(parent_d):
"""
Go over all top level files and move them to right dirs
and delete all non metadata.json files (photo metadata)
"""
info('------ PROCESS FILES')
for f in os.listdir(parent_d):
ff = os.path.join(parent_d, f)
if os.path.isfile(ff):
if is_a... |
def info(msg):
log(msg, 'I')
def remove_empty_dir(d):
path, dirs, files = next(os.walk(d))
if METADATA in files:
files.remove(METADATA) # if this is the only file, remove dir still
if len(files) == 0:
return delete(d, 'empty dir')
return False
def is_album(name):
if re.match(NON_... | The main task of the code is to process directories within a parent folder by skipping a specific directory, removing empty directories, and handling non-empty directories as either albums or non-albums through separate processing functions. | def massage_folders(parent_d):
# now go over all dirs and rename/move them
info('------ PROCESS DIRECTORIES')
for d in os.listdir(parent_d):
if d == NO_ALBUM_DIR:
continue # skip this one
dd = os.path.join(parent_d, d)
if os.path.isdir(dd):
if remove_empty_di... |
def init():
if len(sys.argv) not in [2, 3]:
print('Wrong arguments!')
print('- first arg: directory with images')
print('- second arg: optional -e to execute the changes (the default is a dry run)')
sys.exit(1)
if len(sys.argv) == 3 and sys.argv[2] == '-e':
global DRYRUN... | The main task of the code is to initialize settings, remove media metadata from files, move files, and reorganize folder structures using a provided directory path as input. The `init()` function likely sets up initial configurations, `delete_media_metadata()` strips metadata from media files, `move_files()` relocates ... | def main():
init()
delete_media_metadata(sys.argv[1])
move_files(sys.argv[1])
massage_folders(sys.argv[1]) |
def getAngle1(self):
return self.Angle1
def Axis1Counter_clockwise(self, angleLabel, event=None):
#calculate new link1 tip position
self.Angle1 = self.Angle1 + 1
angleLabel['text'] = self.Angle1
newTipX = self.link1.getBaseXPos() + 150*math.cos(math.radians(self.Angle1))
... | The code calculates inverse kinematics for a robotic arm to determine joint angles needed to reach a target (x, y) position. It computes angles for three joints (Axis1–Axis3), adjusts them via rotation methods if current angles differ from calculated targets, and handles edge cases in trigonometric computations to posi... | def GoTo(self, x, y):
#self.paint_frame.create_oval(
#x - 10,
#800 - y - 10,
#x + 10,
#800 - y + 10,
#fill="red",
#tags="a1"
#)
#inverse kinematic solution to arm angles given target position
#since last 2 links sum ... |
def perturb_length(
lengths: torch.Tensor
) -> torch.Tensor:
"""
Add noise to the lengths of each ray in-place.
Args:
lengths: A tensor of shape `(..., num_points_per_ray)`
containing the lengths at which the rays are sampled.
Duplications here spare room for the noise ad... | The function transforms rays from camera space to world space by applying rotation and translation based on camera parameters (yaw, pitch, roll, radius, delta_x, delta_y). It samples camera positions, adds noise to ray lengths if enabled, and returns transformed rays (origins, directions, lengths) along with updated ca... | def transform_rays(
rays: RayBundle,
yaw: torch.Tensor,
pitch: torch.Tensor,
roll: torch.Tensor,
radius: torch.Tensor,
delta_x: torch.Tensor,
delta_y: torch.Tensor,
add_noise: bool = True
):
r"""
Sample a camera position and Transform rays in Camera Space into World Space.... |
def get_corrected_delta_depth(
yaw: torch.Tensor,
pitch: torch.Tensor,
roll: torch.Tensor,
radius: torch.Tensor,
delta_x: torch.Tensor,
delta_y: torch.Tensor,
) -> torch.Tensor:
camera_pos = get_camera_positions(yaw, pitch, radius) # \vec{OC}
camera_dir = F.normalize(camera_pos - 0... | The code generates a rendered image and depth map from 3D planes (xy, xz, yz) and camera parameters using neural rendering. It projects rays onto planes, computes density/color with a decoder, performs ray marching for coarse/fine sampling, and combines results to produce final color, depth, and weights, enabling view ... | def forward(self,
xy_plane: torch.Tensor,
yz_plane: torch.Tensor,
xz_plane: torch.Tensor,
camera: torch.Tensor,
verbose: bool = False,
):
"""
Args:
xy_plane: tensor of shape (B, C, N, N)
xz_plane: tensor of shape (B, C, N, N)
... |
def create_labels(self):
label = tk.Label(self.window, text="Welcome to the parking lot", font=("Arial", 20, "bold"))
label.grid(column=0, row=0, columnspan=21, pady=10)
close_button = tk.Button(self.window, text="CLOSE", command=self.window.quit, font=("Arial", 14, "bold"),
... | This code initializes a Tkinter GUI for a parking lot system, setting up the window, labels, image objects, buttons, and database integration. It manages car slot tracking, initializes data structures for occupied slots, and loads data from a database to populate the application's state. | def __init__(self):
self.window = tk.Tk()
self.window.title("Parking Lot")
self.window.geometry('200x600')
self.window.configure(bg='cyan')
self.buttons = [] # Empty list to store buttons
self.create_labels()
self.create_image_objects()
self.create_butt... |
def is_correct(self, ans):
"""Check for valid answer without adding to player sequence.
Don't add to the sequence so that this can be called multiple times
per button, and detect wrong answers before a button is released.
"""
seq = self.player_seq.copy()
... | The code handles player input in a sequence-matching game by validating button clicks, appending correct answers to the player's sequence, managing timeouts for sequence progression, and triggering game over if an invalid input is detected. | def player_ans(self, ans):
"""Receive a button click and check validity, respond accordingly."""
# Received a click, don't end game because of timeout
Fl.remove_timeout(self.gameover)
# Check validity of click
if self.is_correct(ans):
self.player_seq.app... |
def pseudolegal_positions(self, position):
retVal = []
piece = self.get_piece(position)
if(piece == 'P' or piece == 'p'):
direction = 1
if(piece == 'p'):
direction = -1
up = (position[0] , position[1]+1*direction)
doubleUp =... | The code renders a chessboard-like grid, highlighting pseudolegal positions based on `self.highlight`, using 'X' for own moves and 'A' for opponent moves, with light squares represented by Unicode blocks. It prints the board state and the FEN notation. | def render(self):
highlights = []
if(self.highlight != None):
highlights = self.pseudolegal_positions(self.highlight)
print('-' * 10)
for y in range(7, -1, -1):
print('|', end='')
for x in range(0, 8):
icon = self.get_piece((x, y))
... |
def element_definitions(window):
"""
Manager for element definitions.
:param window: the screen where the elements will exist
:return: tuple of element groups
"""
labels = label_definitions(window)
entries = entry_definitions(window)
button = button_definition(window, entries)
retur... | The main task of the code is to initialize a main window by setting up its UI elements and tooltips. It generates elements using `element_definitions`, draws them with `draw_elements`, and attaches tooltips via `create_tooltip`, all based on the provided `window` object. The function performs these setup tasks without ... | def initialize(window):
"""
Sets up main window elements.
:param window: the window popup
:return: None
"""
elements = element_definitions(window)
draw_elements(elements)
create_tooltip(elements) |
def element_definitions(window, website):
"""
Manager for element definitions.
:param window: the screen where the elements will exist
:param website: the website being viewed
:return: tuple of element groups
"""
clicked = StringVar()
decrypted_results = fetch_data(website) # db query
... | The code's main task is to initialize UI elements for a given website within a popup window. It defines elements using `element_definitions`, draws them with `draw_elements`, and adds tooltips via `create_tooltips`, ensuring the interface is set up and interactive for the specified website. | def initialize(window, website):
"""
Manager function that calls helper functions to define elements and then draw elements.
:param window: the window popup
:param website: the website being viewed
:return: None
"""
elements = element_definitions(window, website)
draw_elements(elements)
... |
def label_definitions(window):
"""
Creates the text on the screen.
:param window: the screen where the text will exist
:return: tuple of text labels
"""
header = Label(window, text="Matt's Password Manager")
username = Label(window, text='Username:')
password = Label(window, text='Passwo... | The main task of the code is to create and return UI element groups (labels, entries, and a button) for a given window. It delegates element creation to helper functions, aggregates them into a tuple, and returns them for use in a GUI application. | def element_definitions(window):
"""
Manager for element definitions.
:param window: the screen where the elements will exist
:return: tuple of element groups
"""
labels = label_definitions(window)
entries = entry_definitions(window)
button = button_definition(window, entries)
return... |
def listbox_definitions(frame):
"""
Listbox and scrollbar definitions. Populates the listbox with database data and configures the scrollbar
to interact with the listbox.
:param frame: the part of the window where the listbox will be located
:return: tuple of listbox and scrollbar elements
"""
... | The function `element_definitions` manages UI element creation for a given window, generating and grouping components like frames, listboxes, labels, and buttons. It returns a tuple containing these organized element groups for use in a graphical interface. | def element_definitions(window):
"""
Manager for element definitions.
:param window: the screen where the elements will exist
:return: tuple of element groups
"""
frame = Frame(window)
list_and_scroll = listbox_definitions(frame)
labels = label_definitions(window, frame)
buttons = bu... |
def element_definitions(window):
"""
Manager for element definitions.
:param window: the screen where the elements will exist
:return: tuple of element groups
"""
labels = label_definitions(window)
entries = entry_definitions(window)
button = button_definition(window, entries)
return... | The main task of the code is to initialize a GUI by defining elements via `element_definitions`, drawing them using `draw_elements`, and attaching tooltips with `create_tooltip`, all under a provided `root` master frame. The function orchestrates element creation, rendering, and tooltip setup in a structured workflow. | def initialize(root):
"""
Manager function that calls helper functions to define elements and then draw elements.
:param root: master frame
:return: None
"""
elements = element_definitions(root)
draw_elements(elements)
create_tooltip(elements) |
def element_definitions(window):
"""
Manager for element definitions.
:param window: the screen where the elements will exist
:return: tuple of element groups
"""
frame = Frame(window)
list_and_scroll = listbox_definitions(frame)
labels = label_definitions(window, frame)
buttons = bu... | The function `initialize` manages the setup of a UI by first defining interactive elements using `element_definitions`, then rendering them on the provided window via `draw_elements`, and finally creating tooltips for these elements with `create_tooltips`. Its primary task is to orchestrate the initialization of graphi... | def initialize(window):
"""
Manager function that calls helper functions to define elements and then draw elements.
:param window: the current screen
:return: None
"""
elements = element_definitions(window)
draw_elements(elements)
create_tooltips(elements) |
def submit_args():
if len(sys.argv) != 4:
print("Invalid Input!",end="")
return 1
try:
k = int(sys.argv[1])
goal = sys.argv[2]
intgoal = int(goals[goal].value)
input_filename = sys.argv[3]
f_input_1 = open(input_filename,"r")
length_file = len(f_in... | The main task of the code is to execute a clustering algorithm based on input parameters, processing a matrix file to perform spectral clustering (spk) or other matrix operations (jacobi, wam, etc.). It handles error cases, generates output files, and prints results. If the input arguments indicate an error or invalid ... | def main():
args = submit_args()
mus_filename = 'mus_file.txt'
data_filename = "matrix_from_C.txt"
if args == 1:
return 1
k, goal, input_filename = args
try:
matrix = mykmeanssp.Spkmeans(k,goal,input_filename)
if matrix!= None:
if goal == 0: # goal = spk
... |
def get_files(path):
"""Return a list of all file path in the given dictionary path."""
file_list = []
for root, dirs, files in os.walk(path, topdown=True):
for name in files:
if name.split('.')[-1] == 'py' and name != 'tests.py':
file_path = os.path.join(root, name)
... | The code checks Python files or directories for code style issues by parsing command-line arguments, reading files, and using multiple check functions to identify and report specific issues. It collects warnings for each file and prints them in a structured format. | def main():
parser = argparse.ArgumentParser(description='Check the code style of python file.')
parser.add_argument("path", help='Enter the path of dictionary or file to check.', default=None, nargs='?')
args = parser.parse_args()
path_to_check = args.path
path_list = []
# Check the path is a ... |
def compute_fid_infinity(path_to_stylized, path_to_style, batch_size, device, num_points=15, num_workers=1):
"""Computes the FID infinity for the given paths.
Args:
path_to_stylized (str): Path to the stylized images.
path_to_style (str): Path to the style images.
batch_size (int): Batc... | The function `compute_art_fid` calculates an **ArtFID score** by combining **FID (Fréchet Inception Distance)** and **content distance** metrics. It computes FID between stylized and style/content images (via `compute_fid` or `compute_fid_infinity` based on mode) and content distance (using LPIPS/VGG/AlexNet) between s... | def compute_art_fid(path_to_stylized, path_to_style, path_to_content, batch_size, device, mode='art_fid_inf', content_metric='lpips', num_workers=1):
"""Computes the FID for the given paths.
Args:
path_to_stylized (str): Path to the stylized images.
path_to_style (str): Path to the style images... |
def send_cmd(ser, start, address, length, typee, operand, content):
# List of commands (a list for the general case) #TODO move this list to another point
payload_list = []
payload_list.append([typee, operand, content]) # Example to try a list of commands: payload_list = example_multiple_payloadlist()
... | The function `send_cmd_string` sends predefined serial commands based on the input string (e.g., "ON", "OFF", "STATUS"), with optional value parameters and redundancy. It uses `send_cmd` to transmit hex-formatted instructions, handling value conversion, default settings, and command-specific parameters. Redundancy repe... | def send_cmd_string(ser, string, val=0, redundancy=1):
for i in range(0, redundancy):
value = val # do not remove, useful for the redundancy
if string == "ON":
send_cmd(ser, 0x55, 0x01, 0x01, 0x02, 0x0B, 0x00000001)
time.sleep(0.3)
elif string == "OFF":
se... |
def open_window_init(self):
print("Window opened")
def run_plc_check(self):
if not self.__thread_plc.isRunning():
self.__thread_plc = self.__get_thread_plc()
self.__thread_plc.start()
else:
print("Thread already running, killing it")
self.__thread_... | The code initializes a MainWindow by setting up UI components, disabling the close button, creating threads for PLC communication, and connecting the exit button to the close method. | def __init__(self):
self.__thread = QtCore.QThread()
self.__thread_plc = QtCore.QThread()
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.open_window_init()
self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False) # disa... |
def send_cmd_string(ser, string, val=0, redundancy=1):
for i in range(0, redundancy):
value = val # do not remove, useful for the redundancy
if string == "ON":
send_cmd(ser, 0x55, 0x01, 0x01, 0x02, 0x0B, 0x00000001)
time.sleep(0.3)
elif string == "OFF":
se... | This function reads a parameter from a serial device, sends a command, waits for a response, processes the received data into a structured format, updates the provided data structure (`rf_values`), and tracks non-response occurrences (`noresp_counter`). It handles hex conversion, payload parsing, and optional verbose o... | def read_param(ser, noresp_counter, rf_values, param="STATUS", wait=1, verbose=False):
# read response
start_waiting = time.time()
resp_len = 0
send_cmd_string(ser, param)
while time.time() <= start_waiting + wait:
r = ser.read(100)
resp_len = len(r)
if resp_len == 0:
... |
def rf_log(text):
write_to_file(log_file, "{} {}".format(datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S"), text))
def disablePlayButton(self):
self.ui.Qplay.setEnabled(False)
def enableStopButton(self):
self.ui.Qstop.setEnabled(True)
def enableResetButton(self):
self.ui.Qreset.setEnabled(... | The main task of the code is to initialize a GUI window by updating the status label, logging a startup message, configuring button states based on a configuration flag (`execution_from_config`), and initiating a long-running task. It disables certain buttons (Play, Exit, Open CSV) and enables others (Stop, Reset) when... | def open_window_init(self):
global execution_from_config
global log_file
self.ui.QoutputLabel.setText("Process started.")
# Save log file
rf_log("Software ON, ready to start.")
if execution_from_config:
self.disablePlayButton()
self.enableStopButto... |
def shooting_sounds():
global mag, shooting, last_shot, curr_time, mag_size, m4_sounds, lobby, nickname
#shooting sounds
if held_keys["left mouse"] and mag > 0:
if not shooting:
shooting = True
last_shot = time.perf_counter()
mag -= 1
shoot_check_hit()... | The code updates game state by handling player movement, shooting sounds, location broadcasting, death detection, and gun animation. It adjusts the gun's position/rotation based on movement, manages running speed, sends location every 0.2s when alive, and triggers death events if the player falls off-screen. | def update():
"""
Updates values and then renders to screen
"""
global gun_up, running, moving, enemies, last_loc_send, my_player, alive
shooting_sounds()
if alive:
# check if enough time had passed to send current location
curr = time.perf_counter()
if curr - last_loc_s... |
def diffie_hellman(sock):
global key, tcp_sock
n = 1008001 # relatively large prime number
g = 151 # small prime number
a = random.randint(0, n)
bg = int(recv_by_size(tcp_sock).decode("utf-8"))
ag = (g**a) % n
send_with_size(sock, str(ag))
key = (bg**a) % n
key = key.to_bytes(32, ... | The code handles the pre-game start menu by connecting to a server, performing a Diffie-Hellman key exchange, and allowing a user to create or join a lobby with a nickname and password. It sends encrypted messages to the server, waits for confirmation, and returns True if the game can start, or exits with errors otherw... | def menu():
"""
Takes care of start menu before the game begins
"""
global nickname, tcp_sock, lobby, password
connected = False
try:
tcp_sock.connect((IP, PORT))
print(f'Connect succeeded {IP}:{PORT}')
connected = True
except:
print(f'Error while trying to c... |
def tcp_broadcast(self, message):
print(f"broadcasting - {message}")
for player in self.players:
encrypt_send(self.players[player][0], message, keys[player])
def send_walls(self):
#sending the walls' locations
#wall number 1
self.walls["wall1"] = [13, 0, 0, 13, 5, 1]
... | The code's main task is to initialize a game session by setting the 'playing' flag to True, broadcasting "GAMEON" and "START" signals via TCP, printing a lobby start message, and preparing game elements like walls and player locations for active gameplay. | def ready(self):
if not self.playing:
self.playing = True
self.tcp_broadcast("GAMEON")
print(f"Starting lobby called {self.name}")
#sending the walls' locations
self.send_walls()
# generating and sending player locations
for pla... |
def is_empty(self):
# TC: O(1); SC: O(1)
return self.start_node is None and self.end_node is None and self.__len__() == 0
def _actions_on_pop_when_len_is_1(self) -> Node | None:
# pop itself when len(q) == 1
if self.__len__() == 1:
node = self.start_node
self.star... | This code removes a node with a specified ID from a doubly linked list in O(1) time and space. It handles edge cases like empty lists or missing IDs by raising errors, checks if the node is the first/last element to use specialized removal methods, and updates adjacent nodes' pointers to maintain list integrity. It als... | def pop(self, id: int) -> Node:
# pop by id from anywhere; TC: O(1); SC: O(1)
if self.is_empty() or (self.nodes.get(id, None) is None):
raise ValueError(f"id {id} not found in tasks")
tmp = self._actions_on_pop_when_len_is_1()
if tmp is not None:
return tmp
... |
def is_empty(self):
# TC: O(1); SC: O(1)
return self.start_node is None and self.end_node is None and self.__len__() == 0
def _actions_on_pop_when_len_is_1(self) -> Node | None:
# pop itself when len(q) == 1
if self.__len__() == 1:
node = self.start_node
self.star... | The function removes a node at a specified index from a doubly linked list, handling edge cases like invalid indices, empty lists, and single-node scenarios. It adjusts neighboring node links, removes the node from the list's node collection, and returns the popped node. | def pop_at_index(self, index: int) -> Node:
# pop at any index; TC: O(N); SC: O(1)
# needed for removing task if previous tasks cannot be executed due to resource limitations
if index < 0:
raise ValueError("negative index does not exist in a list")
if self.is_empty():
... |
def is_empty(self):
# TC: O(1); SC: O(1)
return self.start_node is None and self.end_node is None and self.__len__() == 0
def append_left(self, data: Task) -> None:
# TC: O(1); SC: O(1)
# if empty
if self.is_empty():
return self.insert_to_empty_list(data)
# ... | This method inserts a new task node at a specified index in a doubly linked list, handling edge cases like invalid indices, empty lists, and duplicate IDs. It adjusts node pointers to maintain list integrity, supporting dynamic task priority updates or mid-list insertions. | def insert_at_index(self, index: int, data: Task) -> None:
# insert at any index; TC: O(N); SC: O(1)
# needed if one wants to implement task priority update or insert task into the middle (aka higher priority)
if index < 0:
raise ValueError("negative index does not exist in a list")
... |
def pullSpaces():
deleteSpaces()
results = dbspaces.posts.insert_many(xml25live.querySpaces())
def pullReservations():
deleteReservations()
for room in getSpaces():
idtime = xml25live.queryTimes(room["space_id"])
print("Information: %s" % idtime)
result = dbidtimes.posts.insert_one(idtime)
print("Updated Sp... | The main task of the code is to synchronize data by calling three functions: `pullSpaces()` to retrieve space information, `pullReservations()` to fetch reservation details, and `pullGpsMappings()` to update GPS mapping data, ensuring all relevant data sources are refreshed and aligned. | def updateAll():
pullSpaces();
pullReservations();
pullGpsMappings(); |
def uniform_cost_search(self, head_node):
closed_list = []
open_queue = []
closed_list.append(head_node)
open_queue.append(head_node)
while open_queue:
node = open_queue.pop(0)
self.states_visited += 1
self.search_path.append(node)
... | The code executes a search algorithm (UCS, A*, or GBFS) to solve a board game, records the solution path and search steps, measures execution time, and logs results including game ID, algorithm type, heuristic, solution length, search depth, and time to a file. | def play(self):
# Search algorithm
state = {"board": self.board, "cars": self.cars, "move": []}
node = {"state": state, "parent": {}, "cost": 0}
print(self.board)
if self.algorithm == "ucs":
start = time.time()
final_node = self.uniform_cost_search(node)
... |
def get_containers(stack):
containers = []
containers.extend(stack.containers)
for c in stack.children:
containers.extend(get_containers(c))
return containers
def get_container_name(c):
global root_stack
name = f"{root_stack.name}_"
for s in get_stacks(root_stack):
name += f"... | This code initializes and starts a Docker container stack by setting up a network, removing existing containers, pulling necessary images, configuring environment variables, and creating containers with specified volumes, ports, and networking settings. It ensures the 'stacker' network exists, handles container creatio... | def start_stack(stack):
try:
apiClient.remove_network("stacker")
except:
# Network does not exist, create it
pass
try:
apiClient.create_network("stacker")
except Exception as e:
print("Unable to create container network 'stacker': ")
print(e)
pass
... |
def compute_random_spike(self,config):
active_count, active = self.compute_active_functions(config)
# if config in self.explored_states:
# key = tuple(config)
# comb_count = np.prod(active_count, where = active_count > 0)
# spike_count = len(self.state_graph['nodes'][key]['spike'])
# if(comb_count ==... | The function generates a spiking matrix representing active neuron functions based on configuration parameters. It computes active functions, constructs a matrix of spikes by iterating through neurons and their active functions, and optionally samples a subset of rows if a branch size is specified. The matrix is initia... | def get_smatrix(self,config,branch=None):
if branch == 'initial':
spike = self.compute_random_spike(config)
return np.tile(np.array(spike, dtype=float), (1, 1))
active_count, active = self.compute_active_functions(config)
comb_count = np.prod(active_count, where = active_count > 0)
spiking_mx = np.zeros(... |
def get_smatrix(self,config,branch=None):
if branch == 'initial':
spike = self.compute_random_spike(config)
return np.tile(np.array(spike, dtype=float), (1, 1))
active_count, active = self.compute_active_functions(config)
comb_count = np.prod(active_count, where = active_count > 0)
spiking_mx = np.zeros(... | This function simulates a single state's transitions in a branching process. It calculates next states using matrix operations (S, P, E, V), explores potential states, updates unexplored states, and records the state in a graph with computed parameters. It handles both default and spike-configured states, computes enga... | def simulate_single(self,config,depth,branch=None,spike=None):
next_states = []
S = self.get_smatrix(np.array(config),branch) if spike is None else\
np.tile(np.array(spike, dtype=float), (1, 1))
P, E = self.get_pmatrix(np.array(config))
V = self.get_vmatrix(S,np.array(config))
IV, IM = self.get_inputs_det... |
def compute_random_spike(self,config):
active_count, active = self.compute_active_functions(config)
# if config in self.explored_states:
# key = tuple(config)
# comb_count = np.prod(active_count, where = active_count > 0)
# spike_count = len(self.state_graph['nodes'][key]['spike'])
# if(comb_count ==... | This function processes the next state in a graph by checking if a configuration exists in the state graph. If not, it simulates a new node. It updates the node's spike information, input details, and returns a formatted configuration. The task involves managing graph nodes, handling spikes, inputs, and state transitio... | def next(self, config, depth, spike=None):
key = tuple(config)
if spike is None:
spike = self.compute_random_spike(config)
if key not in self.state_graph['nodes']:
self.simulate_single(config, depth, 'initial', spike)
node = self.state_graph['nodes'][key]
if spike not in node['spike']:
self... |
def InitialPopulation(Inputs: inputs, population_size: int):
"""
Randomly generated population
:param Inputs:
:param n:
:return:
"""
population = []
print('Initial population:')
for _ in range(population_size):
while True:
solution = heuristic_solution(Inputs)
... | The code implements a genetic algorithm to optimize a problem by evolving a population of solutions over a specified running time. It initializes a population, sorts it, and iteratively applies crossover (with 80% probability) or heuristic-based solutions to update the population. The process continues until the time l... | def GeneticAlgorithm(Inputs: inputs, RunningTime: float):
"""
Genetic algorithm launched for a selected running time in second then it returns the best solution of the population
:param Inputs:
:param RunningTime:
:return:
"""
population_length = 20
start_time = time.time() * 1000
po... |
def clearscreen(x, y, width, height):
block = pygame.Rect(startx + (x * blocksize), starty + (y * blocksize), width * blocksize, height * blocksize)
pygame.draw.rect(s, RESET, block)
def createsfinderboxes():
for box in ezsfindervariables:
setezsfinderbutton(box[0], "deprecated", box[1], box[2], box... | The function `createmenu()` displays UI elements based on the `menu` variable's value. If `menu == 1`, it creates finder, text, and true/false boxes; if `menu == 0`, it shows help boxes; if `menu == 2`, it configures settings, control, and true/false options. It first clears the screen using `clearscreen()` to reset th... | def createmenu():
clearscreen(17.5, -4, 8.5, 16)
if(menu == 1):
createsfinderboxes()
createsettextboxes()
createtruefalse()
elif(menu == 0):
createhelpboxes()
elif(menu == 2):
createsettingboxes()
createcontrolboxes()
settingtruefalse() |
def clearscreen(x, y, width, height):
block = pygame.Rect(startx + (x * blocksize), starty + (y * blocksize), width * blocksize, height * blocksize)
pygame.draw.rect(s, RESET, block)
def drawghostpiece():
global currentpiece, currentpiecerotation, currentpiecex, currentpiecey, allboards, piecesplaced, bag
... | The function `drawallpieces()` renders the game state by redrawing the board, current piece, ghost piece, and statistics (score, pieces placed, chain counts). It clears sections of the screen, formats and displays metrics with aligned text, handles visual elements like the queue and visualizer, and updates the board la... | def drawallpieces():
global board, lastdrawn
clearscreen(0, 0, boardlength + 6, boardheight + 2)
clearscreen(0, -1, 2, 1)
drawghostpiece()
drawlastcommand()
statx = -5
staty = 5
statincrement = 0.8
statsize = blocksize//4
clearscreen(statx, 5, staty, 10)
stattext(statx, sta... |
def placeable(piece, rotation, column, row):
currentpieceboard = deepcopy(pieces[piece]["shape"])
for i in range(rotation):
currentpieceboard = rotate(currentpieceboard)
for piecerowindex, piecerow in enumerate(currentpieceboard):
for piececolumnindex, piecevalue in enumerate(piecerow):
... | This function handles a "hard drop" in a Tetris-like game, moving the current piece down as far as possible, updating the score, clearing filled rows, placing the piece, and preparing the next piece from the queue. It adjusts positions, checks placement validity, calculates scores, and updates game state variables. | def harddrop():
global currentpiece, currentpiecerotation, currentpiecex, currentpiecey, allboards, piecesplaced, bag, visualizeboard, score, gointob2b, piecesplaced, undooffset
visualizeboard = ""
counter = 0
while placeable(currentpiece, currentpiecerotation, currentpiecex, currentpiecey):
c... |
def clearscreen(x, y, width, height):
block = pygame.Rect(startx + (x * blocksize), starty + (y * blocksize), width * blocksize, height * blocksize)
pygame.draw.rect(s, RESET, block)
def drawinfopieces(x, y, piece):
currentpieceboard = pieces[piece]["shape"]
for piecerowindex, piecerow in enumerate(cur... | This function restores a previously saved game state by copying board configurations, piece data, and scores from a specific index in the 'allboards' list. It initializes game variables, handles visual elements like the hold piece, resets the piece bag if empty, and redraws the game interface with the current piece's p... | def loadboard():
global nopieceboard, board, queue, currentpiece, holdpiece, bag, piecesplaced, currentpiecerotation, currentpiecex, currentpiecey, score, undooffset, visualizeboard
visualizeboard = ""
nopieceboard = deepcopy(allboards[-1 - undooffset][0])
board = deepcopy(nopieceboard)
queue = de... |
def piecepick():
global bag
chosenseed = ((piecesplaced * startingseed) + startingseed * startingseed)
seed(chosenseed)
piecepicked = choice(bag)
bag.remove(piecepicked)
if(len(bag) == 0):
bag = deepcopy(ogbag)
return piecepicked
def clearscreen(x, y, width, height):
block = pyga... | The code resets a Tetris-like game by initializing global variables, setting a random seed, generating a new piece queue, resetting the board, score, and counters, and preparing the game state for a new session. | def reset():
global holdpiece, currentpiece, queue, currentpiecerotation, currentpiecex, currentpiecey, nopieceboard, board, bag, score, piecesplaced, startingseed, visualizeboard, consecutivepcs, consecutiveb2bs
startingseed = randint(0, 100000)
bag = deepcopy(ogbag)
currentpiece = piecepick()
qu... |
def round_given_columns(data):
"""
We are rounding a number of columns to facilitate branching of the decision tree.
:param data: Original training data.
:return: data: Training data with rounded weather variables.
"""
data['temp'] = data['temp'].round()
data['atemp'] = data['atemp'].round()... | The main task of the code is to perform feature engineering on the input dataset by applying a series of transformations: rounding specific columns, adding features like free days, weekends, day types, binned hours, and good day indicators, calculating dew points, and binning dew values to enhance the dataset's predict... | def feature_engineering(data):
"""
We are performing a number of feature engineering operations.
:param data: Original training data.
:return: data: Original training data with additional features.
"""
data = round_given_columns(data)
data = add_variable_free_day(data)
data = add_variabl... |
def read_in_training_data():
"""
We are reading in the data and we split the outcome variables.
:return: train_x: Training data for the algorithm.
:return: train_y: All outcome variables for the training data.
"""
# We are finding the the folder where the data is stored.
path_training_data... | The function preprocesses and prepares training and test data for a machine learning model by reading datasets, extracting date features, combining data for unified preprocessing, interpolating missing values, performing feature engineering, splitting back into train/test sets, applying log transformation to labels, an... | def preprocess_save_data():
"""
We are reading in the data and performing all preprocessing steps.
:param perform_preprocessing: Repeat preprocessing or load data.
:return train_x: Training data for the algorithm.
:return train_y: Labels for the training data.
:return test_x: Test cases which ne... |
def isSufficientMaterial(board):
whiteMaterial = getMaterial(board,1)
blackMaterial = getMaterial(board,-1)
if blackMaterial[:5] == (0,0,0,0,0) and whiteMaterial[:5] == (0,0,0,0,0):
return False
if (whiteMaterial[:5] == (0,1,0,0,0) and blackMaterial[:5] == (0,0,0,0,0)) or (whiteMaterial[:5] == (... | The function generates all legal moves for the current player on a chessboard, considering rules like threefold repetition, 50-move draw, and insufficient material. It checks each piece's possible moves, filters out those that leave the king in check, and returns either the list of legal moves, a checkmate (0), or stal... | def getLegalMoves(board,player,castle,en,halfmove,history):
attack_mask = 0
legalMoves=[]
for move in set(history):
if history.count(move) > 2:
return [2,[]]
if halfmove == 100:
return [2,[]]
if not isSufficientMaterial(board):
return [2,[]]
... |
def _create_node_from_fen(self, fen):
"""
Creates a new TreeNode object from a given FEN string.
:param fen: The FEN string representing the game state.
:return: A TreeNode object representing the game state.
"""
board = chess.Board(fen)
turn = 'white' if board.tu... | The code determines the best next move for the current player using Alpha-Beta pruning. It evaluates legal moves from the given game state (node), applies each move to generate child nodes, and calculates scores recursively. The best move is selected based on maximizing/minimizing scores depending on the player's turn,... | def get_best_next_move(self, node, depth, notation="SAN"):
"""
Determines the best next move for the current player using the Alpha-Beta pruning algorithm.
:param node: The current game state.
:param depth: The depth of the search tree to explore.
:param notation: The notation sy... |
def get_board_visualization(self, board):
"""
Generates a visual representation of the board.
:param board: The board to visualize.
:return: A visual representation of the board.
"""
print(board)
def _apply_move(self, move, node, notation="SAN"):
"""
Appli... | The code visualizes the board state evolution as a specific move is applied iteratively up to a given depth, displaying each resulting position and the best next move at each step. It starts from the root node, applies the move using the specified notation (default: SAN), and prints the board after each move. The proce... | def visualize_decision_process(self, depth, move, notation="SAN"):
"""
Visualizes the decision-making process for a particular move up to a certain depth.
:param depth: The depth of the analysis.
:param move: The move being analyzed.
:param notation: The notation system for the m... |
def getWalls():
MAX_DISTANCE_WALL = 7
correctDirection(NORTH)
north, west, east = getSensors()
correctDirection(EAST)
_, _, south = getSensors()
walls = (west < MAX_DISTANCE_WALL, north < MAX_DISTANCE_WALL, east < MAX_DISTANCE_WALL, south < MAX_DISTANCE_WALL)
return walls
def getPossible... | The code determines the robot's current position by tracking movement history and wall encounters. It appends wall data and direction to a list, then checks possible positions. If only one position remains valid, it returns it. Otherwise, it randomly selects a direction, adjusts it, and moves forward to narrow down pos... | def findPosition():
movementList = []
direction = None
while True:
walls = getWalls()
movementList.append((walls, direction))
positionsList = getPossiblePositions(movementList)
# return position when there is only one possible position
if len(positionsList) == 1:
... |
def getCylindersDistances():
redDir = getCylinderDirection(RED)
redDis = getSensors()[0] + cylinder_radius
yellowDir = getCylinderDirection(YELLOW)
yellowDis = getSensors()[0] + cylinder_radius
greenDir = getCylinderDirection(GREEN)
greenDis = getSensors()[0] + cylinder_radius
blueDir = g... | The main task of the code is to estimate a robot's position and grid cell by calculating x/y coordinates using distances from four colored cylinders (red, yellow, green, blue) and returning the cell, x, and y values for localization or navigation. | def getPose():
redDis, yellowDis, greenDis, blueDis = getCylindersDistances()
x, y = getXY(red_x, red_y, redDis, green_x, green_y, greenDis, blue_x, blue_y, blueDis)
cell = getCellEstimation(x, y)
return cell, x, y |
def __misclassification(self, x_dot_w, label):
''' Returns true if x is misclassified. '''
return x_dot_w * label < 1
def __gradient(self, x, label):
''' Returns the gradient of the loss with respect to the weights '''
regularizer = self.__regularizer_g(x)
return {k: (v * label -... | The main task of the code is to compute gradients and train loss for a model. It iterates over data points, calculates gradients based on misclassification or regularization, accumulates gradients in `total_delta_w`, and computes loss using hinge loss and regularization. If `update=True`, model weights are updated with... | def fit(self, data, labels, update=True):
'''
Calculates the gradient and train loss.
If the update flag is set to False, gradient is calculated but own weights will not be updated
'''
total_delta_w = {}
train_loss = 0
for x, label in zip(data, labels):
... |
def read_data(amount_data, show_bugs=False):
"""Read data
Parameters
----------
amount_data : int
show_bugs: bool
Returns
-------
data_storage : list of int
"""
red = "\033[1;31m"
off = "\033[0;0m"
filename = amount_data_filename(amount_data)
try:
data_stora... | The main task of the code is to sort a list of integers generated from the input `amount_data` using a specified sorting algorithm (`bubble` or `insertion`). It reads the data, applies the chosen sorting method, and returns the sorted list. If an invalid sort type is provided, it raises an error. | def sort_data(amount_data, sort_type='bubble'):
"""
Parameters
----------
amount_data : int
sort_type : string, optional
Returns
-------
data : list of int
"""
data = read_data(amount_data)
sort_type = sort_type.lower()
if sort_type == 'bubble':
data = bubble_so... |
def board_set(board):
for row in board:
print(' | '.join(row))
print('-' * 9)
def best_move(board):
best_eval = float('-inf')
best_move = None
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
board[i][j] = AI_BOT
eval = mi... | This code implements a tic-tac-toe game where a human player and AI alternate turns on a 3x3 board. The human inputs moves, while the AI uses a best_move function for its turns. After each move, the board updates, and the game checks for a win or draw. The loop continues until a winner is declared or the game ends in a... | def start_game():
board = [[EMPTY] * 3 for _ in range(3)]
player_turn = random.choice([USER, AI_BOT])
board_set(board)
while True:
if player_turn == USER:
move = input("Enter row and column (0-2) for your move: ").split()
row, col = map(int, move)
if boar... |
def ac_01_pure_function(domains, constraints):
old_domains = dict(domains)
constraints = augment_with_inverses(constraints)
revise_count = 0
while True:
new_domains = dict(old_domains)
for constraint in constraints:
new_domains = revise_pure_function(constraint, new_domains)
... | The main task of the code is to demonstrate constraint propagation algorithms AC-01 and AC-03 on a sample constraint satisfaction problem. It initializes example variable domains and constraints, then applies both algorithms to compute and print updated domains after enforcing the constraints. The code compares the res... | def main():
example_domains = {
"a": [1, 2, 3, 4],
"b": [1, 2, 3, 4],
"c": [1, 2, 3, 4],
"d": [1, 2, 3, 4],
}
example_constraints = [
("a", "c", "a == 2 * c"),
("b", "c", "b > c + 1"),
("a", "d", "a > d - 1"),
]
print("-" * 60)
print("AC-01... |
def process_argv(argv: Optional[List] = None) -> namedtuple:
"""Processes argv into namedtuple."""
parser = setup_parser()
if argv:
args, unknown_args = parser.parse_known_args(argv)
else:
args, unknown_args = parser.parse_known_args()
args_dict = vars(args)
args_dict["extras"... | The main task of the code is to execute a program with provided command-line arguments, handle exceptions, log execution time and errors, and return an exit code. It processes arguments, initializes logging, runs the program, records runtime, and returns 0 on success or 1 on failure. | def main(argv=None) -> int:
exit_code = 0
argv = argv or sys.argv
args = process_argv(argv)
setup_logger()
start = time.time()
try:
run(args)
logger.info("Finished, took %s seconds.", round(time.time() - start, 2))
except Exception as e:
logger.exception(e)
e... |
def get_datset(config):
raw_dataset = load_dataset(f"{config['datasource']}", f'{config["lang_src"]}-{config["lang_tgt"]}', split='train')
tokenizer_src = get_or_build_tokenizer(raw_dataset, config, config['lang_src'])
tokenizer_tgt = get_or_build_tokenizer(raw_dataset, config, config['lang_tgt'])
... | The code trains a sequence-to-sequence model (e.g., transformer) using a specified configuration. It initializes the model, sets up training parameters (optimizer, loss function), loads data, and performs training with backpropagation. It logs metrics via TensorBoard, validates periodically, saves checkpoints, and hand... | def train_model(config):
# device definition
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# create weights folder if it doesn't exist
Path(f"{config['datasource']}_{config['model_folder']}").mkdir(parents=True, exist_ok=True)
# ... |
def run_calculation_in_thread(window, data, selected_sheet, selected_columns, selected_result_column, calculation_settings):
global cancel_calculation
# NB: this function was created and annotated using OpenAI's ChatGTP.
# Create a thread for the calculation
calculation_thread = CalculationThread(targe... | The main task of this code is to provide a **graphical user interface (GUI)** for performing **Automatic VTNA (Virtual Thermal Non-Equilibrium Analysis)** calculations on kinetic data. The tool allows users to:
1. **Load kinetic data** from Excel or CSV files.
2. **Configure analysis settings** (e.g., fitting constrai... | def main():
# NB: some parts of the main GUI code was written with help from OpenAI's ChatGTP.
# Define the cancel_calculation as global
global cancel_calculation
img = None # Placeholder for overlay score versus order plot image.
fixed_orders={} # Placeholder for fixed_orders dictionary
enable_... |
def _select_action(self, state, epsilon):
"""
Helper function to choose between the explore-exploit dilemma
This is actually the pi(a|s) function
"""
p = np.random.random()
if p <= epsilon:
selected_action = np.random.choice(self.action_space)
else:
... | The code performs policy iteration using a linear function approximator with TD learning. It iteratively updates the weight vector W by minimizing the TD error over episodes, using epsilon-greedy action selection. After training, it updates the policy and value function based on learned Q-values, returning the maximum ... | def iterate_policy(self, env, alpha=0.1, gamma=0.9, epsilon=0.3, num_episodes=1000):
deltas = []
for n in range(num_episodes):
print("Running policy iteration episode: {}".format(n))
max_diff = float("-inf")
s = self.start_state
while not env.is_terminal(... |
def _select_action(self, state, epsilon):
"""
Helper function to choose between the explore-exploit dilemma
This is actually the pi(a|s) function
"""
p = np.random.random()
if p <= epsilon:
selected_action = self.env.action_space.sample()
else:
... | This function implements Q-learning to update the weights of a Q-function approximator over multiple episodes. It uses epsilon-greedy action selection, computes TD targets with gamma discounting, and updates weights via stochastic gradient descent. The maximum Q-value difference per episode is recorded in 'deltas' to m... | def iterate_policy(self, alpha=0.1, gamma=0.9, epsilon=0.3, num_episodes=1000):
""" Implementation of Q learning on the environment """
deltas = []
for n in range(num_episodes):
print("Iterating episode {}".format(n))
s = self.env.reset()
done = False
... |
def read_input(fname): # For reading from the file
data_points = []
for row in fileinput.FileInput(fname):
info = row.split()
data_points.append((int(info[0]), int(info[1]), int(info[2])))
return data_points
def median(data, axis): # Calculates and return the median
data_axis = []
... | The main task of the code is to map input points into a grid-based spatial partitioning structure, dynamically splitting grids when buckets overflow. It reads dataset points, assigns them to grid cells, and splits grids along x/y axes using median values when buckets reach capacity, updating the grid and split points a... | def Mapper_func(grid, b, split_point_x, split_point_y, bucket_name): # Main Mapper function that reads points one by one and add to GRID and BUCKET
points = read_input("DataSet.txt") # Name of the DatSet
axis = 'y'
c = 0
for record in points:
for g in range(len(grid)):
if grid[g].x... |
def load_data(load_filepath, gen_filepath):
# read data in:
load_data = pd.read_csv(load_filepath).drop('Unnamed: 0', axis=1)
gen_data = pd.read_csv(gen_filepath).drop('Unnamed: 0', axis=1)
return load_data, gen_data
def preprocess_data(load_data, gen_data):
# generates the files used for prediction... | The main task of the code is to load and preprocess two datasets (loaded_data and gen_data), save the processed data, then re-load the datasets, apply a second preprocessing method, split the cleaned data into training and test sets, and save these subsets for further use in machine learning tasks. | def main(input_gen_file, input_load_file, output_data_file, train_output, test_output):
loaded_data, gen_data = load_data(input_load_file, input_gen_file)
data = preprocess_data(loaded_data,gen_data)
save_data(data, output_data_file)
loaded_data_wide, gen_data_wide = load_data(input_load_file, input_gen... |
def handleinput(value):
try:
MatchIt(value).res_value()
return value[1]
except NoResMatchWarning:
res = check(value)
if(res!=None):
print(f'Command not found : {value}\n Did you mean -{res} ?'.format())
else:
... | The code defines a recursive function `organize()` that processes user commands for image manipulation and file management tasks. It measures execution time, handles input to trigger actions like displaying help, resizing images, converting formats, editing files, generating edges, or deleting folders. The function loo... | def organize():
start = time()
try:
common = handleinput(myinput())
if common == 'h':
print('>>')
help()
elif common == 's':
getImageSize()
elif common == 'c':
convertImg()
elif common == 'm':
editSpImgExtFile(st... |
def set_depths(tree: nx.DiGraph, node, depth: int = 0) -> None:
tree.nodes[node]['depth'] = depth
for child in tree.successors(node):
set_depths(tree, child, depth + 1)
def remove_exceeding_nodes(tree: Tree, dataset: Dataset) -> None:
exceeding_nodes = [
node
for node in tree.structu... | The main task of the code is to prune a decision tree by removing redundant nodes, adjusting node labels to match dataset classes, and ensuring structural validity. It sets node depths, removes exceeding nodes, computes cutoff metrics, applies relabeling until stabilization, corrects leaf labels with majority classes, ... | def prune(tree: Tree, dataset: Dataset, epsilon: float = 1) -> Tree:
set_depths(tree.structure, tree.root)
remove_exceeding_nodes(tree, dataset)
compute_cutoff_metrics(tree.structure, tree.root, len(dataset), epsilon)
cutoff(tree, dataset, tree.root)
current_nodes = tree.structure.number_of_nodes(... |
def setupCameraLight(self):
# create a orbiting camera
self.cameractrl = CameraCtrl(self, self.cam)
self.cameraRefNode = self.camera # pc.NodePath('camera holder')
self.cameraRefNode.setPos(0,0,0)
self.cameraRefNode.setHpr(0,0,0)
self.cameraRefNode.reparentTo(self.render)... | This code initializes a 3D environment by setting up a camera, loading ground and character models, configuring display properties, creating a texture for links, and registering tasks for updates and input handling. It disables mouse control, adjusts camera settings, limits frame rate to 60 FPS, and prepares the scene ... | def __init__(self, fStartDirect=True, windowType=None):
'''
this is only used for my project... lots of assumptions...
'''
super().__init__(fStartDirect, windowType)
self.disableMouse()
self.camera.lookAt(0,0.9,0)
self.setupCameraLight()
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.