dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def initialize_NN(layers,VarScope):
weights = []
biases = []
num_layers = len(layers)
with tf.variable_scope(VarScope):
for l in range(0, num_layers - 1):
W = xavier_init(size=[layers[l], layers[l + 1]])
b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtyp... | The code initializes neural networks for identification tasks, setting up layers, placeholders, and loss functions for supervised learning (u_loss) and PDE constraints (f_loss). It configures optimizers (L-BFGS-B and Adam) to train separate networks for solution variables and PDE parameters, combining losses for joint ... | def idn_init(self, u_layers, pde_layers):
# Layers for Identification
self.u_layers = u_layers
self.pde_layers = pde_layers
# Initialize NNs for Identification
self.u_weights, self.u_biases = initialize_NN(u_layers, "Solution")
self.pde_weights, self.pde_biases = initia... |
def initialize_NN(layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0, num_layers - 1):
W = xavier_init(size=[layers[l], layers[l + 1]])
b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtype=tf.float32)
weights.append(W)
biases.appe... | The code initializes neural networks for PDE identification, setting up layers, placeholders for input data, and defining prediction networks. It computes losses for solution (u) and PDE residuals (f), employing L-BFGS-B and Adam optimizers to minimize these losses. The function prepares the model for training by confi... | def idn_init(self, u_layers, pde_layers):
# Layers for Identification
self.u_layers = u_layers
self.pde_layers = pde_layers
# Initialize NNs for Identification
self.u_weights, self.u_biases = initialize_NN(u_layers)
self.pde_weights, self.pde_biases = initialize_NN(pde_... |
def stylesheet_as_st_markdown():
with open('streamlit_customizations.css') as style_sheet:
style_sheet_text = style_sheet.read()
#return st.write(f'Style sheet:{style_sheet}')
return st.markdown(f'<style>{style_sheet_text}<style>', unsafe_allow_html=True)
def create_parameters_form():
parameters_secti... | The code defines a function `create_page()` that initializes a Streamlit web application for a "Jobs Wizard" tool. It sets up page configuration, applies styling, displays a header, and integrates forms for parameters, filters, and state text generation. The main task is to configure and structure the UI/UX of a job-re... | def create_page():
st.session_state.should_contain = []
st.set_page_config(page_title='Jobs Wizard', page_icon=":male_mage:")
stylesheet_as_st_markdown()
st.header('Jobs Wizard 🧙')
create_parameters_form()
create_filters()
generate_state_text() |
def encrypt(msg, key=key):
return pow(str_to_int(msg), key.e, key.n)
def decrypt(cipher, key=key):
return int_to_str(pow(cipher, key.d, key.n))
def decrypt_fast(cipher, key=key):
d_p = key.d % (key.p - 1)
d_q = key.d % (key.q - 1)
m_p = pow(cipher % key.p, d_p, key.p)
m_q = pow(cipher % key.q, d... | The code's main task is to compare the performance of two decryption methods by timing their execution. It encrypts a flag, displays its hex representation, and prompts users to input hex ciphers. For each input, it measures and prints the time taken by both a standard and a "fast" decryption function, highlighting eff... | def loop():
enc_flag = encrypt(f)
print('Ain\'t nobody got time for slow algos ...\nWanna see how much difference a clever decryption makes, e.g. for this encrypted flag:\n%s\nBut you can also enter some other cipher in hex: ' %
hex(enc_flag)[2:])
while True:
sys.stdout.flush()
cip... |
def __server(self, alias):
return self.__servers()[alias] if alias in self.__servers() else None
def __servers(self):
return self.config['servers'] if self.config and 'servers' in self.config else {}
def list_servers(self):
if not self.__serves_any():
return
max_len_alias = ... | This code switches the active server to the specified alias by updating server configurations, marking a change, and listing servers. It checks if the alias exists, deactivates all servers, activates the specified one, and notifies the user of the switch. | def switch_server(self, alias: str):
if not self.__server(alias):
print(f"Server '{alias}' is unknown.")
return
for server in self.__servers():
server_config = self.__servers()[server]
server_config['active'] = server == alias
print(f"Switched to s... |
def __server(self, alias):
return self.__servers()[alias] if alias in self.__servers() else None
def __servers(self):
return self.config['servers'] if self.config and 'servers' in self.config else {}
def list_servers(self):
if not self.__serves_any():
return
max_len_alias = ... | The code removes a server identified by an alias from the system. If the server exists, it deletes it and marks the configuration as changed. If no active servers remain after removal, it activates the first remaining server and lists all servers. If no servers are left, it notifies the user. | def remove_server(self, alias):
if not self.__server(alias):
print(f"Server '{alias}' is unknown.")
return
del self.__servers()[alias]
self.is_changed = True
any_active = any(server['active'] for (server_alias, server) in self.__servers().items() if 'active' in ... |
def addrec():
name = input("\nEnter student's full name ")
sub = int(input("\nEnter number of subjects taken "))
subjects={}
for i in range(sub):
s=input("\nEnter subject ")
m=input("\nEnter percentage in {0} ".format(s))
subjects[s]=m
student_records[name]=(subjects)
printmenu()
def viewrec():
k=list(stu... | The code defines a menu function that repeatedly prompts the user for a numeric choice (1-4). It executes corresponding actions: adding, viewing, or deleting records (via addrec(), viewrec(), delrec()) based on the input, or exiting if '4' is chosen. It validates input to ensure numeric values and provides error messag... | def menu():
while True:
choice = input("Enter your choice : ")
if choice.isnumeric():
if int(choice)==1:
addrec()
elif int(choice)==2:
viewrec()
elif int(choice)==3:
delrec()
elif int(choice)==4:
break
else:
print("Enter 1, 2,3 or 4... How hard can that be...")
else:
print("... |
def draw_lines(self):
for i in range(ROWS+1):
pygame.draw.line(self.screen, BLACK, (0, i * SQUARE_SIZE),
(WIDTH, i * SQUARE_SIZE ), width=LINE_WIDTH)
for i in range(COLS+1):
pygame.draw.line(self.screen, BLACK, (i * SQUARE_SIZE, 0),
... | The main task of the code is to render a game state on the screen by clearing the display with LIGHTGRAY, drawing grid lines, end squares, and the robot's image based on the provided state, then updating the display for visualization. | def draw (self, state):
self.screen.fill(LIGHTGRAY)
self.draw_lines()
self.draw_end_squares()
self.draw_img(state,self.robot)
pygame.display.update() |
def get_purchase_order_items(purchase_order_id):
url = cw_manage_url + f"/procurement/purchaseorders/{purchase_order_id}/lineitems"
params = {
"pageSize": "1000",
}
items = requests.get(headers=headers_cw, url=url, params=params).json()
logging.debug(f"Gathering Items for PurchaseOrder: {pu... | The main task of the code is to process a webhook event by identifying the closest purchase order item to the webhook's timestamp that is marked as "FullyReceived," ensuring the time difference is within ±10 seconds, and then generating a label for it if conditions are met. | def proccess_request(webhook_json_data):
webhook_entity_json_data = json.loads(webhook_json_data["Entity"])
logging.debug(f"Entity json data from CW CallBack:\n{webhook_entity_json_data}")
purchase_order_items = get_purchase_order_items(webhook_entity_json_data["id"])
# get the item from the purchase o... |
def _selectByIndecies(self, indicies):
return self._X[np.sort(indicies.astype(int))]
def _getMatricies(self, nid, side, order, feature):
value = self.tree.get_value(nid)
grad, hess = self._computeGradients(nid)
X = self._selectByIndecies(value["indicies"])
g, h, X = grad[order], ... | This function updates a tree node by selecting the optimal feature and threshold to split data, adjusting parameters using linear algebra, and splitting the node into left and right children if necessary. It iterates through features, evaluates splits, and applies corrections to node parameters before updating the tree... | def _updateTree(self, nid):
value = self.tree.get_value(nid)
X = self._selectByIndecies(value["indicies"])
best_loss = -np.inf
best_feature = None
best_threshold = None
best_matricies = None
best_order = None
for feature in np.arange(self._feature_numbe... |
def perform_movement(animal_to_move):
move_dir = random.randint(1, 4)
move_vel = random.uniform(0.01, 0.7)
if move_dir == 1:
animal_to_move.entity.x += move_vel
elif move_dir == 2:
animal_to_move.entity.x -= move_vel
elif move_dir == 3:
animal_to_move.entity.y += move_vel
... | The code updates a simulation by iterating through each animal, moving it, and checking for collisions with other animals, water, and food to manage interactions and environmental responses. | def update():
for i in range(len(animals)):
perform_movement(animals[i])
handle_animal_collisions(animals[i], animals)
handle_water_collisions(animals[i], water)
handle_food_collisions(animals[i], food) |
def _check_keydown_events(self, event):
if event.key == pygame.K_LEFT:
self.hero.moving_up = True
self.hero.moving_down = False
elif event.key == pygame.K_RIGHT:
self.hero.moving_down = True
self.hero.moving_up = False
elif event.key == pygame.K_SP... | This method handles Pygame events by checking for quit requests, key presses, key releases, and mouse clicks. It triggers appropriate responses by calling private methods for keydown, keyup, and play button interactions, using event data to determine actions like exiting the game or initiating gameplay. | def checkevnts(self):
"""Respond to key presses"""
# watch for keyboard events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
# self._check_keydown_events(self, event) --> wrong... |
def _change_fleet_edges(self):
"""Respond appropriately if any aliens have reached an edge"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _hero_hit(self):
"""Respond to the hero being hit by an a... | This method updates alien positions, checks for edge collisions to reverse direction, detects hero-alien collisions to trigger hit responses, and verifies if aliens have reached the screen bottom to handle game-over logic. | def _update_aliens(self):
"""Check if at edge and update position of all aliens"""
self._change_fleet_edges()
self.aliens.update()
# look for alien hero collisions
if pygame.sprite.spritecollideany(self.hero, self.aliens):
self._hero_hit()
# look for aliens ... |
def checkevnts(self):
"""Respond to key presses"""
# watch for keyboard events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
# self._check_keydown_events(self, event) --> wrong... | The code runs the main game loop by continuously checking events, updating game elements (hero, lasers, aliens) if the game is active, rendering the latest frame, and maintaining a 30 FPS frame rate to ensure smooth gameplay. | def run_game(self):
"""Start main game loop"""
while True:
self.checkevnts()
if self.game_active:
self.hero.update()
self._update_lasers()
self._update_aliens()
# draw most recent frame
self._update_scre... |
def isUserQuarantined(self, user):
quarantined_users = self.getQuarantinedUsers()
usernames = [record.split(",")[0] for record in quarantined_users]
return user.name in usernames
def isSafeText(self, item):
user_text = self.PRAW_utils.extractText(item).lower()
user_text = "".join... | This function analyzes a Reddit item (comment or submission) by checking various conditions such as visit status, author identity, bot interaction history, user quarantine status, text safety, bot invocation, character mentions, comment nesting, and top comment limits. It returns a dictionary of boolean flags indicatin... | def analyseItem(self, item):
results = dict()
results["IsVisited"] = item.id in self.visited
results["IsAuthorMe"] = hasattr(item.author, "name") and item.author.name == reddit.user.me().name
results["HasBotCommentedOnComment"] = isinstance(item, praw.models.Comment) and self.PRAW_utils.... |
def analyseItem(self, item):
results = dict()
results["IsVisited"] = item.id in self.visited
results["IsAuthorMe"] = hasattr(item.author, "name") and item.author.name == reddit.user.me().name
results["HasBotCommentedOnComment"] = isinstance(item, praw.models.Comment) and self.PRAW_utils.... | The function determines if a bot should comment on a given Reddit post or comment by evaluating multiple conditions. It checks if the item is already visited, authored by the bot, has existing bot comments, involves quarantined users, or exceeds reply limits. If unsafe text is detected, it logs and quarantines the user... | def getBotComment(self, item, chat_history = None):
results = self.analyseItem(item)
if results["IsVisited"]:
return None
if not self.debug_settings.debug and results["IsAuthorMe"]:
return None
if results["HasBotCommentedOnComment"]:
... |
def constructChatHistory(self, comments):
constructed_history = []
for comment in comments:
comment_dict = {"role": None, "content": None}
comment_dict["role"] = "assistant" if self.PRAW_utils.isBotComment(comment, self.debug_settings.debug) else "user"
comment_conten... | The code processes replies to a root comment by generating and posting bot responses. It retrieves all replies, constructs chat history from comment chains, generates bot comments using the history, and posts them. The main task is automating reply generation and posting for each comment in a discussion thread. | def checkCommentReplies(self, root_comment):
all_replies = root_comment.replies.list()
for comment in all_replies:
comment_chain = self.PRAW_utils.getCommentChain(comment)
chat_history = self.constructChatHistory(comment_chain)
bot_comment ... |
def printInfo(self, messages_arr):
dividor = "-" * 50
for message in messages_arr:
print(message)
sys.stdout.flush()
print(dividor)
sys.stdout.flush()
def updateQuarantinedUsers(self, user = None):
if user and self.isUserQuarantined(user):
retu... | The main task of the code is to monitor Reddit subreddits, generate and post bot comments on new submissions/comments, track comment activity, manage image posting frequency, update quarantined users, and log progress. It runs in a loop, checking for new content, avoiding duplicate comments, and ensuring operations occ... | def startBot(self):
self.printInfo(["Bot monitoring..."])
if self.debug_settings.debug:
self.printInfo(["DEBUG Mode Started..."])
self.subreddits = self.PRAW_utils.subreddits = [self.debug_settings.debug_subreddit_settings]
visited = dict()
self.updateQuarantine... |
def get_master(cluster_name, region=default_region):
masters = get_masters(cluster_name, region=region)
if not masters:
raise CommandError("No master on {}".format(cluster_name))
return masters[0].public_dns_name
def get_job_with_tag(job_name, job_tag):
return '{job_name}.{job_tag}'.format(job_n... | This function terminates a job on a specified cluster by killing its processes via SSH. It retrieves the job's master node, identifies the job's control directory, and executes a shell command to read the process ID (PID) from a file, then kills the PID and its child processes using `sudo kill`. The task involves stopp... | def kill_job(cluster_name, job_name, job_tag, key_file=default_key_file,
master=None, remote_user=default_remote_user,
region=default_region,
remote_control_dir=default_remote_control_dir):
master = master or get_master(cluster_name, region=region)
job_with_tag = get_job... |
def get_master(cluster_name, region=default_region):
masters = get_masters(cluster_name, region=region)
if not masters:
raise CommandError("No master on {}".format(cluster_name))
return masters[0].public_dns_name
def get_job_with_tag(job_name, job_tag):
return '{job_name}.{job_tag}'.format(job_n... | This function transfers job results from a cluster's master node to a local directory by syncing files via rsync, excluding the 'RUNNING' file, and returns the local path to the collected results. It determines the master node, locates the job's control directory, executes the transfer, and constructs the final local f... | def collect_job_results(cluster_name, job_name, job_tag,
key_file=default_key_file,
region=default_region,
master=None, remote_user=default_remote_user,
remote_control_dir=default_remote_control_dir,
... |
def cluster_job_run(*args, **kwargs):
send_heartbeat()
cluster.job_run(*args, **kwargs)
def notify(message, severity="CRITICAL", entity_id=runner_eid):
try:
return victorops_alert(entity_id, severity, message)
except Exception as e:
log.exception('This is bad, notification failed. Someon... | The function `run_job` repeatedly executes a specified job on a cluster with retry logic, handling failures by incrementing a consecutive failure counter. If failures exceed a threshold, it destroys the cluster and notifies stakeholders. It performs sanity checks post-failure and returns success/failure status along wi... | def run_job(cluster_name, job_name, full_conf, collect_results_dir, consecutive_failures=0, entity_id=runner_eid):
while True:
try:
log.info('Running {}'.format(job_name))
cluster_job_run(cluster_name=cluster_name, job_name=job_name, job_mem=full_conf.cluster_conf.job_mem,
... |
def cluster_exists(cluster_name, region):
try:
get_master(cluster_name, region=region)
return True
except Exception as e:
return False
def call_ec2_script(args, timeout_total_minutes, timeout_inactivity_minutes):
ec2_script_path = chdir_to_ec2_script_and_get_path()
return check_c... | (The code launches and configures an EC2 cluster for distributed computing, handling parameters like instance types, spot pricing, VPC settings, and Spark/Hadoop versions. It checks for existing clusters, retries on failure, applies tags, and ensures cluster health before returning the master node's IP. The function ma... | def launch(cluster_name, slaves,
key_file=default_key_file,
env=default_env,
tag=[],
key_id=default_key_id, region=default_region,
zone=default_zone, instance_type=default_instance_type,
ondemand=False, spot_price=default_spot_price, master_spot=False,
... |
def fetch(url, path):
run(["curl", "-L", "-o", path, url])
def _environment(self, *, for_builder: bool) -> Dict[str, str]:
env = os.environ.copy()
prefix = self._prefix(for_builder=for_builder)
prepend_env(
env, "CPPFLAGS", "-I" + self._mangle_path(os.path.join(prefix, "include"... | This function builds a package using the Autoconf build system. It updates essential configuration scripts (config.guess/config.sub), determines platform-specific configure arguments, handles cross-compilation settings for macOS arm64, and executes the build process with make and installation. The core task is to autom... | def _build_with_autoconf(self, package: Package, for_builder: bool) -> None:
assert package.build_system == "autoconf"
package_path = os.path.join(self.build_dir, package.name)
package_source_path = os.path.join(package_path, package.source_dir)
package_build_path = os.path.join(package_... |
def get_platform():
"""
Get the current platform tag.
"""
system = platform.system()
machine = platform.machine()
if system == "Linux":
return f"manylinux_{machine}"
elif system == "Darwin":
# cibuildwheel sets ARCHFLAGS:
# https://github.com/pypa/cibuildwheel/blob/52... | The code builds the x265 library three times: 12-bit and 10-bit static libraries, then an 8-bit shared library linked to the others. It configures platform-specific flags, renames generated libraries, and sets build arguments to enable multi-bit support (8, 10, 12) in the final shared library. | def _build_x265(self, package: Package, for_builder: bool) -> None:
assert package.name == "x265"
assert len(package.build_arguments) == 0
# Build x265 three times:
# 1: Build 12 bits static library version
# 2: Build 10 bits static library version
# 3: Build 8 bits s... |
def _prefix(self, *, for_builder: bool) -> str:
if for_builder:
return self._builder_dest_dir
else:
return self._target_dest_dir
def log_group(title):
"""
Starts a log group and ends it at exit.
"""
start_time = time.time()
success = False
log_print(f"::gr... | The code builds a package if it is not already installed, using different build systems (CMake, Meson, Autoconf) or specific methods (e.g., x265) based on the package's configuration. It logs the build process, extracts the package, executes the appropriate build method, and marks the package as installed by creating a... | def build(self, package: Package, *, for_builder: bool = False):
# if the package is already installed, do nothing
installed_dir = os.path.join(
self._prefix(for_builder=for_builder), "var", "lib", "cibuildpkg"
)
installed_file = os.path.join(installed_dir, package.name)
... |
def meetAgent(agentProfile, agentArray,alpha):
# A function that represents the agent being told a hypothesis, and given
# evidence for why it is beleived.
otherAgentID = agentProfile[0]
while otherAgentID == agentProfile[0]:
otherAgentID = random.randint(0,len(agentArray)-1)
otherAgentProfi... | The function determines an agent's action by randomly selecting between three options: chatting with another agent, testing environment knowledge, or thinking independently. It updates the agent's profile with the chosen action ("meet," "test," or "thought") and returns the modified profile. The decision weights are go... | def agentAction(agentProfile, environmentReliability, agentArray, theTruth,alpha, chatChance, testChance, beta=0):
# Function to represent an agent deciding what to do, currently choosing to
# learn from either the environment or another agent, or to think through
# their existing knowledge
whatToDo = r... |
def tile_variants(in_tile):
rval = list()
for _ in range(4):
if in_tile not in rval:
rval.append(in_tile)
if flip_tile(in_tile) not in rval:
rval.append(flip_tile(in_tile))
in_tile = rotate_tile(in_tile)
return rval
def match_tile_right(t1_v, t2_v):
t1_v =... | This function finds compatible tile variants for a corner position by checking each variant of the specified corner tile against the tiles to its right and below. It returns the first valid combination of corner, right, and below tile variants that match, or None if no matches are found. | def match_0_0_corner(tiles, corner, right, below):
for c_v in tile_variants(tiles[corner]):
r_v = match_tile_right(c_v, tiles[right])
b_v = match_tile_below(c_v, tiles[below])
if r_v and b_v:
return c_v, r_v, b_v
return None, None, None |
def match_0_0_corner(tiles, corner, right, below):
for c_v in tile_variants(tiles[corner]):
r_v = match_tile_right(c_v, tiles[right])
b_v = match_tile_below(c_v, tiles[below])
if r_v and b_v:
return c_v, r_v, b_v
return None, None, None
def update_grid_cell(grid, row, col, v)... | This code constructs an image grid by matching tiles according to a given tile grid structure. It starts by identifying the top-left corner tiles, then fills the left column by matching tiles below existing ones, and finally completes each row by matching tiles to the right of their predecessors. The function returns t... | def make_image(tiles, tile_grid):
image = [[None for x in range(len(tile_grid))] for y in range(len(tile_grid))]
## Find the top-left corner
r0_0, r0_1, r1_0 = match_0_0_corner(tiles, tile_grid[0][0], tile_grid[0][1], tile_grid[1][0])
image = update_grid_cell(image, 0, 0, r0_0)
image = update_grid_... |
def print_board(self):
"""print the chessboard in a user friendly way."""
board = deepcopy(self.board)
letters = "# A B C D E F G H #"
print(letters, flush=True)
for i in range(0, 8):
board[i].insert(0, str(8-i)+" ")
board[i].append(" " + str(8-i))
... | This method implements the main game loop, handling player input, validating moves, checking end conditions, and alternating turns between the player and AI. It also manages game reset, replay options, and state rollback for "cancel" actions, ensuring the game flows until a quit or end condition is met. | def run(self):
"""
this method is the main gameloop.
"""
while True:
self.print_board()
if self.check_end_condition(True):
replay = self.ending_menu("Computer", self.check_end_condition(True))
if replay:
self.re... |
def json_loads_byteified(json_text):
return _byteify(
json.loads(json_text, object_hook=_byteify),
ignore_dicts=True
)
def get_bot_room_id(BOT_ACCESS_TOKEN):
URL = 'https://webexapis.com/v1/people/me'
headers = {
"Authorization": "Bearer "+BOT_ACCESS_TOKEN,
"Content-Type"... | The code retrieves Webex rooms the bot belongs to, lists them, and checks configured webhooks. It compares webhook details (name, URL, status) against expected values, removing mismatches and creating new webhooks if needed. It ensures the bot's webhook configuration aligns with predefined settings, updating or deletin... | def get_bot_status():
url = "https://webexapis.com/v1/rooms"
payload = {}
headers = {
'Content-Type': 'application/json',
'Authorization': "Bearer " + bearer
}
response = requests.request("GET", url, headers=headers, data=payload)
data = json_loads_byteified(response.text)
p... |
def init_weights():
return np.zeros((N, ACTION_NO))
def init_E():
return np.zeros((N, ACTION_NO))
def normalize_state(state):
p, v = state
p_n = (p-env.observation_space.low[0]) / (env.observation_space.high[0] - env.observation_space.low[0])
v_n = (v-env.observation_space.low[1]) / (env.observation... | The code implements the **SARSA(λ)** algorithm with linear function approximation for reinforcement learning. It trains a policy in an environment by updating weights (W) using eligibility traces (E) and temporal difference (TD) errors. Key steps include: initializing weights, selecting actions via ε-greedy, computing ... | def sarsa_lambda(env, episodes=episodes, max_steps=max_steps_in_episode, is_saving_weights=False,
epsilon_max=epsilon_max, epsilon_min=epsilon_min, is_decay=False, _lambda=_lambda, alpha=alpha):
# (p,v,a) = (p,v,i) @ (i,a) => the shape of W should be (i,a): (32,3)
W = init_weights()
total... |
def type(self) -> Type:
return self.types[self.index] if self.canRetrieve() else Types.EOF
def getLineOfCurrentToken(self) -> int:
# returns the line the current token is on
# get index before stepping down
indexBeforeStepDown = self.index
# go back to the start
... | This function checks if the current token's type matches any of the specified expected types. If not, it prints an error message with the line number, expected types, token index, and highlights the problematic line in the input. It then exits with an error code. The main task is to validate token types during parsing ... | def expect(self, *types: Type):
typeFound = False
for i in types:
if self.type() == i:
typeFound = True
break
if not typeFound:
#error
print(traceback.format_exc())
print(bcolors.UNDERLINE + bcolors.BOLD + bcolors.FA... |
def add_random_word_to_scores(scores, vocab, model, cache):
sample_score = None
while sample_score is None:
sample = vocab.sample(1).iloc[0]
sample_score = get_score_from_word_key(sample.key, cache)
return add_word_to_scores(sample.key, sample_score, scores, model)
def get_score_from_word_ke... | The code performs an iterative search to find a word with the highest score by exploring similar words in a vocabulary. It starts with a random word, uses a model to find similar words, checks their scores, and updates the best score iteratively. The process continues until a score of 1 is achieved, returning the optim... | def search(button):
N_vocab = int(widget_N_vocab.value)
N_neighborhood = widget_N_neighborhood.value
vocab_selection = vocab.head(N_vocab)
with OUTPUT:
print(f"Search start.")
cache = dict()
scores = pd.DataFrame(columns=["key", "score", "vector"])
scores = add_random_word_to_scores(... |
def threewayhandshake():
global seq_number
message_number_2 = '0'
successful_connection_2 = False
# Starts three-way handshake
seq_num = 0
syn_header = Header(seq_num, 0, ack_bit = 0, syn = 1, fin = 0, data_size = 0, judge_timeout = 0)
clientSocket.sendto(syn_header.bits(), server_address)... | The code implements a sender thread for reliable data transmission using a sliding window protocol. It initializes the sender window buffer, sends data packets with sequence numbers, manages retransmission timers, tracks sent packets, and handles acknowledgments. The thread maintains flow control, ensures ordered deliv... | def senddataThread():
global t_lock
global clientSocket
global timeout
global message_number
global successful_connection
#global message_size
global seq_number
global retransimit
global message_amount
global max_packet
global sender_window
global socket_num
global s... |
def is_func(self, str):
"""
Checks if a token string contains a function.
@param str: Token string to be checked.
@type str: string
@return: True if the token string contains a function.
@rtype: Boolean
"""
return str in ['exp', 'ln']
def is_op(self, st... | This function parses a tokenized arithmetic expression into an abstract syntax tree (AST) using recursive descent and operator precedence rules. It processes tokens, manages operator and value stacks, and recursively handles subexpressions within parentheses. The AST is built by evaluating operator precedence, combinin... | def parse_token_list_rec(self, min_precedence):
"""
Parses a tokenized arithmetic expression into a parse tree. It calls
itself recursively to handle bracketed subexpressions.
@return: Returns a token string.
@rtype: lems.parser.expr.ExprNode
@attention: Does not handle... |
def wait_until(function):
while not function():
pass
def is_button_pressed(side:int=0):
if side == button.LEFT:
return button.pressed(button.LEFT) > 0
elif side == button.RIGHT:
return button.pressed(button.RIGHT) > 0
else:
return button.pressed(button.LEFT) > 0 or button... | Your return
The code continuously waits for the right button to be pressed. Upon detection, it moves forward and plays two sounds: 'Wand' followed by 'Emotional Piano'. This loop repeats indefinitely, triggering movement and sound each time the button is pressed. | def my_code_right():
while True:
wait_until(lambda: is_button_pressed(button.RIGHT))
forward()
appsound.play('Wand')
appsound.play('Emotional Piano') |
def generate_blocks(n_genes, n_informative, n_topics=2, n_cells=1, mixed=False, blocks=None, means=None, variances=None):
"""
Gives all necessary information to understand a block dataset based on the specified boundaries
Parameters
----------
n_genes : int
The number of to... | The main task of the code is to generate a synthetic labeled dataset for testing segmentation algorithms. It creates structured data with configurable parameters like gene counts, topics, noise, and spatial patterns (blocks, gradients, splits), returning features, true labels, and optionally noisy labels in array or Da... | def generate_dataset(n_genes, n_informative, n_cells=900, n_topics=2, blocks=None, mode=None, mixed=False, means=None, variances=None, x_max=30, y_max=30, as_df=False):
"""
Used for testing any segmentation algorthim by returning a lebeled dataset.
Parameters
----------
n_genes : int
... |
def _set_priors(self, vocab_size):
if self.topics_prior is None:
self.topics_prior = np.ones(vocab_size)/vocab_size
if self.docs_prior is None:
self.docs_prior = np.ones(self.n_topics)/self.n_topics
return self.topics_prior, self.docs_prior
def _init_labels(self, X, n_doc... | This code trains a probabilistic model by initializing priors, document-topic labels, and distributions, then iteratively sampling document-topic assignments over n_steps to refine the model's understanding of the input data's topic structure. | def fit(self, X, n_steps=100, verbose=1):
n_docs, n_words, vocab_size = *X.shape, np.unique(X).shape[0]
self._set_priors(vocab_size)
self._init_labels(X, n_docs, n_words, vocab_size)
self._init_dists()
for _ in tqdm(range(n_steps)) if verbose == 1 else range(n_steps):
... |
def conv_bn_relu_pool(self,bottom,id,name):
"""
This function performs a series of operations including convolution, batch normalization, ReLU activation, and max pooling. It takes three parameters: bottom (the input data), id (an identifier), and name (a string for naming layers). It returns the result... | This code builds a neural network for face parsing and image generation. It processes input images through downsampling convolutional layers, upsampling transpose convolutions with skip connections, and residual blocks. The model generates face labels via softmax and combines them with blurred inputs to produce refined... | def build(self,blur,halfImg):
"""
Face Parsing
"""
# Face Parsing
# downsample
self.conv_bn_reluP_1,self.pool_P_1=self.conv_bn_relu_pool(blur,0,name='P')
self.conv_bn_reluP_2,self.pool_P_2=self.conv_bn_relu_pool(self.pool_P_1,1,name='P')
self.conv_bn_relu... |
def _normalize(self, x: torch.Tensor):
if self.normalize == "peak":
return (1.0 / self.peak) * x * 0.95
else:
return x
def _stabilized_threshold_and_psd_maximum(self, x_ref: torch.Tensor):
"""
Return batch of stabilized masking thresholds and PSD maxima.
:... | The code computes a scaled masking hinge loss for adversarial examples by measuring perturbation against a reference waveform, applying a stabilization threshold, and normalizing inputs. It calculates the difference between adversarial and reference signals, derives loss using a masking function, then scales the result... | def forward(self, x_adv: torch.Tensor, x_ref: torch.Tensor = None):
self.peak = torch.max(
torch.abs(x_ref) + 1e-12, dim=-1, keepdim=True)[0]
x_adv = self._normalize(x_adv)
# use precomputed references if available
if self.ref_wav is None:
x_ref = self._normali... |
def get_total_attraction_force(self, objects):
total_fx = total_fy = 0
for object in objects:
if self == object:
continue
fx, fy, f= self.attraction_force(object)
total_fx += fx
total_fy += fy
return total_fx, total_fy
def calculat... | This function calculates the position and velocity of an object influenced by gravitational forces from other objects. It first computes the total attraction forces (Fx, Fy), then determines velocity (x_vel, y_vel) based on these forces, and finally calculates the new position (x, y) using the velocity. The result is t... | def calculate_pos_and_vel(self, objects):
total_fx, total_fy = self.get_total_attraction_force(objects)
x_vel, y_vel = self.calculate_velocity(total_fx, total_fy)
x, y = self.calculate_position(x_vel, y_vel)
return x, y, x_vel, y_vel |
def clear_screen():
# for windows
if os.name == 'nt':
_ = os.system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = os.system('clear')
def create_and_stock_shop():
s = Shop()
with open('../files/stock.csv') as csv_file:
csv_reader = csv.reader(csv_file, del... | The code implements a procedural Python shop system allowing users to view stock, process customer orders with budget validation, and engage in live shop mode. It maintains a loop for menu-driven interactions, handles customer purchases by checking affordability, and manages shop inventory dynamically. | def main():
clear_screen()
print(f"Shop in Python (procedural) project by Killian Foley.\n")
# Create and stock the shop
print(f"Opening today's shop.")
shop = create_and_stock_shop()
# display menu first time
shop_menu()
# forever loop
while True:
# display the menu
... |
def add_article(self):
mand_attributes = ["author", "title", "journal", "year"]
opt_attributes = ["volume", "number", "pages", "month", "note"]
self.app.add_reference(self.add_loop(
mand_attributes, opt_attributes, "article"), self.add_tags())
self.io.write_screen(
... | The main task of the code is to present a menu for users to select a reference type (article, book, inproceedings, phdthesis) or return to the main menu. It processes user input, invokes the corresponding method to add the selected reference type, and handles invalid inputs by displaying an error message. The loop ensu... | def add_reference(self):
while True:
self.console.print(
"\n[bold cyan2]Choose reference type:[/bold cyan2]\n" +
"[cyan]1[/cyan] to [bright_blue]add article[/bright_blue]\n" +
"[cyan]2[/cyan] to [bright_blue]add book[/bright_blue]\n" +
... |
def add_reference(self):
while True:
self.console.print(
"\n[bold cyan2]Choose reference type:[/bold cyan2]\n" +
"[cyan]1[/cyan] to [bright_blue]add article[/bright_blue]\n" +
"[cyan]2[/cyan] to [bright_blue]add book[/bright_blue]\n" +
... | This code provides a menu-driven interface for managing references, allowing users to add, view, save, search, delete references, or exit. It loops until the user selects option 7, handling input with conditional method calls for each action. | def start(self):
while True:
self.console.print(
"\n[bold cyan1]Choose an action:[/bold cyan1]\n" +
"1 to [bright_blue]add references[/bright_blue]\n" +
"2 to [bright_blue]print references[/bright_blue]\n" +
"3 to [bright_blue]save refe... |
def ssh_run_command(
name_and_client: Tuple[str, paramiko.SSHClient],
command: str,
) -> str:
name, client = name_and_client
_, stdout, stderr = client.exec_command(command)
error: str = stderr.read().decode()
out: str = stdout.read().decode()
if error:
raise Exception(f'Fail... | This function adds non-duplicate SSH keys to a remote server's authorized_keys file. It optionally backs up the original file, retrieves existing keys, removes duplicates by combining them with new keys using a set, then writes the merged unique keys back to the authorized_keys file. | def add_nonduplicate_keys(
name_and_client: Tuple[str, paramiko.SSHClient],
keys: List[str],
make_backup: bool = True,
) -> None:
if make_backup:
ssh_run_command(name_and_client, 'cp ~/.ssh/authorized_keys ~/temp_authorized_keys')
existing_keys = get_authorized_keys(name_and_clie... |
def get_best_split(self, dataset : pd.DataFrame, num_features : int) -> dict:
'''Method to find the best split
This is a greedy method that finds the best feature and value to split\\
on to maximize information gain. It does not guarantee an optimal\\
decision tree, but for its ... | The function recursively constructs a decision tree by selecting the optimal feature-threshold split (based on information gain) to partition the dataset. It continues splitting until stopping conditions (minimum samples, maximum depth) are met, returning a Decision Node with left/right subtrees. If conditions halt spl... | def build_tree(self, dataset : pd.DataFrame, curr_depth : int =0) -> NodeDTC:
'''Recursive method to build the tree
Parameters
----------
dataset : `Dataframe`
The dataset to build the tree on
curr_depth : `int`
The current depth of the tree under constru... |
def detect_languages(path: str) -> set[str]:
extensions = {
".go": "go",
".js": "javascript",
".ts": "typescript",
".php": "php",
".py": "python",
".rs": "rust",
".c": "c",
".c++": "cpp",
".cc": "cpp",
".cpp": "cpp",
".cu": "cpp... | The main task of the code is to analyze a project's codebase by detecting supported languages, applying specified linters for each language, and aggregating linting results. It initializes a structured output with linter configurations and files processed, handling different programming languages through specialized li... | def lint_project(path: str, linters: dict[str, str]) -> dict:
langs = detect_languages(path)
linters = get_linters(langs, linters)
result = {
"status": "done",
"linters": linters,
"files": [],
}
try:
for lang in langs:
linter = linters[lang]
... |
def num_violations(self):
return self.has_front_violation() + self.has_sm_side_violation() + self.has_lg_side_violation() + self.has_rear_violation()
def has_front_violation(self):
return self.has_violation(self.lot.front_sb, self.setbacks.get_front_setback_for_lot)
def has_sm_side_violation(self):
... | This method generates a textual summary of setback violations for a lot. It checks if there are no violations, returning 'no violations' if true. Otherwise, it constructs a string listing the number of violations and details for each type (front, sm_side, lg_side, rear), including required and actual setback values fro... | def get_violations_text(self):
if self.num_violations() == 0:
text = 'no violations'
else:
text = f'{self.num_violations()} violations: '
if self.has_front_violation():
text += f'front: setback={self.setbacks.get_front_setback_for_lot(self.lot):0.0f} a... |
def get_num_lots(self):
return len(self.lots)
def get_num_unsavable_lots(self):
return len(self.unsavable_lots)
def get_fraction_unsavable_lots(self):
return 1.0 * self.get_num_unsavable_lots() / self.get_num_lots()
def get_num_savable_lots(self):
return self.get_num_lots() - self.get_nu... | This function generates a summary text reporting setback rules and their impact on lots, including counts and percentages of conformable/unconformable lots, conforming/non-conforming lots, and violation fractions among conformable lots. It formats statistical data for clarity, highlighting compliance rates and minimum ... | def get_violations_summary_text(self):
txt = f'\n\nSetback Rules:\n'
txt += f' Front: {self.setbacks.get_front_formula()}\n'
txt += f' SmSide: {self.setbacks.get_sm_side_formula()}\n'
txt += f' LgSide: {self.setbacks.get_lg_side_formula()}\n'
txt += f' Rear: {self.setb... |
def assign_random_vulnerabilities(os_type: str, vulnerability_library: List[Vulnerability], library: Library) \
-> List[Vulnerability]:
vulnerability_list = []
for vulnerability in vulnerability_library:
if vulnerability.effected_os == os_type and\
random.random() < library.os_vu... | This function generates a list of computer nodes with randomized attributes including OS type, vulnerabilities, properties, services, and firewall rules. Each node is initialized with unique IDs, assigned random configurations from provided libraries, and added to the nodesList. Credentials from services are collected ... | def create_nodes(self):
for num in range(self.num_nodes):
node = ComputerNode()
node.nodeId = str(num)
node.OSType = random.choice(self.library.os_library)
assigned_vulnerabilities = assign_random_vulnerabilities(node.OSType, self.library.vulnerability_library,
... |
def get_compromised_node_info(self):
for node in self.network.nodesList.values():
if node.compromised and node.nodeId not in self.compromised_node_ids \
and node.nodeId not in self.explored_node_ids:
self.compromised_node_ids.append(node.nodeId)
se... | The code simulates a local attack on a network node by selecting a compromised target, exploiting vulnerabilities to escalate privileges, and collecting cached credentials or node IDs. It checks exploitation success, updates rewards, and tracks discovered credentials or nodes. If privilege escalation succeeds, the node... | def local_attack(self):
self.get_compromised_node_info()
while True:
self.target_node_id = self.compromised_node_ids[random.randint(0, len(self.compromised_node_ids) - 1)]
if self.target_node_id not in self.defender.re_imaging_nodes:
break
self.current_nod... |
def get_compromised_node_info(self):
for node in self.network.nodesList.values():
if node.compromised and node.nodeId not in self.compromised_node_ids \
and node.nodeId not in self.explored_node_ids:
self.compromised_node_ids.append(node.nodeId)
se... | The code performs a remote attack by probing discovered nodes, exploiting vulnerabilities to achieve lateral movement, updating network connections, and adjusting rewards based on success. It gathers credentials, selects matching vulnerabilities, and attempts exploitation, modifying node statuses and reward accumulatio... | def remote_attack(self):
self.get_compromised_node_info()
for node_id in self.discovered_node_ids:
if self.remote_probe(node_id):
print("Gathered information about " + node_id)
self.reward_accumulated += 2
else:
self.reward_accumula... |
def get_compromised_node_info(self):
for node in self.network.nodesList.values():
if node.compromised and node.nodeId not in self.compromised_node_ids \
and node.nodeId not in self.explored_node_ids:
self.compromised_node_ids.append(node.nodeId)
se... | The code determines whether to perform a local or remote attack based on the presence of compromised nodes and discovered nodes. If compromised nodes exist and no discovered nodes are found, it triggers a local attack. If discovered nodes exist, it initiates a remote attack. Otherwise, it returns False, indicating no a... | def attack(self):
self.get_compromised_node_info()
if len(self.compromised_node_ids) != 0 and len(self.discovered_node_ids) == 0:
self.local_attack()
elif len(self.discovered_node_ids) != 0:
self.remote_attack()
else:
return False
return True |
def log_sth(self, log:str) -> None:
"""Writes given string to the log file of the base_path
Args:
log (str): String to be written in the log
"""
msg = f"{self.name}:\t{log}\n"
with open(os.path.join(self.base_path,"log.dat"), "a") as out:
out.write(msg)
with open(o... | This method initializes setup for an '.ins' configuration by logging parameters like base_path, energy_source, and solution_name. It conditionally calls setupInsHeader(), setupInsIns(), or setupInsDefault() based on the energy_source value, then logs confirmation that the '.ins' setup is complete. | def setupIns(self) -> None:
self.log_sth(f"\n===========================\nbase_path:{self.base_path}\nenergy_source:{self.energy_source}\nsolution_name:{self.solution_name}\n===========================")
if self.energy_source == "header":
self.setupInsHeader()
elif self.energy_source == "ins"... |
def setupIns(self) -> None:
self.log_sth(f"\n===========================\nbase_path:{self.base_path}\nenergy_source:{self.energy_source}\nsolution_name:{self.solution_name}\n===========================")
if self.energy_source == "header":
self.setupInsHeader()
elif self.energy_source == "ins"... | The code's main task is to initialize setup, check the validity of a file, perform refinement, and extract information with error handling. It logs progress and errors during setup, refinement, and info extraction, ensuring proper workflow and handling failures in extraction gracefully. | def run(self) -> None:
self.setupIns()
if os.path.getsize(self.final_ins_path) == 0:
self.log_sth("Failed to init the .ins, filesize = 0!")
return
self.log_sth("Finished Setup of INS")
self.refine()
self.log_sth("=========================== Finished Refinement =============... |
def inputGenXY(path):
global x
global y
f = open(path)
f_content = f.read()
# Nested list of sentences and its words
x = []
# Corresponding labels matching the sentence
y = []
xi = []
yi = []
for data_pair in f_content.split('\n'):
if data_pair == '':
... | The main task of the code is to train a sequence model (likely an HMM) by generating transition and emission parameters from labeled data, preparing unique label vocabulary, and saving these for later use in prediction. It processes input data, computes second-order transition tables, emission probabilities, and stores... | def run_train(path):
global x
global y
global label_count
global word_list
print("--- Training Start ---")
x,y = inputGenXY(path)
# Generate Transition Params Table
transParamsTable()
transitionParameters_second_order()
# Generate Emission Params Table
emissionParameters()
... |
def transitionParamsTable(trainFile):
global transition
global x
global y
# # Input training file
# x, y = inputGenXY(trainFile)
# Initialise an square array of zeros.
transition = np.zeros((len(tag)-1, len(tag)-1))
for yi in y:
# START
transition[-1, yi[0]] += 1... | This function applies the Viterbi algorithm with k=3 to tag sequences in a development dataset using pre-trained transition and emission probabilities. It loads parameters from a training file, processes input data, runs the modified Viterbi algorithm, and writes tagged results to a specified output file. | def executeViterbiK(trainingFile, devIn, filepath, k=3):
global transition
global emission
# Load Trained Params
transition, emission = transitionParamsTable(trainingFile), emissionParamsTable(trainingFile)
# Store results specified output file
with open(filepath, 'w') as f:
w... |
def clear_frame(self, frame):
for widget in frame.winfo_children():
widget.destroy()
def create_button(self, master, text, command, width=20, height=2, pady=10):
return tk.Button(master, text=text, command=command, width=width, height=height, fg='black', bg='#3c3f41', activebackground='#4b4b... | This code displays a screen with buttons for selecting tonalities (Major, Minor, Chromatic, Modes). Clicking "Modes" navigates to the modes screen, while other tonalities proceed to the difficulty selection screen. A "Back" button returns to the main menu. The function clears the current frame and dynamically generates... | def show_tonality_screen(self):
self.clear_frame(self.main_frame)
tonalities = ["Major", "Minor", "Chromatic", "Modes"]
for tonality in tonalities:
self.create_button(self.main_frame, tonality, lambda t=tonality: self.show_modes_screen() if t == "Modes" else self.show_difficulty_scre... |
def clear_frame(self, frame):
for widget in frame.winfo_children():
widget.destroy()
def create_button(self, master, text, command, width=20, height=2, pady=10):
return tk.Button(master, text=text, command=command, width=width, height=height, fg='black', bg='#3c3f41', activebackground='#4b4b... | This code displays the seven major modes (Ionian to Locrian) as buttons on the main frame, allowing users to select a mode to proceed to a difficulty screen, with a "Back" button to return to the modes screen. | def show_major_modes_screen(self):
self.clear_frame(self.main_frame)
major_modes = ["Ionian", "Dorian", "Phrygian", "Lydian", "Mixolydian", "Aeolian", "Locrian"]
for mode in major_modes:
self.create_button(self.main_frame, mode, lambda m=mode: self.show_difficulty_screen(m, from_mode... |
def clear_frame(self, frame):
for widget in frame.winfo_children():
widget.destroy()
def create_button(self, master, text, command, width=20, height=2, pady=10):
return tk.Button(master, text=text, command=command, width=width, height=height, fg='black', bg='#3c3f41', activebackground='#4b4b... | This function displays a screen with buttons for each melodic minor mode (e.g., Dorian b2, Lydian Augmented). Each button triggers the difficulty screen for its respective mode. A "Back" button returns to the main modes screen. | def show_melodic_minor_modes_screen(self):
self.clear_frame(self.main_frame)
melodic_minor_modes = ["Melodic Minor", "Dorian b2", "Lydian Augmented", "Lydian Dominant", "Mixolydian b6", "Locrian #2", "Altered"]
for mode in melodic_minor_modes:
self.create_button(self.main_frame, mode... |
def class_name_generation2(self, set_text):
cname2count = ddict(int)
idx_generator = self.rand_idx(len(set_text))
for _ in range(GENERATION_SAMPLE_SIZE):
for template in self.generation_templates2:
candidate = set()
q = queue.Queue()
q.... | The code expands a query set of entities to a specified target size by iteratively generating class names, identifying related entities, and filtering results. It uses class-guided expansion to add new entities while avoiding duplicates and adjusting parameters like 'margin' to handle stagnation, ensuring efficient gro... | def expand(self, query_set, target_size, m=2):
print('start expanding: ' + str([self.eid2name[eid] for eid in query_set]))
start_time = time.time()
expanded_set = []
prev_cn = set()
neg_set = set()
neg_cnames = set()
decrease_count = 0
margin = m
... |
def evaluate(self):
score_window = deque(maxlen=10)
with torch.no_grad():
next_obs = torch.Tensor(self.env.reset()).to(self.device)
next_done = torch.zeros(self.config['num_workers']).to(self.device)
for t in range(self.config['ppo_eval_steps']):
... | The code trains a model by iteratively evaluating performance, updating parameters, and clearing the buffer until early stopping is triggered. After training, it tests the agent and saves the results. | def train(self):
while not self.early_stopped:
self.evaluate()
self.update()
self.buffer.clear()
self.test_agent()
self.save() |
def _config_mode(self):
self._set_mode(self.OPERATION_MODE_CONFIG)
def _read_byte_data(self,address,reg):
return self._i2c.read_byte(address,reg)
def _write_byte_data(self,i2c_addr, reg, value, force=None):
self._i2c.write_byte_data(i2c_addr,reg, value,force)
def _operation_mode(self):
s... | (The function retrieves and returns system status, self-test results, and error information from a sensor device. It returns a tuple with three values: the system status register (indicating operational state), the self-test result register (bitwise pass/fail for sensors/MCU), and the system error register (error codes... | def get_system_status(self, run_self_test=True):
"""Return a tuple with status information. Three values will be returned:
- System status register value with the following meaning:
0 = Idle
1 = System Error
2 = Initializing Peripherals
3 = Syst... |
def _write_byte_data(self,i2c_addr, reg, value, force=None):
self._i2c.write_byte_data(i2c_addr,reg, value,force)
def _config_mode(self):
self._set_mode(self.OPERATION_MODE_CONFIG)
def _read_byte_data(self,address,reg):
return self._i2c.read_byte(address,reg)
def get_system_status(self, run_self... | (The code initializes a BNO055 sensor by configuring GPIO, sending a dummy command to reset the device, verifying its chip ID, resetting the system, setting power mode to normal, configuring units, and switching to ACCGYRO operation mode to enable accelerometer and gyroscope data collection.) | def initialize(self):
# Initialize GPIO
self._gpio.initialize()
# First send a thow-away command and ignore any response or I2C errors
# just to make sure the BNO is in a good state and ready to accept
# commands (this seems to be necessary after a hard power down).
self.... |
def getById(self, itemId):
for item in self.items:
if item[0] == itemId:
return item
return []
def renderTable(self, page, tableWidget, nameSearch="name", tagSearch="tags"):
# page = 0: Main
# page = 1: PLanner
tableWidget.clear()
tableWidget.s... | This function updates an item's name and tags based on user input, refreshes the table display, saves changes to the database, and optionally schedules a calibration task after a 6-minute delay if synchronization is enabled. | def changeItem(self, itemId, values, tableWidget, dialogue, nameSearch, tagSearch, sync):
item = self.getById(itemId)
item[1] = values[0].text()
tags = values[1].text().split("|")
for tag in tags:
tag = tag.strip()
item[2] = tags
self.renderTable(0, tableWidge... |
def check_events(self):
self.global_trigger = False
for event in pg.event.get():
if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
pg.quit()
sys.exit()
elif event.type == self.global_event:
self.gl... | The code's main task is to continuously process events, update the application's state, and render visuals in an infinite loop, typically used in game or GUI applications to maintain real-time interaction and dynamic content display. | def run(self):
while True:
self.check_events()
self.update()
self.draw() |
def layer_norm(x, weight, bias, eps: float = 1e-5):
mean = np.mean(x, axis=-1, keepdims=True)
variance = np.var(x, axis=-1, keepdims=True)
return weight * (x - mean) * rsqrt(variance + eps) + bias
def token_mixing(x, x_prev, a_prev, b_prev, p_prev, time_mix_r, time_mix_k, time_mix_v, r_proj, k_proj, v_proj,... | The code processes a token through a neural network with multiple blocks, applying layer normalization and mixing operations (token and channel) iteratively. It updates the state at each step and returns logits for prediction, likely in a language model context. | def rwkv_net(token, state, emb, blocks, ln_out, head):
x = emb['weight'][token]
# initial layer norm is stored in block 0 in default weight file
ln0 = blocks[0]['ln0']
x = layer_norm(x, **ln0)
for i in range(len(blocks)):
x_tm = layer_norm(x, **blocks[i]['ln1'])
x_p, a_state, b_sta... |
def check_d(self,g):
for x in range(self.size[0]):
for y in range(self.size[1]):
if g[x][y]>0 and g[x][y]!=9:#0...
b=0
e=[]
for way in self.ways:
if x+way[0]>=0 and x+way[0]<self.size[0]:
... | The code's main task is to solve a grid-based puzzle by iterating through cells, performing mouse actions (clicks/right-clicks) at calculated positions, updating the grid state (`self.g`), and invoking helper methods (`check_d`, `check_u`, `desperate_measure`, `getall`) to navigate or resolve the puzzle. It continues l... | def solve(self):
self.g=[[0 for y in range(self.size[1])]for x in range(self.size[0])]
while True:
a=self.check_d(self.g)
if a!=False:
if a[0]:
for w in a[3]:
pp.moveTo((self.s[0]+(a[1]+w[0])*self.ss+self.ss//2,self.s[1]... |
def checkForPinsAndChecks(self):
pins = []
checks = []
inCheck = False
if self.whiteToMove:
enemyColor = 'b'
allyColor = 'w'
startRow = self.whiteKingLocation[0]
startCol = self.whiteKingLocation[1]
else:
enemyColor = '... | This code generates valid moves for the current player, considering check status, checkmate/stalemate conditions, and castling. It filters moves to block checks, handle double checks by moving the king, and includes castling moves when applicable. | def getValidMoves(self):
# for log in self.castleRightsLog:
# print(log.wks, log.wqs, log.bks, log.bqs, end = ", ")
moves = []
tempCastlingRights = CastlingRights(self.currentCastlingRights.wks, self.currentCastlingRights.bks,
self.curr... |
def removeWorkingDir():
#remove files from previous run if dir exists
path = 'lazy_rla_cvr/'
isdir = os.path.isdir(path)
if isdir:
rmtree(path)
def batchSelect(manifest_file, tabulation_file, seed, overvotes1 = 1, undervotes1 = 1, overvotes2 = 1, undervotes2 = 1):
'''
Summary: takes i... | The code performs an election audit by selecting batches and ballots for verification, checking required files, generating test data, and calculating a risk level to assess election integrity. It simulates auditing processes, validates file presence, and computes risk based on sampled votes against official counts to d... | def electionAudit():
'''
Audit election
'''
print('Election audit:')
removeWorkingDir()
#manifest, tabulation and seed will be given by user on Michael's end
seed1 = 2368607141
tabulation_file = str(os.path.join(sys.path[0], 'electionTabulation.csv'))
manifest_file = str(os.path.joi... |
def popDeck(deck):
for i in range(6):
for j in range(4):
for k in range(13):
deck.append(Card(j, k))
random.shuffle(deck)
def reshuffleDeck(deck, ddeck):
for i in range(len(ddeck)):
deck.append(ddeck.pop())
random.shuffle(deck)
return deck, ddeck
def initG... | This code simulates a card game (likely Blackjack) over multiple rounds. It manages a deck, initializes player/dealer hands, and applies strategy rules for hitting/staying based on card values. The player's turn follows conditional logic for Aces and dealer cards, while the dealer follows a fixed 17 rule. Outcomes (win... | def main(games):
deck = []
ddeck = [] # Dead deck to contain all cards that were played
wins = 0
global gamesPlayed
popDeck(deck)
for i in range(games):
print("Game #" + str(i+1))
if len(deck) < 157:
deck, ddeck = reshuffleDeck(deck, ddeck)
player, dealer, d... |
def check_config():
this = True
if not os.path.isfile(configFile):
this = False
else:
f = read_yaml(configFile)
for i in f['scriptSettings']:
if f['scriptSettings'][i] == None or f['scriptSettings'][i] == '':
this = False
for i in f['awsSettings']:... | The main task of the code is to retrieve and process unseen emails from multiple IMAP accounts based on a configuration file, upload them to an AWS S3 bucket, and handle errors during the process. It checks the config's validity, connects to each email account, fetches a specified number of unread emails, sorts them, p... | def main():
logging.info('Start')
if not check_config():
print("\033[93m","The configuration file is missing or contains empty parameters. Try to run Init script first.")
return False
scrCon = read_yaml(configFile)['scriptSettings']
aws = read_yaml(configFile)['awsSettings']
emails ... |
def _build_model( self, input_ ):
# deep_1 = Dense( self.encoding_dim * 3, activation = "elu" )( input_ )
# deep_2 = Dense( self.encoding_dim * 2, activation = "elu" )( deep_1 )
encoding = Dense( self.encoding_dim, activation = "elu" )( input_ )
# deep_3 = Dense( self.encoding_dim * 2, a... | This code trains an autoencoder neural network using provided data. It builds a model from scratch, compiles it with Adam optimizer and custom loss functions, trains via generators with specified batch sizes, validates if configured, and saves the trained model to a file. Key steps include data validation checks, model... | def train( self, save_dir = "dae.h5" ):
logging.info( "Building new net from scratch" )
if self.data is None:
logging.error( "An attempt to build the autoencoder was made without supplying data to train from!" )
exit() # turn this in to a proper error
input_ = Input... |
def init_env_tab(self):
self.tab_env = ttk.Frame(self.tabControl)
frm_rules = tk.Frame(self.tab_env)
frm_params = tk.Frame(self.tab_env)
frm_controls = tk.Frame(self.tab_env)
self.selection_frame(frm_rules, 'env')
self.set_controls(frm_controls)
frm_rule... | The main task of the code is to initialize a settings window with multiple tabs using Tkinter. It creates a Toplevel window titled "Settings," adds a ttk.Notebook widget for tabbed interface management, and initializes three tabs via separate methods (init_env_tab, init_cell_tab, init_plot_tab). The tabbed interface is... | def init_window(self):
self.win = tk.Toplevel()
self.win.title("Settings")
self.tabControl = ttk.Notebook(self.win)
self.init_env_tab()
self.init_cell_tab()
self.init_plot_tab()
self.tabControl.pack(expand=1, fill="both") |
def update_selected(self, new_selected_envrule=None, new_selected_cellrule=None, new_selected_plotrule=None):
if new_selected_envrule:
self.selected_envrule = new_selected_envrule
self.selected_envrule_params = self.selected_envrule.params
self.selected_envrule_params_exp = s... | This code initializes an object with simulation rules and a chosen plot rule, assigns attributes from the simulation, updates selected rules, retrieves rules, and initializes a window. | def __init__(self, sim, chosen_plotrule):
self.sim = sim
self.chosen_envrule = self.sim.envrule
self.chosen_cellrule = self.sim.cellrule
self.chosen_plotrule = chosen_plotrule
self.update_selected(self.chosen_envrule, self.chosen_cellrule, self.chosen_plotrule)
... |
def manhattan_distance(state, grid_size):
accumulated_cost = 0
curr_x = 0
curr_y = 0
fixed_x = 0
fixed_y = 0
for i in range(len(state)):
curr_x = state[i] % grid_size
fixed_x = i % grid_size
curr_y = math.floor(state[i] / grid_size)
... | This function handles user input for a sliding puzzle game, enabling tile selection via mouse clicks, puzzle shuffling, and algorithm-based solving (A* or IDA*). It also processes keyboard inputs for directional moves and initiates animations, while checking for valid moves and preventing actions during ongoing animati... | def handle_input(npuzzle):
# see mouse select which tile
selected_x, selected_y = pygame.mouse.get_pos()
selected_x = int(selected_x/npuzzle.tile_size)
selected_y = int(selected_y/npuzzle.tile_size)
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_presses = pygame.mou... |
def forward_backbone(self, data):
############################################## get ResNet features #############################################
search_dict_list = []
search_img = data['search_images'].view(-1, *data['search_images'].shape[2:]) # (batch, 3, 320, 320)
search_att = dat... | This function routes input data through different processing stages based on the 'mode' parameter. When mode is 'backbone', it processes data via forward_backbone; for 'transformer', it uses search/refer dictionaries in forward_transformer; and for 'head', it generates box predictions from out_embed via forward_box_hea... | def forward(self, data=None, search_dic=None, refer_dic=None, refer_reg=None, out_embed=None,
mode='backbone'):
if mode == 'backbone':
return self.forward_backbone(data)
elif mode == 'transformer':
return self.forward_transformer(search_dic, refer_dic, refer_reg)
... |
def enforce_corrected_spec_in_uncorrected_mt(mt, skip_entry_add=False):
if mt.count_rows() > 0:
raise NotImplementedError('enforce_corrected_spec_in_uncorrected_mt() is only intended for use on empty MatrixTables.')
mt2 = mt.key_rows_by().drop('locus','alleles','grch38_seq').rename({'locus_grch38':'locu... | The main task of the code is to correct and validate genetic insertion sites relative to the GRCh38 reference genome. It ensures consistent haplotype mappings, checks allele alignment, enforces one-to-one mappings between variants and haplotypes, and handles discrepancies by generating new haplotypes or filtering inval... | def fix_ref_insertions(mt, mt_meta, insertions_in, self_reference, allow_NONREF, log):
mt = mt.persist()
if mt.count_rows() == 0:
return enforce_corrected_spec_in_uncorrected_mt(mt.drop('is_reversed_grch38_to_self')), 0
mt = mt.annotate_rows(locus_grch38 = insertions_in[mt.locus].coord_t,
... |
def enforce_corrected_spec_in_uncorrected_mt(mt, skip_entry_add=False):
if mt.count_rows() > 0:
raise NotImplementedError('enforce_corrected_spec_in_uncorrected_mt() is only intended for use on empty MatrixTables.')
mt2 = mt.key_rows_by().drop('locus','alleles','grch38_seq').rename({'locus_grch38':'locu... | The function resolves deletions spanning insertion boundaries by adjusting alleles to match the reference. It handles two cases: (1) deletions starting with an insertion’s base, and (2) deletions starting before insertions. It annotates, validates, and transforms variants, ensuring allele consistency with the reference... | def resolve_deletion_boundary_cases(mt, mt_meta, exploded_insertions, self_homoplasmies, insertions_table, ref, self_ref, allow_NONREF):
""" Thus function only supports:
- Spanning deletions where first base is the same as a reference insertion and last base is outside
- Deletions where the first base is BE... |
def process_single_run(storage_client, bucket, this_folder, run_folder, success_only):
run_prefix = f'{run_folder}/MitochondriaPipelineWrapper/{this_folder}/'
# get all subfolders
subfolders = list_gcs_directories(storage_client, bucket, run_prefix)
dirnames = [os.path.basename(os.path.dirname(x)) for ... | The function checks the status of a merging process in a storage system, categorizing each shard's status (PASS/FAIL/IN PROGRESS/NOT YET MERGING), and returns a structured DataFrame with task details, log files, and success status. It processes results from individual runs, filters outcomes, and aggregates data for rep... | def check_success_single(storage_client, bucket, this_folder, run_folder, success_only):
shards, merge_not_run, merge_items, merge_res, merge_log = process_single_run(storage_client, bucket, this_folder, run_folder, success_only)
if (not merge_not_run) and (merge_res == 'PASS'):
failed = False
... |
def u_arrow():
pen.setheading(-90) # go bottom-middle
pen.forward(unit_length)
pen.setheading(0)
pen.forward(unit_length/2)
pen.setheading(90)
arrow() # draw arrow
pen.setheading(180) # return top-left
pen.forward(unit_length/2)
pen.setheading(90)
pen.forward(unit_length)
... | The function `draw_move` determines which arrow (up, right, down, left) to draw based on the `move` parameter (0-3) and then calls `_next()` to proceed to the next action. Its main task is to render the corresponding directional arrow and trigger the next step in a sequence, likely for a game or animation. | def draw_move(move):
if move == 0:
u_arrow()
elif move == 1:
r_arrow()
elif move == 2:
d_arrow()
elif move == 3:
l_arrow()
_next() |
def initialize(_width, _height):
# module parameter setup
global width, height
global pen, screen
pen = turtle.Turtle()
pen._tracer(0, 0) # Instant drawing
pen.hideturtle()
screen = turtle.Screen()
width = _width
height = _height
# turtle setup
screen.setup((width + 2) * uni... | The code visualizes an environment's actions and a policy's moves using turtle graphics. It initializes a canvas with dimensions from the environment, draws actions in blue, then overlays policy decisions in gray, updating the screen for display. | def draw(env, policy):
width = env.y()
height = env.x()
actions = env.actions.flatten()
initialize(width, height)
pen.color('blue')
for action in actions:
draw_action(action)
move_top()
pen.color('gray')
for move in policy.flatten():
draw_move(move)
pen._update() ... |
def parseBibtexEntry():
#Dictionary to store each entry in the bibtex as a separate key-value pair.
articlesDict = {}
#dictionary for single entry
articleDict = {}
with open('C:\\Users\\aguha\\Documents\\1-PPPL-Research\\1-PPPL-Research\\SupportFiles\\gyrorecs.bib', encoding="utf8") as f:
... | The main task of the code is to simulate and visualize the dynamic positioning of nodes on a spherical surface using repulsive and attractive forces. It parses academic references, generates initial coordinates, applies iterative force calculations to adjust node positions, and creates VTK files for each step. The proc... | def generateCoords3_animation():
articlesDict, adjacencyList, adjacencyListNumTimesReferenced, generatedSphericalCoords = parseBibtexEntry()
adjacencyListInGraph = []
for entry in adjacencyList:
if entry[2] == True:
adjacencyListInGraph.append(entry)
coordsDict = generateCoor... |
def ratio(self):
html = self.get("/index.php")
li = html.find("li", attrs={"id": "stats_ratio"})
title = li.find("a", class_="user-info-bar__link").attrs.get('title')
matches = re.findall(r"Ratio: ([\d.]+)", title)
ratio = float(matches.pop(0))
return ratio
def bonus(self):
html = self.get("... | This code gathers and returns key statistics from a torrent client, including upload/download ratios, bonus points, seeding data, and free leech (FL) information. It applies optional filters, separates 'GoldenPopcorn' content, and aggregates results into a structured dictionary with metrics like total FL entries, golde... | def summary(self, limit=-1, filters=None, filterGoldens=False):
results = {}
results['ratio'] = self.ratio()
results['bonus'] = self.bonus()
results['bprate'] = self.bonus_rate()
results['up'] = self.uploaded()
results['down'] = self.downloaded()
results['buffer'] = self.buffe... |
def allEn():
plainText = getPlainText() #Check
keyword = getKeyword() #Check
keyLenIndex = len(keyword)
if keyLenIndex == 5:
keyLenIndex == len(plainText) % 6
keyLenLetter = alph[keyLenIndex]
newKeyword = decrpytKey(keyword) #Check
newText, spacesAt = findSpaces(plainText) #Check
... | The code provides a menu-driven interface for text scrambling and decryption. It loops until the user selects option 4 to exit. Options 1 and 3 generate scrambled text using `allEn()`, while option 2 decrypts user-provided scrambled text via `allDe()`. Option 3 combines scrambling and decryption in sequence. | def menu():
game = True
while game == True:
validOptions = ['1','2','3','4']
validIn = False
while validIn == False:
select = str(input("SELECT MENU OPTION: "))
if select not in validOptions:
print("INVALID INPUT")
else:
... |
def allEn():
plainText = getPlainText() #Check
keyword = getKeyword("EMBEDDED") #Check
keyLenIndex = len(keyword)
if keyLenIndex == 5:
keyLenIndex == len(plainText) % 6
keyLenLetter = alph[keyLenIndex]
newKeyword = decrpytKey(keyword) #Check
newText, spacesAt = findSpaces(plainText) ... | The code defines a menu-driven interface for encrypting/decrypting text using a Vigenère cipher. It loops until the user selects option 4, validating inputs (1-4). Options 1 and 3 encrypt text via `allEn()` and `vignere()`, while option 2 decrypts user-provided text with `allDe()`. Option 3 combines encryption and decr... | def menu():
game = True
while game == True:
validOptions = ['1','2','3','4']
validIn = False
while validIn == False:
select = str(input("SELECT MENU OPTION: "))
if select not in validOptions:
print("INVALID INPUT")
else:
... |
def reshape_weights(weights_flat, nodes_per_layer):
weights = []
no_params_reshaped = 0
no_layers = len(nodes_per_layer)
for k in range(no_layers - 1):
weights += [ weights_flat[no_params_reshaped: no_params_reshaped + nodes_per_layer[k+1]*(nodes_per_layer[k]+1) ].reshape( (nodes_per_layer[k+1],... | (The function computes the gradient of a neural network using backpropagation. It reshapes input weights into the network structure, calculates gradients via backpropagation with given inputs/outputs and regularization, then flattens the resulting gradient for output.) | def backprop_grad(weights, nodes_per_layer, inputs, outputs):
network = reshape_weights(weights, nodes_per_layer)
gradient = backpropagated_gradient(network, x=inputs, y=outputs, regularisation=regularisation)
return flatten_weights(gradient) |
def flatten_weights(weights_shaped):
weights_flat = []
for _weights in weights_shaped:
weights_flat = np.append( weights_flat, _weights.flatten() )
return weights_flat
def reshape_weights(weights_flat, nodes_per_layer):
weights = []
no_params_reshaped = 0
no_layers = len(nodes_per_layer)... | This function approximates the gradient of the cost function with respect to a specific weight in a neural network using finite differences. It perturbs the weight at index `idx` by ±ε, recomputes the network's cost for both perturbed and original weights, and returns the difference divided by 2ε to estimate the gradie... | def approx_costgrad(network, x, y, idx, regularisation=0.0):
eps = 1e-4
weights = flatten_weights(network)
weights_plus = weights.copy()
weights_plus[idx] += eps
weights[idx] -= eps
nodes_per_layer = [network[0].shape[1]-1]
for weight_mat in network:
nodes_per_layer += [ weight_mat.s... |
def backpropagated_gradient(network, x, y, regularisation=0.0):
no_layers = len(network) + 1
network_delta = [ None ]*(no_layers)
output, a_s = forward_pass(network, x, return_intermediate=True) #Note: output should equal a_s[no_layers-1] so it is not stored in a_s to save memory
for i in reversed(rang... | The function checks the correctness of backpropagation in a neural network by comparing analytically computed gradients with numerically approximated gradients. It generates random inputs/outputs, computes backpropagated gradients, and approximates gradients via finite differences. Regularization is applied to the appr... | def check_backpropagate(network, no_features, no_outputs, regularisation=0.0, no_samples=10, no_trials=5, rng_seed=None):
rng = np.random.default_rng(rng_seed)
nodes_per_layer = [network[0].shape[1]-1]
for weight_mat in network:
nodes_per_layer += [ weight_mat.shape[0] ]
for t in range(no_trials... |
def initialize_network(no_layers=1, nodes_per_layer=[], rng_seed=None):
rng = np.random.default_rng(rng_seed)
network = []
for k in range(no_layers - 1):
network += [ rng.random( size = (nodes_per_layer[k+1],nodes_per_layer[k]+1) ) ] #+1 for bias
return network
def check_backpropagate(network, n... | The code trains a neural network to predict QAOA angles for a 9-qubit, 3-layer quantum circuit. It processes command-line arguments to define network architecture, regularization, and backpropagation tests. The network is initialized, trained on Ising coefficient data, and optimized across 10 random initializations. Th... | def main():
#Predefined from generated QAOA instances
N = 9 #9 qubit QAOA circuit
p = 3 #3 layer QAOA circuit
#Pass argument for number of NN layers and number of neurons per layer
no_layers = int(sys.argv[1])
nodes_per_layer = []
for layer in range(no_layers):
nodes_per_layer += [ ... |
def train_input_fn():
return _input(args.epochs, args.batch_size, args.train, 'train')
def eval_input_fn():
return _input(args.epochs, args.batch_size, args.eval, 'eval')
def validation_input_fn():
return _input(args.epochs, args.batch_size, args.validation, 'validation')
def keras_model_fn(learning_rate, w... | The main task of the code is to train and evaluate a Keras model using specified datasets and hyperparameters. It loads training, evaluation, and validation data, configures a model with learning rate, optimizer, and regularization settings, trains the model with epoch-based steps, validates during training, evaluates ... | def main(args):
logging.info("getting data")
train_dataset = train_input_fn()
eval_dataset = eval_input_fn()
validation_dataset = validation_input_fn()
logging.info("configuring model")
model = keras_model_fn(args.learning_rate, args.weight_decay, args.optimizer, args.momentum)
callbacks = ... |
def itsDsId(self, idx):
return self.Data[idx, 0].astype(int)
def itsNbrVehsId(self, idx):
dsId = self.itsDsId(idx)
planVehId = self.itsPlanVehId(idx)
targVehsId = self.itsTargVehsId(idx)
t = self.itsTime(idx)
nbrVehsId = np.array([], dtype=np.int64)
for target in ... | The main task of the code is to retrieve historical trajectory data of neighboring vehicles up to the current time `t` for a given index. It identifies the dataset and neighbor vehicle IDs, locates the time index in their tracks, and extracts historical positions (x, y) from the track data using specified time and spat... | def absNbrsTraj(self, idx):
dsId = self.itsDsId(idx)
nbrVehs = self.itsNbrVehsId(idx)
t = self.itsTime(idx)
nbrHisList, nbrFutList = [], []
for nbrVeh in nbrVehs:
colIndex = np.where(self.Tracks[dsId - 1][nbrVeh - 1][0, :] == t)[0][0]
vehTrack = self.Track... |
def absPlanTraj(self, idx):
dsId = self.itsDsId(idx)
planVeh = self.itsPlanVehId(idx)
t = self.itsTime(idx)
colIndex = np.where(self.Tracks[dsId - 1][planVeh - 1][0, :] == t)[0][0]
vehTrack = self.Tracks[dsId - 1][planVeh - 1].transpose()
planHis = vehTrack[np.maximum(0, ... | The function `itsAllGroundTruthTrajs` retrieves and returns a list of three trajectory-related data arrays for a given index `idx`: absolute planned trajectory (`absPlanTraj`), absolute target trajectory (`absTargsTraj`), and absolute neighbor trajectory (`absNbrsTraj`). This consolidates ground truth trajectory inform... | def itsAllGroundTruthTrajs(self, idx):
return [self.absPlanTraj(idx), self.absTargsTraj(idx), self.absNbrsTraj(idx)] |
def irt(data, val_data, lr, iterations):
""" Train IRT model.
You may optionally replace the function arguments to receive a matrix.
:param data: A dictionary {user_id: list, question_id: list,
is_correct: list}
:param val_data: A dictionary {user_id: list, question_id: list,
is_correct: list}... | The main task is to implement and evaluate an Item Response Theory (IRT) model by tuning learning rate and iterations. The code loads training/validation/test data, trains the IRT model, computes log-likelihoods for training/validation sets, evaluates accuracy on validation/test sets, and visualizes log-likelihood tren... | def main():
train_data = load_train_csv("../data")
# You may optionally use the sparse matrix.
sparse_matrix = load_train_sparse("../data")
val_data = load_valid_csv("../data")
test_data = load_public_test_csv("../data")
#####################################################################
... |
def await_data(self, n: int = 1, unwrap=True, is_json=False):
"""
Waits for n data pieces and returns them.
Parameters
----------
n : int, default=1
number of data pieces to wait for
unwrap : bool, default=True
if True, will return the first eleme... | The function aggregates data from multiple participants based on the specified operation. If `use_smpc` is True, it directly returns pre-aggregated SMPC data. Otherwise, it gathers raw data from all participants and applies the given aggregation operation to compute the result. | def aggregate_data(self, operation: SMPCOperation, use_smpc=False):
"""
Waits for all participants (including the coordinator instance) to send data and returns the aggregated value.
Parameters
----------
operation : SMPCOperation
specifies the aggregation type
... |
def get_distance(coords_1, coords_2): # (lat, long)
distance = geopy.distance.distance(coords_1, coords_2).m
return round(distance, 3)
def initialized(vehicle, x = NAME):
obj = Initial.objects.filter(vehicle=vehicle, intersection=x)
exist = obj.exists()
if exist:
return obj[0].init
ret... | The code processes vehicle data by validating coordinates against a range, checking initialization status, extracting path and action data, and updating or deleting related database records, returning success or failure responses based on conditions. | def post(self, request, *args, **kwargs):
serializer = self.get_serializer(request.data)
vehicle = serializer.data['vehicle']
point = (float(serializer.data['latitude']), float(serializer.data['longitude']))
detect = get_distance(point , REF)
if detect > DETECT_RANGE:
... |
def update_fitnesses_and_novelty(self):
if self.show_output:
pbar = trange(len(self.population))
else:
pbar = range(len(self.population))
# fits = self.fitness_function(torch.stack([g.get_image() for g in self.population]), self.target).detach() # TODO maybe don't detach... | This code evolves a population of individuals over multiple generations to optimize a solution. It initializes a population, updates fitness and novelty metrics, sorts individuals by fitness, and iterates through generations using a progress bar. The best individual is tracked, and the process continues until completio... | def evolve(self, run_number = 1, show_output=False, initial_population=True):
self.start_time = time.time()
self.run_number = run_number
self.show_output = show_output or self.debug_output
if initial_population:
for i in range(self.config.population_size):
se... |
def get_input(self):
"""Getting Input from terminal
Convert into list
returns list of input
"""
# print("Input Sudoku Problem:")
self.matrix = []
for _ in range(9):
self.matrix.append([int(num) for num in input().split(" ")])
def solver(self):
... | The code's main task is to initialize an object by reading input data into a matrix, solving a problem using the matrix data, and printing the result. The `__init__` method sequentially calls `get_input()` to populate the matrix, `solver()` to process the data, and `print_result()` to display the outcome. This structur... | def __init__(self):
self.matrix = []
self.get_input()
self.solver()
self.print_result() |
def check_collisions(self):
self.check_food_collision()
self.check_colony_collision()
def check_vision(self):
# Update pheromone sprite position
self.vision_sprite.rect.center = self.position
food_collisions = pygame.sprite.spritecollide(self.vision_sprite, self.food_group, Fals... | The main task of the code is to update an object's state by checking for collisions, assessing environmental visibility, adjusting orientation toward a destination, and executing movement. This sequence enables navigation or interaction within a simulated environment by prioritizing collision avoidance, visual awarenes... | def update(self):
self.check_collisions()
self.check_vision()
self.turn_to_destination()
self.move() |
def test_answer():
assert answer(1) == 0
assert answer(10) == 1
# simple ranges
# calculated by hand + inspection
for i in range(2, 4):
assert answer(i) == 0
for i in range(4, 6):
assert answer(i) == 1
assert answer(6) == 0
for i in range(7, 12):
assert answer(i) == 1
assert answer(12) == 2
for i in ra... | The code defines a function `test()` that sequentially invokes four test functions: `test_answer()`, `test_max()`, `test_min()`, and `test_gen_fib()`. Its primary purpose is to execute these test cases, likely validating functionalities such as answering logic, maximum/minimum calculations, and Fibonacci sequence gener... | def test():
test_answer()
test_max()
test_min()
test_gen_fib() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.