dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def sunrise(self) -> datetime:
"""Calculates the time of the sunrise.
Returns:
A datetime object, containing the time of the sunrise.
"""
return self.calculate_time()
def format_time(time_: t.Union[datetime, float]) -> str:
"""Formats time to hours and minutes.
Args... | The function retrieves and formats sunrise and sunset times, selecting the next day's sunrise if available, then returns both formatted times as a string. | def get_sun_times(self) -> str:
if self.sun_tomorrow is None:
sunrise = self.sunrise()
else:
sunrise = self.sun_tomorrow.sunrise()
return format_time(sunrise), format_time(self.sunset()) |
def sunrise(self) -> datetime:
"""Calculates the time of the sunrise.
Returns:
A datetime object, containing the time of the sunrise.
"""
return self.calculate_time()
def format_time(time_: t.Union[datetime, float]) -> str:
"""Formats time to hours and minutes.
Args... | The code's main task is to generate a string representation of an object's sunrise, sunset, day length, and time-to-change details. It dynamically selects the sunrise time from either the current instance or a 'sun_tomorrow' attribute, formats the output with specific time details, and returns the structured string for... | def __str__(self) -> str:
if self.sun_tomorrow is None:
sunrise = self.sunrise()
else:
sunrise = self.sun_tomorrow.sunrise()
return (
f"Sunrise at: {sunrise.strftime('%H:%M')}\n"
f"Sunset at: {format_time(self.sunset())}\n"
f"{self.day_... |
def getRequest():
conn = sqlite3.connect('small.db', detect_types=sqlite3.PARSE_DECLTYPES, check_same_thread=False)
cur = conn.cursor()
keys = [
"ID",
"title",
"address",
"room_num",
"start_date",
"end_date",
"message",
"user_id"
]
info... | The function `view_request` retrieves a requestID from URL parameters, fetches associated request data (`posts`) and comments (`comments`), and renders a template to display the request details. If the request method is POST, it captures a user comment, associates it with the requestID, and stores it. The template is r... | def view_request():
requestID = request.args.get('requestID')
posts = getRequest()
if request.method == 'POST':
comment = request.form["comment"]
load_comment(comment, requestID)
comments = getComment()
return render_template('view_request.html', posts=posts, comments=comments, requ... |
def initialize_alignment(self):
self.alignment_matrix[0,0] = Node(0, [])
for i in range(1,len(self.P)+1):
self.alignment_matrix[i, 0] = Node(i, [(i-1, 0)])
for j in range(1,len(self.T)+1):
self.alignment_matrix[0, j] = Node(0, [(0, j-1)])
def fill_alignment_matrix(self)... | The main task of the code is to find all valid alignment positions of a pattern in a sequence using dynamic programming. It initializes alignment, fills a matrix with scores, identifies valid end positions within a max distance threshold, and uses backtracking to trace all possible alignments. The result is a set of lo... | def find_pattern(self):
# initialization
self.initialize_alignment()
# recurrence
self.fill_alignment_matrix()
#self.print_alignment_matrix()
# find where to backtrack
bottom_row = self.alignment_matrix[len(self.P), :]
indices = []
for j in ran... |
def selection_from_generation(cur_gen, N=10, rand=5, verbose=False, mutation_rate=0.08):
## Get the best population from the last step
fittness_scores = check_fitness(cur_gen)
## sort such that lowest trip duration is first
sorted_cur_gen = sorted(fittness_scores, key=lambda x: x[1])
#print(sor... | The code implements a genetic algorithm over a specified number of generations. It selects parents (combining top performers and random entries), generates offspring with mutation, tracks the best solution's fitness, and returns the fitness history and final best guess. Verbose output logs generation progress and best ... | def final_solve(cur_generation, max_generations, take_best_N, take_random_N,
mutation_rate, perCouple_children, print_every_n_generations, verbose=False):
fitness_tagging = []
for i in range(max_generations):
if verbose and not i % print_every_n_generations and i > 0:
... |
def new_images(login_frame):
canvases=[]
photo_images=[]
total_width=0
categories = ["cat", "mouse", "flower"]
num_images_per_category = 1
# Iterate over categories to create canvases with images
for i, category in enumerate(categories):
# Get random images for the current category
... | This function creates a login GUI interface with a canvas, including a title, username/password fields, login/back buttons, and image placeholders. It sets window properties, arranges elements via canvas placement, and links buttons to authentication and navigation functions. | def create_canvas(window):
window.title("Login Page")
window.geometry("1280x600")
login_frame = Frame(window, height=600, width=1280,bg='#F5F5DC')
login_frame.pack(fill='both', expand=1)
width = 700
height = 700
# canvas for title
canvas = Canvas(login_frame, width=width, height=height... |
def read_the_transcript_file(file_path):
"""method to read the transcript file"""
# open and read the transcript file.
file_obj = open(file_path, 'r')
# removing unnecessary spaces.
text = file_obj.read()
return text
def sentence_tokenizer(text):
"""method for sentence tokenizer in transcrip... | The main task of the code is to align transcribed audio segments with a main transcript by tokenizing, filtering, and comparing text. It processes each audio transcription, matches sentences via word similarity, and organizes aligned segments into a structured output. The result is written to a text file, linking times... | def audio_transcript_segmentation(audio_list, main_audio_transcript):
"""control the main method"""
# method call
text_document_content = read_the_transcript_file(main_audio_transcript)
# method call
sentence_token_content = sentence_tokenizer(text_document_content)
print(sentence_token_content)... |
def moveEast(self, distance):
print('moving {} to the east'.format(distance))
self.wayPointEast += distance
def moveWest(self, distance):
print('moving {} to the west'.format(distance))
self.wayPointEast -= distance
def moveNorth(self, distance):
print('moving {} to the north'.fo... | This code defines a `move` method that directs an object to move in a specified direction (east, west, north, south, left, right, or forward) by a given distance. It delegates movement to specific methods based on the direction input and then calls a `print` method to output the result. The primary task is to handle di... | def move(self, direction, distance):
if direction == EAST:
self.moveEast(distance)
elif direction == WEST:
self.moveWest(distance)
elif direction == NORTH:
self.moveNorth(distance)
elif direction == SOUTH:
self.moveSouth(distance)
e... |
def oblique(self, pi, pcf, pcp, ccf):
if pcf == ccf:
intervals = list(filter(lambda x:x!=pi, self.consonants))
ri = randint(0, len(intervals)-1)
return intervals[ri]
else:
# if the melody moves, then the cp must stay the same
ci = self.quickObl... | This function generates a random interval from a list of 'imperfect' intervals, adjusted by octaves if necessary, based on conditions comparing pcf and ccf. It uses oblique, quickOblique, or contrary methods depending on gap calculations and filter criteria, ensuring valid intervals are selected through iterative expan... | def directAbove(self, pi, pcf, pcp, ccf):
if pcf == ccf:
return self.oblique(pi, pcf, pcp, ccf)
if ccf > pcf:
gap = pi - self.findInterval(ccf,pcf)
fil = lambda x:x>gap
y = 1
else:
gap = pi + self.findInterval(ccf,pcf)
fil =... |
def oblique(self, pi, pcf, pcp, ccf):
if pcf == ccf:
intervals = list(filter(lambda x:x!=pi, self.consonants))
ri = randint(0, len(intervals)-1)
return intervals[ri]
else:
# if the melody moves, then the cp must stay the same
ci = self.quickObl... | The code selects a random interval from self.imperfects based on conditions involving pcf, ccf, and pi. It adjusts intervals by adding 8 iteratively if no valid intervals exist, and returns a random valid interval or results from auxiliary methods like oblique, quickOblique, or contrary when specific criteria are met. | def directBelow(self, pi, pcf, pcp, ccf):
if pcf == ccf:
return self.oblique(pi, pcf, pcp, ccf)
if ccf > pcf:
gap = pi + self.findInterval(pcf,ccf)
fil = lambda x:x<gap
y = 1
else:
gap = pi - self.findInterval(pcf,ccf)
fil =... |
def oblique(self, pi, pcf, pcp, ccf):
if pcf == ccf:
intervals = list(filter(lambda x:x!=pi, self.consonants))
ri = randint(0, len(intervals)-1)
return intervals[ri]
else:
# if the melody moves, then the cp must stay the same
ci = self.quickObl... | The function `contraryAbove` selects a random consonant interval from a list, adjusted based on conditions involving parameters `pcf`, `ccf`, and `pi`. It filters intervals using a dynamic gap calculation, prioritizing specific methods (`oblique`, `quickOblique`, `direct`) depending on the relationship between `pcf` an... | def contraryAbove(self, pi, pcf, pcp, ccf):
if pcf == ccf:
return self.oblique(pi, pcf, pcp, ccf)
if ccf > pcf:
gap = pi - self.findInterval(ccf,pcf)
fil = lambda x:x<gap
y = 1
else:
gap = pi + self.findInterval(pcf,ccf)
fil... |
def oblique(self, pi, pcf, pcp, ccf):
if pcf == ccf:
intervals = list(filter(lambda x:x!=pi, self.consonants))
ri = randint(0, len(intervals)-1)
return intervals[ri]
else:
# if the melody moves, then the cp must stay the same
ci = self.quickObl... | The function `contraryBelow` selects a consonant interval from a list based on conditions involving parameters `pi`, `pcf`, `pcp`, and `ccf`. It adjusts the interval size using `findInterval`, filters valid intervals with a lambda function, and randomly chooses from filtered results. If no valid intervals exist, it att... | def contraryBelow(self, pi, pcf, pcp, ccf):
if pcf == ccf:
return self.oblique(pi, pcf, pcp, ccf)
if ccf > pcf:
gap = pi + self.findInterval(ccf,pcf)
fil = lambda x:x>gap
y = 1
else:
gap = pi - self.findInterval(ccf,pcf)
fil... |
def _createDeadCells(self):
newCells = []
for y in range(self._maxy):
newCol = []
for x in range(self._maxx):
newCol.append(Dead())
newCells.append(newCol)
return newCells
def _getLiveNeighborCount(self, x, y):
count = 0
for xOf... | This code updates a cellular automaton grid by applying Game of Life rules: it checks each cell's live neighbors, preserves live cells with 2-3 neighbors, creates new live cells where dead cells have exactly 3 neighbors, and updates the grid state while tracking cell age for visual/color effects. | def tick(self):
oldCells = self._cells
newCells = self._createDeadCells()
for x in range(self._maxx):
for y in range(self._maxy):
neighborCount = self._getLiveNeighborCount(x, y)
if oldCells[x][y].isLive() and neighborCount in [2, 3]:
... |
def getHistoryDiversityScore(self):
score = 0
hashes = {}
for hash in self._hashHistory:
hashes[hash] = 1
for key, value in hashes.items():
score += value
return score
def injectRandomNewNeighbor(self):
if self.getLiveCount() < 1:
retur... | The code's main task is to prevent system stagnation by introducing randomness when conditions indicate potential "stuckness." It checks three criteria: if diversity is low, it injects new neighbors; if live elements are insufficient, it seeds randomness; and if a glider chance threshold is met, it creates a random gli... | def handleStuck(self):
if self.getHistoryDiversityScore() < 3:
self.injectRandomNewNeighbor()
if self.getLiveCount() < 2:
self.seedRandom()
if self._gliderChance > random.randrange(100):
# Create a randomly located Glider to smash stuff
self._creat... |
def _net2wider_target_conv(self,
target_conv_layer: str,
width: int,
sigma: float,
random_pad: bool) -> np.ndarray:
"""Widen a convolutional layer of a neural network
Args:
... | This function widens specified convolutional layers in a neural network by increasing their output filter count. It adjusts connected layers (convolutional or fully connected) and batch normalization layers to accommodate the new width. The operation uses random mapping for filter indices, initializes new filters with ... | def net2wider_operation(self,
target_conv_layers: list,
next_layers: list,
width: list,
batch_norm_layers: list = [None],
sigma: float = 0.001,
random_p... |
def moveServo(index, targetPosition):
if(index == 0 or index == 1):
verticaleMove2(targetPosition)
return
# if(index == 2 or index == 4):
if(targetPosition < minValues[index]):
targetPosition = minValues[index]
if(targetPosition > maxValues[index]):
targetPosition = maxV... | The code positions multiple servos to specific angles (7°, 5°, 6°, 2°, 4°) and executes vertical movements, likely controlling a robotic arm or mechanical system. It adjusts servos sequentially, with conditional checks for certain positions, then finalizes movements to predefined angles and vertical offsets. The main t... | def last():
moveServo(7,90)
moveServo(5,0)
moveServo(6,90)
# moveServo(4,180)
# verticaleMove2(120)
ifLessThenMoveTo(0, 120, 120)
# moveServo(2,90)
ifGreatThenMoveTo(2, 90, 90)
verticaleMove2(170)
moveServo(2,0)
moveServo(4,140) |
def get_bass_instr(midi):
for i, inst in enumerate(midi.instruments):
if 'bass' in inst.name.lower():
return i
raise LookupError('Bass does not exist')
def get_guitar_instr(midi):
gtrs = []
for i, inst in enumerate(midi.instruments):
if 'gtr' in inst.name.lower() or 'guitar... | This function processes all MIDI files in a specified directory to extract pairs of bass and guitar notes. It identifies bass and guitar instruments, divides the MIDI into measures (optionally doubled), and generates note pairs between the bass and each guitar track. The resulting pairs are aggregated and returned as a... | def get_pairs_all_midis(dir, double_measures=False):
pairs = []
for subdir, dirs, files in os.walk(dir):
for f in files:
midi = pretty_midi.PrettyMIDI(midi_file=dir + '/' + f)
try:
bass_ind = get_bass_instr(midi)
guitar_inds = get_guitar_instr(mid... |
def load(self, path):
with open(path+'.json', 'r') as f:
rules = json.load(f)
return rules
def map_rules(self, rules):
return {rule: self.map_params(params)
for rule, params in rules.items()}
def build_rules(self,rules):
built_rules = []
for _, params... | The main task of the code is to read, process, and construct rule data. It loads raw rules from a specified path, applies mappings to transform them, builds structured rule objects, and returns the final processed rules for use in the system. | def read(self):
rules = self.load(self.path)
rules = self.map_rules(rules)
rules = self.build_rules(rules)
return rules |
def find_legal_moves(self, board):
legal = []
for i in range(len(board[0])):
for j in range(len(board)):
if board[j][i] == 'O' and j == len(board)-1:
legal.append((j,i))
break
if board[j][i] == 'O' and board[j+1][i] != '... | This function implements a depth-limited Minimax algorithm to select the optimal move in a game. It evaluates all legal moves by recursively applying Minimax with a depth constraint, stores each move's value, and chooses the move with the highest value. It then prints the evaluated values for each column and the select... | def depth_limited_minmax(self):
best_move = None
best_value = -float('inf')
move_values = {}
for move in self.find_legal_moves(self.board):
new_state = self.apply_move(self.board, move)
value = self.minmax(new_state, self.depth_limit - 1, False)
move_... |
def average_f(self):
total = 0
for i in self.agent_list:
total += self.get_f(i)
return total/self.n
def count_yes(self):
return self.count_opinion(1)
def count_no(self):
return self.count_opinion(0) | The function updates or creates a summary object based on convergence status. If converged, it updates the last summary's step number. If not, it calculates the average_f metric, constructs a new Summary instance with experiment details, counts, and average_f, appends average_f to a convergence queue, and returns the u... | def step_to_summary(self):
if self.converged:
self.last_summary.stepno = self.stepno
else:
# Compute the average_f value
average_f = self.average_f()
self.last_summary = Summary(self.uuid_exp,
self.ensemble_id,
... |
def step(self):
pass
def test_convergence(self):
'''
Test convergence and avoid extra computation for the rest of simulation time
'''
self.converged = (len(set(self.convergence_queue)) == 1) and (len(self.convergence_queue) == 5)
def save_all(self):
'''
Save all t... | The main task of the code is to repeatedly execute steps until convergence or maximum steps are reached, saving agent states at each iteration. It checks for convergence, performs a step if not converged, increments the step counter, and terminates when either convergence is achieved or the maximum step limit is exceed... | def run(self):
while self.running:
# Perform the step if not converged
if not(self.converged):
self.step()
self.test_convergence()
else:
if self.stepno == self.max_steps:
self.running = False
... |
def train_on_video(head_model, tail_model, ctx_proc, frames, label, head_optimizer, tail_optimizer, n_bins):
"""
Train glow to generate all frames of a video
:param head_model: this Glow model generates the first frame of a video
:param head_frame: this Glow model generates all other frames of the video... | The code trains a video generation model by optimizing a head model (generating the first frame) and a tail model (generating subsequent frames) using a dataset. It processes frames with downsampling, computes losses (log_p, log_det, video_loss), logs metrics, and saves checkpoints. Periodic sampling generates and save... | def train(args, ds, head_model, tail_model, ctx_proc, head_optimizer, tail_optimizer, n_epochs=1, n_frames=30):
"""Head model produces the first frame of the video. Tail model produces the rest of the frames."""
# Load dataset of images
#dataset = iter(sample_data(args.path, args.batch, args.img_size))
... |
def parse_cfg_files(app_cfg_file, batch_cfg_file, platforms_supported):
fbatch = open(batch_cfg_file, "r")
batch_config = json.load(fbatch)
fbatch.close()
fapp = open(app_cfg_file, "r")
app_config = json.load(fapp)
fapp.close()
assert(batch_config["app_name"] == app_config["app_name"]),"ap... | The main task of the code is to process a batch job by configuring input files, creating and submitting a batch, monitoring its completion, downloading output files, and retiring the batch, ensuring proper directory management and error handling for batch execution across specified platforms. | def process_batch(app_cfg_file, batch_cfg_file, platforms_supported):
assert(len(platforms_supported) > 0),"no platforms specified. Provide --platform_supported argument on the command line"
batch_cfg = parse_cfg_files(app_cfg_file, batch_cfg_file, platforms_supported)
if os.path.exists(batch_cfg.outp... |
def get_fixed_cards(cards):
return [card_id for card_id in cards if card_id is not None]
def calculate_rough_chances(board, hands, fixed_cards, mainLayout):
DECK_SIZE = 52
board_saved = board.copy()
hands_saved = deepcopy(hands)
max_counter = 300_000
times = [[0, 0, 0] for _ in range(len(hands))... | This function calculates the number of possible remaining card combinations in a deck for a card game, considering the board, players' hands, and discarded cards. It computes exact or rough probabilities by evaluating combinations using factorial math, then triggers probability calculations based on whether the total c... | def start_calculator(mainLayout):
DECK_SIZE = 52
hands = []
board = [card.card_id for card in mainLayout.children[2].children]
for hand_grid in mainLayout.children[1].children:
hand = [hand_grid.children[4].children[0].card_id, hand_grid.children[4].children[1].card_id]
hands.append(han... |
def sort_data(train, valid):
data = np.loadtxt(train)
# Special case of just one data sample will fail
# without this check!
if len(data.shape) < 2:
data = np.array([data])
print(data)
# Sort all columns - just retain sorted indices
# NOT the sorted data to prevent need to resort
... | The code trains a decision tree (ID3 algorithm) using training data, then evaluates its accuracy on validation data. It reads input files, extracts features and labels, constructs the tree, makes predictions, and calculates the number of correct classifications. The main task is to build and assess a decision tree mode... | def main():
train_file = sys.argv[1]
valid_file = sys.argv[2]
train_data, valid_data = sort_data(train_file, valid_file)
labels_train = train_data[:, -1]
labels_valid = valid_data[:, -1]
attributes = train_data[:, :-1]
print(attributes)
# iloc allows us to pick specific row/col
... |
def set_cor_mosaic():
"""
p_in and p_ref are N x 2 matrices (correspond to (x,y) coordinates)
criterion: selected 8 corner points from both images.
"""
p_in = np.array([[1187, 1009],
[1282, 693],
[1447, 694],
[1255, 241],
... | The code performs two tasks: (1) Image mosaicing by warping an input image using a computed homography matrix to align it with a reference image, then merging them. (2) Image rectification by adjusting an input image using corresponding points to correct perspective, saving the aligned/rectified result. Both tasks invo... | def main():
##############
# step 1: mosaicing
##############
# read images
img_in = Image.open('data/porto1.png').convert('RGB')
img_ref = Image.open('data/porto2.png').convert('RGB')
# shape of igs_in, igs_ref: [y, x, 3]
# the two images have the same shape
igs_in = np.array(... |
def send_command(self, command, response_delay:float = 0.1):
# print(">> " + command)
try:
if not self.connection:
self.connect()
self.connection.sendall((command.encode("ascii") + b"\n"))
sleep(response_delay) # Wait for response dela... | The main task of the code is to restart a safety system by sending a 'restart safety' command, waiting 10 seconds, disconnecting and reconnecting to the system, releasing brakes, and returning the output of the initial restart command. This sequence ensures proper system reset and safety protocol reinitialization. | def restart_safety(self):
output = self.send_command('restart safety')
sleep(10)
self.disconnect()
self.connect()
output2 = self.brake_release()
return output |
def get_robot_mode(self):
"""Return the robot mode"""
output = self.send_command("robotmode")
output = output.split(' ')
return output[1]
def get_operational_mode(self):
return self.send_command('get operational mode')
def get_safety_status(self):
output = self.send_comma... | The main task of the code is to retrieve and standardize the robot's operational status by converting mode-related attributes to uppercase and storing them as instance variables, while also checking the remote control status. | def get_overall_robot_status(self):
self.robot_mode = self.get_robot_mode().upper()
self.operational_mode = self.get_operational_mode().upper()
self.safety_status = self.get_safety_status().upper()
self.remote_control_status = self.is_in_remote_control() |
def get_overall_robot_status(self):
self.robot_mode = self.get_robot_mode().upper()
self.operational_mode = self.get_operational_mode().upper()
self.safety_status = self.get_safety_status().upper()
self.remote_control_status = self.is_in_remote_control()
def unlock_protective_stop(self)... | The main task of the code is to initialize a robot system by checking its status, handling safety conditions (e.g., unlocking protective stops, restarting safety), switching operational modes from manual to automatic if needed, ensuring remote control readiness, and powering on the robot while releasing brakes if it's ... | def initialize(self):
if self.connection_error:
return
self.get_overall_robot_status()
if self.safety_status == 'PROTECTIVE_STOP':
print("Unlocking protective stop")
self.unlock_protective_stop()
elif self.safety_status != "NORMAL": #s... |
def validate_task_resource_map(t_r_map):
row = 0
for t_r in t_r_map:
row += 1
if len(t_r) < 3:
print("Missing data at ROW: %d" % (row) )
return False
try:
if not(t_r[2].isnumeric()):
print("Wrong work-day param at ROW: %d" % (row) )
... | The main task of the code is to optimize resource allocation for tasks based on dependencies and resource availability, minimizing project duration. It collects input data (task-resource mapping, task dependencies, start date), validates them, computes task timelines for different allocations, identifies the optimal al... | def __Main__(t_r_map=None, d_p_map=None, process_start=None):
''' Debuug '''
# Welcome Script ...
print("----------------")
print("----------------")
print("RESOURCE PLANNER")
print("----------------")
print("----------------")
if(t_r_map==None):
# Collecting T_R_MAP ...
... |
def _save_menu(self):
"""
Saves the current menu on disk as a json file, at path timestamp_menu.json
:return: None
"""
with open(f"./menu/{datetime.now().strftime('%Y%m%d-%H%M%S')}_menu.json", 'x') as f:
json.dump(self._menu, f)
def _say(self, sentence):
"""
... | The code processes user commands by analyzing syntax, handling save/load operations, determining frames, switching between frames, and generating appropriate responses based on the current frame, with verbose output and frame stack management for context restoration. | def process(self, command):
"""
Processes the given command
:param command: command
:return: a proper reply (None if interaction is over)
"""
# obtain spacy syntax dependency tree
parsed = syntax_analysis(command)
# if prompted to load last stored menu, ... |
def extract(zip_path, project_dir, extract_dict):
"""Extracts files from zip archive according to extract_dict.
Returns list of paths of extracted files.
Parameters
----------
zip_path : Path
Path to zip archive
project_dir : Path
Path to project directory
extract_dict :... | This function preprocesses Sentinel-2 satellite data and DEM for analysis by extracting bands, downloading/clipping DEM, reprojecting, stacking raster layers, and generating inference-ready tiles. It handles file management, including optional deletion of temporary files after processing. | def run_default_preprocessing(project_dir, s2_zip_path, extract_dict=None, delete_all=True):
Mtic, mtic = time.time(), time.time()
print(f"o---o---o---o---o---o---o\tNot Started \t\t\t(0/7 - {time.time()-mtic:.2f}s|{time.time()-Mtic:.2f}s)")
if extract_dict is None:
extract_dict = EXTRACT_DICT
... |
def extract(zip_path, project_dir, extract_dict):
"""Extracts files from zip archive according to extract_dict.
Returns list of paths of extracted files.
Parameters
----------
zip_path : Path
Path to zip archive
project_dir : Path
Path to project directory
extract_dict :... | This function processes multiple Sentinel-2 zip files by extracting, converting, downloading and processing DEM data, reprojecting, stacking, and generating tiles for machine learning (training/inference). It handles file cleanup and returns tiled data directories for model input preparation. | def run_multiple_default_preprocessing(project_dir, s2_zip_paths, extract_dict=None, set_type='inference', delete_all=True):
Mtic, mtic = time.time(), time.time()
num_images, num_steps = len(s2_zip_paths), 7*len(s2_zip_paths)+2
project_dir = Path(project_dir)
print(f"o---o---o---o---o---o---o\tNot Star... |
def insert(root, key,pos):
if not root:
return TreapNode(key,pos)
if key <= root.key:
root.left = insert(root.left, key,pos)
if root.left.priority > root.priority:
root = rightRotate(root)
else:
root.right = insert(root.right, key,pos)
if root.right.priority > root.priority:
root = leftRotate(ro... | The code performs a permutation swap on a matrix `M` by first constructing a binary tree from its elements, then swapping the nodes at positions `i` and `j` using a `multiswap` function, and finally returning the inorder traversal of the modified tree. The random seed is set for reproducibility, though the exact swappi... | def swap_permutation(M,i,j):
random.seed(0)
root = None
for x in range(len(M)):
root = insert(root, M[x],x)
x = multiswap(root, i,j,len(M))
z = inorder(root)
return (z) |
def LCA(u, v, n):
LCA_aux = np.full(n+5, -1)
if node[u].depth < node[v].depth:
u, v = v, u
while u != -1:
LCA_aux[u] = 1
u = node[u].par
while v:
if LCA_aux[v] == 1:
break
v = node[v].par
return v
def op(x,y):
if mode==0:
#maximiza
return max(x,y)
else:
return min(x,y)
def crawl_tree(u, v,... | The main task of the code is to find the maximum edge weight on the path between nodes u and v in a tree. It computes the lowest common ancestor (LCA) of u and v, then traverses the tree from u and v up to the LCA using `crawl_tree`. The results are combined via the `op` function to determine the maximum edge weight al... | def maxEdge(u, v, n, chain_heads):
lca = LCA(u, v, n)
ans = op(crawl_tree(u, lca, n, chain_heads), crawl_tree(v, lca, n, chain_heads))
return ans |
def initialize(C,n,p):
for x in range(len(C)):
addEdge(x+1, C[x][0], C[x][1], p(C[x][0],C[x][1]))
root = 0
parent_of_root = -1
depth_of_root = 0
dfs(root, parent_of_root, depth_of_root, n)
chain_heads = np.full(N, -1)
edge_counted = [0]
curr_chain = [0]
hld(root, n-1, edge_counted, curr_chain, n, chain... | The code processes queries on a tree structure to determine the maximum edge weight between nodes. It initializes the tree with edges `C` and node count `n`, then handles queries in `Q` specifying node pairs and modes (0/1). For each query, it calculates the maximum edge using `maxEdge` and prints results via `printing... | def main():
C = [[1,2],[1,3],[2,4],[3,5]] #lados del arbol
n = 5 #nodo de mayor valor existente en el arbol
chain_heads = initialize(C,n,p)
#Existen dos modos en los que se pueden calcular los valores:
#mode 0 si es para todas las conexiones entre u y v
#mode 1 si es para algunas de las conexiones entre u y v
... |
def run_program(program, input_json):
output = subprocess.run(shlex.split(program), input=input_json, capture_output=True, text=True)
return output.stderr
def shuffle_input(input_as_list):
"""
Shuffle the input.
:param input_as_list: input as list
:return: shuffled input
"""
random.shuff... | The code reduces a file's input by iteratively halving it, checking which half reproduces the same error, and retaining that half until minimal. If both halves are error-free, it shuffles the input. After reduction, it removes keys and array elements to further simplify the input, saving the result to a file for debugg... | def start_iterations_of_reduction(filename, program):
# read file and check the error and number of lines
number_of_lines = 0
initial_input = ""
with open(filename, 'r') as f:
for line in f:
initial_input += line
number_of_lines += 1
error = run_program(program, init... |
def _check_keydown_events(self, event):
"""Respond to keypresses."""
if event.key == pygame.K_RIGHT:
self.car.moving_right = True
self.seccar.moving_right = True
elif event.key == pygame.K_LEFT:
self.car.moving_left = True
self.seccar.moving_left =... | The main task of the code is to handle user inputs in a Pygame application by iterating through events. It exits the game on quit requests, processes key presses and releases via `_check_keydown_events` and `_check_keyup_events`, and detects mouse clicks to check if the play button is pressed, using the mouse position ... | def _check_events(self):
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.KEYUP:
self._check_key... |
def _check_fleet_edges(self):
for cone in self.cones.sprites():
if cone.check_edges():
self._change_fleet_direction()
break
def _car_hit(self):
if self.stats.cars_left > 0:
self.stats.cars_left -= 1
self.cones.empty()
self.... | The main task of the code is to update the positions of cones, check for collisions between the car and cones, trigger collision responses, and verify if cones have reached the bottom. It ensures movement, collision detection, and boundary checks for cones in a game environment. | def _update_cones(self):
self._check_fleet_edges()
self.cones.update()
if pygame.sprite.spritecollideany(self.car, self.cones):
self._car_hit()
self._check_cone_bottom()
if pygame.sprite.spritecollideany(self.seccar, self.cones):
self._seccar_hit()
... |
def _check_events(self):
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.KEYUP:
self._check_key... | The code defines a game loop that continuously checks for events, updates game objects (cars, bullets, cones), and renders the screen to run the game. | def run_game(self):
while True:
self._check_events()
# if self.stats.game_active:
self.car.update()
self.seccar.update()
self._update_bullets()
self._update_cones()
self._update_screen() |
def touchingObject(self, app):
if self.inCollision:
self.stillInCollsion(app)
return False
else:
# check if car is touching any other cars or walls
return self.inCarCollision(app) or self.inWallCollision(app)
def playCrashSound(self):
mixer.music.l... | This function handles collision responses by checking if the object is touching another entity. If the object is a Player, it plays a crash sound. It retrieves the line segment of the collision, calculates directional vectors (dx, dy), and adjusts the object's angle and velocity based on the collision type (e.g., "Car"... | def collision(self, app):
if self.touchingObject(app):
# play crash sound if player collided
if isinstance(self, Player):
self.playCrashSound()
# get points of the line the car is intersecting
((x1, y1), (x2, y2)) = (self.lineIntersected[0],
... |
def collision(self, app):
if self.touchingObject(app):
# play crash sound if player collided
if isinstance(self, Player):
self.playCrashSound()
# get points of the line the car is intersecting
((x1, y1), (x2, y2)) = (self.lineIntersected[0],
... | The code handles a car's movement by checking for collisions, updating movement variables if no collision occurs, recalculating the car's position based on velocity and angle, updating its visual representation, and applying friction to simulate realistic motion. | def move(self, app):
# collision check
self.collision(app)
# update movement variables
if not self.inCollision:
self.movement()
# updates position
self.x, self.y = self.updateCarCenter(self.angle, self.x, self.y,
... |
def get_var(name, default=None, env=True):
try:
return globals()[name]
except KeyError:
if default is not None:
name = "PYS_{}".format(name.upper())
return os.environ.get(name, default) if env else default
raise
def abspath(x):
"""
Compute absolute path an... | The code sets up logging, determines a home directory, generates a virtual environment (venv) path based on the script's hash, checks for an active venv, creates a new venv with dependencies if needed, and restarts the script using the configured venv's Python interpreter to ensure the correct environment is used. | def main():
log_level = get_var("log", "INFO")
log_level = logging.getLevelName(
int(log_level) if log_level.isdigit() else log_level.upper()
)
logging.basicConfig(
level=log_level,
format="%(asctime)s %(levelname)5s | %(message)s",
datefmt="%I:%M:%S",
)
src = a... |
def read_status():
file = open(STATUSFILENAME, "r")
status = file.readline()
# remove potential noise such as newline
status = re.sub(r"[\n\t\s]*", "", status)
file.close()
print_and_log("Current status is: -->" + status + "<--")
return(status)
def print_and_log(message):
logging.info(m... | The function `close_door` checks if the door is in the "Opened" state. If true, it logs the closing process, triggers an autostop mechanism for a specified duration, and confirms closure. If the door is not open, it logs an error warning. The task ensures proper door closure with status tracking and error handling. | def close_door():
if read_status() == "Opened":
print_and_log("DOOR Closing…")
close_autostop(TIME_CLOSE)
print_and_log("DOOR Closed!")
else:
logging.warning("ERROR! Action CLOSE but door not opened!") |
def replace_spaces_and_commas_with_underscores(text):
return text.replace(" ", "_").replace(",", "_")
def calculate_max(category, identifier, limits):
multiplier = {'Proteinas': 4, 'Lipidos': 9, 'Carbohidratos': 4}
lhs_ineq = []
rhs_ineq = []
for macronutrient in limits:
list_o... | The main task of the code is to create a Streamlit app for nutritional optimization, allowing users to adjust macronutrient quantities (proteins, lipids, carbohydrates) via buttons and display real-time updates against predefined daily limits based on a fixed 2200-calorie intake. The app tracks user inputs in session s... | def main():
st.title("Nutritional Optimization App")
# Calories = st.text_input('Calorie consumption:', 2000)
Calories = 2200
limits = {"Proteinas":{"min":Calories*0.1,"max":Calories*0.35},
"Lipidos":{"min":Calories*0.2,"max":Calories*0.35},
"Car... |
def get_changes_after_last_release(self) -> list[dict[str, str]]:
"""Get all the merged pull request.
Only after specified release, optionally until specified release.
:return: The list of pull requests
"""
since_release_date = self._get_release_date(self.since_version)
... | (The code's main task is to generate a changelog by fetching recent changes since the last release, parsing them into structured data, sorting entries by pull request, and writing the updated changelog. It exits early if no changes are found.) | def run(self) -> None:
"""Entrypoint."""
changes = self.get_changes_after_last_release()
# exit the method if there are no changes found
if not changes:
return
self._string_data = self.parse_changelog(changes)
self._sort_by_pr()
self._write_changelog(... |
def _get_current_price(self):
return self.data.iloc[self._current_tick]['close']
def _no_position(self, action):
self.truncated = False
if action == self.actions[2]:
reward = self._on_buy()
#reward = 0
elif action == self.actions[1]:... | The code defines a `step` method for a reinforcement learning environment, processing an action by updating the environment state, calculating rewards based on position status, tracking balances, and managing episode termination. It records episode metrics, handles rendering, and returns the observation, reward, done s... | def step(self, action):
self.data.iloc[self._current_tick, self.data.columns.get_loc('RL')] = action
self.current_price = self._get_current_price()
self.instant_percentage_change = ((self.current_price - self.previous_price) / self.previous_price) * 100
if ... |
def get_user_subscription(uid):
# get product id subscription list
dic_pid = {
"access_token": access_token,
"table": "user_subcription_product_id",
"uid": uid
}
url = web + 'query-select'
response_pid = requests.get(url, data=dic_pid)
# get keyword subscription list
... | The code collects user subscription data (product and keyword) from a notification list, retrieves price history for each subscription type, generates personalized emails with subscription details based on a specified interval, and returns "success" upon completion. | def collect_data(notification_interval, notification_list):
keyword_sub_info = []
product_sub_info = []
for uid in notification_list:
# for each user, find user's subscribe info
# generate email, send email
api_key = notification_list[uid]["api_key"]
email = notification_li... |
def insert_by_keyword(uid, keyword, expected_price):
if not keyword:
return (400, "missing keyword")
if len(keyword) > 128:
return (400, "Max keyword length is 128")
sqlite_connection = SqliteService.get_db()
cursor = sqlite_connection.cursor()
sql = """ SELECT sid, keyword
FRO... | The function `subscribe_product` handles user subscription requests based on input type. If the type is "keyword", it directly inserts a subscription using the keyword. For "productID", it generates a website link first, then inserts the subscription with the product ID and website. It returns success/failure responses... | def subscribe_product(uid, product, type, platform, expected_price):
if type == "keyword":
# subscirbe based on keyword
respond = insert_by_keyword(uid, product, expected_price)
elif type == "productID":
# gengerate corresponding website
website_message = generate_website(platfo... |
def get_all_users():
# get all users in user table
dic = {
"access_token": access_token,
"table": "user"
}
url = web + 'query-select'
response = requests.get(url, data=dic)
user_info = json.loads(response.content)
return user_info
def get_notification_interval(user_info):
... | The code's main task is to retrieve user data, categorize them into monthly, daily, and weekly notification intervals, process date-related logic based on these intervals, and return a simple HTTP 200 response with a "hello" message. The core functionality revolves around user notification scheduling and date handling,... | def lambda_handler(event, context):
user_info = get_all_users()
monthly_list, daily_list, weekly_list = \
get_notification_interval(user_info)
get_date(monthly_list, daily_list, weekly_list)
return {
'statusCode': 200,
'body': json.dumps("hello")
} |
def __check_data_properties(self, data: dataUtils.Data) -> None:
"""Check data properties. Raises assertion error if there is a
mismatch between ESN and data properties
:param data: Data object
:return: None
"""
assert (
data.no_input_series == self._no_i... | This code trains an Echo State Network (ESN) by computing the reservoir's readout weights using ridge regression. It collects reservoir states from training data, constructs a covariance matrix with regularization, solves for weights via matrix inversion, handles singular matrices by setting weights to zero, and comput... | def fit(self, data: dataUtils.Data, no_forget_points: int) -> None:
"""Fit the ESN to the training data
:param data: Data object
:param no_forget_points: number of data points to ignore at the
beginning of the training when collecting the reservoir states.
This in... |
def atomic_number_species_with_mt_min(atomic_numbers: List[int]) -> int:
""" Get atomic number of the species expected to have the smallest MT radius in the system.
Use rgkmax as proxy for MT radius (seem to be correlated).
:param atomic_numbers: List of atomic numbers
:return: Atomic number of elemen... | The main task of the code is to compute optimal Muffin Tin (MT) radii for a system, ensuring non-overlapping radii while maintaining ratios relative to the smallest MT radius. It identifies the element with the smallest MT radius, calculates minimum bond lengths, derives optimal MT radii using rgkmax ratios, scales the... | def main(system, scaling_factor=1.0):
"""Get Muffin Tin radii with optimal ratios w.r.t. the smallest MT.
The smallest MT radius determines all other MT radii in the system.
This routine proceeds by:
* Using rgkmax values to establish the species that will have the smallest MT radius in the system... |
def send(self, status, data):
message = f'> {status} - {data}\n' # We need to add a newline here
self.connection.sendall(str.encode(message))
def recv_basic(self):
total_data = []
while True:
data = self.connection.recv(1).decode()
if not data:
... | This code initializes a client connection to a server, sets up logging, sends a welcome message with supported commands, and enters a loop to receive and process client input. It handles basic communication, including login, message sending, and command parsing, while managing exceptions and logging errors. | def __init__(self, connection, address, core_server):
self.connection = connection
self.endpoint = f"{address[0]}:{address[1]}"
self.logger = logging.getLogger(self.endpoint)
self.logger.info('Client connected')
self.username = None
self.server = core_server
self.... |
def search_class(cl):
rel_discard = ['http://www.geoscienceontology.org/svo/svu#subLabel',
'http://www.w3.org/2000/01/rdf-schema#comment',
'http://www.w3.org/2000/01/rdf-schema#label']
#'http://www.w3.org/1999/02/22-rdf-syntax-ns#type']
sparql = SPARQLWra... | The function generates an HTML index file by retrieving class data, combining it with metadata and timestamps, and writing the result to a file. If the class is 'Property', it aggregates data from related classes (PropertyStandardization, PropertyType) before generating the HTML. The output is saved as [ext]index.html ... | def write_to_file(ext,cl,desc):
now = datetime.datetime.now(pytz.timezone("America/New_York"))
if cl != 'Property':
test = search_class(cl)
text = print_index_html(cl,test,desc,now)
else:
properties = search_class(cl)
standardization = search_class('PropertyStandardization')
... |
def get_optimal_return(lake):
"""
Returns the returns (sum of discounted rewards) under an optimal policy
Uses policy iteration to get this optimal policy
args:
lake: the lake to build the environment from
returns:
optimal return
"""
env = build_env(lake)
# policy itera... | The function `search_algorithm_on_lake` executes a grid search to optimize parameters for a given reinforcement learning algorithm (e.g., SARSA or Q-Learning) on a specified lake environment. It calculates the optimal return for the environment, runs the algorithm's parameter search, and saves the results (including al... | def search_algorithm_on_lake(algorithm, algorithm_name, lake, lake_name):
"""
Runs the parameter search for an algorithm-lake combination
Will save the results to file
args:
algorithm: the function to run (SARSA or Q-Learning)
algorithm_name: the name of the algorithm
lake: the ... |
def _is_tracing():
return torch._C._get_tracing_state()
def _batched_nms_vanilla(
boxes: Tensor,
scores: Tensor,
idxs: Tensor,
iou_threshold: float,
) -> Tensor:
# Based on Detectron2 implementation, just manually call nms() on each class independently
keep_mask = torch.zeros_like(scores, dt... | The function `batched_nms` performs non-maximum suppression (NMS) on a batch of bounding boxes, suppressing overlapping boxes within the same category (defined by `idxs`). It removes boxes with IoU exceeding `iou_threshold`, retaining higher-scoring boxes. The implementation adapts to input size and device type for eff... | def batched_nms(
boxes: Tensor,
scores: Tensor,
idxs: Tensor,
iou_threshold: float,
) -> Tensor:
"""
Performs non-maximum suppression in a batched fashion.
Each index value correspond to a category, and NMS
will not be applied between elements of different categories.
Args:
... |
def download_images(url):
try:
#print("downloading " + url)
#print(path)
filename = url.split('/')[-1]
r = requests.get(url, allow_redirects=True)
open(path + "image_" + country + "/" + "_" + filename + ".jpg",
'wb').write(r.content)
except:
pass
def ... | The main task of the code is to evaluate hotel images by assessing their aesthetic quality, technical parameters, EXIF data, and quantity. It processes images, groups similar ones, removes duplicates, calculates scores (AES, tech, EXIF), and generates a final composite score. The code also prepares evaluation comments ... | def main():
# hotels_df = get_hotel_data()
# im_indonesia1 = pd.read_csv(path + country + "_images_link.csv")
# im_amenities = pd.read_csv(path + country + "_amenities.csv")
# im_indonesia5 = generate_and_get_property_mrc(hotels_df['oyo_id'], im_indonesia1)
download_images(sys.argv[3])
# hotel_a... |
def _setup_hubdir():
global hub_dir
# Issue warning to move data if old env is set
if os.getenv('TORCH_HUB'):
warnings.warn('TORCH_HUB is deprecated, please use env TORCH_HOME instead')
if hub_dir is None:
torch_home = _get_torch_home()
hub_dir = os.path.join(torch_home, 'hub')
... | The function retrieves and returns the docstring of a specified model entrypoint from a GitHub repository. It takes the repository identifier (`github`), the entrypoint name (`model`), and a flag to force reloading (`force_reload`). The function downloads the repo, imports its `hubconf.py` module, locates the specified... | def help(github, model, force_reload=False):
r"""
Show the docstring of entrypoint `model`.
Args:
github: Required, a string with format <repo_owner/repo_name[:tag_name]> with an optional
tag/branch. The default branch is `master` if not specified.
Example: 'pytorch/vision[:h... |
def _setup_hubdir():
global hub_dir
# Issue warning to move data if old env is set
if os.getenv('TORCH_HUB'):
warnings.warn('TORCH_HUB is deprecated, please use env TORCH_HOME instead')
if hub_dir is None:
torch_home = _get_torch_home()
hub_dir = os.path.join(torch_home, 'hub')
... | The function `load` downloads and loads a pretrained model from a specified GitHub repository. It accepts the repository path, model name, and parameters. It temporarily adds the repo directory to the system path, imports the `hubconf.py` module, retrieves the model entry point, and instantiates the model with provided... | def load(github, model, *args, **kwargs):
r"""
Load a model from a github repo, with pretrained weights.
Args:
github: Required, a string with format "repo_owner/repo_name[:tag_name]" with an optional
tag/branch. The default branch is `master` if not specified.
Example: 'pyto... |
def _setup_hubdir():
global hub_dir
# Issue warning to move data if old env is set
if os.getenv('TORCH_HUB'):
warnings.warn('TORCH_HUB is deprecated, please use env TORCH_HOME instead')
if hub_dir is None:
torch_home = _get_torch_home()
hub_dir = os.path.join(torch_home, 'hub')
... | The function retrieves and returns the docstring of a specified model entrypoint from a GitHub repository. It takes the repo identifier (`github`), model name (`model`), and a flag to force reloading (`force_reload`). It caches the repo, imports the hubconf module, locates the entrypoint, and returns its docstring, com... | def help(github, model, force_reload=False):
r"""
Show the docstring of entrypoint `model`.
Args:
github: Required, a string with format <repo_owner/repo_name[:tag_name]> with an optional
tag/branch. The default branch is `master` if not specified.
Example: 'pytorch/vision[:h... |
def _setup_hubdir():
global hub_dir
# Issue warning to move data if old env is set
if os.getenv('TORCH_HUB'):
warnings.warn('TORCH_HUB is deprecated, please use env TORCH_HOME instead')
if hub_dir is None:
torch_home = _get_torch_home()
hub_dir = os.path.join(torch_home, 'hub')
... | The function `load` retrieves and instantiates a pretrained model from a GitHub repository. It takes the repository path, model entrypoint, and parameters, downloads the repo if needed, imports the model definition from `hubconf.py`, and returns the initialized model with pretrained weights. Key features include option... | def load(github, model, *args, **kwargs):
r"""
Load a model from a github repo, with pretrained weights.
Args:
github: Required, a string with format "repo_owner/repo_name[:tag_name]" with an optional
tag/branch. The default branch is `master` if not specified.
Example: 'pyto... |
def init_from_centers(args):
global conditionals
from torch.distributions.multivariate_normal import MultivariateNormal
bs = args.buffer_size
if args.dataset == 'tinyimagenet':
size = [3, 64, 64]
else:
size = [3, 32, 32]
centers = t.load('./%s_mean_one.pt' % args.dataset)
cov... | The code trains a generative model (likely an Energy-Based Model or GAN variant) to maximize log probabilities of data distribution $ p(x) $ and conditional distribution $ p(y|x) $, using both labeled and unlabeled data. It initializes model parameters, sets up an optimizer (Adam or SGD), and employs learning rate deca... | def main(arg):
np.random.seed(arg.seed)
t.manual_seed(arg.seed)
if t.cuda.is_available():
t.cuda.manual_seed_all(arg.seed)
device = t.device('cuda' if t.cuda.is_available() else 'cpu')
arg.device = device
# datasets
dload_train, dload_train_labeled, dload_valid, dload_test = get_d... |
def treeSearch(self, key):
return self.search(self.root, key)
def transplant(self, u, v):
if u.parent is None:
self.setRoot(v.key)
elif u == u.parent.left:
u.parent.left = v
else:
u.parent.right = v
if v is None:
v.parent = u.parent... | This code deletes a node with the specified key from a binary tree. It handles cases where the node has no children, one child, or two children. For two children, it finds the minimum in the right subtree, adjusts pointers to replace the node, and reattaches subtrees. The 'transplant' method replaces one node with anot... | def delete(self, key):
z = self.treeSearch(key)
if z is None:
return None
elif z.left is None:
self.transplant(z, z.right)
elif z.right is None:
self.transplant(z, z.left)
else:
y = self.minimum(z.right)
if y.parent != z... |
def forward(self, X):
encoding_var = self.encoder(X)
risk_pred = self.predictor(encoding_var)
#return risk_pred, self.con_weight, self.cen_weight, encoding_var
return risk_pred, encoding_var
def _get_cox_loss(self, risk_pred, y, e):
weight = self._get_con... | The code computes the loss components for a survival analysis model. It calculates the Cox loss for risk prediction, constraint weight loss from encoding variables, and censoring weight loss using encoding variables and event indicators. It also retrieves constraint and censoring weight parameters, returning all compon... | def _compute_loss(self, X, y, e):
risk_pred, encoding_var = self.forward(X=X)
cox_loss = self._get_cox_loss(risk_pred, y, e)
con_weight_loss = self._get_con_weight_loss(encoding_var)
#cen_weight_loss = self._get_cen_weight_loss(X, e)
cen_weight_... |
def splitData(X,y):
# split data into training and test parts
# ... for now, we use all of the data for training and testing
Xtrain=X; ytrain=y; Xtest=X; ytest=y
return (Xtrain,ytrain,Xtest,ytest)
def normaliseData(x):
# rescale data to lie between 0 and 1
scale = x.max(axis=0)
return (x/scale, scale)
def... | The main task of the code is to perform linear regression on stock price data (Amazon vs. Google) by loading, normalizing, and splitting the dataset. It tests prediction/cost functions, runs gradient descent to fit parameters, and visualizes results through scatter plots, regression lines, cost curves, and a 3D cost su... | def main():
# load the data
data=np.loadtxt('stockprices.csv',usecols=(1,2))
X=data[:,0]
y=data[:,1]
# plot the data so we can see how it looks
# (output is in file graph.png)
fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(X, y, label='Data')
ax.set_xlabel('Amazon')
ax.set_ylabel('Google')
... |
def build_dataset(width=21, step=10, threshold=5, formants_number=4, wav_number=15, random_sate=None):
"""
build_dataset(width=21, step=10, threshold=5, formants_number=4, wav_number=15, random_sate=None)
Parameters
----------
width : float
The width of frame in ms.
... | The code tests machine learning models on an audio dataset. It builds a dataset with 120 WAV files, preprocesses features, splits data into training/test sets, and evaluates Decision Tree and Random Forest classifiers for classification accuracy. The process includes data cleaning, splitting, preprocessing, and model e... | def test_machine_learning():
"""
Test the machine learning-based model.
"""
df = build_dataset(wav_number=120, random_sate=42)
df = df.drop(['fs', 'duration'], axis=1)
train_set, test_set = train_test_split(df, test_size=0.2, random_state=42)
X_train, y_train = preprocessing(train_set)
... |
def write_to_file(self):
words_to_learn = pd.DataFrame(self.cards, columns=['French', 'English'])
words_to_learn.to_csv("./data/words_to_learn.csv", index=False)
def update_deck(self):
self.card_number -= 1
# Update the current card
if self.card_number >= 0:
self.cur... | The main task of the code is to remove the current card from the deck, add it to a removed list, write the removed words to a CSV file, update the deck structure to prevent index errors, and ensure proper handling of the next card to avoid multiple button press issues. | def remove_word(self):
# Get current card and remove it from the list
current_card_index = self.cards.index(self.current_card)
# Add removed word to list
self.removed_list.append(self.cards.pop(current_card_index))
# Write removed words to csv file
self.write_to_file()
... |
def get_peaks(ti, ys):
noisy_peak_x, noisy_peak_y = decide_peaks(ti, ys)
noisy_peak_x = np.insert(noisy_peak_x, 0, ti[0])
noisy_peak_y = np.insert(noisy_peak_y, 0, ys[0])
noisy_peak_x = np.insert(noisy_peak_x, len(noisy_peak_x), ti[-1] + (ti[1] - ti[0]))
noisy_peak_y = np.insert(noisy_peak_y, len(no... | This function fits a mono-exponential model to the input data (ti, ys) after taking the absolute value of ys. It identifies peaks, initializes parameters, performs curve fitting using scipy.optimize.curve_fit, calculates the R-squared value of the fit, and returns the R-squared, fitted parameters (m, t, b), and the fit... | def fit_T2_star(ti, ys):
# this is a special characteristic of t2_star
ys = np.absolute(ys)
noisy_peak_x, noisy_peak_y = get_peaks(ti, ys)
# perform the fit
p0 = get_monoExp_init_param(ti, ys)
try:
params, cv = scipy.optimize.curve_fit(monoExp, noisy_peak_x, noisy_peak_y, p0=p0)
ex... |
def get_peaks(ti, ys):
noisy_peak_x, noisy_peak_y = decide_peaks(ti, ys)
noisy_peak_x = np.insert(noisy_peak_x, 0, ti[0])
noisy_peak_y = np.insert(noisy_peak_y, 0, ys[0])
noisy_peak_x = np.insert(noisy_peak_x, len(noisy_peak_x), ti[-1] + (ti[1] - ti[0]))
noisy_peak_y = np.insert(noisy_peak_y, len(no... | The code fits a mono-exponential model to peak data from input signals, calculates the R-squared value of the fit, and returns the model parameters (m, t, b) along with the fitted values. It handles errors by returning 0 if fitting fails due to runtime or type issues. | def fit_T2(ti, ys):
noisy_peak_x, noisy_peak_y = get_peaks(ti, ys)
# perform the fit
p0 = get_monoExp_init_param(ti, ys)
try:
params, cv = scipy.optimize.curve_fit(monoExp, noisy_peak_x, noisy_peak_y, p0=p0)
except RuntimeError:
return 0
except TypeError:
return 0
... |
def find_gsutil():
# Ideally we would use the gsutil that comes with depot_tools since users
# are much more likely to have that in thier PATH. However I found this
# depot_tools version to be a lot slower.
# return [sys.executable, webports.util.find_in_path('gsutil.py')]
return ['gsutil']
def parse_gs_util... | This script scans webports packages for a specified revision, downloads them from Google Storage (GS), and generates an index. It uses command-line arguments to control caching, parallel downloads, and verbosity. The tool checks GS for package listings, processes the output, downloads binaries while verifying integrity... | def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('revision', metavar='REVISION',
help='webports revision to to scan for.')
parser.add_argument('-v', '--verbose', action='store_true',
help='Output extra information.')
parser.add... |
def set_IS(li):
if len(li[0]) > 1:
IS = list(choose_most_support_IS(li[0]))[0]
elif len(li[0]) == 1:
IS = list(list(li[0])[0])[0]
return IS
def set_IS_number(li):
if len(li[0]) > 1:
for value in choose_most_support_IS(li[0]).values():
num = value
elif len(li[0]) =... | The code processes 'plus' and 'minus' lists by extracting features like IS elements, their counts, possible IS variants, and proviral numbers from each entry. It compiles these into a unified list of lists, tagging each entry with 'plus' or 'minus' to distinguish their origin, then returns this merged list. | def plus_minus_merge(plus, minus):
"""
final_list = [['chr:pos', pos/str, proviral_split, 'plus'], [], ...]
"""
plus_minus_list = []
for i in plus:
IS = set_IS(i)
IS_num = set_IS_number(i)
possible_is = possible_IS(i)
proviral_num = len(i[1][0])
unit = [IS... |
def compute_next_tipo(signed_tipo, inst): # checked
go_right = [['A', 1], ['B', -1], ['C', -1], ['A', -1], ['B', 1], ['C', 1]]
go_left = [['A', 1], ['C', 1], ['B', 1], ['A', -1], ['C', -1], ['B', -1]]
hand = inst[0]
clicks = inst[1]
if hand == 'R':
pos = go_right.index(signed_tipo)
... | The function `close_parti` extends the input list `parti` by iteratively appending new elements (parti_tail) with specific instructions ('R' or 'L') until the computed virtual value matches the initial element's type and sign, effectively closing a loop or sequence. It dynamically adjusts the list by joining new nodes ... | def close_parti(parti):
if parti[-1].inst[0] == 'L':
virtual = compute_next_tipo([parti[-1].tipo, parti[-1].sign], parti[-1].inst)
while virtual != [parti[0].tipo, parti[0].sign]:
parti_tail = []
append_note(parti_tail)
parti_tail[0].tipo = virtual[0]
... |
def parti_is_periodic(parti):
virtual_tipo_sign = compute_next_tipo([parti[-1].tipo, parti[-1].sign], parti[-1].inst)
if virtual_tipo_sign == [parti[0].tipo, parti[0].sign]:
return True
else:
return False
def longer_parti(parti): # checked
if len(parti) == 1:
print('way too shor... | This function extracts a suffix and prefix from a periodic partiture. It extends the partiture, handles edge cases by wrapping around, and returns [suffix, prefix] for analysis, ensuring valid periodic data processing. | def get_affixes(parti, pos): # checked
if parti_is_periodic(parti):
pass
else:
print("this will make no sense because the given partiture is not periodic")
exit()
new_parti = []
head = []
tail = []
new_parti = longer_parti(parti)
if pos + TURNS <= len(new_parti):
... |
def compute_point(given_suffix, given_prefix, shear=None): # checked
##############################
# given_suffix and given_prefix do not need to have been expanded
##############################
if shear is None:
shear = [0, 0, 0]
eta = compute_fixed_points(given_suffix, True, shear)[0]
... | This function processes a periodic structure 'parti' by calculating geometric properties. It initializes shear parameters, verifies periodicity, computes points and cosines for each segment using suffix/prefix data, then calculates hyperbolic distances between consecutive points (with wrap-around). The modified structu... | def hyper_parti(parti, shear=None): # checked
###########################################
# parti does not need to be expanded
###########################################
if shear is None:
shear = [0, 0, 0]
else:
pass
if parti_tools.parti_is_periodic(parti):
pass
els... |
def insert_valuein_max_heap(max_heap, length, val):
max_heap[length] = val
while length > 1 and max_heap[length//2] < max_heap[length]:
swap = max_heap[length//2]
max_heap[length//2] = max_heap[length]
max_heap[length] = swap
length //=2
def insert_valuein_min_heap(min_heap, leng... | The function `insert_element` inserts a value into either a max-heap or min-heap based on its comparison with the max-heap's root. If the value is smaller, it increments the max-heap counter and inserts the value there; otherwise, it increments the min-heap counter and inserts into the min-heap. After insertion, it cal... | def insert_element(max_heap, min_heap, val, idx):
global maxh, minh
if val < max_heap[1]:
maxh += 1
insert_valuein_max_heap(max_heap, maxh, val)
else:
minh += 1
insert_valuein_min_heap(min_heap, minh, val)
compare_heaps(max_heap, min_heap, idx) |
def ahead_behind(self) -> Optional[AheadBehind]:
"""Count unsynched commits between current branch and it's remote.
:return: AheadBehind comparing local and remote if remote branch exists
"""
try:
return AheadBehind(
ahead = self._count(['rev-list', '@{push}..... | The code generates a concise, color-coded summary of a repository's status, combining branch name, commit differences (ahead/behind), status indicators, and stashes into a single string using terminal escape sequences for visual clarity. | def short_stats(self) -> str:
"""Generate a short text summary of the repository status.
Colour coding is done with terminal escapes.
:return: a short string which summarises repository status
"""
result = [self.ICON]
if not self.root_dir.endswith(self.branch):
... |
def _fixup_template(self, ExtensionTemplate):
return self.ExtensionTemplate if ExtensionTemplate is None else ExtensionTemplate
def compile_module(self, main_src, ExtensionTemplate=None, name='mytest', extra_sources=()):
"""
Create and compile a HPy module from the template
"""
E... | The `make_module` function compiles and loads a Python module from source without registering it in `sys.modules`, avoiding global state modification. It uses `compile_module` to generate the module, then selects a loader based on the `hpy_abi` setting: universal/debug ABIs use `load_universal_module`, while 'cpython' ... | def make_module(self, main_src, ExtensionTemplate=None, name='mytest',
extra_sources=()):
"""
Compile & load a module. This is NOT a proper import: e.g.
the module is not put into sys.modules.
We don't want to unnecessarily modify the global state inside tests:
... |
def delta_z_i(temperature_i, pressure_i, pressure_ip1, g, m_bar=2.4 * m_p):
"""
Change in height in the atmosphere from bottom to top of a layer.
Malik et al. (2017) Equation 18
"""
return ((k_B * temperature_i) / (m_bar * g) *
np.log(pressure_i / pressure_ip1))
def c_p(m_bar=2.4 * m_p,... | The function calculates the maximum allowable timestep for radiative or convective equilibrium in a stellar or astrophysical simulation. It computes both radiative (dt_radiative) and convective (dt_convective) timescales using equations from Malik et al. (2017), then returns the minimum of the two scaled by a stability... | def delta_t_i(p_1, p_2, T_1, T_2, delta_F_i_dz, g, m_bar=2.4 * m_p, n_dof=5):
"""
Timestep in iteration for radiative equilibrium.
Follows Equations 27-28 of Malik et al. (2017).
"""
dz = delta_z_i(T_1, p_1, p_2, g, m_bar)
# Malik 2017 Eqn 28
if (delta_F_i_dz * dz).value != 0:
... |
def rho_p(p_1, p_2, T_1, g, m_bar=2.4 * m_p):
"""
Local density.
"""
return ((p_1 - p_2) / g) / delta_z_i(T_1, p_1, p_2, g, m_bar)
def c_p(m_bar=2.4 * m_p, n_dof=5):
"""
Heat capacity, Malik et al. (2017) Equation 25
"""
return (2 + n_dof) / (2 * m_bar) * k_B
def mixing_length(T_1, g, al... | This function calculates the convective flux in a fluid layer using temperature and pressure gradients. It computes density (rho), specific heat (cp), mixing length (lmix), and gamma gradient (delta_g). If delta_g is positive, it returns the flux as rho * cp * lmix² * sqrt(g/temperature_i) * delta_g^1.5; otherwise, it ... | def convective_flux(
temperature_i, temperature_ip1, pressure_i, pressure_ip1, g,
m_bar=2.4 * m_p, n_dof=5, alpha=1
):
rho = rho_p(pressure_i, pressure_ip1, temperature_i, g, m_bar=m_bar)
cp = c_p(m_bar=m_bar, n_dof=n_dof)
lmix = mixing_length(temperature_i, g, alpha, m_bar)
delta_g = delta_gam... |
def delta_tau_i(kappa_i, p_1, p_2, g):
"""
Contribution to optical depth from layer i, Malik et al. (2017) Equation 19
"""
return (p_1 - p_2) / g * kappa_i
def propagate_fluxes(
lam, F_1_up, F_2_down, T_1, T_2, delta_tau, omega_0=0, g_0=0, eps=0.5
):
"""
Compute fluxes up and down using ... | The function `emit` computes an emission spectrum by iteratively solving for radiative equilibrium in a layered atmosphere. It calculates outgoing fluxes, updates temperatures based on radiative heating/cooling, and tracks temperature evolution over timesteps until convergence (temperature changes fall below a threshol... | def emit(
opacities, temperatures, pressures, lam, F_TOA, g, m_bar=2.4 * m_p,
n_timesteps=50, convergence_thresh=10 * u.K, alpha=1, fluxes_up=None,
fluxes_down=None
):
"""
Compute emission spectrum.
Parameters
----------
opacities : dict
Opacity database binned to wavelength gri... |
def BB(temperature):
"""
Compute the blackbody flux
Parameters
----------
temperature : ~astropy.units.Quantity
Temperature of the blackbody
Returns
-------
bb : function
Returns a function which takes the wavelength as an
`~astropy.units.Quantity` and returns t... | (The function computes the emission spectrum by iteratively solving for the temperature profile in radiative equilibrium. It propagates upwelling and downwelling fluxes through atmospheric layers, calculates optical depth changes, and updates temperatures until convergence. The process uses opacities, pressure-temperat... | def absorb(
opacities, temperatures, pressures, lam, F_TOA, g, m_bar=2.4 * m_p,
n_timesteps=50, convergence_thresh=10 * u.K, alpha=1, fluxes_up=None,
fluxes_down=None
):
"""
Compute emission spectrum.
Parameters
----------
opacities : dict
Opacity database binned to wavelength g... |
def build_dag(self, tasks):
dag = nx.DiGraph()
for task_name, task in tasks.items():
dag.add_node(task_name, task=task)
for dependency in task.get("dependencies", []):
if dependency not in tasks:
self.logger.error(f"Undefined dependency '{depen... | This code executes tasks in a directed acyclic graph (DAG) order, ensuring dependencies are resolved before execution. It uses caching to reuse outputs, manages task execution via a thread pool, and handles errors. The main task is to process tasks in topological order, leveraging concurrency and caching to efficiently... | def execute_tasks(self, target_name, tasks):
dag = self.build_dag(tasks)
if not nx.is_directed_acyclic_graph(dag):
self.logger.error("Circular dependencies detected in the build graph.")
return
task_order = self.get_task_order(dag, target_name)
cache_metadata = ... |
def __event_handler(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
self.server.stop()
elif event.type == pygame.KEYDOWN:
# WASD movement on keydown
if event.key == pygame.K_w:
self.movement[FORWARD] = True
elif event.key == pygame.K_s:
... | The code starts a server in a separate thread and runs a loop to handle events, update the application state, and render the UI while the application is running. | def run(self):
server_thread = threading.Thread(target=self.server.start)
server_thread.start()
while self.running:
self.__event_handler()
self.__update()
self.__render() |
def _fwd_prop(self, X): #input the starting x values and then find what we call netj by taking dot product
self.net_inner = np.dot(self.w_inner.T, X.T)
self.net_outer = np.dot(self.w_outer.T, X.T)
if(self.mode == "sigmoid"):
self.activ_inner = self._sigmoid(self.net_inner)
... | The code trains a neural network model by iterating for a specified number of epochs. In each iteration, it performs forward propagation to compute predictions, calculates the loss compared to true labels, executes backpropagation to compute gradients, updates model weights, and prints the loss every three epochs to mo... | def train(self, X, y, n_epoch = 10):
for i in range(n_epoch):
y_hat = self._fwd_prop(X)
loss = self._loss(y_hat,y)
self._back_prop(X,y)
self._update_wt()
if i%3 == 0:
print("loss: ", loss) |
def nav_action_x(self, action):
if action == BUTTON.CLICKED:
self._publish_keyframe()
print("CLICKED X")
def nav_action_square(self, action):
# if action == BUTTON.CLICKED:
# self.go_home()
# elif action == BUTTON.DOUBLE_CLICKED:
# print("GOTO HOME... | This function processes incoming navigation signals by checking each signal's name and triggering corresponding actions (e.g., nav_action_x, nav_action_square) with the signal's data converted to an integer, enabling device interaction based on button presses. | def _navigator_states_cb(self, msg):
for signal in msg.signals:
if signal.name == "right_button_triangle":
self.nav_action_x(int(signal.data[1]))
elif signal.name == "right_button_square":
self.nav_action_square(int(signal.data[1]))
elif signal... |
def wrong_guesses(s_word, guess_list):
"wrong_guess: returns the number of wrong guesses"
count = 0
for i in guess_list:
if i not in s_word:
count += 1
return count
def guess_manager(guessed, guess_list):
"""guess_manager: prints string for failed input-condition
and asks for new... | The code implements a word guessing game loop where the player attempts to guess letters in a secret word. It tracks incorrect guesses, displays the current word state, remaining lives (as heart symbols), and guessed letters. The loop continues until the player either guesses all letters correctly (win) or exceeds 6 wr... | def playloop(secret_word):
formatter = "\nWord: {:^15} Life:{:<12} Guessed: {:<10}"
guesslist = ""
game_won = "no"
# Game losses when 6 guesses are wrong
while not wrong_guesses(secret_word, guesslist) == 6:
newguess = input("Enter a guess: ")
newguess = guess_manager(newguess,... |
def get_valid_locations(board):
valid_locations = []
for col in range(C_CNT):
if is_valid_loc(board, col):
valid_locations.append(col)
return valid_locations
def is_terminal_node(board):
return winning_move(board, PLAYER_PIECE) or winning_move(board, AI_PIECE) or len(get_valid_locati... | This function implements the Minimax algorithm to determine the optimal move for an AI player in a game like Connect Four. It evaluates all possible moves recursively, alternating between maximizing (AI) and minimizing (player) players. The algorithm assigns scores based on game outcomes (win, loss, draw) and selects t... | def minimax(board, depth, maximizingPlayer, difficulty):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if winning_move(board, AI_PIECE):
return (None, 100000000000000)
elif winn... |
def get_valid_locations(board):
valid_locations = []
for col in range(C_CNT):
if is_valid_loc(board, col):
valid_locations.append(col)
return valid_locations
def is_terminal_node(board):
return winning_move(board, PLAYER_PIECE) or winning_move(board, AI_PIECE) or len(get_valid_locati... | This function implements the alpha-beta pruning algorithm for a game, determining the optimal move for the AI player by recursively evaluating possible board states. It maximizes the AI's score while minimizing the opponent's, using depth-limited search with alpha-beta pruning to enhance efficiency. The function return... | def alpha_beta(board, depth, alpha, beta, maximizingplayer, difficulty):
valid_locations = get_valid_locations(board)
terminal_node = is_terminal_node(board)
if depth == 0 or terminal_node:
if terminal_node:
if winning_move(board, AI_PIECE):
return (None, 1000000)
... |
def get_valid_locations(board):
valid_locations = []
for col in range(C_CNT):
if is_valid_loc(board, col):
valid_locations.append(col)
return valid_locations
def is_terminal_node(board):
return winning_move(board, PLAYER_PIECE) or winning_move(board, AI_PIECE) or len(get_valid_locati... | This function implements the minimax algorithm for a Connect Four-like game, recursively evaluating all possible moves to determine the optimal column for the AI (maximizing player) or opponent (minimizing player). It checks terminal states, scores positions, and selects the move with the highest (for AI) or lowest (fo... | def minimax(board, depth, maximizingPlayer):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if winning_move(board, AI_PIECE):
return (None, 100000000000000)
elif winning_move(boa... |
def get_valid_locations(board):
valid_locations = []
for col in range(C_CNT):
if is_valid_loc(board, col):
valid_locations.append(col)
return valid_locations
def is_terminal_node(board):
return winning_move(board, PLAYER_PIECE) or winning_move(board, AI_PIECE) or len(get_valid_locati... | This code implements the alpha-beta pruning algorithm for a game, likely Connect Four, to determine the optimal move. It evaluates all valid board positions recursively, alternating between maximizing (AI) and minimizing (player) players, while pruning suboptimal branches using alpha-beta values. The function returns t... | def alpha_beta(board, depth, alpha, beta, maximizingPlayer):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if winning_move(board, AI_PIECE):
return (None, 100000000000000)
elif ... |
def minimax(board, depth, maximizingPlayer):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if winning_move(board, AI_PIECE):
return (None, 100000000000000)
elif winning_move(boa... | The code initializes and runs a Connect Four game with AI using either Minimax or Alpha-Beta pruning based on the selected algorithm and difficulty level. It converts difficulty to search depth, alternates between human and AI turns, handles game logic, checks for wins, and renders the game state using Pygame. The AI s... | def start_game(algorithm, difficulty_level):
if (algorithm == "Minimax"):
selected_algorithm = 1
else:
selected_algorithm = 2
# Convert the difficulty_level to depth
if difficulty_level == "Easy":
depth = 1
elif difficulty_level == "Medium":
depth = 3
elif difficu... |
def process_file(data_path: Path, open_flags: int, conn: Connection, cur: Cursor,
executor: Executor = None, prog_config: Tuple[int, int] = None) -> int:
# Use os.open instead of the built-in open() to avoid any unnecessary overhead in the creation
# of a file object.
fd = os.open(data_path, open_fl... | The main task of the code is to set up a PostgreSQL database schema and import weather and collision data from CSV files. It handles OS-specific file flags (O_BINARY for Windows), connects to a database, executes SQL schema definitions, and processes large datasets efficiently while measuring operation durations for pe... | def main() -> None:
# Note that this is a Path object, not a string of a path
this_dir = Path(__file__).parent
# Working with byte sequences rather than encoded strings reduces CPU effort during memory
# mapping. However, Windows requires the O_BINARY flag for this, whereas POSIX doesn't have it
# ... |
def endem21a(prop1, prop2):
return imp(phi(prop1, prop2), conj(imp(prop1, prop2), neg(box(prop2))))
def phi(prop1, prop2):
return conj(conj(S(prop1, prop2),S(prop1, neg(prop2))), conj(S(neg(prop1), prop2),S(neg(prop1), neg(prop2))))
def endem21b(prop1, prop2):
return conj(eq(prop1, S(prop1, prop2)), imp(pro... | The code defines a function `endem21` that computes the conjunction of two expressions: the result of `endem21a(prop1, prop2)` and the disjunction of `phi(prop1, prop2)` with `endem21b(prop1, prop2)`. Its main task is to combine these logical operations to produce a composite result based on the inputs `prop1` and `pro... | def endem21(prop1, prop2):
return conj(endem21a(prop1, prop2), disj(phi(prop1, prop2), endem21b(prop1, prop2))) |
def generate_rewards(num_states, each_step_reward, terminal_left_reward, terminal_right_reward):
rewards = [each_step_reward] * num_states
rewards[0] = terminal_left_reward
rewards[-1] = terminal_right_reward
return rewards
def generate_transition_prob(num_states, num_actions, misstep_prob = 0):
... | The code generates visualizations for an optimal policy and Q-values in a reinforcement learning environment. It computes the optimal policy, value function, and action-specific Q-values using given rewards, transition probabilities, and discount factor, then plots these results to illustrate decision-making dynamics i... | def generate_visualization(terminal_left_reward, terminal_right_reward, each_step_reward, gamma, misstep_prob):
num_states = 6
num_actions = 2
rewards = generate_rewards(num_states, each_step_reward, terminal_left_reward, terminal_right_reward)
transition_prob = generate_transition_prob(num_states,... |
def adjacentLocations(position):
adjacent = [
[1, 3],
[0, 2, 9],
[1, 4],
[0, 5, 11],
[2, 7, 12],
[3, 6],
[5, 7, 14],
[4, 6],
[9, 11],
[1, 8, 10, 17],
[9, 12],
[3, 8, 13, 19],
[4, 10, 15, 20],
[11, 14],
... | This function counts the number of a player's pieces on a board that are in positions capable of forming a mill if an adjacent opponent's piece is removed. It iterates through each player's piece, temporarily replaces it with the opponent's symbol, checks for a mill, and restores the original piece. For player "2", it ... | def getPiecesInPotentialMillFormation(board, player):
count = 0
for i in range(len(board)):
if (board[i] == player):
adjacent_list = adjacentLocations(i)
for pos in adjacent_list:
if (player == "1"):
if (board[pos] == "2"):
... |
def adjacentLocations(position):
adjacent = [
[1, 3],
[0, 2, 9],
[1, 4],
[0, 5, 11],
[2, 7, 12],
[3, 6],
[5, 7, 14],
[4, 6],
[9, 11],
[1, 8, 10, 17],
[9, 12],
[3, 8, 13, 19],
[4, 10, 15, 20],
[11, 14],
... | The function generates all possible valid moves for a player's pieces on a board by moving them to adjacent empty positions. It creates deep copies of the board for each move, checks if the move forms a mill, and removes an opponent's piece if a mill is formed. The resulting valid board configurations are collected and... | def possibleMoves_stage2(board, player):
board_list = []
for i in range(len(board)):
if(board[i] == player):
adjacent_list = adjacentLocations(i)
for pos in adjacent_list:
if (board[pos] == 'x'):
# If the location is empty, then the piece can... |
def numOfPieces(board, value):
return board.count(value)
def possibleMoves_stage3(board, player):
board_list = []
for i in range(len(board)):
if(board[i] == player):
for j in range(len(board)):
if (board[j] == 'x'):
board_copy = deepcopy(board)
... | This function determines the appropriate move generation stage based on the number of a player's pieces on the board. If the player has exactly 3 pieces, it calls the stage 3 move generator; otherwise, it uses the stage 2 move generator. The function acts as a router to select the correct strategy for generating valid ... | def possibleMoves_stage2or3(board, player='1'):
if numOfPieces(board, player) == 3:
return possibleMoves_stage3(board, player)
else:
return possibleMoves_stage2(board, player) |
def getPossibleMillCount(board, player):
count = 0
for i in range(len(board)):
if (board[i] == "X"):
if checkNextMill(i, board, player):
count += 1
return count
def possibleMoves_stage2or3(board, player='1'):
if numOfPieces(board, player) == 3:
return possibl... | This function evaluates a board game state by calculating a heuristic value based on potential mill formations for two players. It adjusts weights for potential mills depending on the game stage (stage 1 vs. later stages) and piece counts, prioritizing mill creation while penalizing or rewarding scenarios with limited ... | def potentialMillsHeuristic(board, isStage1):
evaluation = 0
numPossibleMillsPlayer1 = getPossibleMillCount(board, "1")
if not isStage1:
movablePieces = len(possibleMoves_stage2or3(board))
potentialMillsPlayer2 = getPiecesInPotentialMillFormation(board, "2")
if not isStage1:
if n... |
def display_board():
print("\n")
print(board[0] + " | " + board[1] + " | " + board[2] + " 1 | 2 | 3")
print(board[3] + " | " + board[4] + " | " + board[5] + " 4 | 5 | 6")
print(board[6] + " | " + board[7] + " | " + board[8] + " 7 | 8 | 9")
print("\n")
def handle_turn(player):
# Get p... | The code simulates 1000 rounds of a turn-based game (likely Tic-Tac-Toe), tracking wins for 'X' and 'O' and displaying a scoreboard after each round. It initializes a 3x3 board, alternates players, handles turns, checks game status, and updates scores. The loop resets the board each iteration, with player roles flippin... | def play_game():
global replay,board,game_still_going,current_player
o = x = 0
p=0
while(p<1000):
board = ['-','-','-','-','-','-','-','-','-']
display_board()
game_still_going = True
player = current_player
while game_still_going:
# Hand... |
def remove_value(self, cell:cell.Cell, row:int, column:int, value:int)->None:
"""Removes the value from row, column and grid"""
self.remove_number_from_list(self.number_for_row, value, row)
self.remove_number_from_list(self.number_for_column, value, column)
self.remove_number_from_grid(s... | The main task of the code is to generate a valid Sudoku puzzle by randomly filling the first row and iteratively solving the grid using backtracking. It employs a while loop to traverse cells, check available options, and backtrack when conflicts arise, ensuring each number placement adheres to Sudoku rules. The proces... | def generate_sudoku(self):
"""
generates a new sudoku
use a while loop
"""
# randomly generate the first row
random_order_number = [x for x in range(1, 10)]
random.shuffle(random_order_number)
for x in range(9):
value = random_order_number[x]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.