dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _create_encoder(self, args):
# Series of downconvolutions and bottleneck layers
downconv_input = self.x
# Determine how many possible downsamples to perform in each direction
self.down_x = int(math.log2(args.n_x))-2
self.down_y = int(math.log2(args.n_y))-2
f... | This code initializes a computational graph for a neural network modeling fluid dynamics simulations. It sets up state variables, parameters, GPU devices, and constructs encoder/decoder networks, dynamics models, and optimizers for simulating and reconstructing fluid flow data using multiple GPUs. | def __init__(self, args):
# Placeholder for states and control inputs
self.x = tf.Variable(np.zeros((args.batch_size*args.seq_length, args.n_x, args.n_y, 4), dtype=np.float32), trainable=False, name="state_values")
self.params = tf.Variable(np.zeros((args.batch_size, args.param_dim), dtype=np.f... |
def _create_feature_extractor(self, args):
# Series of downconvolutions and bottleneck layers
downconv_input = self.x
# Determine how many possible downsamples to perform in each direction
self.down_x = int(math.log(args.n_x,2))-2
self.down_y = int(math.log(args.n_y,2))-... | This code initializes a TensorFlow model for a physics-informed neural network, setting up state variables, control inputs, hyperparameters, normalization parameters, and building computational graph components like feature extractors, temporal encoders, inference/prior networks, and decoders. It prepares for tasks inv... | def __init__(self, args):
# Placeholder for states and control inputs
self.x = tf.Variable(np.zeros((args.batch_size*args.seq_length, args.n_x, args.n_y, 6), dtype=np.float32), trainable=False, name="state_values")
self.params = tf.Variable(np.zeros((args.batch_size, args.param_dim), dtype=np.f... |
def predict_start_from_noise(self, x_t, t, noise):
return (
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
)
def q_sample(self, x_start, t, noise):
noise = default(noise, lambda: torch.randn_li... | This code performs diffusion-based sampling to generate a prediction y from input x and context c. It iterates over reversed time steps, using a learned model to predict noise or denoised values. The output is refined via PCA blending, controlled by a mask, to combine sampled noise (y_no) and denoised predictions (y_de... | def predict(self, x, c, mask, ori_shape):
self.ori_shape = ori_shape
y = torch.randn_like(x, device=x.device)
for t in tqdm(reversed(range(0, self.num_timesteps)), desc='sampling loop time step', total=self.num_timesteps):
b, n, _ = y.shape
t = torch.full((b,), t, device ... |
def _validateEntry(self,text):
if len(text)>>2:
return True
else:
return False
def _sortEntry(self,text):
if "https://www.youtube.com/watch" in text:
return "LINK"
else:
return "SEARCH"
def clickDownload(self):
text=self.homeView.se... | The code handles a search action by validating user input, determining if it's a link, and either triggering a download or passing the search term to a model. It updates an error log if the input is too short. | def clickSearch(self):
text=self.homeView.searchEntry.get()
if self._validateEntry(text):
if self._sortEntry(text)=="LINK":
self.clickDownload()
else:
self.tempModel._putNext("search",text)
self.close("search")
else:
... |
def hessianMatrix(self) -> np.ndarray:
"""calculate total Hessian = geometric + prestress"""
hGeometric = self.hessianMatrixGeometric()
hPrestress = self.hessianMatrixPrestress()
hTotal = hGeometric + hPrestress
return hTotal
def rigidityMatrix(self) -> np.ndarray:
"""Cal... | The code computes the elastic modulus by calculating the energy resulting from deformation caused by the input strain matrix, using the system's spring constants, Hessian matrix, and rigidity matrix. It transforms coordinates and basis vectors, computes forces, solves for displacements, and derives the modulus as energ... | def elasticModulus(self, strainMatrix: np.ndarray) -> np.ndarray:
"""Return the elastic modulus for the given strain matrix.
Note:
To compute bulk and shear moduli, use ``bulkModulus`` and ``shearModulus`` functions.
Args:
strainMatrix (np.ndarray): In ``d`` dimensions,... |
def infect():
global config, rumors, rumors_recieved, waiting, is_spreader, iterNum, Percentege
is_spreading_right_now.fill(0)
# Check if a cell is infected
for x in range(BOARD_SIZE):
for y in range(BOARD_SIZE):
being_infected = (
is_spreader[x, y] == 0) and (
... | The main task of the code is to perform one iteration of a simulation process. It executes infection logic, updates statistics, optionally draws the current state if `doesDraw` is True, increments the iteration counter, and updates the GUI. This function likely belongs to a simulation loop, such as modeling disease spr... | def one_step(doesDraw = False):
global iterNum
infect()
update_stats()
if doesDraw:
draw()
iterNum += 1
root.update() |
def get_best_gen(text, population, letter_freq, two_letter_freq, words_set):
fitnesses = [fitness(text, gen, letter_freq, two_letter_freq, words_set) for gen in population]
return population[fitnesses.index(max(fitnesses))]
def create_plain(text,gen):
text = decode(text, gen)
with open(FILE_NAME_PLAIN, ... | The main task of the code is to export the best generation from a genetic algorithm. It retrieves the optimal solution from the population, generates plain text and permutation files, and logs the number of fitness calculations performed during the process. | def export(text, population, letter_freq, two_letter_freq, words_set, fitness_counter):
best_gen = get_best_gen(text, population, letter_freq, two_letter_freq, words_set)
create_plain(text, best_gen)
create_perm(best_gen)
print("Exported to " + FILE_NAME_PLAIN + " and " + FILE_NAME_PERM)
print("Numb... |
def one_step(doesDraw = False):
global iterNum
infect()
update_stats()
if doesDraw:
draw()
iterNum += 1
root.update()
def draw():
global canvas, root, iteration_label, rect_ids, percentage_label
iteration_label.config(text=f"Iteration:{iterNum+1}")
percentage_label.config(tex... | The main task of the code is to execute a simulation in multiple steps, updating the GUI periodically. It runs iterations using `one_step()`, checks termination conditions (e.g., simulation completion or user interruption), and transitions to the next simulation once finished. If all simulations are completed, it displ... | def multiple_steps():
global is_running, simNum
finished = False
is_running = True
button.config(text="Stop", command=stop)
while True:
if iterNum % DRAW_EVERY_X_ITERATIONS == DRAW_EVERY_X_ITERATIONS-1:
one_step(True)
else:
one_step(False)
finished = (... |
def initialize_population(text,population_size):
# get the most used letters in general
letter_freq = get_letter_freq()
# sort it and make it into an array
most_used_letters = [x for _,x in sorted(zip(letter_freq.values(), letter_freq.keys()), reverse=True)]
# get the most used letters in the text
... | This function implements a genetic algorithm to evolve a population of potential solutions for decoding text. It iteratively calculates fitness based on letter and word frequencies, selects survivors, applies mutations, and stops early if no improvement is detected. The process exports results if enabled, returning the... | def normal_genetic(text, letter_freq, two_letter_freq, words_set, try_export = True, population_size=POPULATION_SIZE, survivor_fraction=SURVIVOR_FRACTION, mutation_chance=MUTATIONS_CHANCE):
last_iteration, fitness_counter, best_score, no_improvement_counter = 0, 0, 0, 0
fitnesses = [0 for _ in range(population_... |
def initialize_population(text,population_size):
# get the most used letters in general
letter_freq = get_letter_freq()
# sort it and make it into an array
most_used_letters = [x for _,x in sorted(zip(letter_freq.values(), letter_freq.keys()), reverse=True)]
# get the most used letters in the text
... | The function `darwinian_genetic` implements a genetic algorithm to evolve a population of candidate strings toward a target text. It uses letter and two-letter frequency statistics, along with a word set, to evaluate fitness. The algorithm iteratively improves the population through selection, mutation, and fitness cal... | def darwinian_genetic(text, letter_freq, two_letter_freq, words_set, try_export = True, population_size=POPULATION_SIZE, survivor_fraction=SURVIVOR_FRACTION, mutation_chance=MUTATIONS_CHANCE,search_count=SEARCH_COUNT):
last_iteration, fitness_counter, best_score, no_improvement_counter = 0, 0, 0, 0
fitnesses = ... |
def initialize_population(text,population_size):
# get the most used letters in general
letter_freq = get_letter_freq()
# sort it and make it into an array
most_used_letters = [x for _,x in sorted(zip(letter_freq.values(), letter_freq.keys()), reverse=True)]
# get the most used letters in the text
... | This function implements a genetic algorithm to evolve a population of potential solutions (likely for generating text like limericks) by iteratively improving fitness based on letter and word frequencies. It initializes a population, evaluates fitness, selects survivors, applies mutations, and stops early if progress ... | def lamirick_genetic(text, letter_freq, two_letter_freq, words_set, try_export = True, population_size=POPULATION_SIZE, survivor_fraction=SURVIVOR_FRACTION, mutation_chance=MUTATIONS_CHANCE, search_count=SEARCH_COUNT):
last_iteration, fitness_counter, best_score, no_improvement_counter = 0, 0, 0, 0
fitnesses = ... |
def get_results_file_name():
# remove the .csv
file_name = FILE_NAME_RESULTS[:-4]
if os.path.exists(file_name + ".csv"):
i =1
while os.path.exists(file_name + str(i) + ".csv"):
i += 1
return file_name + str(i) + ".csv"
else:
return file_name + ".csv"
def calc... | This function generates CSV data by running multiple genetic algorithm configurations (normal, darwinian, lamirick) with varying mutation rates, population sizes, survivor fractions, and search counts. It iterates through all parameter combinations, executes the corresponding algorithm, records results like iterations,... | def data_to_csv(algorithms, mutation_chances, population_sizes, survivor_fractions, search_counts, text, letter_freq, two_letter_freq, words_set):
file_name = get_results_file_name()
current_run_index = 1
max_runs = calc_max_runs(algorithms, mutation_chances, population_sizes, survivor_fractions, search_cou... |
def get_vars(file_name):
text = ""
with open(file_name, "r") as f:
text = f.read()
letter_freq = get_letter_freq()
two_letter_freq = get_two_letter_freq()
words_set = get_words_set()
return text, letter_freq, two_letter_freq, words_set
def normal_genetic(text, letter_freq, two_letter_fre... | The code validates command-line arguments, processes a text file to extract linguistic data, and executes one of three genetic algorithms (normal, darwinian, or lamirick) based on the specified mode to analyze or generate text using frequency statistics and word sets. | def normal_main():
if (len(sys.argv) < 3) or (sys.argv[2] not in ["1", "2", "3"]):
print(INCORRECT_ARGS_MESSAGE)
sys.exit(1)
file_name = sys.argv[1]
mode = int(sys.argv[2])
text, letter_freq, two_letter_freq, words_set = get_vars(file_name)
if(mode == 1):
normal_genetic(tex... |
def pick_event_id(self, beg: int, end: int):
return beg
def part_by_part_summery(self, beg: int, end: int, gap=GAP):
"""
Add summery to history
"""
if beg > end:
return ""
full_summery = ""
while beg <= end:
if beg + gap >= end:
... | The code selects an event within a range, generates a summary of preceding events, creates a new event plot, updates the current event ID, and returns the combined summary and plot. | def initial_loop(self):
end = self.current_event_id + GAP - 1
if end >= TOTAL_EVENTS:
end = TOTAL_EVENTS - 1
chosen_event_id = self.pick_event_id(self.current_event_id, end)
full_summery = self.part_by_part_summery(self.current_event_id, chosen_event_id - 1)
self.cho... |
def generate_result(self, user_input: str):
"""
takes in new event, asks for the user
:param user_input:
:return:
"""
choice = self.action_evaluator(user_input)
prompt = (f"SYSTEM: Consider the outcome of the event: ***{self.chosen_event_plot}*** regarding\n"
... | The code processes user input to generate a narrative sequence by selecting the next event, creating a summary of prior events, and producing a new event plot. It updates the current event ID and returns the combined result, summary, and plot, with debug checks and end-game handling. | def next_loop(self, user_input):
end = self.current_event_id + GAP
if end >= TOTAL_EVENTS:
end = TOTAL_EVENTS - 1
result_of_event = self.generate_result(user_input)
if self.debug:
print("CHAT HISTORY: ", self.chat.chat_history)
if self.current_event_id >= ... |
def pick_event_id(self, beg: int, end: int):
return beg
def part_by_part_summery(self, beg: int, end: int, gap=GAP):
"""
Add summery to history
"""
if beg > end:
return ""
full_summery = ""
while beg <= end:
if beg + gap >= end:
... | The code selects an event within a range, generates a summary of prior events, creates a new event plot, and updates the current event ID, returning the combined summary and plot. | def initial_loop(self):
end = self.current_event_id + GAP - 1
if end >= len(events):
end = len(events) - 1
chosen_event_id = self.pick_event_id(self.current_event_id, end)
full_summery = self.part_by_part_summery(self.current_event_id, chosen_event_id - 1)
self.chose... |
def generate_result(self, user_input: str):
"""
takes in new event, asks for the user
:param user_input:
:return:
"""
choice = self.action_evaluator(user_input)
prompt = (f"SYSTEM: Consider the outcome of the event: ***{self.chosen_event_plot}*** regarding\n"
... | The code processes user input to generate a response by selecting the next event, summarizing previous events, and creating a new event plot, then combining these parts for output. It manages event tracking, debug logging, and constructs a response by concatenating generated results, summaries, and new event plots. | def next_loop(self, user_input):
end = self.current_event_id + GAP
if end >= len(events):
end = len(events) - 1
result_of_event = self.generate_result(user_input)
if self.debug:
print("CHAT HISTORY: ", self.chat.chat_history)
if self.current_event_id >= le... |
def pick_event_id(self, beg: int, end: int):
# chosen_id = random.randint((beg + end + 1) // 2, end)
# return chosen_id
prompt = (f"Choose the most important event in the plot "
f"from this list:***\n{generate_context(beg, end, include_id=True)}***\n"
f"Only o... | The main task of the code is to select the next event within a bounded range, generate a summary of prior events, create a new event plot, and return their combined result. It adjusts event boundaries, picks an event ID, constructs a summary, generates a new event, updates the current event ID, and concatenates the sum... | def initial_loop(self):
end = self.current_event_id + GAP
if end >= TOTAL_EVENTS:
end = TOTAL_EVENTS - 1
chosen_event_id = self.pick_event_id(self.current_event_id, end)
full_summery = self.part_by_part_summery(self.current_event_id, chosen_event_id - 1)
self.chosen_... |
def generate_result(self, user_input: str):
"""
takes in new event, asks for the user
:param user_input:
:return:
"""
choice = user_input
prompt = (f"""
## Profile
- Author: Game Developer
- Version: 0.1
- Language: English
- Description: Based on Ser Astarion's c... | The function `next_loop` processes user input to generate a narrative by selecting an event, summarizing prior events, and combining the result with a newly generated event plot, updating the current event ID for subsequent iterations. | def next_loop(self, user_input):
end = self.current_event_id + GAP
if end >= TOTAL_EVENTS:
end = TOTAL_EVENTS - 1
result_of_event = self.generate_result(user_input)
if self.debug:
print("CHAT HISTORY: ", self.chat.chat_history)
chosen_event_id = self.pick... |
def ind(index):
return index - 1
def euclidean_distance(a, b):
return np.linalg.norm(a - b)
def h_fn(c, i, j, m, l, kind='bubble'):
global VICINITIES, ALPHA_FN_KIND
kinds = ['bubble', 'gaussian']
if kind == kinds[0]:
if N_c(c, i, j, m, l, n=VICINITIES):
return alpha_fn(m, l, ki... | The code trains a Self-Organizing Map (SOM) by iteratively adjusting the weights of neurons in a 2D grid (kx x ky) to better represent input data. For each input vector, it computes Euclidean distances to all neurons, identifies the best-matching neuron (BMU), and updates neuron weights using a neighborhood function th... | def som_train(X, M, e, kx, ky):
global H_FN_KIND
m = X.shape[0] # no of input vectors
print(f'Learning...')
for t in range(1, e + 1):
print(f'Epoch {t}')
for l in range(1, m + 1): # for every input vector 'l'
distances = np.zeros((kx, ky))
for i in range(1, ... |
def aesECBMode(text, aesKey, flag): #flag tells the function to enc or dec
if type(text) == str:
text = text.encode()
cipher = Cipher(algorithms.AES(aesKey), modes.ECB(), backend=default_backend())
if flag == 'd': #decrypt: the incoming text must be in bytes
ct = text
decry... | This function performs AES encryption/decryption in CBC mode based on the 'flag' parameter. For decryption ('d'), it processes 16-byte blocks by decrypting with AES-ECB, XORing with the previous ciphertext block (or IV), and returns plaintext. For encryption ('e'), it pads the input, uses AES-CBC with the provided IV, ... | def aesCBCMode(text, aesKey, IV, flag): #incoming text must be bytes
previousBlock = IV #first IV is all 0s
if flag == 'd':
pt = b''
for i in range(0, len(text), 16): #incoming text must be bytes
currentBlock = text[i:i+16] #take out 16 bytes
... |
def generateId(self, size):
return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(size))
def generateLink(self, fileName):
return "https://prnt.sc/" + fileName
def generateImgur(self, url, fileName):
soup = BeautifulSoup(self.generateHtml(fileName), 'html.parser')
... | The code's main task is to continuously scrape data by generating unique IDs, creating corresponding URLs, and saving images from Imgur. It uses a loop to repeatedly generate filenames, construct links, download images as PNG files, and log completion status. The process runs indefinitely, producing and storing image d... | def run(self):
with console.status("[bold green]Scraping data...") as status:
while True:
fileName = self.generateId(LENGTH)
url = self.generateLink(fileName)
self.generateImgur(url, fileName)
fmt_filename = ''.join((fileName, '.png'))
... |
def convert_htmls_to_dfs(json_list: List[Dict]) -> List[Dict]:
"""
Function takes in list of dicts with html dataframes from files processed with XML Preprocessing script,
Converts html tables to pandas dataframes and outputs a list of dicts
"""
df_list = []
counter = 0
for item in json_list... | The function `parse_xml_tables` converts XML tables from a list of JSON dictionaries into HTML tables for labeling tasks. It processes XML data into dataframes, extracts structured value dictionaries, and transforms them into a named entity recognition (NER) JSONL format. The function also saves hash identifiers to a p... | def parse_xml_tables(json_list: List[Dict], pkl_file_name: str) -> List[Dict]:
"""
Converts list of xml tables to list of html tables for labelling
"""
# convert xml tables to dataframes
table_dfs_list = convert_htmls_to_dfs(json_list)
# parse to value dicts
parsed_table_dict_list = parse_t... |
def __draw_entrance(self):
# The road ahead.
self.road = []
if (self.experience_replay.is_empty() == False):
(car_position, road, future_states) = self.experience_replay.pop()
self.car_position = car_position
self.road = road
if (future_states is n... | The main task of the code is to simulate a self-driving car navigating a road with obstacles, using reinforcement learning. It tracks the car's position, actions, and road states to learn from crashes, generating new road sections iteratively until a collision occurs. The car starts centered, moves forward, and adjusts... | def __play_game(self):
# Keep track of each advance, so that we know how well we are learning.
self.num_advances = 0
# This keeps the last several states -- that is, the way the road looked, the car
# position and the action taken. In the event of a crash, we go back and learn from
... |
def get_data_partition(partition_file):
'''
Reads mappings from subject ids to their partition and vice versa
:param partition_file: path to the partition file (csv with two columns: id, partition)
:return: dicts subject2partition, partition2subject
'''
subject2partition, partition2subject = {},... | The main task of the code is to load and preprocess emotion-related datasets for specified tasks (e.g., stress, humor, reaction), normalizing features, segmenting training data, and structuring data into train/devel/test splits with features, labels, and metadata, optionally caching results as pickle files. | def load_data(task, paths, feature, emo_dim, normalize=True, win_len=200, hop_len=100, save=False,
segment_train=True):
'''
Loads the complete data sets
:param task: task
:param paths: dict for paths to data and partition file
:param feature: feature to load
:param emo_dim: emotion... |
def _expect(self, value):
if self.tokenizer.peek_token() == value:
return self.tokenizer.next_token()
def _ints(self, n):
"""
Expect to match `n` ints next. If a match fails, returns `None` for the
remaining matches so that it can be used in an unpacking expression.
"... | This code parses regex pattern info data by checking for an 'INFO' token, extracting four integers (skip, flags, min/max width), advancing the tokenizer if valid, and returning an Info object with these values. If invalid, it returns None. | def info(self) -> Optional[Info]:
if op := self._expect(sre_constants.INFO):
(skip, flags, min_width, max_width) = self._ints(4)
if max_width is not None:
for _ in range(skip - 4):
self.tokenizer.next_token()
return Info(op.pos, skip, f... |
def _expect(self, value):
if self.tokenizer.peek_token() == value:
return self.tokenizer.next_token()
def _ints(self, n):
"""
Expect to match `n` ints next. If a match fails, returns `None` for the
remaining matches so that it can be used in an unpacking expression.
"... | This code parses a repeat operator in a regex pattern, handling min/max repetition counts. It checks for REPEAT/MIN_REPEAT, retrieves repetition parameters, parses the repeat body, and constructs a Repeat object with parsed values, including min/max limits and the repeat body expression. | def repeat(self):
if (op := self._expect(sre_constants.REPEAT)) or (
op := self._expect(sre_constants.MIN_REPEAT)
):
(skip, min_times, max_times) = self._ints(3)
if max_times is not None:
with self.tokenizer.limit_to_next(skip - 1):
... |
def _expect(self, value):
if self.tokenizer.peek_token() == value:
return self.tokenizer.next_token()
def _ints(self, n):
"""
Expect to match `n` ints next. If a match fails, returns `None` for the
remaining matches so that it can be used in an unpacking expression.
"... | The main task of the code is to parse a regex repetition operator (e.g., *, +, {m,n}) by extracting its type, minimum/maximum repetition counts, and associated loop operation, then returning a RepeatOne object encapsulating these parsed values for further processing in a regex engine. | def repeat_one(self):
if (op := self._expect(sre_constants.REPEAT_ONE)) or (
op := self._expect(sre_constants.MIN_REPEAT_ONE)
):
(skip, min_times, max_times) = self._ints(3)
if max_times is not None:
with self.tokenizer.limit_to_next(skip - 1):
... |
def at(self) -> Token:
return self.tokens[0]
def eat(self) -> Token:
return self.tokens.pop(0)
def _parse_py(self):
if self.at().method == Methods.PYTHON:
return Python(code=self.eat().data)
elif self.at().method == Methods.VARIABLE:
return Variable(code=self.eat(... | This function parses different types of statements (BLOCK, EXTENDS, INCLUDE, PASS) by checking the current method, constructs corresponding objects (Block, Extends, Include, Pass), and returns them. It processes BLOCKs by collecting nested data until an END is encountered, handles file paths for EXTENDS/INCLUDE, and de... | def _parse_func(self):
if self.at().method == Methods.BLOCK:
block_name = self.eat().data
block_data = []
while self.at().method != Methods.END:
block_data.append(self._parse_func())
self.eat()
return Block(block_name=block_name, data=b... |
def history_answer(question, history):
try:
global columns_list
# Create a chat comxpletion using the question and context
if(len(history)==0):
return 'no-history'
history_answer = find_answer_from_history(history=history,question=question)
print('context... | The function `answer_question` processes a query by first checking historical context for an answer, then consulting documents, and finally using a cloud API (e.g., GPT-3.5) if needed. It handles errors, ensures rate limits are respected, and updates the conversation history with the generated answer. | def answer_question(question, history):
try:
history_ans= history_answer(history=user_history, question=question)
print('History: -',history_ans)
if(history_ans == "error"):
return "An error has occurred while processing the request"
if(history_ans == "NAAA"):
... |
def getKLlistForEachLayer(self, weights, ids=["H1","H2","H3"]):
"""
It gets
"""
# Parse the data for better readibilty
# This array will store each hospitals layer-wise weights
models = [weights[i][0]for i in range(len(weights))]
layerPairs = []
... | The main task of the code is to identify the most significant neural network layers using KL divergence, train these layers for alignment, save results, and optionally reintegrate updated weights. It calculates layer-wise KL divergences, selects top-N layers, trains them, and stores outputs while skipping weight reinte... | def run(self, topN=5):
"Allaha emanet bir fonksiyon"
print("Calculating KLs for each layer")
hospitalPair, klList,layerList = self.getKLlistForEachLayer(self.weights, self.ids)
topNIndexes,hospitalPairID, hospital = self.getLayerForKL(self.weights, klList,topN=topN, hospitalPa... |
def create_blocks(text: str, padding: bool) -> list:
if len(text)%64 != 0:
text = text + '00001000'*(8 - (len(text) % 64)//8)
if padding:
text = text + '00001000'*8
pattern = "."*64
B = re.findall(pattern, text)
return B
def ECB_encrypt(Blocks: list, K: list) -> str:
result=''
... | The code processes encryption/decryption using specified modes (ECB, CBC, etc.), converts input data into blocks, applies the chosen cryptographic mode with a key and IV, transforms binary results to hexadecimal (or string if raw), and outputs the final result. | def menu(plaintext: str, ciphertext: str, key: str, IV: str, mode: str, C: list, D: list, K: list, pad: bool, raw: bool) -> None:
B = create_blocks((plaintext if plaintext is not None else ciphertext), pad)
if mode == 'ECB':
result = (ECB_encrypt(B, K) if plaintext != None else ECB_decrypt(B, K))
el... |
def norm2(x):
"""Euclidian norm of array x, |x|_2"""
return np.sqrt(np.sum(x**2))
def time_observed(time):
"""Add Gaussian noise to time"""
time_noise = time + gaussian_noise(time)
return time_noise
def g_matrix():
"""Define G matrix. Picks out the squares that each ray (both directions) passes ... | The function `tikhonov` computes the optimal model parameter `m_optimal` and regularization parameter `epsilon_optimal` using Tikhonov regularization. It balances the data misfit `||Gm - d_obs||` against a variance-based constraint, minimizing a loss function that combines residuals and regularization. The optimal `eps... | def tikhonov(time, illustrate_find_eps=False):
"""Calculate the optimal m value using Tikhonov regularization with the constraint on epsilon: ||Gm - d_obs|| ~= variance(t_obs) * N_data
Args:
time (1darray): Time values
illustrate_find_eps (bool, optional): If true, draw the plot that shows the... |
def prior_initialization(illustrate_find_eps=False):
"""Use Tikhonov regularization to initialize MCMC prior updates
Args:
N_bands (int): Number of bands
returns:
(1darray, float): magnetization, optimal epsilon
"""
# Calculate terms without epsilon for speeding up the loop
G = ... | The function performs MCMC sampling to estimate the posterior distribution of magnetization states. It initializes magnetization and stripe edges, iteratively proposes new states, calculates acceptance probabilities, and updates the history if accepted. The output includes magnetization and misfit histories after disca... | def MCMC_posterior(N_bands, N_step, burn_in_steps):
"""Sample from posterior using MCMC
Args:
N_bands (_type_): _description_
N_step (_type_): _description_
burn_in_steps (_type_): _description_
Returns:
(1darray, 1darray): magnetization history, missfit history
"""
... |
def latest_date_in_the_data_file(self,)->date:
datas = self.read_data_file()
item = datas[-1]
temp = item.split("/")
return datetime.strptime(temp[2], date_format).date().strftime(date_format)
def order_of_ladder_in_date(self,_date:str)->list:
datas = self.read_data_file()
... | The main task of the code is to update the ladder file by determining the latest date in the data file, retrieving the ordered player list for that date, and rewriting the ladder order based on the retrieved list. | def update_ladder_file(self,)->None:
latest_date = self.latest_date_in_the_data_file()
player_list = self.order_of_ladder_in_date(latest_date)
self.rewrite_ladder_order(player_list) |
def get_epp_file_by_name(result_dir, model_path, suffix=''):
model_name = os.path.basename(model_path)[:-4].replace('Wrapper_', '') + suffix
return os.path.join(result_dir, model_name + '.epp'), model_name + '.epp'
def src_01_start_ep(ep_api_object, matlab_version, model_name, results):
# check if the ep ap... | The main task of the code is to automate the migration of a Matlab model by generating full-coverage test vectors, performing MIL/SIL simulations to capture reference behavior, and producing a BTC EmbeddedPlatform Project file (.epp) for embedded testing. It handles model import, test generation, simulation execution, ... | def migration_source(old_model, matlab_version, test_mil=False, ep_api_object=None, model_results=None, export_executions=False, reuse_code=False):
"""Generates tests for full coverage on the given model using the
specified Matlab version, then performs a MIL and SIL simulation
to record the reference behav... |
def get_epp_file_by_name(result_dir, model_path, suffix=''):
model_name = os.path.basename(model_path)[:-4].replace('Wrapper_', '') + suffix
return os.path.join(result_dir, model_name + '.epp'), model_name + '.epp'
def src_01_start_ep(ep_api_object, matlab_version, model_name, results):
# check if the ep ap... | The function performs migration testing by importing reference execution records, simulating MIL/SIL tests against a specified MATLAB version, checking interface changes, applying tolerances, generating regression reports, and returning results. It handles EPP file management, profile updates, test execution, and cover... | def migration_target(new_model, matlab_version, test_mil=False, ep_api_object=None, epp_file=None, accept_interface_changes=False, model_results=None, reuse_code=False):
"""Imports the reference execution records and simulates the same
vectors on MIL and SIL based on the specified Matlab version. This
regre... |
def _collect_scope_signal_data(ep, tol_fxp, tol_flp, tol_regex):
# query tolerances based on category (using model name)
xml_subsystems = []
scopes = ep.get('scopes')
scopes = [scope for scope in scopes]
for scope in scopes:
# check apply_to / FLOAT_FLOAT, etc.
signals = ep.get(f"sco... | This function defines and applies signal tolerances for test cases (RBT/B2B) by checking signal names against regex patterns, applying specified absolute/relative tolerances based on data types (float/fixed-point), and generating an XML file to configure test profiles with these tolerances. | def set_tolerances(ep, tol_fxp={ 'abs': '1*LSB' }, tol_flp={ 'abs': 1E-16, 'rel': 1E-8 }, tol_regex=[], use_case='B2B'):
"""Tolerances can be defined for RBT (requirements-based tests) and B2B (back-to-back & regression tests)
and will automatically be applied (supported with EP 24.1 and beyond)
For each scope, for... |
def initialize_report(models, title, filename, additional_stats={}):
global report_json; report_json = os.path.abspath(os.path.join('results', 'report.json'))
report_data = {
'title' : title,
'filename' : filename,
'results' : { },
'additionalStats' : additional_stats
}
... | This function generates comprehensive test suites for model migration by creating full-coverage tests for each input model using a specified Matlab version. It executes MIL and SIL simulations to capture reference behaviors, initializes reporting, prepares the execution environment, runs migration tasks for all models,... | def migration_suite_source(models, matlab_version, toolchain_script=None, test_mil=False, export_executions=False, reuse_code=False, ep=None):
"""For each of the given models this function generates tests for
full coverage on the given model using the specified Matlab version,
then performs a MIL and SIL si... |
def update_report(project_item=None, additional_stats={}):
global report_json
# load existing state
with open(report_json, "r") as f:
report_data = json.load(f)
# add information
if project_item:
if project_item['projectName'] in report_data['results']:
# update existing... | This function performs regression testing by simulating model executions on MIL/SIL environments using a specified Matlab version, comparing results against reference data to detect behavioral changes. It processes multiple models, generates reports, and returns validation outcomes while handling toolchain configuratio... | def migration_suite_target(models, matlab_version, model_results=None, accept_interface_changes=False, test_mil=False, toolchain_script=None, reuse_code=False,ep=None):
"""For each of the given models this function
imports the reference execution records and simulates the same
vectors on MIL and SIL based o... |
def migration_source(old_model, matlab_version, test_mil=False, ep_api_object=None, model_results=None, export_executions=False, reuse_code=False):
"""Generates tests for full coverage on the given model using the
specified Matlab version, then performs a MIL and SIL simulation
to record the reference behav... | This function tests if a model produces consistent results across different MATLAB versions or after refactoring. It uses migration_source to prepare the old model configuration and migration_target to validate results with the new model setup, defaulting to SIL-to-SIL testing. If the new model matches the old one, it ... | def migration_test(old_model, old_matlab, new_model=None, new_matlab=None, test_mil=False):
"""Convenience 1-liner to test:
- if a given model yields the same results with a different matlab version
- if a refactored model yields the same results
By default, only SIL <-> SIL is tested
"""
# ste... |
def parse_input_command(self, lines):
idx, line = lines.popleft()
if line.strip() != '@command':
raise SyntaxError('invalid command in line %s: %s' % (idx, line))
self.groups.send(lines)
source = consume_python_code_block(self.groups)
# Saves in definitions
... | This function parses a group of lines by identifying the starting command (e.g., @command, @import, @input) and delegating parsing to the appropriate method, returning the parsed tree. It handles specialized blocks like errors or plain input, raises syntax errors for invalid commands, and defaults to regular block pars... | def parse_group(self, lines):
"""Parse all lines in group and return the parsed tree."""
first_line = lines[0][1]
# Block-start flags
if first_line.startswith('@command'):
return self.parse_input_command(lines)
elif first_line.startswith('@import') or first_line.sta... |
def checknoisetest(values):
data = convertunitstomicrovolts(max(values) - min(values))
if data < 6:
return ['passed', data]
else:
return ['FAILED', data]
def checkwithoutR(values):
data = fivehertzamptransform(values)
if data > 80 and data < 110:
return ['passed', data]
e... | The function `checkdata` determines which specific data validation method to apply based on the `testindex` and `electrodeindex` parameters. It routes the `values` to either `checknoisetest`, `checkwithoutR`, `checkwithR`, or `checkidle` depending on the calculated relationships between the indices, enabling targeted a... | def checkdata(testindex, electrodeindex, values):
if testindex == 0:
return checknoisetest(values)
elif (testindex-1)/2 == electrodeindex:
return checkwithoutR(values)
elif (testindex-2)/2 == electrodeindex:
return checkwithR(values)
else:
return checkidle(values) |
def serialize(self):
data = JSONSerializer([self])
json_data = json.loads(data)
for field in json_data[0]['fields'].keys():
if field in self.excluded_fields:
del json_data[0]['fields'][field]
return json_data
def foreignkey_list(self, one2one=True, non_concret... | This function recursively serializes an object's data and its related foreign key fields. It first serializes the main object, then iterates over foreign key fields, checking if they are one-to-one. For each valid field, it recursively calls `deep_serialize` on the related object, appending results to the data. Excepti... | def deep_serialize(self, one2one=True):
data = self.serialize()
for field_name in self.foreignkey_list(one2one):
try:
one2one_flag = self._is_one_to_one_field(field_name)
field_content = getattr(self, field_name)
field_content = field_content.d... |
def load_linkage_region(self, *, i):
geno_dt = self.reg_dt[i]
store_dt = geno_dt['store_dt']
for varname, file_dt in store_dt.items():
module = importlib.import_module('.'.join(file_dt['typestr'].split('.')[:-1]))
cname = file_dt['typestr'].split('.')... | The function computes and stores linkage information (L, D, R) for a genomic region based on shift and cm parameters. It checks if data exists to avoid recomputation, calculates left/right linkage regions via shifts or centimorgans, and updates indices for variable slicing. If compute_sumstats is True, it retrieves ass... | def retrieve_linkage_region(self, *, i):
geno_dt = self.reg_dt[i]
if 'store_dt' in geno_dt.keys():
self.load_linkage_region(i=i)
shift = self.shift; cm = self.cm
compute_sumstats = self.compute_sumstats
if 'L' in geno_dt.keys():
... |
def get_left_linkage_region(self, *, i):
return self.get_specificied_linkage_region(i=i, shiftletter='L')
def get_auto_linkage_region(self, *, i):
return self.get_specificied_linkage_region(i=i, shiftletter='D')
def get_right_linkage_region(self, *, i):
return self.get_specificied_li... | The main task of the code is to compute locus-specific decay scores (LDS) for each row in the input dataframe by summing the squared values of three linkage regions (left, auto, right), taking their square root, and storing the result in a new 'lds' column. The function returns the updated dataframe with these computed... | def compute_ldscores_region(self, *, i):
sst_df = self.reg_dt[i]['sst_df'].copy()
L = self.get_left_linkage_region(i=i)
D = self.get_auto_linkage_region(i=i)
R = self.get_right_linkage_region(i=i)
for k, j in enumerate(sst_df.index):
slds = np.... |
def get_service_commission(self):
return self.get_total_payment_by_filter(
lambda o: o.operation_type == OperationTypeWithCommission.SERVICECOMMISSION)
def get_commissions(self) -> Dict[str, float]:
return self.get_total_payment_by_filter(lambda o: o.operation_type in self.commission_operati... | The main task of the code is to aggregate and format financial statistics by calculating total profit across currencies, combining service commissions, and compiling formatted dictionaries for commissions, pay details, operations, and balance. It returns a structured summary of financial metrics for reporting or analys... | def get_statistics(self) -> Dict[str, str]:
service_comission = self.get_service_commission()
comission = self.get_commissions()
profit = self.get_profit()
total_profit = defaultdict(float)
for figi, cur_val in profit.items():
for currency, value in cur_val.items():
... |
def IdentifyExamples(orig_examples: InputArtifact[Examples],
identified_examples: OutputArtifact[Examples],
id_feature_name: Parameter[str],
component_name: Parameter[str]) -> None:
# Get a list of the splits in input_data
splits_list = artifact_ut... | This function constructs a machine learning pipeline for training a model using TensorFlow Data Validation and Transform components. It processes data splits, generates statistics, validates schema, synthesizes graphs, transforms examples, augments with graph neighbors, and trains a model with specified steps, returnin... | def _create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text,
module_file: Text, serving_model_dir: Text,
metadata_path: Text,
direct_num_workers: int) -> pipeline.Pipeline:
input_config = example_gen_pb2.Input(splits=[
examp... |
def _fetch_expenses_csv(event):
return fetch_from_s3(
event['Records'][0]['s3']['bucket']['name'],
event['Records'][0]['s3']['object']['key']
).decode('utf-8')
def _format_csv_headers(csv_reader):
csv_reader.fieldnames = [
name if name == 'BatchID' else name.replace('ID', 'Id')
... | The main task of the code is to process an expenses CSV file by fetching it, parsing its contents with headers, formatting the headers, and sending the data to a D365 system. If the CSV is not found, it logs an error. The function returns payloads from the D365 transmission or an error message. | def start(event, context):
csv_string = _fetch_expenses_csv(event)
if csv_string:
csv_reader = csv.DictReader(csv_string.splitlines())
_format_csv_headers(csv_reader)
payloads = _send_to_d365(csv_reader)
return payloads
log_error('Expenses CSV not found', extra_data=event) |
def log(msg: str) -> None:
if not args.quiet:
print(msg)
def delete_tracks(genome_id: str) -> None:
if args.dry_run:
log(f"Deleting tracks for genome {genome_id}")
return
request = requests.delete(f"{track_api_url}/track_categories/{genome_id}")
if request.status_code != 204:
print(f"Error delet... | This function processes a data directory by validating its existence, filtering subdirectories that are valid UUIDv4 genome directories, optionally deleting existing tracks if overwrite is enabled, and processing files ending with .bb or .bw in each genome directory using match_template. It skips non-genome directories... | def process_data_dir() -> None:
if not os.path.isdir(data_dir):
print(f"Error: data directory {data_dir} not found")
exit(1)
subdirs = os.listdir(data_dir)
for i, subdir in enumerate(subdirs):
if not os.path.isdir(f"{data_dir}/{subdir}"):
continue
try:
UUID(subdir, version=4)
excep... |
def log(msg: str) -> None:
if not args.quiet:
print(msg)
def delete_tracks(genome_id: str) -> None:
if args.dry_run:
log(f"Deleting tracks for genome {genome_id}")
return
request = requests.delete(f"{track_api_url}/track_categories/{genome_id}")
if request.status_code != 204:
print(f"Error delet... | The main task of the code is to process genomic tracks for multiple genomes. It iterates through each genome, logs progress, deletes existing tracks if overwrite is enabled, and applies template/file-based track matching for each genome. The function handles track management tasks like deletion and application based on... | def process_track_list() -> None:
files = args.template or args.file
for i, genome_id in enumerate(args.genome):
log(f"Processing genome {genome_id} ({i+1}/{len(args.genome)})")
if args.overwrite: # delete existing tracks first
delete_tracks(genome_id)
for filename in files:
match_... |
def gameover_check(self):
'''checks if game is over'''
if self.win_check():
# checks for a win
self.gameover = True
elif self.state > 6:
# checks for a loss
self.gameover = True
else:
pass
def win_check(self):
'''checks ... | The code runs the game loop, checking for game over conditions each iteration. If the game ends, it determines if the player won or lost, displaying appropriate messages and the correct word. If not, it proceeds to the next turn, repeating until the game concludes. | def play(self):
'''runs the game'''
# loop until game finished
while self.gameover is False:
# checks for a gameover
self.gameover_check()
if self.gameover is True:
# if the game is over
if self.win_check():
... |
def quitgame():
db.disp()
pygame.quit()
quit()
def paused():
global pause
largeText = pygame.font.SysFont("comicsansms",115)
TextSurf, TextRect = text_objects("Paused", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
while pa... | The code defines a game loop for a car-dodging game, handling user input for movement and pausing, updating the car's position, generating obstacles, checking collisions, and increasing difficulty as the player dodges more obstacles. It maintains game state variables, updates the display, and controls the game flow unt... | def game_loop():
global pause
global dodged
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 4
thing_width = 100
thing_height = 100
thingCount = 1
dodged = 0
ga... |
def _get_syntax_settings(self, syntax, formatting_mode):
key = 'options_%s' % formatting_mode
settings = get_settings_for_view(self.view, key, default={})
if syntax and syntax != formatting_mode:
key = 'options_%s' % syntax
settings_override = get_settings_for_view(
... | This function constructs and returns a formatted string of options for a code formatter (likely Astyle) by combining default settings, syntax-specific configurations, and user-provided additional options. It prioritizes user-specified options when enabled, otherwise merges defaults with syntax settings to generate the ... | def _get_options(self, syntax, formatting_mode):
syntax_settings = self._get_syntax_settings(syntax, formatting_mode)
# --mode=xxx placed first
options_list = [Options.build_astyle_mode_option(formatting_mode)]
if 'additional_options_file' in syntax_settings:
astylerc_option... |
def get_syntax_for_view(view):
caret = view.sel()[0].a
syntax = SYNTAX_RE.search(view.scope_name(caret))
if syntax is None:
return ''
return syntax.group(0).lower()
def _get_formatting_mode(self, syntax):
mapping = get_settings_for_view(
self.view, 'user_defined_syntax_mode_m... | The main task of the code is to format code using AStyle, handling errors and displaying messages. It runs formatting on selected text or the entire file, validates configuration options, and displays errors if they occur. It also includes debugging info if enabled, and shows a status message upon completion. | def run(self, edit, selection_only=False):
# Close output panel previouslly created each run
under_unittest = self.view.settings().get('_UNDER_UNITTEST')
error_panel = ErrorMessagePanel("astyle_error_message",
under_unittest=under_unittest)
error_p... |
def load_data():
train = open("ann-train.data", "r")
training_data = []
for line in train:
training_data.append(line.strip().split(" "))
convert_types(training_data)
test = open("ann-test.data", "r")
test_data = []
for line in test:
test_data.append(line.strip().spl... | The code's main task is to evolve a population of decision trees using genetic algorithms to minimize classification fitness on a dataset. It loads training/test data, initializes a population, iteratively evolves it via selection/optimization, tracks average fitness over generations, and stops early if fitness drops b... | def main():
training_features, training_labels, test_features, test_labels, costs = load_data()
data = [training_features, training_labels, test_features, test_labels, costs]
clf = tree.DecisionTreeClassifier()
pop = population(20, training_features[0])
fitness_history = []
for i in ra... |
def initWeightsAndBiases():
Ws = []
bs = []
np.random.seed(0)
W = 2 * (np.random.random(size=(NUM_HIDDEN, NUM_INPUT)) / NUM_INPUT ** 0.5) - 1. / NUM_INPUT ** 0.5
Ws.append(W)
b = 0.01 * np.ones(NUM_HIDDEN)
bs.append(b)
for i in range(NUM_HIDDEN_LAYERS - 1):
W = 2 * (np.random.r... | The function `findBestHyperparameters` performs an exhaustive grid search over predefined hyperparameter combinations (hidden layers, units, learning rate, squiggle size, etc.) to train and evaluate a neural network model on validation data. It iterates through all possible combinations, trains the model, computes vali... | def findBestHyperparameters(X_tr, y_tr, X_tr_vald, y_tr_vald):
no_data = X_tr.shape[1]
no_features = X_tr.shape[0]
global NUM_HIDDEN_LAYERS, NUM_HIDDEN
n_hidden_layers_set = np.array([3, 4, 5])
n_hidden_set = np.array([30, 40, 50])
eps_set = np.array([0.001, 0.005, 0.01, 0.1])
n_squig_set ... |
def findBestHyperparameters(X_tr, y_tr, X_tr_vald, y_tr_vald):
no_data = X_tr.shape[1]
no_features = X_tr.shape[0]
global NUM_HIDDEN_LAYERS, NUM_HIDDEN
n_hidden_layers_set = np.array([3, 4, 5])
n_hidden_set = np.array([30, 40, 50])
eps_set = np.array([0.001, 0.005, 0.01, 0.1])
n_squig_set ... | The function performs stochastic gradient regression with hyperparameter tuning. It splits data into training and validation sets, initializes weights/biases, trains a model using specified parameters, and evaluates validation performance. It returns trained weights and training trajectory, either using tuned or predef... | def stoch_grad_regression(X_tr, y_tr, weightsAndBiases, tuning):
no_data = X_tr.shape[1]
no_features = X_tr.shape[0]
X_tr_raw = X_tr
y_tr_raw = y_tr
vald_perct = 80
vald_num = (int)(no_data * vald_perct / 100)
global NUM_HIDDEN_LAYERS, NUM_HIDDEN
X_tr = X_tr_raw[:, 0:vald_num]
X_tr... |
def generate_anthro_model(name,df):
y_name = getColumnName(df)
return anthroModel(
name = name,
y_name=y_name,
clean_name = CLEAN_NAME_LIST[name] if name in CLEAN_NAME_LIST else name,
data_male=generate_anthro_concepts(df,1,y_name),
data_female=generate_anthro_conce... | The code generates FHIR anthropometric resources from a DataFrame by creating directory structures for CQL libraries, code systems, and value sets. It extracts a base name from the input file, constructs a model using `generate_anthro_model`, and exports corresponding FHIR components to specified output paths. | def generate_anthro_df(filename,df):
cql_base_path = os.path.join(OUTPUT_PATH, 'cql')
lib_base_path = os.path.join(OUTPUT_PATH, 'resources/library')
valuset_base_path=os.path.join(OUTPUT_PATH, 'vocabulary/valueset')
codesystem_base_path = os.path.join(OUTPUT_PATH, 'vocabulary/codesystem')
if n... |
def get_temps(file):
if is_zipfile(file):
return _get_zip_temps(file)
else:
return _get_log_temps(file)
def get_processor_summary(temps: Temps):
summary = {}
for i in preprocess_rows(temps):
proc, mi, mx, avg = i['processor'], i['min'], i['max'], i['avg']
if None in (proc... | This script processes temperature data from .DM.log files (or zip archives containing them), aggregates statistics per processor, and optionally outputs results to CSV or generates time-series plots. It accepts file paths via command-line arguments, defaults to a standard directory if none are provided, and uses matplo... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--out', '-o', help='A file path to write the CSV output to. File must not already exist.')
parser.add_argument('files', nargs='*', help='A list of zip files containing .DM.log files and/or a list of .DM.log files directly.')
parser.add_... |
def load_vocab(vocab_path):
vocabs = set()
with open(vocab_path) as vocab_file:
for word in vocab_file:
vocabs.add(word.strip())
return vocabs
def preprocess_folder(folder_path: str, vocabs):
vector_list = []
for filename in os.listdir(folder_path):
comment = preprocess_f... | The code preprocesses text data from two folders by converting them into vector representations using a given vocabulary. It labels each vector with class identifiers, checks for presence of strong positive/negative words, and saves the results (in a specific format) to an output file. | def preprocess(folder_path1, folder_path2, vocab_path, path1_class, path2_class, output_path):
# label######{json format of vector}
# ###### is the separator of column to access easier
vocabs = load_vocab(vocab_path)
folder_path1_vectors = preprocess_folder(folder_path1, vocabs)
folder_path2_vectors... |
def show_default_path():
"""
Invoke check_process() to get the operating system and
the default directory.
"""
common.check_process()
operating_system, _, default_folder = check_default_profile()
print()
print("--------------------------------------------------------------")
print(f... | The main task of the code is to present a menu-driven interface for users to select actions related to profile management and application information. It continuously prompts the user for input, executes corresponding functions (e.g., showing profile path, backup, restore, version info, or quitting), and validates inpu... | def user_input():
"""
Check user input
"""
print()
print("----------------------------------------------------------")
print("What do you want to do?")
print()
print("-1- Show the path of the default profile")
print("-2- Backup the default profile")
print("-3- Restore the default... |
def get_num_qubits(algorithm):
"""
Determine the max qubit value used in the algorithm.
algorithm: iterable, each element must be a string gate, as in
apply_string_gate above.
ie, algorithm = ["h(0)", "cx(0, 1)", "rx(pi/4, 1)",..]
ret... | The function executes quantum algorithms on a specified backend, creating quantum circuits, handling multiple algorithms, and returning a probability distribution of measurement outcomes. It manages backend-specific errors, adjusts qubit counts, and formats results with reversed bit order for compatibility. | def run(algorithm, num_qubits=None, num_samples=8000, backend=simulator):
"""
Create a quantum circuit, run the algorithm, return the resulting
probability distribution.
algorithm: algorithm (list of strings) or list of algorithms,
each string is a gate in GATE_ARGUMENTS.keys() with... |
def get_num_qubits(algorithm):
"""
Determine the max qubit value used in the algorithm.
algorithm: iterable, each element must be a string gate, as in
apply_string_gate above.
ie, algorithm = ["h(0)", "cx(0, 1)", "rx(pi/4, 1)",..]
ret... | The function `algorithm_unitary` computes the unitary matrix representing a quantum algorithm defined by a list of gates. It adjusts qubit indices to align with Qiskit's convention, constructs a quantum circuit, applies the gates, and uses Qiskit's unitary simulator to output the resulting unitary matrix. The task invo... | def algorithm_unitary(algorithm, num_qubits=None):
"""
Find the unitary corresponding to the algorithm.
algorithm: list of strings, each string is a gate in GATE_ARGUMENTS.keys()
with whatever arguments required to define the
gate.
nu... |
def get_num_qubits(algorithm):
"""
Determine the max qubit value used in the algorithm.
algorithm: iterable, each element must be a string gate, as in
apply_string_gate above.
ie, algorithm = ["h(0)", "cx(0, 1)", "rx(pi/4, 1)",..]
ret... | The function `run` executes quantum algorithms on a quantum simulator, generating and returning the probability distribution of quantum states. It constructs quantum circuits from a list of gate instructions, simulates them using Cirq, and calculates state probabilities from the simulation results. The function handles... | def run(algorithm, num_qubits=None, num_samples=8000):
"""
Create a quantum circuit, run the algorithm, return the resulting
probability distribution.
algorithm: algorithm (list of strings) or list of algorithms,
each string is a gate, ie "cx(0, 1)" or rz(pi/2, 0)
num_qubits: in... |
def get_num_qubits(algorithm):
"""
Determine the max qubit value used in the algorithm.
algorithm: iterable, each element must be a string gate, as in
apply_string_gate above.
ie, algorithm = ["h(0)", "cx(0, 1)", "rx(pi/4, 1)",..]
ret... | The function generates a sequence of quantum computation results where each subsequent run uses the previous measurement as input, creating a Markovian chain. It executes an algorithm multiple times, feeding the output of one run into the next, and returns a list of measured quantum states. The process starts with an i... | def markovian_sample(algorithm, num_qubits=None,
num_samples=1, backend=simulator):
"""
Get a list of all the outputs from an algorithm, where the previous output
is prepared as the starting point for the next algorithm; ie the
measurement of the algorithm is input to run the algor... |
def get_cities() -> dict[str, City]:
return {city["name"]: City.parse_obj(city) for city in cities_table.all()}
def get_extra_data(name: str, currency: str) -> CityExtraData:
extra_query = Query()
extra = cities_extra_data_table.search(
(extra_query.name == name) & (extra_query.currency == currency)... | The code generates travel recommendations based on a user's budget, location, and currency. It iterates through cities, checks for a matching location, and either creates a recommendation with filtered data or an empty list. Aggregates results into a structured response for each city. | def get_recommendations(budget: BudgetRequest, location: str, currency: Currency):
recommendations = []
for city_name, city in get_cities().items():
if location == city_name:
recommendation = Recommendation(city=city, budget=budget, data=[])
recommendations.append(recommendation)... |
def parse_tree(line):
toks = tokenize(line)
stack = []
t = next(toks)
try:
while t:
if t=="(":
stack.append(t)
elif t==")":
subtree = []
s = stack.pop()
while s[0]!="(":
subtree.append(s)
... | The code evaluates the performance of a parser on a treebank by parsing each sentence, comparing the parser's output to the gold standard tree, and computing metrics like coverage and average F-scores for parsed and all sentences. | def evaluate_parser(parser, treebank_file):
total = 0
unparsed = 0
fscore_sum = 0.0
for line in treebank_file:
gold_tree = parse_tree(line.strip())
tokens = get_leafs(gold_tree)
print("input: ",tokens)
chart,probs = parser.parse_with_backpointers(tokens)
prin... |
def choice_inside_door():
print("You're inside the house.")
print("There's a note on the table.")
print("Do you:")
print("1. Pick up and read the note?")
print("2. Leave it and go home")
choice = input("Choose: ")
if choice == '1':
choice_read_note()
elif choice == '2':
choic... | The function presents two options to the user: entering a cracked door or leaving. It handles input to decide the next action, recursively prompting until a valid choice is made. | def choice_back_door():
print("the door is cracked with a warning sign on it...")
print("Do you:")
print("1. Go inside")
print("2. Give up and go home")
choice = input("Choose: ")
if choice == '1':
choice_inside_door()
elif choice == '2':
choice_go_home()
else:
prin... |
def choice_back_door():
print("the door is cracked with a warning sign on it...")
print("Do you:")
print("1. Go inside")
print("2. Give up and go home")
choice = input("Choose: ")
if choice == '1':
choice_inside_door()
elif choice == '2':
choice_go_home()
else:
prin... | The function `choice_front_door` presents a scenario where the front door is locked, offering the user two choices: check the back or give up. It prompts for input, directs the flow to other functions based on the choice, and recursively re-prompts for invalid inputs, ensuring the user makes a valid decision to proceed... | def choice_front_door():
print("Try the front door.")
print("It's locked.")
print("Do you:")
print("1. Check around back")
print("2. Give up and go home")
choice = input("Choose: ")
if choice == '1':
choice_back_door()
elif choice == '2':
choice_go_home()
else:
... |
def choice_front_door():
print("Try the front door.")
print("It's locked.")
print("Do you:")
print("1. Check around back")
print("2. Give up and go home")
choice = input("Choose: ")
if choice == '1':
choice_back_door()
elif choice == '2':
choice_go_home()
else:
... | The main task of the code is to display a text-based game menu with four options, handle user input, and branch to corresponding functions (e.g., trying the front door, sneaking back, going home, or quitting). It validates input and re-prompts for invalid choices, serving as the entry point for a narrative-driven game ... | def main_menu():
print("Main Menu")
print("You're in front of a spooky old house...")
print("Do you:")
print("1. Try the front door")
print("2. Sneak around back")
print("3. Forget it and go home")
print("4. [Quit]")
choice = input("Choose: ")
if choice == '1':
choice_front_d... |
def get_localvar_aspell_suggest(buffer):
return weechat.buffer_get_string(buffer, 'localvar_aspell_suggest')
def get_last_position_of_misspelled_word(misspelled_word, buffer):
input_pos = weechat.buffer_get_integer(buffer,'input_pos')
input_line = weechat.buffer_get_string(buffer, 'input')
x = input_lin... | The main task of this code is to handle inline spell correction in a text input, replacing misspelled words with Aspell suggestions. It enables cycling through suggestions using TAB, adjusts the input line and cursor position, manages inline replace mode, and updates UI elements like the spell suggestion bar. The funct... | def input_complete_cb(data, buffer, command):
# check if a misspelled word already exists!
localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)
if not localvar_aspell_suggest and not weechat.buffer_get_string(buffer,'localvar_inline_replace_mode'):
return weechat.WEECHAT_RC_OK
# first... |
def get_LEI_mappings():
LEIs = get_holdings_Eikon()['LEI'].dropna().astype('string').unique()
lei_input = pd.DataFrame({})
localID = 1
for lei in LEIs:
lei_input = lei_input.append(pd.DataFrame({'LocalID': localID, 'Standard Identifier': 'LEI:' + lei}, index = [0]))
localID += 1
... | The function `get_sector_mappings` generates or retrieves a sector mappings dataset by merging company LEI data from `holdingsECB` with sector information from external sources using `PermID` as a key. If the output file `sector_mappings_data.xlsx` does not exist, it creates it by combining mappings from `get_LEI_mappi... | def get_sector_mappings(holdingsECB):
path = __file__
parent = os.path.join(path, os.pardir)
parent = os.path.join(parent, os.pardir)
if not (os.path.isfile(parent+'\output\sector_mappings_data.xlsx')):
sector_mappings = get_LEI_mappings().merge(convert_sector_lookups(), how = 'left', on = 'Perm... |
def scan_next_reserved(cursor):
token = ''
cursor.skip('\n \t')
if cursor.get_char() == '#':
return '#', cursor
elif cursor.get_char() == '$':
return '$', cursor
if not is_alpha(cursor.get_char()):
parsing_error(cursor,emsg('errors parsing comments'))
while is_alpha(cur... | This function parses a list of a specified type (int, string, float, list, or struct) from the input cursor. It validates syntax, processes each element according to the list type, collects parsed values into a result list, and returns the list along with the updated cursor. | def scan_next_list(cursor):
#scan type of list
list_type, cursor = scan_next_reserved(cursor)
result = []
cursor.skip_spaces()
if cursor.skip_char_ifexpected('[') != True:
parsing_error(cursor, emsg('list format error', 'expected ['))
cursor.skip_spaces()
while cursor.char_isnot(']... |
def scan_next_reserved(cursor):
token = ''
cursor.skip('\n \t')
if cursor.get_char() == '#':
return '#', cursor
elif cursor.get_char() == '$':
return '$', cursor
if not is_alpha(cursor.get_char()):
parsing_error(cursor,emsg('errors parsing comments'))
while is_alpha(cur... | This function parses a namespace's body by reading variables, checking their types (int, float, string, list, struct, namespace), and building a dictionary of variables with their values. It handles syntax validation, recursive namespace parsing, and error checking for invalid types or formatting. | def scan_namespace_body(cursor, access_data, namespace):
body = {}
cursor.skip_spaces()
if cursor.skip_char_ifexpected('{') != True:
parsing_error(cursor,emsg(f" Format Error while scanning namespace:[{namespace}] elements",f"was expected {'{'} after {namespace} "))
cursor.skip_spaces()
wh... |
def arg_parse():
""" Parser for command-line edition
"""
parser = argparse.ArgumentParser()
parser.add_argument("SRC_FILE", nargs='+')
parser.add_argument("DESTINATION")
parser.add_argument("-r", action="store_true")
parser.add_argument('-u', action="store_true")
return parser.parse_args... | The main task of the code is to copy files or directories from source paths to a destination path, handling symlinks, file updates, and directory operations based on command-line arguments. It checks file types, uses flags like `-r` (recursive) and `-u` (update), and performs actions such as creating symlinks, copying ... | def main():
""" Main function
"""
# Create arguments from argument parser
args = arg_parse()
print(args)
# Get source path and destination path
dest_path = os.path.abspath(args.DESTINATION)
for src_path in args.SRC_FILE:
src_path = os.path.abspath(src_path)
# Case process... |
def remove_conditional_content(content, info, tag=None):
"""
Removes any conditional content that doesn't match for the specified distro
"""
# Remove any ifdef content
ifdef = IFDEF_RE.search(content)
while ifdef is not None:
is_not_def = ifdef.group(1) == "n"
ifdef_distros = ifd... | The main task of the code is to correct internal and external links in content by replacing source references with output paths or portal URLs, using a file-to-ID mapping and book-specific metadata. It identifies links, resolves their targets based on the current directory and distribution info, constructs proper Ascii... | def _fix_links(content, book_dir, src_file, info, tag=None, cwd=None):
"""
Fix any links that were done incorrectly and reference the output instead of the source content.
"""
# TODO Deal with xref so that they keep the proper path. Atm it'll just strip the path and leave only the id
file_to_id_map ... |
def scrub_file(info, book_src_dir, src_file, tag=None, cwd=None):
"""
Scrubs a file and returns the cleaned file contents.
"""
base_src_file = src_file.replace(info["src_dir"] + "/", "")
# added 1/Sep/2020
# to allow loading files like json and yaml from external sources, this
# procedure l... | This function copies a source file to a destination directory, processing its content to scrub data, fix links, and handle includes. It recursively copies referenced includes, adjusts paths for cross-references, and ensures proper file structure. If includes exist, it processes them by resolving paths, copying files wh... | def copy_file(
info,
book_src_dir,
src_file,
dest_dir,
dest_file,
include_check=True,
tag=None,
cwd=None,
):
"""
Copies a source file to destination, making sure to scrub the content, add id's where the content is referenced elsewhere and fix any
links that should be cross re... |
def recv_data(s):
buf = b''
while len(buf) < 4: # Get the length of the payload (fixed size)
buf += s.recv(4 - len(buf))
length = struct.unpack('!I', buf)[0]
data = b''
while len(data) < length: # Get the payload
data += s.recv(length - len(data))
return deserializer(data)
def ... | The code manages a multiplayer game over sockets using I/O multiplexing. It accepts client connections, assigns roles (X/0), processes game moves, updates the state, and sends responses. It handles readable/writable sockets, manages game turns, detects wins, and cleans up disconnected clients. The server ensures two pl... | def monitor_sockets(server):
try:
inputs = [server, ]
outputs = []
message_queues = {}
i = 0
turn = ['X', '0']
jackpot = ''
while inputs:
readable, writable, exceptional = select.select(inputs, outputs, inputs)
if server in readable:
... |
def home_page(self):
self.wait_until_element_exist(By.CLASS_NAME, "productList_31W-E")
product_container = self.get_element(By.CLASS_NAME, "productList_31W-E", method="first")
links = product_container.find_elements(By.CLASS_NAME, "link_3hcyN")
links = [link.get_attribute("href") for li... | The code scrapes product prices and store availability data by iterating through product links, inputting a postal code, extracting prices via XPath, parsing store pages, checking availability status for each store, and compiling results into a dictionary. It returns a structured dataset of product prices and store ava... | def run(self):
links = self.home_page()
for link in links:
product_ = self.parse_link(link)
if not product_:
continue
self.input_postal_code()
self.product_info[product_]["price"] = self.driver.find_element(
By.XPATH,
... |
def seeds(seed: int = 0, frame: int = 0, limit: int = 2**32):
""" Yields successive seeds (32 bits) up to a limit.
Args:
seed (int): Initial seed. Defaults to 0.
frame (int): Cycles to skip. Defaults to 0.
limit (int): Number of seeds to produce. Defaults to 2**32.
>>> list(seeds(li... | This function generates wild Pokémon encounter data by simulating RNG-based mechanics. It yields tuples containing cycle count, seed value, encounter slot, and Pokémon PID (Personality ID). Key steps include: skipping frames, checking encounter rates (adjusted for bike mechanics), selecting valid slots, generating Poké... | def wild_mons(seed=0, cycle=0, limit=1000, diff=False, bike=False, rate=20, slots=None):
""" Yield (cycle, seed, slot, pid) tuples for wild pokemon encounters.
Seed is the RNG state on the frame *before* the tile transition.
Args:
seed (int): Starting value for RNG. Defaults to 0.
cycle (i... |
def battle_seeds(seed=0, frame=0, limit=1000):
""" Yield success battle seeds. The RNG advances twice per frame in battle.
Args:
seed (int): Starting seed. Defaults to zero.
frame (int): Cycles to skip. Defaults to 0.
limit (int): Number of seeds to yield. Defaults to 1000.
"""
... | This function simulates move accuracy calculations in a battle scenario by iterating through potential seed values. For each seed, it generates a random number, computes hit probability using given parameters (accuracy stage, evasion, move accuracy), and prints results showing base seed, accuracy percentage, and hit st... | def acc_seek(seed, frame=0, limit=10, acc_stage=6, evade=6, move_acc=95):
offset = 3 # 2 frames are skipped, the next is used
for base in battle_seeds(seed, frame, limit):
rng = rand(base, offset)
hit, acc = acc_calc(rng, acc_stage, evade, move_acc)
print(f'{base:08x}:{acc:03d}{"Y" if h... |
def battle_seeds(seed=0, frame=0, limit=1000):
""" Yield success battle seeds. The RNG advances twice per frame in battle.
Args:
seed (int): Starting seed. Defaults to zero.
frame (int): Cycles to skip. Defaults to 0.
limit (int): Number of seeds to yield. Defaults to 1000.
"""
... | This function explores and prints critical hit and damage values for different seed inputs. It iterates through generated battle seeds, calculates damage and critical hit status using a random number generator, and outputs results in hex seed format with damage values and critical markers. The parameters control seed e... | def dmg_seek(seed, frame=0, limit=10, chance=0): # Explore critical and damage values
offset = 3 # 2 frames are skipped, the next is used
for base in battle_seeds(seed, frame, limit):
rng = rand(base, offset)
crit, dmg = crit_dmg_calc(rng, chance)
print(f'{base:08x}:{dmg:03d}{"!" if cr... |
def _set_original_board_list(self):
"""Sets the original_board_list attribute as a 9-element list of the current game board."""
self.original_board_list = self._create_board_list(self.game.game_matrix)
def _minimax(self, new_board, character):
"""Returns the index of the best possible move for t... | The code uses a minimax algorithm to determine the optimal move in a game. It initializes the board state, calculates the best move via minimax, converts the resulting index to matrix coordinates, and assigns this move to the game's current move attribute for execution. | def set_hard_move(self):
"""Uses a minimax algorithm to play a move."""
self._set_original_board_list()
move = self._minimax(self.original_board_list, self.game.current_character)
board_list_index = move['index']
move_tuple = self._list_to_matrix_index(board_list_index)
s... |
def _set_starting_parameters(self):
"""Sets the starting commands from the user."""
commands = input("Input command: ").split()
if self._commands_are_valid(commands):
self._set_player_attributes()
return
else:
print("Bad parameters!")
retur... | The main task of the code is to initialize and execute a game by setting starting parameters, printing the game matrix, and running the game loop. The `play_game` method serves as the entry point for the game's operation, orchestrating setup and gameplay流程 through internal methods. | def play_game(self):
"""The main call of the class."""
self._set_starting_parameters()
self._print_game_matrix()
self._game_loop()
return |
def selection(self, best_count):
sorted_population = sorted(self.population, key=lambda bird: bird.alive_time + bird.score)
self.add_to_elites()
return sorted_population[len(sorted_population):len(sorted_population) - best_count - 1:-1]
def get_best_unit(self):
return sorted(self.populat... | The main task of the code is to evolve the next generation of a population in a genetic algorithm. It selects top-performing individuals, performs crossover operations to generate offspring, maintains elite individuals, and ensures the population size is maintained by adding new random individuals if necessary. The pro... | def next_generation(self):
best3 = self.selection(3)
if self.get_best_unit().score == 0:
print("Population reset")
self.reset_population()
new_population = list()
child_population = list()
child_population.append(self.crossover(best3[0], best3[1]))
... |
def remove_bottom_half_genomes_in_species(self):
"""
Removes the bottom half genomes in each species depending of the genome fitness
"""
for species in self.species_list:
species.genomes = list(reversed(sorted(species.genomes, key=lambda genome: genome.fitness)))
... | The main task of the code is to generate a new population by removing weak/stale species, calculating average fitness, breeding offspring proportional to species' fitness, and ensuring population size through selection and crossover, while incrementing the generation count. | def create_new_generation(self):
"""
Creates a new generation of population by using crossover and removing stale and weak species
"""
import math
# Remove bottom half of the genomes in each species based on fitness
self.remove_bottom_half_genomes_in_species()
# ... |
def checkCredentialsAndConnect(self):
# ask for server address and domain name if not already set via config file
if self.cfgDomain == "":
item, ok = QInputDialog.getText(self, '♕ Domain', 'Please enter your Domain name (e.g. example.com).')
if ok and item:
self.cfgDomain = item
self.server = None
... | The main task of the code is to search for a computer in an LDAP directory using a provided name. It validates input, authenticates if needed, performs an LDAP query for computer objects matching the name, retrieves attributes like SAMAccountname and distinguishedName, updates the UI with results or errors, and manages... | def OnClickSearch(self, e):
# check and escape input
computerName = self.txtSearchComputer.text()
if computerName.strip() == "": return
computerName = ldap3.utils.conv.escape_filter_chars(computerName)
# ask for credentials
self.btnSearchComputer.setEnabled(False)
if not self.checkCredentialsAndConnect()... |
def change_name(entry, root, head):
# validate change name string
if entry.get() != "":
if messagebox.askquestion("Access Required", "Are you sure?") == "yes":
head.name = entry.get()
entry.delete(0, tk.END)
root.title(head.name)
head.history.append("name ... | This code defines an admin interface GUI with functionalities to change names, add/remove/repair vehicles, and navigation controls. It creates labels, entry fields, and buttons for vehicle management tasks, linking actions to functions like change_name, handle_remove_vehicle, and final_repair. Navigation buttons allow ... | def admin_action(root, head):
print("admin action")
clear.clear(root)
change_name_label = tk.Label(text="change name :- ",
width="15",
bg="deep sky blue",
font=("Arial", 12))
change_name_label.place(re... |
def gain(root, head, bts):
frame = tk.Frame(root, width="1000", height="500", bg="white")
frame.place(relx=0.05, rely=0.1)
# list to show
listbox = []
global start_index_b
for i in range(len(head.all_cars)):
# insert to list
listbox.insert(i, [head.all_cars[i].id, head.all_cars[i... | The function `change_frame` updates button backgrounds based on the input `txt` value and invokes corresponding management functions (`gain`, `manage_cars`, or `manage_customers`) to switch between different UI sections. It acts as a controller to navigate between "gain", "cars", and "customers" modules by changing but... | def change_frame(root, head, txt, bts):
if txt== "gain":
bts[0].config(bg="red")
bts[1].config(bg="gray40")
bts[2].config(bg="gray40")
gain(root, head, bts)
elif txt == "cars":
bts[1].config(bg="red")
bts[0].config(bg="gray40")
bts[2].config(bg="gray40")
... |
def __loadData(self, datain=None):
data = datain
if data is None:
data = [json.load(open("../../static/data/cifar.json")), json.load(open("../../static/data/cifernew.json")) ]
ms = [Model(data_item) for data_item in data]
[m.buildModel() for m in ms]
return ms
def ge... | The code initializes a Dash application, loads data into models, sets the app layout using `getTopNav()`, registers callbacks, and sets up a shutdown process. | def __init__(self, data=None):
self.app = dash.Dash(__name__, external_stylesheets=self.external_stylesheets)
self.models = self.__loadData(data)
self.app.layout = self.getTopNav()
self.loadCallbacks()
self.loadShutdown() |
def navigate_page_1(driver):
driver.get("https://www.starbucks.com/shop/card/egift/workplace")
return driver
def cards_loop(price, email_arr, arr_len, driver):
email = ""
for i in range(arr_len):
email = email_arr.pop()
gift_card(price, email, driver, i, arr_len)
return driver
def ch... | The code automates gift card processing by navigating web pages, retrieving email lists and gift prices, looping through cards for input, and handling checkout. It uses a loop for multiple gift cards, prompts user confirmation, and performs guest checkout steps, requiring manual input at key stages for review and progr... | def main():
driver = webdriver.Chrome(ChromeDriverManager().install())
driver = navigate_page_1(driver)
flag = True
while flag == True:
emails = CommandLine()
price = emails.gift_price()
email_arr = emails.email_list()
#driver = webdriver.Chrome(options=options)
a... |
def obj_funcCLAHE(input):
target_chromosome=input
if input is target_chromosome:
obj_func=(1/1200)*entropy(input)+(1/1200)*edge_contentCLAHE(input)+(1/1200)*std(input)
# print("Objective Function(CLAHE):",obj_func)
return obj_func
def mse(org,en):
difference_array = np.subtract(org,e... | The code performs image enhancement using Discrete Wavelet Transform (DWT) with different methods (CLAHE, gamma correction, GA optimization) and evaluates results via PSNR, SSIM, and other metrics, displaying original vs. enhanced images for comparison. | def dwt_enhancemnet(o):
select=o
if (select=="1"):
img_new = np.float32(image)/256
h, w = img_new.shape
coeffs2 = dwt2(img_new, 'bior1.3')
LL, (LH, HL, HH) = coeffs2
LL/=256
LL=exposure.equalize_adapthist(LL, kernel_size=None, clip_limit=obj_funcCLAHE(LL), nbin... |
def user_inputs(self):
'''Checks user's inputs and acts in consequence'''
self.is_moving = False
if self.status != "Death":
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]: self.player_left()
if keys[pygame.K_RIGHT]: self.player_right()
if k... | This code updates game elements by processing player inputs, applying physics (gravity), managing character positioning, charging/super attacks, and updating sprite groups. It renders game objects like shields, super attacks, hearts, and players, excluding charged elements if the player's status is "Death" | def update(self):
screen = settings.screen
self.user_inputs()
self.apply_gravity()
self.stick_character_to_hitbox()
self.charge_super_attack()
self.check_super_attack()
self.set_heart_frame_index()
self.hit.update(self)
self.draw_super_attack_charg... |
def _install_config(host=None):
config = get_config('INSTALL.')
if host:
config.update(dict(get_config(f'INSTALL_{host}.')))
return config
def sjoin(split_command):
"""Return a shell-escaped string from *split_command*."""
return ' '.join(quote(arg) for arg in split_command)
def cmd_restart(... | The main task of the code is to reload an application using a configuration-specified command. It appends optional arguments from `args.arg`, logs the command, and executes it via `subprocess.run`. If no reload command exists, it defaults to restarting the app via `cmd_restart`. | def cmd_reload(args):
config = _install_config(get_config('ENVIRONMENT.INSTALL_HOST'))
reload_cmd = config.get('RELOAD_CMD')
if reload_cmd:
if args.arg:
reload_cmd += f' {sjoin(args.arg)}'
logger.info('Reloading app: %r', reload_cmd)
subprocess.run(['bash', '-c', reload_c... |
def _populate_from_globals(param_name: str, value: any, param_type: str, gbls: dict[str, dict[str, dict[str, Any]]]):
if value is None and gbls is not None:
if 'parameters' in gbls:
if param_type in gbls['parameters']:
if param_name in gbls['parameters'][param_type]:
... | This function generates query parameters from a dataclass instance by extracting fields annotated with 'query_param' metadata, applying serialization styles (form/deepObject), and incorporating global variables. It constructs a dictionary mapping parameter names to lists of values, handling nested structures and dynami... | def get_query_params(clazz: type, query_params: dataclass, gbls: dict[str, dict[str, dict[str, Any]]] = None) -> dict[str, list[str]]:
params: dict[str, list[str]] = {}
param_fields: Tuple[Field, ...] = fields(clazz)
for field in param_fields:
request_metadata = field.metadata.get('request')
... |
def marshal_json(val):
marshal = make_dataclass('Marshal', [('res', type(val))],
bases=(DataClassJsonMixin,))
marshaller = marshal(res=val)
json_dict = marshaller.to_dict()
return json.dumps(json_dict["res"])
def serialize_multipart_form(media_type: str, request: dataclass) ... | This function serializes HTTP request bodies based on the specified media type. It checks the media type to determine the serialization method: JSON, multipart/form-data, or URL-encoded. It returns a tuple containing the media type, serialized data (as JSON, bytes, or string), and None or processed form data. If the re... | def serialize_content_type(field_name: str, media_type: str, request: dataclass) -> Tuple[str, any, list[list[any]]]:
if re.match(r'(application|text)\/.*?\+*json.*', media_type) is not None:
return media_type, marshal_json(request), None
if re.match(r'multipart\/.*', media_type) is not None:
re... |
def _split_role_and_args(self, raw_role_and_args):
raw_role_and_args = raw_role_and_args.strip()
role = None
raw_args = ""
for known_role in self._KNOWN_ROLES:
if raw_role_and_args.startswith(known_role):
role = known_role
# expected format: A0... | The function processes a decoded string to extract arguments by removing special tokens, splitting the text into role-argument pairs, locating corresponding spans in the original tokens, and creating QasemArgument objects with extracted text, roles, and span indices. | def _postprocess(self, decoded: str, sample: ArgInputExample) -> list[QasemArgument]:
arguments = []
# we did not skip special tokens because we rely on <extra_id_2>
# now need to remove other special tokens by ourselves
decoded2 = decoded.replace(
self.tokenizer.pad_token, "... |
def _is_list_of_spacy_doc(cls, input: Any):
if not isinstance(input, list):
return False
return isinstance(input[0], Doc)
def _is_list_of_pretokenized(cls, input: Any):
if not isinstance(input, list):
return False
return isinstance(input[0], list) and input[0] and... | The code's main task is to extract verbal and nominal predicates from input sentences. It first validates and tokenizes the input (using spaCy if needed), then detects verbal predicates via `detect_verbal` and nominal predicates via `detect_nominal`. Finally, it combines these predicate lists per sentence and returns t... | def predict(self, sentences: List[Union[Doc, TokenizedSentence]]) -> List[List[Predicate]]:
# let's syntactically analyze the sentences first:
if not sentences:
return []
if self._is_list_of_spacy_doc(sentences):
docs = sentences
elif self._is_list_of_pret... |
def get_shorthand(person_links):
shortlinks = []
for link in person_links:
idx = link.find('_')
if idx != -1:
shortlinks.append(link[0:idx])
else:
shortlinks.append(link)
return shortlinks
def get_html(link):
html = requests.get(root + link)
soup = Bea... | The code converts a list of person links into a JSON structure representing nodes (people) and edges (connections between them), grouping nodes by 'groupnum' and saving the result to a file. It processes HTML data to extract connections and metadata, then writes the structured data as JSON. | def data_to_json(personlinks, groupnum, filename):
data = {
"nodes":[],
"edges":[]
}
index = 0
short_all = get_shorthand(personlinks)
for person in personlinks:
personhtml = get_html(person)
personconnections, connection_indices = get_connections(all_person_links, sho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.