dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_socket():
try:
global SERVER_HOST
global SERVER_PORT
global server
server_name = socket.gethostname()
SERVER_HOST = socket.gethostbyname(server_name)
SERVER_PORT = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.er... | The code defines a worker function `work()` that continuously processes tasks from a queue. If the task is 1, it creates, binds, and accepts a socket. If the task is 2, it starts a shell if connections exist. The function handles network operations and command execution based on queued instructions, ensuring each task ... | def work():
while True:
x = queue.get()
if x == 1:
create_socket()
bind_socket()
accept_socket()
if x == 2:
if all_connections is not None:
start_shell()
queue.task_done() |
def build_differencing_chart(df, target, results):
df.index = df.index.astype("str")
fig = make_subplots(rows=3, cols=1)
fig.append_trace(
go.Scatter(x=df["Year"], y=df[target], marker=dict(color="black", size=3)),
row=1,
col=1,
)
fig.append_trace(
go.Scatter(x=df... | The function generates two visualizations: a differencing chart for the time series and ARIMA prediction plots. It handles errors by returning blank figures if either plot fails, ensuring the program continues without crashing. The first figure visualizes the differenced data, while the second displays forecasted value... | def arima_visual_controller(df, target, params, differenced, results):
try:
fig = build_differencing_chart(differenced, target, results)
except Exception as E:
print("Differencing Error: ", E)
fig = blank()
try:
fig2 = plot_arima_predictions(df, target, params[0])
excep... |
def executeEpisode(self, board):
"""
Returns:
trainExamples: a list of examples of the form (canonicalBoard, currPlayer, pi,v)
pi is the MCTS informed policy vector, v is +1 if
the player eventually won the game, else -1.
"""
... | The code performs iterative self-play training for a neural network. It runs multiple iterations, each with self-play episodes to collect training examples. After each iteration, it trains the neural network on accumulated examples, then evaluates the new model against the old one. If the new model meets a performance ... | def learn(self):
"""
Performs numIters iterations with numEps episodes of self-play in each
iteration. After every iteration, it retrains neural network with
examples in trainExamples (which has a maximum length of maxlenofQueue).
It then pits the new neural network against the o... |
def get_parser():
parser = ArgumentParser(
description='Load data into the Rangespan catalog')
parser.add_argument('-v', '--version',
action='store_true',
help='Show version number and exit.'
)
parser.add_argument(
'sourcefile',
nargs='?',
type=FileType('r... | The main task of the code is to parse command-line arguments, check for a version flag to print the version and exit, and either launch an interactive REPL if input is from a terminal or evaluate a script file's content. It handles input sources via stdin or a specified file, using `repl()` for interactive mode or `eva... | def main(argv):
parser = get_parser()
args = parser.parse_args()
if args.version:
print('v%s' % (VERSION,))
sys.exit(0)
if sys.stdin.isatty() and args.sourcefile == sys.stdin:
repl()
else:
eval_string(args.sourcefile.read()) |
def return_poss_for_element(problem, x, y, characters, block_size):
row = problem[x]
possible_in_row = check_row(row, characters)
possible_in_col = check_column(problem[:, y], characters)
block_row_edge, block_col_edge = decide_block(x, y, block_size)
block = problem[block_row_edge - block_size: block_row_edge, bl... | The code solves a Sudoku-like puzzle by identifying cells where a value can only be placed in one location (naked singles) or cannot fit elsewhere in the row, column, or block. It iterates through empty cells, checks possible values, and fills them if they are uniquely constrained. The function updates the grid and cou... | def solve(problem, characters, block_size):
counter = 0
for x, row in enumerate(problem):
for y, element in enumerate(row):
if element == ' ':
possible_values = return_poss_for_element(problem, x, y, characters, block_size)
# print(possible_values)
# now run through all possible values
# if for a... |
def filter_duplicate_lines(lines, orientation, delta_rho=10, delta_theta=np.pi/90, tolerance=6):
filtered_lines = []
for line in lines:
x1, y1, x2, y2 = line[0]
duplicate_found = False
for fl in filtered_lines:
x1_fl, y1_fl, x2_fl, y2_fl = fl[0]
# Calculate rho and theta for the current line
rho = n... | The code's main task is to solve a Sudoku puzzle from an uploaded image. It processes the image to detect grid lines, extracts individual cells, performs OCR to identify numbers, and then solves the Sudoku using an algorithm. The function reads the latest image file from a directory, detects the Sudoku grid structure, ... | def solve_sudoku_upload():
t1 = time.time()
# Specify the directory
directory = 'uploads'
# Get a list of all the files in the directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
# Check if there are any files in the directory
if files:
# Get the most recently ... |
def activate_log(log_lvl='DEBUG', logfile=LOG_FILE, logoff=False):
"""
control the logger properties.
"""
logger.setLevel(LOG_LVL[log_lvl])
if logfile:
# Create handlers
f_handler = logging.FileHandler(logfile, 'w')
f_handler.setLevel(LOG_LVL['DEBUG'])
# Create forma... | This program scrapes smartphone data from http://www.gsmarena.com based on user-selected brands (Apple, Samsung, or both). It validates input, retrieves device specifications using a scraper function, and saves results to JSON files. Data is stored separately for Apple and Samsung when both are chosen, ensuring structu... | def main():
print("This program scrape http://www.gsmarena.com for smartphones properties")
activate_log()
answer = input("Please, choose the Brand:\n1.Apple\n2.Samsung\n3.Apple and Samsung\n>>> ")
while not (answer.strip() in ['1', '2', '3']):
answer = input("Please, choose the Brand:\n1.Apple\... |
def run_agent(self, name):
"""Invoke an agent against the population"""
op, k = self.agents[name]
picks = self.get_random_solutions(k)
new_solution = op(picks)
self.add_solution(new_solution)
def remove_dominated(self):
"""Remove dominated solutions from the population"""... | The main task of the code is to evolve a population by iteratively running random agents, removing dominated solutions at intervals, tracking progress, and syncing with saved solutions, while adhering to time limits and population size constraints to optimize solutions. | def evolve(self, n=1, dom=100, status=10000, sync=1000, time_lim=600.0):
"""Run n random agents against the population to get optimal solutions"""
# Get the names of all agents and set a timer
agent_names = list(self.agents.keys())
start = time.time()
# Run agents against the po... |
def calc_gradient(image, gradientImageName):
sobel_x = cv.Sobel(image, cv.CV_64F, 1, 0, ksize=3)
sobel_x = np.max(sobel_x, axis=2)
sobel_y = cv.Sobel(image, cv.CV_64F, 0, 1, ksize=3)
sobel_y = np.max(sobel_y, axis=2)
gradient_image = sobel_x ** 2 + sobel_y ** 2
gradient_image = np.sqrt(gradient_... | The code computes the structure tensor of an image to detect interest points. It calculates gradients, applies Gaussian blur, computes determinant and trace of the tensor, thresholds the response, performs non-maximum suppression, and visualizes detected points. The main task is feature detection using tensor analysis ... | def calc_tensor_structure(image, kernelSize, kernelSigma, k, threshold, gradientImageName, scoreImageName,
scoreThreshImage, resultName):
i_x, i_y, _ = calc_gradient(image, gradientImageName)
i_x2 = i_x * i_x
i_y2 = i_y * i_y
i_xy = i_x * i_y
s_x2 = cv.GaussianBlur(i_x2, (k... |
def init_nonl_term(self):
self.nonl = np.empty(self.shape, dtype = 'complex128')
self.get_nonl_vec_product()
self.get_nonl_k = np.vectorize(self.get_one_node_nonl)
def init_jac(self):
case_dic = {'l': self.init_jac_1,
'n': self.init_jac_2,
'ln'... | This code initializes a simulation setup by loading parameters from a data file, configuring nonlinear and linear terms with complex arrays, setting coefficient arrays for calculations, determining operational flags (linear, nonlinear, dissipation), constructing a case identifier string, and initializing the Jacobian a... | def __init__(self, data_file):
super().__init__(data_file)
self.data = data_file
#self.a
#self.f
#with open(data_file) as file_object:
# self.data = json.load(file_object)
self.nonlinear_term = np.zeros(self.shape,dtype = np.complex128)
self.linear_term... |
def forcing(self):
self.force_ar = np.zeros(self.shape,dtype = np.complex128)
self.force_ar[0:11,0:2,:] = 0.01*((0.5-np.random.random((11,2,2,2)))+1.j*(0.5-np.random.random((11,2,2,2))))
return self.force_ar
def get_full_nonlinear_term(self,g,chiPhiB,chiA,chi1):
nonl_term_full = np.zeros... | This function computes a combined linear and nonlinear term for a system, involving calculations of coefficients (phi, A, B), chi parameters, and a variable h. It returns the sum of forcing terms, nonlinear contributions, linear terms, and adjustments using dispersion coefficients, along with the Jacobian matrix for sy... | def func_lin_nonl_dis(self,y):
phi = self.getPhi(y)
A = self.getA(y)
B = self.getB(y)
chiPhiB,chiA,chi1 = self.getChi(phi,A,B)
h = self.getH(y,chiPhiB,chiA,chi1)
jac = self.update_jac(y,chiPhiB,chiA,chi1)
return self.forcing()+self.get_full_nonlinear_term(y,chiPhi... |
def init_nonl_term(self):
self.nonl = np.empty(self.shape, dtype = 'complex128')
self.get_nonl_vec_product()
self.get_nonl_k = np.vectorize(self.get_one_node_nonl)
def init_jac(self):
if self.LINEAR:
self.__linear_jac_blocks()
self.__linear_jac_chi()
i... | This code initializes a simulation object by loading parameters from a data file, setting up complex-valued arrays for linear and nonlinear terms, computing coefficient arrays for calculations, and initializing Jacobian and RHS components based on simulation flags (linear, nonlinear, dissipation). It prepares numerical... | def __init__(self, data_file):
super().__init__(data_file)
#with open(data_file) as file_object:
# self.data = json.load(file_object)
self.data = data_file
self.nonlinear_term = np.zeros(self.shape,dtype = np.complex128)
self.linear_term = np.zeros(self.shape, dtype = ... |
def step(self, action):
for i in range(self.height):
if self.board[i][action] == 0:
self.board[i][action] = self.player
break
# else:
# raise RuntimeError('BAD')
self.has_winner = have_winner(self.board, self.player)
if self.has_wi... | The code resets the game environment by initializing an empty board, setting the starting player, and executing a specified number of random legal moves to generate an initial state. It returns the resulting observation for the new episode. | def reset(self, num_pre_moves=0):
self.board = np.zeros((self.height, self.width), dtype="int32")
self.player = 1
for _ in range(num_pre_moves):
self.step(np.random.choice(self.legal_actions()))
return self.get_observation() |
def one():
nonlocal cur
cur += 1
return s.read(bool)
def rub():
z = 0
while not one():
z += 1
if 0 == z:
return 0
below = z - 1
lbits = bits(below)
bex = 1 << below
return bits(bex ^ lbits) | The function `r` recursively constructs a data structure (likely a tree or linked list) by either retrieving a precomputed value from `refs` or combining results of recursive calls to itself. It uses conditions based on `one()` and `rub()` to determine whether to store a reference or build a `Cell` object with two chil... | def r(start: int):
ret = None
if one():
if one():
ret = refs[rub()]
else:
hed = r(cur)
tal = r(cur)
ret = Cell(hed, tal)
else:
ret = rub()
refs[start] = ret
return ret |
def render(self , htmlFile , **params):
page = JINJA_ENV.get_template(htmlFile+'.html')
self.write(page.render(params))
def is_valid_pw(name, pw, h):
salt = h.split(',')[1]
if make_pw_hash(name, pw, salt) == h:
return True
else:
return False
def set_cookie(self, name, value, path='/'):
hashed_cookie = make... | This code handles user login by verifying credentials against a database. It checks if the username exists, validates the password, and sets a session cookie upon successful authentication, redirecting to the homepage. If invalid, it displays appropriate error messages on the login page. | def login(self, username, password):
user = User.all().filter('username =', username).get()
if user == None:
error = 'The user doesn\'t exist'
self.render('login', error=error, username=username, password=password)
elif user.username == username and is_valid_pw(username, password, user.password):
self.se... |
def _reset(self):
"""
reset environment and reset the obtained return
"""
self.state = self.env.reset()
self.last_obtained_return = 0.0
def _play_step(self, eval=False):
"""
Play one step and return if episode ended
"""
action, state_action... | The main task of the code is to evaluate the agent's performance by running episodes in the environment without training, collecting metrics like average return and maximum predicted Q-values, logging results with a writer, and saving model snapshots. It pauses training, runs episodes until a frame limit, then computes... | def _evaluate(self, writer):
"""
Pause Training and evaluate agent by running environment like training,
but without actually training the model and decreased exploration.
"""
_eval_iteration_returns = []
_eval_iteration_max_q_vals = []
print("**********... |
def _reset(self):
"""
reset environment and reset the obtained return
"""
self.state = self.env.reset()
self.last_obtained_return = 0.0
def _play_step(self, eval=False):
"""
Play one step and return if episode ended
"""
action, state_action... | The code trains a reinforcement learning agent using a DQN-like approach. It initializes an optimizer, runs episodes in a loop, uses experience replay for learning, updates the policy network with gradient descent, periodically syncs the target network, tracks metrics like speed and memory usage, logs results to Tensor... | def train_agent(self):
"""
Train the Agent.
"""
writer = SummaryWriter(comment="_"+self.env_name)
optimizer = optim.Adam(self.policy_net.parameters(), lr=self.hp_learning_rate)
print ("Start Training on %s" % self.device)
episode = 0
while True:
... |
def get_new_corners(image: np.ndarray, H: np.ndarray) -> List[np.ndarray]:
"""
Get the new corners of an image after applying a homography.
Parameters
----------
image : np.ndarray
Original image.
H : np.ndarray
Homography matrix.
Returns
-------
corners : List[np.n... | The function calculates the new image size and offset matrix required to combine an input image with an existing panorama using a homography matrix. It computes transformed corners of the image and panorama, determines the bounding size to accommodate both, and adjusts coordinates to ensure positive alignment. The resu... | def get_new_parameters(
panorama: np.ndarray, image: np.ndarray, H: np.ndarray
) -> Tuple[Tuple[int, int], np.ndarray]:
"""
Get the new size of the image and the offset matrix.
Parameters
----------
panorama : np.ndarray
Current panorama.
image : np.ndarray
Image to add to t... |
def clear_db(c):
c.execute('DROP TABLE IF EXISTS USERS')
c.execute('DROP TABLE IF EXISTS POSTS')
c.execute('DROP TABLE IF EXISTS COMMENTS')
def create_tables(c):
c.execute('CREATE TABLE USERS(\
id INTEGER PRIMARY KEY,\
username text,\
name text,\
password text,\
e... | The code generates a SQLite database named 'test.sqlite3' by connecting to it, clearing existing data, creating tables, inserting an anonymous user, generating additional users, and creating 200 test posts. It then commits changes and closes the connection to finalize the database setup. | def gen_db():
# connect
conn = sqlite3.connect(os.path.join('test.sqlite3'))
c = conn.cursor()
clear_db(c)
create_tables(c)
# Create anon user
c.execute('INSERT INTO USERS VALUES(1,"Anon","Anon","password","xvgwm@example.com","","",0)')
# create rest
users = gen_users(c)
gen_p... |
def compile_program(client, source_code):
compile_response = client.compile(source_code.decode('utf-8'))
return base64.b64decode(compile_response['result'])
def create_app(client, private_key,
approval_program, clear_program,
global_schema, local_schema):
print("Creating new... | The main task of the code is to deploy a smart contract application on a blockchain, storing license details in global state if account balance is sufficient and the app count is under 10. It compiles smart contract programs, deploys them, adds license data, and returns the app ID. If conditions fail, it returns None w... | def smart_crt(license_id, license_detail):
if account_bal > 0 and app_count < 10:
print("Account balance: ", account_bal)
print("Number of created global apps: ", app_count)
# Read the smart contract source files
smart_contract_file = open(sm_contract_file, "rb")
smart_contr... |
def _render_for_human(self):
if self.render_mode == "human":
self._render_frame()
def play_action(self, action):
if not self.is_action_valid(action):
if self.render_mode == "human":
print("action_invalid played!")
self.invalid_move_has_been_played = Tr... | This method resets the game environment by initializing the board, managing player turns, handling opponent moves, and rendering the state. It sets up a new game state with a random or specified starting player, processes initial opponent actions if applicable, and returns the board and empty options dictionary. | def reset(self, seed=None, options=None):
super().reset(seed=seed)
self.board = np.zeros((self.ROWS_COUNT, self.COLUMNS_COUNT), dtype=np.int8)
self.last_move_row = None
self.last_move_col = None
self.invalid_move_has_been_played = False
self._render_for_human()
... |
def play_action(self, action):
if not self.is_action_valid(action):
if self.render_mode == "human":
print("action_invalid played!")
self.invalid_move_has_been_played = True
return
for i in range(self.ROWS_COUNT - 1, -1, -1):
if se... | This function executes a game step by applying an action, checking if the game is finished, switching players, and rendering the state. If the game ends, it returns the board and result. If an opponent exists, it recursively processes the opponent's action, negating their result. Otherwise, it returns a neutral outcome... | def step(self, action, play_opponent=True):
action = action.item() if isinstance(action, np.ndarray) else action
self.play_action(action)
result, is_finish = self.is_finish()
self.switch_player()
self._render_for_human()
if is_finish and self.render_mode == "human":
... |
def create_window(window_name, title, size):
new_window = tk.Toplevel()
new_window.title(title)
new_window.geometry(size)
windows[window_name] = new_window # Store a reference to the new window
return new_window
def go_to_customer_window(current_window, parent_window):
current_window.destroy() ... | The code creates a GUI window to display package details from a database, including labels for each package's attributes and a "Book" button. It sets up a scrollable interface with a logout/home navigation bar, fetches data via SQL query, and dynamically generates UI elements for each package record, allowing users to ... | def fetch_package_details():
package_details_window = create_window("package_details_window", "Package Details", "600x600")
# Add a stylish heading
heading_label = tk.Label(package_details_window, text="Quick Cargo", font=("Helvetica", 20, "bold"))
heading_label.pack(pady=15)
# Create a frame for ... |
def _add_forward_graph(self, retraining=False):
"""NN architecture."""
mc = self.mc
print("mc.LOAD_PRETRAINED_MODEL is {}".format(mc.LOAD_PRETRAINED_MODEL))
# pre-define model
if mc.LOAD_PRETRAINED_MODEL:
assert tf.gfile.Exists(mc.PRETRAINED_MODEL_PATH), 'Cannot find pretrained model at the given path... | This code initializes a neural network model for image classification, setting up GPU device placement, input placeholders, data queues, and computational graph components. It configures parameters for training/evaluation, initializes counters for model size, FLOPs, and activations, and constructs forward propagation, ... | def __init__(self, mc, gpu_id=0, hashed=True, retraining=False):
#with tf.device('/cpu:0'):
with tf.device('/gpu:{}'.format(gpu_id)):
self.mc = mc
# a scalar tensor in range (0, 1]. Usually set to 0.5 in training phase and
# 1.0 in evaluation phase
self.keep_prob = 0.5 if mc.IS_TRAINING else 1.0
#--... |
def create_agent():
# Agent configuration and creation
agent_config_dict = {
'map_x': constant.AGENT_MAP_X,
'map_y': constant.AGENT_MAP_Y,
'direction': constant.AGENT_DEFAULT_DIRECTION
}
agent = Agent(agent_config_dict)
return agent
def create_labyrinth(agent):
# Labyrinth map creat... | The main task of the code is to implement a Q-learning algorithm for an agent to navigate a labyrinth environment using Pygame. It initializes game components, randomizes the agent's starting position, and runs a game loop that processes events, updates the agent's moves via Q-learning, renders the environment, and res... | def main():
# Create q-learning and other necessary objects for the window
agent = create_agent()
labyrinth = create_labyrinth(agent)
q_learning_solver = create_q_learning_solver(labyrinth)
screen = create_game_window()
monospace_font, fps_clock, game_step_timed_event = create_window_objects()
... |
def create_q_value_direction_dict(self, x, y):
q_value_direction_dict = {}
current_position_x = x
current_position_y = y
current_position = self.labyrinth.map_squares[current_position_y][current_position_x]
directions = ["left", "bottom", "right", "top", "my_type"]
for d... | The main task of the code is to determine the next move for an agent using a Q-learning approach. It evaluates possible directions (left, bottom, right, top) by calculating their Q-values, selects the direction with the highest Q-value (exploitation), or randomly explores if the Q-value is zero or based on an explorati... | def decide_next_move(self):
# key: directions ("left", "bottom", "right", "top")
# value: tuples with (next_move_position.id and q_matrix[(current_position.id ,next_move_position.id)])
q_value_direction_dict = self.create_q_value_direction_dict(self.labyrinth.agent.map_x, self.labyrinth.agent.ma... |
def draw(win, bar):
global reset
global name
global sorting
global project
win.fill(BLUE)
pygame.draw.rect(win, DARK_BLUE, (0, 0, 800, 180))
win.blit(project, (30, 20))
win.blit(name, (40, 90))
pygame.draw.rect(win, BLUE, (250, 15, 5, 150))
for i in range(len(sorting)):... | This code creates a Pygame-based visualization for sorting algorithms. It initializes a window, handles user input via keyboard keys (0-6) to trigger different sorting methods (shuffle, selection, bubble, merge, quick, heap, insertion sort), updates the bar representation of data, and renders the sorted state in real-t... | def main(win):
clock = pygame.time.Clock()
global RUN
global bar
global SORTED
while RUN:
clock.tick(FPS)
draw(win, bar)
for event in pygame.event.get():
if event.type == pygame.QUIT:
RUN = False
break
keys = pygame.key.g... |
def get_parser():
parser = argparse.ArgumentParser(
description="Retrieve a primer pairs metadata from UCSC and Ensembl"
)
parser.add_argument("-p", "--primers", nargs=2, type=str, help="primer pair")
parser.add_argument(
"-i", "--input", type=str, help="a tab delimited file containing p... | The main task of the code is to process command-line arguments for primer and genomic data analysis. It generates a header for output formatting and conditionally executes either parsing input data into structured output or printing metadata, depending on whether an input file is provided. The code handles primer seque... | def cli():
parser = get_parser()
args = vars(parser.parse_args())
header = "\t".join(
(
"Primer",
"F_Primer",
"R_Primer",
"Genome",
"Gene",
"Transcript",
"Exon",
"Intron",
"Product_Size",
... |
def check_float(potential_f):
try:
float(potential_f)
return True
except ValueError:
return False
def add_formatted_rows(data):
formatted_rows = [
(1, []),
(2, ["Assets"]),
(3, []),
(4, ["Bank"]),
(find_in_list_of_list(data, "Total Bank") + 1, ... | The code converts input data into an Excel file by first normalizing numerical values, formatting rows, creating a DataFrame with custom headers, and applying specific Excel formatting. It saves the output to a designated file path, ensuring structured data presentation in an Excel sheet. | def format_in_excel(data, headers):
file_name = str(Path.home() / "Downloads") + '/xero_balance_sheet.xlsx'
sheet_name1 = "Sheet1"
# Convert all numbers to float
for ele in range(len(data)):
for i in range(len(data[ele])):
data[ele][i] = float(data[ele][i]) if check_float(data[ele][... |
def detect(self, ignore=None, sort_key="color", check_last_xyz=None, frac=3/4):
"""!
@brief Detect the blocks
"""
# 1280x720
# ----------------- 6 := 1 + 2
# | 2 | 1 |
# ----------------- frac {3}{4}
# | 3 |ARM| 4 |
# -------------... | The main task of the code is to control a robotic arm to detect, pick up, and place blocks of different sizes (large and small) in specific positions. It adjusts placement coordinates iteratively and returns to a safe pose if picking fails. The task transitions to the idle state upon completion unless an emergency stop... | def task1(self):
self.current_state = "task1"
self.status_message = "Start task1!"
self.rxarm.go_to_safe_pose(moving_time=2,
accel_time=0.5,
blocking=True)
# if not self.calibrate():
# self.next_state = ... |
def detect(self, ignore=None, sort_key="color", check_last_xyz=None, frac=3/4):
"""!
@brief Detect the blocks
"""
# 1280x720
# ----------------- 6 := 1 + 2
# | 2 | 1 |
# ----------------- frac {3}{4}
# | 3 |ARM| 4 |
# -------------... | The code performs block sorting and stacking using a robotic arm. It detects blocks, differentiates between large/small sizes, picks them up, and places them in designated positions (stack_xyz or small_xyz) while adjusting coordinates to build towers. It loops until all blocks are processed, then returns to a safe pose... | def task2(self):
self.current_state = "task2"
self.status_message = "Start task2!"
self.rxarm.go_to_safe_pose(moving_time=2,
accel_time=0.5,
blocking=True)
# if not self.calibrate():
# self.next_state = ... |
def detect(self, ignore=None, sort_key="color", check_last_xyz=None, frac=3/4):
"""!
@brief Detect the blocks
"""
# 1280x720
# ----------------- 6 := 1 + 2
# | 2 | 1 |
# ----------------- frac {3}{4}
# | 3 |ARM| 4 |
# -------------... | The main task of the code is to control a robotic arm (rxarm) to detect, pick up, and place blocks of different sizes (large/small) and colors in designated positions. It processes blocks by distance first, adjusting placement coordinates iteratively, then by color, using specific placement logic (e.g., `auto_place`, `... | def task3(self):
self.current_state = "task3"
self.status_message = "Start task3!"
self.rxarm.go_to_safe_pose(moving_time=2,
accel_time=0.5,
blocking=True)
# if not self.calibrate():
# self.next_state = ... |
def detect(self, ignore=None, sort_key="color", check_last_xyz=None, frac=3/4):
"""!
@brief Detect the blocks
"""
# 1280x720
# ----------------- 6 := 1 + 2
# | 2 | 1 |
# ----------------- frac {3}{4}
# | 3 |ARM| 4 |
# -------------... | The main task of the code is to control a robotic arm to detect, pick up, and place blocks of different sizes (large/small) into designated positions (large_xyz/small_xyz) while dynamically adjusting target coordinates after each placement. The robot repeatedly detects blocks, performs picking/stable placement, updates... | def task4(self):
self.current_state = "task4"
self.status_message = "Start task4!"
self.rxarm.go_to_safe_pose(moving_time=2,
accel_time=0.5,
blocking=True)
# if not self.calibrate():
# self.next_state = ... |
def detect(self, ignore=None, sort_key="color", check_last_xyz=None, frac=3/4):
"""!
@brief Detect the blocks
"""
# 1280x720
# ----------------- 6 := 1 + 2
# | 2 | 1 |
# ----------------- frac {3}{4}
# | 3 |ARM| 4 |
# -------------... | The main task of the code is to stack detected blocks in a vertical line by repeatedly picking and placing them at incrementing heights, then relocating the entire stack to a new position using inverse kinematics. It involves detecting blocks, picking them with the robotic arm, placing them sequentially, adjusting posi... | def task5(self):
self.current_state = "task5"
self.status_message = "Start task5!"
self.rxarm.go_to_safe_pose(moving_time=2,
accel_time=0.5,
blocking=True)
self.detect(ignore=6, sort_key="distance", frac=4/5)
... |
def uninformed_search(starting, goal, dfs=None):
fringe = [starting]
already_visited = set()
while len(fringe) > 0:
if dfs:
vertex = fringe.pop()
current = vertex.current
else:
vertex = fringe.pop(0)
current = vertex.current
if current ... | The main task of the code is to evaluate and compare the performance of various search algorithms (BFS, DFS, Greedy, UCS, A*, Beam Search, Dijkstra, Bidirectional) in finding a path from a start to a goal node in a graph. It measures execution time, path cost, and nodes explored for each algorithm, constructs the found... | def test_random_search(start, goal):
print('Start:', start)
print('End:', goal)
starting_vertex = Vertex(None, start, 0)
goal_vertex = Vertex(None, goal, 0)
start_t = time.time()
end, length = uninformed_search(starting_vertex, goal)
end_t = time.time()
cost = end.cost
if end.curr... |
def load(image_file):
image = tf.io.read_file(image_file)
image = tf.image.decode_jpeg(image)
w = tf.shape(image)[1]
w = w // 2
real_image = image[:, :w, :]
input_image = image[:, w:, :]
input_image = tf.cast(input_image, tf.float32)
real_image = tf.cast(real_image, tf.float32)
... | The main task of the code is to load an image file, apply random jitter augmentation, normalize pixel values, and return two processed images (input_image and real_image) for training. This function prepares data for machine learning tasks like image generation or reconstruction by introducing variability and standardi... | def load_image_train(image_file):
input_image, real_image = load(image_file)
input_image, real_image = random_jitter(input_image, real_image)
input_image, real_image = normalize(input_image, real_image)
return input_image, real_image |
def load_images():
pieces = ['wp', 'wR', 'wN', 'wB', 'wK', 'wQ', 'bp', 'bR', 'bN', 'bB', 'bQ', 'bK']
# using python transform.scale to scale the dimensions of the imported images to the dimensions we want
for piece in pieces:
IMAGES[piece] = p.transform.scale(p.image.load("Chess/images/" + piece + "... | The code implements a chess game with a graphical interface using Pygame. It initializes the game window, handles user input for move selection, validates moves, animates them, and integrates AI opponents. The main loop processes events, updates game state, manages AI move calculations via threading, checks for game-en... | def main():
p.init()
screen = p.display.set_mode((BOARD_WIDTH + MOVE_LOG_PANEL_WIDTH, BOARD_HEIGHT))
clock = p.time.Clock()
screen.fill(p.Color("white"))
move_log_font = p.font.SysFont("Arial", 20, False, False)
game_state = engine.GameState()
valid_moves = game_state.get_valid_moves()
#... |
def square_under_attack(self, row, column):
# switch point of view to opponent view
self.white_to_move = not self.white_to_move
opponent_moves = self.get_all_possible_moves()
self.white_to_move = not self.white_to_move
for move in opponent_moves:
if move.end_row == ro... | The function generates valid castling moves for the king if the king is not in check and the corresponding castling rights (king-side or queen-side) are available, appending these moves to the provided 'moves' list. | def get_castle_moves(self, row, column, moves):
# cannot castle while king in check
if self.square_under_attack(row, column):
return
if (self.white_to_move and self.current_castling_rights.white_king_side) or \
(not self.white_to_move and self.current_castling_rights.... |
def check_for_pins_and_checks(self):
# squares where pinned pieces from same side are + the direction of the pin
pins = []
# squares from where enemy pieces are checking
checks = []
is_king_in_check = False
# start from the king for pins and checks
if self.white_... | This function generates valid chess moves by checking if the king is in check, filtering moves to avoid check, handling single/double checks, and adding castling moves when not in check. It also determines checkmate or stalemate if no valid moves exist. | def get_valid_moves(self):
moves = []
self.is_king_in_check, self.pins, self.checks = self.check_for_pins_and_checks()
if self.white_to_move:
king_row = self.white_king_location[0]
king_column = self.white_king_location[1]
else:
king_row = self.black_k... |
def calculateNumDays(preference):
start_date = preference.start_date
end_date = preference.end_date
diff = date(int(end_date.split('-')[0]), int(end_date.split('-')[1]), int(end_date.split('-')[2])) - date(int(start_date.split('-')[0]), int(start_date.split('-')[1]), int(start_date.split('-')[2]))
num_... | The main task of the code is to generate a list of recommended points of interest (POIs) for a user's trip based on their preferences. It starts by determining the origin city, calculates travel constraints (distance and duration), identifies nearby cities within a max distance, filters them according to trip days, and... | def calculateTrip(user, preference):
location = preference.origin_city
curr_city = Cities.query.filter_by(city_name=location)[0]
origin_airport = curr_city.airport_code
latitude = float(curr_city.city_latitude)
longitude = float(curr_city.city_longitude)
num_days = calculateNumDays(preference)... |
def set_random_seed(seed):
"""
This function controls the randomness by setting seed in all the libraries we will use.
"""
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(s... | The main task of the code is to initialize a W&B project for experiment tracking, configure a random seed, load training/validation/test datasets, prepare a model with optimizers/schedulers/loss function, and execute the training process for a specified number of epochs. | def main():
wandb.init(project="Fusion_Final", group="late_linear")
wandb.config.update(args)
if(args.seed == -1):
seed = random.randint(0, 9999)
print("seed",seed)
else:
seed = args.seed
wandb.config.update({"seed": seed}, allow_val_change=True)
set_r... |
def set_random_seed(seed):
"""
This function controls the randomness by setting seed in all the libraries we will use.
"""
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.enabled = False
torch.backends.cudnn.deterministic = True
random.seed(seed)
os.environ["PYTHONHASHSEED"]... | The main task of the code is to evaluate a pre-trained model on a test dataset using binary cross-entropy loss. It sets up data loaders, initializes the model, configures the loss function, and runs the test_score_model function to assess model performance on the test_data_loader. | def main():
set_random_seed(args.seed)
(
train_data_loader,
dev_data_loader,
test_data_loader,
) = set_up_data_loader()
model = get_model()
print("loaded")
loss_fct = BCEWithLogitsLoss()
test_score_model(model, test_data_loader, loss_fct) |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--output_dir', default='logs')
parser.add_argument('--spm_path', default='../spm_models/unigram_8k.model')
parser.add_argument('--rom_path', default='zork1.z5')
parser.add_argument('--env_step_limit', default=100, type=int)
... | The main task of the code is to train a DRRN agent in a ScienceWorld environment using multiple parallel environments. It initializes training and evaluation history buffers, executes training for a specified number of steps with periodic updates, checkpoints, and logging. The code measures training duration, steps per... | def main():
## assert jericho.__version__ == '2.1.0', "This code is designed to be run with Jericho version 2.1.0."
args = parse_args()
print(args)
configure_logger(args.output_dir)
agent = DRRN_Agent(args)
# Initialize a threaded wrapper for the ScienceWorld environment
envs = VecEnv(a... |
def _is_valid_clause(self, clause, level):
counter = 0
maxi = -1
cand = -1
for lit in clause:
var = self._get_literal_var(lit)
node = self._nodes_variable[var]
if node.level == level:
counter += 1
if node.index > maxi:... | The function analyzes a conflict in a SAT solver by resolving conflicting clauses through binary resolution, learning new clauses if applicable, and determining a backtrack level. It identifies the conflict node, processes the clause, updates data structures, and returns the backtrack level and an assigned node to reso... | def _analyze_conflict(self):
assigment_stack_pointer = len(self._stack_of_decision) - 1
conflict_node = self._stack_of_decision[assigment_stack_pointer]
conflict_level = conflict_node.level
conflict_clause = self._clauses[conflict_node.clause]
self._stack_of_decision.pop()
... |
def _read_file(self, cnf_filename):
cnf_file = open(cnf_filename, "r")
lines = [
line.strip().split() for line in cnf_file.readlines()
if (not (line.startswith('c') or
line.startswith('%') or
line.startswith('0'))
and line... | The code solves a Boolean Satisfiability Problem (SAT) using a backtracking algorithm with unit propagation and conflict analysis. It reads a CNF input file, tracks statistics, and determines if the formula is SAT or UNSAT. If SAT, it outputs the variable assignment to a file. The algorithm iteratively propagates const... | def solve(self, cnf_filename):
self.stats._input_file = cnf_filename
self.stats._start_time = time.time()
self._read_file(cnf_filename)
self.stats._read_time = time.time()
self.stats._num_vars = self._num_vars
self.stats._num_clauses = self._num_clauses
if self.s... |
def _get_unspent_owned_transaction(self) -> Optional[Transaction]:
"""
gets an available unspent transaction of this node
"""
owned_funds = self._get_my_unspent_transactions()
owned_funds_ids = [t.get_id() for t in owned_funds]
# frozen funds are inputs which are in the m... | The main task of the code is to generate a signed transaction that transfers funds by leveraging available unspent transactions. It first checks for unspent funds, returns `None` if none exist, otherwise creates and signs a new transaction using the unspent transaction's ID and the target public key. The transaction is... | def create_transaction(self, target_public_key: PublicKey) -> Optional[Transaction]:
"""
returns a signed transactions which moves funds
"""
unspent_transaction = self._get_unspent_owned_transaction()
# return None if no available funds
if not unspent_transaction:
... |
def _create_coinbase(self) -> Transaction:
"""
creates a coinbase transaction which grants money to this node,
which potentially mined a block
"""
random_bits = secrets.token_bytes(SIGNATURE_LEN)
coinbase = Transaction(
# this node will get this coin
... | The main task of the code is to generate a new block containing a specified number of coinbase transactions (for miner rewards) and mempool transactions, combine them into a block with the latest block's hash as its predecessor, update the blockchain state with this new block, and return the computed hash of the newly ... | def mine_block(self) -> BlockHash:
"""
creates a single block containing transactions from the mempool
and one additional coinbase(s), notifying all connections upon creation,
and returning the new block hash
"""
# create new coinbase txs which will be included as a fee t... |
def _get_blockchain_hashes(self) -> list[BlockHash]:
"""
returns the ordered list of the current state's blockchain hashes
"""
block_hashes = [b.get_hash() for b in self._state.blockchain]
return [GENESIS_BLOCK_PREV] + block_hashes
def _find_forking_point(
self,
... | This function handles the reception of a new block by a node, determining if it belongs to a longer valid chain. It identifies the fork point, validates the new branch, and if valid, reorganizes the blockchain state by updating the UTXO set and mempool. Conflicting transactions are removed, and the node adopts the new ... | def get_introduced_to_new_block(
self,
block_hash: BlockHash,
sender: Node
) -> None:
"""
handles the reception of new blocks by a node's connection,
requesting unknown blocks and processing received blocks for validity.
if the received block is on... |
def iter_leaves(n):
# return [a, [x, y], 1] where a is index of square, x,y are coordinates of left-upper corner
L = get_L(n)
all_squares = (4 * L * L - 1) // 3
for i in range(L * L):
yield [i + all_squares - L * L, [i % L, i // L], 1]
def iter_portal_usages(m, c):
# return list of (m*c) num... | The code computes the minimal length of a well-behaved tour through hierarchical squares using dynamic programming (DP). It initializes a DP table with states representing square indices and portal usage configurations. The base case calculates tour lengths for leaf squares, while the recursive step combines child squa... | def do_dp(points, c, m):
global log_counter
# create dp[square i][valid visit k] = minimal length of well-behaved tour
n = len(points)
L = get_L(n)
SQUARES_AMOUNT = (4*L*L-1) // 3 # amount of squares on all levels 1 + 4 + 16 + ... + L*L
POSITIONS_AMOUNT = 3**(4*m*c) # 2^(2r)=2^(2mc) - how many d... |
def _split_line(ln: bytes) -> Iterable[bytes]:
# Consume either:
# Whitespace
# "quoted string with \" "
# non-space token
for m in re.finditer(
rb'((?P<space>\s+)|(?P<quoted_string>"(?:\\"|.)*?")|(?P<token>[^"\s][^\s]+))',
ln,
):
if m.... | The code processes each line from an input iterator, skipping comments, splitting lines into tokens, parsing each token into ParsedObjects, and yielding a new object. Its main task is to convert raw byte lines into structured ParsedObject instances by tokenizing and parsing data while ignoring comment lines. | def parse_lines(self, line_iterator: Iterable[bytes]) -> Iterable[ParsedObject]:
for ln in line_iterator:
ln = ln.strip()
if ln.startswith(b"#"):
continue
for token in self._split_line(ln):
yield from self.parse_token(token)
yield from ... |
def bfs(self) -> list:
"""implement the breadth first search algorithm
Returns:
list: the path from start to goal
"""
start = tuple(self.start.values())
goal = tuple(self.goal.values())
current = Queue()
current.put(start)
explored = set()
... | The main task of the code is to determine a path from the start to the goal node using a specified search algorithm (BFS, UCS, or A*). The method delegates to the corresponding algorithm's implementation based on the `self.algorithm` value and returns the computed path. If an unsupported algorithm is specified, it rais... | def find_path(self) -> list:
"""find the path from start to goal using the specified algorithm"""
self.path = None
if self.algorithm == "bfs":
return self.bfs()
elif self.algorithm == "ucs":
return self.ucs()
elif self.algorithm == "astar":
ret... |
def get_input(self):
moves = self.get_Valid_Moves()
prompt = 'Please enter you choice: {} \n"[vertical, horizontal])" \n' \
'Enter with a space and no comma (ex: 0 0) : '.format(moves)
user_input = input(prompt)
input_lst = [int(item) for item in user_input.split(" ")]
... | This function determines the next move in a game, handling both human and computer turns. It retrieves input or a random move, updates the board by flipping tiles, checks for game over conditions, and toggles the turn. The logic differentiates between human and computer moves, ensuring appropriate actions and messages ... | def move(self):
next = None
if self.turn == 'W' and self.human == 'W':
next = self.get_input()
print("\nYour move")
elif self.turn == 'W' and self.robot == 'W':
input('Press Enter to see the computer\'s move.')
print("\nComputer move")
... |
def read_csqa_examples(input_file, have_answer=True):
with open(input_file, "r", encoding="utf-8") as f:
examples = []
for line in f.readlines():
csqa_json = json.loads(line)
if have_answer:
label = ord(csqa_json["answerKey"]) - ord("A")
else:
... | The main task of the code is to fine-tune a BERT model for multiple-choice tasks, such as the CSQA dataset, with options for training, evaluation, and testing. It supports distributed training, early stopping, and handles different datasets like WSC/SWAG. The code processes input data, trains the model with specified h... | def main():
parser = argparse.ArgumentParser()
## Required parameters
parser.add_argument("--data_dir",
default=None,
type=str,
required=True,
help="The input data dir. Should contain the .csv files (or other da... |
def resetPartial():
save_file_textfield.disabled=True
save_file_textfield.hint_style={"color":Black}
save_button.disabled=True
VarGlobal.MAX_VALUE = 0
VarGlobal.MAX_VALUE = 0
txt_savefile.color=Black
save_file_textfield.error_text=""
save_file_textfield.he... | The code validates input tokens to ensure they are exactly two alphanumeric characters each. If valid, it stores them in a list, generates a sequence, creates a random matrix using these tokens, and updates the UI. Invalid inputs trigger error messages and reset processes. | def token_changed(e):
resetPartial()
makeListEmpty(unique_tokens)
tokens = e.control.value
tokens = tokens.split(" ")
isValid = True
for token in tokens:
if len(token)!=2:
makeListEmpty(unique_tokens)
e.control.error_text="Token... |
def read_file_list(filename):
with open(filename) as f:
file_list = f.read().split('\n')
return file_list
def preprocess(filename, set_type, config):
infer = set_type == 'infer'
if not infer:
txt_file, mid_file, wav_file = files4train(filename, config)
else:
txt_file, mid_fi... | The code's main task is to preprocess and extract features from training and validation datasets using a configuration file. It creates directory structures, reads file lists, processes data with multiprocessing (if enabled), and saves features along with indices. The script ensures GPU usage is disabled during multipr... | def main():
config = Config()
config_basename = os.path.basename(config.config[0])
print("Configuration file: \'%s\'" % (config_basename))
set_list = ['train', 'valid']
file_list = {}
# Creating Path for Features
create_path(config.feature_path, action='overwrite', verbose=False)
for s... |
def get_latest_date(df):
df = dataframe_dates_to_datetime(df)
return df["date_time"].max()
def fns_later_than_date(input_files, threshold):
input_file_dates = parse_dates_from_filenames(input_files)
new_file_i = new_file_indices(input_file_dates, threshold)
return [input_files[i] for i in new_file_i... | The main task of the code is to update an existing CSV file by appending only new data from recent CSV files. It reads the existing data, identifies the latest date, filters input files with newer dates, combines them with the existing data, and saves the updated dataset to a new file. | def main():
"""
Update data by appending only new data to an existing file.
"""
combined_fn = "./data/mobility.csv"
input_path = "./data/raw/*.csv"
out_fn = "./data/mobility_updated.csv"
prev_data = pd.read_csv(combined_fn)
input_files = glob.glob(input_path)
latest_date = get_lat... |
def read_input_csv_files(input_folder: str) -> List[Any]:
""" Collect full paths of csv files inside the input folder provided by config. """
input_files = list()
for root, dirs, files in os.walk(input_folder):
for file in files:
filename, extension = os.path.splitext(file)
i... | (The main task of the code is to generate Excel (.xlsx) pivot tables from CSV files using a configurable setup. It parses command-line arguments for a config file, imports configuration settings, reads CSV files from a specified input folder, processes each file into a pivot table, and writes the results to Excel files... | def main():
parser = argparse.ArgumentParser(
description='Pivot table creating script, making .xlsx files out of dataframes read from csv files.',
usage='python comparing_script.py [-c config_file.py]'
)
parser.add_argument('-c', dest='config', default='config.py', help='[optional] path to ... |
def clear() -> None:
os.system("cls" if os.name == "nt" else "clear")
def argue_with_me() -> tuple:
"""
This is called if there are arguments passed to the script via cli,
and assigns and returns the variables qty (int), length (int),
spec_char (True / False) and copy (True / False) to the script.
... | The main task of the code is to generate high-entropy passwords using customizable parameters (length, special characters, quantity) through either command-line arguments or interactive dialogs. It includes features like random character replacement, shuffling, and optional output formatting/copying to clipboard, while... | def main():
clear()
"""
Arguably, this is yet another example of generating passwords but with a higher entropy
by the method of generation, shuffling, random char replacement, and so on. Just
another script that will sit unused but good for continued work.
I've tried to optimize this one a b... |
def load_users_list():
"""
for load users list from file... "users.data" (to enter a parameter?)
incoming: users - list of dictionaries with keys: "name" and "birthday"
return: users - list from file...
"""
if os.path.isfile(os.path.join(os.path.abspath(os.path.dirname(__file__)), "users.data")... | The main task of the code is to display users' birthdays for the upcoming week. It allows automatic generation of user data with random dates and names or manual input. The program validates dates, processes user lists, and shows birthdays for the current or specified week using the `get_birthdays_per_week` function, w... | def main():
"""
Basic function to display user birthdays per week.
The function displays users with birthdays one week ahead of the current day.
1 - automatically form a list of users with random date and numbered names - for example and for testing
0 - manually create a list of users (or load from ... |
def init_db():
'''
Connects to db with retry
Inits DB tables, if not created
'''
conn = db_connect(DB_SETTINGS)
while conn == 1:
time.sleep(5)
conn = db_connect(DB_SETTINGS)
init_coverage(conn)
logging.info('Closing DB Connection')
conn.close()
return True
def get... | (The main task of the code is to periodically execute an ETL process that retrieves coverage data, stores it in a database and Redis, and manages data retention. It maintains a scheduled loop checking the next run time from the database, executes the job when due, updates the schedule, and logs execution details. The p... | def main():
'''
Start loop with 1 minute check-in interval.
Every checkin, look in database for next run time.
If next run time has passed, execute next run.
'''
# Initialize DB Tables, if required
init_db()
# Gather ETL attributes, or create if non existant
(next_run, run_interval... |
def connect(self):
""" Connect to the dongle, verify it's supported, obtain and upgrade token
:returns: True if successful
"""
self.dongleVersion = self._getDongleVersion()
if not self._isSupportedDongleVersion(self.dongleVersion):
raise Exception("Unsupported dongl... | The function sends a hexadecimal message to a device via an API, using parameters like device codes, message type, and token authentication. It handles token expiration by reconnecting and retrying, returning the response or raising exceptions for errors. | def _sendHexMessageToDevice(self, msgValue, msgType="0"):
""" Sends the supplied hex string to the API and returns the result
:param msgValue: The hex string to send
:param msgType: The type of message to send, default is "0"
:returns: Dict containing the response
"""
if... |
def check_length_argv(argv):
if argv is None:
print("Error: No Argument")
return -1
if len(argv) != 6:
return -2
else:
print("user args: %s" % argv)
return 0
def pre_setting(db):
try:
print("Your database contains these schemas"
"please input... | The main task of the code is to validate input arguments, establish a database connection, perform preprocessing, execute query refinement, handle exceptions, and ensure proper database closure. It processes command-line inputs, interacts with a database object, and executes predefined operations while maintaining erro... | def ui(argv):
argv_check_result = check_length_argv(argv)
pre_setting_value = {}
if argv_check_result != 0:
raise Exception("Error: Invalid Argument")
db = DBObj(argv[1], argv[2], argv[3], argv[4], argv[5])
try:
db.connect()
pre_setting_value = pre_setting(db)
print(... |
def near_locate_mesh(xyo, ikle, meshx, meshy, tree=None):
"""
Requires the scipy.spatial and the matplotlib.tri packages to be loaded.
- Will use already computed tree or re-create it if necessary.
- Will use already computed neighbourhood or re-create it if necessary.
This function return the ele... | The function `cross_mesh` computes the intersection points between a polyline and a mesh, collecting the corresponding mesh elements and boundary indices where intersections occur. It traces rays from the polyline's nodes through the mesh, appending intersection coordinates, element IDs, and boundary flags to lists. Th... | def cross_mesh(polyline, ikle, meshx, meshy, tree=None, neighbours=None):
# ~~ Intersection nodes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ipt = []
iet = []
ibr = []
# ~~ Locate nodes of the polyline ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
xyo = polyline[0]
e_o, b_o, tree = near_locate_mesh(xyo, i... |
def rowReduction(self):
for i in range(self.n):
minValue = self.costEdges[i].min()
for j in range(self.n):
self.costEdges[i, j] = self.costEdges[i, j] - minValue
def columnReduction(self):
for j in range(self.n):
minValue = self.costEdges[:, j].min()
... | This code implements the Hungarian algorithm for solving assignment problems. It reduces the cost matrix via row and column operations, iteratively adjusts the matrix to find the minimum cover lines, and repeats until the optimal solution is reached. The goal is to identify independent zeros in the matrix that represen... | def calculate(self):
self.rowReduction()
self.columnReduction()
# print("Cost matrix after row and column reduction")
# print(self.costEdges)
(coverRows, coverColumns, independentZeros) = self.findMinCoverLines()
n1 = len(coverRows) + len(coverColumns)
while n1 !=... |
def white_noisy_validate(val_loader, model, time_begin=None):
perturbed_test_accs = []
noise_levels = [0, 0.02, 0.04, 0.06, 0.08, 0.1, 0.12, 0.15, 0.18, 0.2, 0.25, 0.3, 0.35]
# noise_levels = [0, 0.1, 0.2, 0.3]
for eps in noise_levels:
model.eval()
acc1_val = 0
n = 0
with... | The main task of the code is to evaluate multiple pre-trained models on a specified dataset (e.g., CIFAR10) under different noise conditions. It loads models from a folder, applies noise-specific validation (white, sp, or none), computes test accuracy using a test loader, and prints results. The code iterates through a... | def main(data='cifar10', folder=None, batch_size=512, noise_type='none'):
models = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
models = sorted(models)
print('************************')
print("Beginning evaluation")
print('************************')
print("Noise ty... |
def current_account():
"""
Perform account validation or registration for the BudgetBits application.
This function interacts with the AccountValidator class to either validate an existing user's login
or facilitate user registration, ensuring the user's account is properly managed.
Returns:
... | The code defines the main function of the BudgetBits expense tracker, managing user authentication (login/registration), expense tracking, and data persistence. It loads user data from a JSON file, allows users to add or view expenses, update monthly budgets, and displays personal information. The loop provides menu-dr... | def main():
"""
The main function of the BudgetBits expense tracker.
This function orchestrates the login and registration process, handles user interactions,
and manages the overall flow of the BudgetBits application.
"""
# check the registered users
info = InformationManager(os.path.join... |
def get_last_night_chart():
labels = {
"hotel": "Hotel",
"notFit": "Place Not Fit For Habitation",
"psychiatric90": "Psychiatric Facility",
"substanceAbuse90": "Substance Abuse Facility",
"hospital90": "Hospital",
"jail90": "Jail",
"transitionalHousingName": "Transitional Housing",
"emergencyShelterNam... | The main task of the code is to return a list of pie chart functions, including `get_last_night_chart()`, `get_volunteer_chart()`, `get_veteran_chart()`, and `get_cause_chart()`, which likely generate specific data visualizations. The comment indicates the list can be expanded with additional pie charts, suggesting thi... | def get_pie_chart_list():
return [
get_last_night_chart(),
get_volunteer_chart(),
get_veteran_chart(),
get_cause_chart()
#Add more pie charts here
] |
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--device", type=int, default=0)
parser.add_argument("--width", help='cap width', type=int, default=3000)
parser.add_argument("--height", help='cap height', type=int, default=1500)
parser.add_argument('--use_static_image_mode',... | The code detects the object "Zoa" using a YOLO model, calculates its distance from the camera via pixel width and calibrated parameters, and triggers a response (pointing to the target) when "Zoa" is identified. It processes video input, performs real-time object detection, and displays annotated frames with distance i... | def main():
# THIS IS WHAT YOU WANNA HIT #######################################################
wanna_hit = "Zoa"
# CONSTANTS ########################################################################
CALIBRATED_FOCAL_LENGTH = 245
KNOWN_WIDTH = 35.0
# Argument parsing ##########################... |
def split_validation_data(subject_condition,which,pca,scale_out,k_fold_index):
if pca ==True:
X_train, Y_train, X_test, Y_test,X_train_pca,X_test_pca = read_total_data(subject_condition,which,pca,scale_out)
else:
X_train, Y_train, X_test, Y_test = read_total_data(subject_condition,which,pca,sca... | This function performs k-fold cross-validation for a neural network model. It splits data into training/validation/test sets, trains the model with specified hyperparameters, and saves outputs for each fold, including model details, data, and hyperparameters, labeled by fold index and configuration. | def run_cross_valid(subject_condition,which,hyper_arg,hyper_val,k_fold,pca,scale_out, model_class):
for k in range(k_fold):
X_Train, Y_Train, X_val, Y_val, X_test, Y_test = split_validation_data(subject_condition,which,pca,scale_out,k) ###### k index is required for subject_naive case
model = ru... |
def return_model(f,criteria):
avg_train_mse, avg_val_mse, avg_test_mse, avg_train_pc, avg_val_pc, avg_test_pc = estimate_validation_results(f)
if criteria == "avg_val_mse":
if np.mean(avg_val_mse) == 0:
return 1000
else:
return np.mean(avg_val_mse)
def return_model_stat(f):
avg_train_mse, avg_val_mse, avg_... | This function identifies the top-performing models by comparing their average validation MSE values across multiple files. It iterates through potential model indices, checks for existing files, and updates the best model metrics. Once 10 optimal models are found, it triggers training of a final model using the best in... | def run_final(which):
count=0
start=1000
for i in range(131220):
if Path('text_out/Angles_hyper_'+str(i)+'_k_fold_4.txt').is_file():
f='text_out/'+which+'_hyper_'+str(i)+'_k_fold_XXXX.txt'
tmp = return_model(f,"avg_val_mse")
if tmp < start:
print("model_index = ",i,start,which)
start = tmp
re... |
def return_model(f,criteria): #### obkective of this function is to obtain average cross validation error
avg_train_mse, avg_val_mse, avg_test_mse, avg_train_pc, avg_val_pc, avg_test_pc = estimate_validation_results(f)
if criteria == "avg_val_mse":
if np.mean(avg_val_mse) == 0: #### this if condition is only... | This function identifies the top-performing models based on cross-validation (CV) error (MSE) by iterating through 43741 model candidates. It saves models with lower MSE than a threshold, tracking up to 6 best models. Once 5 valid models are found, it triggers training of a final model using the best-performing one, de... | def run_final(subject_condition,which,scale_out,model_class): #### this model find some best model as per CV error and then run train_final_model
count=0
start=1000 ### initiate with large mse value
for i in range(43741):
if Path('text_out/'+which+'_hyper_'+str(i)+'_k_fold_'... |
def parse_telegramMessage(message):
chat_id = message['message']['chat']['id']
txt = message['message']['text']
return chat_id, txt
def send_message(chat_id,text='Temp text'):
url = f'https://api.telegram.org/bot{key}/sendMessage'
payload = {'chat_id': chat_id, 'text': text} # Required parameters fo... | The code handles Telegram bot interactions by processing incoming POST requests. It parses messages, checks for 'START' or 'EXIT' commands to send appropriate responses, uses a model to predict intent and fetch responses for other inputs, and handles errors by apologizing. GET requests return a simple HTML heading. | def index():
if request.method == 'POST':
try:
msg = request.get_json()
chat_id, txt = parse_telegramMessage(msg)
if txt == 'START' or txt == 'start':
send_message(chat_id, 'Welcome to our telegram bot, made to keep you healthy. Try using keywords... |
def _step1(anndata, min_cells, num_cells, num_genes=2000):
"""
Filters the matrix for lowly expressed genes. Performs subsampling of genes and cells. Gene sampling is implemented
using Kernel Density Estimation in order to sample genes in such a way that genes that are highly expressed are more
likely ... | The main task of the code is to compute Pearson residuals for an anndata object through regression-based transformation, filter genes by expression thresholds, and optionally retain highly variable genes based on Pearson variance. It processes the data in steps: sub-sampling, model parameter estimation, regularization,... | def pytransform(anndata, min_cells=5, num_genes=2000, num_cells=5000, workers=os.cpu_count()-1, inplace=True,
verbose=False, highly_variable=3000):
"""
Performs pearson residual estimation on the anndata object. Please note that the initial regression estimation is
very compute intensive, th... |
def get_possible_moves(board):
possible_moves = []
for i in range(3):
for j in range(3):
if board[i][j] == '-':
possible_moves.append((i,j))
return possible_moves
def ai_turn(board, ai_player):
best_score = -1000
best_move = None
for i, j in get_possible_moves... | The function `enter_move` handles a player's or computer's turn in a game. If it's the player's turn, it prompts for valid row and column inputs; otherwise, it uses an AI to determine the move. It updates the board with the current player's symbol and prints the updated board state. | def enter_move(board, whose_turn, player):
if whose_turn == player:
print("Player move:")
while True:
i = int(input("\tPlease enter row index:"))
j = int(input("\tPlease enter column index:"))
if (i, j) in get_possible_moves(board):
break
else:... |
def get_possible_moves(self):
"""Generating a list of possible moves"""
possible_moves = []
for i in range(3):
for j in range(3):
if self.board[i][j] == '-':
possible_moves.append((i,j))
return possible_moves
def player_move(self):
... | The function `enter_move` handles a player's or AI's turn in a game by determining the move coordinates, updating the game board with the current player's symbol, drawing the corresponding mark (X or O) at the calculated midpoint of the selected grid cell, and switching to the next player's turn. | def enter_move(self):
"""Apply the move"""
self.get_possible_moves()
if self.whose_move == self.player_symbol: i, j = self.player_move()
else: i, j = self.ai_move()
p1 , p2 = self.grid[i][j]
point = ((p1[0] + p2[0])/2, (p1[1] + p2[1])/2, 0)
self.board[i][j] = self... |
def print_board(board):
for i in board:
print('|'.join(i))
print('')
def enter_move(board, whose_turn, player):
if whose_turn == player:
print("Player move:")
while True:
i = int(input("\tPlease enter row index:"))
j = int(input("\tPlease enter column index:")... | The code implements a Tic-Tac-Toe game where a human player (O) and an AI (X) alternate turns on a 3x3 board. It randomly selects the starting player, updates the board with moves, checks for a win or tie after each move, and terminates the game when a victory or tie is detected, displaying the result. | def tic_tac_toe():
board = [['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']]
player = PLAYER_O
ai_player = PLAYER_X
if random.randint(0, 1):
whose_turn = player
else:
whose_turn = ai_player
print()
print_board(board)
while True:
ent... |
def create_board(self, size=CELL_SIZE):
"""Drawing a game board"""
board_location_point = rs.GetPoint("Set board starter point")
if board_location_point:
self.board_location_point = board_location_point
point = self.board_location_point
self.grid = []
for i in... | The code initializes and runs a Tic Tac Toe game by creating a board, determining the player's symbol, randomly selecting the starting player (AI or human), and entering a loop where it processes moves. After each move, it checks for a win or tie, displaying a message box to announce the result (win, tie) and terminati... | def start(self):
"""Starts the game"""
self.create_board()
self.get_player_symbol()
# Who will start the game?
if random.randint(0, 1):
self.whose_move = self.ai_symbol
while True:
self.enter_move()
if self.is_victory():
... |
def standard_primitive(struct,symprec=1e-5):
Analyzer = SpacegroupAnalyzer(struct)
dataset = get_symmetry_dataset(struct,symprec)
lattice = dataset["primitive_lattice"]
positions = dataset["positions"]
types = dataset["primitive_types"]
magmoms = dataset["magmoms"]
_, T_mat,trans,_ = _c... | The function symmetrizes a crystal structure's magnetic moments by converting it to a standard primitive cell, identifying magnetic symmetries, applying these symmetries to the structure and magnetic moments, and returning the modified structure with symmetrized magnetic moments for improved magnetic symmetry analysis. | def symmetrize(struct,symprec=0.01,nround = 10):
# magnetic symmetry may be improved after only symmetrized nonmagnetic lattice
# symmetries is obtained with respect to standard primitive cell of symmetrized structure
# Primitive cell of non symmetrized structure does not match symmetries of standard primit... |
def quitGame():
pygame.quit()
quit()
def checkForCollisions(snake):
snakeListCopy = snakeList.copy()
snakeListCopy.remove(snake)
if snake.isColliding(snake.trailGroup.sprites()[:-5]):
roundWinner = killSnake(snake)
if (roundWinner is not None): return roundWinner
for otherSnake... | The function `updateGame()` processes game events (quit/escape), updates active snakes' movements and collision checks, manages powerup interactions (applying effects and removing expired ones), spawns new powerups, updates the display, and maintains the game clock/FPS. It returns the round winner if a collision determ... | def updateGame():
for event in pygame.event.get():
if event.type == pygame.QUIT:
quitGame()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quitGame()
for snake in snakeList:
if not (snake.dead):
controlInput = play... |
def initGame():
for index in range(0, PLAYERS):
newSnake = Snake(index, playerList[index])
newSnake.setPos(findUnoccupiedPosForSnake(snakeList))
newSnake.setAng(randrange(0, 360))
snakeList.append(newSnake)
spriteSnakeGroup.add(snakeList)
createAndPlacePowerup()
print("N... | The code manages a game loop by initializing the game, updating game state, rendering visuals, detecting round winners, resetting for new rounds, and returning the winner. It includes a placeholder for checking global win conditions and restarting the game after each round. | def gameLoop():
initGame()
while True:
roundWinner = updateGame()
gameRender()
if (roundWinner is not None):
print("Round winner detected, resetting")
resetForNewRound()
# TODO: check for global wincondition
startScreen()
... |
def init():
global DISPLAY, GAMECLOCK
pygame.init()
GAMECLOCK = pygame.time.Clock()
DISPLAY = pygame.display.set_mode((WIDTH, HEIGHT))
for index in range(0, PLAYERS):
playerControl = Control(index, CONTROL_MODE)
playerList.append(Player(index, playerControl))
drawBackground()... | The main task of the code is to run a game loop where players compete, track their scores, and end the game when a player reaches a specified score limit. It initializes the game, processes each round to determine a winner, updates scores, checks for a win condition, displays the final scoreboard if the game ends, and ... | def main():
init()
startScreen()
while True:
gameOver = False
roundWinner = gameLoop()
playerList[roundWinner.owner_id].incrementScore()
if playerList[roundWinner.owner_id].score > SCORE_LIMIT:
gameOver = True
roundWinner = None
... |
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot... | This code implements Boruvka's algorithm to find the Minimum Spanning Tree (MST) of a graph. It initializes disjoint sets, iteratively selects the cheapest edge connecting different components, and merges them until all nodes form a single tree. The MST's total weight and edges are printed. | def boruvkaMST(self):
parent = []
rank = []
cheapest = []
numTrees = self.V
MSTweight = 0
for node in range(self.V):
parent.append(node)
rank.append(0)
cheapest = [-1] * self.V
# Keep comb... |
def parse():
"""
Parser config and input args to generate test parameters
Returns
------------
arguments
A configargparse object
"""
parser = cfg.ArgumentParser(
config_file_parser_class=cfg.ConfigparserConfigFileParser
)
parser.add_argument(
"config",
... | The main task of the code is to run a Bayesian inference sampler using Bilby, handling data loading, prior parameter setup, likelihood configuration based on noise type, and generating posterior samples. It checks for existing data, initializes parameters, constructs a prior dictionary, selects an appropriate likelihoo... | def run_sampler():
"""
Runs the sampler for the data
Inputs
-------------------
"""
# get arguments
arguments = parse()
# add a custom model if necessary
arguments.add_custom_model = eval(arguments.add_custom_model)
if arguments.add_custom_model != ():
add_model(
... |
def menu_is_available(menu_object, current_datetime=datetime.now(), by_date_only=False):
"""
Checks if menu object is available at current application time
Args:
menu_object (JSON menu object): menu to be evaluated
current_datetime (datetime): Time to take as 'now', defaults to current syst... | The function retrieves a list of tuples containing restaurant objects and their operating hours for restaurants currently open at the given datetime. It checks menu availability, collects eligible restaurant IDs, then fetches full restaurant data and operating hours, combining them into tuples. Returns the list or an e... | def retrieve_current_restaurants_with_operating_hours(current_datetime=datetime.now()):
"""
Retrieve list of tuples for restaurants that are currently available.
tuple[0] contains restaurant object, tuple[1] contains it's operating hours
Returns:
list of tuples if any restaurants are open, empt... |
def setup_argument_parser():
"""
Setup argument parser with required arguments and their properties.
"""
parser = argparse.ArgumentParser(
description="Copy files and/or directories to another or directory."
)
parser.add_argument(
"sources",
nargs="+",
help="The file/s or directory/ies to be copied."
)
... | The main task of the code is to parse command-line arguments, identify files and directories from specified sources, copy them to a destination, count the number of files and directories copied, and print a summary of the operation. | def main():
"""
Parse and handle user's call.
"""
parser = setup_argument_parser()
arguments = parser.parse_args()
sources, destination = (arguments.sources, arguments.destination)
files_count = 0
dirs_count = 0
for source in sources:
if fu.does_file_exist(source):
files_count += 1
copy_file(source, d... |
def events(self):
"""Events handler"""
for event in pg.event.get():
if event.type == pg.QUIT:
self.running = False
if event.type == pg.KEYDOWN and event.key == pg.K_q:
self.running = False
def update(self):
"""Simulation loop updates"""
... | The code defines a game loop that runs while `self.running` is True. It controls the frame rate with `self.clock.tick(FPS)`, processes events, updates game state, renders the display, and optionally saves results if `self.record` is enabled. The main task is to maintain the game's execution cycle, handling input, logic... | def run(self):
"""Game loop."""
while self.running:
self.clock.tick(FPS)
self.events()
self.update()
self.display()
if self.record: self.save_results() |
def send_broadcast(clients):
message = randColor() + "Server started, listening on IP address " + ip_address
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP need to check ipproto
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADC... | The code sets up a TCP server to handle multiple clients, managing game sessions by accepting connections, broadcasting data, initiating games, and cleaning up resources. It uses threading for concurrent client handling, includes error handling, and prints statistics after each game round. The server repeatedly listens... | def main():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: # init the TCP socket
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # allow use 2 sockets from the same port
sock.bind(('', TCP_PORT)) # bind the socket with our port
sock.listen() # set queue of wai... |
def build_mst(maze, start_node, objectives):
dist = dict()
predecessor = dict()
visited = []
graph = objectives + [start_node]
for vertex in graph:
dist[vertex] = float("inf")
predecessor[vertex] = None
dist[start_node] = 0
pqueue = []
hq.heapify(pqueue)
hq.he... | The code computes a suboptimal path through a maze by constructing a minimum spanning tree (MST) connecting the start position and objectives, then concatenating precomputed A* paths between MST nodes. It returns a list of coordinates representing the combined path. | def fast(maze):
"""
Runs suboptimal search algorithm for part 4.
@param maze: The maze to execute the search on.
@return path: a list of tuples containing the coordinates of each state in the computed path
"""
# TODO: Write your code here
start_pos = maze.getStart()
objectives = maze.g... |
def create_bid(current_bids):
"""Prompts user for the creation of a bid."""
var_name = [
{
'type': 'input',
'message': 'Input a variable name:',
'name': 'var'
} ]
language_question = [
{
'type': 'list',
... | The code implements an interactive bidding languages interpreter, allowing users to create, view, solve, or translate bids. It maintains a dictionary of current bids and loops through a menu of operations, executing corresponding functions like create_bid, solve_bid, or translate_bid based on user input until exit is c... | def main():
print("Welcome to the Bidding Languages Interpreter.")
current_bids = {}
while True:
question = [
{
'type': 'list',
'message': 'Select an action',
'name': 'operation',
'choices': [
{
'name': 'See... |
def Battery_loading(self):
start_pos = len(self.MassAircraftCurrent) - 1
self.CGPositions.append(self.CG_Calculator(self.MassAircraftCurrent[self.Counter], self.CGPositions[self.Counter], 400, 4.25))
self.MassAircraftCurrent.append(self.MassAircraftCurrent[self.Counter] + 400)
self.Count... | The code simulates aircraft loading scenarios based on input 'con' values (1-6), calculating mass and center-of-gravity (CG) data for components like cargo, passengers, fuel, and hydrogen. It then plots these values against CG positions, adding safety margins and reference lines for OEM, ZFM, MTOM, and CG limits, visua... | def Run(self, con, plot: bool = True):
if con == 1: # cargo, pass, fuel
start_battery, end_battery = self.Battery_loading()
start_cargo, end_cargo = self.CargoLoading()
start_front_pass, end_front_pass = self.PassengerFrontLoading()
start_rear_pass, end_rear_pass ... |
def analyze_body_temperature(value):
print("{} - Analyze body temperature".format(LOGPREFIX))
print("{} - Payload: {}".format(LOGPREFIX, value))
response = {}
if value > 37.5:
response = {
"message": "You have fever"
}
else:
response = {
"mes... | The code processes SQS messages containing patient vital signs (BP, BT, HR, etc.), analyzes each parameter for abnormalities using dedicated functions, and stores alerts (non-NORMAL results) into an MSSQL database. It logs processing steps, extracts patient IDs and vital values, checks each metric against thresholds, a... | def analyze_vital_sign(event, context):
print("{} - Analyze Vital Sign".format(LOGPREFIX))
# Get value from SQS
print("{} - Number of records = {}".format(LOGPREFIX, len(event.get("Records"))))
list_payload = []
if len(event.get("Records")) > 0:
for record in event.get("Records"):
... |
def get_time_left(self, date):
# Get the time left in the current period.
# This is done by subtracting the current time from the time of the next period.
# If the current time is less than the next period, then the time left is 0.
period = self.get_time(date)
if period is None:
... | This method retrieves the current time period, day type, and remaining time for a given date, then returns them encapsulated in a TimeModel object. | def get_info(self, date):
# This method returns a TimeModel object, which contains the current period, the type of day, and the time left in the period.
time_left, total_time = self.get_time_left(date)
# getattr the period from EvenDayPeriodTimes or OddDayPeriodTimes to PeriodTypes
day_t... |
def get_object_pose(self, sample, obj_root):
seq_path = os.path.join(obj_root, sample['subject'], sample['action_name'],
sample['seq_idx'], 'object_pose.txt')
with open(seq_path, 'r') as seq_f:
raw_lines = seq_f.readlines()
raw_line = raw_lines[sample[... | The code preprocesses a dataset sample by converting 3D object and hand poses into 2D image coordinates using camera intrinsics/extrinsics. It generates tensors for object and hand positions, masks, and action labels, mapping them to 5x13x13 grids. The output includes images, pose tensors, classification probabilities,... | def preprocess(self, idx):
sample = self.samples[idx]
object_category = {
'juice': 0,
'liquid_soap': 1,
'milk': 2,
'salt': 3
}
action_category = {
'open_milk': 0,
'close_milk': 1,
'pour_milk': 2,
'open_juic... |
def load_objects(self, obj_root):
object_names = ['juice', 'liquid_soap', 'milk', 'salt']
all_models = {}
for obj_name in object_names:
obj_path = os.path.join(obj_root, '{}_model'.format(obj_name),
'{}_model.ply'.format(obj_name))
mesh... | This code initializes a dataset for hand pose estimation, handling data loading, splitting into train/test sets, and sample creation with transformations. It loads 3D object models, camera parameters, and processes video frames with actions, mapping them to objects. Normalization and color jittering are applied, and da... | def __init__(self, mode='train', root='../data', loadit=False, name=None, normalized=False):
#### TODO: add normalization of hand pose option
self.name = name
self.root = root
self.loadit = loadit
self.mode = mode
self.normalized = normalized
self.transfo... |
def child(a, b):
return amb(
unify((a, "jim"), (b, "bob")), # jim is a child of bob.
unify((a, "joe"), (b, "bob")), # joe is a child of bob.
unify((a, "ian"), (b, "jim")), # ian is a child of jim.
unify((a, "fifi"), (b, "fluffy")), # fifi is a child of fluffy.
... | The main task of the code is to resolve logical expressions involving variables x and y, generating substitutions for "child" relationships and "mortal but not dog" conditions. It iterates through resolved solutions, printing formatted statements about descendants and entities that are mortal but not dogs. The code dem... | def main():
x = var()
y = var()
for subst in resolve(child(x, y)):
print(f"{subst[x]} is a descendant of {subst[y]}.")
print()
for subst in resolve(seq(mortal(x), no(dog(x)))):
print(f"{subst[x]} is mortal and no dog.") |
def load_world(self) -> None:
self.load_lights()
self.load_ground()
self.load_trees()
self.load_camp()
self.load_post()
self.load_screamer()
self.load_spiders()
self.load_grass()
self.load_buttons()
self.load_intro()
def load_sound(self) ->... | This code initializes a game component by setting up player data, loading game elements like the world, sounds, and UI, and initializing variables to track timing for events (e.g., monster appearances, hissing intervals), game state (e.g., game over status), and other dynamic properties (e.g., growling state, side dire... | def __init__(self,player) -> None:
super().__init__()
self.player = player
self.ui = None
self.load_world()
self.load_sound()
self.load_ui()
self.time = 0
self.next_hiss = random.randint(5,10)
self.next_monster = random.randint(10,15)
self.... |
def __get_cyc_and_cap(self, names, cyc_raw, cap_raw):
cyc_data = []
cap_data = []
gp_cyc_raw = self.__group_cyc_by_name(cyc_raw, names)
gp_cap_raw = cap_raw.groupby('test_name')
for test_name in names:
last_cap_group_index = 0
cap_group = gp_cap_raw.get... | The code prepares training and testing datasets by extracting charge/discharge cycle and capacity data from raw inputs using specified names. It cleans the data by aligning charge/discharge parameters, adds SOC (State of Charge) and SOH (State of Health) parameters to discharge data, and logs dataset shapes. The main t... | def prepare_data(self, train_names, test_names):
self.logger.debug("Start preparing data for training: %s and testing: %s..."
% (train_names, test_names))
self.train_charge_cyc, self.train_charge_cap = self.__get_cyc_and_cap(
train_names, self.charge_cyc_raw, self.... |
def LoadUI(self):
self.ui=uic.loadUi('PI_GUI.ui',self)
def WidgetWrap(self):
self.labelaxiset=[self.label_xaxis,self.label_yaxis,self.label_zaxis]
self.btnlset=[self.pushButton_xl,self.pushButton_yl,self.pushButton_zl]
self.btnrset=[self.pushButton_xr,self.pushButton_yr,self.pushButton_z... | This code initializes a GUI application by loading the user interface, setting up widgets, applying styles, connecting signal-slot interactions, and displaying the main window. | def __init__(self):
super().__init__()
self.LoadUI()
self.WidgetWrap()
self.Restyle()
self.SignalSlotBinding()
self.show() |
def __serialize_arguments(self, arguments):
return {k: self.__serialize_value(v) for k, v in arguments.items()}
def __patched_create_method(self):
"""
A context manager to temporarily patch the create method for logging purposes.
"""
with self.lock:
patched = self.dat... | This code wraps a function to track its execution within a task, managing thread-local storage, logging function calls with parameters/results, and handling task lifecycle events. It generates unique task IDs, records call stacks, serializes arguments, and logs events with timestamps, ensuring proper task tracking and ... | def wrapper(*args, **kwargs):
if track and hasattr(thread_local_storage, 'task_id') and len(self.data_store[thread_local_storage.task_id]['call_stack']) > 0:
raise ValueError("Cannot track a top level function that is already part of a task.")
if not hasattr(thread_lo... |
def max_node(self):
max = 0
nodes = self.tree.all_nodes()
for node in nodes:
if node.identifier > max:
max = node.identifier
return max
def create_leaf(self, y, instances, parent, mutual_info = None):
o = self.create_orthopartition(y, instances=instanc... | The code builds a decision tree using mutual information for feature selection. It recursively splits data instances based on the feature with maximum information gain, creating internal nodes or leaf nodes when conditions (e.g., uniform targets, depth limits) are met. Leaf nodes store class distributions, while intern... | def fit(self, X, y, instances=None, parent=-1):
if instances is None:
instances = [i for i in range(0, len(X))]
if len(instances) == 0:
print("all data considered")
return
targets = set()
for el in instances:
targets.add(y[el])
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.