dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def meaningful(tree, level):
'''
Number of moves in the meaningful search tree at level L
'''
total = 0
for node in tree.node_list:
if node.depth == level:
total += 1
return total
def possible_moves(tree, level):
'''
Number of legal moves at level L
'''
total ... | The main task of the code is to generate a collection of heuristic values from a tree structure at varying depths. It computes metrics like meaningfulness, possible moves, branching factors, and solution narrowness, padding results with zeros to standardize the output. The heuristics are concatenated into a numpy array... | def get_all_heuristics(tree, depth):
a = [meaningful(tree, d) for d in range(1, depth + 1)]
for x in range(depth + 1, 6):
a.append(0)
b = [possible_moves(tree, d) for d in range(1, depth + 1)]
for x in range(depth + 1, 6):
b.append(0)
c = [all_possible_moves(tree, depth)]
d = [br... |
def get_possible_moves(board):
n = len(board)
for i in range(n):
for j in range(n):
for k in range(n):
if board[i][j][k] == 0:
yield i,j,k
def fill_winning_lines(board, winning_lines):
n = len(board)
possible_lines = []
lines = list(winning_lin... | The main task of the code is to determine the optimal move in a 3D tic-tac-toe-like game by evaluating all possible moves using the minimax algorithm with alpha-beta pruning. It prioritizes filling immediate winning lines if many moves remain, otherwise selects the move with the highest minimax score to maximize the pl... | def best_move(board, winning_lines):
n = len(board)
best_score = float('-inf')
move = (-1, -1, -1)
if sum(1 for _ in get_possible_moves(board)) > n**3 - 5:
return fill_winning_lines(board, winning_lines)
for i,j,k in get_possible_moves(board):
# print(i,j,k)
board[i][j][k] = ... |
def reversed_arc(graph):
graph_rev = {}
for tail_node, head_node_list in graph.items():
for node in head_node_list:
if node not in graph_rev:
graph_rev[node] = [tail_node]
else:
graph_rev[node].append(tail_node)
return graph_rev
def DFS_Loop(gr... | The code implements **Kosaraju's algorithm** to find **Strongly Connected Components (SCCs)** in a directed graph. It first constructs a reversed graph, performs a DFS to determine node finishing times, maps these times to the original graph, and then conducts a second DFS to identify SCCs. The result is a list of SCC ... | def kosaraju_scc(graph):
global new_graph, grev
scc_info = []
# reversed graph
grev = reversed_arc(graph)
# 1st DFS on reversed graph
DFS_Loop(grev)
# print(magic_order)
print("\n===1st DFS finish!===\n")
del grev
gc.collect()
# map magic_order on graph
new_graph = ma... |
def ask_gpt(prompt):
url = "https://api.openai.com/v1/completions"
gpt_key = get_keys("/the-last-show/gpt-key")
headers = {
"Content-Type": "application/json" ,
"Authorization": f"Bearer {gpt_key}"
}
body = {
"model": "text-davinci-003",
"prompt": prompt,
"max_tokens": 40... | The main task of the code is to process a multipart/form-data request containing binary data and text fields (name, born, died), decode the request, generate an obituary message using AI, upload the binary data and generated text to Cloudinary, and store the results in a DynamoDB table. It handles JSON/base64 decoding,... | def handler(event, context):
"""try:
body = json.loads(event['body'])
print(body)
except KeyError:
body = {}
if "isBase64Encoded" in event and event["isBase64Encoded"]:
body = base64.b64decode(event['body'])
print("this mis a body", body)
else:
r... |
def state_quality(self, input_country: Country) -> float:
country_resources = input_country.resources
negative_resources_found = False
overconsumption_found = False
under_resource_threshold = False
state_quality = 0.0
for current_resource in country_resources.keys():
... | The function calculates the expected utility of an action in a world state transition. It evaluates the discounted reward from the current to next state of the agent's country, weighted by success probability, and adds a fallback value (C) for failure. The result is scaled by 100 to return a normalized utility score fo... | def expected_utility(self, current_world_state: list, next_world_state: list, depth: int, action: tuple) -> float:
my_country_current_state = next((country for country in current_world_state if country.name == MY_COUNTRY), None)
start_quality = self.state_quality(my_country_current_state)
my_cou... |
def _truncate_tables(self, session: Session):
all_tables = list(Base.metadata.tables.keys())
for table in all_tables:
session.execute(text(f'TRUNCATE TABLE IF EXISTS {0};'.format(table)))
def _seed_users(self, faker: Faker, session: Session):
# Generate users and posts:
users... | The code populates a database with fake data using Faker, truncating tables if specified. It seeds users and posts if none exist, then generates comments, likes, and follows for existing posts and users, ensuring related entities are created when empty. | def __call__(self) -> None:
faker = Faker()
Faker.seed(DB_SEED)
with Session(self.engine) as session:
count = session.query(User.user_id).count()
if TRUNCATE_TABLES:
self._truncate_tables(session)
# Generate users and posts:
if c... |
def test_put_validate_error():
ts = now();
# empty json string
execute_put_then_assert_fail("")
# invalid json
execute_put_then_assert_fail("{xxx")
# empty metric
execute_put_then_assert_fail("""
{
"metric": "",
"timestamp": {ts},
"value": 18,
"tags": {
"host": "web... | The main task of the code is to execute a series of unit tests for OpenTSDB's data insertion functionalities, including error validation, single/multi-point data insertion with varying data types (int/float), timestamp formats, and multi-table operations, to verify correctness and robustness of the system. | def main():
print("OpenTSDB test start.")
test_put_validate_error()
test_put_single_point_with_int_value()
test_put_single_point_with_float_value()
test_put_single_point_with_second_timestamp()
test_put_multi_points_with_different_tags_in_one_table()
test_put_multi_points_with_different_d... |
def PrepareImportFiles():
"""Create a list of ImportFile to conversion later.
This process is doing these things:
- Parse all input file patterns (*.txt) in FLAGS.input_file_pattern
- download to local for files on gcs
- dedup files by file path (to prevent uploading the same file twice)
- g... | The main task of the code is to process input files by preparing, converting, annotating, and uploading them to a specified GCS directory. It first logs the number of input files and target location, then sequentially prepares import files, converts them, annotates the converted files, and uploads the annotated files t... | def main():
print('Got %d inputs to convert and upload to %s' %
(len(FLAGS.input_file_pattern), FLAGS.target_gcs_directory))
import_files = PrepareImportFiles()
converted_files = ConvertFiles(import_files)
annotated_files = AnnotateFiles(converted_files)
UploadFiles(annotated_files, FLAGS.target_gcs_d... |
def generate_random_sha256(max_length=128):
characters = string.ascii_letters + string.digits + string.punctuation
random_string = ''.join(choice(characters) for _ in range(randrange(1, max_length + 1)))
sha256 = hashlib.sha256()
sha256.update(random_string.encode('utf-8'))
return sha256.hexdigest(... | The main task of the code is to mine cryptocurrency blocks by generating random data, hashing it with Argon2, and checking if the resulting hash meets specific targets (e.g., containing "XUNI[0-9]" or 65+ uppercase letters for "XEN11"). It dynamically adjusts mining difficulty, tracks progress, submits valid hashes to ... | def mine_block(stored_targets, prev_hash):
global memory_cost # Make it global so that we can update it
global updated_memory_cost # Make it global so that we can receive updates
found_valid_hash = False
#memory_cost=fetch_difficulty_from_server()
argon2_hasher = argon2.using(time_cost=difficulty,... |
def inferIntent(self, utterance):
encodings = self.intent_tokenizer([utterance], padding=True, truncation=True, return_tensors='pt')
# print(self.intent_model(encodings["input_ids"], attention_mask=encodings["attention_mask"])[0])
logits = self.intent_model(encodings["input_ids"], attention_mask... | The code processes a user message by inferring its intent and topic, tracking context, and compiling results into a structured output. It returns the detected intent (with confidence scores), inferred topic, and copies of the current context and cache for subsequent processing. | def process_user_message(self, utterance):
intent, intent_probs = self.inferIntent(utterance)
topic = self.inferTopic(utterance)
self.track_context(utterance)
cache = self.cache.copy()
context = self.context.copy()
output = {
"intent": intent,
"in... |
def setupscr(stdscr):
# Window is scrolled up one line when newline is added
stdscr.scrollok(1)
# Permits colour in terminal
curses.start_color()
# Allows use of key shortcuts
stdscr.keypad(True)
def exitscr():
# Restore cursor
curses.curs_set(1)
# Ends curses window
curses.endwi... | This function displays a text-based menu with customizable title, notes, and options using the curses library. It allows users to navigate options with arrow keys/WS, highlights the selected option, and returns the chosen option upon Enter or 'x' key press. The menu supports color formatting and handles user input for ... | def __PrintMenuOpts(title, notes, options):
stdscr = curses.initscr()
setupscr(stdscr)
curses.curs_set(0)
attributes = {}
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
attributes['normal'] = curses.color_pair(1)
curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)
... |
def setupscr(stdscr):
# Window is scrolled up one line when newline is added
stdscr.scrollok(1)
# Permits colour in terminal
curses.start_color()
# Allows use of key shortcuts
stdscr.keypad(True)
def exitscr():
# Restore cursor
curses.curs_set(1)
# Ends curses window
curses.endwi... | The function displays a menu with a title, notes, and input prompt using curses. It captures user input, exits on 'x/X', restarts on empty/enter, or returns the input. | def __PrintMenuInput(title, notes, prompt):
# Initializes the curses screen and sets up the screen
stdscr = curses.initscr()
setupscr(stdscr)
# Defines text attributes (colours)
attributes = {}
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
attributes['normal'] = curses.color_... |
def load_obj(self, name):
with open('obj/' + name + '.pkl', 'rb') as f:
return pickle.load(f)
def save_obj(self, obj, name):
with open('obj/'+ name + '.pkl', 'wb') as f:
pickle.dump(obj, f)
def __StartCap(self):
global basesettings
# Used to count how many packet... | The code initializes by loading base settings, generates a unique PCAP log file name to avoid overwriting existing files, creates the PCAP file, updates the settings with the new log path, saves the updated settings, and initiates packet capture. | def __init__(self):
# Loads the pickle object for the base settings dictionary
global basesettings
basesettings = self.load_obj('settings')
# Creates the log files
pathfile = (basesettings['BaseCapPath'] + '/' + basesettings['BaseFileName'])
# Checks to see if file alre... |
def ispath(path):
if path.startswith('~'):
return os.path.exists(path)
elif path.startswith('/'):
return os.path.exists(path)
else:
curdir = os.getcwd()
curpath = curdir + '/' + path
return os.path.exists(curpath)
def __ReadPCAP(PCAP):
packets = rdpcap(PCAP)
r... | The code's main task is to process a provided PCAP file by validating its path, creating a directory to store analysis results, and executing packet analysis. It checks for command-line arguments, verifies the PCAP file's existence, generates a unique output folder, sets permissions, reads packets, and computes statist... | def __Main():
global savepath
if len(sys.argv) > 1:
# Where to find the PCAP file to analyze
PCAP = sys.argv[1]
# Verify that the provided PCAP file is valid
if ispath(PCAP) == False:
print("[*] Error: Unknown path")
sys.exit()
# Determining wher... |
def player_data(player_url):
response = requests.get(player_url)
soup = BeautifulSoup(response.text, 'html.parser')
get_pic(soup)
player_info(soup)
st.session_state['soup'] = soup
def player_tables(url):
drop_list = ['Age', 'Lg', 'Pos', 'G', 'MP']
per_game = pd.read_html(url, attrs = {"id"... | This function retrieves and displays basketball player statistics by constructing a URL from the player's name and extension. It checks if the name matches the session state; if not, it fetches player data, extracts regular and playoff seasons, determines peak performance, and updates session variables. If the name mat... | def player_stats(name, ext, option):
url = 'https://www.basketball-reference.com/players/'
end = '.html'
player_url = url + ext[0] + '/' + ext + end
if name != st.session_state['name']:
player_data(player_url)
regular, playoffs = player_tables(player_url)
peak_data = determine... |
def create_sidebar():
sb = st.sidebar
sb.title(":basketball: Basketball Peak Finder V2")
name = sb.text_input("Enter a player's name:", value="").strip().lower()
option = sb.selectbox("Select an option:", ["Regular Season", "Playoffs"])
return sb, name, option
def get_player(name):
with open('p... | The main task of the code is to retrieve and display player statistics based on user input. It creates a sidebar for input, checks if a player name is provided, fetches the player's URL, and displays an error if the player isn't found. If valid, it shows the player's name and calls a function to generate statistics usi... | def main():
sb, name, option = create_sidebar()
if name != '':
ext = get_player(name) # retrieves player URL
if ext == None:
sb.error("Player not found. Please check spelling and try again.")
else:
st.subheader(name.upper())
player_stats(name, e... |
def get_filings(filters: Dict[str, str]) -> Dict[str, Any]:
"""pulls filings from openfec api"""
path = '/filings/'
reports = []
openFec = OpenFec(API_KEY)
for report in openFec.get_route_paginator(path, filters):
results = report['results']
if results:
reports.append(r... | This AWS Lambda function processes incoming messages to extract committee IDs, retrieves filings and totals for the current cycle from a database/API, handles 404 errors, and upserts parsed data into storage. It logs events, flattens nested results, and ensures data is persisted for each committee's latest report. | def lambdaHandler(event:dict, context: object) -> bool:
"""see https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html"""
logger.debug(json.dumps(event))
messages = event['Records']
for message in messages:
message_parsed = parse_message(message)
committee_id = message_parse... |
def mk_candles( qty=0, num_lit=0, width=0 ):
''' Make a string that represents candles.
qty = total number of candles
num_lit = number of candles that should be burning
'''
if qty < 0:
raise UserWarning( 'num candles cant be less than 0' )
if num_lit > qty:
raise UserWarn... | The function `mk_cake` validates input parameters for a cake-making process, calculates the cake's width based on the number of guests, and delegates tasks to create candles, layers, and a bottom. It ensures parameters like `num_guests`, `layers`, `num_candles`, and `lit_candles` meet constraints (e.g., non-negative va... | def mk_cake( num_guests=2, layers=1, num_candles=1, lit_candles=1 ):
if num_guests < 1:
raise UserWarning( 'num_guests cannot be less than 1' )
if layers < 1:
raise UserWarning( 'layers cannot be less than 1' )
if num_candles < 1:
raise UserWarning( 'num_candles cannot be less than 1... |
def load_data(root):
"""Load synthetic dataset.
Args:
root (type): Dataset directory to load the dataset.
Returns:
tuple: dataset, index_quant_map.
Raises: ExceptionName: Why the exception is raised.
Examples
Examples should be written in doctest format, and
sh... | The function creates a DataLoader for a specified dataset by loading data, configuring input/output quantities based on the dataset type (MotorDynamics, MotorDenoise, SpeedTorque), instantiating a preloader, and returning the DataLoader along with the sample count. It handles dataset-specific feature mappings and batch... | def _get_loader(dir, args, shuffle):
dataset, index_quant_map = load_data(dir)
samples = get_sample_metadata(dataset, 1, 100)
preloader_class = _get_prelaoder_class(args)
if args.dataset == 'MotorDynamics':
inp_quants = ['voltage_d', 'voltage_q', 'speed']
out_quants = ['current_d', 'curr... |
def generate_new_customers(self):
if random.uniform(0, 1) < CUSTOMER_PROBA_LST[self.time[0]]:
self._generate_new_customer()
def generate_new_taxi(self):
if len(self.customers) / max(len(self.taxis), 1) < CUSTOMERS_TO_TAXIS_RATIO:
return
possible_lst = list(self.city_plan... | The code simulates a step in a system managing customers and taxis by generating new entities, assigning taxis to customers, processing customer statuses (waiting, inside, end), updating taxi statuses, tracking waiting time metrics, removing completed customers, and advancing the system time. It ensures efficient resou... | def make_step(self):
self.generate_new_customers()
self.generate_new_taxi()
self.assign_taxis_to_customers()
customers_to_delete = []
for i, customer in enumerate(self.customers):
if customer.status == CustomerStatus.WAITING:
self._process_customer_w... |
def daftar():
success = False
while (True):
NamaDepan = input("Masukkan nama depan peminjam: ")
if NamaDepan.isalpha():
break
while (True):
NIM = input("masukkan 5 digit terakhir NIM anda: ")
if NIM.isnumeric():
menu_awal()
break
pr... | The code manages a library system by checking user registration status, retrieving loan records from a text file, validating user data, generating a return receipt with date/time, and initializing the main menu. It handles errors for invalid users and creates structured documentation for book returns. | def pembuka():
print(" Selamat Datang di Perpustakaan FT 11 Maret ")
x = input("daftar sebagai anggota dulu, ya(Y/N)!")
if x == "Y":
daftar()
elif x == "N":
name = input("Masukkan nama peminjam: ")
NIM = input("maukkan 5 digit terakhir NIM Anda")
a = "Pinj... |
def get_matrix_from_cache(position: Position, push_to_top: True) -> Matrix:
for matrix_index in range(len(cache_matrices)):
if not cache_matrices[matrix_index].is_position_out_of_limits(position):
matrix = cache_matrices[matrix_index]
if push_to_top:
cache_matrices.ap... | The function `swap_matrixes` retrieves or generates a matrix based on the current position and command, updates the current matrix state, adds a new entry position to the matrix, and ensures the matrix is cached. It prioritizes cached data, falls back to the database, and generates a new matrix if necessary, then final... | def swap_matrixes(command: str) -> None:
global current_position
matrix = get_matrix_from_cache(current_position, True)
if matrix is not None:
set_current_matrix(matrix)
visit_house()
add_new_entry_position_to_matrix(matrix)
return
matrix = get_matrix_from_db(current_p... |
def get_new_position(command: str, position: Position) -> Position:
new_position = Position(position.x, position.y)
if command == "N":
new_position.y += 1
if command == "S":
new_position.y -= 1
if command == "E":
new_position.x += 1
if command == "O":
new_position.x -... | The code processes a movement command by updating the current position, checking if it exceeds matrix limits (swapping matrices if so), marking new positions as visited, and incrementing the total Pokémon count when applicable. | def process_command(command: str) -> None:
global current_position
current_position = get_new_position(command, current_position)
if current_matrix.is_position_out_of_limits(current_position):
swap_matrixes(command)
elif not current_matrix.has_position_been_visited(current_position):
cu... |
def is_input_valid(commands: str) -> bool:
for character in commands:
if character != "N" and character != "O" and character != "E" and character != "S":
return False
return True
def init() -> None:
global total_pokemons_hunted
total_pokemons_hunted = 0
db_service.init()
gl... | The `pokemon_hunt` function processes a user-input command list to simulate Pokémon hunting. It validates the input, initializes game state, executes each command sequentially, and closes the database connection. The function aims to track and return the total Pokémon hunted but incorrectly returns `total_pokemons_hunt... | def pokemon_hunt() -> None:
global input_
global input_index
input_ = input("Enter your list of commands: ")
# file = open("../inputs/input6.txt", "r")
# input_ = file.read()
if not is_input_valid(input_):
#print("Bad input")
return -1
init()
for input_index in range(... |
def initialize(self):
# Randomly generate generation_size points to self.generation
print("INIT")
self.generation = []
for _ in range(self.generation_size):
x = []
for decision in self.decision_boundary:
if type(decision) == list:
... | The main task of the code is to execute a genetic algorithm (GA) to optimize and evolve solutions, iteratively selecting, competing, and mutating candidates to find the best Pareto frontier (pf_best). The algorithm runs until reaching the maximum generation limit or exhausting its "life" counter, returning the final no... | def tune(self):
# Main function of my_GA
# Stop when self.iter == self.max_generation or self.life == 0
# Return the best pareto frontier pf_best (list of decisions that never get binary dominated by any candidate evaluated)
print("TUNE")
self.initialize()
while self.life... |
def get_agent_under_mouse(self, agents):
mouse_pos = pygame.mouse.get_pos()
return self.get_clicked_agent(mouse_pos, agents)
def draw_pheromones(self, pheromones):
# If you want a semi-transparent overlay, retain the following lines
surface = pygame.Surface((self.window.get_width(), self... | This function updates the simulation by handling user input, rendering agents, items, and pheromones, displaying a "Paused" message when active, generating plots from statistics, and recording video frames. It manages game state transitions, visual feedback, and data visualization within a Pygame window. | def update(self, agents, items, pheromones=None, draw_pheromones_flag=True, stats=None):
hovered_agent = None
# Handle events first
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
# Detect... |
def create_configmap():
i = random.randint(0, 99)
cm = client.V1ConfigMap(
metadata=client.V1ObjectMeta(
name=f"test-{i:02}"))
configmaps[i] = create_or_get_configmap(cm)
def update_configmap():
if not configmaps:
return
i = random.choice(list(configmaps.keys()))
... | The main task of the code is to interact with a Kubernetes cluster by creating, updating, deleting, or listing ConfigMaps in a specified namespace. It first connects to the cluster, checks the version, creates a namespace if it doesn't exist, then randomly performs ConfigMap operations in a loop for a given number of r... | def main(rounds, *args, **kwargs):
global v1
try:
config.load_kube_config()
version = client.VersionApi().get_code()
logging.info(f"Connected to {Configuration._default.host} - {version.git_version}")
except Exception as e:
logging.error(f"Kubernetes version check failed: {e... |
def read_paris_file(pairs_filename):
pairs = []
with open(pairs_filename, 'r') as f:
# NOTE first line is properties of the pairs file
for line in f.readlines()[1:]:
pair = line.strip().split()
pairs.append(pair)
return np.array(pairs)
def get_pairs(pairs):
"""
... | The code evaluates a face recognition model's performance using a test set of image pairs. It loads a pre-trained model, extracts embeddings from image pairs, computes cosine similarity thresholds, and calculates metrics like accuracy, AUC, EER, and FPR. The evaluation processes images in batches, compares embeddings a... | def main(args):
thresholds = np.arange(0, 4, 0.001)
global gdt
gdt = GetDistanceTensorflow(metric_type='cos', embedding_dim=args.embedding_dim, epslon=1e-8)
print('** start evaluation pipeline.')
print('(1) load model.\n')
fe = FeatureExtractorCtrl(args.use_model, args.model_path, args.gpu_mem... |
def calc_reynoldsnum(q_lpm, diam_m, rho, mu):
area_m2 = calc_area(diam_m)
vel_mps = flow_to_vel(q_lpm, area_m2)
reynoldsnum = rho * vel_mps * diam_m / mu
return reynoldsnum
def flow_to_vel(q_lpm, area_m2):
'''converts flow rate (m3/s) and area (m2) to velocity (m/s)'''
q_m3s = lpm_to_m3s(q_lpm)
... | This function calculates the pressure drop using the Modified-Pedley/van Ertbruggen model, which incorporates a generation-dependent gamma factor, Reynolds number, and fluid properties. It computes the pressure drop by combining viscous and inertial effects through a formula involving gamma, Reynolds number, pipe dimen... | def calc_pdrop_modpedley(q_lpm, diam_m, length_m, rho_kgm3, mu_pas, gen):
"""Modified-Pedley/van Ertbruggen model pressure drop"""
GAMMA_DICT = {0:0.162, 1:0.239, 2:0.244, 3:0.295,
4:0.175, 5:0.303, 6:0.356, 7:0.566}
gamma = GAMMA_DICT.get(gen, GAMMA_DICT[7]) # use gen7 gamma for higher ge... |
def calc_reynoldsnum(q_lpm, diam_m, rho, mu):
area_m2 = calc_area(diam_m)
vel_mps = flow_to_vel(q_lpm, area_m2)
reynoldsnum = rho * vel_mps * diam_m / mu
return reynoldsnum
def flow_to_vel(q_lpm, area_m2):
'''converts flow rate (m3/s) and area (m2) to velocity (m/s)'''
q_m3s = lpm_to_m3s(q_lpm)
... | This function calculates the pressure drop in a pipe using the Blasius turbulent flow model. It computes the friction factor based on Reynolds number, then applies the Darcy-Weisbach equation with velocity, density, and pipe dimensions to determine the pressure loss. | def calc_pdrop_blasius(q_lpm, diam_m, length_m, rho_kgm3, mu_pas, c_coef=0.316):
"""Turbulent Blasius model pressure drop"""
ALPHA = 0.25
reynoldsnum = calc_reynoldsnum(q_lpm, diam_m, rho_kgm3, mu_pas)
f = c_coef*(reynoldsnum + 0.0000001)**-ALPHA
vel_mps = flow_to_vel(q_lpm, calc_area(diam_m))
p... |
def collectBeanIds(self, startDir):
idList = {}
otherXML = {}
ET.register_namespace('bean',self.nsbeansuri)
for dirName, subdirList, fileList in os.walk(startDir):
if re.match('.*/(target|\.svn|alf_data_dev)/.*', dirName):
continue
if True: #re.ma... | The code compares bean definitions across three versions (custom, old, new) by collecting bean IDs, checking their presence in each version, and reporting differences. It compares XML elements, checks class consistency, and triggers Java class comparisons if classes differ. It logs info or action requirements for beans... | def compareBeanDefs(self, oldPath, newPath):
myIdList, myOtherXML = self.collectBeanIds(self.customPath) # print str(myIdList)
oldIdList, oldOtherXML = self.collectBeanIds(oldPath)
# print str(oldIdList)
newIdList, newOtherXML = self.collectBeanIds(newPath)
for beanDef in myId... |
def handle_disruption(self):
"""
handle disruption behaviour: count down ongoing disruptions, start new disruptions
"""
if self.is_in_disruption:
# count down the disruption duration
self.left_disruption_duration -= 1
if self.left_disruption_du... | The code simulates a supply chain environment step by step, updating inventory, orders, and shipments based on policies (PPO, BS, STRM) or disruptions. It calculates rewards, tracks inventory levels, demand, shortages, and overstock, then returns the new state, reward, episode status, and detailed metrics for reinforce... | def step(self, action = None):
"""take a step in the environment
Args:
action (List[int], optional): Actions to take, BS or STRM calculated in place. Defaults to None.
Returns:
state: current state
reward: step reward
done: indicates if episode i... |
def add_sidebar():
st.sidebar.header("Cell Nuclei Details")
data=get_clean_data()
slider_labels = [
("Radius (mean)", "radius_mean"),
("Texture (mean)", "texture_mean"),
("Perimeter (mean)", "perimeter_mean"),
("Area (mean)", "area_mean"),
("Smoothness (mean)"... | The main task of the code is to create a Streamlit web application for breast cancer prediction using machine learning. It sets up a styled interface with a sidebar for input sliders, displays a radar chart of user-provided cytology data, and generates predictions based on the input. The app includes an "Info" button t... | def main():
st.set_page_config(
page_title="Breast Cancer Predictor",
page_icon=":female-doctor",
layout="wide",
initial_sidebar_state="expanded"
)
current = os.path.dirname(os.path.realpath(__file__))
css_file_path = os.path.join(current, "../assets/style.css")
with ... |
def attacks(sp: GameStatePer, s: GameState) -> Tuple[Set[Planet], List[Fleet]]:
attacked_planets: Set[Planet] = set()
attacking_fleets: List[Fleet] = list()
for fleet in s.fleets:
is_friendly = fleet.owner_id == s.player_id
if is_friendly:
continue
target = s.planet_get... | This function identifies the optimal friendly position to attack an unfriendly target by evaluating distance, ship availability, and battle outcomes. It skips invalid or suboptimal attacks, prioritizing the closest viable source that can successfully capture an enemy position. If a valid target is found, it returns a S... | def strat_capture_simple(sp: GameStatePer, s: GameState) -> Move:
attacked, fleets = attacks(sp, s)
best_from, best_to, best_dist = None, None, 0
for target in unfriendly(s):
for src in friendly(s):
dist = sp.dist(src, target)
if sp.is_reserved(src):
continu... |
def attacks(sp: GameStatePer, s: GameState) -> Tuple[Set[Planet], List[Fleet]]:
attacked_planets: Set[Planet] = set()
attacking_fleets: List[Fleet] = list()
for fleet in s.fleets:
is_friendly = fleet.owner_id == s.player_id
if is_friendly:
continue
target = s.planet_get... | The function determines if a bailout move is necessary by checking imminent attacks, simulating battle outcomes, and selecting the nearest safe planet to retreat to, returning a Send move if conditions are met; otherwise, returns Nop. | def strat_bailout(sp: GameStatePer, s: GameState) -> Move:
attacked_planets, attacking_fleets = attacks(sp, s)
for fleet in attacking_fleets:
# only bail if attack eminent
delay = fleet.eta - s.round
if delay > 4:
continue
origin = s.planet_get(fleet.origin_id)
... |
def attacks(sp: GameStatePer, s: GameState) -> Tuple[Set[Planet], List[Fleet]]:
attacked_planets: Set[Planet] = set()
attacking_fleets: List[Fleet] = list()
for fleet in s.fleets:
is_friendly = fleet.owner_id == s.player_id
if is_friendly:
continue
target = s.planet_get... | The function determines if any friendly planet can send ships to defend against an imminent attack by simulating battle outcomes. It identifies attacking fleets, checks if their attacks are imminent, and evaluates friendly planets' ability to reinforce the target planet's defense. If a suitable planet is found, it send... | def strat_defend(sp: GameStatePer, s: GameState) -> Move:
attacked_planets, attacking_fleets = attacks(sp, s)
for fleet in attacking_fleets:
# only bail if attack eminent
delay = fleet.eta - s.round
origin = s.planet_get(fleet.origin_id)
target = s.planet_get(fleet.target_id)
... |
def log(data):
cols_names = [f.name for f in fields(Stats)]
try:
exists = not os.path.exists(CSV_FILE)
with open(CSV_FILE, 'a') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=cols_names)
if not exists:
writer.writeheader()
writer.write... | This code processes a game state update, selects the highest-priority strategic move (e.g., capture, defend), updates statistics, executes move callbacks, and returns the chosen action. If the game is over, it logs victory/defeat stats and returns a no-op. | def tick(self, raw: dict) -> Union[Send, Nop]:
s = GameState.load(raw)
self.s = s
self.sp.init(s)
sp = self.sp
if s.over:
if s.winner == s.player_id:
stats.Victory = True
print('Victory')
else:
print('Defea... |
def is_assigned(history: Any, direction: Literal['from', 'to']) -> bool:
result = None
for it in history.items:
if it.field == 'assignee':
if (direction == 'to' and it.to == config.JIRA_ACCOUNT_ID) or (
direction == 'from' and getattr(it, 'from') == config.JIRA_ACCOUNT_ID... | This function processes Jira issue history items to update work records and log status/assignee changes. It checks if history relates to the user's account or assignments, then processes status changes by adding work logs and printing details. For assignee changes (when the user removed themselves), it updates the end ... | def process_history_items(issue: Issue, history: Any, issue_work: Dict[str, List[Activity]]) -> None:
assigned_to_me = is_assigned(history, 'to')
assigned_from_me = is_assigned(history, 'from')
if history.author.accountId == config.JIRA_ACCOUNT_ID or assigned_to_me or assigned_from_me:
for item in ... |
def process_history_items(issue: Issue, history: Any, issue_work: Dict[str, List[Activity]]) -> None:
assigned_to_me = is_assigned(history, 'to')
assigned_from_me = is_assigned(history, 'from')
if history.author.accountId == config.JIRA_ACCOUNT_ID or assigned_to_me or assigned_from_me:
for item in ... | The function processes Jira issues in batches, retrieving histories and comments for each, then aggregates valid activities with both start and end times. It iterates through paginated results, updating ongoing issues and compiling activities into a list for return. | def process_issues(ongoing_issues: List[str] = None, start_at: int = 0, max_results: int = 100) -> List[Activity]:
if ongoing_issues is None:
ongoing_issues = []
issue_work: Dict[str, List[Activity]] = dict()
while True:
issues = jira_client.search_issues(start_at=start_at, max_results=max_r... |
def _xr(self, epsilon, K, L, a):
if (self._fx(L, a))**3 > epsilon:
return (self._fx(L, a))**3
else:
return (116*self._fx(L, a) - 16)/K
def _yr(self, epsilon, K, L):
if L > K*epsilon:
return ((L+16)/116)**3
else:
return L/K
def _zr(self, eps... | This function converts a color from CIELAB (L,a,b) space to CIELUV (L,u,v) space using CIE standard formulas. It calculates XYZ values from L,a,b, adjusts L based on Y/Yr, then computes u and v using reference white point D65 values. The conversion involves non-linear transformations and normalization to derive the fin... | def _CIELUV_convert(self, chip):
'''Returns a chip in the form of (L,u,v), representing its position in CIELUV space.
chip is originally given as a 3-tuple (L,a,b).
'''
L = chip[0]
a = chip[1]
b = chip[2]
e = 0.008856 #Actual CIE Standard
K = 903... |
def plot_empty(lang_nu, theta, write=True, plot=True):
'''Plots the empty type classifications of color chips in heatmaps organized by simulation round.
write determines whether the classifications are written out into a file (rows: simulation rounds (snapshots from every 10,000 rounds), columns: 320 color chips)
pl... | This function processes multiple languages (lang_list) by iterating through theta values (0 to 1 in 0.1 steps). For each language-theta pair, it calls plot_empty (for visualization/data export), boundary_chips (to generate boundary chips), and get_bound_prob (to calculate boundary probabilities). The write_emp and plot... | def do_all(lang_list, write_emp=True, plot_emp=True):
'''Generates all of the data at once for all the langs in lang_list.'''
for lang_num in lang_list:
for theta in np.linspace(0,1,11):
theta = round(theta, 1)
print("LANG NUM: " + str(lang_num) + " // theta = " + str(theta))
plot_empty(lang_num, theta, w... |
def get_user_account(self):
return User_Account.objects.last()
def create_company(self, company_name="MaskPlanet"):
company, status = Company.objects.get_or_create(company_name=company_name, date_joined=timezone.now(),
uid='334e3af3-648f-455d-b100-effbc2060268', us... | The code creates a new Transaction instance with predefined and dynamically generated fields, including a fixed UID, user account, income type, sum, transaction ID, and associated company, account, and contractor objects. It returns the created transaction. | def create_transaction(self):
transaction, status = Transaction.objects.create(uid='664e27f3-648f-455d-b100-effbc2079126', user_account=self.get_user_account(),
transaction_type='Income', sum_of_transactions=36, transaction_id='Y35HREF',
... |
def scan_up_generator(self, step_size, max_steps, scale=1):
max_pos = self.focus.zpos + abs(max_steps)
while self.focus.zpos < max_pos:
yield self.get_tile(scale=scale)
self.focus.up(step_size)
def scan_down_generator(self, step_size, max_steps, scale=1):
max_pos = self.f... | The code scans in a specified direction (up/down) to find the optimal focus position by analyzing the variance of the Laplacian in generated images. It tracks z-positions and blur values, returning the best focus point when a "sweetspot" (sufficient focus) is detected and subsequent blur decreases. If no valid focus is... | def scan(self, stepsize=10, maxsteps=200, thresh=100, direction=-1):
zpos = []
blur = []
sweetspot = False
if direction == 1:
image_gen = self.scan_up_generator(stepsize, maxsteps)
else:
image_gen = self.scan_down_generator(stepsize, maxsteps)
for ... |
def scan_up_generator(self, step_size, max_steps, scale=1):
max_pos = self.focus.zpos + abs(max_steps)
while self.focus.zpos < max_pos:
yield self.get_tile(scale=scale)
self.focus.up(step_size)
def scan_down_generator(self, step_size, max_steps, scale=1):
max_pos = self.f... | This code scans through focus positions (up/down) to check if an image reaches a specified blur threshold using Laplacian variance. It returns True if the blur meets or exceeds the target, otherwise False after exhausting steps. | def find(self, stepsize=1, maxsteps=50, blur_target=100, direction=-1):
zpos = []
blur = []
if direction == 1:
image_gen = self.scan_up_generator(stepsize, maxsteps)
else:
image_gen = self.scan_down_generator(stepsize, maxsteps)
for i, img in enumerate(ima... |
def LoadTroikaDataset():
"""
Retrieve the .mat filenames for the troika dataset.
Review the README in ./datasets/troika/ to understand the organization of the .mat files.
Returns:
data_fls: Names of the .mat files that contain signal data
ref_fls: Names of the .mat files that contain r... | The `Evaluate()` function assesses the performance of a pulse rate algorithm on the Troika dataset. It loads dataset files, iterates through each trial, executes the pulse rate algorithm, collects error and confidence metrics, aggregates them, and computes an overall error metric using `AggregateErrorMetric`. The resul... | def Evaluate():
"""
Top-level function evaluation function.
Runs the pulse rate algorithm on the Troika dataset and returns an aggregate error metric.
Returns:
Pulse rate error on the Troika dataset. See AggregateErrorMetric.
"""
# Retrieve dataset files
data_fls, ref_fls = LoadTro... |
def LoadTroikaDataset():
"""
Retrieve the .mat filenames for the troika dataset.
Review the README in ./datasets/troika/ to understand the organization of the .mat files.
Returns:
data_fls: Names of the .mat files that contain signal data
ref_fls: Names of the .mat files that contain r... | The function `test_function` evaluates the pulse rate algorithm on a specific subject from the Troika dataset. It retrieves the subject's data, runs the algorithm to compute errors and confidence, and prints the mean error. Parameters control whether to visualize raw/filtered signals or spectrograms. The function does ... | def test_function(idx, figures="", specgram=False):
'''
Top-level function to test code.
Runs the pulse rate algorithm on one subject of the Troika dataset
and prints some metrics and dsiplay figures.
Parameters: - idx: positive int, index of subject to evaluate
- figures: arraysof ... |
def read_message(log_file):
hs = open(log_file,"r", encoding="utf8")
a = hs.read()
hs.close()
return a
def get_main_table():
if settings.USE_DATABASE == True:
select_sql = "SELECT bot_id , strategy ,minutes , DATE_FORMAT(bot_start_run, '%Y-%m-%d %h:%i:%s') AS bot_start_run , wa... | The main task of the code is to generate an HTML email containing a dynamically populated table and embedded images, then securely send it via SMTP to a specified email address. It reads a template, constructs table rows from database data, attaches chart images using Content-ID headers, and sends the email with embedd... | def send_email(email_addr):
template_path = static_path + "email_template/maintable.html"
template_content = read_message(template_path)
table_url = settings.BASE_URL + "/wallet_status/maintable"
image_path = static_path + "images/chart/"
table_content = ""
chart_content = ""
table = get_... |
def getBestSplit(self, dataset, num_samples, num_features):
# dictionary to store the best split
best_split = {}
max_info_gain = -float("inf")
# loop over all the features
for feature_index in range(num_features):
feature_values = dataset[:, feature_index]
... | The code recursively builds a decision tree by splitting the dataset at each node based on the best information gain, subject to constraints on maximum depth and minimum samples per split. If conditions permit further splitting, it recursively constructs left and right subtrees. If not, it creates a leaf node with the ... | def buildTree(self, dataset, curr_depth=0):
X, Y = dataset[:,:-1], dataset[:,-1]
num_samples, num_features = np.shape(X)
# split until stopping conditions are met
if num_samples>=self.min_samples_split and curr_depth<=self.max_depth:
# find the best split
... |
def run_episode(self):
# reset state at the beginning of each iteration
self.reset_env()
state = self.env.get_state()
states = np.zeros((self.horizon, self.env.n_links*self.training_actor[self.env.network].num_features), dtype=np.float32)
actions = [] #np.zeros(self.horizon, dtyp... | This function trains a reinforcement learning agent by iterating through episodes, collecting experience data, computing generalized advantage estimates (GAE), updating actor and critic networks via policy gradient methods, logging training progress, and periodically evaluating performance while saving model checkpoint... | def train_and_evaluate(self):
training_episode = -1
while not (self.env.num_sample == self.last_training_sample and self.change_sample == True):
training_episode += 1
print('Episode ', training_episode, '...')
states, actions, rewards, log_probs, values, last_value = ... |
def viewAllgames(self):
"""
Print names of all games on system.
"""
print("All games in this software:")
for name in self.games.keys():
print(name)
def exit(self):
"""
Exit the software
"""
self.save()
self.activePlayer = None
... | This function displays the active player's profile, allowing them to view their game collection or manage it. It enters a loop showing the profile, lists all games, and prompts for input: '0' to exit or '1' to manage games. Invalid inputs trigger an error message, while '0' exits the current context and '1' navigates t... | def jumpToProfile(self):
"""
Jump to active player's profile
"""
while True:
print("-------------------- {}'s Profile ----------------------\n".format(self.activePlayer.name))
self.viewAllgames()
self.activePlayer.viewPersonalGames()
cmd ... |
def signUp(self):
"""
Sign up a new account
"""
print("-------------------- Sign Up Page ----------------------")
playerName = input("Signup: input player name: ")
if playerName in self.players:
print("name {} has existed\n". format(playerName))
re... | This code displays a welcome page allowing users to either sign up (0) or log in (1). It loops until a valid choice is made, then calls the corresponding method (signUp/login). Once authentication is successful (activePlayer is set), it transitions to the user's profile page. | def welcome(self):
"""
Welcome page of the software, where players can log in an account
or sign up a new account.
"""
while self.activePlayer == None:
print("-------------------- Welcome Page ----------------------")
choice = input("0 to sign up, 1 to l... |
def set_buffer_length(expected_area, AB_flag, flag_override):
if AB_flag & (not flag_override):
# if the artificial boundary flag is present,
# return a buffer length equivalent to the expected
# area divided by 2*dx where dx is the pixel resolution
print(' ...HYSETS artificial b... | This function generates a basin polygon for a hydrological station by processing digital elevation model (DEM) data. It reprojects spatial data, clips and reprojects the DEM, fills depressions, calculates flow direction and accumulation, snaps the pour point, delineates the watershed using hydrological tools, converts ... | def derive_basin_polygon(row, proj_crs, basin_temp_folder, write_file=True):
station_id = row['Official_ID']
gsim_flag = row['Flag_GSIM_boundaries']
gsim_da = row['Drainage_Area_GSIM_km2']
hysets_area = row['Drainage_Area_km2']
stn_loc = gpd.GeoDataFrame(geometry=[row['geometry']], crs=f'EPSG:4326... |
def process_basin_elevation(clipped_raster):
# evaluate masked raster data
values = clipped_raster.data.flatten()
mean_val = np.nanmean(values)
median_val = np.nanmedian(values)
min_val = np.nanmin(values)
max_val = np.nanmax(values)
return mean_val, median_val, min_val, max_val
def calculat... | The function processes basin characteristics for a given station by calculating and compiling key hydrological and geographical attributes, including elevation statistics, slope, aspect, drainage area, Gravelius index, perimeter, permeability, porosity, and land use data, using input raster and polygon data. It aggrega... | def process_basin_characteristics(stn, reproj_raster):
print(f' ...processing {stn} basin characteristics')
basin_data = {}
# print(f' Processing {stn}')
basin_data['Official_ID'] = str(stn)
# hysets_data = hysets_stn_df[hysets_stn_df['Official_ID'] == stn]
# hysets_area = hysets_data['Dr... |
def polygon_area(polygon):
"""
Finds the true area of a polygon
Args:
polygon: shapely polygon
Returns:
The area of that polygon in square kilometers
"""
return abs(Geod(ellps="WGS84").geometry_area_perimeter(polygon)[0])/1e6
def split_polygon(polygon, axis):
"""
Splits ... | This function recursively splits a Shapely polygon into smaller regions until each has an area below the specified max_area. It uses a chosen axis (e.g., 'minor') to divide the polygon iteratively, collecting all resulting parts into a GeometryCollection. If a polygon's area is already under max_area, it is directly re... | def split_recursive(polygon, axis='minor', max_area=2.8):
"""
recursively splits a shapely polygon into parts that are all smaller than the max_area
Args:
polygon: shapely polygon to split up
axis: the type of split by axis (vertical, horizontal, minor)
max_area: the maxi... |
def split_recursive(polygon, axis='minor', max_area=2.8):
"""
recursively splits a shapely polygon into parts that are all smaller than the max_area
Args:
polygon: shapely polygon to split up
axis: the type of split by axis (vertical, horizontal, minor)
max_area: the maxi... | This function splits a geojson polygon feature into smaller polygons until all are below a specified maximum area, using a defined axis (minor, vertical, horizontal). It returns a geojson FeatureCollection of split polygons or exports them to a file. The process includes printing split details if enabled, using the fea... | def polygon_splitting_wrapper(feature, axis='minor', max_area=2.8, export_path=False, prints=False):
"""
Take in a geojson feature and split it up into polygons until all are smaller than a max area
Args:
feature: the geojson feature that we want to split up
axis: the axis ... |
def get_callsites_for_function(self, func):
location = get_location(func)
references = list(ReferenceUtils.getReferenceAddresses(location, self._monitor))
incoming_calls = []
for call_address in references:
self._monitor.checkCanceled()
callerFunction = self.fm.ge... | The code renames functions based on parameter values passed to a target function. It analyzes calling functions' P-code to identify parameters, extracts copied values, and uses them to determine new names. If a filter is provided, it selects the best name; otherwise, it uses a default method. Functions with ambiguous p... | def rename_functions_by_function_call(self, func, param_index, function_name_filter=None):
incoming_calls = self.get_callsites_for_function(func)
additional_analysis_needed_funcs = set()
incoming_functions = set([i.function for i in incoming_calls])
for calling_func_node in incoming_func... |
def get_data_accesses_from_function(self, func):
pcode_ops = self.get_pcode_for_function(func)
stackspace_id = self.addr_fact.getStackSpace().spaceID
varnodes = set(sum([[op.getOutput()] + list(op.getInputs()) for op in pcode_ops], []))
# filter out the majority of nodes that are known t... | This code renames a function by analyzing strings accessed within it. It retrieves data addresses from the function, extracts non-empty strings from those addresses, selects the best name from these strings, and assigns it to the function with user-defined source type. | def rename_function_from_accessed_strings_guess(self, func):
valid_data_addresses = self.get_data_accesses_from_function(func)
maybe_strings = [self.read_string_at(i) for i in valid_data_addresses]
maybe_strings = [i for i in maybe_strings if i != '']
chosen_function_name = self.choose_b... |
def get_callsites_for_function( func):
location = get_location(func)
references = list(ReferenceUtils.getReferenceAddresses(location, _monitor))
incoming_calls = []
for call_address in references:
_monitor.checkCanceled()
callerFunction = fm.getFunctionContaining(call_address)
if callerFunction is None:
co... | This code analyzes function calls to rename functions dynamically by examining parameter data flow. It identifies calling functions, traces parameter definitions, extracts potential names from memory addresses, and applies a filter to rename functions starting with "FUN_" to more descriptive names. Functions requiring ... | def rename_functions_by_function_call( func, param_index, function_name_filter=None):
incoming_calls = get_callsites_for_function(func)
additional_analysis_needed_funcs = set()
incoming_functions = set([i.function for i in incoming_calls])
for calling_func_node in incoming_functions:
current_function_name = calli... |
def get_data_accesses_from_function( func):
pcode_ops = get_pcode_for_function(func)
stackspace_id = addr_fact.getStackSpace().spaceID
varnodes = set(sum([[op.getOutput()] + list(op.getInputs()) for op in pcode_ops], []))
# filter out the majority of nodes that are known to be out
varnodes = [i for i in varnodes i... | This function renames a given function by analyzing strings accessed within it. It retrieves data addresses from the function, extracts non-empty strings from those addresses, selects the best string as a candidate name, and assigns it to the function with user-defined source type. | def rename_function_from_accessed_strings_guess( func):
valid_data_addresses = get_data_accesses_from_function(func)
maybe_strings = [read_string_at(i) for i in valid_data_addresses]
maybe_strings = [i for i in maybe_strings if i != '']
chosen_function_name = choose_best_function_name(maybe_strings)
func.setName(c... |
def generate_condensed_query(query, history):
chat_history = ""
for turn in history:
chat_history += f"Human: {turn[0]}\n"
chat_history += f"Assistant: {turn[1]}\n"
condense_question_prompt = create_condense_question_prompt(query, chat_history)
#print("Generate condense query called", c... | The code generates a response to a query by condensing the input message, retrieving and reranking relevant information chunks, creating a QA prompt, and streaming the generated text. It also handles text-to-speech audio streaming. | def generate(
message: str,
history_with_input: list[tuple[str, str]],
system_prompt: str,
max_new_tokens: int,
temperature: float,
top_p: float,
top_k: int,
) -> Iterator[list[tuple[str, str]]]:
if max_new_tokens > MAX_MAX_NEW_TOKENS:
raise ValueError
history = history_with_... |
def handle_dos20bpb(self):
self.OEM_name = self.bs[3:0xB].decode()
self.bytes_per_sector = struct.unpack_from("H", self.bs, 0xB)[0]
self.sectors_per_cluster = struct.unpack_from("B", self.bs, 0xD)[0]
self.reserved_sectors = struct.unpack_from("H", self.bs, 0xE)[0]
self.num_FATs =... | This function identifies and processes a BIOS Parameter Block (BPB) by checking its size. It determines the BPB type (e.g., DOS 2.0, 3.0, etc.), prints the corresponding label, and calls the appropriate handler method. If the size is unrecognized, it defaults to handling a DOS 2.0 BPB and displays the bytes before the ... | def handle_bpb(self):
bpb_size = self.jump_offset - 0xB
if bpb_size == 13:
print("BPB: DOS 2.0 BPB")
self.handle_dos20bpb()
elif bpb_size == 19:
print("BPB: DOS 3.0 BPB")
self.handle_dos30bpb()
elif bpb_size == 21:
print("BPB: D... |
def update_progress(self):
total_number = len(self.df)
n_pos = self.df.index.get_loc(self.current_pos)+1
filled_df = self.df.copy(deep=True)
filled_df.dropna(inplace=True)
filled_df = filled_df[self.target]
if len(filled_df) != 0:
fil... | This code initializes an interactive UI for navigating and editing a DataFrame's rows with missing values in a specified target column. It sets up buttons for moving between rows, clearing data, and displays progress, using IPython widgets arranged in a grid layout for user interaction. | def __init__(self, df, html_col, target, labels):
self.df = df
self.html_col = html_col
self.target = target
self.labels = labels
# go to next unfilled row
self.current_pos = self.df[target].isnull().idxmax()
if self.current_pos is None or self.c... |
def find_block_id(self, node_name, block_info):
if block_info is None:
return None
for block_id, block_data in block_info.items():
if node_name in block_data["nodes"]:
return block_id
# Return None if the node is not found in any block
return None... | This function converts an ONNX graph into a PyTorch module by mapping each ONNX node to equivalent PyTorch operations. It processes inputs, creates placeholders, and iterates through nodes to generate corresponding PyTorch modules or function calls for operations like Conv, Relu, Add, etc. Special handling is applied f... | def gen_pytorch_graph_module(self):
for input in self.graph.inputs:
node = self.pytorch_graph.placeholder(
self._illegal_char_regex.sub("_", input.name)
)
self.env[input.name] = node
for onnx_node in self.graph.nodes:
node_name = onnx_node... |
def _get_view(self, environ: dict):
url = environ['PATH_INFO']
view = self._find_view(url)
return view()
def _get_request(self, environ):
return Request(environ, self.settings)
def apply_to_request(self, request):
for i in self.middleware:
i().to_request(request)
def ... | This code processes a WSGI request by logging environment details, retrieving the view and request objects, applying custom processing to the request, generating a response, modifying the response, and returning the response body as an iterator. The function acts as a WSGI application handler, transforming incoming req... | def __call__(self, environ, start_response):
from pprint import pprint; pprint(environ)
pprint(environ['PATH_INFO'])
view = self._get_view(environ)
request = self._get_request(environ)
self.apply_to_request(request)
response = self._get_response(environ, view, request)
... |
def create_connection(db_file):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect(db_file)
conn.row_factory = dict_factory
return conn
except Error as e:
print(e)
def get_text(c, supernote):
rows = c.execute("SELECT * FROM alignments_text WHERE... | This code processes database entries to compute alignment metrics between rebuttal and review text chunks. It retrieves annotated pairs, calculates Jaccard similarity between chunks, collects human annotation labels (excluding specific annotators), and outputs tuples containing chunk identifiers, similarity scores, agr... | def main():
args = parser.parse_args()
conn = create_connection(args.dbfile)
c = conn.cursor()
pairs = c.execute(("SELECT DISTINCT review_supernote, rebuttal_supernote "
"FROM alignments_annotatedpair;")).fetchall()
matches = []
for pair in pairs:
review_chunks, = get_text(c, pair[... |
def prune_unofficial(parents, comment_map):
children = collections.defaultdict(list)
for child, parent in parents.items():
children[parent].append(child)
official_children = collections.defaultdict(list)
queue = ["None"]
while queue:
curr_id = queue.pop(0)
for child in children[curr_id]:
i... | The code processes a database of structured data, filtering entries marked as 'train'. It constructs maps of structures and comments, prunes unofficial elements, identifies hierarchical node relationships, generates characterized paths for non-parent nodes, and saves these paths as JSON. | def main():
args = parser.parse_args()
conn = ordb.create_connection(args.dbfile)
cur = conn.cursor()
cur.execute("SELECT * FROM structure WHERE split=?", ("train",))
rows = cur.fetchall()
structure_map, comment_map = ordb.crunch_structure_rows(rows)
official_structure_map = {
forum_id:prune... |
def load_characteristic_paths(filename):
with open(filename, 'r') as f:
list_paths = json.loads(f.read())
characteristic_paths = []
for nodes, char in list_paths:
comments = [ordb.Comment(*node) for node in nodes]
characteristic_paths.append(ordb.CharacterizedPath(comments, char))
return character... | The main task of the code is to process text data from a database, identify matching chunks between reviews and rebuttals using exact match checks, and write these matches along with their content to a file for analysis. It filters specific paths, extracts relevant text segments, compares them, and stores results in a ... | def main():
args = parser.parse_args()
characteristic_paths = load_characteristic_paths(args.pathsfile)
conn = ordb.create_connection(args.dbfile)
cur = conn.cursor()
cur.execute("SELECT * FROM text WHERE split=?", ("train",))
rows = cur.fetchall()
text_data = ordb.crunch_text_rows(rows)
with open... |
def _load(self):
"""Reads file and returns a list of scans."""
scan_list = read_twix(self.filename, keep_syncdata_and_acqend=False)
self.scan_list = scan_list
return scan_list
def _read_scan_data(self, scan_list):
"""Reads each scan/measurement and stores in NumPy arrays."""
... | The code's main task is to process scan data by loading, reading, and reformatting it. It starts by loading scan data, reads the scan data into a list, extracts headers and mini headers, reformats the data, and returns the processed result stored in `self.data` for further use. | def run(self):
scan_list = self._load()
image_scans = self._read_scan_data(scan_list)
self._read_header(image_scans)
self._read_minidataheader(image_scans)
self._reformat()
return self.data |
def binarizeImage(image, C, blurSize, dilutionKernel):
image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#adaptiveThreshold doc:
#http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html?highlight=adaptive#cv2.adaptiveThreshold
image = cv2.adaptiveThreshold(image,255,1,1,11,C)
... | The code processes a Sudoku image by binarizing it, detecting the largest contour (Sudoku grid), applying perspective transformation to warp the grid into a square, extracting individual cells, and returning the processed Sudoku grid along with number indices for further analysis or solving. | def return_sudoku(image_name, printing = 0):
sudoku_original = cv2.imread(image_name)
if printing:
pl.figure(1)
pl.imshow(sudoku_original)
pl.axis('off')
#Binarize the image
sudoku_binary = binarizeImage(sudoku_original, C, blurSize, dilutionKernel)
if printing... |
def __fetch_html(search_url: str) -> str:
try:
response = requests.get(search_url)
return response.text
except Exception as e:
LOG.error(f'fetch html error: {e}')
def __parse_articles_urls(topic_html: str) -> List[str]:
urls = []
soup = BeautifulSoup(t... | The code scrapes Medium articles for given topics by fetching search results, extracting article URLs, retrieving article content, and returning a filtered list of non-null articles. | def scrape(self, topics: List[str]) -> List[Article]:
articles = []
for topic in topics:
search_url = "https://medium.com/search?q={}".format(topic)
topic_html = self.__fetch_html(search_url)
if not topic_html:
continue
articles_urls = self... |
def piece_placement_offset(xCells,yCells):
cell_delta=Tuples.sub((xCells,yCells),(3,3))
tl_3x3_delta=Tuples.elementwise_mult(
piece_placement_offset_perblock,
cell_delta)
touchloc_board00=Tuples.add(
piece_placement_touchloc_3x3,
tl_3x3_delta)
return Tuples.sub(
t... | This function moves a game piece from its original location to a new cell position with an offset, validating the piece index, calculating destination coordinates, and performing a swipe animation over 1000 units. | def move_piece(piece_index,piece_bbox,cell_coord):
if not (0<=piece_index<3):
raise ValueError("OOB index "+str(piece_index))
origin=piece_locations[piece_index]
ppo=piece_placement_offset(*piece_bbox)
cloc=cellLocation(*cell_coord)
dest=Tuples.add(cloc,ppo,(0,-20)) #overshoot a little
s... |
def _open(self) -> bool:
"""
Open the window.
"""
response = self._send_command("OPEN")
response = self._split_response(response)
if response[0] == AXARawStatus.OK:
if self._status == AXAStatus.LOCKED:
self._timestamp = time.time()
... | The code updates the window opener's position dynamically based on its movement phase (e.g., unlocking, opening, closing, locking) by calculating progress over time. It transitions between states (OPEN, LOCKED, etc.), adjusts position linearly using time intervals, and handles target position alignment. Error logging a... | def _update(self) -> None:
"""
Calculates the position of the window opener based on the direction the window opener is
moving.
"""
if self._status in [
AXAStatus.LOCKED,
AXAStatus.STOPPED,
AXAStatus.OPEN,
]:
# Nothing to ca... |
def _connect(self) -> bool:
if self.connection and not self.connection.is_open:
logger.info("Connecting to %s", self.connection)
try:
self.connection.open()
self.connection.write(b"\r\n")
self.connection.reset()
except AXAConnec... | The main task of the code is to establish a connection to a window opener device, retrieve its device information and version, determine its operational status (locked or open) via raw status checks, and update internal attributes accordingly. The function returns True on successful connection and status validation, or... | def connect(self) -> bool:
# pylint: disable=too-many-return-statements
"""
Connect to the window opener.
"""
if not self._connect():
return False
if self._is_initialised():
return True
try:
response = self._send_command("DEVI... |
def close(self) -> bool:
"""
Closes the window opener.
"""
self._target_position = 0.0
return self._close()
def open(self) -> bool:
"""
Opens the window opener.
"""
self._target_position = 100.0
return self._open()
def _open(self) -> bool:
... | This method sets the window's target position by initiating opening or closing actions based on the target value. It validates the position range (0.0-100.0), checks current position status, and triggers appropriate movement commands while ensuring no redundant operations when already at the target position. Regular sy... | def set_position(self, target_position: float) -> None:
"""
Initiates the window opener to move to a given position.
sync_status() needs to be called regularly to calculate the current position and stop the
move once the given position is reaced.
"""
assert 0.0 <= target... |
def connect(self) -> bool:
# pylint: disable=too-many-return-statements
"""
Connect to the window opener.
"""
if not self._connect():
return False
if self._is_initialised():
return True
try:
response = self._send_command("DEVI... | The main task of the code is to synchronize the device's actual raw state with the system's presumed internal state. It checks connectivity, retrieves raw status, compares it with the current assumed state, and updates internal variables like `_status`, `_position`, and `_timestamp` to resolve discrepancies. Error hand... | def sync_status(self) -> None:
"""
Synchronises the raw state with the presumed state.
"""
if not self.connect():
# Device is offline
if self.connected:
logger.debug("Device is offline")
else:
logger.debug("Device is sti... |
def read_embeddings(self, project: str):
embedding_path = os.path.join(
self.faiss_index_root_path,
self.kind,
f"faiss_index_{project}_{self.embedding_model}",
)
embedder = OpenAIEmbeddings(api_key=self.api_key, model=self.embedding_model)
faiss_db = ... | The code generates a task description by retrieving similar tasks from a FAISS database using embeddings, constructing a prompt with the task summary and similar tasks, and obtaining an answer via a language model. It returns the generated description, token count, similar tasks, and callback information. | def create_task_description(
self,
project: str,
task_summary: str,
task_desc: str = "",
n_similar_tasks: int = 5,
temperature: float = 0,
):
embedder, faiss_db = self.read_embeddings(project)
if n_similar_tasks > 0:
similar_tasks, n_token... |
def render_project_selection(self) -> str:
st.markdown("### Project")
project = st.selectbox("Select Project", self.projects)
return project
def render_task_summary_form(self, project: str) -> Optional[str]:
task_summary = self.render_task_summary_input()
def _on_create_task_des... | The main task of the code is to manage a multi-stage user interface workflow for collecting project and task information. It handles session state transitions between stages (task summary input and description generation), validates user inputs, and progresses to the next page for task generation once all required data... | def render_page_container(self):
if STAGE_NAME not in st.session_state:
st.session_state[STAGE_NAME] = "task_summary_input"
project = self.render_project_selection()
task_summary = self.render_task_summary_form(project)
task_desription_generated = None
if not task_s... |
def is_applicable(self, agent: 'int', action: 'Action') -> 'bool':
agent_row = self.agent_rows[agent]
agent_col = self.agent_cols[agent]
agent_color = self.agent_colors[agent]
if action.type is ActionType.NoOp:
return True
elif action.type is Act... | The code generates all non-conflicting joint action outcomes for multi-agent systems by iterating through permutations of applicable actions, creating child states via `apply_action`, and returning shuffled results. It first identifies valid actions per agent, then systematically tests every combination, filtering out ... | def get_expanded_states(self) -> '[State, ...]':
num_agents = len(self.agent_rows)
# Determine list of applicable action for each individual agent.
applicable_actions = [[action for action in Action if self.is_applicable(agent, action)] for agent in range(num_agents)]
#... |
def guess_from_nlp(pdf_fp, n_completions):
guess_title_prompt = make_gpt_prompt(pdf_fp, gpt_question="The title is")
title_completion = openai.Completion.create(engine="babbage-instruct-beta",
prompt=guess_title_prompt,
... | The code initializes a population of guesses by combining results from NLP analysis, PDF metadata, and ArXiv filename parsing, then randomly samples a subset of the specified size using a random number generator. | def initialize(self):
nlp_guess = guess_from_nlp(self.full_text, n_completions=3)
population = [
guess_from_pdf_metadata(self.pdf_fp),
guess_arxiv_from_filename(self.filename),
]
population += nlp_guess
population = self.rng.choice(population, self.popul... |
def search_online_databases(citation):
if len(citation.title) == 0:
return [NO_CITATION_INFO]
query_string = f"{citation.title}"
query_string = query_string[:MAX_QUERY_SIZE]
arxiv_citation = search_arxiv(query_string)
ss_citation = search_semantic_scholar(query_string)
return np.array(... | The function calculates the cost of a citation by comparing it to results from online searches. It filters valid citations, computes distances for fields like title, authors, venue, and year, and sums these to determine a cost. If no valid results are found, it returns a high default cost. The minimum cost across all v... | def online_search_cost(citation):
# one way to see if a citation is good is to use it to search a database.
# If you don't get a result, that's a bad sign and deserves high cost. If you do, then the distance
# of that result to the citation used for querying can be used as cost
all_online_citations = se... |
def search_online_databases(citation):
if len(citation.title) == 0:
return [NO_CITATION_INFO]
query_string = f"{citation.title}"
query_string = query_string[:MAX_QUERY_SIZE]
arxiv_citation = search_arxiv(query_string)
ss_citation = search_semantic_scholar(query_string)
return np.array(... | The code mutates a citation by standardizing its venue and authors with 50% probability, then performs crossover with a randomly selected valid citation from online search results. If no valid citations are found, it returns the original citation. | def mutate(self, citation: Citation):
# To mutate, we simply perform crossover with search results
online_citations = search_online_databases(citation)
valid_online_citations = list(filter(lambda c: c != NO_CITATION_INFO, online_citations))
if len(valid_online_citations) == 0:
... |
def goBeginning(self): #naviages to the head (which points to the first real node)
(self.setCurr(self.getHead()))
def isEmpty(self):
if self.getHead() == None:
return True
return False
def isEnd(self): #checks if the node is that last node in the list
return(self.getCurr() ==... | The main task of the code is to count and return the number of items in a linked list. It starts at the beginning, iterates through each node using `goNext()`, increments a counter for each node, and adds one final count for the last node before returning the total. | def getSize(self): #returns how many items are in the linked list
h = self.goBeginning()
count = 0
if self.isEmpty():
return count
else:
while not self.isEnd():
count+=1
self.goNext()
count += 1
return count |
def getPos(self): #finds what the position is of cur
#returns the current position as a number
if self.isEmpty():
return -1
elif self.getHead() == self.getCurr():
return 0
temp = self.getHead()
pos = 0
while temp != self.getCurr():
pos ... | The main task of the code is to navigate to the previous node in a linked list by decrementing the current position, but only if the current node is not at the beginning and the list is not empty. It updates the position to the destination if valid. | def goPrev(self): #navigates to the previous node in the linked list
x = self.getPos()
dest = x-1
if not self.isBeginning() and not self.isEmpty():
self.setPos(dest) |
def isEmpty(self):
if self.getHead() == None:
return True
return False
def setHead(self, here):
self._head.link = here
def setTail(self, here):
self._tail.link = here
def setCurr(self, here):
self._curr.link = here
def isBeginning(self): #checks if a node is the first... | The method `insertBefore` inserts a new node `n` before the current node in a linked list. It handles three cases: if the list is empty, it sets `n` as the head, tail, and current node. If the current node is at the beginning, it updates the head and links `n` to the current node. Otherwise, it moves to the previous no... | def insertBefore(self, n): #add a node before curr
if self.isEmpty():
self.setHead(n)
self.setTail(n)
self.setCurr(n)
#print("1")
elif self.isBeginning():
self.setHead(n)
n.link = self.getCurr()
self.setCurr(n)
... |
def isBeginning(self): #checks if a node is the first node in the linked list
if self.getHead():
return(self.getHead() == self.getCurr())
def setHead(self, here):
self._head.link = here
def getCurr(self):
return self._curr.link
def isEnd(self): #checks if the node is that last node i... | The code removes the current node from a linked list by adjusting pointers. If the node is the head, it updates the head to the next node. If it's the tail, it updates the tail and nullifies the last node's link. For middle nodes, it bypasses the current node by linking the previous node to the next node. | def remove(self): #kill
#removes the node at curr
if self.isBeginning():
self.setHead(self.getCurr().link)
elif self.isEnd():
self.goPrev()
self.setTail(self._curr)
self.getCurr().link = None
elif not self.isEmpty():
self.goPrev... |
def _get_dataframe(self):
return parse_audioset.parse_csv(self.csv_loc, self.ont_loc,
csv_head=self.csv_head,
label_ix_start=self.label_ix_start,
label_ix_end=self.label_ix_end,
... | This code initializes a dataset object by configuring parameters from a dictionary, handling different data modes (CSV or files), setting audio/spectrogram parameters, estimating file sizes, and preparing the dataset for training. It processes metadata, loads CSV data, configures spectrogram settings, calculates averag... | def __init__(self, params_dict):
print("Creating Dataset object...")
self.params = params_dict
self.dataset_loc = self.params['data']['dataset_dir']
self.dataset_name = self.params['data']['dataset_name']
self.dataset_dir = os.path.join(self.dataset_loc, self.dataset_name)
... |
def goal_test2(s):
global GOAL2
return s==GOAL2
def R(s, a, sp):
'''Rules: Exiting from the correct goal state yields a
reward of +100. Exiting from an alternative goal state
yields a reward of +10.
The cost of living reward is -0.1.
'''
# Handle goal state transitions first...
if goal_test(s):
if ... | The function `simulate(s, a)` computes a new state `sp` and reward `r` based on the current state `s` and action `a`, using transition probabilities `T` and reward function `R`. It checks if `s` is a goal state, returning a terminal state with an "Exit" reward if so. It then generates a random number to probabilistical... | def simulate(s, a):
'''Take a state s and action a, and figure out a new state sp and
reward r, according to T and R.'''
global NGOALS, Terminal_state
# See if this is a goal state. If so, force the Exit action.
#if goal_test2(s):
# print("Got to a secondary goal. NGOALS is "+str(NGOALS))
if goal_test(... |
def generate_all_states():
'''Basically create an explicit representation of the state-space
graph by creating a hash that maps states to their adjacency lists,
where each item on the adjacency list is an item of the form
[operator_number, new_state]
'''
global STATES_AND_EDGES, CLOSED
# do special breadth-... | The function `set_up_state_space()` initializes the state space for a problem (likely Tower of Hanoi), defining all states, terminal states, and agent positions. It generates goal paths, sets up visualization parameters, disables certain UI features, and prepares Q-learning components by initializing value functions an... | def set_up_state_space():
global ALL_STATES, CLOSED, Terminal_state, Agent_state, N_disks, STATES_AND_EDGES
global NEED_Q_LEARN_SETUP, Q_from_VI, Q_from_QL
global GOLDEN_PATH, SILVER_PATH, NGOALS
make_goal_state()
generate_all_states()
ALL_STATES = CLOSED + [Terminal_state]
#Agent_state = CLOSED[0] # Set ... |
def Agent_turn(a, reset=False):
global Agent_state, Terminal_state, LAST_REWARD, TERMINATED
#print("Entering Agent_turn")
if reset:
if not QUIET_MODE:
print("Putting the Agent back at the initial state.")
New_Agent_state = CLOSED[0]
# Set the old one to something bogus, so comparis... | This function trains a Q-learning agent for a specified number of transitions, optionally checking for convergence. It suppresses output (quiet mode), updates the agent's state, handles episode termination, and resets for new episodes. It tracks transitions, episodes, and updates Q-values/policies, finally displaying s... | def train_quietly(n_transitions, check_for_convergence=False):
global QUIET_MODE, POLICY_from_VI, POLICY_from_QL, CLOSED, ACTIONS
#if check_for_convergence!=False : POLICY_from_VI = VI.extract_policy(CLOSED, ACTIONS)
Vis.unhighlight(Agent_state)
QUIET_MODE = True
for i in range(n_transitio... |
def load_state_dict(self, checkpoint, strict=True):
"""Resume cells of trainer from checkpoint. """
self._load_state(self.__dict__, checkpoint, strict)
def transfer(self, weights):
"""Return (dict of) weights transferring to aim model(s). """
raise NotImplementedError
def train(self):
... | This code defines the main training and validation loop. It loads pre-trained weights (either via resume or transfer learning), then iterates through epochs, training the model and validating periodically. Validation results determine checkpoint saving, tracking the best performance. | def __call__(self):
"""Main cycle of training and validation. """
if self.args.resume:
if os.path.isfile(self.args.resume):
print("loading checkpoint '{}' ...".format(self.args.resume))
checkpoint = torch.load(self.args.resume)
self.load_state_... |
def create_energy_grid(n: int):
"""
method to create an energy grid for the n*n grid
:param n: amount of rows, cols
"""
grid = np.zeros((n, n), dtype=float)
for i in range(n):
for j in range(n):
grid[i, j] = E((i, j))
return grid
def randomize_start(visitor_grid, n: int):... | The code performs a Metropolis-Hastings MCMC simulation on an n×n grid, sampling positions over m iterations. It initializes a visitor grid, calculates energy changes, and uses the Boltzmann factor kT to determine move acceptance probabilities. The algorithm updates the visitor count at each accepted move, returning th... | def run_MCMC(n: int, m: int, kT: float):
"""
running MCMC according to given values
:param n: number of rows/cols
:param m: number of rotations
:param kT: given boltzman value
:return: vistior grid
"""
visitor_grid = np.zeros(shape=(n, n), dtype=int)
energy_grid = create_energy_grid(... |
def get_cmdline_parser():
"""
method to help parse info from cmd line
:return: the parser itself
"""
parser = argparse.ArgumentParser(
description='Run MCMC on a discrete n*n configuration space.')
parser.add_argument('n', type=int, default=5, nargs='?',
help='num... | The code runs a Metropolis-Monte Carlo (MCMC) simulation for varying parameters (m and kT) to explore configuration spaces. It generates heatmaps to visualize results: first testing m values (10, 100, 500k), then analyzing kT effects (0.1–50.0) at m=500k. Outputs include heatmaps and logs to study system behavior under... | def part_1_algorithm():
"""
part 1 algorithm of ex3
:return:none
"""
parser = get_cmdline_parser()
args = parser.parse_known_args()[0]
n, m, kT = args.n, args.m, args.kT
configurations = generate_random_configuration_space(n)
# q2-5
for m in [10, 100, 500000]:
visitor_gri... |
def decide(self, board):
if not self.is_alive:
return
weights = [self.chance_to_move,
self.chance_to_turn, self.chance_to_wait]
if self.use_brain:
weights = self.brain.forward_propagate(inputs=self.get_brain_inputs(
board))
self.... | The code updates an entity's state by recording its current position, direction, and alive status in memory. It then decides an action (turn, move, wait) based on the board, executes the chosen action, and increments the entity's age. If not alive, the method exits early. | def update(self, board):
if not self.is_alive:
return
self.last_position.x = self.position.x
self.last_position.y = self.position.y
self.last_direction.x = self.direction.x
self.last_direction.y = self.direction.y
self.memory.append({'pos': self.position, 'di... |
def config_parser():
import configargparse
parser = configargparse.ArgumentParser()
parser.add_argument('--config', is_config_file=True, help='config file path')
parser.add_argument("--expname", type=str, help='experiment name')
parser.add_argument("--basedir", type=str, default='./logs/', help='whe... | The code trains a neural network (NERF) using distributed data parallel (DDP) by parsing configurations, setting up logging, detecting available GPUs, and initiating training on a single GPU (or preparing for multi-GPU via commented-out code). It configures the training environment, handles GPU allocation, and executes... | def train():
parser = config_parser()
args = parser.parse_args()
logger.info(parser.format_values())
setup_logger(args, "train")
if args.world_size == -1:
args.world_size = torch.cuda.device_count()
logger.info('Using # gpus: {}'.format(args.world_size))
ddp_train_nerf(... |
def recenter_poses(poses):
poses_ = poses + 0
bottom = np.reshape([0, 0, 0, 1.0], [1, 4])
c2w = poses_avg(poses)
c2w = np.concatenate([c2w[:3, :4], bottom], -2)
bottom = np.tile(np.reshape(bottom, [1, 1, 4]), [poses.shape[0], 1, 1])
poses = np.concatenate([poses[:, :3, :4], bottom], -2)
pos... | The main task of the code is to load and process camera poses and intrinsic parameters from a dataset. It reshapes, scales, and re-centers the poses, computes camera-to-world matrices, and returns intrinsics and transformed pose matrices for 3D scene reconstruction or rendering. | def load_poses(scene):
a = np.load(f'/home/meric/GNT_Style/data/nerf_llff_data/{scene}/poses_bounds.npy')
poses_arr = a
poses = poses_arr[:, :-2].reshape([-1, 3, 5]).transpose([1, 2, 0])
bds = poses_arr[:, -2:].transpose([1, 0])
sfx = ""
factor = 8
img0 = [
os.path.join(f'/... |
def header(self):
if self._header:
return self._header
else:
header_bytes = self.get_bytes(0, 512000)
assert int.from_bytes(header_bytes[0:2], byteorder="little") == 0x4D50
version = int.from_bytes(header_bytes[2:4], byteorder="little")
metadat... | This code retrieves data bytes for a given (z, x, y) coordinate by first checking the root directory, then falling back to leaf directories if needed. It calculates hierarchical levels, navigates through directory structures, and returns the corresponding byte data if found, otherwise returns None. | def get(self, z, x, y):
h = self.header()
val = h.root_dir.get((z, x, y))
if val:
return self.get_bytes(val[0], val[1])
else:
if len(self.header().leaves) > 0:
level_diff = z - self._leaf_level()
if level_diff < 0:
... |
def getTotalNumberOfGames(self,sport):
if (sport == "NFL"):
return 16
elif (sport == "MLB"):
return 162
elif (sport == "NBA" or sport == "NHL"):
return 82
else:
raise Exception("Not a valid sport.")
def getRealDataForSeasonAndPlayer(self,se... | The code initializes a player's data structure with IPO price, shares, and season statistics. It retrieves real and projected performance data for a sports season, then iterates through weeks to calculate performance changes using the `performanceChange` method, updating the player's value over time. | def __init__(self,ipo,playerName,sport,playerid):
self.currentPrice = round(ipo,2)
self.ipo = round(ipo,2)
self.name = playerName
self.totalShares = 1000
self.totalPriceData = {}
self.totalNumberOfGames = self.getTotalNumberOfGames(sport)
self.totalPriceData[0] = ... |
def _pre_cleanup(self):
pass
def _cleanup(self, driver, test_name, current_path):
self._save_screenshot(driver, test_name, current_path)
driver.quit()
def _post_cleanup(self):
pass | The code defines a method `t_cleanup` that performs test-specific cleanup operations. It first calls `_pre_cleanup` for initial setup, then invokes `_cleanup` with the driver and test name to release resources, and finally executes `_post_cleanup` to finalize the process. The method ensures proper resource management a... | def t_cleanup(self, test_name):
self._pre_cleanup()
self._cleanup(self._driver, test_name)
self._post_cleanup() |
def _pre_initizalize(self):
pass
def _initialize_page(self):
pass
def _post_initialize(self):
pass
def t_cleanup(self, test_name):
self._pre_cleanup()
self._cleanup(self._driver, test_name)
self._post_cleanup() | The main task of the code is to initialize a test environment by performing pre-initialization steps, acquiring a driver from a pool, initializing a page, and post-initialization. It ensures cleanup of resources (via `t_cleanup`) in both successful and exceptional cases, printing errors and raising a `RuntimeError` if ... | def test_initialize(self):
try:
self._pre_initizalize()
self._driver = self._driver_pool.get_driver()
self._initialize_page()
self._post_initialize()
self.t_cleanup('test_init')
except Exception as ex:
self.t_cleanup('test_init')
... |
def get_chatroom_by_token(self, token):
match = [chat for chat in self.chatrooms if chat.token == token]
print('CHAT BY TOKEN ', token, match)
return match[0] if match else None
def broadcast(self, msg, name='', chatroom=''):
clients = self.get_client_sock_from_chat(chatroom)
pri... | This function handles client connections in a chat application by authenticating users, managing chatrooms, broadcasting messages, and maintaining connection state. It receives user names and chatroom tokens, creates chatrooms if needed, tracks members, and sends updates. Messages are broadcast to the chatroom, with sp... | def handle_client(self, conn, addr, q):
print(f'[NEW CONNECTION] {addr} connected.')
send_protocol('Welcome to our friendly chat!', conn)
connected = True
name = receive_protocol(conn)
self.clients[addr] = name
send_protocol(f'Hi {name}!', conn)
chatroom = rece... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.