dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def make_test_map(index: int) -> Map:
return Map(
name=f"Test Map {index}", author=f"Test Author {index}", color=f"#00000{index}"
)
def make_test_map_xml(name: int, index: int) -> ElementTree.Element:
return make_element_with_children(
"Button",
{
"id": f"Test Map {name}"... | This test verifies that the get_map_elements function correctly generates an XML structure containing a ToggleGroup element with specific attributes and child elements when provided with a map of size 2. It compares the actual output against a predefined expected structure using assert_xml_lists_equal to ensure correct... | def test_map_generation_2():
actual = get_map_elements([make_test_map(2)])
expected = [
make_element_with_children(
"ToggleGroup",
{"id": "fanMapButtons1", "active": "False"},
[
make_test_map_xml(name=2, index=0),
],
)
]
a... |
def make_test_map(index: int) -> Map:
return Map(
name=f"Test Map {index}", author=f"Test Author {index}", color=f"#00000{index}"
)
def make_test_map_xml(name: int, index: int) -> ElementTree.Element:
return make_element_with_children(
"Button",
{
"id": f"Test Map {name}"... | The code tests if generating 8 maps produces the expected XML structure. It creates 8 test maps, constructs a ToggleGroup element with specific attributes and child elements, then verifies the generated XML matches this structure using an assertion. | def test_map_generation_len8():
actual = get_map_elements([make_test_map(i) for i in range(8)])
expected = [
make_element_with_children(
"ToggleGroup",
{"id": "fanMapButtons1", "active": "False"},
[make_test_map_xml(name=i, index=i) for i in range(8)],
)
... |
def make_test_map(index: int) -> Map:
return Map(
name=f"Test Map {index}", author=f"Test Author {index}", color=f"#00000{index}"
)
def make_test_map_xml(name: int, index: int) -> ElementTree.Element:
return make_element_with_children(
"Button",
{
"id": f"Test Map {name}"... | This test verifies that generating 9 map elements produces the correct XML structure. It checks if the `get_map_elements` function creates two ToggleGroups with specific attributes and child elements: the first group contains 7 test maps and a "Next" button, while the second includes two maps and a "Previous" button. T... | def test_map_generation_len9():
actual = get_map_elements([make_test_map(i) for i in range(9)])
expected = [
make_element_with_children(
"ToggleGroup",
{"id": "fanMapButtons1", "active": "False"},
[make_test_map_xml(name=i, index=i) for i in range(7)]
+ [... |
def make_test_map(index: int) -> Map:
return Map(
name=f"Test Map {index}", author=f"Test Author {index}", color=f"#00000{index}"
)
def make_test_map_xml(name: int, index: int) -> ElementTree.Element:
return make_element_with_children(
"Button",
{
"id": f"Test Map {name}"... | This test verifies that generating 14 map elements creates two paginated XML interfaces. It checks if the first page displays 7 maps + a next button, and the second page shows 4 maps + previous/next buttons, ensuring correct structure and pagination logic through XML comparison. | def test_map_generation__2_full_pages():
actual = get_map_elements([make_test_map(i) for i in range(14)])
first_page_buttons = [make_test_map_xml(name=i, index=i) for i in range(7)] + [
make_next_map_button(0)
]
second_page_buttons = (
[make_test_map_xml(name=i + 7, index=i) for i in r... |
def make_test_map(index: int) -> Map:
return Map(
name=f"Test Map {index}", author=f"Test Author {index}", color=f"#00000{index}"
)
def make_test_map_xml(name: int, index: int) -> ElementTree.Element:
return make_element_with_children(
"Button",
{
"id": f"Test Map {name}"... | This test verifies that generating map elements creates three paginated ToggleGroups with correct navigation buttons. It constructs expected XML structures for three pages (7, 4, and 2 maps respectively), including previous/next buttons, and compares against actual generated elements to ensure proper pagination and UI ... | def test_map_generation__3_pages():
actual = get_map_elements([make_test_map(i) for i in range(15)])
first_page_buttons = [make_test_map_xml(name=i, index=i) for i in range(7)] + [
make_next_map_button(0)
]
second_page_buttons = (
[make_test_map_xml(name=i + 7, index=i) for i in range(... |
def eat(self, token_type):
if token_type == self.current_token.type:
self.current_token = self.lexer.get_next_token()
else:
error('Unknown token ' + str(self.current_token))
def declare(self):
"""declare : ~ID"""
node = self.current_token.value
self.eat(T... | This method parses compound statements by processing tokens like DEFINE, arithmetic operations, control structures (IF/WHILE), and I/O commands, constructing corresponding AST nodes (e.g., BinOp, If, Print), and aggregating them into a Compound structure for further processing. | def compound(self):
"""
declarations : DEFINE (compound)*
| (ADD | SUB | MUL | DIV) VAR factor (compound)*
| (IF | WHILE) (NOT)* factor factor LPAREN (compound) RPAREN (compound)*
| (PRINTASCII | PRINTVAL) (compound)*
... |
def buildExpNum(exponent: int, constant: int, base: int = 2) -> int:
return pow(base, exponent) - constant
def generatePrivateKey(e: int, p: int, q: int) -> (int, int):
n = p * q
lambda_n = (p - 1) * (q - 1) # Euler totient function
d = modularInverse(e, lambda_n)
# verify
if (e * d) % lambda_n... | The main task of the code is to perform RSA encryption and decryption using provided parameters. It parses inputs, generates public/private keys, decrypts a ciphertext to plaintext, encrypts plaintext to ciphertext, and outputs results conditionally based on the verbose flag. | def main(args: argparse.Namespace) -> None:
# pre-processing inputs
p_e = int(args.p_e)
p_c = int(args.p_c)
q_e = int(args.q_e)
q_c = int(args.q_c)
e_e = int(args.e_e)
e_c = int(args.e_c)
ciphertext = str(args.ciphertext)
plaintext = int(args.plaintext)
verbose = args.verbose
... |
def _compute_gain(self, action_distrib, action_distrib_old, actions, advs):
"""Compute a gain to maximize."""
prob_ratio = F.exp(action_distrib.log_prob(actions)
- action_distrib_old.log_prob(actions))
mean_entropy = F.mean(action_distrib.entropy)
surrogate_gai... | The main task of the code is to update the policy parameters using Conjugate Gradient (CG) and line search optimization, leveraging a given dataset. It processes states, actions, and advantages, standardizes advantages, computes action distributions, evaluates gain, calculates a KL-divergence constrained step, and perf... | def _update_policy(self, dataset):
"""Update the policy using a given dataset.
The policy is updated via CG and line search.
"""
assert 'state' in dataset[0]
assert 'action' in dataset[0]
assert 'adv' in dataset[0]
# Use full-batch
xp = self.policy.xp
... |
def _update_obs_normalizer(self, dataset):
assert self.obs_normalizer
states = batch_states(
[b['state'] for b in dataset], self.obs_normalizer.xp, self.phi)
self.obs_normalizer.experience(states)
def _update_policy(self, dataset):
"""Update the policy using a given dataset.
... | The code updates the policy and value function using the provided dataset. If an observation normalizer is enabled, it first updates the normalizer. Then, it separately updates the policy and value function components with the dataset to refine their parameters. | def _update(self, dataset):
"""Update both the policy and the value function."""
if self.obs_normalizer:
self._update_obs_normalizer(dataset)
self._update_policy(dataset)
self._update_vf(dataset) |
def _flush_last_episode(self):
if self.last_episode:
self.memory.append(self.last_episode)
self.last_episode = []
def _make_dataset(self):
dataset = list(itertools.chain.from_iterable(self.memory))
xp = self.vf.xp
# Compute v_pred and next_v_pred
states =... | This function checks if the accumulated dataset size meets a threshold. If so, it flushes the last episode, creates a dataset, updates the model, then resets the memory buffer to manage data processing intervals efficiently. | def _update_if_dataset_is_ready(self):
dataset_size = (
sum(len(episode) for episode in self.memory)
+ len(self.last_episode))
if dataset_size >= self.update_interval:
self._flush_last_episode()
dataset = self._make_dataset()
self._update(datas... |
def _flush_last_episode(self):
if self.last_episode:
self.memory.append(self.last_episode)
self.last_episode = []
def stop_episode(self):
pass
def _update_if_dataset_is_ready(self):
dataset_size = (
sum(len(episode) for episode in self.memory)
+ le... | This function ends an episode by logging the transition (state, action, reward, next_state) into the last episode buffer, resets the last state/action, flushes the episode data, stops the episode, and triggers model updates if the dataset is ready for training. | def stop_episode_and_train(self, state, reward, done=False):
assert self.last_state is not None
self.last_episode.append({
'state': self.last_state,
'action': self.last_action,
'reward': reward,
'next_state': state,
'nonterminal': 0.0 if done ... |
def get_squares(self, piece: str) -> list:
result_squares = []
for x in range(8):
for y in range(8):
if self.board_list[x][y].rstrip('.') == piece:
result_squares.append(Square(x, y))
return result_squares
def king_possible_moves(board: Board, squa... | This function checks if the current player's king is in check by simulating possible moves of opponent's pieces. It creates board copies, applies each piece's movement logic, and checks if the king's square is attacked. If any attacking piece (rook, bishop, queen, knight, or king) can reach the king's position, it retu... | def is_king_in_check(self) -> bool:
#print(original_board.next_move_color)
if self.is_next_move_white:
king_square = self.get_squares('K')[0]
q = copy.deepcopy(self)
#q.print()
board = king_possible_moves(q, king_square, True)
if board.get_s... |
def pawn_possible_moves(board: Board, square: Square, king_check = False) -> Board:
if not board.is_next_move_white:
board.flip()
square.x = (8-square.x)%8
square.y = (8-square.y)%8
_pawn_captures_moves(board, square)
_pawn_straight_moves(board, square)
_pawn_promotion_moves(boar... | The function generates possible moves for a selected chess piece on a board, considering the current player's turn. It identifies the piece at the given square, checks if it's the correct player's turn, converts the piece to lowercase for uniformity, and calls specific functions to compute moves based on the piece type... | def generate_possible_moves(board: Board, square: Square) -> Board:
piece = board.get_piece(square)
print(piece)
if (board.is_next_move_white and piece.isupper()) or (not board.is_next_move_white and piece.islower()):
piece = piece.lower()
if piece == 'p':
board = pawn_possible_m... |
def get_serial_number():
with open("/proc/cpuinfo", "r") as f:
for line in f:
if line[0:6] == "Serial":
return line.split(":")[1].strip()
def create_device(config, device_serial_number):
broker = config.get("mqtt", "broker_ip")
port = int(config.get("mqtt", "broker_port")... | Your return
The code reads configuration settings from `config.ini`, generates a Raspberry Pi device ID using its serial number, and initializes an MQTT client to publish environmental sensor data (from Enviro Plus) to a specified broker. It configures MQTT parameters (broker IP, port, topic, TLS, authentication) and... | def main():
config = configparser.ConfigParser()
config.read("config.ini")
# Raspberry Pi ID
device_serial_number = get_serial_number()
# device_serial_number = "1234567890"
device_id = "raspi-" + device_serial_number
print(
f"""mqtt-all.py - Reads Enviro plus data and sends over ... |
def find(self, key_value):
if not isinstance(self.primary_key, tuple):
primary_key_string = self.primary_key
placeholder_string = '?'
params = (key_value,)
else:
primary_key_string = remove_quotes_in_tuple(self.primary_key)
placeho... | This code inserts a record into a database table after checking for duplicates using the primary key. It generates an SQL INSERT query with placeholders, executes it with the record's values, and handles both single and composite primary keys. | def insert(self, record):
if not isinstance(self.primary_key, tuple):
key_value = record[self.primary_key]
else:
key_value = tuple(record[key] for key in tuple(self.primary_key))
result = self.find(key_value)
if result is not None:
... |
def find(self, key_value):
if not isinstance(self.primary_key, tuple):
primary_key_string = self.primary_key
placeholder_string = '?'
params = (key_value,)
else:
primary_key_string = remove_quotes_in_tuple(self.primary_key)
placeho... | This code deletes a database record based on a primary key. It checks if the record exists, constructs a parameterized SQL DELETE query (handling single/multi-field primary keys), and executes the deletion with safety against SQL injection. | def delete(self, key_value):
result = self.find(key_value)
if result is None:
print('Record not found!')
else:
if not isinstance(self.primary_key, tuple):
primary_key_string = self.primary_key
placeholder_string = '?'
params... |
def find(self, key_value):
if not isinstance(self.primary_key, tuple):
primary_key_string = self.primary_key
placeholder_string = '?'
params = (key_value,)
else:
primary_key_string = remove_quotes_in_tuple(self.primary_key)
placeho... | This code updates a database record by setting new values from the 'record' parameter where the primary key matches 'key_value'. It constructs an SQL UPDATE query with placeholders for values, handles primary key formatting, and executes the update with parameterized queries to ensure data integrity and prevent SQL inj... | def update(self, key_value, record):
result = self.find(key_value)
if result is None:
print('Record not found!')
else:
keys = list(record.keys())
update_string = ','.join([f'"{key}" = ?' for key in keys])
params = tuple(record.values())
... |
def difficult_words(text):
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
# Find all words in the text
words = []
sentences = break_sentences(text)
for sentence in sentences:
words += [str(token) for token in sentence]
# difficult words are those with syllables >= 2
# easy_w... | The code calculates the Gunning Fog index, a readability score estimating text complexity. It computes the percentage of difficult words relative to total words, adds 5, and combines this with average sentence length. The result is multiplied by 0.4 to determine the grade level required to understand the text, aiding i... | def gunning_fog(text):
per_diff_words = (difficult_words(text) / word_count(text) * 100) + 5
grade = 0.4 * (avg_sentence_length(text) + per_diff_words)
return grade |
def word_count(text):
sentences = break_sentences(text)
words = 0
for sentence in sentences:
words += len([token for token in sentence])
return words
def difficult_words(text):
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
# Find all words in the text
words = []
sentence... | The function calculates the Dale-Chall readability score for a given text by computing the percentage of difficult words (PDW) and average sentence length (ASL). It applies the formula: Raw score = 0.1579*PDW + 0.0496*ASL + 3.6365 (if PDW > 5%). The result is rounded to two decimal places, assessing text complexity for... | def dale_chall_readability_score(text):
"""
Implements Dale Challe Formula:
Raw score = 0.1579*(PDW) + 0.0496*(ASL) + 3.6365
Here,
PDW = Percentage of difficult words.
ASL = Average sentence length
"""
words = word_count(text)
# Number of words not termed ... |
def dale_chall_readability_score(text):
"""
Implements Dale Challe Formula:
Raw score = 0.1579*(PDW) + 0.0496*(ASL) + 3.6365
Here,
PDW = Percentage of difficult words.
ASL = Average sentence length
"""
words = word_count(text)
# Number of words not termed ... | The code calculates three readability scores (Dale-Chall, Gunning Fog, Flesch Reading Ease) for input text, formats them into a string, and returns both the formatted string and individual score values. | def get_all_fluency_value(txt):
dale_chall_readability_s = dale_chall_readability_score(txt)
gunning_fog_s = gunning_fog(txt)
flesch_reading_ease_s = flesch_reading_ease(txt)
# return dale_chall_readability_s, gunning_fog_s, flesch_reading_ease_s
score = 'dale_chall_readability ' + str(dale_chal... |
def dale_chall_readability_score(text):
"""
Implements Dale Challe Formula:
Raw score = 0.1579*(PDW) + 0.0496*(ASL) + 3.6365
Here,
PDW = Percentage of difficult words.
ASL = Average sentence length
"""
words = word_count(text)
# Number of words not termed ... | The main task of the code is to calculate readability scores (Dale-Chall, Gunning Fog, Flesch Reading Ease) for generated sentences in each data entry, update the data with these scores, and save the modified dataset. It processes each entry by extracting text, computing metrics, applying checks, and storing results in... | def run():
datalist = get_purpose_data()
lst = []
for data in datalist:
print(data)
sentences = data["generated_sentences"]
app_name = data["app"]
doc_index = data["doc_index"]
print(sentences)
dcr = dale_chall_readability_score(sentences)
gf = g... |
def dale_chall_readability_score(text):
"""
Implements Dale Challe Formula:
Raw score = 0.1579*(PDW) + 0.0496*(ASL) + 3.6365
Here,
PDW = Percentage of difficult words.
ASL = Average sentence length
"""
words = word_count(text)
# Number of words not termed ... | The code calculates and compares readability scores of two texts using four metrics: Dale-Chall, Gunning Fog, Flesch Reading Ease, and SMOG Index. It prints scores for an original text (orig_) and a generated text (gen_), highlighting differences in readability. The task is to evaluate how simplified or complex each te... | def test():
orig_ = 'We collect the content, communications and other information you provide when you use our Products, including when you sign up for an account, create or share content, and message or communicate with others'
gen_ = "we 'll get the content , communications and other information , and you 'l... |
def motion_ready(self):
self.add_robot()
self.take_arm(self._robot_handle)
self.motor_on(self._robot_handle)
def pick(self, x, y, z, alpha, beta, gamma, approach):
T_grasp = euler_matrix(radians(alpha), radians(beta), radians(gamma), axes="sxyz")
T_grasp[:3, 3] = np.array([x, y, z])
# tune gra... | This code initiates a robotic control loop to execute grasping and placement tasks. It starts a joint thread, checks for motion readiness, and iterates through grasp candidates to attempt picking using the `pick()` method. Upon successful grasping, it proceeds to place the object via `place()`, clears error states, and... | def start(self):
"""
start the control loop
"""
self._joint_thread.start()
self.motion_ready()
r = rospy.Rate(50)
while not rospy.is_shutdown():
if self._move:
for grasp in self._grasp_candidates:
if self.pick(grasp[0], grasp[1], grasp[2], grasp[3], grasp[4], grasp[5... |
def init_history(self) -> None:
self.history = ttk.Frame(self.root, padding=5, borderwidth=3, relief="solid")
self.history.grid(row=0, column=0, stick=tk.SW)
self.history.grid_columnconfigure(0, weight=1)
self.history_lines = DoublLinkdList()
self.history_scroll_bar = t... | The main task of the code is to create a GUI root window for a chemistry-related application, configuring its layout, adding a user input field with return event binding, initializing history data, and setting up a molecule inspector component. It sets up a Tkinter window with specific dimensions, grid configurations f... | def create_root(self):
#create user input
#create exit button
#create table of elements
self.root = tk.Tk()
self.root.title(configs["WindowName"])
self.root.geometry("800x510+0+0")
self.root.rowconfigure(0, weight=9)
self.root.rowconfigure(1, weight=1)
... |
def open_file():
global erase
global boardClear
global userColor
global blankColor
counter = 0
erase = False
boardClear = False
userColor = blankColor
openFile = filedialog.askopenfile(initialdir=path, title="Open Design")
colorArray = openFile.readlines()
colorArray = [... | The code creates a GUI menu tab with a "File" submenu containing options to "Open Design", "Save Design", and "Exit", using Tkinter. The menuStrip is a top-level menu, and 'file' is a cascading submenu attached to it. Each menu item is linked to functions like open_file(), save_file(), and on_closing() via lambda expre... | def createMenuTab():
global menuStrip
global file
menuStrip = Menu(tk)
file = Menu(menuStrip, tearoff=0)
menuStrip.add_cascade(label="File", menu=file)
file.add_command(label="Open Design", command=lambda: open_file())
file.add_command(label="Save Design", command=lambda: save_file())
... |
def filter_by_region(data_frame, region_name):
"""
Filters a DataFrame based on the specified region name.
"""
filtered_df = data_frame[data_frame['Region of Incident'] == region_name]
return filtered_df
def split_coordinates(df, column_name):
"""
Splits the coordinates column into lati... | The function filters input data to isolate Mediterranean region entries, processes coordinates, fetches corresponding weather data, and merges it into the dataset, returning an enriched DataFrame with weather information for Mediterranean locations. | def initialise_df_and_add_weather(df):
"""
Isolate data from the Mediterranean region and enrich it with weather data.
"""
mediterranean_df = filter_by_region(df, "Mediterranean")
split_coordinates(mediterranean_df, "Coordinates")
reset_and_drop_index(mediterranean_df)
weather_data_dict = fe... |
def interface(): # display interface and return str
with open("interface.csv") as file:
reader = csv.reader(file)
interface_list = list(reader)
print("\n Car Summon Application")
print(tabulate(interface_list, headers="firstrow", tablefmt="fancy_grid"))
# first time asking for input... | The main task of the code is to create a menu-driven application that allows users to access their information or summons via CSV file interactions. It authenticates users, retrieves data, and navigates between interfaces based on user input, with an exit option. The loop ensures continuous operation until the user cho... | def main():
n = 0 # define a variable to set as counter for interface() function
while True:
if n == 0:
user = interface() # this function will be called in beginning of program only
if user == "1": #To access "User's Information"
n = 1 # to not repeat function interf... |
def read_string(self):
length = self.read_u32()
s = self.f.read(length)
if length % 4 != 0:
padding = self.f.read(4 - (length % 4))
for p in padding:
if p != 0:
raise ValueError("String {} padded with {:r}", s, padding)
return s... | The code reads and parses structured data related to skins and sets, including name, zone flags, skin names, and set information, organizing them into a dictionary for structured output. | def read_skin(self):
name = self.read_string()
zone = self.read_u32()
is_blocked = self.read_u32()
is_toww = self.read_u32()
is_boss = self.read_u32()
skins = []
skin_count = self.read_u32()
for i in range(skin_count):
skins.append(self.read_s... |
def changeFlightMode(self, flightMode: str) -> None:
self.log('Changing flight mode to ' + flightMode + '......')
if self.__vehicle != None:
self.__vehicle.mode = dronekit.VehicleMode(flightMode)
self.log('Waiting for flight mode change ......')
while s... | This method arms a drone by switching it to STABILIZE mode, checking the 'isArmable' status, arming the vehicle, and waiting for confirmation. If the vehicle is not connected, it logs an error. | def arm(self) -> None:
if self.__vehicle != None:
self.changeFlightMode('STABILIZE')
self.log('Checking isArmable flag ......')
while not self.get_status('isArmable'):
sleep(0.5)
self.log('Arming ......')
self.__vehicle.arm(wait=True... |
def changeFlightMode(self, flightMode: str) -> None:
self.log('Changing flight mode to ' + flightMode + '......')
if self.__vehicle != None:
self.__vehicle.mode = dronekit.VehicleMode(flightMode)
self.log('Waiting for flight mode change ......')
while s... | This method transitions the drone to landing mode, monitors its altitude while it's armed, and logs progress until the altitude drops below 0.05 meters, indicating a successful landing. | def land_useMode(self) -> None:
self.changeFlightMode('LAND')
self.log('Landing ......')
currentAlt = self.get_relativeAlt()
while abs(currentAlt) >= 0.05 and self.get_status('isArmed'):
self.log('Current altitude is %.2f m' % (currentAlt))
sleep(0.5)
... |
def drone_rotateRight(self):
if self.globalData.isTerminated:
return
(self.mapWidth, self.mapHeight) = self.swap2D(self.mapWidth, self.mapHeight)
self.map = np.rot90(self.map)
self.mapOrigin = (self.mapHeight - self.mapOrigin[1], self.mapOrigin[0])
self.globalLocat... | The code's main task is to control a drone for SLAM initialization through rotational movement, generate a Voronoi diagram based on predefined human locations, and autonomously navigate toward a target location using decision logic (forward/back/left/right) while avoiding obstacles. It also supports guided mode with us... | def droneDo(self):
self.communication.receiveData('Press ENTER to start the mission .....')
# Rotate drone clockwise and try to get pose.
logText('[GOAL] Try to build SLAM')
while not self.globalData.isTerminated and not self.isPoseSet:
for i in range(4):
se... |
def __set_attitude_loop(self, roll_angel: float, pitch_angel: float, yaw_angel: float, throttle_perc: float, duration_sec: float) -> None:
ending = datetime.now().timestamp() + duration_sec
while datetime.now().timestamp() < ending:
self.__set_attitude(roll_angel, pitch_angel, yaw_angel, t... | This method sets a drone's attitude (orientation) using predefined angles and throttle, ensuring the vehicle is armed and parameters are valid. It adjusts the drone's pitch, roll, or yaw based on the specified AttitudeType, applies a default throttle if none is provided, and logs errors for invalid inputs or disconnect... | def set_attitude(self, attitude: AttitudeType, duration: float, throttle: float = None) -> None:
THROTTLE = 0.5
ANGLE_DIFF = 5
if throttle == None or (throttle < 0 or throttle > 1):
throttle = THROTTLE
if duration >= 0:
if self.__vehicle != None:
... |
def log(self, msg: str):
if self.__isLogToStdout:
print(msg)
if self.__isLogToFile:
with open('Copter.log', 'a') as fout:
fout.write('[' + datetime.now().strftime("%Y.%m.%d %H:%M:%S") + '] ' + msg + '\n')
def arm(self) -> None:
if self.__vehicle != None... | The code's main task is to execute a drone takeoff to a specified altitude by adjusting throttle based on altitude difference, handling negative altitude errors, arming the vehicle if needed, switching to GUIDED_NOGPS mode, and reverting to the original flight mode upon reaching the target altitude. It logs progress an... | def takeOff(self, altitude: float) -> bool:
if altitude < 0:
self.log('Failed to takeoff. Altitude should NOT be a negative value.')
return False
else:
if self.__vehicle != None:
self.log('Run takeoff procedure ......')
if no... |
def log(self, msg: str):
if self.__isLogToStdout:
print(msg)
if self.__isLogToFile:
with open('Copter.log', 'a') as fout:
fout.write('[' + datetime.now().strftime("%Y.%m.%d %H:%M:%S") + '] ' + msg + '\n')
def changeFlightMode(self, flightMode: str) -> None:
... | This method executes a drone landing procedure by descending until the altitude is near zero, then disarming and switching to STABILIZE mode. It checks if the drone is connected and armed, logs status updates, and uses attitude control to descend safely. If not armed, it logs a 'landed due to not armed' message. | def land(self) -> None:
if self.__vehicle != None:
self.log('Run landing procedure ......')
if self.__vehicle.armed:
self.changeFlightMode('GUIDED_NOGPS')
while True:
currentAlt = self.get_relativeAlt()
self.log('... |
def get_video_ids_from_playlist(self, playlist_id):
"""
Retrieve video IDs from a YouTube playlist.
Parameters:
- playlist_id (str): The ID of the YouTube playlist.
Returns:
- videos (list): A list of video IDs.
"""
videos = []
next_page_token = ... | The code downloads transcripts for all videos in a YouTube playlist identified by `playlist_id`. It retrieves video IDs, fetches titles and transcripts, saves each transcript as a text file in a "transcripts" directory, and includes error handling and rate-limiting pauses. | def download_playlist_transcripts(self, playlist_id):
"""
Download transcripts for all videos in a YouTube playlist.
Parameters:
- playlist_id (str): The ID of the YouTube playlist.
"""
videos = self.get_video_ids_from_playlist(playlist_id)
for video in tqdm(vid... |
def solve_sudoku_hidden_single(temp_grid):
if find_blank(temp_grid):
return False
attempt = 0
total_grid(temp_grid)
def single_number():
nonlocal attempt
nonlocal group
nonlocal number
count = 0
cell_to_clean = (-1, -1)
for cell in group:
... | This code solves a Sudoku puzzle using backtracking with constraint propagation. It applies hidden single and simple elimination techniques, then recursively fills blank cells by testing valid numbers, visualizing each step. If a choice leads to no solution, it backtracks. The function returns the count of valid soluti... | def solve_sudoku(temp_grid):
while solve_sudoku_hidden_single(temp_grid):
solve_sudoku_hidden_single(temp_grid)
while solve_sudoku_simple_elimination(temp_grid):
solve_sudoku_simple_elimination(temp_grid)
reload_options(temp_grid)
# Find first blank square
j, i = 0, 0
while i < 9... |
def is_valid(temp_grid, row, col, candidate):
# int i, j
if temp_grid[row][col].number != 0:
return False
# Check column
for i in range(9):
if i != row:
if temp_grid[i][col].number == candidate:
return False
# Check row
for i in range(9):
if ... | This function solves a Sudoku puzzle using constraint propagation and backtracking. It identifies the first empty cell, tests valid numbers, updates the grid visually, and recursively explores solutions. If no solution is found, it backtracks. Returns the count of valid solutions discovered. | def solve_sudoku_constraint_propagation(temp_grid):
# Find first blank square
j, i = 0, 0
while i < 9:
j = 0
while j < 9 and temp_grid[i][j].number != 0:
if j == 8:
break
else:
j += 1
if temp_grid[i][j].number == 0:
... |
def computeDeterminant(matrix):
if len(matrix) == 1 and len(matrix[-1]) == 1:
return matrix[0][0]
determinant = 0
for i in range(len(matrix)):
submatrix = computeSubmatrix(matrix, 0, i)
minor = computeDeterminant(submatrix)
cofactor = minor * ((-1)**(i))
determinant ... | The code computes the modular inverse of a matrix over the integers modulo 26. It calculates the determinant, finds its modular inverse, computes the cofactor matrix, transposes it, and scales each element by the inverse determinant modulo 26. If the determinant is zero, it prints an error. Otherwise, it returns the re... | def computeMatrixInverse(matrix):
determinant = computeDeterminant(matrix) % 26
for i in range(1, 26):
if (determinant * i) % 26 == 1:
determinant = i
break
cofactorMatrix = computeCofactorMatrix(matrix)
transposedCofactorMatrix = transposeMatrix(cofactorMatrix)
if d... |
def convert_string_to_matrix(text):
size = math.ceil(math.sqrt(len(text)))
text = text.upper()
matrix = []
for i in range(size):
matrix.append([ord(char)-65 for char in text[i*size: (i+1)*size]])
for i in range(size - len(matrix[-1])):
matrix[-1].append(ord('X')-65)
return matri... | The code decrypts ciphertext using a Hill cipher with a given key matrix. It computes the inverse of the key matrix, checks if it's invertible (non-zero determinant), and applies matrix multiplication to each block of ciphertext. Characters are converted to numerical values, processed with the inverse matrix, and trans... | def decryption(key, ciphertext):
matrix = convert_string_to_matrix(key)
determinant = computeDeterminant(matrix)
if determinant == 0:
print("Inverse of key matrix cannot be computed as determinant is 0")
return
inverseMatrix = computeMatrixInverse(matrix)
plaintext = ""
for i in ... |
def try_one_tracker(self) -> bool:
assert self.state == State.IDDLE
req_msg_buf, _= self.create_connection_request()
for tracker_addr in self.tracker_adresses:
self.sock.sendto(req_msg_buf, tracker_addr)
try:
data, addr = self.sock.recvfrom(1024)
... | The main task of the code is to establish a connection to a tracker, send an announce message, and enter a loop to handle incoming data from the socket. If no best tracker is configured, it attempts to connect using `try_one_tracker()`, sends an announce message, and then uses `select.select()` to monitor the socket fo... | def run_loop(self) -> bool:
if not self.config.best_tracker:
if not self.try_one_tracker():
return False
assert self.state == State.CONNECTED
print(f"Connected to tracker: {self.tracker_addr}")
if not self.send_announce_msg():
ret... |
def _draw_sign(self, square: int) -> None:
self._field[square]["state"] = "disabled"
self._field[square]["text"] = self._cur_sign
self._field[square]["disabledforeground"] = self._color[self._cur_sign]
def _check_win(self) -> None:
for a, b, c in self._win_pos:
if (self._fiel... | This method handles a player's move in a game by playing a sound effect, marking the selected square, removing it from available moves, checking for a win, switching turns, and determining if the game should end. | def _click(self, square: int) -> None:
self.master.click_music.play()
self._draw_sign(square)
self._free_squares.remove(square)
self._check_win()
self._change_sign_and_status()
self._if_end_game() |
def _player_sign_lbl(self) -> None:
tk.Label(self, font=self.master.font, text=self._player_sign_msg).pack(
side="top", anchor="n", pady=(10, 15))
def _create_field(self, frame: tk.Frame) -> List[tk.Button]:
field = []
for i in range(9):
button = tk.Button(frame, text=' '... | The main task of the code is to create and organize UI components for a game or application. It initializes a player sign label, a game field within a frame, a status label, and a return button, arranging them in a Tkinter window to build the graphical interface. | def _create_widgets(self) -> None:
self._player_sign_lbl()
frame = tk.Frame(self)
frame.pack(side="top")
self._field = self._create_field(frame)
self._status_lbl()
self._create_return_btn() |
def _sign_choose(self) -> Tuple[str, str]: # type: ignore
if self.master.sign.get() == "R":
i = random.randint(0, 1)
return ["X", "O"][i], ["X", "O"][1 - i]
elif self.master.sign.get() == "X":
return "X", "O"
elif self.master.sign.get() == "O":
re... | This code initializes a GUI-based Tic-Tac-Toe game interface, setting up player symbols, names, game state variables (free squares, win positions), status messages, and widgets. It configures window properties, prepares game logic components, and calls widget creation to ready the game for play. | def __init__(self, master: Ttt.App) -> None:
super().__init__(master)
self.configure(height=650, width=550)
self.pack_propagate(False)
self.master: Ttt.App
self._cur_music: pg.mixer.Sound = self.master.win_music
self._user1_sign: str
self._user2_sign: str
... |
def find_epsilon(clust,ite=50,waiting_thresh=10,verbose=False):
reach = deepcopy(clust.reachability_)
prev_max=0
#size_array = np.shape(clust.reachability_)[0]
stb_ct = 0
eps_stb=-1
prev_n_labels = -1
n_labels_this_eps = -1
first_app_this_eps = -1
for i in range(ite):
... | The code visualizes and analyzes clusters from t-SNE data using OPTICS DBSCAN with adaptive epsilon thresholds. It loads precomputed embeddings, computes stability and variability epsilons, clusters data, evaluates feature standard deviations per cluster, and outputs metrics like cluster statistics, max feature varianc... | def visualize_TSNE_PF_ph(ph,seed,F_nh_small=True,
path='/home/fplana/evol_datafr_analysis/',n_ite=50,wait_th=10,verb=False,mnp=0.02,rst=1.5):
name=path + "clusters/tSNE_PF_"+str(seed)+ "seed_"+str(ph)+"ph_"+str(F_nh_small)+"Fnhsmall.pickle"
with open(name, "rb") as fil... |
def find_epsilon(clust,ite=50,waiting_thresh=10,verbose=False):
reach = deepcopy(clust.reachability_)
prev_max=0
#size_array = np.shape(clust.reachability_)[0]
stb_ct = 0
eps_stb=-1
prev_n_labels = -1
n_labels_this_eps = -1
first_app_this_eps = -1
for i in range(ite):
... | The main task of the code is to visualize and analyze t-SNE embeddings by loading precomputed data, applying OPTICS-DBSCAN clustering with varying epsilon thresholds, calculating cluster standard deviations, and plotting results. It processes data to evaluate cluster stability, identifies features with maximum variance... | def visualize_TSNE(ph,seed,path='/home/fplana/evol_datafr_analysis/',n_ite=50,wait_th=10,verb=False,mnp=0.02,rst=1.5,proc_NA=False):
# open tSNE data
# 1 opt
if ph == floor(ph):
if ph <4:
if not proc_NA:
name= path + "clusters/tSNE_"+str(ph)+"opt_"+str(seed)+... |
def filter_df(fs,ph,F_nh_small,path):
with open(path + "all_var_all_optima.pickle", "rb") as file:
all_data = pickle.load(file)
# filter PF data, the ph, F, nh region
all_data_3 = all_data[all_data['type_min']==3]
all_data_3 = all_data_3[all_data_3['ph']==ph]
del all_dat... | This function generates and analyzes decision trees (DTs) from clustered data, focusing on stability and accuracy. It loads precomputed t-SNE clusters, processes features, adds derived variables, and runs a parameterized DT search. Distinct DTs are identified, saved with metadata, and visualized. The output includes st... | def produce_PF_ph_DTs(ph,seed,n_cores,HP,nM,F_nh_small=True,
root='/home/fplana/evol_datafr_analysis/',
inter_I=False,prop_min_sampl=.03,
mnp=0.02,rst=1.5,inter1st=False):
name=root + "clusters/tSNE_PF_"+str(seed)+ "seed_"+str(ph)+"ph_"+str(F_nh_sma... |
def find_epsilon_III(clust,df,verbose=False,max_nois_prop=0.02,ratio_std_thr=1.5):
reach = deepcopy(clust.reachability_)
prev_max=0
ite = ceil(df.shape[0] * max_nois_prop)
curr_min_eps = np.inf
curr_min_std = np.inf
for i in range(ite):
curr_max = np.amax(reach)
po... | The function `produce_PF_DTs` generates and analyzes decision trees (DTs) from a dataset, using parameters like `ph`, `seed`, and `n_cores`. It loads precomputed data, selects features, computes clustering, and uses parallel processing to build DTs. It then searches for stable, accurate DTs via `PFsearch_DT_stbacc_II`,... | def produce_PF_DTs(ph,seed,n_cores,HP,nM,root='/home/fplana/evol_datafr_analysis/',
inter_I=False,prop_min_sampl=.03,
mnp=0.02,rst=1.5,inter1st=False,proc_NA=False):
#rg = default_rng(seed)
# 1 opt
if ph == floor(ph):
if ph < 4:
if not pr... |
def extract_constraints_from_DT(DT):
split_nodes, leaf_nodes = DT._get_node_ids()
idbr_split_nodes = dict(zip(split_nodes.values(), split_nodes.keys()))
idbr_leaf_nodes = dict(zip(leaf_nodes.values(), leaf_nodes.keys()))
output = {}
for node_id in idbr_leaf_nodes:
the_dic... | The function processes and combines data from tSNE clustering, Decision Trees (DTs), and power-law degree distribution fits to analyze network structures under single/multiobjective optimization scenarios. It loads precomputed data, merges features like F, nh, ph, and gamma values, applies filters, and generates graph ... | def graph_DT_plus_pl_degDistr(opt,seed,root,n_DT,ph=0,F_nh_small=True,proc_NA=False,mnp=0.02,
is_dir=True,lay=True,p_vr=None,to_file=False,extra_DTfeat=None,n_s=None,r_n=2):
if opt < 3: # single optima, ph is not used
# tSNE path
if not proc_NA:
name= root + ... |
def extract_constraints_from_DT(DT):
split_nodes, leaf_nodes = DT._get_node_ids()
idbr_split_nodes = dict(zip(split_nodes.values(), split_nodes.keys()))
idbr_leaf_nodes = dict(zip(leaf_nodes.values(), leaf_nodes.keys()))
output = {}
for node_id in idbr_leaf_nodes:
the_dic... | This function loads decision tree (DT) data and constraints, processes feature selections, generates derived features (e.g., F*nh*ph), and constructs graph structures for leaf nodes using a specified DT. It returns the DT, constraints, processed data, and graph components for analysis or visualization. | def graph_DT_PF_ph(ph,seed,root,n_DT,F_nh_small=True,
is_dir=True,lay=True,p_vr=None,to_file=False,extra_DTfeat=None):
name= root + "clusters/tSNE_PF_"+str(seed)+ "seed_"+str(ph)+"ph_"+str(F_nh_small)+"Fnhsmall.pickle"
with open(name, "rb") as file:
[tsne, clust, fs] ... |
def extract_constraints_from_DT(DT):
split_nodes, leaf_nodes = DT._get_node_ids()
idbr_split_nodes = dict(zip(split_nodes.values(), split_nodes.keys()))
idbr_leaf_nodes = dict(zip(leaf_nodes.values(), leaf_nodes.keys()))
output = {}
for node_id in idbr_leaf_nodes:
the_dic... | The function `graph_DT_plus_pl_vars` loads decision tree (DT) data and associated constraints, merges them with additional variables from a master dataset, and generates graph structures (e.g., leaf nodes, masks) based on input parameters. It handles both single-objective (`opt < 3`) and multiobjective (`opt ≥ 3`) scen... | def graph_DT_plus_pl_vars(opt,seed,root,n_DT,ph=0,F_nh_small=True,proc_NA=False,mnp=0.02,
is_dir=True,lay=True,p_vr=None,to_file=False,extra_DTfeat=None):
if opt < 3: # single optima, ph is not used
# tSNE path
if not proc_NA:
name= root + "clusters/tSNE_"+st... |
def extract_constraints_from_DT(DT):
split_nodes, leaf_nodes = DT._get_node_ids()
idbr_split_nodes = dict(zip(split_nodes.values(), split_nodes.keys()))
idbr_leaf_nodes = dict(zip(leaf_nodes.values(), leaf_nodes.keys()))
output = {}
for node_id in idbr_leaf_nodes:
the_dic... | The function `graph_DT_plus_pl_ddd` processes decision trees (DTs) and clustering data for single or multiobjective optimization scenarios. It loads tSNE and DT data, merges additional variables (e.g., `pval`, `xmin`, `alpha`), applies constraints from DTs, and generates graph structures (masks, leaf nodes) using clust... | def graph_DT_plus_pl_ddd(opt,seed,root,n_DT,ph=0,F_nh_small=True,proc_NA=False,mnp=0.02,
is_dir=True,lay=True,p_vr=None,to_file=False,extra_DTfeat=None):
if opt < 3: # single optima, ph is not used
# tSNE path
if not proc_NA:
name= root + "clusters/tSNE_"+str... |
def fix_text_problems(text, pg=None):
"fix common text problems"
text = re.sub('\s+[-]\s+','',text) # word continuation in the next line
return text
def split_pages_into_fragments(pages, frag_size):
"split pages (list of texts) into smaller fragments (list of texts)"
page_offset = [0]
for p,page in enumerate(page... | The function generates a vector index for a PDF file by calculating its MD5 hash, splitting pages into text fragments, processing text (if needed), extracting vectors via AI, and compiling metadata like fragment size, summary, and usage statistics into a structured dictionary for document representation and retrieval. | def index_file(f, fix_text=False, frag_size=0, pg=None):
"return vector index (dictionary) for a given PDF file"
# calc md5
h = hashlib.md5()
h.update(f.read())
md5 = h.hexdigest()
f.seek(0)
#
pages = pdf.pdf_to_pages(f)
if fix_text:
for i in range(len(pages)):
pages[i] = fix_text_problems(pages[i], pg)
... |
def getResponseCode(req):
global responseStatus
split = req.split('HTTP/')
if '/product' in split[0]:
if '?' in split[0]:
parsed = split[0].split('?')
values = parsed[1] # 'a=3&b=7 '
if hasValidData(values):
return 200
else: # Invalid ... | The code defines a TCP server that listens on a specified port, accepts client connections, processes incoming requests, generates appropriate HTTP responses (200 OK with JSON data or error status), constructs headers and body, sends them to the client, then closes the connection and exits after handling each request. | def hostFunction():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# SOCK_STREAM specifies we are using TCP
s.bind(('', port))#listen to all addresses
s.listen()
global responseCode
while True:
conn, addr = s.accept()
req = conn.recv(1024... |
def _ensure_dir_exists(path):
Path(path).mkdir(parents=True, exist_ok=True)
def _make_linked_issues_regex(owner, repo):
owner = owner.replace('.', r'\.')
repo = repo.replace('.', r'\.')
pattern = _linked_issues_pattern_template.format(owner=owner, repo=repo)
return re.compile(pattern, flags=re.IGNOR... | The code crawls GitHub repositories to extract merged pull requests (PRs) and their linked issues. It iterates through pages of closed PRs, checks if a PR is merged and contains issue links, then fetches and saves the PR and linked issues as JSON files. Files are stored in structured directories with names like 'pull-N... | def crawl(self, owner, repo, start_page=1):
"""Crawls a GitHub repository, finds and saves merged pull requests and the issues
they have fixed.
The crawler goes through the pages of closed pull requests, from oldest to
newest. If a pull request is merged and links one or more issues in ... |
def renderMaze(self):
count = 0
for i in range(len(self.maze)):
for j in range(len(self.maze[i])):
# Render a wall
if self.maze[i][j] == 1:
# Wall position, and height
x = j * self.cube_size
... | The main task of the code is to initialize a 3D maze game environment, setting up maze structure, player, enemies, keys, and exit. It generates a maze, positions game elements, checks for initial collisions, and initializes audio/visual components for gameplay. | def __init__(self, window, enemy_speed, number_of_keys):
self.window = window
self.enemy_speed = enemy_speed
self.number_of_keys = number_of_keys
# Enemy
self.start_moving = True
# Maze
self.maze_size = 5
self.cube_size = 5.0
self.wall_hei... |
def get_tracking_param_dicts() -> dict:
"""Will return dictionaries specifying the feature parameters and tracking parameters.
In future, these may vary based on version."""
feature_params = dict(maxCorners=10000, qualityLevel=0.01, minDistance=12, blockSize=3)
window = 5
lk_params = dict(winSize=(w... | This function tracks points across a sequence of images using adaptive parameters. It adjusts feature and Lucas-Kanade tracking parameters iteratively to ensure robust tracking, increasing the window size if displacements are too small. It returns tracked points and warns if displacements are subpixel, indicating limit... | def track_all_steps_with_adjust_param_dicts(img_list_uint8: List, mask: np.ndarray) -> dict:
"""Given image list and mask. Will automatically update the feature parameters and tracking parameters to ensure accurate and robust tracking.
Will return tracked points through the whole img list in order. """
feat... |
def create_sub_domains(
mask: np.ndarray,
*,
pillar_clip_fraction: float = 0.5,
shrink_row: float = 0.1,
shrink_col: float = 0.1,
tile_dim_pix: int = 40,
num_tile_row: int = 5,
num_tile_col: int = 3,
tile_style: int = 1,
clip_columns: bool = True,
clip_rows: bool = False,
... | The main task of the code is to perform strain analysis on sub-domains extracted from tracked image data. It reads a tissue mask and tracking results, creates sub-domains using specified parameters (e.g., tile dimensions, clipping, shrinking), computes strain metrics for each sub-domain, and saves the results as text f... | def run_sub_domain_strain_analysis(
folder_path: Path,
pillar_clip_fraction: float = 0.5,
shrink_row: float = 0.1,
shrink_col: float = 0.1,
tile_dim_pix: int = 40,
num_tile_row: int = 5,
num_tile_col: int = 3,
tile_style: int = 1,
is_rotated: bool = True,
clip_columns: bool = Tru... |
def image_folder_to_path_list(folder_path: Path) -> List:
"""Given a folder path. Will return the path to all files in that path in order."""
name_list = glob.glob(str(folder_path) + '/*.TIF')
name_list.sort()
name_list_path = []
for name in name_list:
name_list_path.append(Path(name))
r... | The function `run_tracking` processes a folder containing images and a mask to track objects. It reads images, applies a mask, tracks objects using two trackers, computes their time-series positions, and saves the tracking results as text files. The main task involves image processing, object tracking, and result stora... | def run_tracking(folder_path: Path) -> List:
"""Given a folder path. Will perform tracking and save results as text files."""
# read images and mask file
movie_folder_path = folder_path.joinpath("movie").resolve()
name_list_path = image_folder_to_path_list(movie_folder_path)
tiff_list = read_all_tif... |
def compute_loss(a_or_ipw_outputs,f_outcome_out,x_out,fr_targets,targets,x_inputs_,L_kl,lengths,Pred_X,criterion,args,obs_w,batchSize,device,inference=False):
a_or_ipw_loss = torch.zeros(1).to(device)
outcome_loss = torch.zeros(1).to(device)
fail_loss = torch.zeros(1).to(device)
curve_loss = torch.zeros... | The main task of the code is to train a machine learning model for causal inference or treatment effect estimation using inverse probability weighting (IPTW), with support for GPU acceleration, validation, and model saving. It processes training data, computes losses including outcome and treatment-related terms, perfo... | def trainInitIPTW(train_loader, val_loader,test_loader, model, args, epochs, optimizer, criterion,
use_cuda=False, save_model=None,TEST=False):
if use_cuda:
print("====> Using CUDA device: ", torch.cuda.current_device(), flush=True)
model.cuda()
model = model.to('cuda')
... |
def first_start(self):
# self.sumoCmd[0] = 'sumo-gui'
traci.start(self.sumoCmd)
self.shape_intersection = traci.junction.getShape('J1')
self.len_intersection = 2 * max([max(ele) for ele in self.shape_intersection])
self.lane_length = [traci.lane.getLength(id) for id in self.lane_... | The `reset` method initializes or reinitializes the simulation environment for a new episode. It sets initial observations, resets agent states, handles curriculum parameters (e.g., random behavior, communication lag), spawns vehicles, loads SUMO configurations, and prepares data structures for tracking vehicle positio... | def reset(self, env_args=None):
""" Returns initial observations and states"""
print(self.intention_probs)
if self.episode_num == 0:
if self.run_curricula:
self.random_behavior = env_args["random_behavior"]
self.comm_lag = env_args["comm_lag"]
... |
def _set_enter_and_leave_flags(self):
# assign true flag to enter_flag_list from tmp variable
for id_idx, id in enumerate(self.CAVs_id_list):
if id not in self.curr_ID_list: # if one CAV goes out of scope, continue.
continue
self._if_veh_enters_the_junction(vehID... | This code executes a single step in a simulation environment, applying given actions to control traffic (e.g., traffic lights), updating vehicle states, calculating rewards, and determining episode termination. It handles action processing, simulation progression, observation updates, reward computation, and returns re... | def step(self, actions):
""" Returns reward, terminated, info """
# wait all vehicles
self.curr_ID_list = traci.vehicle.getIDList()
# decide if the vehicle has entered or left the intersection
self._set_enter_and_leave_flags()
if self.use_ppo_like_algo:
action... |
def load_data():
global wks_dict
global data_dict
credentials = json.loads(GOOGLE_JSON)
# print(type(credentials))
gc = gspread.service_account_from_dict(credentials)
# gc = gspread.service_account(filename='config/creds.json')
allWks = gc.open("trading_python").worksheets(exclude_hidden=Tr... | The main task of the code is to automate trading operations by placing buy orders via the Kite API based on SIP (Systematic Investment Plan) or average-down conditions. It processes predefined trading data, skips jobs if specified, checks market prices, executes orders, and logs results with notifications. The function... | def trading_job():
global kite
global scheduler
global data_dict
load_data()
# print(data_dict)
# return
for dataKey in data_dict.keys():
print('- - - - - - - - - - - - - - - - - - -')
skip_job = data_dict[dataKey]['skip_job'].lower() in ['true', '1', 't', 'y', 'yes']
... |
def highres_spectrogram(ppath, rec, nsr_seg=2, perc_overlap=0.95, recalc_highres=False,
mode='EEG', get_M=False):
"""
Load or calculate high-resolution spectrogram for a recording
@Params
ppath - base folder
rec - name of recording
nsr_seg, perc_overlap - set FFT bin... | The code plots multiple neural/physiological signals (EEG, EMG, LFP, DFF, etc.) from a recording on a shared time axis, with customizable parameters for signal selection, preprocessing (downsampling, normalization, smoothing), spectrogram visualization, brain state annotations, and P-wave detection. It loads data, proc... | def plot_example(ppath, rec, PLOT, tstart, tend, ma_thr=20, ma_state=3, flatten_tnrem=False,
eeg_nbin=1, emg_nbin=1, lfp_nbin=17, dff_nbin=250, highres=False,
recalc_highres=True, nsr_seg=2.5, perc_overlap=0.8, pnorm=0, psmooth=0,
fmax=30, vm=[], cmap='jet', ylims=[], ... |
def wavefunctionMRsplit(r,filling,Nb,Ntotal): #Moore-Read wavefunction in presence of TWO impurities supposing they bind to half-vortices
# #GS
ex=0
## #FIRST EXCITED
# if edge==1:
# ex=np.log(np.sum(r[0,Nb:]+1j*r[1,Nb:]))
# if edge==2:
# ex=np.log(np.sum(r[0,:Nb]+1j*r[1,:Nb])**3)
# SECOND EXCITED
# if e... | The code performs a Monte Carlo simulation using the Metropolis algorithm to compute the average total angular momentum (Lz) and impurity-related quantities (LzImpu) for a system of particles. It initializes particle positions, iterates over blocks, moves, and thermalization steps, updating positions based on a wavefun... | def MCrun(step,nblk,nmov,nterm,filling,Nb,Ntotal):
lz=0
lzimpu=0
#lzimpu2=0
r=10*step*(np.random.rand(2,Ntotal)-0.5) #initialize particles positions
wfold=wavefunctionMRsplit(r,filling,Nb,Ntotal)
#starts integration
count=0
for iblk in range(1,nblk+1): #number of runs
for jmov in r... |
def get_values(self):
row_clues = []
col_clues = []
row_vals = {}
col_vals = {}
num_vals = {}
for i in range(self.n):
rv, r_num = self.line_values(i, is_row=True)
cv, c_num = self.line_values(i, is_row=False)
row_vals.update(rv)
... | This code initializes a puzzle-solving class by configuring parameters like clue handling, cell order strategy (smart vs. naive), and value tracking. It sets up the board, possible values for each cell, and initializes solving logic with options to enable/disable optimization features like smart cell ordering and value... | def __init__(self, clues, use_obvious=True, use_smart_cell_order=True,
use_update_vals=True):
self.clues = clues
self.use_obvious = use_obvious
self.use_smart_cell_order = use_smart_cell_order
self.use_update_vals = use_update_vals
self.num_guesses = 0
s... |
def get_matrix(partition1, centroids1, partition2, centroids2, df):
n = df.shape[0]
matrix = []
for i in range(n):
matrix.append([0 for j in range(i + 1, n)])
v_index1 = squared_error(df, partition1, centroids1)
v_index2 = squared_error(df, partition2, centroids2)
for i in range(n):
... | The code generates a matrix from clustering partitions, saves it to Excel, constructs a graph, computes a Minimum Spanning Tree (MST), adjusts it based on parameter `k`, and applies flood fill to assign labels to nodes, returning these labels for ensemble clustering analysis. | def ensemble(partition1, centroids1, partition2, centroids2, df, k):
matrix = get_matrix(partition1, centroids1, partition2, centroids2, df)
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
for row in matrix:
ws.append(row)
wb.save('matrix10.xlsx')
nodes = df.shape[0]
... |
def get_initial_membership(data, c):
data_size = len(data)
membership_matrix = []
for i in range(data_size):
temp = []
for j in range(c):
temp.append(random.randint(1, data_size))
temp = [t/sum(temp) for t in temp]
membership_matrix.append(temp)
return me... | This code implements the Fuzzy C-Means clustering algorithm to group input data into 'c' clusters. It initializes membership values and cluster centroids, iteratively updates them using fuzzy partitioning and centroid calculation, and stops when membership changes fall below a threshold (0.001). Finally, it assigns eac... | def fuzzy_c_means(data, c):
m = 3
new_membership_matrix = get_initial_membership(data, c)
new_f_centers = get_centroids(data, new_membership_matrix, c, m)
print(new_f_centers)
J = calculate_error(data, new_f_centers, new_membership_matrix, c, m)
old_J = float("inf")
membership_matrix = None
... |
def get_initial_centroids(data, n_clusters, data_size):
centroids = []
index = []
i = 0
while i < n_clusters:
r = random.randint(0, data_size)
if r not in index:
centroids.append(data.iloc[r].tolist())
index.append(r)
i += 1
return centroids
def g... | This code implements the K-means clustering algorithm to group input data into 'n_clusters' clusters. It initializes centroids, iteratively assigns data points to the nearest centroid, recalculates centroids as cluster means, and repeats until centroids stabilize or 1000 iterations are reached. The function returns fin... | def KMeans(data, n_clusters):
data_size = data.shape[0]
feature_size = data.shape[1]
centroids = get_initial_centroids(data, n_clusters, data_size)
change = True
iterations = 0
clusters = []
while change and iterations < 1000:
old_centroids = centroids.copy()
clusters = get_c... |
def _generate_auth_url(self, path, params, accepts_clientid):
"""Returns the path and query string portion of the request URL, first
adding any necessary parameters.
:param path: The path portion of the URL.
:type path: string
:param params: URL parameters.
:type params: ... | The function performs an authenticated HTTP GET request with retry logic, handling timeouts and retriable status codes. It includes exponential backoff with jitter for retries, processes the response body as JSON, and raises appropriate errors for API, transport, or timeout issues. | def _get(self, url, params, first_request_time=None, retry_counter=0,
base_url=_DEFAULT_BASE_URL, accepts_clientid=True, extract_body=None):
"""Performs HTTP GET request with credentials, returning the body as
JSON.
:param url: URL path for the request. Should begin with a slash.
... |
def move_R(board,i,j):
Children=[]
if j > 0 and i < 7 and board[i+1][j-1] == '-':
tempboard=return_with_new_move(board,i,j,i+1,j-1)
tempboard=convert_to_king(tempboard,i+1,j-1)
if tempboard != board:
Children.append(tempboard)
if j < 7 and i < 7 and board[i+1][j+1] == ... | The main task of the code is to generate all possible child states of a board by identifying positions of 'R' and 'KR' pieces, applying their valid moves (including captures) via helper functions, and aggregating resulting states into a list. It iterates through the board, processes each piece type with corresponding m... | def get_all_children_R(board):
Children=[]
for i in range(0,len(board)):
for j in range(0,len(board[i])):
if board[i][j] == 'R':
temp=move_R(board,i,j)
for x in range(0, len(temp)):
Children.append(temp[x])
temp=move_and_bea... |
def move_B(board,i,j):
Children=[]
if j > 0 and i > 0 and board[i-1][j-1] == '-':
tempboard=return_with_new_move(board,i,j,i-1,j-1)
tempboard=convert_to_king(tempboard,i-1,j-1)
if tempboard != board:
Children.append(tempboard)
if j < 7 and i > 0 and board[i-1][j+1] == ... | This function generates all possible child states of a board by iterating through each cell. For 'B' pieces, it appends results from move_B and move_and_beat_B. For 'KB' (king black), it similarly processes move_R, move_and_beat_R, and repeats the 'B' moves. The collected states are returned as a list, representing all... | def get_all_children_B(board):
Children=[]
for i in range(0,len(board)):
for j in range(0,len(board[i])):
if board[i][j] == 'B':
temp=move_B(board,i,j)
for x in range(0, len(temp)):
Children.append(temp[x])
temp=move_and_bea... |
def get_all_children_B(board):
Children=[]
for i in range(0,len(board)):
for j in range(0,len(board[i])):
if board[i][j] == 'B':
temp=move_B(board,i,j)
for x in range(0, len(temp)):
Children.append(temp[x])
temp=move_and_bea... | This function implements the Alpha-Beta pruning algorithm for a two-player game, recursively evaluating board states to determine the optimal move. It alternates between maximizing ('B') and minimizing ('R') players, pruning suboptimal branches to improve efficiency. When multiple optimal moves exist at the top level, ... | def AlphaBeta(board, Depth, Player, Alpha, Beta):
list_children_same_max=[]
if Player == 'B':
PrivousPlayer='R'
Children=get_all_children_B(board)
else:
PrivousPlayer='B'
Children=get_all_children_R(board)
if utility(board,PrivousPlayer) != 0:
return utility(board... |
def forwardN(tiles):
for i in range (tiles*12):
vehicle.drive_forward(3)
time.sleep(0.1)
distance = distance_sensor1.distance
print (distance)
#Checks distance sensor and checks if weed if object is close
if (distance <= 0.25):
... | The code navigates through an array by alternating between right and left turns (180-degree rotations) at each step, moving forward one unit per iteration. It checks a condition `forwardN(len(array))` to potentially break the loop early. The primary task is to traverse the array's elements with directional changes base... | def navigate(array):
for i in range (array[0].size):
if (forwardN(len(array))):
break
if (i%2 == 0):
turn90right()
forwardN(1)
turn90right()
if (i%2 == 1):
turn90left()
... |
def forwardN(tiles):
for i in range (tiles*12):
vehicle.drive_forward(3)
time.sleep(0.1)
distance = distance_sensor1.distance
print (distance)
#Checks distance sensor and checks if weed if object is close
if (distance <= 0.25):
... | Your return
The function `navigate2` simulates a path navigation task, moving forward a specified `length` and adjusting direction based on the iteration index. It iterates `width` times, attempting to move forward `length` units. If successful, it breaks. Otherwise, it alternates between right and left turns (depend... | def navigate2(length, width):
for i in range (width):
if (forwardN(length)):
break
if (i%2 == 0):
turn90right()
forwardN(1)
turn90right()
if (i%2 == 1):
turn90left()
forwardN(1)
... |
def set_openai_key(self):
openai.api_key = self.openai_api_key
def set_serper_api_key(self):
os.environ["SERPER_API_KEY"] = self.serper_api_key
def generate_article_and_statements(self, story):
# Prompt to generate a baseline article about the short story provided
article_prompt = Promp... | The code transforms a user-provided short story into a structured news article by generating a baseline text, verifying factual statements, refining content, integrating web-sourced testimonials, and formatting the final output for publication. | def generate_response(self, text):
self.set_openai_key()
self.set_serper_api_key()
# deactivated for now
# input -> theme to build a short story - str
# output -> short_story_response['story'] - dict
# short_story_response = self.generate_short_story("Your theme here")
... |
def load_bib(bib_path):
with open(bib_path) as bibtex_file:
bibtex_str = bibtex_file.read()
parser = btp.bparser.BibTexParser(common_strings=True)
bib_database = btp.loads(bibtex_str,parser = parser)
return [x for x in bib_database.entries]
def get_all_pdfs(bibdata,pdfs):
all_pdfs =... | The main task of the code is to organize PDF files into structured folders based on corresponding .bib files. It reads .bib files from a source folder, creates matching directories in a target folder, and copies associated PDFs into these directories, maintaining filename consistency. The function ensures each .bib fil... | def sort_pdfs(bibfolder,pdffolder,sortedfolder):
bibs = Path(bibfolder)
pdfs = Path(pdffolder)
sorts = Path(sortedfolder)
bibs = [x for x in bibs.glob('./**/*.bib')]
pdfs = [x for x in pdfs.glob('*.pdf')]
for b in bibs:
target_folder = Path(sorts,*b.stem.split('-'))
if ... |
def delete_queries(client: Client, tags=[]):
print(f"cleaning up queries with tags in {tags}...")
for d in get_all_queries(client, tags):
print(f"deleting query {d['id']} - {d['name']}")
requests.delete(client.url+"/api/2.0/preview/sql/queries/"+d["id"], headers = client.headers).json()
def dele... | The code deletes existing dashboards and queries in a target environment tagged with specified tags, then clones dashboards from a source environment with the same tags. It manages a state file to track cloning progress between source and target URLs, ensuring consistent updates and avoiding redundant operations. The p... | def delete_and_clone_dashboards_with_tags(source_client: Client, target_client: Client, tags: List):
assert len(tags) > 0
#Cleanup all existing ressources.
delete_queries(target_client, tags)
delete_dashboard(target_client, tags)
print(f"fetching existing dashboard with tags in {tags}...")
dash... |
def generate_script_modal(id, name, script, description):
html = f"""
<div class="modal fade" id="{id}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="... | The main task of the code is to generate a structured HTML page with collapsible sections and modals, organizing demo content and resources from a JSON configuration file. It iterates through categories, domains, demos, and flows to create a hierarchical UI with buttons, expandable content, and resource links, using a ... | def generate_vertical():
with open("configuration.json", 'r') as file:
data = json.loads(file.read())
html = """<div class="container">"""
i = j = k = l = 0
for category in data:
i+=1
html += f"""<h2>{category}</h2><div class="row">"""
for domain i... |
def getClusterInfo(c: Union[KmeansGroup, DepotInfo]):
if isinstance(c, KmeansGroup):
return c.getCentroid(), c.getAllNodes()
if isinstance(c, DepotInfo):
return c.getLocation(), [c]
def calBearing(a: list, b: list):
lat1, lng1 = a[0], a[1]
lat2, lng2 = b[0], b[1]
dlng = lng2 - lng1
rlat1, rlat2, rdlng... | This function calculates the minimum distance between suitable nodes of two clusters (c1 and c2) by first determining their centroids, computing directional bearings between centroids, filtering nodes aligned with these bearings, and then finding the closest pair of nodes from the filtered sets. | def getClusterDis(c1: Union[KmeansGroup, DepotInfo], c2: Union[KmeansGroup, DepotInfo]):
# cent1, cent2 = c1.getCentroid(), c2.getCentroid()
# cNodes1, cNodes2 = c1.getAllNodes(), c2.getAllNodes()
cent1, cNodes1 = getClusterInfo(c1)
cent2, cNodes2 = getClusterInfo(c2)
ccBearing1, ccBearing2 = calBearing(cent1... |
def getClusterInfo(c: Union[KmeansGroup, DepotInfo]):
if isinstance(c, KmeansGroup):
return c.getCentroid(), c.getAllNodes()
if isinstance(c, DepotInfo):
return c.getLocation(), [c]
def calBearing(a: list, b: list):
lat1, lng1 = a[0], a[1]
lat2, lng2 = b[0], b[1]
dlng = lng2 - lng1
rlat1, rlat2, rdlng = math.... | This function calculates the minimum distance between two clusters (c1 and c2) by first determining their centroids and suitable nodes based on directional bearings between centroids. It then computes the shortest distance between these filtered nodes of the two clusters, likely for clustering or routing optimization t... | def getClusterDis(c1: Union[KmeansGroup, DepotInfo], c2: Union[KmeansGroup, DepotInfo]):
# cent1, cent2 = c1.getCentroid(), c2.getCentroid()
# cNodes1, cNodes2 = c1.getAllNodes(), c2.getAllNodes()
cent1, cNodes1 = getClusterInfo(c1)
cent2, cNodes2 = getClusterInfo(c2)
ccBearing1, ccBearing2 = calBearing(cent1, cen... |
def display_welcome(self):
welcome = '''
Welcome to Battleship!
----------------------
In this game you will be placing your ships on your board trying to avoid them all being sunk. Then players
will ... | The code's main task is to run a game loop that repeatedly initializes, plays, and displays results of a game until the user chooses to stop. It uses a while loop to handle multiple game sessions, calling methods to display the welcome message, set up players, execute the game logic, and show the winner. The loop conti... | def run_game(self):
play_again = True
while play_again:
self.display_welcome()
self.setup_players()
self.game_loop()
self.display_winner()
play_again = gtool.validate_Y_N('Would you like to play again: ') |
def enum_name(self, path: str) -> str:
return path.replace('.', '_').upper()
def enum_value(self, path: str, value: str) -> str:
return self.enum_name(path + '_' + value)
def enum_count(self, path: str) -> str:
return self.enum_value(path, '_COUNT') | This code generates C-style enum definitions and typedefs from a structured data model, recursively processing nested enums and array items. It constructs enum names, assigns values based on indices, includes a count member, and aggregates results from child elements and array types. | def gen_c_enums(self, path: str = '') -> str:
if self.name:
cpath = (path + '.' + self.name) if path else self.name
else:
cpath = path
s = ''
if self.type == 'enum':
s += f'enum {self.enum_name(cpath)}_ {{\n'
for i, v in enumerate(self.valu... |
def yesNo(text):
while True:
choice = input(text)
print()
if (choice.lower() == "y" or choice.lower() == "yes"):
return True
elif (choice.lower() == "n" or choice.lower() == "no"):
return False
print("Please type in (Y / N) or (Yes / No)\n")
def reviewMessages(usedNumbersList, allNumbersList, mess... | The code processes a list of numbers by tracking used numbers from a file, interacts with a Discord channel to send and monitor messages, and manages counting progress. It handles user input, updates the used numbers list, checks for specific message conditions, and triggers notifications or actions based on status, su... | def processCount(allNumbers):
success = False
usedNumbers = []
dummyNumber = None
with open(os.path.dirname(__file__) + f"\\{textFileName}") as readFile: numbers = readFile.read()
usedNumbers = [int(number) for number in (numbers.strip("[]")).split(', ') if number.isdigit()]
if usedNumbers:
if yesNo("Do yo... |
def newGame():
global ball,playerPaddle,enemyPaddle,score
ball = [64,32,3,randSpeed(1,4,1),randSpeed(2,3,1)]
playerPaddle = [125,22,3,20,2]
enemyPaddle = [0,22,3,20,1.5]
oled.hctext('ENEMY PLAYER',25,1)
oled.hctext('%d %d'%(score[1],score[0]),35,1)
oled.hctext('[A] to Play',56,1)
oled.show()
while btn.A.va... | This code initializes and runs a Pong-like game loop, handling player input, enemy AI movement, ball physics, collision detection, scoring, and screen updates. It clears the display, updates paddle positions, moves the ball, checks for wall/paddle collisions, updates scores when the ball goes out of bounds, and redraws... | def app_start():
oled.fill(0)
global ball,playerPaddle,enemyPaddle,score
newGame()
while btn.B.value():
if btn.U.value() == 0: playerPaddle[1]-=playerPaddle[4]
if btn.D.value() == 0: playerPaddle[1]+=playerPaddle[4]
enemyMiddle = enemyPaddle[1] + enemyPaddle[3]/2
if abs(ball[1] - enemyMiddle) > 2: enemyPad... |
def AL_old_data(self, model, train_data, train_label,str_name, C, k_, rtrain_size = 1, stand = 0):
train_label = torch.tensor(train_label)
if stand == 0:
temp = np.zeros([train_data.shape[0],1])
with torch.no_grad():
pred = model(torch.tensor(train_data).to(torch.... | The code trains a GAN (Generator-Discriminator) model with active learning (AL) for multiple iterations (k-fold). It loads training/test data, initializes G/D networks, trains them using Adam optimizers, computes generator/discriminator losses with a teacher model, and evaluates performance on test data. Results, inclu... | def itrain_model_d2(self, k=5, batch_size = 88, rtrain_size = 0.5,epochs = 300, lr_G = 0.0001, lr_D = 0.0005, lr_T = 0.001, lamb = 1,
save_model = True, C = 10):
for kk in range(k):
if self.number ==0:
self.train_data = np.load(self.datasrc + 'train_data.npy')... |
def convertToGrayScale(img_array):
img_width =len(img_array[0])
img_height = len(img_array)
out = numpy.empty([img_height, img_width])
for i in range(0, img_height):
for j in range(0, img_width):
out[i][j] = rgb_to_grayscale(img_array[i][j])
return out
def bilinearInterpolation(i... | The main task of the code is to process an image through a series of transformations: converting it to grayscale, resizing it using bilinear interpolation, normalizing pixel values, applying mean and median filters for noise reduction, and detecting edges via the Canny algorithm. Each processed image is saved at each s... | def main_170620P():
img = cv2.imread('/dashcam_view_1.jpg')
img_gray = convertToGrayScale(img)
cv2.imwrite('image_gray.png', img_gray)
new_width = int(img.shape[1] * 0.80)
new_height = int (img.shape[0] * 0.8)
img_scaled =bilinearInterpolation(img_gray, new_height, new_width)
cv2.imwrite('image_scale.p... |
def __read_section(self,section="record"):
'''
Reads the section of a Orcid member Profile
return : a dictionary of summary view of the section of ORCID data
'''
access_token = self._orcid_access_token
# Set the headers with the access token for authentication... | This function extracts and structures funding activity details from ORCID data. It reads 'fundings' section data, processes each funding summary to extract title, type, dates, organization info, and URL, formats dates, and compiles structured dictionaries. Returns a tuple containing the list of funding details and the ... | def fundings(self):
'''
Summary of funding activities
return : a tuple containing the Funding details and the whole info tree related to funding from orcid
'''
funding_details = []
data = self.__read_section("fundings")
group = data.get('group', [])
fo... |
def __read_section(self,section="record"):
'''
Reads the section of a Orcid member Profile
return : a dictionary of summary view of the section of ORCID data
'''
access_token = self._orcid_access_token
# Set the headers with the access token for authentication... | This function extracts work-related details from ORCID data, including title, type, publication date, journal title, organization info, and URL. It processes nested JSON structures, formats dates, and compiles results into a list of dictionaries. The output is a tuple containing the structured work details and the orig... | def works(self):
'''
Summary of research works
return : a tuple containing the Work details and the whole info tree related to work from orcid
'''
data = self.__read_section("works")
work_details = []
group = data.get('group', [])
for work_summary in ... |
def __get_value_from_keys(self, json_obj, keys):
"""
Get the value associated with the last key in the list if all keys are accessible cumulatively.
Args:
json_obj (dict): The JSON-like object (dictionary).
keys (list): List of keys to check for accessibility and retrieve the fi... | The function extracts structured details like department, role, dates, organization, and URL from nested data based on a given key, formatting dates and addresses, then returns a list of dictionaries containing these extracted records. | def __extract_details(self, data, key):
'''
Helper function for record_summary()
'''
details = []
# Extract the 'affiliation-group' from the data
affiliation_group = data.get('affiliation-group', [])
for group in affiliation_group:
su... |
def _distance(self, fs:torch.tensor, gs:torch.tensor) -> torch.tensor:
""" Computes the distance between fs and gs according to the chosen inner product.
Args:
fs: torch.tensor: The first set of function outputs. Shape can vary, but typically (n_functions, n_datapoints, input_size)
gs: ... | The code trains a function encoder using a dataset over specified epochs, employing either inner product or least squares methods. It computes prediction losses, applies regularization for least squares, and optionally trains an average function. Gradient clipping is used during backpropagation, with callbacks for prog... | def train_model(self,
dataset: BaseDataset,
epochs: int,
progress_bar=True,
callback:BaseCallback=None):
""" Trains the function encoder on the dataset for some number of epochs.
Args:
dataset: BaseDataset: ... |
def correct_rotation(im1, im2, scaling_factor=4, gpu_device=0):
print("Resizing image 1 for rotation check.")
# im1_small=resize(im1, (im1.shape[0] // scaling_factor, im1.shape[1] // scaling_factor),
# anti_aliasing=True)*255.
im1_small=cv2.resize(im1,(int(im1.shape[1] // scaling_factor), int(im1.shape[0] //... | The code registers two images by aligning their tissue sections through segmentation, property matching, and affine transformations. It loads images, segments objects, extracts features (e.g., area, orientation), matches sections between images, applies rotation/alignment, and saves registered outputs. The process uses... | def register_images_(im1_fname='A.npy',
im2_fname='B.npy',
connectivity=8,
apply_watershed=False,
overwrite=False,
min_object_size=50000,
clip=True,
fix_rotation=True,
mult_factor=2.0,
scaling_factor=4.,
output_dir='practice_reg_results/images',
properti... |
def search(root, coords):
res_list = []
depth = 0
while root:
dimension = depth % DIMENSIONS # dimension = 0 or 1
if coords[dimension] < root.coords[dimension]:
root = root.left
elif coords[dimension] > root.coords[dimension]:
root = root.right
else:... | The code updates a tree structure by replacing nodes with specific coordinates (`coords`) with new nodes having updated coordinates (`new_coords`). It searches for matching nodes, creates new nodes with the same data, deletes the old nodes, and inserts the new ones, returning the modified tree. | def update(root, coords, new_coords):
to_change_nodes = search(root, coords)
if len(to_change_nodes) == 0:
print("Node NOT Found!")
return root
new_nodes = []
for node in to_change_nodes: # create new nodes
new_nodes.append(Node(new_coords, node.data))
for node in to_change_nodes: # delete old nodes
root ... |
def get_possible_moves(self):
# generate a list of all possible moves
moves=[]
for row in range(BOARD_DIM):
for col in range(BOARD_DIM):
cur_piece=self.board[row, col]
if cur_piece==None: continue
else: moves.extend(cur_piece.get_moves(... | The code filters valid moves by removing those that leave the player in check, using temporary moves and undoing them to assess the resulting state. It also identifies checkmate or stalemate if no valid moves remain. | def get_valid_moves(self):
# moves which end in a checkmate are not allowed and get filtered here
# no need for deep copy since undo_move() can be used instead
moves=self.get_possible_moves()
for i in range(len(moves)-1, -1, -1):
# active player makes move
... |
def content_choose1(list_mail, list_file, subject_mail, content_mail) :
print("Day la thong tin soan email: (neu khong dien vui long nhan enter de bo qua)")
# nhap thong in to,cc,bcc
list_mail["to"] = input("To: ").replace(","," ").split()
list_mail["cc"] = input("CC: ").replace(","," ").split()
... | The code defines a menu-driven interface for an email application, allowing users to send emails, view received emails, switch accounts, or exit. It recursively calls itself to maintain the loop, handling user input by invoking specific functions for each option, including sending emails via `mailsmtp.client_mail` and ... | def MENU() :
print("\r\nVui long chon: ")
print("1. De gui email")
print("2. De xem danh sach cac email da nhan")
print("3. Dang nhap vao tai khoan khac")
print("4. Thoat")
choose = input("Ban chon: ")
if (choose == "4"): return
if (choose == "1"):
list_mail = {"to": [], "cc": [... |
def write_report(report):
with open('/dev/hidg0', 'rb+') as fd:
fd.write(report.encode())
def wait_then_release_keys():
time.sleep(0.1)
write_report(NULL_CHAR*8)
def type_out(str_to_type):
for char in str_to_type:
time.sleep(0.1)
# press letter's key
write_report(NULL_CHAR*2+chr(ord(char)-93)+NULL_... | This code automates launching a Windows program via the Start menu by simulating keyboard inputs: it closes any open menus, opens the Start menu, types a search string, and presses Enter to select the program. | def open_from_windows_menu(search_str):
# press esc key in case windows menu is already open
write_report(NULL_CHAR*2+chr(41)+NULL_CHAR*5)
wait_then_release_keys()
# press windows key
write_report(chr(8)+NULL_CHAR*7)
wait_then_release_keys()
time.sleep(1)
# type out name of program
type_out(search_str)
# pres... |
def train():
"""**Instructions**
1. Use load_images_from_folder() for reading images from the stored /train folders.
2. Create class labels (0: Non-Satellite, 1: Satellite class) using functions np.zeros() and np.ones() and np.append().
"""
# Use load_images_from_folder() to read all the stored trai... | The main task of the code is to train a model by obtaining weights and bias using the `train()` function, then evaluate its performance on the full testing dataset by loading test data with `load_test_data()` and passing the trained parameters to the `test()` function for assessment. | def train_and_test_model():
weights, bias = train()
# test on the full testing dataset
test_images_flatten, cls_test = load_test_data()
test(weights, bias, test_images_flatten, cls_test) |
def load_image(filename):
img = PIL.Image.open(filename)
# Convert to RGB to remove Alpha channel
img = img.convert("RGB")
# Resize and convert to Numpy array
img = np.array(img.resize((width, height)))
return img
def normalize_data(flattened_images):
# Explicitly cast as Float64
flatten... | The function loads pre-trained model parameters (bias and weights), processes a test image by normalizing and flattening it, then uses these parameters to test the model's prediction on the input image, printing progress and completion status. | def load_and_test_model(testfile):
print("\nTesting: {}...".format(testfile))
bias = np.loadtxt("learned_bias.txt")
weights = np.loadtxt("learned_weights.txt")
# print("Loaded bias:\n{}\n".format(bias))
# print("Loaded weights:\n{}\n".format(weights))
print("Loaded bias and weights.")
test_p... |
def init_data():
#Get file paths
rootDir = Path(sys.path[0]).parent
train_images = str(rootDir) + "\\MNIST data\\train-images.idx3-ubyte"
train_label = str(rootDir) + "\\MNIST data\\train-labels.idx1-ubyte"
test_images = str(rootDir) + "\\MNIST data\\t10k-images.idx3-ubyte"
test_label = str(root... | The code trains a neural network using mini-batch stochastic gradient descent with momentum. It initializes weights, processes data in batches, performs forward and backward passes, updates weights via velocities, applies learning rate decay, and tracks training/test accuracy per epoch. The function returns training du... | def train():
#Get opts, data, weights, velocities
linalg.init()
X, y = init_data()
arch = ((opts.n_x, opts.n_h), (opts.n_h, opts.n_h2), (opts.n_h2, opts.n_o))
weights = init_weights(arch)
velocities = init_velocities(arch)
opts.alpha = 0.002
epoch_accuracies = []
start_time = ti... |
def computeReward(startState: GameState,
endState: GameState) -> float:
"""
Args:
startState: A starting state
endState: A resulting state
Returns:
The reward assigned for the given trajectory
"""
"*** YOUR CODE HERE ***"... | The code implements a reinforcement learning agent that selects actions to maximize reward while balancing exploration and exploitation. It updates Q-values using the previous state-action pair and current state, applies an exploration function to Q-values and action counts, and chooses the action with the highest util... | def getAction(self, state: GameState) -> Directions:
"""
Choose an action to take to maximise reward while
balancing gathering data for learning
If you wish to use epsilon-greedy exploration, implement it in this method.
HINT: look at pacman_utils.util.flipCoin
Args:
... |
def getEpisodesSoFar(self):
return self.episodesSoFar
def incrementEpisodesSoFar(self):
self.episodesSoFar += 1
def getNumTraining(self):
return self.numTraining
def setAlpha(self, value: float):
self.alpha = value
def setEpsilon(self, value: float):
self.epsilon = value
def comp... | This method handles the end of a game episode by updating episode counters, adjusting learning parameters (epsilon and alpha) after training completion, calculating rewards, and performing learning updates using the previous state, action, and current state features. | def final(self, state: GameState):
"""
Handle the end of episodes.
This is called by the game after a win or a loss.
Args:
state: the final game state
"""
print(f"Game {self.getEpisodesSoFar()} just ended!")
# Keep track of the number of gam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.