dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def empty_spaces(self):
empty_space_list = []
for row in range(3):
for col in range(3):
if self.board[row][col] == '-':
empty_space_list.append(f'{row} {col}')
return empty_space_list
def split_position(self, position):
row, col = position.... | The function determines the best move for a player by evaluating all possible empty positions on the board using the minimax algorithm. It simulates placing the player's symbol in each empty spot, calculates the resulting move value, and selects the position with the lowest value as the optimal move. The board is reset... | def find_best_move(self):
best_value = 1000
best_move = ''
empty_spaces = self.empty_spaces()
for empty_space in empty_spaces:
row, col = self.split_position(empty_space)
self.board[row][col] = self.player_two
move_value = self.minimax(self.board, 0, T... |
def get_stores_path(args, require_exist=True):
p = Path(args["path"] or SECRETS_PATH)
if require_exist and not p.exists():
abort(f"ERROR: secrets path does not exist ({p})")
return p
def get_or_prompt(args, key, message, secure=False, double_check_message=None):
v = args.get(key)
if v:
... | The main task of the code is to create a new secure store by collecting user inputs for the store's name, key, and fields. It prompts the user to define mandatory/hidden fields interactively if not provided, constructs a Store object, and saves it to a `.sec` file. The function handles field formatting, attribute parsi... | def command_create(args):
path = get_stores_path(args, require_exist=False)
name = get_or_prompt(args, "name", "Store name: ")
key = get_store_key(args, name)
store_path = path / f"{name}.sec"
raw_fields = args["fields"]
if not raw_fields:
raw_fields = []
i = 1
print("\... |
def get_stores_path(args, require_exist=True):
p = Path(args["path"] or SECRETS_PATH)
if require_exist and not p.exists():
abort(f"ERROR: secrets path does not exist ({p})")
return p
def get_or_prompt(args, key, message, secure=False, double_check_message=None):
v = args.get(key)
if v:
... | This function retrieves and processes secrets from a store, filtering and formatting them based on specified fields. It handles default fields like "ID", adds timestamp fields if requested, sorts secrets, and returns the filtered data for display. | def _command_projection(args):
path = get_stores_path(args, require_exist=False)
name = get_or_prompt(args, "name", "Store name: ")
key = get_store_key(args, name)
store_path = path / f"{name}.sec"
fields = args["fields"]
store = open_store(name, store_path, key)
if not fields:
fi... |
def get_stores_path(args, require_exist=True):
p = Path(args["path"] or SECRETS_PATH)
if require_exist and not p.exists():
abort(f"ERROR: secrets path does not exist ({p})")
return p
def get_or_prompt(args, key, message, secure=False, double_check_message=None):
v = args.get(key)
if v:
... | This function clears all secrets from a specified store. It retrieves the store's path and name, opens the store using the provided key, clears its secrets, and attempts to save the changes. If saving fails, it aborts with an error. The main task is to remove all stored secrets and persist the updated store state. | def command_clear(args):
path = get_stores_path(args, require_exist=False)
name = get_or_prompt(args, "name", "Store name: ")
key = get_store_key(args, name)
store_path = path / f"{name}.sec"
store = open_store(name, store_path, key)
store.clear_secrets()
if not store.save():
abor... |
def get_stores_path(args, require_exist=True):
p = Path(args["path"] or SECRETS_PATH)
if require_exist and not p.exists():
abort(f"ERROR: secrets path does not exist ({p})")
return p
def get_or_prompt(args, key, message, secure=False, double_check_message=None):
v = args.get(key)
if v:
... | The main task of the code is to add a new secret store by collecting secret key-value pairs from either provided data or user prompts, then saving them securely. It handles mandatory fields, validates inputs, and stores the secrets in a specified path. If saving fails, it aborts with an error. | def command_add(args):
path = get_stores_path(args, require_exist=False)
name = get_or_prompt(args, "name", "Store name: ")
key = get_store_key(args, name)
store_path = path / f"{name}.sec"
data = args["data"] or []
secret = {}
for d in data:
try:
key, value = d.split("=... |
def get_stores_path(args, require_exist=True):
p = Path(args["path"] or SECRETS_PATH)
if require_exist and not p.exists():
abort(f"ERROR: secrets path does not exist ({p})")
return p
def get_or_prompt(args, key, message, secure=False, double_check_message=None):
v = args.get(key)
if v:
... | The main task of the code is to modify a secret in a store by either directly providing key-value pairs or interactively selecting a field to update. It validates inputs, handles user prompts for secure fields, and saves changes to the store. If no data is provided, it guides the user to choose a secret field, input it... | def command_modify(args):
path = get_stores_path(args, require_exist=False)
name = get_or_prompt(args, "name", "Store name: ")
key = get_store_key(args, name)
secret_id = get_or_prompt(args, "key", "ID of the secret to modify: ")
store_path = path / f"{name}.sec"
data = args["data"] or []
t... |
def get_stores_path(args, require_exist=True):
p = Path(args["path"] or SECRETS_PATH)
if require_exist and not p.exists():
abort(f"ERROR: secrets path does not exist ({p})")
return p
def get_or_prompt(args, key, message, secure=False, double_check_message=None):
v = args.get(key)
if v:
... | This function removes specified secrets from a store. It retrieves the store path and key, prompts for secret IDs if not provided, validates them as integers, removes the secrets in reverse order to avoid index issues, and saves the updated store. Errors occur if validation fails or removal/saving fails. | def command_remove(args):
path = get_stores_path(args, require_exist=False)
name = get_or_prompt(args, "name", "Store name: ")
key = get_store_key(args, name)
store_path = path / f"{name}.sec"
secrets_to_remove = args["secrets"]
store = open_store(name, store_path, key)
if not secrets_to_... |
def _command_projection(args):
path = get_stores_path(args, require_exist=False)
name = get_or_prompt(args, "name", "Store name: ")
key = get_store_key(args, name)
store_path = path / f"{name}.sec"
fields = args["fields"]
store = open_store(name, store_path, key)
if not fields:
fi... | The code defines a function `command_grep` that searches for a specified pattern in secret values, highlights matches, and displays results either as JSON or a table. It processes input arguments, retrieves a search pattern, iterates through secrets, checks for pattern matches using regex, and formats output based on t... | def command_grep(args):
fields, projection_secrets = _command_projection(args)
pattern = get_or_prompt(args, "pattern", "Search pattern: ")
display_secrets = []
for s in projection_secrets:
match = False
display_secret = {}
for k, v in s.items():
v_highlighted = str(... |
def change_player(current_player: bool):
'''
Return the opposite boolean value
'''
return not current_player
def get_current_empty_fields(board):
'''
Collect and return all empty fields coordinates from the
given board. If there not empty fields retun False
'''
empty_fields_coordinat... | The code simulates multiple games to evaluate potential moves for an AI player. It generates a score board by running GAMES_COUNT simulations, randomly selecting moves, and updating scores based on game outcomes (win/loss). The AI identifies the move with the highest score as the optimal choice, returning this best mov... | def find_best_ai_move(board, current_player):
'''
Generate a board with scores which will help the AI to choose his
next best move.
The start position of every game will be always the given board.
The score board will calculate his fields after every game with WIN.
The count of AI played games d... |
def generate_board(size=BOARD_SIZE):
'''
Generate game board with BOARD_SIZE x BOARD_SIZE dimensions
'''
matrix = []
for _ in range(size):
matrix.append([EMPTY_FIELD for __ in range(size)])
return matrix
def view_board_state(board):
'''
Print the current board
'''
for ro... | The code implements a turn-based game where a player and AI alternate moves on a board. It validates moves, updates the board, checks for a winner after each move, and ends the game if a player wins or the board is full. | def main():
'''
Initialize a board, players and messages with information about the
game state after every move. Changes the player and AI after every move.
If there is a win or all of the board fields are filled, the game ends.
'''
game_board = generate_board()
view_board_state(game_board)... |
def get_startup_query(self):
query = self.get_default_query()
query['path'] = {'query': (list(self.parent_paths_to_nav_root()) +
list(self.get_toplevel_paths())),
'depth': 4}
return query
def get_nodes_by_query(self, query, unrestricted... | The code's main task is to retrieve and prepare navigation nodes for a mobile interface by checking user permissions, configuring HTTP headers for caching and content type, filtering nodes based on request parameters, and returning the processed nodes as a JSON response. It ensures proper access control, cache settings... | def startup(self):
"""Return all nodes relevant for starting up a mobile navigation
on the current context.
"""
if not api.user.has_permission('View', obj=self.context):
raise Unauthorized()
response = self.request.response
response.setHeader('Content-Type', ... |
def revenue(self,x,player,q_,batch=1, locs=None, price_index=0):
z=self.query_env_player(x,player,q_,locs=locs, batch=batch)
return 0.5*z@(x[player]+self.tot_rev*self.prices_[price_index])
def revenue_loc(self,x,player,q_,locs=None, batch=1, price_index=0):
z=self.query_env_player(x,player, q_,l... | The code implements a stochastic gradient descent (SGD) optimization algorithm to maximize revenue across locations for a specific price bin. It initializes parameters, iteratively updates decision variables using projected gradients, and tracks metrics like revenue, demand, and loss for two platforms (Lyft/Uber) over ... | def runSGD(self,x0,price_index=0,eta=0.001,BATCH=10,MAXITER=1000, verbose=False, perform_sgd=[True,True], RETURN=True, MYOPIC=False, tot_rev=1):
'''
Runs for one price bin and all locations
'''
self.stepsize_sgd=eta
self.batch_sgd=BATCH
self.maxiter_sgd=MAXITER
se... |
def revenue_so(self,x,q1,q2,batch=1, locs=None, price_index=0):
z1=self.query_env_player(x,0, q1,locs=locs,batch=batch)
z2=self.query_env_player(x,1, q2,locs=locs,batch=batch)
return 0.5*z1@(x[0]+self.tot_rev*self.prices_[price_index])+0.5*z2@(x[1]+self.tot_rev*self.prices_[price_index])
def rev... | This function performs gradient descent optimization for social optimum in a transportation pricing model, iteratively updating a solution vector (x) to maximize revenue while tracking metrics like revenue, demand, and loss across iterations for a specific price bin and all locations. It returns a dictionary containing... | def runSO(self,x0,price_index=0,eta=0.001,BATCH=10,MAXITER=1000, verbose=False, RETURN=True,tot_rev=1):
'''
Runs for one price bin and all locations
'''
self.stepsize_so=eta
self.batch_so=BATCH
self.maxiter_so=MAXITER
self.tot_rev=tot_rev
self.price_index_... |
def revenue(self,x,player,q_,batch=1, locs=None, price_index=0):
z=self.query_env_player(x,player,q_,locs=locs, batch=batch)
return 0.5*z@(x[player]+self.tot_rev*self.prices_[price_index])
def revenue_loc(self,x,player,q_,locs=None, batch=1, price_index=0):
z=self.query_env_player(x,player, q_,l... | This function performs gradient descent optimization for a specific price level across all locations, tracking revenue, demand, and loss metrics over iterations. It initializes parameters, iteratively updates the solution using projected gradients, and returns a dictionary containing the optimization trajectory and per... | def runRGD(self,x0,price_index=0,eta=0.001,BATCH=10,MAXITER=1000, verbose=False, RETURN=True,tot_rev=1):
'''
Runs for one price bin and all locations
'''
self.stepsize_rgd=eta
self.batch_rgd=BATCH
self.maxiter_rgd=MAXITER
self.tot_rev=tot_rev
self.price_in... |
def revenue(self,x,player,q_,batch=1, locs=None, price_index=0):
z=self.query_env_player(x,player,q_,locs=locs, batch=batch)
return 0.5*z@(x[player]+self.tot_rev*self.prices_[price_index])
def demand(self,x,player,q_,locs=None,batch=1):
return self.query_env_player(x,player, q_,locs=locs,batch=b... | The function simulates a competitive game between two players (e.g., Lyft and Uber) by iteratively updating their strategies (x) to maximize revenue, considering performative effects. It modifies internal matrices, computes gradients, projects updates, tracks revenues/demands over iterations, and optionally resets matr... | def rungame_cor(self,A1_,A2_,Ac1_,Ac2_,x0,price_index=0,eta=0.001,BATCH=10,MAXITER=1000, verbose=False, reset=False):
self.A1_=np.copy(self.A1)
self.A2_=np.copy(self.A2)
self.Ac1_=np.copy(self.Ac1)
self.Ac2_=np.copy(self.Ac2)
self.price_index=price_index
print("Price we ... |
def revenue(self,x,player,q_,batch=1, locs=None, price_index=0):
z=self.query_env_player(x,player,q_,locs=locs, batch=batch)
return 0.5*z@(x[player]+self.tot_rev*self.prices_[price_index])
def revenue_loc(self,x,player,q_,locs=None, batch=1, price_index=0):
z=self.query_env_player(x,player, q_,l... | The main task of the code is to perform an accelerated gradient descent (AGD) optimization for a given price bin and all locations. It initializes parameters, iteratively updates model estimates (A1_hat, Ac1_hat, etc.), and tracks metrics like revenue, demand, and loss over iterations. The algorithm projects updates us... | def runAGD(self,x0,A_dic, price_index=0,eta=0.001,nu=0.01, BATCH=10,MAXITER=1000, verbose=False, perform_agd=[True,True], RETURN=True, INNERITER=1, B=1, UNCORR=False,tot_rev=1):
'''
Runs for one price bin and all locations
'''
self.stepsize_agd=eta
self.nu=nu
self.batch_a... |
def init_session_state(self):
if "tab_selected" not in st.session_state:
st.session_state.tab_selected = tab_labels[0]
def load_tokenizer(model_path):
tokenizer = BertTokenizer.from_pretrained(model_path)
return tokenizer
def load_model():
model = IndoBERTBiLSTM.from_pretrained(MODELS_PA... | The code defines a method `run` that initializes session state, loads a tokenizer and model, and sets up a web interface for an app review classifier. It displays a styled header, tabs, and a process button to classify reviews using the loaded model and tokenizer. | def run(self):
self.init_session_state() # Initialize session state
tokenizer = load_tokenizer(MODELS_PATH)
model = load_model()
"""App Review Classifier"""
html_temp = """
<div style="background-color:blue;padding:10px">
<h1 style="color:white;text-align:center;... |
def ag1(params, inputs, is_training):
if params.f_strategy == 'late':
seq_pool, inputs_accel, inputs_gyro = ag(params, inputs, is_training)
return seq_pool, inputs_accel + inputs_gyro
elif params.f_strategy == 'early':
return ag(params, inputs, is_training)
def ag2(params, inputs, is_tra... | The main task of the code is to route input data through different sensor fusion processing functions based on configuration parameters. It checks the 'fusion' and 'f_mode' settings in self.params, then calls corresponding functions (ag1, ag2, dnd1) to process inputs during training or inference, returning the result o... | def __call__(self, inputs, is_training):
if self.params.fusion == 'accel_gyro':
if self.params.f_mode == 'ag1':
return ag1(self.params, inputs, is_training)
if self.params.f_mode == 'ag2':
return ag2(self.params, inputs, is_training)
elif self.para... |
def IQsample4times(self): # nframe: number of frames
list_of_dfs = self.ReadSplitFile()
cdata = np.zeros((self.nline*self.nframe, self.nchannel, 8))
for i, v in enumerate(list_of_dfs):
for j, col in enumerate(v.columns):
I, Q = self.IQcalculation(np.array(v[col]))
... | The code splits calculated data into 8×8×8 3D numpy arrays, generates scatter or heatmap plots for each frame based on the `plottype` parameter, and stores the resulting figures in a dictionary with sequential names like 'Frame_i'. The method returns this dictionary containing all generated plots. | def PlotFrames(self, plottype = 'heatmap'): #split the calculated data into 8*8*8 3d numpy array, plot respectively and store in a dict with name in sequence 'Frame_i'
cdata = self.IQsample4times()
list_of_cdatas = [cdata[i*self.nline:(i+1)*self.nline, :, :] for i in range(self.nframe)]
figdict ... |
def Readcsv(self):
self.df = pd.read_csv(self.filepath, header = 0)
self.df.columns = ['ch1','ch2','ch3','ch4','ch5','ch6','ch7','ch8','ch9','ch10','ch11','ch12','ch13','ch14','ch15','ch16']
def init_para(self):
self.channel = tk.StringVar()
self.channel.set('ch1')
def init_gui(self):
... | This code initializes a GUI application for plotting ADC data by setting up the main window properties, loading data from a CSV file, initializing parameters, and creating the graphical interface. | def __init__(self, root, filepath):
self.root = root
self.root.title('ADC data plot')
self.root.resizable(0,0)
self.root.geometry('900x720+30+30')
self.filepath = filepath
self.Readcsv()
self.init_para()
self.init_gui() |
def encrypt_data(self, data_id, data: str):
"""
encrypt data
:param data_id: int of data id
:param data: data to encrypt
:return: encrypted data (encryption of nonce + tag + ciphertext)
"""
cipher = AES.new(self.secret_key, AES.MODE_EAX)
# convert data (s... | This function stores encrypted data in a root bucket by replacing a dummy entry, assigns a new random leaf index to the data ID in the position map, and prevents bucket overflow. It validates data size and ID uniqueness, encrypts the data, inserts it into the root bucket, and ensures the tree structure remains efficien... | def store_date(self, server: Server, data_id: int, data: str) -> None:
"""
write data to root bucket. decrypt root bucket and find a dummy data to replace with given data.
assign new random leaf to data and store in position_map.
call prevent_overflow() to make sure root will not be full... |
def read_path(self, leaf_index: int, server: Server):
"""
return the list of indices and buckets of the nodes from root to the given tree leaf
"""
path_indices = get_path_to_leaf(leaf_index, self.tree_height)
path_buckets = server.get_buckets_by_indices(path_indices)
retu... | The function retrieves data by ID from a structured storage system, traversing a root-to-leaf path using `position_map` and `read_path`. It removes the data from relevant buckets, updates the position map, and writes the data back to the root with a new random leaf to prevent overflow, ensuring efficient data retrieval... | def retrieve_data(self, server: Server, requested_data_id: int) -> Union[str, None]:
"""
get data by id. search the correct path from root to leaf of given data by its id.
call store_data() to write the requested data back to the root
:param server: server object
:param requested... |
def parse_input(input_str: str) -> List[int]:
'''Reads the string of the input and make a list of integers out of it'''
return [int(int_str) for int_str in input_str.strip().split(',')]
def calc_min_fuel(distances_list: List[int], cost_function) -> int:
'''Given a list of crab locations, and cost function, ... | The code reads input data from a file, parses it into a list of distances, and calculates the minimum fuel required for two distinct cost functions. It first computes the result for "Part 1" using a linear cost function, then initializes a different cost function for "Part 2" and recalculates the minimum fuel. The goal... | def main():
input_str = open('input/day07.txt', 'r').read()
distances_list = parse_input(input_str)
min_fuel = calc_min_fuel(distances_list, cost_function_part_1)
print(f'Part 1: Minimum fuel {min_fuel}')
init_part_2_cost_function()
min_fuel = calc_min_fuel(distances_list, cost_function_part_... |
def parse_drawn_numbers(drawn_numbers_str: str) -> List[int]:
'''Parses a list of ints out of a comma seperated string of ints'''
return [int(number_str) for number_str in drawn_numbers_str.split(',')]
def parse_bingo_cards(bingo_cards_strs: List[str]):
'''Parses bingo cards (i.e. numpy arrays) from a list ... | The code reads input for a Bingo game, parses drawn numbers and Bingo cards, then simulates two game scenarios: one to find the first winning card and another to determine the last winning card in the sequence of drawn numbers. | def main():
input_lines = open('input/day04.txt', 'r').readlines()
drawn_numbers_str = input_lines[0]
drawn_numbers = parse_drawn_numbers(drawn_numbers_str)
bingo_cards = parse_bingo_cards(input_lines[2:])
play_game(bingo_cards, drawn_numbers.copy())
play_game_til_last_win(bingo_cards, drawn_... |
def init():
global engine
global session
engine = sqlalchemy.create_engine(db.db_conn_string)
models.Base.metadata.drop_all(engine)
models.Base.metadata.create_all(engine)
sessionmaker = orm.sessionmaker(bind=engine)
session = sessionmaker()
def robots():
drilldough = models.Machine(
... | The code defines a function `gogogadget()` that sequentially executes four operations: initialization (`init()`), robot management (`robots()`), human-related processing (`people()`), and crowd simulation with 50 entities (`crowd(50)`). Its main task is to orchestrate a multi-component system involving setup, robotic e... | def gogogadget():
init()
robots()
people()
crowd(50) |
def _make_save_dirs(base_dir,save_dir,save_all):
if save_dir == None:
save_dir = base_dir
if save_all:
save_one = os.path.join(save_dir,'class_files')
save_two = os.path.join(save_dir,'class_files_split')
save_three = os.path.join(save_dir,'final_files')
if not os.path.ex... | This function organizes and splits data from multiple folders into training/validation sets. It processes each class directory, splits files according to specified ratios (70% train, 20% val), and saves structured outputs. Parameters control saving options, class filtering, and data types. The result is a consolidated ... | def from_folders_to_split(base_dir,print_=False,save_all=False,img=False,val=False,split_train=0.7,
split_val=0.2,one_class=False,save_dir=None,which_class=None):
save_one, save_two, save_three = _make_save_dirs(base_dir,save_dir,save_all)
class_names = os.listdir(base_dir)
for class_name in class_n... |
def select_menu():
print('\n- m - Main menu')
print('- c - Compute engine menu')
selector=input('\nType the option of the menu from which you want to add a test case: ')
if selector=='m':
create_case_main_menu()
if selector=='c':
create_case_compute_menu()
def test_case_module():
... | This function prompts the user to add another test case step, branching to a menu if 'y' is selected, returning to the test case module if 'n' is chosen, or handling invalid input by re-prompting. | def add_another_step_compute_menu():
add_step_or_not = input("\nDo you want to add another step to this test case?. y/n: ")
if add_step_or_not == "y":
select_menu()
if add_step_or_not == "n":
input("\nYou decided not to add more steps for this test case. Press enter to get back to the test c... |
def _get_from_request(db_request, key, default=None):
answer = db_request[key] if key in db_request else default
if answer == default and answer == "AUTO":
answer = str(uuid4())
return answer
def _is_card_owned_by_user(self, card_id, user):
kvm = {"user": user, "cid": card_i... | This function handles creating or updating a card in a database. It validates user ownership, checks required fields (user, collection, name), and executes SQL INSERT/UPDATE operations. If the card ID exists, it updates fields like parent_id, name, or identifier. It ensures data integrity, commits changes, and retrieve... | def _card_set(self, db_request):
answer = {"error": False, "message": "ok."}
user = self._get_from_request(db_request, "user")
card_id = self._get_from_request(db_request, "id")
parent_id = self._get_from_request(db_request, "parent_id")
collection = self._get_from_request(db_re... |
def _cards_index(self, db_request):
answer = {"error": False, "message": "ok."}
user = db_request["user"] if "user" in db_request else ""
kvm = {"user": user}
sql = """SELECT c.*, COUNT(ca.key) AS attr_count
FROM cards AS c
LEFT OUTER JOIN card_attributes AS ... | This code processes a database request by routing it to the appropriate handler based on the specified operation type (e.g., index, get_card, set_card, etc.), executes the operation, and returns a structured response containing the operation result or an error message if the operation is unknown. | def handle_request_operation(self, db_request):
db_response = {"request": db_request, "response": {}}
if not "operation" in db_request:
db_request["operation"] = ""
if db_request["operation"] == "index":
operation_response = self._cards_index(db_request)
elif db_... |
def get_input_variables(data_loader):
B = FLAGS.batch_size if FLAGS is not None else 1
DIM_R = data_loader.dim_r
NUM_R = data_loader.num_rp
NUM_P = data_loader.max_phrase_per_sentence
input_variables = data_loader.get_input_variables(batch_size=B)
input_variables['region_ious'] = (tf.float32, (B, NUM_R, NUM... | The code trains a model using TensorFlow with optional distillation, loading data, setting up placeholders, optimizing with Adam, and saving checkpoints. It initializes variables, restores checkpoints, and runs training steps, updating losses and shuffling data per epoch. Distillation maps phrases to classes if enabled... | def main(args):
global FLAGS
FLAGS = args
# Enable distillation.
if FLAGS.phrase_to_label_json:
phrase_to_label = json.load(open(FLAGS.phrase_to_label_json, 'r'))
PHRASE_TO_CLASS_INDEX.update({
p : BG_AND_CLASSES.index(phrase_to_label[p]) for p in phrase_to_label})
p... |
def read_filenames(self):
filenames = self.cloud.get_file_names(prediction=True)
return filenames
def validate_one_file(self, filename):
failed = (False, None)
if Validator.validate_file_name(filename) is True:
file = self.read_one_file(filename)
if Validator.vali... | The main task of the code is to prepare training data by validating each file from a list of filenames and inserting valid files into a database. It logs progress and errors, returning True on success or False if an exception occurs during processing. | def prepare_data(self):
try:
self.logger.log_training_pipeline("PREPARING TRAINING DATA : Started : Please check file validation logs for more information")
filenames_list = self.read_filenames()
for filename in filenames_list:
(status, file) = self.validate_o... |
def read_filenames(self):
filenames = self.cloud.get_file_names()
return filenames
def validate_one_file(self, filename):
failed = (False, None)
if Validator.validate_file_name(filename) is True:
file = self.read_one_file(filename)
if Validator.validate_number_of_... | The main task of the code is to prepare data by validating files fetched from a server, inserting valid files into a database, and logging the process. It reads filenames, checks each file's validity, increments counters for accepted/rejected files, logs results, and returns True on success or False on error. Error han... | def prepare_data(self):
try:
self.logger.log_training_pipeline("DATA PREPARATION: Started")
filenames_list = self.read_filenames()
num_accepted = 0
num_rejected = 0
self.logger.log_training_pipeline(f"DATA PREPARATION: Fetched {len(filenames_list)} fil... |
def _GetInodePos(inode):
s = GetInodeStart()
bytes_per_block = superblock.Read(7)
s *= bytes_per_block
inodes_per_block = superblock.Read(2)
bytes_per_inode = bytes_per_block // inodes_per_block
s += inode * bytes_per_inode
return s
def _GetInode(inode):
a = []
s = _GetInodePos(inode... | This function writes data to a file system inode, handling direct and indirect blocks. It updates disk positions based on offset, recursively finds free inodes when needed, and sets pointers for indirect blocks. The task involves managing inode entries, locating valid storage locations, and ensuring data is correctly p... | def WriteDataNode(inode, offset, value, indirect=False):
p = _GetInodePos(inode)
if offset < 5:
disk.WriteInt(p + ((2 + offset)*4), value)
elif offset == 5 and indirect:
disk.WriteInt(p + ((2 + offset)*4), value)
else:
n = _GetInode(inode)
#find an invalid inode and set t... |
def bucket_test():
logging.info(f"bucket test {COS_BUCKET_NAME}")
logging.info(f"bucket creation date {data_bucket().creation_date}")
def s3_increment_object(o):
"""Return the dict {count: num} where num is the number of times this function has been called"""
initial = dict(count=0)
def put_contents(body_str)... | The main task of the code is to test an S3 bucket via `bucket_test()`, retrieve a data object using `data_object()`, and increment an S3 object's value via `s3_increment_object()`, returning the result. | def read_cos():
bucket_test()
return s3_increment_object(data_object()) |
def readFile(filepath, files=[]):
lines = []
gen = getFirstCommentBlock(filepath, lines)
settings = {}
for tag,data in gen:
settings[tag] = data
print(shorten(str(len(files) + 1) + ") " + settings["title"], width=50, placeholder="..."))
print("\n".join(wrap(shorten(settings["description... | The code traverses a directory tree starting at 'path', collects files with extensions specified in 'extensions', reads their content into a data list, and then generates an index and sitemap from this data. | def walk(path, extensions):
data = []
for subdir, dirs, files in os.walk(path):
for filename in files:
_,ext = os.path.splitext(filename)
filepath = os.path.join(subdir, filename)
if ext[1:] in extensions:
readFile(filepath, data)
writeIndex(data)
... |
def sky_cone(ra_c, dec_c, theta, steps=50, include_center=True):
"""
Get ra and dec coordinates of a cone on the sky.
Parameters
----------
ra_c, dec_c: float
Center of cone in degrees.
theta: astropy Quantity, float, or int
Angular radius of cone. Must be in arcsec
if n... | The function generates a stitched cutout image centered at specified RA/Dec coordinates using astronomical data from a butler repository. It calculates pixel size, retrieves relevant image patches, stitches overlapping regions, constructs a new WCS, and returns the combined cutout with optional PSF. The process handles... | def generate_cutout(butler, skymap_name, ra, dec, band='N708', data_type='deepCoadd_calexp',
half_size=10.0 * u.arcsec, psf=True, verbose=False):
"""Generate a single cutout image.
"""
skymap = butler.get('skyMap', skymap=skymap_name)
if not isinstance(half_size, u.Quantity):
... |
def init(session, params):
assert session.trials
if params.seed is None:
params.seed = random.getrandbits(32)
key = jax.random.PRNGKey(params.seed)
trial = session.trials[0]
n_channels = trial.y.shape[-1]
n_regressors = trial.x.shape[-1]
n_factors = params.n_factors
if params.a... | This function fits a probabilistic model using either GPFA or EM algorithm based on parameters, initializes sessions, handles model training with optional keyboard interrupt handling, performs inference, and returns updated session and parameters. | def fit(session: Session, n_factors: int, kernel: Union[Callable, Sequence[Callable]],
*, seed=None, **kwargs):
params = Params(n_factors, kernel, seed=seed)
if isinstance(kwargs, dict):
vars(params.args).update(kwargs)
session, params, em_session = init(session, params)
try:
if... |
def get_prop_value(dt_struct, dt_strings, prop_path):
"""Get the content of a property based on its path
Args:
dt_struct (bytes): Devicetree struct section
dt_strings (bytes): Devicetree strings section
prop_path (str): full path of the target property
Returns:
bytes: Prope... | The function performs a "kernel@ attack" by duplicating the kernel node in the device tree, appending '@evil' to its name, and replacing its content and hash with provided values. It assumes the U-Boot method is 'kernel' and updates the structure to inject a modified kernel, bypassing security checks by exploiting the ... | def kernel_at_attack(dt_struct, dt_strings, kernel_content, kernel_hash):
"""Conduct the kernel@ attack
It fetches from /configurations/default the name of the kernel being loaded.
Then, if the kernel name does not contain any @sign, duplicates the kernel
in /images node and appends '@evil' to its name... |
def get_prop_value(dt_struct, dt_strings, prop_path):
"""Get the content of a property based on its path
Args:
dt_struct (bytes): Devicetree struct section
dt_strings (bytes): Devicetree strings section
prop_path (str): full path of the target property
Returns:
bytes: Prope... | The function performs a "fakenode attack" by duplicating the original root node of a device tree, modifying the duplicated node to replace the loaded kernel's name and data with malicious values. It alters the kernel content and hash digest in the modified tree, assuming a specific UBoot loading method. Key steps inclu... | def fake_root_node_attack(dt_struct, dt_strings, kernel_content, kernel_digest):
"""Conduct the fakenode attack
It duplicates the original root node at the beginning of the tree.
Then it modifies within this duplicated tree:
- The loaded kernel name
- The loaded kernel data
Important ... |
def update_model(self):
self.model = [[self.cubes[i][j].value for j in range(self.cols)] for i in range(self.rows)]
def is_valid_move(self, num, pos):
row, col = pos
return self.is_valid_row(num, row) and self.is_valid_column(num, col) and self.is_valid_box(num, row, col)
def solve(self):
... | This code attempts to place a value in a selected Sudoku cell. If valid and solvable, it retains the value; otherwise, it reverts the change. It checks validity, updates the model, and uses backtracking via solve() to determine success. | def place(self, val):
row, col = self.selected
if self.cubes[row][col].value == 0:
self.cubes[row][col].set(val)
self.update_model()
if self.is_valid_move(val, (row, col)) and self.solve():
return True
else:
self.cubes[row]... |
def legal_moves(self):
"""Return a list of column indices of all legal moves
sorted in ascending order.
"""
legal = []
for i in range(0, 4):
this_col = self.cols[i]
if this_col and self.count + rank_count[this_col[-1][:-1]] <= 31:
# If t... | The main task of the code is to execute a move by taking the bottom card from column `i` if legal, update the game state, display changes, check for game end conditions, and return `True` for valid moves or `False` if the move is illegal but other options exist. It handles visual updates, game termination, and stack re... | def do_move(self, i):
"""Make the move visually by taking the bottom card of
column i.
Return False if this move is illegal and there are other legal
moves, else return True.
"""
if i in self.legal_moves():
display_codes(self.make_move(i))
if s... |
def game_over(self):
"""Return `True` if the game is over."""
return self.cols == [[], [], [], []]
def dump(self):
"""Print information about the current game."""
print(self)
print(f'STACK: {self.stack}')
print(f'POINTS: {self.points}')
print(f'COUNT: {self.count}... | The `autoplay` method automatically plays a game until completion by repeatedly selecting legal moves, executing them, and updating the game state. It prints move details and stack status if `verbose` is enabled, pauses after each move if requested, and resets the stack when no moves remain. Upon game end, it outputs t... | def autoplay(self, verbose=True, pause=False):
"""Automatically play a game until finished.
Argument:
- verbose: if `True`, print extra information after a move
- pause: if `True`, pause after printing move info.
Return value: none
"""
while not self.game_over()... |
def soft_e_policy(S,w,env,e):
sample = np.random.uniform()
Q_values = np.zeros(env.action_space.n)
for i in range(env.action_space.n):
Q_values[i] = Q(S,i,w,env)
if(sample > e):
action = np.argwhere(Q_values == np.amax(Q_values))
action = action.flatten()
a = np.random.... | This code implements semi-gradient SARSA on-policy algorithm for MountainCar-v0 environment using linear function approximation. It learns optimal policy weights (w) through 1000 episodes by updating weights with TD error, combining immediate reward and discounted future estimates. The ε-greedy policy balances explorat... | def Sarsa_on_policy():
total_g = 0
alpha = 0.1
gamma = 0.1
e = 0.1
env = gym.make('MountainCar-v0')
w = np.zeros(21)
for episode in range(1000):
G = 0
if(episode%100 == 0):
print(G)
print(episode)
S = env.reset()
action = soft_e_policy... |
def getPose(self):
#get the current end effector pose and orientation
link_state = self.p.getLinkState(self.kuka, self.num_joints_k-1,computeForwardKinematics=True)
return([link_state[4],link_state[5]])
def getEquidistantPoints(self,p1, p2, numpoints):
return zip(np.linspace(p1[0], p2[0]... | This function moves a robotic arm to release an object (LEGO or SPHERE) by calculating equidistant path points between the current position and a target tray location, moving in steps to ensure controlled descent, then opening the gripper. It uses object-specific tray coordinates and a fixed orientation for precise pla... | def dumpObj(self,objectName):
curPose=self.getPose()[0]
if(objectName=="LEGO"):
numSteps=2#move in steps to slow down #TODO - make it global
nwpos=list(self.getEquidistantPoints((curPose[0],curPose[1],self.ExtractZ), (self.LEGO_TRAY_X,self.LEGO_TRAY_Y,0.3), numSteps))
... |
def removeAll(self):
#remove the spheres and legos in the environment
self.legoIds=[]
self.sphereIds=[]
self.p.resetSimulation()
def loadRobot(self):
self.kuka = self.p.loadURDF('kuka_iiwa/model.urdf', useFixedBase = 1)
self.blgripper=self.p.loadURDF(curPath+"/data/blgr... | This function resets a simulation environment by removing all objects, reinitializing physics settings (gravity, real-time mode), reloading the robot and objects, resetting tracking flags/variables (e.g., grasp status, visited areas), and returning the initial observation state. It prepares the environment for a new ep... | def reset(self):
#remove all objects, reset everything
self.removeAll()
#re-init
self.p.setRealTimeSimulation(0)
self.FREQ=240.0
self.p.setGravity(0,0,-10.0)
#load robot
self.loadRobot()
#reinitialize random position of objects
self.loadObj... |
def getPose(self):
#get the current end effector pose and orientation
link_state = self.p.getLinkState(self.kuka, self.num_joints_k-1,computeForwardKinematics=True)
return([link_state[4],link_state[5]])
def movetoPosPose(self,goal_pos, goal_orn):
p_thres=0.001 #1 MM within commanded posi... | The main task of the code is to execute a robotic control step by processing an action (movement deltas and gripper command), updating the robot's end-effector position, adjusting the gripper state, calculating rewards, observing the new environment state, and returning the reward, episode termination status, and obser... | def step(self,action):
self.prevGripCmd=False
self.StepCount=self.StepCount+1
delta_x=action[0]
delta_y=action[1]
delta_z=action[2]
gripper_cmd=action[3]
#get current EE position
link_state = self.getPose()[0] #p.getLinkState(kuka, n... |
def new(self):
self.clearcar()
for road in self.lines:
c.delete(road)
for light in self.lights:
c.delete(light.id)
self.lines = []
self.level = []
self.rtype = []
self.lights = []
self.lanes = []
self.spawn = []
for trigger in self.triggers:
tm.delete(0)
self.triggers = []
def high(color)... | This code loads road data from a database, processes each road's attributes (like lanes, coordinates), aggregates lane counts for overlapping segments, sets bounding box coordinates, initializes graphical elements (lines with event bindings), and configures triggers and traffic lights for a simulation or visualization ... | def load(self, db):
roads = lib.loadFile(db)
self.new()
carry = {}
count = 0
self.minx, self.miny, self.maxx, self.maxy = 2147483647, 2147483647, 0, 0
for road in roads:
if road.covering in covers:
self.rtype.append(road.covering)
else:
self.rtype.append(0)
try:
carry[tuple({(road.x1... |
def fuzzify(self, center):
self.close = self.close(center)
self.moderate = self.moderate(center)
self.far = self.far(center)
def inference(self):
self.low = self.close
self.medium = self.moderate
self.high = self.far
def defuzzify(self):
X = np.linspace(0, 90, 900... | The code's main task is to perform fuzzy logic-based decision-making by fuzzifying input data, applying inference rules, and defuzzifying results to produce a crisp output value. | def decide(self, center_dist):
self.fuzzify(center_dist)
self.inference()
return self.defuzzify() |
def fuzzify(self, left_dist, right_dist):
self.close_L = self.fuzzy_membership(left_dist, 0, 50, 50)
self.close_R = self.fuzzy_membership(right_dist, 0, 50, 50)
self.moderate_L = self.fuzzy_membership(left_dist, 35, 50, 65)
self.moderate_R = self.fuzzy_membership(right_dist, 35, 50, 65)
... | This code processes input distances using fuzzy logic to make a decision. It fuzzifies the input values, applies inference rules, and defuzzifies the result to produce a crisp output for decision-making. | def decide(self, left_dist, right_dist):
self.fuzzify(left_dist, right_dist)
self.inference()
return self.defuzzify() |
def getPossibleCurrency(sampleData, inputImageGray):
matchesSummary = {}
maxMatchings = 0
maxMatchingsData = None
maxMatchingsCurrency = None
kp, des = getFeatures(inputImageGray)
for currencyValue, images in sampleData.items():
totalMatches = 0
for imageData in images:
... | The code processes a video frame to detect currency using template matching. It converts the frame to grayscale, identifies potential currency with a cache, and highlights the detected bill if sufficient matches are found. Debug mode draws matching points. Returns the processed frame with annotations if currency is det... | def processFrame(frame, cache):
colorFrame = frame
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
homographyData, matchingSummary, maxMatching, detectedCurrency = getPossibleCurrency(cache, frame)
if not (detectedCurrency is None) and maxMatching > MIN_MATCH_COUNT:
print("Detected currency is ... |
def getPossibleCurrency(sampleData, inputImageGray):
matchesSummary = {}
maxMatchings = 0
maxMatchingsData = None
maxMatchingsCurrency = None
kp, des = getFeatures(inputImageGray)
for currencyValue, images in sampleData.items():
totalMatches = 0
for imageData in images:
... | The code performs real-time currency detection using a webcam feed. It captures video frames, converts them to grayscale, and identifies currency notes by matching features against a cached dataset. When a currency is detected with sufficient matches, it prints the result and optionally highlights the detected bill and... | def realTime(cache):
videoCapture = cv2.VideoCapture(0)
while 1:
ret, frame = videoCapture.read()
colorFrame = frame
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
homographyData, matchingSummary, maxMatching, detectedCurrency = getPossibleCurrency(cache, frame, colorFrame)
... |
def get_boundaries(ins_table, resolution, sample_id):
"""
Params: ins_table, resolution, sample_id
Returns: boundaries_df
"""
column = 'is_boundary_'+str(resolution)
return ins_table[sample_id][(ins_table[sample_id].is_bad_bin == False) & (ins_table[sample_id][column] == True)]
def overlap(ipg, ... | The function processes each sample in the provided list by retrieving boundaries, calculating overlaps with a given dataset, aggregating results, normalizing the data, and concatenating all processed dataframes into a single output. | def norm_boundaries_ipg(ins_table, dld_ipg, resolution, sample_id_list):
appended_data = []
for sample_id in sample_id_list:
b = get_boundaries(ins_table, resolution, sample_id)
o = overlap(dld_ipg, b)
ag = agg(o, sample_id)
n = normalize(ag)
appended_data.append(n)
... |
def L_model_forward(X, parameters):
caches = []
A = X
L = len(parameters) // 2 # number of layers in the neural network
for l in range(1, L):
A_prev = A
A, cache = A, cache = linear_activation_forward(
A_prev, parameters['W'+str(l)], parameters['b'+str(l)], activation="relu... | The main task of the code is to train a neural network model using mini-batch gradient descent. It iteratively computes forward propagation, calculates the cost (MAE), performs backward propagation to obtain gradients, updates model parameters, and tracks/triggers cost printing every 100 iterations. The goal is to mini... | def train(self, X_train: np.array, y_train: np.array):
costs = []
# Loop (gradient descent)
for i in range(0, self.num_iterations):
indexes = np.random.choice(
X_train.shape[-1], self.batchSize, replace=False)
X_trainBatch = X_train[:, indexes]
... |
def My_Extract_y_Labels(self,y):
Labels_list=list()
for _,j in enumerate(y):
if j not in Labels_list: Labels_list.append(j)
return Labels_list
def y_MajorityLabel(self,y):
self.y_Labels_list=self.My_Extract_y_Labels(y)
print('y_Labels_list is: ', self.y_Label... | The code implements an ID3 decision tree algorithm recursively. It increments depth, checks termination conditions (max depth or no attributes left), calculates information gain for each attribute-value pair, selects the best pair, splits the dataset into subsets based on the selected feature, and recursively builds su... | def fitt(self):
self.depth=self.depth+1
print('\n\n<<<<----------id3 depth of: '+str(self.depth)+' staretd---------->>>>')
# extract class labels
self.y_Labels_list=self.My_Extract_y_Labels(self.y_trn)
print('No of Data in this ID3 is: ', len(self.y_trn))
... |
def get(self, url: str) -> dict:
if DEBUG:
print(">>> FETCHING: ", url)
url = f"{BASE_URL}{url}" if not url.startswith("https://") else url
with urllib.request.urlopen(
urllib.request.Request(
url,
headers=self.get_headers(),
)
... | The main task of the code is to retrieve the status of the most recent build for a specific job on the same branch by querying GitHub's API. It fetches completed and partial workflow runs, checks their associated jobs, identifies the latest job matching the current context, and returns its conclusion as "success" or "f... | def get_previous_build_status(self) -> Literal["success", "failure"]:
"""We need the previous build status of the job of the **SAME** branch
https://docs.github.com/en/rest/actions/workflows
"""
completed = self.get(
f"/repos/{GITHUB_REPOSITORY}/actions/workflows/{self.get_wo... |
def convert_duration_to_seconds(duration):
if duration == "":
return 200
minutes, seconds = map(int, duration.split(':'))
total_seconds = minutes * 60 + seconds
return total_seconds
def onCdPlayerStarted(artist, title, duration):
global player_new_video
#if player_new_video == False:
... | The code processes webhook data to handle media playback commands (PLAY/PREPARE_TRACK) by parsing hexadecimal values for CD/track positions, querying a database for matching tracks, and triggering actions like playing music videos on Kodi or a TV system. It maps track details to database entries, adjusts formatting for... | def process_webhook(data):
print(data)
if not USE_KODI:
print('Kodi is disabled.')
return 'OK', 200
status = data.get('status', '')
if status == 'PLAY':
headers = {'Content-Type': 'application/json'}
track = int(data.get('track', 1), 16)
duration = int(data.get... |
def send_socket(self, json_body):
server_address = '192.168.1.122'
server_port = 5000
# Manually crafting the HTTP GET request with a body (unconventional use)
request = "POST /webhook HTTP/1.1\r\n"
request += "Host: 192.168.1.122:5000\r\n"
request += "Content-Type: a... | This code handles HTTP GET requests to control a media player, parsing URL paths to execute commands like 'playButton', 'stop', 'nextTrack', and 'prevTrack'. It constructs JSON status messages, resets playback state, and triggers hardware actions via subprocess calls. The function checks path segments and lengths to de... | def do_GET(self, path):
path = path.split('/')
print(path[1])
print(len(path))
if path[1] == 'playButton' and len(path) == 6:
print("play button")
# Convert the data dictionary to a JSON string
json_body = '{"status":"PLAY", "device":"%s",... |
def create_json_file(num):
# check token is current and if not update
# 1 = last_db_import
# 2 = complete activity list_json
access_token = get_access_token()
activities_url = "https://www.strava.com/api/v3/athlete/activities/"
header = {'Authorization': 'Bearer ' + str(access_token)}
if n... | The main task of the code is to update a database with new activity data from a JSON file. It processes each activity's details (e.g., name, distance, time, elevation, heart rate) by converting timestamps and formatting data, then creates and saves `ActivityObject` instances in the database. The function ensures existi... | def update_activity_database(request):
# update JSON with new activities or create blank JSON
create_json_file(1)
with open('activities_after_last_save_to_db.json') as json_data:
d = json.load(json_data)
name_list = []
distance_list = []
moving_time_list = []
elapsed_... |
def process_lead_field_data(self, lead):
field_data = lead.pop('field_data')
lead_data = dict(lead)
lead_data.update([(l['name'], l['values'][0])
for l in field_data
if l.get('name') and l.get('values')])
return lead_data
def lead_creat... | This function processes leads from a paginated API response by checking if each lead exists in the database (via 'facebook_lead_id'), creating it if not found, committing transactions, and recursively fetching the next page of data if available to ensure all leads are processed. | def lead_processing(self, r, form):
if not r.get('data'):
return
for lead in r['data']:
lead = self.process_lead_field_data(lead)
if not self.search([('facebook_lead_id', '=', lead.get('id')), '|', ('active', '=', True), ('active', '=', False)]):
self.... |
def read_config() -> tuple:
if len(sys.argv) < 2:
sys.exit(1)
if not os.path.exists(sys.argv[1]):
sys.exit(1)
server_port_given = False
send_path_given = False
properties = {}
with open(sys.argv[1], "r") as fobj:
for property in fobj:
property = property.rst... | The main task of the code is to read email files from a configured path, validate their format, and send them via SMTP to a server on a specified port. It handles authentication for emails with "auth" in their path, manages client-server communication, and ensures proper error handling for file access and formatting is... | def main():
config_info = read_config()
server_port = config_info[0]
send_path = config_info[1]
# Check send_path can be read
if not os.access(send_path, os.R_OK):
sys.exit(2)
emails_to_send = get_emails_to_send(send_path)
for email in emails_to_send:
abspath = os.path.abs... |
def load_config():
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, "r") as f:
return json.load(f)
return None
def is_token_valid(token: str):
# Decode the JWT token
try:
decoded_token = jwt.decode(
token, algorithms=["none"], options={"verify_signature": Fa... | This function manages catalog operations on specified datastores, allowing users to include specific elements, prune/recreate catalog entries, and run tasks in the background. It processes input parameters, validates credentials, and triggers the `run_catalog` function with configured options. | def catalog_operation(
datastores: str = typer.Option(
...,
"--datastore",
help="Comma-separated list of Datastore IDs or array-like format",
),
include: Optional[str] = typer.Option(
None,
"--include",
help='Comma-separated list of include types or array-like... |
def load_config():
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, "r") as f:
return json.load(f)
return None
def is_token_valid(token: str):
# Decode the JWT token
try:
decoded_token = jwt.decode(
token, algorithms=["none"], options={"verify_signature": Fa... | This function initiates data profiling operations by processing parameters like datastore IDs, container filters, analysis thresholds, and incremental data constraints. It validates inputs, formats time values, and triggers the profiling process, optionally running it in the background. | def profile_operation(
datastores: str = typer.Option(
...,
"--datastore",
help="Comma-separated list of Datastore IDs or array-like format",
),
container_names: Optional[str] = typer.Option(
None,
"--container_names",
help='Comma-separated list of include typ... |
def load_config():
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, "r") as f:
return json.load(f)
return None
def is_token_valid(token: str):
# Decode the JWT token
try:
decoded_token = jwt.decode(
token, algorithms=["none"], options={"verify_signature": Fa... | The main task of the code is to configure and initiate a scan operation on specified datastores, allowing customization of container types, incremental processing, remediation strategies, and record limits. It validates inputs, prepares parameters, and triggers a background scan if enabled, using a validated token for ... | def scan_operation(
datastores: str = typer.Option(
...,
"--datastore",
help="Comma-separated list of Datastore IDs or array-like format",
),
container_names: Optional[str] = typer.Option(
None,
"--container_names",
help='Comma-separated list of include types ... |
def randn_lpf(self, shape):
win = torch.hann_window(self.hp.N_FFT).to(self.dev)
noise = torch.randn(*shape).to(self.dev)
spec = torch.stft(
input=noise[...,:-1],
n_fft=self.hp.N_FFT,
hop_length=self.hp.HOP,
win_length=self.hp.N_FFT,
win... | This function evaluates a model on a validation dataset by computing loss metrics, generating audio samples for a subset of batches, and saving these samples along with their spectrograms. It disables gradient calculations, iterates through validation batches, applies noise schedules, predicts noise, calculates losses,... | def valid_loop(self):
self.model.eval()
with torch.no_grad():
val_loss = 0
wav_val_loss = 0
audio_preds = []
with tqdm(self.val_dl, leave=False) as pbar:
for i, b in enumerate(pbar):
aud = b['audio'].to(self.dev)
... |
def train_step(self, a, spec, tgt_std):
for param in self.model.parameters():
param.grad = None
with self.autocast:
t = torch.randint(0, len(self.hp.NOISE_SCHEDULE), [a.shape[0]], device=self.dev)
ns = self.noise_level[t].unsqueeze(1)
ns_sqrt = ns ** 0.5
... | This code trains a machine learning model using a training data loader, iterating through batches to compute loss, monitor for NaNs, adjust learning rates, validate periodically, save checkpoints, and log progress. The loop runs until a predefined number of iterations (N_ITER) is reached, updating the model's parameter... | def train_loop(self):
self.model.train()
while True:
train_loss = 0
with tqdm(self.train_dl, leave=False) as pbar:
for b in pbar:
if self.step >= self.hp.N_ITER:
print('training done')
return
... |
def createPoints(n):
print("Dimention: ", n)
start_a = time.time()
L = [0, 0]
dist = 1300
0
x = 0;
while x < n:
print(x)
if (x < 3):
pass
else:
dist = int(float(dist) * 1.3)
# print("begin loop: ",L)
deltaX = randomSign() * int(... | The code generates an image by creating points, determining dimensions, drawing them on a white background, saving as a PNG, and measuring the time taken for image creation. | def drawArg(n):
global draw
global dim
points = createPoints(n)
start_b = time.time()
dim = Max(points)
im = Image.new('RGBA', (dim[0] + dim[1] + 300, dim[2] + dim[3] + 300), 'white')
draw = ImageDraw.Draw(im)
Draw(points, n)
im.save('drawing_' + str(n) + '_2.png')
end_b = time... |
def train_epoch(self, epoch):
stats_meter = self.stats_meter()
train_loader_iter = self.train_loader.__iter__()
num_iter = self.train_loader.__len__()
self.model.train()
pbar = tqdm(range(num_iter))
for iter in pbar:
inputs = train_loader_iter.next()
... | The code trains a model over multiple epochs, performing training and validation in each epoch. It tracks the best loss and recall metrics, saves snapshots at each epoch and when improved metrics are found, and finally saves training results after completing all epochs. | def train(self):
print('start training...')
for epoch in range(self.start_epoch, self.max_epoch + 1):
print(f"{'*'*30} Epoch {epoch} {'*'*30}")
self.train_epoch(epoch) # train
self.scheduler.step()
self._snapshot(epoch)
res = self.eval(epoch)... |
def get_profile_id(name):
profiles = dget("list")
name_key = ":{profile_id}/visible-name"
for profile_id in profiles:
profile_name = dget(name_key.format(profile_id=profile_id))
if f"{name}" == profile_name:
return profile_id
return None
def _make_profile():
profile_id = ... | The code creates a new GNOME Terminal profile with a specified name and parameters, checks for existing profiles to avoid duplication, applies custom settings, and optionally sets the profile as default. It logs warnings for duplicates and debug info for parameter assignments. | def create_new_profile(name, profile_params, set_default=False):
"""Create a new gnome-terminal profile.
Parameters
----------
name : str
The value for 'visible-name' on the new profile.
profile_params : dict
All keys that should be set for the profile apart from 'visible-name'.
... |
def address_lookup(self):
""" Search the address of the pulse dbus socket """
# 1. try the environment var
addr = os.environ.get('PULSE_DBUS_SERVER')
if addr: return addr
# 2. well-known system-wide daemon socket
if os.access('/run/pulse/dbus-socket', os.R_OK | os.W_OK):... | The code establishes a DBus connection to a PulseAudio server, retries up to 3 times if failed, and subscribes to signals for monitoring audio device/stream changes, volume/mute updates, and manages reconnection logic via Ecore. | def connect(self):
print("PULSE: connect %d", self.exe_count)
self.srv_addr = self.address_lookup()
try:
self.conn = dbus.connection.Connection(self.srv_addr,
mainloop=DBusEcoreMainLoop())
except:
if self.exe_coun... |
def genABQmodel():
session.journalOptions.setValues(replayGeometry=COORDINATE,recoverGeometry=COORDINATE)
mmd=mdb.Model(name=mdbModelName)
######
LL2,WW2=0.5*LL,0.5*WW
sRR=3*WW2 ;sRR=6*WW2
ptheta=30*mpi/180.0
cptheta,sptheta=mcos(ptheta),msin(ptheta)
dRRx,dRRy=sRR*cptheta,sRR*sptheta
... | The code automates running and analyzing multiple Abaqus simulations for different material models and loading angles. It generates finite element models, configures material properties (elastic, plastic, UMAT, or polynomial), sets boundary conditions, executes jobs with specified CPUs, and extracts stress-strain data,... | def runTests(nCPUs=1):
oschdir(thisPATH)
mdb,datumID,ndAlabel,ndBlabel,ndClabel,ndDlabel,elmLabel=genABQmodel()
##errStatusFile=figDirPlot+'_000_allJobsStatus.txt'
##errf=open(errStatusFile,'w');errf.close()
for ttest in vvTests:
vAngles=ttest['angles']
ff=figDirPlot+ttest['dfile'].s... |
def printMsg(msg):
if(noGUI):
#print >> sysOut, printThisName+str(msg)
print(str(msg),file=sysOut)
#elif(verprt):
# #print msg
# pass
else:
print(msg)
def read_NN_InpFile(wFile):
NTENS=int(3)
vNNparam=[0.0,] ### Added a first element to start counting from 1... | This function processes uniaxial simulation data by generating file paths for stress, node, and job data based on angular parameters from each test. It handles different material models (Poly_UMAT/NN) by reading input parameters or direct data files, then invokes a plotting function to visualize results. The core task ... | def plotTests():
if(not uaxSim):printMsg('plotTests: Only for uniaxial sims\nPost-proc aborted');sysexit()
for ttest in vvTests:
vAngles=ttest['angles']
ff=figDirPlot+ttest['dfile'].strip('.txt')
vFileJob,vFileNode,vFileStress=[],[],[]
for idxAngle in range(len(vAngles)):
... |
def runTests(nCPUs=1):
oschdir(thisPATH)
mdb,datumID,ndAlabel,ndBlabel,ndClabel,ndDlabel,elmLabel=genABQmodel()
##errStatusFile=figDirPlot+'_000_allJobsStatus.txt'
##errf=open(errStatusFile,'w');errf.close()
for ttest in vvTests:
vAngles=ttest['angles']
ff=figDirPlot+ttest['dfile'].s... | This function executes either simulation (STEP_1) using Abaqus or post-processing (STEP_2) using Python3 with Numpy/Matplotlib based on input flags. It runs `runTests()`/`runDDtests()` for simulations and `plotTests()`/`plotDDtests()` for visualization, aborting with environment requirements if neither condition is met... | def zexec(inpData):
if(abqSims):###---------STEP_1: simulation
if(uaxSim):
##Run sims (or create cae only)
runTests()
else:
runDDtests()
#
elif(pytPlot):###-------- STEP_2: post-processing
if(uaxSim):
##readPlotData(bParam,zINP,... |
def all_surveys():
return Survey.query.all()
def get_current_user_enrolment():
return [[enrolment.course_id, surveys_for_a_course(enrolment.course_id)] for enrolment in Enrolment.query.filter(Enrolment.zid == user_id).all()]
def requires_roles(*roles):
def wrapper(f):
@wraps(f)
def wrapped(*... | The main task of the code is to handle the staff index page by processing POST requests to redirect to survey-related routes (ViewSurveys, ViewSurveyResults, other) and rendering the staffIndex.html template with dynamic data: available surveys and the current user's enrolled courses. | def staff_index():
if request.method == "POST":
if "ViewSurveys" in request.form:
return redirect(url_for("display_survey_staff"))
elif "ViewSurveyResults" in request.form:
return redirect(url_for("view_questions"))
elif "other" in request.form:
return red... |
def handleHPSPinmuxesNode(self, pinmuxesNode):
""" PinmuxesNode is a list of pinmuxNodes
"""
self.pinmuxHeaderBuffer.write(str("const u8 sys_mgr_init_table[] = {\n"))
pinmuxNode = xmlgrok.firstElementChild(pinmuxesNode)
while pinmuxNode != None:
if pinmuxNode.hasAttr... | The main task of the code is to parse an HPS XML configuration, process its elements (e.g., pin_muxes, peripherals), generate pinmux configuration header and source files, and write them to disk. It uses string buffers to build file content dynamically, handles multiple HPS nodes, and applies device-specific templates ... | def createFilesFromHPS(self):
""" Parse xml and create pinmux_config.h """
# Unfortunately we can't determine the file name before
# parsing the XML, so let's build up the source file
# content in string buffer
self.pinmuxHeaderBuffer = CompatStringIO()
self.pinmuxConfigB... |
def get_default_pinmux_regs(self):
""" Set default pinmux values """
p = collections.OrderedDict()
p['EMACIO0'] = 0
p['EMACIO1'] = 0
p['EMACIO2'] = 0
p['EMACIO3'] = 0
p['EMACIO4'] = 0
p['EMACIO5'] = 0
p['EMACIO6'] = 0
p['EMACIO7'] = 0
... | This code initializes an HPSGrokker object to process High-Performance System (HPS) configuration data from an XML file. It sets input/output directories, parses the HPS XML file, initializes variables for pinmux configurations, peripheral streams, and buffer storage. The `createFilesFromHPS()` method is invoked to gen... | def __init__(self, inputDir, outputDir, hpsFileName='hps.xml'):
""" HPSGrokker initialization """
self.inputDir = inputDir
self.outputDir = outputDir
self.hpsInFileName = inputDir + os.sep + hpsFileName
self.dom = xml.dom.minidom.parse(self.hpsInFileName)
self.peripheralS... |
def precision(self, y, y_pred, c=0):
true_positives = np.sum((y == c) & (y_pred == c))
false_positives = np.sum((y != c) & (y_pred == c))
if true_positives + false_positives == 0:
return 0
else:
return true_positives / (true_positives + false_positives)
def recall... | This function generates a classification report as a pandas DataFrame, calculating precision, recall, and F1-score for each class (0 to k-1), along with accuracy, macro-averaged, and weighted-averaged metrics. It uses custom methods like precision(), recall(), and f1_score() for individual classes and their aggregated ... | def classification_report(self, y, y_pred):
cols = ["precision", "recall", "f1-score"]
idx = list(range(self.k)) + ["accuracy", "macro", "weighted"]
report = [[self.precision(y, y_pred, c),
self.recall(y, y_pred, c),
self.f1_score(y, y_pred, c)] for c in ra... |
def avalanche_separate(grid, coordinates_left, coordinates_right, grid_size_number, index_of_site):
for single_coordinate_left in coordinates_left:
grid, index_of_site = avalanche_separate_left(grid, single_coordinate_left, grid_size_number, index_of_site)
for single_coordinate_right in coordinates_righ... | This function simulates an avalanche process by recursively updating a grid. It uses 'avalanche_separate' to modify the grid and 'find_coordinates' to detect new regions needing processing. The recursion continues until no more coordinates are found, ensuring the grid reaches a stable state. | def avalanche(grid, coordinates_left, coordinates_right, grid_size_number, index_of_site):
grid, index_of_site = avalanche_separate(grid, coordinates_left, coordinates_right, grid_size_number, index_of_site)
coordinates_left, coordinates_right = find_coordinates(grid)
if not (coordinates_left == [] and co... |
def shorten_liberty_for_groups(self, point, color):
"""
Remove the liberty from all belonging groups.
For opponent's groups, update consequences such as libertydict, winner or endangered group.
endangered groups for self will be updated in put_stone() after self groups are merged
... | This function places a stone on a specified point in a board game (likely Go), checks move legality, updates game state by adjusting groups' liberties, handles captures, merges or creates new stone groups, tracks endangered groups, switches player turns, and determines game outcomes like victory by lack of legal moves. | def put_stone(self, point, check_legal=False):
if check_legal:
if point not in self.legal_actions:
print('Error: illegal move, try again.')
return False
# If more than 400 moves (which shouldn't happen), print the board for debug
if self.counter_move >... |
def build_tree(data):
if len(data) == 0:
return None
if len(data) == 1:
node = KDNode()
node.split = data[0]
return node
max_var = 0
max_var_ind = 0
row_count = len(data)
# find max variance of attributes
for index in range(len(data[0]) - 1):
column... | The code implements a k-Nearest Neighbors (k-NN) classifier using a k-d tree for efficient nearest neighbor search. It builds a k-d tree from training data, then for each test point, traverses the tree to collect nearest neighbors, stores their labels in a heap, and determines the majority vote for classification. The ... | def knn_kdtree(data, test):
# training
root = build_tree(data)
# predict
for point in test:
path = walk_tree(root, point)
dist_heap = []
visited = set()
max_dist = 0
max_dist, dist_heap = visit(path, point, max_dist, dist_heap, visited)
# for node in reve... |
def solve_captcha_if_any():
try:
print(' + detecting capcha ...')
is_captcha_present = captcha_wait.until(expected_conditions.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[name^='a-']")))
except Exception:
is_captcha_present = False
if is_captcha_present:
... | The main task of the code is to scrape vendor data from a website by navigating to vendor links, handling CAPTCHA and modals, locating and clicking an "info" button, extracting structured vendor information, and logging successes/failures. It appends valid data to a results list while tracking errors for failed scrapes... | def scrape_vendor(vendor):
# We set the user agent to random one on each request so we don't get are you a robot capcah
driver.execute_cdp_cmd("Network.setExtraHTTPHeaders", {"headers": {"User-Agent": f"{user_agent_provider.random}"}})
# here we can set the xpath of the damn pesky modal we want to delete f... |
def calc_index(node, c):
ind = (node.yawind - c.minyaw) * c.xw * c.yw + \
(node.yind - c.miny) * c.xw + (node.xind - c.minx)
if ind <= 0:
print("Error(calc_index):", ind)
return ind
def calc_cost(n, h_dp, goal, c):
ind = (n.yind - c.miny) * c.xw + (n.xind - c.minx)
if ind not in h_... | (Hybrid A* algorithm is used for path planning in a 2D space with obstacles. It combines A* search with dynamic programming to find a collision-free path from a start to a goal position, considering grid resolution (xyreso) and yaw angle resolution (yawreso). The function returns the planned path or empty lists if no p... | def hybrid_a_star_planning(start, goal, ox, oy, xyreso, yawreso):
"""
start
goal
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
xyreso: grid resolution [m]
yawreso: yaw angle resolution [rad]
"""
start[2], goal[2] = rs.pi_2_pi(start[2]), rs.pi_2_pi(goal[2]... |
def get_desired_dataset(args):
train_transform, valid_transform, classes, grayscale = utils.data_transforms(args)
if args.dataset == 'CIFAR10':
train_data = dset.CIFAR10(root=args.datapath, train=True, download=True, transform=train_transform)
test_data = dset.CIFAR10(root=args.datapath, train=False, downl... | The main task of the code is to perform neural architecture search (NAS) on a specified dataset by searching for optimal model depth, width, operations, and kernel configurations. It initializes GPU settings, loads data, executes two-stage searches for architecture parameters, constructs the final model with discovered... | def main():
if not torch.cuda.is_available():
logging.info('GPU not available.')
sys.exit(1)
np.random.seed(args.seed)
torch.cuda.set_device(args.gpu)
cudnn.benchmark = True
torch.manual_seed(args.seed)
cudnn.enabled=True
torch.cuda.manual_seed(args.seed)
logging.info('GPU Device = %d' % args.g... |
def move_head(self, command):
if command == 'U':
# move up
self.head = Coordinates(self.head[0], self.head[1] - 1)
elif command == 'D':
# move down
self.head = Coordinates(self.head[0], self.head[1] + 1)
elif command == 'L':
# move left... | The code processes a movement command by repeating the specified number of steps. It saves the original head position, moves the head, updates the tail position based on the original head, marks the tail as visited, and checks for spare room conditions. The main task is to execute a movement command, adjust the snake's... | def submit_command(self, command: Command):
for _ in range(command[1]):
original_head_position = deepcopy(self.head)
self.move_head(command[0])
self.assess_tail_position(original_head_position)
self.set_tail_position_as_visited()
self.assess_spare_room... |
def move_head(self, command):
head = self.lengths[0]
if command == 'U':
# move up
head = Coordinates(head[0], head[1] - 1)
elif command == 'D':
# move down
head = Coordinates(head[0], head[1] + 1)
elif command == 'L':
# move lef... | The code processes a movement command by repeatedly moving the head in a specified direction, updating tail positions for each segment, marking visited positions, and assessing available space, iterating based on the command's second parameter. | def submit_command(self, command: Command):
for _ in range(command[1]):
self.move_head(command[0])
for i, _ in enumerate(self.lengths):
# skip the head
if i > 0:
self.assess_tail_position(i)
self.set_tail_positions_as_visit... |
def reduce_noise(self):
res = [''] * len(self.color_enhancement_adapthisteq(True))
for i, img in enumerate(self.color_enhancement_adapthisteq(True)):
res[i] = cv2.fastNlMeansDenoising(img, dst=None, h=5,
templateWindowSize=7, searchWindowSize=21)... | This code generates side-by-side comparisons of original, preprocessed, and edge-detected images using OpenCV and Matplotlib. For each image in the input set, it applies noise reduction, detects edges via Canny, and displays or saves the trio of images in a 1x3 grid. If save_=True, it saves each comparison as a JPG; ot... | def show_comparison_images(self, save_=False):
images = self.reduce_noise()
for i in range(len(images)):
edges = cv2.Canny(images[i], 100, 200)
plt.subplot(131), plt.imshow(normalize(self.resize()[i]), cmap=plt.cm.bone)
plt.title('Original Image'), plt.xticks([]), plt... |
def validate(self, left: Graph, lhs_to_self_mapping: Dict[int, int]) -> bool:
for lhs_ID, self_ID in lhs_to_self_mapping.items():
if self.labels_dict.get(self_ID) != left.labels_dict.get(lhs_ID):
return False
for left_ID, left_edges in left.outgoing_edges_dict.items():
... | This function applies a graph production by validating the left-hand side (lhs) subgraph, removing it, merging the right-hand side (rhs) graph, adding new edges based on definitions, and saving the updated graph. It checks lhs isomorphism, collects vertices for edge creation, removes the lhs subgraph, merges the rhs, m... | def apply_production(self, production: Production, lhs_to_self_mapping: Dict[int, int]):
"""lhs - left hand side of the production"""
if not self.validate(production.left_graph, lhs_to_self_mapping):
raise ValueError("invalid lhs_to_self_mapping - given subgraph of the start graph not\
... |
def init_data(file_name):
with open(file_name, "r") as f:
lines = f.readlines()[1:]
data = [player.strip().split(",") for player in lines]
data = [player[:3] + list(map(int, player[3:])) for player in data]
return data
def season_insert(root, players, current):
current_season = play... | The code processes a CSV file containing player statistics, inserting seasonal data into a Red-Black Tree (RBT) and printing the tree structure and stats for each season. It initializes player data, constructs an RBT with the first season's data, and iteratively inserts subsequent seasons while printing the tree and se... | def main():
stats = ["Rebs", "Assists", "Points"]
csv_file = sys.argv[1]
players = init_data(csv_file)
root = RBNode(players[0][1], BLACK, players[0][3:], None)
root, current = season_insert(root, players, 0) # first season
print_season(stats, players, root, current)
root.pre_order() # p... |
def handle_extract_entire_line_edge_case(
self,
original_node: cst.CSTNodeT,
updated_node: cst.CSTNodeT,
) -> cst.RemovalSentinel | cst.CSTNodeT:
if self.expr.deep_equals(original_node) and self.is_same_position(node=original_node):
return cst.RemovalSentinel.REMOVE
... | This function handles code transformation during a 'leave' phase by checking if the original node is an expression, then applying specific logic: extracting variables if conditions match, or replacing nodes with variables when applicable. It returns modified nodes, removal flags, or flattening instructions based on the... | def on_leave( # type: ignore
self,
original_node: cst.CSTNodeT,
updated_node: cst.CSTNodeT,
) -> cst.CSTNodeT | cst.RemovalSentinel | cst.FlattenSentinel[cst.CSTNodeT] | cst.Name:
if isinstance(original_node, cst.Expr):
return self.handle_extract_entire_line_edge_case(
... |
def CalcPotentialByDFIRE(predDistMatrix, alpha=1.61, largestDistance=18, useWeight=False, minPotential=-30, maxPotential=30):
#potentials = dict()
## validProbs saves the prob of one atom/residue pair likely have valid coordinates
#validProbs = dict()
cutoff = distCutoffs
rc = min(cutoff[-1], largestDistance) ... | The main task of the code is to load a pickle file containing contact data, compute a potential energy matrix using DFIRE, generate distance constraints via spline interpolation, and save these constraints to specified output files. It processes the 'probs' matrix from the input data, calculates inter-residue potential... | def parse_distance_pickle_file(args):
f = tf.io.gfile.GFile(args.distance, 'rb')
contact_dict = pickle.load(f, encoding='latin1')
#num_res = len(contact_dict['sequence'])
#print("Number of residues: %d" % (num_res))
#print(contact_dict.keys())
#dict_keys(['min_range', 'max_range', 'num_bins', 'domain', 'seq... |
def empty_squares(self, board):
return (board == 0).sum()
def score_state(self, board, player_id, move):
score = 0
score += (self.rowTest(player_id, board, move) + self.diagTest(player_id, board, move))
score -= (self.rowTest(-player_id, board, move) + self.diagTest(-player_id, board, mo... | This function implements the Minimax algorithm with alpha-beta pruning for a board game, evaluating optimal moves by recursively assessing board states. It calculates scores based on game outcomes, empty squares, and heuristic adjustments, while pruning suboptimal branches to improve efficiency. The function returns th... | def minimax_ab(self, board, player_id, depth, alpha, beta, prev_state, prev_move, prev_score):
max_player = self.ID
other_player = -player_id
empty_squares = self.empty_squares(board)
#Cost function for board when time limit reached
if prev_move!= None:
if (time.tim... |
def empty_squares(self, board):
return (board == 0).sum()
def score_state(self, board, player_id, move):
score = 0
score += (self.rowTest(player_id, board, move) + self.diagTest(player_id, board, move))
score -= (self.rowTest(-player_id, board, move) + self.diagTest(-player_id, board, mo... | The code implements the **minimax algorithm with alpha-beta pruning** for a two-player game. It evaluates the best move for the current player by recursively exploring possible game states, considering the opponent's optimal responses. The function checks for terminal states (win/loss/draw), applies heuristic scoring b... | def minimax_ab(self, board, player_id, depth, alpha, beta, prev_state, prev_move, prev_score):
max_player = self.ID
other_player = -player_id
empty_squares = self.empty_squares(board)
if prev_move!= None:
if (time.time() - self.start > 3):
#if depth == 0:
... |
def empty_squares(self, board):
return (board == 0).sum()
def minimax_ab(self, board, player_id, depth, alpha, beta, prev_state, prev_move, prev_score):
max_player = self.ID
other_player = -player_id
empty_squares = self.empty_squares(board)
#Cost function for board when time li... | The code determines the best move for a player in a board game using the minimax algorithm with alpha-beta pruning. If the board is empty, it selects the center as the first move. It calculates the optimal move by evaluating potential game states, considering the player's ID, depth, and heuristic values, then returns t... | def move(self, board):
self.start = time.time()
##If board is empty (you are first move) place in center of board
if self.empty_squares(board) == math.pow(self.BOARD_SIZE, 2):
c = math.floor(self.BOARD_SIZE/2)
return (c, c)
#while True:
# move... |
def empty_squares(self, board):
return (board == 0).sum()
def minimax_ab(self, board, player_id, depth, alpha, beta, prev_state, prev_move, prev_score):
max_player = self.ID
other_player = -player_id
empty_squares = self.empty_squares(board)
if prev_move!= None:
if ... | The code implements a game-playing AI's move selection logic. It uses minimax with alpha-beta pruning to determine optimal moves, with random legal moves for empty boards. It tracks game state, scores, and timing, updating the board and score after each move while adhering to time constraints. | def move(self, board):
self.start = time.time()
empty_board = math.pow(self.BOARD_SIZE, 2)
board_count = self.empty_squares(board)
if board_count == empty_board or board_count == empty_board-1:
self.prev_state = np.zeros((self.BOARD_SIZE, self.BOARD_SIZE), dtype=int)
... |
def initializeFirstGenereation(self):
for i in range(500):
self.env.append(self.genereteDNA())
def isGoalGen(self, gen):
if self.utilityFunction(gen) == 0:
return True
return False
def crossOverAndMutant(self):
for i in range(1, len(self.env), 2):
firs... | The main task of the code is to solve a problem using a genetic algorithm (GA). It initializes a population, iterates through generations, checks if a goal is reached, performs crossover and mutation operations, selects the next generation, and repeats until the goal is found. The loop tracks the number of iterations a... | def solveGA(self):
self.initializeFirstGenereation()
for gen in self.env:
if self.isGoalGen(gen):
return gen
count = 0
while True:
self.crossOverAndMutant()
self.env = self.makeSelection()
count += 1
if self.goal... |
def save(self, board):
self.k += 1
solution = self.reduce_board(board)
if self.k == 1:
self.first_solution = solution
with app.app_context():
add_solution(self.n, solution)
self.solutions.append(solution)
def isSafe(self, board, row, col):
# Chec... | This function recursively solves the N-Queens problem by attempting to place a queen in each row of the current column. If placement is safe, it proceeds to the next column recursively. If no valid placement is found, it backtracks by removing the queen and tries alternative positions. It returns True if a valid config... | def solveNQUtil(self, board, col):
""" base case: If all queens are placed
then return true """
if col == self.n:
self.save(board)
return True
""" Consider this column and try placing
this queen in all rows one by one """
res = False
... |
def jogProtocol(Instruction):
a = [255,1,1,0,0,0,0,0,0,0,Instruction]
sum=0
for i in a[1:]:
sum = sum+i
ck = CheckSumCal(sum)
a.append(ck)
serialPort.write(a)
def acknowledge():
arr = []
# wait = 0
arr = serialPort.read(4)
# if arr != None:
# wait = 1
# print(... | This code listens for keyboard inputs and maps each key press to specific control commands for robotic joints or axes. It continuously checks for keys like 'r', 'f', 't', etc., triggering corresponding functions (e.g., jogProtocol with unique IDs) to adjust joint movements. Pressing 'o' breaks the loop. The function ac... | def KeyPressSerial():
while True:
if keyboard.is_pressed('r'): #j1+
print('r')
jogProtocol(5)
acknowledge()
event()
elif keyboard.is_pressed('f'): #j1-
print('f')
jogProtocol(6)
acknowledge()
event()
... |
def find_closest_centroid(centroids, vote_history):
"""Finds the closest centroid to the rep.
Parameters:
- centroids: a list of centroid vectors
- vote_history: the voting history of the rep
Returns: the index of the closest centroid
"""
closest_dist = 9999999999999
closest_centroid =... | The function performs k-means clustering by iteratively assigning data points to the nearest centroid, recalculating centroids based on group averages, and repeating until centroids stabilize. It returns the final grouping of data points into clusters corresponding to each stabilized centroid. | def kmeans_cycle(data, centroids):
"""Performs cycles of kmeans until the system stabilizes.
Parameters:
- Data: the voting data
- Centroids: The list of centroids in vector form
Returns: The groups of reps about each centroid
"""
# make a list of groups
groups = [[] for x in centroid... |
def _is_multisig_account(self, address: str) -> bool:
horizon_server = self._get_horizon_server()
resp = horizon_server.accounts().account_id(address).call()
return len(resp["signers"]) != 1
def _check_has_vesting_account(self, address: str):
vestingaccounts = self._get_vesting_accounts(... | The function creates a vesting account for a given owner address by generating a new escrow account, setting up initial transactions with a balance and trust line, configuring multi-signature permissions, and submitting necessary Stellar transactions. It checks for existing accounts, avoids multisig addresses, and ensu... | def _create_vesting_account(self, owner_address) -> str:
if self._is_multisig_account(owner_address):
raise j.exceptions.Value("Multisig accounts are not supported")
existing_escrow_address = self._check_has_vesting_account(owner_address)
if existing_escrow_address:
ret... |
def init_twitter():
global api
auth = tweepy.OAuthHandler(params.consumer_key, params.consumer_secret)
auth.set_access_token(params.access_key, params.access_secret)
api = tweepy.API(auth)
def pricer():
with open(params.editable_params_filename) as jsonFile:
data = json.load(jsonFile)
... | The main task of the code is to continuously monitor and update pricing information via Twitter. It initializes Twitter integration, then enters an infinite loop where it repeatedly calls the `pricer()` function to refresh pricing data. The loop pauses for a duration specified in a JSON file (`"update_rate"`) between e... | def main():
init_twitter()
while True:
pricer()
time.sleep(get_from_json_file("update_rate")) |
def compute_hash(self,block):
block_string = json.dumps(block.__dict__, sort_keys=True)
block_string=block_string.encode()
return sha256(block_string).hexdigest()
def proof_of_work(self, block):
block.nonce = 0
computed_hash = self.compute_hash(block)
while not computed_hash.startswith('0' * self.difficulty... | The main task of the code is to mine a new block by validating the first unconfirmed transaction, creating a new block with proof-of-work, adding it to the blockchain, and verifying consistency. If validation fails, the block is discarded. It returns the index of the newly added block or False if no transactions exist ... | def mine(self):
if not self.unconfirmed_transactions:
return False
last_block = self.last_block
trans = self.unconfirmed_transactions[0]
if not VerifySignature(trans[2]+trans[6],trans[4],trans[1]):
return False
new_block = Transaction(index=last_block.index + 1,seller=trans[0],buyer=trans[1],token=trans... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.