dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def deal_in(ref_deck, house, player):
"""
test = ref_deck.blackjack()
player.extend(test)
"""
print(f"---{colors.TURN_COL}Dealing Hands{colors.DEF_COL}---")
for i in range(2):
house.append(eodeck_check(ref_deck.draw_card()))
player.append(eodeck_check(ref_deck.draw_card()... | This code simulates a Blackjack game round, handling card dealing, player/house actions, and outcome determination. It checks for blackjack, busts, and compares hands to decide the result, printing the outcome and returning a value indicating win, loss, or push. | def play(ref_deck):
player_hand = []
house_hand = []
reshuffle_at = (18, 23, 26)
reshuffle_idx = ref_deck.depth-1 if ref_deck.depth < 3 else 2
if ref_deck.remaining_cards() < reshuffle_at[reshuffle_idx]:
print("---New card deck!---")
ref_deck.refresh_stack()
result = 0
dea... |
def put_element(value):
cnt = 81
same = {}
while(cnt != 0):
row = copy.deepcopy(random.randint(0,8))
column = copy.deepcopy(random.randint(0,8))
if(same.get(row) != column and not(fixed[row][column])):
ins = copy.deepcopy(value[row][column])
value[row][co... | The code implements a genetic algorithm to evolve a population of solutions toward a target fitness value (243) over a specified number of generations. It initializes a population, evaluates fitness, selects parents, performs crossover, applies mutation, and iterates until the target is met or the maximum generations a... | def genetic(popul,selection,mutation,max_gen):
global values
global value
global high_fitness
fitness_values = []
gen = 0
#First Generation
for i in range(popul):
fitness_values.append(copy.deepcopy(0))
values.append(copy.deepcopy(put_element(copy.deepcopy(value))))
... |
def bohnel_phi1(pf, nur1, pc=0):
phi1 = (1 - pf - pc) / (1 - nur1 * pf)
return phi1
def bohnel_phi2(pf, nur1, nur2, pc=0):
phi2 = (bohnel_phi1(pf, nur1, pc) ** 2) * nur2 * pf / (1 - pf * nur1)
return phi2
def bohnel_phi3(pf, nur1, nur2, nur3, pc=0):
phi1 = bohnel_phi1(pf, nur1, pc)
phi2 = bohnel... | The function `bohnel_sdt` calculates three scaled values `s`, `d`, and `t` using helper functions `bohnel_phi1`, `bohnel_phi2`, and `bohnel_phi3`. It computes these as `s = F * phi1`, `d = F * phi2 / 2`, and `t = F * phi3 / 6`, returning them as a tuple. The parameters `pf`, `nur1`, `nur2`, `nur3`, and `pc` influence t... | def bohnel_sdt(pf, nur1, nur2, nur3, F=1, pc=0):
phi1 = bohnel_phi1(pf, nur1, pc)
phi2 = bohnel_phi2(pf, nur1, nur2, pc)
phi3 = bohnel_phi3(pf, nur1, nur3, pc)
s = F * phi1 / 1.0
d = F * phi2 / 2.0
t = F * phi3 / 6.0
return s, d, t |
def vpf_phi1_r(pf_r, nur1, n=None):
pf = pf_r[0]
if n is None:
n = len(pf_r)
term1 = 1
for i in range(n):
term1 *= nur1 * pf_r[i]
term2 = 0
for i in range(n):
term3 = 1 - pf_r[i]
for j in range(i + 1, n):
term3 *= nur1 * pf_r[j]
term2 += term... | The function computes a mathematical expression `phi3` by combining two terms: `term1`, which is a product of `nur1` and elements from `pf_r`, and `term2`, which involves nested loops to accumulate complex products of `pf_r` elements, recursive calls to `vpf_phi1_r` and `vpf_phi2_r`, and coefficients `nur2` and `nur3`.... | def vpf_phi3_r(pf_r, nur1, nur2, nur3, n=None):
pf = pf_r[0]
if n is None:
n = len(pf_r)
term1 = 1
for i in range(n):
term1 *= nur1 * pf_r[i]
term2 = 0
for i in range(n):
term3 = nur3 * pf_r[i] * (vpf_phi1_r(pf_r, nur1, n=i) ** 3)
term3 += (
3
... |
def vpf_phi1(pf, nur1, q=0):
n = len(pf)
term1 = 1
for i in range(q, n):
term1 *= nur1 * pf[i]
term2 = 0
for i in range(q, n):
term3 = 1 - pf[i]
for j in range(q, i):
term3 *= nur1 * pf[j]
term2 += term3
phi1 = term1 * bohnel_phi1(pf[-1], nur1) + te... | This function computes a complex mathematical expression involving products and combinations of other functions (vpf_phi1, vpf_phi2, bohnel_phi3) on the input list `pf` with parameters `nur1`, `nur2`, `nur3`, and `q`. It calculates two terms: `term1` as a product of weighted elements from index `q` to end, and `term2` ... | def vpf_phi3(pf, nur1, nur2, nur3, q=0):
n = len(pf)
term1 = 1
for i in range(q, n):
term1 *= nur1 * pf[i]
term2 = 0
for i in range(q, n):
term3 = nur3 * pf[i] * (vpf_phi1(pf, nur1, i + 1) ** 3)
term3 += (
3
* nur2
* pf[i]
* v... |
def rank_sentences(self, text, k=0.5, min_sentence_len=4, m=0.3):
text_info = self.process_text(text)
sentences = [(i, sentence) for i, sentence in enumerate(text_info['sentences'])]
selected_sentences = []
words_in_summ = set()
n_selected = 0
while n_selected < text_info... | This code ranks sentences in a text by scores, groups them into paragraphs, and returns both scored sentences and structured paragraphs. It uses parameters like n (number of phrases), k (ranking factor), and m (threshold) to control grouping and filtering, ensuring paragraphs meet minimum length requirements. | def rank_phrases(self, text, n, k=1, min_sentence_len=4, m=0.3):
sentences_with_scores, start_indices_of_paragraphs = self.rank_sentences(text, k, min_sentence_len, m)
groups, start_indices_of_paragraphs = self.group_sentences(sentences_with_scores, start_indices_of_paragraphs)
paragraphs = self... |
def ReadLinesExcludeEmpty(self):
buffer = ""
ret = []
length = len(self.__text)
for i in range (0,length):
buffer = buffer+self.__text[i]
if self.__text[i] == "\n" :
ret = self.append_exclude_empty_line(ret,buffer)
buffer = ""
... | This code divides a file's lines into blocks based on leading tab counts, ensuring each block starts with the same number of tabs as the first line. It raises errors for invalid formats, appending lines to blocks when the next line's tab count changes. Blocks are split when the current line's tab count matches the init... | def DivideByBlock(self):
block_buffer = ""
line_buffer = ""
prefetch_line_buffer = ""
ret = []
lines = self.ReadLinesExcludeEmpty()
if len(lines)==0:
raise ValueError("Empty file?!")
tab_num = self.CountPrevTab(lines[0])
length = len(lines)
... |
def evaluate_board(board_matrix, color, move, pieces, captured_piece):
# Initialize the total evaluation score
score = 0
# Evaluate mobility score
mobility_score = evaluate_mobility(board_matrix, color, pieces)
mobility_score = round(mobility_score, 1)
# print(f"Mobility Score: {mobility_score}... | The code implements the Minimax algorithm with alpha-beta pruning for a board game. It recursively evaluates board states by simulating moves, alternating between maximizing and minimizing players, and prunes suboptimal branches to optimize performance. The function returns the best evaluation value and associated colo... | def minimax(board_matrix, depth, is_maximizing_player, alpha, beta, color, move, pieces, captured_piece):
# Base case: if depth is 0, reaching the bottom of the minimax tree, evaluate the board and return the evaluation
if depth == 0:
return evaluate_board(board_matrix, color, move, pieces, captured_pie... |
def generate_moves(board_matrix, color, pieces):
moves = []
for col in range(8):
for row in range(8):
piece_symbol = board_matrix[row][col]
# Check if the piece_symbol is of the same color as specified
if piece_symbol != ' ' and (piece_symbol.islower() == (color == '... | The function `find_best_move` determines the optimal move in a board game using a minimax algorithm with alpha-beta pruning. It evaluates each possible move by combining a short-term capture score with a long-term minimax evaluation, prioritizing moves that maximize/minimize total value based on the player's color (whi... | def find_best_move(board_matrix, depth, color, pieces):
best_move = None
best_eval = float('inf') if color == 'white' else float('-inf') # Black max, White min
best_short_term_eval = 0
best_long_term_eval = 0
# base_eval_color = None
moves = generate_moves(board_matrix, color, pieces)
prin... |
def player_hit(self, window, buttonNext, buttonHit, buttonStand, playerFrame):
# get the player from the game
player = self.game.get_player()
# player hits from the game deck
player.hit(self.game.get_deck())
# check if the player's total is greater than 21
if player.get... | The code creates a GUI window for a Blackjack game using Tkinter. It displays the player's bank balance, their hand, and the dealer's partial hand (only the second card visible). Buttons for 'Hit', 'Stand', and 'Next' are added to control gameplay. The window includes event handlers for closing and game actions, with a... | def create_game_window(self, dealer=False):
gameWindow = tk.Tk()
gameWindow.title("Black Jack")
gameWindow.geometry("400x700+500+20")
gameWindow.configure(bg=BGCOLOR)
# label showing how much money you have in the bank
bankLabelText = f"You have ${self.game.get_player()... |
def __retrieve_database_dir(self):
self.__database_path = None
database_path = os.getenv("CURRENT_PROJECT_DIR")
# If database not found close the window
if database_path is None:
self.__stop_and_display_error()
return False
else:
database_path ... | This code initializes an ABC Export tool in Maya, loading the AbcExport plugin, configuring preferences, setting frame ranges, UI dimensions, and retrieving ABC data for export. It sets up the window properties, creates the UI, and prepares parameters for exporting Alembic files, ensuring the tool functions as a top-le... | def __init__(self, prnt=wrapInstance(int(main_window), QWidget) if main_window is not None else None):
super(ABCExport, self).__init__(prnt)
pm.loadPlugin('AbcExport', quiet =True)
# Common Preferences (common preferences on all tools)
self.__common_prefs = Prefs()
# Preference... |
def render_base(self, screen: pygame.Surface):
for pos in self.grid_indexer():
color = self.grid[pos]
self.render_grid_rect(screen, pos, color)
def render_glows(self, screen: pygame.Surface):
for pos in self.grid_indexer():
glow_time = self.glows[pos]
if g... | The code renders multiple visual elements on a Pygame surface in sequence: base elements, glows, visited paths, found paths, and arrows, to update the game's display with layered graphical components. | def render(self, screen: pygame.Surface):
self.render_base(screen)
self.render_glows(screen)
self.render_visited(screen)
self.render_found_path(screen)
self.render_arrows(screen) |
def onClient(fileName):
fileDirectory = [clientDirectoryString, fileName]
fileDirectory2 = ''.join(fileDirectory)
f = open(fileDirectory2, "r")
contents = f.read()
print (contents)
edit = raw_input("Do you want to edit? yes or no")
if edit == 'yes':
f = open(fileDirectory2, "w")
... | The function `Proxy` determines the appropriate directory to access a file by checking if the file exists in the `clientDirectory`, `cache`, or default directory. It constructs a `.txt` file name from the input, then routes the request to `onClient`, `directoryConnect2`, or `directoryConnect` based on the file's locati... | def Proxy(fileName1):
#fileName1 = raw_input("Enter the name of the file you want access to: ")
fileName2 = [fileName1, '.txt']
fileName = ''.join(fileName2)
if fileName in clientDirectory:
onClient(fileName)
elif fileName in cache:
directoryConnect2(fileName)
else:
... |
def remove_quantity(request):
coffees = Coffee.objects.all()
ctx = {'coffees': coffees}
# print("We are in coffee")
coffee = request.POST.get('remove')
print(coffee)
cart = request.session.get('cart')
if cart:
quantity = cart.get(coffee)
print(quantity)
if quantity >... | The main task of the code is to handle a user's cart functionality by processing 'add' or 'remove' actions, retrieving cart items from the session, calculating quantities and total prices, and rendering the cart page with dynamic product data and totals. | def cart(request):
remove = request.POST.get('remove')
# print("Remove:",remove)
add = request.POST.get('add')
# print("Add:",add)
if remove:
remove_quantity(request)
if add:
add_quantity(request)
ids = list(request.session.get('cart').keys())
if 'null' in ids:
i... |
def get_trillium_amt(driverwait, prev=None):
if prev is None:
return float(driverwait.until(
EC.presence_of_element_located((By.XPATH, "//p[text()='Trilium Balance']/parent::div/p"))).text)
checkcount = 0
while True:
checkcount += 1
trilamt = driverwait.until(
... | The code automates mining and claiming Trillium in a game using a browser driver. It tracks mined amounts, handles failures, and logs data to a database. The loop attempts mining, checks claimability, updates metrics, and inserts records. If failures exceed a threshold, it exits. | def mine(walletid, driver, driverwait):
sql_obj = sq()
# MINE-LOOP
uid = str(uuid.uuid4())
start = time.time()
startamt = get_trillium_amt(driverwait)
minedamt = 0.0
deltaamt = 0.0
curramt = 0.0
failcount = 0
failtrys = 5
print(f'Mining started!! | Start : %5.4f' % startamt... |
def get_trillium_amt(driverwait, prev=None):
if prev is None:
return float(driverwait.until(
EC.presence_of_element_located((By.XPATH, "//p[text()='Trilium Balance']/parent::div/p"))).text)
checkcount = 0
while True:
checkcount += 1
trilamt = driverwait.until(
... | The function `mine_one` automates mining and claiming Trillium in a loop using a browser driver. It tracks failures, retries up to 5 times, and returns 'OOM' with resource data if failed. If mining/successful claiming occurs, it returns 'MINED' with the amount mined and current balance. It checks mining eligibility, at... | def mine_one(walletid, driver, driverwait):
# MINE-LOOP
startamt = get_trillium_amt(driverwait)
failcount = 0
failtrys = 5
while True:
if failcount > failtrys:
resource_p = get_resource_amount(driverwait)
return 'OOM', resource_p
if can_mine(driver):
... |
def load_level():
global game_level,enemyTotal,enemyGroup,spriteGroup
# initialize some covid shaped enemy when score is lower than 10
if (game_level == 1):
enemyGroup.empty()
enemyTotal = int(8 / game_level)
for i in range(enemyTotal):
e = Enemy(enemy_covidIMG)
... | The code initializes a game loop for a shooter game, managing player, enemies, bullets, and bonuses. It handles level progression based on score, processes user input (including pause), checks collisions, updates game elements, and renders the screen at 60 FPS. The loop transitions to game over, scoreboard, or main men... | def game_play():
global level,game_level,score,enemyTotal,IS_PAUSE
IS_PAUSE=False
#create a player object and add it to lists
game_level=level
#pause_button = ButtonText("PAUSE", None, 50, WHITE, w-200, 20)
pause_button = ButtonImage(pauseIMG, 50, 50, w-200, 20)
score=0
enemyTotal=8... |
def healthbar(self):
pygame.draw.rect(screen,RED,(100,100,self.current_health/self.health_ratio,25))#1st=pygame screen;2nd=RGB color;3rd,4th=icon location in screen;5th,6th=icon width, height
pygame.draw.rect(screen,WHITE,(100,100,self.health_bar_length,25),1)#last input is to click a border around the ... | This code updates a game object's state by managing health display, shooting, collision detection, respawn logic with a 2-second delay, bullet power-up timer, and player movement based on keyboard input while restricting movement within screen boundaries. | def update(self):
self.healthbar()
self.heart(100,30)
self.shoot()
self.hit_player()
self.hit_bonus()
#set a timer starting now comparing to the respawn time, after 2 seconds, show player image
current_time=pygame.time.get_ticks()
if self.respawn ... |
def loadAudio(audioFileName):
pygame.mixer.music.load(os.path.join('Material','Audio',audioFileName))
pygame.mixer.music.set_volume(volume)
pygame.mixer.music.play(-1)
def main_menu():
play = Button("PLAY", None, fontSize,BLACK,w / 2, 350,WHITE, ButtonLength, ButtonWidth)
scoreboard = Button("SC... | This code manages a game loop that transitions between different scenes (main menu, game play, scoreboard, options, game over) by loading appropriate audio files and calling corresponding functions. It continuously checks the current scene, updates audio, and handles user interactions until the quit scene is reached, a... | def Main():
#music = pygame.mixer.music.load(os.path.join('Material','Audio',"Music_menu.mp3"))
#pygame.mixer.music.play(-1)
scene = PAGE_MAIN
while True:
#clock.tick(FPS)
if scene is None or scene == PAGE_MAIN:
loadAudio("Music_menu.mp3")
#pygame.mixer.music.pla... |
def initialize_parameters_deep(layer_dims):
parameters = {}
L = len(layer_dims)
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l - 1]) * 0.05
parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
assert(parameters['W' + str(l)].... | This code implements a deep neural network training process using gradient descent. It initializes parameters, iteratively performs forward and backward propagation to compute gradients, updates parameters, and visualizes the cost over iterations. The function returns the trained parameters after completing the specifi... | def L_layer_model(X, Y, layers_dims, learning_rate = 0.0005, num_iterations = 3000, print_cost=False):
costs = []
parameters = initialize_parameters_deep(layers_dims)
for i in range(0, num_iterations):
AL, caches = L_model_forward(X, parameters)
cost = compute_cost(AL, Y... |
def raw_vars(self, play, host, hostvars):
if 'raw_vars' not in hostvars:
return
raw_vars = Templar(variables=hostvars, loader=play._loader).template(hostvars['raw_vars'])
if not isinstance(raw_vars, list):
raise AnsibleError('The `raw_vars` variable must be defined as a ... | This function configures host variables and adjusts group priorities during Ansible play execution. It retrieves the 'env' variable from the play, identifies the corresponding inventory group, and sets its priority to 20. For each host in the play, it populates host-specific variables like SSH arguments, CLI options, a... | def v2_playbook_on_play_start(self, play):
env = play.get_variable_manager().get_vars(play=play).get('env', '')
env_group = next((group for key,group in iteritems(play.get_variable_manager()._inventory.groups) if key == env), False)
if env_group:
env_group.set_priority(20)
f... |
def make_cfg(settings):
sim_cfg = hsim.SimulatorConfiguration()
if "enable_physics" in settings.keys():
sim_cfg.enable_physics = settings["enable_physics"]
else:
sim_cfg.enable_physics = False
if "physics_config_file" in settings.keys():
sim_cfg.physics_config_file = settings["ph... | The code generates and saves sensor observations (color, depth, semantic) for multiple scenes/rooms by randomly placing agents in specified regions, rendering environments, and storing data in the output folder. It uses Habitat-Sim to simulate agent positions, captures observations, and saves them with metadata, repeat... | def generate(self, out_folder, split_name, frames_per_room=100):
settings = {}
print(out_folder)
settings['width'] = self._width
settings['height'] = self._height
settings["sensor_height"] = 0
settings["color_sensor"] = True
settings["depth_sensor"] = Tru... |
def grab_files(data_dir = '/media/moor-data/tablet/hdf', prefix = 'chur', start_date_str = '20230121'):
file_names = [f for f in os.listdir(data_dir) if f.startswith(prefix+'20')]
file_names_filtered = []
for name in file_names:
date_str = name.split('_')[0].replace(prefix, '')
if date_str... | The function `make_pred` processes subject data by loading files, constructing dataframes, and extracting summary statistics. It prepares a prediction input by selecting the last row, removing irrelevant columns, and optionally adding a difficulty parameter. The model then predicts based on this processed data, returni... | def make_pred(prefix, model, difficulty=None):
subj, subj_file_names_sorted = grab_files(show=False, prefix = prefix)
subj2 = build_hdf_df(subj, subj_file_names_sorted)
subj3 = build_trial_df_from_hdf_df(subj2)
X = add_hdf_summary_stats(subj2, subj3)
X_row = X.iloc[[-1]]
X_row... |
def trader():
# remove coin pairs from position file not in accumulation or bullish phase -> coinpairByMarketPhase_BUSD_1d.csv
remove_coins_position()
# read position, orders and bestEma files
read_csv_files()
# sort positions by performance rank
df_positions.sort_values(by=['performance_rank... | The main task of the code is to execute trading operations, log orders to a CSV file, summarize open positions, send position updates via Telegram, check position limits, and report execution time. It processes trading data, formats position details, and communicates results through messaging, ensuring transparency and... | def main():
trader()
# add orders to csv file
df_orders.to_csv('orders'+str(gTimeFrameNum)+gtimeframeTypeShort+'.csv', mode='a', index=False, header=False)
# positions summary
df_current_positions = get_open_positions(df_positions)
df_cp_to_print = df_current_positions.drop(columns=['pos... |
def _smart_dim(tensor: tf.Tensor, i: int):
"""Static or dynamic size for dimension `i`."""
static_shape = tensor.shape
dynamic_shape = tf.shape(tensor)
return (static_shape[i].value if hasattr(static_shape[i], 'value')
else static_shape[i]) or dynamic_shape[i]
def double_stft(signal: tf.Tensor, frame_... | The function applies a scalar complex filter in the double Short-Time Fourier Transform (STFT) domain to filter an input signal. It computes STFTs of the input and target signals, derives a filter from their spectral characteristics, applies the filter to the input's STFT, and reconstructs the filtered signal using inv... | def filter_in_double_stft(
input_signal: tf.Tensor, target_signal: tf.Tensor, frame_length: int = 256,
frame_step: int = 16, meta_frame_length: int = 256,
meta_frame_step: int = 32, nfft: Optional[int] = None,
meta_nfft: Optional[int] = None, frame_skip: int = 10,
near_all_pass_alpha: float = 0.7) -... |
def _smart_dim(tensor: tf.Tensor, i: int):
"""Static or dynamic size for dimension `i`."""
static_shape = tensor.shape
dynamic_shape = tf.shape(tensor)
return (static_shape[i].value if hasattr(static_shape[i], 'value')
else static_shape[i]) or dynamic_shape[i]
def _enclosing_power_of_2(input_len: Unio... | The function calculates an FIR multitap filter that minimizes the L2 norm between the filtered input signal and the target signal, using FFT-based correlation and matrix solvers. It supports real/complex signals, frame skipping, diagonal loading, and fixed filter constraints, returning the optimal filter coefficients (... | def calculate_multitap_filter(input_signal: tf.Tensor, target_signal: tf.Tensor,
frame_skip: int = 0,
filter_support_start: int = 0,
filter_len: int = 10,
diagload: float = 0.1,
... |
def read_wav(wav_path: str, start: float, duration: float) -> np.ndarray:
audio, sr = librosa.load(wav_path, sr=None, mono=False, offset=start,
duration=duration)
if sr != SAMPLE_RATE:
raise ValueError(f'{wav_path}: expected sr={SAMPLE_RATE}, got {sr}.')
return audio
def filter_with... | This function processes a CSV row to generate audio and image data for a machine learning example by combining filtered headset and microphone signals. It reads audio files from the AMI dataset, applies filtering to separate speech from noise, and constructs arrays for receiver audio, reverberant source images, and ane... | def row_to_example_with_filtering(
row: Mapping[str, Any],
ami_directory: str,
mic_name: Optional[str] = 'Array1-01',
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Create data for an example from a row of the mixing CSV.
Args:
row: row of CSV as dict.
ami_directory: path of downloaded AMI ... |
def _smart_dim(tensor: tf.Tensor, i: int):
"""Static or dynamic size for dimension `i`."""
static_shape = tensor.shape
dynamic_shape = tf.shape(tensor)
return (static_shape[i].value if hasattr(static_shape[i], 'value')
else static_shape[i]) or dynamic_shape[i]
def _stft(signal: tf.Tensor, frame_length... | This function filters an input signal in the multi-frame STFT domain to closely approximate a target signal. It computes the STFT of both signals, derives a multi-tap filter using constrained optimization, applies the filter, and converts the result back to the time domain. The filter enforces near-all-pass constraints... | def filter_in_multi_frame_stft(
input_signal: tf.Tensor, target_signal: tf.Tensor, frame_length: int = 256,
frame_step: int = 64, nfft: Optional[int] = None,
near_all_pass_alpha: float = 0.7,
near_all_pass_iterations: int = 1, filter_support_start: int = 0,
filter_len: int = 10, frame_skip: int = 1,... |
def calculate_multitap_filter(input_signal: tf.Tensor, target_signal: tf.Tensor,
frame_skip: int = 0,
filter_support_start: int = 0,
filter_len: int = 10,
diagload: float = 0.1,
... | The code filters an input signal to approximate a target signal in the time domain by projecting the target onto a subspace spanned by time-delayed versions of the input. It computes a multitap filter using linear algebra methods, applies constraints for stability (e.g., magnitude clipping), and uses this filter to gen... | def filter_in_time_domain(input_signal: tf.Tensor, target_signal: tf.Tensor,
filter_support_start: int = 0,
filter_len: int = 100,
near_all_pass_alpha: float = 0.0,
near_all_pass_iterations: int = 1,
... |
def filter_in_time_domain(input_signal: tf.Tensor, target_signal: tf.Tensor,
filter_support_start: int = 0,
filter_len: int = 100,
near_all_pass_alpha: float = 0.0,
near_all_pass_iterations: int = 1,
... | The main task of the code is to find and apply the optimal filter that minimizes the difference between an input signal and a target signal. It supports multiple methods (time-domain, STFT-based, double-STFT) to design filters, adjusting parameters like filter length, stability constraints, and domain-specific settings... | def filter_with_best_filter(input_signal: tf.Tensor,
target_signal: tf.Tensor,
method: str = 'time_domain',
filter_support_start: int = 0,
filter_len: int = 100,
near_all_pass_alph... |
def _slide_left_and_merge(self, board):
"""Slide tiles on a grid to the left and merge."""
result = []
score = 0
for row in board:
row = np.extract(row > 0, row)
score_, result_row = self._try_merge(row)
score += score_
row = np.pad(np.array(result_row), (0, self.width - len(re... | The code processes a game move by rotating the board according to the given action, sliding and merging tiles, rotating the board back to original orientation, placing a new tile, updating the score, and returning the updated board state, reward, game status, and an empty dictionary. | def step(self, action: int):
"""Rotate board aligned with left action"""
# Align board action with left action
prevBoard = self._board.copy()
rotated_obs = np.rot90(self._board, k=action)
reward, updated_obs = self._slide_left_and_merge(rotated_obs)
self._board = np.rot90(updated_obs, k=4 - act... |
def extractNumFromBuffer(clientSocket):
buffer = b''
while (True):
msgByte = clientSocket.recv(1)
if (msgByte == b'_'):
break
buffer = buffer + msgByte
return int(buffer.decode())
def recv_file_0(clientSocket, file_name):
f = open(file_name, "ab+")
while (Tr... | This function connects to a simulator server using a socket, sends a student-specific handshake message, waits for a confirmation reply (0), then receives a file based on the specified mode (0, 1, or 2) from the server. It handles different file-receiving protocols depending on the mode parameter and raises an error fo... | def connect_to_simulator(student_key, mode, ip_address, port, file_name):
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((ip_address, port))
handshake_message = ("STID_" + student_key + "_C").encode()
clientSocket.send(handshake_message)
print("CLIENT: ", handshake_message)
rep... |
def extractQueueNum(serverSocket):
buffer = b''
while (True):
msgByte = serverSocket.recv(1)
if (msgByte == b'_'):
break
buffer = buffer + msgByte
return int(buffer.decode())
def send_file_0(serverSocket, file_name):
filesize = os.path.getsize(file_name)
prin... | The code connects to a simulator server using a socket, sends a handshake message with a student key, waits for a queue confirmation (until reply 0), then transmits a file via one of three modes (0, 1, 2) using corresponding functions. It raises an error for invalid modes. | def connect_to_simulator(student_key, mode, ip_address, port, file_name):
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.connect((ip_address, port))
handshake_message = ("STID_" + student_key + "_S").encode()
serverSocket.send(handshake_message)
print("SERVER: ", handshake_message)
rep... |
def CheckNumSect():
parser = configparser.ConfigParser()
parser.read('convert_input.ini')
i=1
for sect in parser.sections():
i+=1
return i
def ShowAllSect():
parser = configparser.ConfigParser()
parser.read('convert_input.ini')
i = 1
print("All sections in flie...")
for se... | The main task of the code is to read a configuration file ('convert_input.ini'), check the number of sections, display all sections, and iterate through each section using a loop. It initializes a counter, processes each section sequentially, and prints the counter value during each iteration to track progress. | def ReadIndex():
parser = configparser.ConfigParser()
parser.read('convert_input.ini')
a = CheckNumSect()
ShowAllSect()
c=0
print("a: ",a)
while c<a :
EachSect(c)
print("c: ",c)
c+=1 |
def prepare_data(data: np.ndarray, timestamps: List[datetime.datetime]) -> np.ndarray:
# Create a dataframe of timestamps and data
df = pd.DataFrame({'date': timestamps, 'count': data})
# Convert the date column to datetime
df['date'] = pd.to_datetime(df['date'])
# Create time features
df = Time... | The main task of the code is to create a web application for forecasting receipt counts using user-selected models. It allows users to input historical data, choose a forecasting model (e.g., Rolling Average, Linear Regression), and visualize historical data alongside predicted values. The app generates monthly aggrega... | def app():
"""
This function runs the Forecasting App.
It allows the user to choose a model type, start time for the forecast, and historical data.
It then prepares the data, generates predictions using the chosen model, and plots the historical data and predictions.
Finally, it displays the monthl... |
def _max_width_():
"""Decrease left margin of the app; from https://discuss.streamlit.io/t/custom-render-widths/81/8"""
max_width_str = f"max-width: 2000px;"
st.markdown(
f"""
<style>
.reportview-container .main .block-container{{
{max_width_str}
}}
</style>
""",
... | The code's main task is to generate an optimal disc golf road trip route based on user preferences (starting location, travel time, number of destinations). It loads a preprocessed course database, iteratively selects the next course using a defined algorithm, and displays the resulting route with course details via St... | def main():
_max_width_()
file_name = '/home/jon/PycharmProjects/jon-insight-project/jon_insight_project/features/all_courses_database_processed.plk'
df = pd.read_pickle(file_name)
st.title('LocalRoute')
st.header('Planning the ideal disc golf road trip')
# Obtain user preferences
user_... |
def _getConfigFilepath(self, configFilename):
currentDir = mypycommons.file.getThisScriptCurrentDirectory()
configDir = mypycommons.file.joinPaths(currentDir, '../config')
return mypycommons.file.joinPaths(configDir, configFilename)
def _getConfigItems(self):
# Todo: validate config fil... | The code initializes a class by validating input parameters (configFilename and loggerWrapper), loading configuration file details, setting up a logger, and preparing a dictionary to store permit enforcer paths. It ensures required arguments are provided, constructs configuration file paths, retrieves config items, and... | def __init__(self, configFilename: str, loggerWrapper: mypycommons.logger.CommonLogger):
if (not configFilename):
raise TypeError("configFilename not passed")
if (loggerWrapper is None):
raise TypeError("commonLogger not passed")
self._configFilepath = self._getConfigFil... |
def book_hotel(intent_request):
session_attributes = get_session_attributes(intent_request)
complete = get_slot(intent_request, 'Complete')
room_id = get_slot(intent_request, 'RoomId')
from_date = get_slot(intent_request, 'FromDate')
to_date = get_slot(intent_request, 'ToDate')
confirm_email = ... | (dispatch) The code routes incoming intent requests to specific handling functions based on the intent name. It checks the intent name from the request and calls corresponding functions like `book_hotel`, `order_food`, etc., if matched. If no match is found, it raises an exception indicating unsupported intent. The mai... | def dispatch(intent_request):
intent_name = intent_request['sessionState']['intent']['name']
if intent_name == 'BookHotel':
return book_hotel(intent_request)
if intent_name == 'OrderFood':
return order_food(intent_request)
if intent_name == 'BookTour':
return book_tour(intent_re... |
def _check_events(self):
"""Respond to key presses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
elif event.t... | This code runs the main game loop, continuously checking for input events, updating game elements (ship, bullets, target) when the game is active, and redrawing the screen to maintain real-time interaction and visual feedback in a game. | def run_game(self):
"""Start the main loop for the game."""
while True:
#Watch for keyboard and mouse events.
self._check_events()
#Check if game still active first!
if self.stats.game_active:
#Update the ship's position.
self.ship.update()
#Update the bullet's position.
self._update_... |
def print_one_line_atts( self, **override_kwargs ):
"""Prints off (or returns a string) with information about a class in one line
Most child classes will redefine this method with custom attributes to print off"""
default_kwargs = {
'atts': self._ONE_LINE_ATTS,
}
... | The function `print_atts` prints or returns class attributes based on the `how` parameter. It delegates to `print_one_line_atts`, `print_imp_atts`, or `print_all_atts` depending on whether `how` is 'one_line', 'imp', 'all', or numeric equivalents. It uses `**kwargs` for additional parameters, returning the result of th... | def print_atts( self, how: str = 'imp', **kwargs ):
"""Print attributes of the class off, if not printed off, the string will be returned"""
if how == 'one_line' or how == 1: #print the one line atts
return self.print_one_line_atts( **kwargs )
elif how == 'imp' or how == 2: #print... |
def mol(self):
self.try_method(Chem.MolFromSmiles, self.smiles, "mol")
def log_p(self):
self.try_method(Descriptors.MolLogP, self.descriptors["mol"], "log_p")
def molecular_wt(self):
self.try_method(Descriptors.ExactMolWt, self.descriptors["mol"], "mol_wt")
def ha_accepters(self):
self.t... | The main task of the code is to compute and collect various molecular descriptors, including molecular weight, logP, hydrogen bond acceptors/donors, rotatable bonds, heavy atom count, aromatic atoms, and aromatic proportion, likely for cheminformatics analysis or property prediction. | def get_descriptors(self):
self.mol()
self.log_p()
self.molecular_wt()
self.ha_accepters()
self.ha_donors()
self.rotatable_bonds()
self.heavy_atom_count()
self.aromatic_atoms()
self.aromatic_proportion() |
def mol(self):
self.try_method(Chem.MolFromSmiles, self.smiles, "mol")
def log_p(self):
self.try_method(Descriptors.MolLogP, self.descriptors["mol"], "log_p")
def molecular_wt(self):
self.try_method(Descriptors.ExactMolWt, self.descriptors["mol"], "mol_wt")
def ha_accepters(self):
self.t... | The main task of the code is to compute and collect various molecular descriptors for a given molecule. It calculates properties such as molecular weight, logP, hydrogen acceptors/donors, rotatable bonds, heavy atom count, aromatic atoms, and aromatic proportion. These descriptors are commonly used in cheminformatics f... | def get_descriptors(self):
self.mol()
self.log_p()
self.molecular_wt()
self.ha_accepters()
self.ha_donors()
self.rotatable_bonds()
self.heavy_atom_count()
self.aromatic_atoms()
self.aromatic_proportion() |
def get_descriptors(self):
self.mol()
self.log_p()
self.molecular_wt()
self.ha_accepters()
self.ha_donors()
self.rotatable_bonds()
self.heavy_atom_count()
self.aromatic_atoms()
self.aromatic_proportion()
def get_lipinski_tests(self):
self.L... | The code initializes a molecule object by processing a SMILES string, computing chemical descriptors, performing Lipinski rule checks, generating visualizations, and preparing structured JSON data. It removes the 'mol' descriptor and organizes results into a dictionary for output. | def __init__(self, smiles):
self.smiles = smiles
self.errors = {}
self.descriptors = {}
self.get_descriptors()
self.Lipinski = {}
self.get_lipinski_tests()
self.visualizations = {}
self.get_visuals()
del self.descriptors["mol"]
... |
def bar(part,whole):
status = str(part)+'/'+str(whole)
width, height = os.get_terminal_size(0)
width = int(int(width-10)/2)-len(status)
prog = int(float(part/whole)*width)
fin = '='*prog
unf = ' '*int(width-prog)
state('\b'*int(width*2))
state('[%s%s] %s' % (fin,unf,status))
def login(username,password):
drive... | The code defines a function `do(choice)` that automates tasks on a learning management system (Canvas). If `choice == 1`, it creates student accounts with generated usernames, emails, and course enrollments. If `choice == 2`, it deletes student accounts. If `choice == 3`, it simulates student activities across courses.... | def do(choice):
print()
os.system('clear')
if choice == 1:
print('Creating Students (%s min)' % (rate.create*info.students.ammount*info.course_count))
bar(0,info.students.ammount)
driver.get("https://atomicjolt.instructure.com/login/canvas")
login(info.admin.username,info.admin.password)
for i,num in enume... |
def write_memory(self, feature, memory, vision, write_weight=None, write_strength=None, cap_lengths=None):
if write_weight is None:
print("There is no write_weight!")
write_weight = self.calc_weight(feature=feature, memory=memory)
if vision:
# generate visual memory ... | This code processes multimodal features (vision, text) through a memory network, enhancing them via read/write operations. If write_signal is active, it updates memory with new features. Otherwise, it calculates attention weights, reads from memory to enhance features, and computes interaction scores using local attent... | def forward(self, v_feature, img_feature, t_feature, cap_lengths, v_strengths=None, t_strengths=None,
v_weight=None, t_weight=None, frag_weights_img=None, frag_weights_cap=None, write_signal=False):
if write_signal:
# write features back to memory
self.v_memory_new = self... |
def input_box(prompt):
user_input = ""
active = True
while active:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
... | The code gathers and validates a Dungeons & Dragons character's details: name, class, level, skill proficiencies (via a GUI toggle interface), and six ability stats (1-20). It uses input boxes for text/numeric data, Pygame for interactive skill selection, and error handling for stat validation. The function returns all... | def input_character_info():
name = input_box("Enter character's name:")
class_ = input_box("Enter character's class:")
# Level Input
level = get_positive_integer("Enter character's level.:")
# Skill Proficiency Selection
proficiency_buttons = create_proficiency_buttons()
selected_profi... |
def input_character_info():
name = input_box("Enter character's name:")
class_ = input_box("Enter character's class:")
# Level Input
level = get_positive_integer("Enter character's level.:")
# Skill Proficiency Selection
proficiency_buttons = create_proficiency_buttons()
selected_profi... | The main task of the code is to create a character in a game, allowing the user to select a skill, choose a dice roll type (advantage, disadvantage, or normal), and display the dice roll result using Pygame. The program handles user input, updates game state, and renders character information and roll outcomes in a gra... | def main():
name, class_, level, selected_proficiencies, stats = input_character_info()
print("Character information:")
print("Name:", name)
print("Class:", class_)
print("Level:", level)
print("Selected Proficiencies:", selected_proficiencies)
print("Stats:", stats)
rolling = False
... |
def CreateIperfOutput(self,iperfout):
"""create output for iperf run"""
b=iperfout.replace('"','')
b1=b.replace('\'','')
c=b1.replace('[','')
d=c.replace(']','')
e=d.split(',')
self.output=[]
now=datetime.datetime.now()
self.output = [now.strf... | The main task of the code is to execute network speed tests using Iperf or Speedtest CLI commands based on the runmode. It randomly alternates between modes when set to 'Both', captures output, formats results into CSV lines, logs them to a file, and handles debugging. It also checks for a new day to rotate log files. | def Run(self):
"""
this is the heart of the wrapper, using the CLI command
"""
# here we do split
if self.runmode == 'Both':
if self.random_click : # we switch randomly between runmodes
if random.random() >.5 :
self.click ... |
def Run(self):
"""
this is the heart of the wrapper, using the CLI command
"""
# here we do split
if self.runmode == 'Both':
if self.random_click : # we switch randomly between runmodes
if random.random() >.5 :
self.click ... | The main task of the code is to continuously run a loop that uploads data files to Dropbox at specific intervals. It checks conditions like time thresholds and connection status, uploads CSV and text files, generates plots, handles errors, and exits at midnight. The loop also manages file descriptors and ensures data s... | def RunLoop(self):
"""
calls run and forms the loop
"""
counter = 0
while(1):
self.Run()
if(self.ConnectDropBox):
counter = counter + 1
#if (counter==50):
if self.Write... |
def initialize_mediapipe():
"""
Initializing mediapipe sub-modules
"""
# Enables face detection
mpFaceDetection = mediapipe.solutions.face_detection.FaceDetection(MIN_CONFIDENCE_LEVEL)
mpFaceModule = mediapipe.solutions.face_mesh
return mpFaceDetection, mpFaceModule
def calculate_thickness_... | This code detects face shapes in an image using MediaPipe. It identifies faces, extracts facial landmarks, calculates key metrics (width, height, angles), determines face shape (e.g., oval, square), and generates visual outputs with annotations. Results are saved as images, optionally displayed, and return detection in... | def detect_face_shape(input_path: str, display_output: bool = False):
"""
Detecting the shapes of the faces showing within the image
"""
# Initialize the mediapipe module
global combined_img
mpFaceDetection, mpFaceModule = initialize_mediapipe()
# Read Input Image
img = cv2.imread(input... |
def read_shell(command: list | str, shell: bool = False, ignore_error: bool = False, retry: bool = False, _attempts: int = 0, timeout: float | None = None) -> str:
try:
p = subprocess.run(command, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
except subprocess.TimeoutExp... | This code reads PulseAudio module data (sources, sinks, etc.) via shell commands, processes JSON output, applies optional filters, and returns structured data in a dictionary. | def read(self) -> dict | list:
buff = {}
for output in ["source", "sink", "sink-input", "source-output"]:
data = json.loads(read_shell(["pactl", "-f", "json", "list", f"{output}s"]))
if not data:
return buff
if isinstance(data, dict):
... |
def createNextGen(self):
"""
Create next generation from current population
Returns
-------
newPop : list
Contains newly generated population of solutions
"""
self.fitArr = self.computeFitnessArray()
# standardise fitness values
stand... | The code's main task is to run a genetic algorithm (GA) for a specified number of generations, creating subsequent populations and recording their fitness history. It may halt early if no improvement in maximum fitness is observed for 'earlyStop' generations. Finally, it computes and stores the fitness and validity of ... | def evolve(self, generations, earlyStop):
"""
Runs GA for some number of generations
Parameters
----------
generations : int
Number of generations to compute
earlyStop : int
Number of generations after which algorithm is halted if no
i... |
def pack_uint32(x):
return struct.pack('<I', int(x))
def pack_string(string):
return pack_bytes(string.encode('utf-8'))
def pack_map_uint32(m):
m = OrderedDict(sorted(m.items(), key=lambda x: int(x[0])))
ret = pack_uint16(len(m.items()))
for k, v in m.items():
ret += pack_uint16(k) + pack_... | The main task of the code is to serialize an object's attributes—nonce, issued_at, expire_at, room_id, user_id, and privileges—into a byte string by concatenating packed uint32 values, strings, and a map of privileges, preparing the data for transmission or storage. | def pack_msg(self):
m = pack_uint32(self.nonce)
m += pack_uint32(self.issued_at)
m += pack_uint32(self.expire_at)
m += pack_string(self.room_id)
m += pack_string(self.user_id)
m += pack_map_uint32(self.privileges)
return m |
def resample(self):
# print('resampling')
X_re = np.zeros((self.mesh['Nsample'],2))
X_re[:,0:1] = np.random.rand(self.mesh['Nsample'],1)*self.mesh['L']
X_re[:,1:2] = np.random.rand(self.mesh['Nsample'],1)*self.mesh['H']
rho_re = griddata(self.mesh['Xint'].reshape((-1,2)), self.da... | The main task of the code is to train a neural network model using gradient descent. It iterates over epochs, resamples data periodically, computes data and physical losses, updates model parameters, tracks loss history, and implements early stopping based on loss trends. Verbose logging and callback mechanisms are inc... | def trainmodel(self,verbose=False):
for epoch in range(1,self.trainParams['Nepoch']+1):
if epoch%10==0:
self.resample()
if verbose==True:
if epoch%50==0:
print(f"Epoch {epoch}:")
print(f"lr: {self.Model.optimizer.lr.... |
def resample(self):
X_re = np.zeros((self.mesh['Nsample'],2))
X_re[:,0:1] = np.random.rand(self.mesh['Nsample'],1)*self.mesh['L']
X_re[:,1:2] = np.random.rand(self.mesh['Nsample'],1)*self.mesh['H']
rho_re = griddata(self.mesh['Xint'].reshape((-1,2)), self.data['rho_quad'].reshape((-1,1))... | This function trains a machine learning model using gradient descent over multiple epochs. It iterates through batches of data, computes total, data, and physics losses, applies gradients to update model parameters, and tracks loss history. Periodic resampling, early stopping based on loss history, and dataset reshuffl... | def trainmodel(self,verbose=False):
for epoch in range(1,self.trainParams['Nepoch']+1):
if epoch%10==0:
self.resample()
if verbose==True:
if epoch%50==0:
print(f"Epoch {epoch}:")
print(f"lr: {self.Model.optimizer.lr.... |
def proof_of_work(txns, prev_block_hash):
nonce = 0
while not Verification.is_pow_valid(txns, prev_block_hash, nonce):
nonce += 1
return nonce
def add_transaction(self, sender, recipient, amount, signature, timestamp=None):
"""
Create a new open transaction.
... | The code mines a block by performing proof-of-work (POW) on open transactions, validates transaction funds, adds a mining reward transaction, creates a new block with the computed POW and previous block hash, appends it to the blockchain, clears open transactions, saves data, and notifies peers. It returns the mined bl... | def mine_block(self, get_balance):
if self.__public_key is None:
print('WARN: Unable to mine block. Public key is not set')
return None
prev_block_hash = calc_hash(str(self.__chain[-1])) if len(self.__chain) > 0 else ''
# Calculate POW on current open transactions befor... |
def get_power_filepath(workload="", rtl='RocketConfig',
output_format='plot_profile',
filename=None,
power_level='rtl',
module='ChipTop',
inst='ChipTop',
num_toggles=N_... | The function reads a power profile file, parses its data, converts time units to seconds and cycles, extracts power values, and returns lists of cycles and power. It handles missing/empty files by returning empty lists, processes comments to determine time units, and filters valid data lines. | def read_profile_file(workload="towers", rtl='RocketConfig',
module='ChipTop',inst='ChipTop',num_toggles=N_CYCLES,
power_level='rtl', profile_file=None):
if profile_file is None:
profile_file = get_power_filepath(workload, rtl=rtl, module=module,
... |
def get_module_insts_dict(rtl='RocketConfig',root_name='chiptop'):
module_insts_dict = {}
inst_module_dict = get_inst_module_dict(rtl)
for inst,module in inst_module_dict.items():
if module not in module_insts_dict: module_insts_dict[module] = []
module_insts_dict[module].append(inst)
mo... | The code generates a Joules power analysis configuration (YAML) for specified RTL modules/workloads, sets up waveform/report parameters, avoids overwriting existing outputs, and executes commands to run power estimation using Chipyard's build system. It handles module instances, toggle counts, and output formats to gen... | def print_joules_commands(my_workloads,rtl='RocketConfig',
module='ChipTop',
modules=None,
inst=None,
insts=None,
num_toggles=N_CYCLES,
w_data_dict=None,
... |
def get_module_tree(rtl='RocketConfig',
module='ChipTop'):
'''
module - root module of tree
'''
g = nx.DiGraph()
tmh = {}
tmh_file = get_tmh_path(rtl)
with open(tmh_file, 'r') as f:
tmh = json.load(f)
start = tmh['instance_name']
# only keep DigitalTop... | This function identifies and returns the highest power-consuming hardware instances from a given workload's power report. It parses power data from a report file, maps it to a module hierarchy graph, subtracts child instance powers from parents if enabled, and returns sorted instances by power, optionally filtered by c... | def get_highest_power_insts(workload,
rtl='RocketConfig',
module='ChipTop',
num_insts=None,
power_cutoff=None,
subtract_children=True):
g = get_module_tree(rtl=rtl,... |
def get_num_idcodes(rtl='RocketConfig',module='ChipTop'):
with open(get_outfile_path('idcodes','all', rtl=rtl,module=module), 'r') as f:
return int(f.readlines()[0].strip())
def read_toggle_bin_file(workload, rtl='RocketConfig', module='ChipTop'):
bin_file = get_outfile_path('toggles',workload,rtl,modul... | This function aggregates toggle data and power metrics across multiple workloads by reading binary files, aligning signal counts, and concatenating results. It returns combined toggle arrays, normalized power values, and workload boundaries for analysis. | def get_workloads_toggles_jpower(workloads, rtl='RocketConfig',
module='ChipTop', inst='ChipTop', num_toggles=N_CYCLES,
power_level='rtl'):
num_signals = get_num_idcodes(rtl,module=module)
toggles = np.ndarray((0,num_signals))
jpower = []
... |
def call_webhook(req):
if req.webhook:
AsyncRequest('kyc request webhook', req.webhook.url).start()
def aplyid_download_pdf(transaction_id):
try:
headers = {'Aply-API-Key': APLYID_API_KEY, 'Aply-Secret': APLYID_API_SECRET}
r = requests.get(APLYID_BASE_URL + '/biometric/pdf/%s.pdf' % tran... | This function handles an AplyID webhook by verifying a Bearer token, parsing JSON data, and updating a KycRequest status to 'completed' if verification passes. It checks event type and verification status, retrieves the request from the database, validates transaction IDs, updates the record, triggers a webhook, and at... | def aplyid_webhook():
logger.info('aplyid webhook entry')
# check bearer token
auth_header = request.headers.get('Authorization')
if not auth_header:
return abort(403, 'auth header not present')
parts = auth_header.split(' ')
if len(parts) != 2 or parts[0] != 'Bearer' or parts[1] != APLY... |
def login(token, check = True):
send(1)
send(token + b'\n')
L = read()
if b'successfully' in L:
name = read(', have a nice day !\n')[6:-20]
return name
if check: assert False
def send(m, e=0):
io.sendafter(b'> ', wrap(m,e))
def read(m = '\n', d = 0):
r = io.readuntil(wrap(m))... | The code defines a function `delete` that authenticates using a token if provided, sends predefined commands (3 and 'y\n'), and optionally reads data based on the `r` flag. Its main tasks are authentication, command transmission, and conditional data retrieval. | def delete(token = None, r = True):
if token: login(token)
send(3)
send('y\n')
if r: read() |
def login(token, check = True):
send(1)
send(token + b'\n')
L = read()
if b'successfully' in L:
name = read(', have a nice day !\n')[6:-20]
return name
if check: assert False
def update(name = '', desc = '', job = '', assets = 0):
send(1)
send(name, 1)
send(desc, 1)
s... | The code's main task is to send a crafted payload to a target memory address (`addr`) via the `fill` function, which authenticates (`login`), updates a user structure with `gen_user(addr, msg)`, and then logs out. The commented lines suggest intentions to manipulate heap pointers, but the active code focuses on exploit... | def fill(addr, msg = b''):
login(token2)
update(
gen_user(addr, msg),
# flat(7, 7, 0, 7, word_size=16),
# flat(heap_base + 0xA70, heap_base + 0x10),
)
logout() |
def random_policy(self):
"""Create a random policy for each state
Policies map states to actions
"""
return [random.choice(a) for a in self.possible_actions]
def estimate_value_function(self, k, pi):
for i in range(k):
V_i = self.iterate_value_function(pi)
... | The code implements policy iteration for reinforcement learning, alternating between evaluating the current policy's value function and improving the policy using that value. It initializes a random policy, iterates up to 10 times, and in each iteration updates the policy and re-estimates its value. The process aims to... | def policy_iteration(self):
num_iterators = 10
# Initialize policy randomly for all states s
i = 0
pi_0 = self.random_policy()
self.pi.append(pi_0)
# Compute the value of that policy
self.estimate_value_function(self.value_estimation_iterations, pi_0)
... |
def run_dssp(self, overwrite=False):
dssp_pdb_file = f"{self.protein_config.output_prefix}_dssp.pdb"
if overwrite or not Path(dssp_pdb_file).exists():
with open(self.protein_config.pdb_file, "r") as f:
with open(dssp_pdb_file, "w") as f2:
f2.write("HEADER\... | The code generates a 2D protein structure plot using matplotlib, either with coordinate-based positioning or a linear layout. It runs DSSP for secondary structure prediction, retrieves coordinates and elements, creates a figure if no axis is provided, disables axis visibility, and returns the Axes object with rendered ... | def run(self, ax=None, linear=False, y_offset=0, overwrite=False):
"""
Plot 2D portrait of a protein
Parameters
----------
ax
matplotlib ax to use, if None, makes new figure with specified height and width
linear
If True, draws all secondary struc... |
def write_omit_hydrogens_and_water(self, file):
file.write(
f"""read
{self.protein_config.pdb_file}
HETATM-----HOH-- 0,9999, 0.5,0.5,0.5, 0.0
ATOM -H-------- 0,9999, 0.5,0.5,0.5, 0.0
ATOM H--------- 0,9999, 0.5,0.5,0.5, 0.0
"""
)
def write_highlight_residues(self, file):
for chain ... | The code generates a command file for protein structure visualization, writing instructions to omit hydrogens/water, highlight specific residues, define chain colors, and apply transformations, likely for tools like PyMOL or similar molecular graphics software. | def make_command_file(self):
with open(f"{self.protein_config.output_prefix}_illustrate.inp", "w") as f:
self.write_omit_hydrogens_and_water(f)
self.write_highlight_residues(f)
self.write_chain_colors(f)
self.write_end_and_transformations(f) |
def rowNum(self) -> int:
"""
@return Number of rows the spreadsheet has.
"""
return len(self.spreadsheet)
def colNum(self) -> int:
"""
@return Number of column the spreadsheet has.
"""
if self.rowNum() == 0:
return 0
return len(self.spr... | The main task of the code is to add cells to a spreadsheet data structure. It checks if each cell's row and column exist in the spreadsheet, expanding rows and columns as needed, then updates the specified cell with its value. | def buildSpreadsheet(self, lCells: [Cell]): # type: ignore
"""
Construct the data structure to store nodes.
@param lCells: list of cells to be stored
"""
# look at all the cells
# for each cell, check if the row and column are in the spreadsheet
# if so, update t... |
def calibrate_cube(info_sat: dict, raw_cube: np.ndarray, correction_coefficients_dict: dict) -> np.ndarray:
"""Calibrate the raw data cube."""
DEBUG = False
if correction_coefficients_dict["radiometric"] is None:
return raw_cube.copy()
#print("Radiometric Correction Ongoing")
background_v... | The main task of the code is to calibrate and correct a raw hyperspectral data cube by applying radiometric calibration, smile correction, and destriping. It processes the input raw_cube using provided calibration coefficients, adjusts for radiometric errors, corrects spectral smile distortions, and removes striping ar... | def get_calibrated_and_corrected_cube(info: dict, raw_cube: np.ndarray, calibration_coefficients_dict: dict):
""" Calibrate cube.
Includes:
- Radiometric calibration
- Smile correction
- Destriping
Assumes all coefficients has been adjusted to the frame size (cropped and
binned), and that ... |
def get_calibration_coefficients_path(info: dict) -> dict:
csv_file_radiometric = None
csv_file_smile = None
csv_file_destriping = None
if info["capture_type"] == "custom":
# Radiometric ---------------------------------
full_rad_coeff_file = "./data/radiometric_calibration_matrix_HYPS... | The function `run_corrections` calibrates and corrects a datacube using calibration coefficients from the capture configuration, applies spectral coefficients to derive wavelengths, mirrors the datacube for orientation correction, and returns the adjusted datacube along with the wavelength list. | def run_corrections(datacube, capture_config: dict):
calibration_coefficients_dict = get_calibration_coefficients_path(capture_config)
calibration_coefficients = get_coefficients_from_dict(calibration_coefficients_dict,
capture_config)
datacube = ... |
def kingcheck(locator, turn):
moves = []
checked = []
if turn == "white":
for i in kingmove(locator, turn):
if i not in blackOptions:
moves.append(i)
if locator in blackOptions:
checked.append(locator)
if turn == "black":
for i in kingmove(... | The main task of the code is to determine if the king is in check by analyzing potential attacks from an opponent's bishop. It checks the king's movement range, iterates through possible opponent pieces, and calculates bishop-specific attack paths based on directional logic (left/right, above/below). The code updates p... | def blockcheck(locator, turn):
right, left, below, above = 0
new = [24, 3]
attacking = []
kingmoves = kingcheck(locator, turn)
if kingmoves[1]:
if turn == "white":
options = check_options(blackSetup, blackCoords, "black")
for i in range(16):
atk = poss... |
def choose_difficulty():
word_length = input("How long would you like the mystery word to be? ")
while word_length.isnumeric() is False:
print("Sorry, that is not a valid number.")
word_length = input("Please enter a positive whole number: ")
return int(word_length)
def build_word_list(lengt... | The code implements a hangman-style word guessing game where the player selects a difficulty level, guesses letters to uncover a hidden word, and has 20 attempts. It reads words from a file, validates inputs, tracks guesses, and checks for win/loss conditions. The game loops until the player chooses to stop, allowing m... | def run_game():
new_game = True
while new_game is True:
with open("words.txt") as file:
word_string = file.read()
main_word_list = word_string.split("\n")
mystery_length = choose_difficulty()
guessed_word = list(mystery_length * '_')
mystery_list = build... |
def game_start():
'''
returns: boolean indicating whether to start the game
'''
print("WELCOME!\n")
print(
"Is the regular Mystery Word game too simple for you?",
"Are you looking for a bigger challenge?",
"Then step right up, this is the game for you!",
"But be warne... | The code runs a hangman-style game where the user guesses letters to uncover a hidden word. It loads word lists, lets the player choose difficulty, tracks guesses, validates inputs, updates the display, and checks for win/loss conditions. The game loops until completion, then asks if the player wants to restart. | def run_game():
new_game = game_start()
while new_game is True:
with open("words.txt") as file:
word_string = file.read()
main_word_list = word_string.split("\n")
mystery_length = choose_difficulty()
guessed_word = list(mystery_length * '_')
mystery_list... |
def load_cookie(self):
if "Cookie" in self.headers:
self.cookie = Cookies.SimpleCookie(self.headers(["Cookie"]))
else:
self.cookie = Cookies.SimpleCookie()
def end_headers(self):
self.send_cookie()
self.send_header("Access-Control-Allow-Origin", self.headers["Ori... | This code handles POST requests to add new shows to a database by parsing form data and inserting records, and GET requests to retrieve specific shows by ID, returning JSON responses or 404 errors for invalid paths. | def do_POST(self):
self.load_cookie()
if self.path == "/shows":
length = self.headers["Content-Length"]
body = self.rfile.read(int(length)).decode("utf-8")
print("BODY", body)
parse_body = parse_qs(body)
print("PASED BODY:", parse_body)
... |
def load_cookie(self):
if "Cookie" in self.headers:
self.cookie = Cookies.SimpleCookie(self.headers(["Cookie"]))
else:
self.cookie = Cookies.SimpleCookie()
def end_headers(self):
self.send_cookie()
self.send_header("Access-Control-Allow-Origin", self.headers["Ori... | This code handles a PUT request at "/shows" by parsing the incoming form data, extracting show details (name, genre, status, rating, ID), updating the database via the editShows method, and responding with a 201 Created status. If the path is invalid, it triggers a 404 Not Found handler. | def do_PUT(self):
self.load_cookie()
if self.path == "/shows":
length = self.headers["Content-Length"]
body = self.rfile.read(int(length)).decode("utf-8")
print("BODY", body)
parse_body = parse_qs(body)
print("PASED BODY:", parse_body)
... |
def load_cookie(self):
if "Cookie" in self.headers:
self.cookie = Cookies.SimpleCookie(self.headers(["Cookie"]))
else:
self.cookie = Cookies.SimpleCookie()
def end_headers(self):
self.send_cookie()
self.send_header("Access-Control-Allow-Origin", self.headers["Ori... | This function retrieves a specific show from a database using an ID extracted from the request path. It loads a cookie, fetches the show data, and returns it as JSON if found (200 OK), otherwise triggers a 404 Not Found response. | def handleShowsRetriveMember(self):
self.load_cookie()
parts = self.path.split("/")
shows_id = parts[2]
db = showsDB()
shows = db.getOneShow(shows_id)
if shows != None:
self.send_response(200)
self.send_header("Content-Type", "application/json")
... |
def load_cookie(self):
if "Cookie" in self.headers:
self.cookie = Cookies.SimpleCookie(self.headers(["Cookie"]))
else:
self.cookie = Cookies.SimpleCookie()
def end_headers(self):
self.send_cookie()
self.send_header("Access-Control-Allow-Origin", self.headers["Ori... | This function deletes a show entry by ID after verifying user authentication. It loads cookies, checks session validity, retrieves the show from the database, deletes it if found, and returns the deleted data in JSON format with a 200 status. If authentication fails or the show isn't found, it returns appropriate error... | def handleShowsDelete(self, id):
self.load_cookie()
if "userId" not in self.session:
self.send_response(401)
return
parts = self.path.split("/")
shows_id = parts[2]
db = showsDB()
shows = db.getOneShow(shows_id)
if shows != Non... |
def load_cookie(self):
if "Cookie" in self.headers:
self.cookie = Cookies.SimpleCookie(self.headers(["Cookie"]))
else:
self.cookie = Cookies.SimpleCookie()
def handleNotfound(self):
self.send_response(404)
self.end_headers()
self.wfile.write(bytes("not fo... | This code handles DELETE requests by parsing the URL path to determine the target collection and ID. It loads cookies, checks if the collection is "shows", and deletes a specific show by ID if provided. If the collection is invalid or no ID is given, it returns a not-found response. | def do_DELETE(self):
self.load_cookie()
parts = self.path.split('/')[1:]
collection = parts[0]
print(parts)
if len(parts) > 1:
id = parts[1]
else:
id = None
db = showsDB()
if collection == "shows":
if id == None or db.ge... |
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 main task of the code is to manage the BudgetBits expense tracker's core functionality. It handles user login/registration, retrieves user data from a JSON file, and provides an interactive menu for users to view personal info, add expenses, display expenses, or exit. The loop updates user data (budget/expenses) an... | 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 update_priority_queue(priority_queue, to_be_removed, adj_nodes, graph):
for adj_node in adj_nodes:
if adj_node.seen:
continue
if adj_node in priority_queue:
change_parent_if_needed(
adj_node.parent, to_be_removed, adj_node, graph)
else:
... | This code implements the A* algorithm to find the shortest path from a start node to a final node in a graph. It uses a priority queue to explore nodes, prioritizing those with the lowest combined cost (path cost + heuristic). The function returns the path, number of iterations, computation time, and whether a solution... | def a_star(graph, start_node, final_node, heuristic=None):
start = time.time()
priority_queue = [start_node]
to_be_removed = start_node
iterations = 0
while to_be_removed != final_node and len(priority_queue) != 0:
to_be_removed = priority_queue[0]
to_be_removed.seen = True
... |
def adb_shell(self, command):
try:
# Can we use "adb exec-out"?
if self.can_use_exec_out is None:
adb = run_safe([adb_exe, 'exec-out', 'id'],
stdin = DEVNULL, stdout = PIP... | The main task of this code is to initialize an ADB connection, verify device capabilities (e.g., /dev/diag presence and root access), configure `su` command formats, deploy an `adb_bridge` binary, and ensure the Android device meets prerequisites for Qualcomm chip compatibility and root privileges. It handles error che... | def __init__(self):
self.su_command = '%s'
# Whether we can use "adb exec-out" instead
# of "adb shell" (we should do it if the
# remote phone supports it)
self.can_use_exec_out = None # (boolean, None = unknown)
self.ADB_TIMEOUT = 10
... |
def make_guesses(words, possibles, exists, not_exists, explored):
letter_probs = {}
position_probs = [{} for _ in range(WORD_LEN)]
build_probs(words, possibles, exists, not_exists, letter_probs, position_probs)
return best_words(words, possibles, exists, not_exists, explored, letter_probs, positio... | This code implements a word-guessing strategy that balances exploration and exploitation. It reads possible guesses from a file, iteratively selects guesses based on probability thresholds, and updates constraints using user feedback (colors). The algorithm aims to minimize turns by adapting its approach—exploring new ... | def main():
with open("sgb.txt", "r") as words:
allowed_guesses = words.read().splitlines()
possibles = []
for i in range(WORD_LEN):
possibles.append(set(ALPHABET))
turn = 1
guess = ""
threshold = EXPLOIT_THRESHOLD
exists = set()
not_exists = set()
explored = set(... |
def handle_register(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8'))
if not all(key in data for key in ['username', 'password', 'email', 'fullname']):
self.send_error(400, 'Mi... | This code handles POST requests by routing them to specific methods based on the URL path. It processes registration, login, and adding restaurants/tables/reservations, with authentication checks required for the latter three to ensure only authorized users can perform these actions. | def do_POST(self):
if self.path == '/register':
self.handle_register()
elif self.path == '/login':
self.handle_login()
elif self.path == '/add_restaurant':
if not self.authenticate():
return
self.handle_add_restaurant()
elif... |
def authenticate(self):
"""Check if the request contains a valid token."""
if 'Authorization' not in self.headers:
self.send_error(401, 'Authorization token is missing')
return False
token = self.headers['Authorization'].split()[-1]
user_id = auth_service.verify_... | This code handles HTTP DELETE requests to remove resources (restaurant, table, reservation) by parsing the request path, validating IDs, checking authentication/admin status, and invoking specific handlers while returning appropriate error responses for invalid inputs or insufficient permissions. | def do_DELETE(self):
if self.path.startswith('/delete_restaurant/'):
if not self.authenticate():
return
restaurant_id = self.path.split('/')[-1]
if restaurant_id.isdigit():
self.handle_delete_restaurant(restaurant_id)
else:
... |
def _load_json_dump(file_name: str) -> dict:
json_dict = {}
with open(file_name, 'r') as definitions_file:
json_dict = json.load(definitions_file)
return json_dict
def process_policy_definitions(definitions_file: dict, output_dir: str = "./policies/definitions") -> None:
Path(output_dir).mkdir(p... | The main task of the code is to process Azure policy-related data from input JSON files, identify duplicate display names, organize outputs into specified directories, and generate processed policy definitions, sets, assignments, and exemptions. It loads input files, enumerates duplicates, creates output directories, a... | def main():
definitions_file = argv[1]
initiatives_file = argv[2]
assignments_file = argv[3]
exemptions_file = argv[4]
root_output_directory = argv[-1]
definitions_list = enumerate_duplicate_display_names(_load_json_dump(definitions_file))
initiatives_list = enumerate_duplicate_display_name... |
def image_data(directory):
image = Image.open(directory)
width, height = image.size
image_data = np.array(list(image.getdata()), dtype=np.uint8)
return width, height, image_data
def getfilecontents(filename):
p = os.path.join(os.getcwd(), "shaders8", filename)
return open... | This code initializes an OpenGL shader program by compiling vertex and fragment shaders from files, sets up textures from provided images, and prepares a triangle VAO for rendering. It processes input images into texture data, creates a shader program, attaches and links shaders, then calls an initialization method to ... | def __init__(self, vertex, image, image1):
self.triangleVAO = 0
self.texture = 0
self.vertex = vertex
self.images1 = self.image_data(image)
self.images2 = self.image_data(image1)
self.program = glCreateProgram()
vertexshadercontent = self.getfilecontents("triangle... |
def check_keydown_events(event, ai_settings, screen, ship, bullets):
'''
Respond to key press events
'''
if event.key == pygame.K_RIGHT:
#move the ship right
ship.moving_right = True
elif event.key == pygame.K_LEFT:
#move the ship left
ship.moving_left = True
elif... | This function handles Pygame event listeners for keyboard, mouse, and quit actions. It processes key presses (shooting bullets, moving ship), key releases, and mouse clicks (activating play button). Events trigger updates to game state, including ship movement, bullet firing, and game initialization via check_play_butt... | def check_events(ai_settings, screen, stats, sb, ship, aliens, bullets,
play_button):
'''
Use listeners for pygame keyboard and mouse events
'''
for event in pygame.event.get():
# event responses go here in this loop
if event.type == pygame.QUIT:
sys.exit()
... |
def check_fleet_edges(ai_settings, aliens):
''' Respond if any aliens have reached an edge of the screen surface'''
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai_settings, aliens)
break
def ship_hit(ai_settings, stats, screen, sb, ship, aliens, ... | This function updates alien positions, checks for collisions between aliens and the player's ship, and detects if aliens reach the screen bottom. It triggers collision responses and updates game state accordingly. | def update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets):
'''
Check if the fleet is at the screen edge,
If it is, update the positions of all the aliens in the group
'''
check_fleet_edges(ai_settings, aliens)
aliens.update()
# Check for alien and player ship collisions
#... |
def parse(buf, offs, ty, order='>'):
pattern = FMT[ty]
size = calcsize(pattern)
value = unpack_from(order + pattern, buf, offs)[0]
return value, offs + size
def parse_b(buf, offs):
b1 = []
for _ in range(7):
val, offs = parse(buf, offs, 'char')
b1.append(val)
b1 = b''.join(b1... | The function `parse_a` parses a sequence of data types (float, int16, a custom format via `parse_b`, uint16, and double) from a buffer starting at a given offset. It updates the offset after each parsing step, uses the uint16 value to offset into the buffer for another parse (`parse_d`), and returns a dictionary contai... | def parse_a(buf, offs):
a1, offs = parse(buf, offs, 'float')
a2, offs = parse(buf, offs, 'int16')
a3, offs = parse_b(buf, offs)
d_offset, offs = parse(buf, offs, 'uint16')
a4, _ = parse_d(buf, d_offset)
a5, offs = parse(buf, offs, 'double')
return dict(A1=a1, A2=a2, A3=a3, A4=a4, A5=a5), off... |
def build_infrastructure(entity_id, newThread=False):
entity = get_entity(entity_id)
saved_documents = entity['documents']['items']
saved_assistant = entity['assistant']
saved_threads = entity['threads']['items']
if(saved_assistant):
assistant = client.beta.assistants.retrieve(
... | The code processes a user message by creating an assistant-thread infrastructure, sending the message to the thread, initiating an assistant run, waiting for completion, and returning the updated thread messages. | def run_assistance(entity_id, message):
(assistant, thread) = build_infrastructure(entity_id)
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content=message,
)
show_json(message)
run = client.beta.threads.runs.create(
thread_id=threa... |
def get_document(id):
variables = {
'id': id,
}
query = """
query GetDocument($id: ID!) {
getDocument(id: $id) {
id
content
}
}
"""
response = query_api(query, variables)
return response['data']['getDocument']
def cl... | The main task of the code is to insert processed text chunks and their corresponding OpenAI embeddings into a PostgreSQL database for a given document ID, splitting the text into manageable parts, generating embeddings, and storing them with the original ID. | def insert_row(id):
conn = psycopg2.connect(os.environ.get('PG_DSN'))
document = get_document(id)
text = clean_text(document.get('content'))
text_strings = []
text_strings.extend(split_strings_from_text(text, max_tokens=MAX_TOKENS))
print(f"{len(text)} charachters split into {len(text_strings)}... |
def ensure_output_folders_exist(output_folder: str,
generate_plots: bool = True,
generate_csv: bool = True,
generate_steven_model: bool = False) -> Tuple[str, str]:
plots_folder = f"{output_folder}/plots"
csv_folder ... | This function generates synthetic ECG leads using a trained neural network model on test data, saving results as plots and CSV files. It processes batches from a dataloader, converts outputs to millivolts, creates visualizations, and optionally computes Steven model metrics for evaluation. Output formats include 12-lea... | def generate_outputs_from_test_data(number_of_leads_as_input: int,
generator_path: str,
model_size: int,
test_dataset: EcgDataset,
test_dataloader: torch.utils.data.DataLoader,... |
def _get_attachment_node(self, node, suffix, volume_name):
attach = False
ntpl = self.nodetemplates
for key, value in node.relationships.items():
if key.is_derived_from('tosca.relationships.AttachesTo'):
if value.is_derived_from('tosca.nodes.BlockStorage'):
... | The main task of the code is to translate TOSCA node templates into HOT resources, handling special cases like BlockStorage Attachments, lifecycle operations, ConnectsTo relationships, dependencies, hosting relationships, property expansions, and resolving function calls like GetProperty. It processes each node, expand... | def _translate_nodetemplates(self):
suffix = 0
# Copy the TOSCA graph: nodetemplate
for node in self.nodetemplates:
hot_node = TOSCA_TO_HOT_TYPE[node.type](node)
self.hot_resources.append(hot_node)
self.hot_lookup[node] = hot_node
# BlockStorage... |
def get_or_initialize_parameters(self, annotation_payload, label_categories, all_worker_prior):
self.label_categories = label_categories
self.n_classes = len(label_categories)
for item in annotation_payload:
i = item["datasetObjectId"]
self.dataset_object_ids.add(i)
... | This code performs parameter estimation using an Expectation-Maximization (EM) algorithm to update labeling models. It iteratively refines probability distributions (p, c_mtrx) over epochs, alternating between E-step (computing expected values) and M-step (maximizing parameters). The process stops when log-likelihood c... | def update(self, annotation_payload, label_categories, label_attribute_name, is_text=False):
all_worker_prior = 0.7
p, c_mtrx = self.get_or_initialize_parameters(
annotation_payload, label_categories, all_worker_prior
)
log_likelihood = None
for epoch in range(self.ma... |
def is_vehicle_stopped(vehicle, stop_threshold=0.1):
velocity = vehicle.get_velocity()
speed = math.sqrt(velocity.x**2 + velocity.y**2 + velocity.z**2)
return speed < stop_threshold
def camera_callback(image,data_dict):
data_dict['image'] = np.reshape(np.copy(image.raw_data),(image.height,image.widt... | The main task of the code is to simulate a CARLA autonomous taxi service, which stops the vehicle, calculates routes from the current location to a user pickup point and then to a destination, attaches camera and radar sensors for environmental perception, and drives along the planned routes while handling vehicle cont... | def call_service():
# Stop autopilot and get current vehicle location
vehicle.set_autopilot(False)
while not is_vehicle_stopped(vehicle):
vehicle.apply_control(carla.VehicleControl(throttle=0.0, steer=0.0, brake=1.0))
world.tick()
vehicle_transform = vehicle.get_transform()
current_... |
def is_null(self, p):
return p == self.null_point
def add(self, p1, p2):
if not self.is_point_on_curve(p1):
raise ValueError("Point p1 is not on curve")
if not self.is_point_on_curve(p2):
raise ValueError("Point p2 is not on curve")
if self.is_null(p1):
... | This code performs scalar multiplication of a point `p` by an integer `n` using binary exponentiation. It handles edge cases where `p` is null or `n` is zero by returning the null point. The loop processes each bit of `n`, adding `p` to the result when the bit is set, then doubling `p` and shifting `n` right iterativel... | def multiply(self, n, p):
if self.is_null(p) or n == 0:
return self.null_point
res = self.null_point
while n:
if n & 1:
res = self.add(res, p)
p = self.double(p)
n >>= 1
return res |
def fetch_model(mdl_path):
mdl = xgb.Booster()
try:
mdl.load_model(mdl_path)
except xgb.core.XGBoostError:
return None, "Failed to load model"
return mdl, None
def payload_to_row(payload, eng_to_esp_inputs, missing_cols):
"""
Take the data given in the GET request, dummy out non-... | The function processes user input data, validates required parameters, loads a machine learning model, prepares input features, generates recommendations, and returns predictions or error messages if any step fails, ensuring robust handling of incomplete or invalid inputs. | def query_model(payload: Dict, model_path: str) -> Union[np.array, None]:
"""
Take a JSON-derived dict of user data
and return an array of recommendation indices
"""
# Allowing a default customer ID value - it's not necessary to provide
cust_id = payload.get('cust_id', 99)
age = payload.get(... |
def read_data():
'''
Read the train, dev, and test datasets
'''
# TRAIN DATA and LABELS
train = pd.read_csv("./regression/data/train.csv")
train_input = (train.iloc[:, 1:]).to_numpy()
train_target = (train.iloc[:, 0]).to_numpy()
train_target = train_target.reshape(train_target.shape[0], ... | The code trains a neural network with specified hyperparameters (epochs, batch size, layers, units) on scaled training data, optionally applying feature selection. It uses gradient descent with L2 regularization (lambda) to optimize the model, validates on a development set, and predicts test outcomes. Results are scal... | def main():
# Hyper-parameters
max_epochs = 3000
batch_size = 64
learning_rate = 0.01
num_layers = 2
num_units = 64
lamda = 0.01 # Regularization Parameter
selected_features = 60
train_input, train_target, dev_input, dev_target, test_input = read_data()
train_input, train_targe... |
def ensure_directories(dir_list):
for directory in dir_list:
ensure_dir(directory)
return
def read_data():
if not (os.path.exists(cnst.data_path + cnst.v1_name)):
return {}
with open(cnst.data_path + cnst.v1_name, 'rb') as f:
loaded_data = pickle.load(f)
return dict(loaded_da... | The main task of the code is to process and validate content data by ensuring directory structure, reading data, verifying keys, removing unlinked files/images, updating image links, and generating a review list for further processing. | def run_first():
global content_dict
ensure_directories(cnst.dir_list)
content_dict = read_data()
content_dict = verify_keys(content_dict)
remove_unlinked_files(content_dict)
remove_unlinked_images(content_dict)
update_image_links(content_dict)
create_review_list(content_dict) |
def backup():
source_dir = cnst.data_path
image_dir = cnst.images
files_dir = cnst.files
save_dir = cnst.backups
images = [f for f in os.listdir(image_dir) if os.path.isfile(os.path.join(image_dir, f))]
files = [f for f in os.listdir(files_dir) if os.path.isfile(os.path.join(files_dir, f))]
... | The main task of the code is to restore a backup by handling an uploaded zip file: extracting its contents, processing data, cleaning unlinked files/images, updating links, and preparing review data, while returning a success response upon completion. | def restore_backup():
backup()
make_clean_dir(cnst.review)
global content_dict
file = request.files['file']
file.save(os.path.join(cnst.review, file.filename))
make_clean_dir(cnst.data_path)
with zipfile.ZipFile(f'{cnst.review}/{file.filename}', 'r') as zip_ref:
zip_ref.extractall(cn... |
def get_hands_and_bids() -> list[tuple[str, int]]:
hands_and_bids: list[tuple[str, int]] = []
for line in get_lines(__file__):
(hand, bid) = line.split(' ')
hands_and_bids.append((hand, int(bid)))
return hands_and_bids
def score_hand_strength_p2(hand: str) -> tuple[int, str]:
counts = Co... | The code processes poker hands to calculate a total bid sum. It scores each hand's strength, sorts hands by score, and computes the sum of bids weighted by their sorted rank. | def part_two():
cards = ['A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J']
hands_and_bids = get_hands_and_bids()
scored_hands_and_bids = [[0, 0, hand, bid]
for (hand, bid) in hands_and_bids]
for i in range(len(scored_hands_and_bids)):
hand = scored_ha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.