dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def solve_vigenere(text, key_min_size=1, key_max_size=12, a_is_zero=True):
best_keys = []
text_letters = [c for c in text.lower() if c in string.ascii_lowercase]
for key_length in range(key_min_size, key_max_size + 1):
# Try all possible key lengths
key = [None] * key_length
for ke... | The main task of the code is to decrypt a Vigenère cipher by testing potential keys in reverse order. It verifies each decryption by re-encrypting the result and checking for meaningful English words. If valid, it prints the key and decrypted text; otherwise, it indicates no solution was found. | def main():
ciphertext = input("Enter the ciphertext to decrypt: ").strip()
for key in reversed(solve_vigenere(ciphertext)):
decrypted_text = vigenere_decrypt(ciphertext, key)
if ciphertext == vigenere(decrypted_text, key) and contains_meaningful_words(decrypted_text):
print("")
... |
def retrieveOutput(listIn):
clr = []
if isinstance(listIn, dict):
if 'type' in listIn:
t = listIn['type']
else:
t = [v for k, v in listIn.items()]
if 'colors' in listIn:
clr = listIn['colors']
else:
t = listIn
if not isinstance(clr, ... | The function processes XML data to extract features, maps them to colors based on predefined types, and compiles the results into a structured pandas DataFrame. It iterates through XML entries, categorizes features like 'chain' or 'domain', assigns colors using provided or random mappings, and aggregates data with offs... | def getFeaturesDataFrame(xmls, types, dess, offsetIn, showProgress):
out = []
proteins = retrieveOutput(xmls)
xmls = dataRetrieval.getProtein(proteins[0], showProgress)
typesSet = retrieveOutput(types)
dessSet = retrieveOutput(dess)
offsetSet = retrieveOutput(offsetIn)
chainClr = proteins[... |
def getTitle(_input):
title = _input.find_all('a')
title = title[1].get_text().strip()
return title
def getPrice(_input):
tmp = _input.find('div', {'class':'holder header'})
price = tmp.find('dd').get_text().strip()
return price
def getArea(_input):
area = _input.find_all('a')
area = are... | This function extracts specific data fields from input text and a URL, compiling them into a list. It retrieves title, price, area, county, ID, categories, product URL, last update date, update days, and comments, returning structured data for processing or storage. | def breakOutData(_input, url):
title = getTitle(_input)
price = getPrice(_input)
area = getArea(_input)
county = getCounty(_input)
id = getID(_input)
mainCat, subCat = getCats(url)
productURL = getProductURL(_input)
lastUpdate, lastUpdateDays = getLastUpdate(_input)
comments = getCom... |
def is_write_query(query):
# Check if the query is a write operation (INSERT, UPDATE, DELETE)
return re.match(r'\b(INSERT|UPDATE|DELETE)\b', query, re.IGNORECASE) is not None
def execute_direct_hit(query):
print("Direct Hit Implementation...")
# Forward the query to the master node
forward_to_node(... | The code routes SQL queries to appropriate MySQL nodes: write queries trigger direct execution, while read queries use a customized execution path. It determines the operation type via `is_write_query()` and delegates handling to `execute_direct_hit()` or `execute_customized()` accordingly. | def execute_query(query):
# Determine which MySQL node to send the query to based on the type of operation
if is_write_query(query):
execute_direct_hit(query)
else:
execute_customized(query) |
def center_window(window, width, height):
# Get the screen dimensions
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
# Calculate the window position to center it
x = (screen_width - width) // 2
y = (screen_height - height) // 2
# Set the window coordi... | The main task of the code is to create an "Edit Content Page" GUI window for selecting characters, editing story content, and generating images. It hides the previous window, displays character options with hover effects, allows text input, and includes a save button to process the selected character and story text. Th... | def edit_content_page(): # Add edit the page content window 5.1 // ADD STORY WINDOW
# Hide generate window when in edit content page
generate_window.withdraw()
# Globalize edit content page to destroy it later in generate save function
global addcharacter_screen
# Globalize Flag for main_char_se... |
def _printVimError(errorMsg: str) -> None:
errorMsgSub = errorMsg.replace("'", "''")
vim.command(f"echohl ErrorMsg | echo '{errorMsgSub}' | echohl None")
def _printVimWarning(warningMsg: str) -> None:
errorMsgSub = warningMsg.replace("'", "''")
vim.command(f"echohl WarningMsg | echo '{errorMsgSub}' | ec... | The function compares two directories by normalizing paths, retrieving Vim configurations, building a directory tree, rendering differences, setting up a Vim buffer with the result, and enabling navigation. It handles errors, excludes specified directories, and ensures proper display with icons and thread settings, sav... | def dirDiffTreeExecute(leftArg: str, rightArg: str) -> None:
# preparing
try:
left = normalizeDirectory(leftArg)
right = normalizeDirectory(rightArg)
except NotADirectoryError as ex:
_printVimError(str(ex))
return
if left == right:
_printVimWarning("both are the s... |
def _check_complete_lines(self):
completed_lines = np.where(self.grid.all(axis=1))[0]
if completed_lines.size != 0:
print('line_completed')
nr_lines = completed_lines.size
np.zeros((self.BOARD_HEIGHT, self.BOARD_WIDTH))
remaining_rows = np.delete(self.grid... | The main task of the code is to transition the game's current piece to the next piece, validate its position, update the score, and handle game-over scenarios if the new piece cannot be placed. It checks for completed lines, updates the game state, and redraws the score and next piece. | def get_piece(self):
self._check_complete_lines()
self.p = self.next_p
self.next_p = Piece(random.choice(list(SHAPES)))
if not self._valid_piece_position():
print(' GAME OVER ')
self._reset_game()
return None
self.score += 20 * (self.level + ... |
def _valid_piece_position(self, x=0, y=0):
px = self.p.coords[1] + x
py = self.p.coords[0] + y
out_of_bounds = False
if any(x >= 10 or x < 0 for x in px):
out_of_bounds = True
elif any(y >= 24 for y in py):
out_of_bounds = True
return not (out_of_... | This method moves a game piece to a specified position (x, y) if valid. If invalid but y > 0, it places the piece on the board and retrieves it. The task involves validating positions and handling piece movement logic within a game context. | def move_piece(self, x, y):
if self.p:
if self._valid_piece_position(x, y):
self.p.move(x, y)
elif y > 0:
self._piece_to_board()
self.get_piece() |
def _valid_piece_position(self, x=0, y=0):
px = self.p.coords[1] + x
py = self.p.coords[0] + y
out_of_bounds = False
if any(x >= 10 or x < 0 for x in px):
out_of_bounds = True
elif any(y >= 24 for y in py):
out_of_bounds = True
return not (out_of_... | The main task of the code is to quickly drop the current game piece to the lowest valid vertical position on the board, then finalize its placement by updating the board state and retrieving the piece. It calculates the maximum downward movement using a loop, moves the piece accordingly, and commits it to the board str... | def fast_drop_piece(self):
if self.p:
y = 1
while self._valid_piece_position(0, y):
y += 1
self.move_piece(0, y-1)
self._piece_to_board()
self.get_piece() |
def set_driver(self):
try:
driver_path = super().set_driver_path()
super().log_info(driver_path)
chrome_service = ChromeService(driver_path)
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("-... | The function automates retrieving weather data from a web page by capitalizing the city name, initializing a browser driver, navigating to a site, interacting with menu elements, clicking the weather tab, fetching location-specific data, and returning the result. It ensures proper browser handling and logs actions duri... | def get_weatherdata_from_web(self, city_name):
if not city_name[0].isupper():
city_name = city_name.capitalize()
else:
pass
driver_object = self.set_driver()
driver_object.maximize_window()
driver_object.get(super().get_json_data().get("web_url").get("site... |
def iRCT(self):
'''
New propensity score based matching and average treatment effect implemented from this code: https://matheusfacure.github.io/python-causality-handbook/11-Propensity-Score.html
'''
T = self.treatmentCol
Y = self.outcomeCol
X = self.df.columns.drop([T, ... | The function `calculateRelationVal` determines which calculation method to execute based on `self.functionNum` (values 2–7), invokes the corresponding method (e.g., `iRCT`, `IPTW`), measures execution time, and returns the computed value along with the elapsed time. | def calculateRelationVal(self):
finalVal = 0.0
if int(self.functionNum) == 2:
startTime = time.time()
finalVal = self.iRCT()
return finalVal, time.time() - startTime
elif int(self.functionNum) == 3:
startTime = time.time()
finalVal = s... |
def collaborator_exists(gitea_api: pygitea, owner: string, repo: string, username: string) -> bool:
collaborator_response: requests.Response = gitea_api.get("/repos/" + owner + "/" + repo + "/collaborators/" + username)
if collaborator_response.ok:
print_warning("Collaborator " + username + " does alrea... | The function imports GitLab project collaborators into Gitea by mapping GitLab access levels to Gitea permissions (read/write/admin), adding each collaborator via API if they don't already exist, and handling errors with status messages. It skips group members and sets default to 'read' for unsupported access levels. | def _import_project_repo_collaborators(gitea_api: pygitea, collaborators: [gitlab.v4.objects.ProjectMember], project: gitlab.v4.objects.Project):
for collaborator in collaborators:
if not collaborator_exists(gitea_api, name_clean(project.namespace['name']), name_clean(project.name), collaborator.us... |
def repo_exists(gitea_api: pygitea, owner: string, repo: string) -> bool:
repo_response: requests.Response = gitea_api.get("/repos/" + owner + "/" + repo)
if repo_response.ok:
print_warning("Project " + repo + " does already exist in Gitea, skipping!")
else:
print("Project " + repo + " not f... | The main task of the code is to import a GitLab project into Gitea by checking if the repository exists, preparing migration parameters (clone URL, visibility, description), fetching the owner (user/group), and triggering a Gitea API migration request. It truncates descriptions to 255 characters, uses SSH if admin cred... | def _import_project_repo(gitea_api: pygitea, project: gitlab.v4.objects.Project):
if not repo_exists(gitea_api, name_clean(project.namespace['name']), name_clean(project.name)):
clone_url = project.http_url_to_repo
if GITLAB_ADMIN_PASS == '' and GITLAB_ADMIN_USER == '':
clone_url = proje... |
def label_exists(gitea_api: pygitea, owner: string, repo: string, labelname: string) -> bool:
existing_labels = get_labels(gitea_api, owner, repo)
if existing_labels:
existing_label = next((item for item in existing_labels if item["name"] == labelname), None)
if existing_label is not None:
... | The main task of the code is to import GitLab project labels into Gitea by checking if each label exists in the target repository, and if not, creating it via the Gitea API with its name, color, and description. The function handles success/failure responses and avoids duplicates. | def _import_project_labels(gitea_api: pygitea, labels: [gitlab.v4.objects.ProjectLabel], owner: string, repo: string):
for label in labels:
if not label_exists(gitea_api, owner, repo, label.name):
import_response: requests.Response = gitea_api.post("/repos/" + owner + "/" + repo + "/labels", jso... |
def milestone_exists(gitea_api: pygitea, owner: string, repo: string, milestone: string) -> bool:
existing_milestones = get_milestones(gitea_api, owner, repo)
if existing_milestones:
existing_milestone = next((item for item in existing_milestones if item["title"] == milestone), None)
if existin... | The function imports GitLab project milestones into Gitea by creating new milestones if they don't exist, parsing due dates, and updating milestone states via API calls. It checks for existing milestones, posts new ones with metadata, and patches their state if creation succeeds. Errors during import/update are logged,... | def _import_project_milestones(gitea_api: pygitea, milestones: [gitlab.v4.objects.ProjectMilestone], owner: string, repo: string):
for milestone in milestones:
if not milestone_exists(gitea_api, owner, repo, milestone.title):
due_date = None
if milestone.due_date ... |
def get_milestones(gitea_api: pygitea, owner: string, repo: string) -> []:
existing_milestones = []
milestone_response: requests.Response = gitea_api.get("/repos/" + owner + "/" + repo + "/milestones")
if milestone_response.ok:
existing_milestones = milestone_response.json()
else:
print_... | The function imports GitLab project issues into Gitea by mapping issue details like assignees, milestones, labels, and due dates to Gitea's existing data. It checks if an issue exists in Gitea before creating it, using the GitLab API to fetch issue data and the Gitea API to post new issues with converted fields. It han... | def _import_project_issues(gitea_api: pygitea, issues: [gitlab.v4.objects.ProjectIssue], owner: string, repo: string):
# reload all existing milestones and labels, needed for assignment in issues
existing_milestones = get_milestones(gitea_api, owner, repo)
existing_labels = get_labels(gitea_api, owner, repo... |
def get_teams(gitea_api: pygitea, orgname: string) -> []:
existing_teams = []
team_response: requests.Response = gitea_api.get("/orgs/" + orgname + "/teams")
if team_response.ok:
existing_teams = team_response.json()
else:
print_error("Failed to load existing teams for organization " + o... | This function imports GitLab group members into a Gitea team by checking existing teams, adding members to the first found team, and handling errors. It verifies member existence before adding them via API, printing success/failure messages. If no teams exist, it logs an error. | def _import_group_members(gitea_api: pygitea, members: [gitlab.v4.objects.GroupMember], group: gitlab.v4.objects.Group):
# TODO: create teams based on gitlab permissions (access_level of group member)
existing_teams = get_teams(gitea_api, name_clean(group.name))
if existing_teams:
first_team = exist... |
def user_key_exists(gitea_api: pygitea, username: string, keyname: string) -> bool:
existing_keys = get_user_keys(gitea_api, username)
if existing_keys:
existing_key = next((item for item in existing_keys if item["title"] == keyname), None)
if existing_key is not None:
print_warning... | The function imports SSH public keys from a GitLab user into Gitea for a specified user. It checks if a key with the same title already exists in Gitea, and if not, sends the key via API to Gitea's user key endpoint. It prints success or error messages based on the API response, ensuring keys are only imported once per... | def _import_user_keys(gitea_api: pygitea, keys: [gitlab.v4.objects.UserKey], user: gitlab.v4.objects.User):
for key in keys:
if not user_key_exists(gitea_api, user.username, key.title):
import_response: requests.Response = gitea_api.post("/admin/users/" + user.username + "/keys", json={
... |
def view_files_and_its_contents():
"""Calls methods needed to view a directory and its content
"""
path = ui.directory_inquirer()
true_path = path_completer(path)
ui.show_tabulate(local.find_files_and_directories(true_path),"Contents")
def file_action(action:str):
"""Handles whether a file will ... | The function `local_mode` handles local operations by selecting actions via a UI. If the action is "View", it displays files and their contents. Otherwise, it determines whether to manipulate a "File" or "Directory" and delegates to respective functions (`file_action` or `directory_action`) based on user input, enablin... | def local_mode():
"""Handles local methods
"""
action = ui.local_action_selector()
if action == "View":
view_files_and_its_contents()
else:
choice = ui.file_manipulation_action(action)
match choice:
case "File":
file_action(action)
case... |
def git_view():
"""Handles git view methods
"""
choice = ui.git_mode_view()
match choice:
case "Remote repos":
display_all_repos()
case "Issues on repo":
display_issues_in_repo()
def git_create():
"""Handles git create methods
"""
choice = ui.git_mode_... | The main task of the code is to manage Git credential operations. It checks if credentials exist/are valid, creates them if missing, and provides a UI-driven interface for users to change/insert tokens, view credentials, create new ones (with a placeholder action), or delete credentials, delegating specific tasks to co... | def git_mode():
"""Handles git methods
"""
if(not remote.credentials_exist() or not remote.verify_credentials()):
remote.create_credentials()
else:
choice = ui.git_mode()
match choice:
case "Change/Insert Token":
remote.create_credentials()
... |
def parsing_all_tokens():
for line in input_source_lines:
parsing_token(line)
pass
def generate_literals():
literals = []
generate_target_position = []
control_section_num = 0
num_of_ltorg = 0
for i in range(0, len(source_tokens)):
token = source_tokens[i]
if token.o... | The main task of the code is to perform a first pass of processing tokens and symbols in a compiler/assembler. It parses tokens, generates literals, adds symbols to the symbol table, and outputs token details (label, operator, operands) followed by symbol table entries (symbol name, address, control section number) for... | def pass1():
parsing_all_tokens()
generate_literals()
add_all_symbols()
for token in source_tokens:
print('%7s %-7s ' % (token.label, token.operator), end='')
print(",".join(token.operands))
print('')
print('')
for symbol in symbol_table:
print('%8s %08X %d' % (sym... |
def get_address_of_symbol(str_symbol, control_section_number):
for symbol in symbol_table:
if symbol.is_same(str_symbol, control_section_number):
return int(symbol.address)
return -1
def calculate_object_code(token, location_counter, control_section_number):
if token.operator == 'BYTE':
... | The main task of the code is to generate object code records (H, D, R, T, L, M) for each control section during the second pass of an assembler. It processes tokens like START, CSECT, EXTDEF, EXTREF, and END to create header, external definition, and end records. For other instructions, it calculates object code, updat... | def pass2():
control_section_number = 0
location_counter = 0
print('')
print('')
for token in source_tokens:
if token.operator == 'START' or token.operator == 'CSECT':
if control_section_number >= 1:
object_codes[control_section_number].append(ObjectCode('E', 0,... |
def calc_dynamic_window(x, param):
# Dynamic window from robot specification
global state_v,goal
Vs = [param.min_speed, param.max_speed,
-param.max_yawrate, param.max_yawrate]
# Dynamic window from motion model
Vd = [x[3] - param.max_accel * param.dt,
x[3] + param.max_accel * para... | The main task of the code is to implement Dynamic Window Approach (DWA) control for a robot, calculating optimal velocity and angular commands based on the robot's current state, goal, and laser scan data. It computes a dynamic window of feasible velocities, generates a trajectory, publishes control commands (Twist mes... | def dwa_control(x, param, goal,laser,angles):
# DWA control
global state_v, pub
dw = calc_dynamic_window(x, param)
u, trajectory = calc_control_and_trajectory(x,dw, param, goal,laser,angles)
twist_msg = Twist()
twist_msg.linear.x = u[0]
twist_msg.angular.z = u[1]
pub.publish(twist_msg)
... |
def dwa_control(x, config, goal, ob):
"""
Dynamic Window Approach control
"""
u, trajectory = calc_control_and_trajectory(x, config, goal, ob)
return u, trajectory
def motion(x, u, dt):
"""
motion model
"""
x[2] += u[1] * dt
x[0] += u[0] * math.cos(x[2]) * dt
x[1] += u[0] *... | The code implements a path planning algorithm using the Dynamic Window Approach (DWA) for a mobile robot to navigate from an initial position to a goal while avoiding obstacles. It simulates the robot's motion, generates predicted trajectories, and visualizes real-time movement, obstacles, and the robot's orientation. ... | def main(gx=10.0, gy=10.0, robot_type=RobotType.circle):
print(__file__ + " start!!")
# initial state [x(m), y(m), yaw(rad), v(m/s), omega(rad/s)]
x = np.array([0.0, 0.0, -math.pi / 8.0, 0.0, 0.0])
# goal position [x(m), y(m)]
goal = np.array([gx, gy])
# obstacles [x(m) y(m), ....]
ob = np.a... |
def ret_dict_awards(row):
id=row['book_id']
book_id=[]
award_str=[]
awards=[]
award_year=[]
if isinstance(row.awards,str):
award_list=row.awards.split(",")
for award in award_list:
book_id.append(int(id))
award_str.append(award)
awardyr=re.find... | The code processes a book dataset by cleaning and transforming columns like 'avg_rating' and 'no_ratings', extracting awards information via custom functions, and aggregating award counts by year. It returns the cleaned DataFrame and a grouped DataFrame showing the number of awards per year. | def process_data(DATA_FILE):
df=pd.read_csv(DATA_FILE)
print("dataset contains %d rows nad %d columns" % (df.shape))
df=df.rename(columns={'Unnamed: 0':'book_id'})
df['avg_rating']=df.avg_rating.apply(lambda x: round(float(x.replace("['","").replace("']","")),2))
df['no_ratings']=df.no_ratings.apply... |
def game_start_info():
rows = 13
columns = 6
rows_list = None
return new_game_mechanics.GameState(rows, columns, rows_list)
def display_game_window(self, size: (int, int)):
pygame.display.set_mode(size, pygame.RESIZABLE)
def get_key(self):
keys = pygame.key.get_pressed()
pressed_keys = []
if key... | The code initializes a Pygame game loop, managing game state, input handling, and rendering. It updates the game window at a fixed frame rate, processes key inputs, updates falling objects, checks for game over conditions, and redraws the screen periodically. The loop runs until the game ends, ensuring smooth gameplay ... | def run(self):
pygame.init()
self.game_state = game_start_info()
try:
clock = pygame.time.Clock()
time_a = time.time()
self.display_game_window((init_width, init_height))
last_input = []
while self.running:
clock.tick(_frame_rate)
time_b = time.time()
temp_key = self.get_key()
if le... |
def _disable_pwm(ch_info):
with open(_pwm_enable_path(ch_info), 'w') as f:
f.write("0")
def _unexport_pwm(ch_info):
with open(_pwm_unexport_path(ch_info), 'w') as f:
f.write(str(ch_info.pwm_id))
def _unexport_gpio(gpio):
if not os.path.exists(_SYSFS_ROOT + "/gpio%i" % gpio):
return
... | The function `_cleanup_one` deallocates resources associated with a channel (ch_info). If the channel uses HARD_PWM, it disables and unexports the PWM; otherwise, it cleans the GPIO event and unexports the GPIO. Finally, it removes the channel's configuration from the `_channel_configuration` dictionary. | def _cleanup_one(ch_info):
app_cfg = _channel_configuration[ch_info.channel]
if app_cfg == HARD_PWM:
_disable_pwm(ch_info)
_unexport_pwm(ch_info)
else:
event.event_cleanup(ch_info.gpio)
_unexport_gpio(ch_info.gpio)
del _channel_configuration[ch_info.channel] |
def _disable_pwm(ch_info):
with open(_pwm_enable_path(ch_info), 'w') as f:
f.write("0")
def _set_pwm_period(ch_info, period_ns):
with open(_pwm_period_path(ch_info), 'w') as f:
f.write(str(period_ns))
def _set_pwm_duty_cycle(ch_info, duty_cycle_ns):
with open(_pwm_duty_cycle_path(ch_info), '... | This function reconfigures PWM settings by validating the duty cycle, updating frequency and period, adjusting duty cycle duration, and restarting PWM if required. It disables PWM if already active, applies new parameters, then re-enables it, ensuring correct signal generation with specified frequency and duty cycle. | def _reconfigure(self, frequency_hz, duty_cycle_percent, start=False):
if duty_cycle_percent < 0.0 or duty_cycle_percent > 100.0:
raise ValueError("")
restart = start or self._started
if self._started:
self._started = False
_disable_pwm(self._ch_info)
... |
def _cleanup_all():
global _gpio_mode
for channel in list(_channel_configuration.keys()):
ch_info = _channel_to_info(channel)
_cleanup_one(ch_info)
_gpio_mode = None
def _channels_to_infos(channels, need_gpio=False, need_pwm=False):
_validate_mode_set()
return [_channel_to_info_loo... | The function `cleanup` releases GPIO resources for specified or all channels. If no channel is provided, it cleans all configured channels. If a specific channel is given, it cleans that one. It checks if GPIO is initialized and warns if not, using helper functions for actual cleanup. | def cleanup(channel=None):
# warn if no channel is setup
if _gpio_mode is None:
if _gpio_warnings:
warnings.warn("No channels have been set up yet - nothing to "
"clean up! Try cleaning up at the end of your "
"program instead!", RuntimeWar... |
def _channel_to_info(channel, need_gpio=False, need_pwm=False):
_validate_mode_set()
return _channel_to_info_lookup(channel, need_gpio, need_pwm)
def _app_channel_configuration(ch_info):
"""Return the current configuration of a channel as requested by this
module in this process. Any of IN, OUT, or None... | This code initializes a hardware PWM channel on a Raspberry Pi GPIO pin. It validates the channel's current configuration, cleans up conflicting GPIO settings, checks for external usage conflicts, exports the PWM channel, and sets initial frequency/duty cycle parameters while marking the channel as HARD_PWM for exclusi... | def __init__(self, channel, frequency_hz):
self._ch_info = _channel_to_info(channel, need_pwm=True)
app_cfg = _app_channel_configuration(self._ch_info)
if app_cfg == HARD_PWM:
raise ValueError("Can't create duplicate PWM objects")
# Apps typically set up channels as GPIO bef... |
def gather_transactions(chain: Blockchain) -> tuple[dict, int]:
done = False
count = 0
transactions = []
while not done:
if count == 0:
mode = input(f"Do you wish to create a transaction for block {chain.chain_length()}? (y/n): ")
else:
mode = input(f"Do you wish ... | This code repeatedly creates blockchain blocks by gathering transactions, generating new blocks, and allowing user input to continue or stop. It displays progress, clears the screen after each block, and outputs the final blockchain as JSON when stopped. | def run(chain: Blockchain) -> None:
run = True
while run:
print(f"Currently creating block with height {chain.chain_length()}")
transactions, count = gather_transactions(chain)
print("Creating block and appending to chain...")
create_block(transactions, chain)
clear_scree... |
def parse_arguments():
parser = argparse.ArgumentParser(
description='''Parse a JS file for occurences of data-cy and generate selectors and actions functions.
'''
)
parser.add_argument("input", help="Input file to parse")
args = parser.parse_args()
return args.input
def parse_file(f... | The main task of the code is to parse input arguments and a file, extract selectors and parameters, generate ID/constant definitions and action mappings, then display these generated outputs for automation or code generation purposes. | def main():
input = parse_arguments()
file_content = parse_file(input)
selectors = get_selectors_from_file(file_content)
extract_parameters_from_selectors(selectors)
generate_ids_constants(selectors)
generate_actions(selectors)
display_ids_constants(selectors)
display_actions(selectors)... |
def get_data(data_file,label_file):
"""
Gets data based off of the specified data and label file
Parameters:
data_file: CSV file that has data lines
label_file: CSV file that has label lines
Return:
data: list of all the data lines
label: list of all the label lines
... | The main task of the code is to train and evaluate an NLP model (NLPNet) on a classification task. It loads and shuffles training, validation, and test datasets, initializes the model with specified hyperparameters, and trains it using Adam optimizer and BCE loss. The code tracks training/validation accuracy/loss acros... | def main():
train_data,train_label = get_data(TRAIN_DATA,TRAIN_LABEL)
test_data,test_label = get_data(TEST_DATA,TEST_LABEL)
val_data,val_label = get_data(VAL_DATA,VAL_LABEL)
train_data,train_label = shuffle(np.array(train_data),np.array(train_label))
test_data,test_label = shuffle(np.array(test_dat... |
def get_line_lengths_train():
"""
Gets the line lengths from the training data
Returns:
list of lengths for each line
"""
elements = get_data_train()
line_lengths = []
for element in elements:
line = element[0]
split_line = line.split(" ")
line_lengths.ap... | The main task of the code is to analyze and report statistical summaries of review lengths (average, max, min word counts) for both training and test datasets, then generate visualizations using `plot_train()` and `plot_test()` to illustrate the data distributions. | def main():
line_lengths = get_line_lengths_train()
print("TRAIN: Average number of words for a review: " +
str(np.mean(line_lengths)))
print("TRAIN: Max Number: " + str(np.amax(line_lengths)))
print("TRAIN: Min Number: " + str(np.amin(line_lengths)))
line_lengths = get_line_lengths_... |
def parrotfy(self, rendered_str):
result = ""
code = random.randrange(3, 16) * 16
if self.party_parrot:
result += u"\u001b[38;5;{0}m".format(code)
result += rendered_str
if self.party_parrot:
result += u"\u001b[38;5;"
return result
def __minimi... | The main task of the code is to render a frame into text using a template, incorporating padding, terminal size, and calculated lines. It optionally prepends a prefix to overwrite previous output if enabled, stores the rendered frame for future reference, and returns the combined result. | def render_frame(self, frame, enable_overwrite=True):
"""
Renders a frame to text. Leaves the value output set in class variable
`previous_frame`. This will allow the next render to overwrite the previous output
appropriately.
"""
rendered_frame = self.parrotfy(
... |
def suggest_coord(self, word):
count = 0
coordlist = []
glc = -1
for given_letter in word.word: # cycle through letters in word
glc += 1
rowc = 0
for row in self.grid: # cycle through rows
rowc += 1
colc = 0
... | This function attempts to fit a given word into a grid, either as the initial seed word (with randomized placement) or subsequent words using precomputed coordinates. It checks if the word fits based on a score, placing it if valid. For the first word, it randomly selects a position and direction, while later words use... | def fit_and_add(self, word): # doesn't really check fit except for the first word; otherwise just adds if score is good
fit = False
count = 0
coordlist = self.suggest_coord(word)
while not fit and count < self.maxloops:
if len(self.current_word_list) == 0: # this is the f... |
def hat(func, omega, a, b):
real = integrate.quad(lambda x : (func(x)*e**(-2*pi*1j*x*omega)).real, a, b, limit = 300)[0]
imag = integrate.quad(lambda x : (func(x)*e**(-2*pi*1j*x*omega)).imag, a, b, limit = 300)[0]
return real + imag*1j
def e_2(wavelet_info):
t0 = wavelet_info[2]
t1 = wavelet_in... | The function `calc_uncertainty` computes uncertainty metrics for a wavelet by evaluating integrals involving the wavelet's parameters. It calculates a scaling factor `Cf` using numerical integration, conditional on `t0`'s sign, and combines it with other precomputed values like `e_1`, `e_2`, and `Sigma1/Sigma2`. The re... | def calc_uncertainty(wavelet_info):
t0 = wavelet_info[2]
t1 = wavelet_info[3]
Cf = 0
if t0 < 0:
Cf = Cf = integrate.quad(lambda w : abs(hat(wavelet_info[0], w, t0, -0.0001))**2/abs(w), 0, wavelet_info[5], limit=300)[0] + integrate.quad(lambda w : abs(hat(wavelet_info[0], w, 0.0001, t1)... |
def _validate_date(dt):
LOG.debug('_validate_date(dt) called')
today = datetime.today().date()
begin = datetime(1995, 6, 16).date() # first APOD image date
# validate input
if (dt > today) or (dt < begin):
today_str = today.strftime('%b %d, %Y')
begin_str = begin.strftime('%b %d, %... | This function retrieves and formats Astronomy Picture of the Day (APOD) data for a specified date. It handles default date fallback, validates input dates, and returns structured JSON with service version metadata. If no data exists for the date, it returns a 404 error. | def _get_json_for_date(input_date, use_concept_tags, thumbs):
"""
This returns the JSON data for a specific date, which must be a string of the form YYYY-MM-DD. If date is None,
then it defaults to the current date.
:param input_date:
:param use_concept_tags:
:return:
"""
# get the date... |
def _validate(data):
LOG.debug('_validate(data) called')
for key in data:
if key not in ALLOWED_APOD_FIELDS:
return False
return True
def _abort(code, msg, usage=True):
if usage:
msg += " " + _usage() + "'"
response = jsonify(service_version=SERVICE_VERSION, msg=msg, cod... | The main task of the code is to handle API requests for astronomical data by validating input parameters, authenticating with an API key, and returning formatted JSON responses based on date ranges, random dates, or specific dates, while managing errors and edge cases with appropriate HTTP status codes and content type... | def apod():
LOG.info('apod path called')
try:
# application/json GET method
args = request.args
if not _validate(args):
return _abort(400, 'Bad Request: incorrect field passed.')
#
input_date = args.get('date')
count = args.get('count')
star... |
def ChangeHasSeen(self):
'''
Set has_seen to false if it is already true. If true then it means that
the birthday of the respective name has already been showed.
'''
from_file = self.ReadJSON()
curr_time = time.strftime('%m-%d')
for _, value in from_file.items()... | The main task of the code is to continuously check for today's birthdays, retrieve their details, and display each birthday entry in a window with the person's ID, name, date, and image. The infinite loop ensures real-time updates, while the `Window` method likely handles the UI presentation of each birthday event. | def main(self):
'''
Entry of the program
'''
while True:
self.ChangeHasSeen()
birth_dates = self.GetTodayBirthdaysDetails()
for _id, name, date, image in birth_dates:
self.Window(_id, name, date, image) |
def checkReqIdAdded(req_id:str) -> bool:
''' Check the number is already added or not '''
ref, app = getConnection()
bill_ref = ref.child('BILL')
all_val = bill_ref.order_by_key().get()
all_val_ = dict(all_val)
endConnection(app)
check = [v for key, v in all_val_.items() if v['refID'] == req_id]
if check:
re... | The main task of the code is to update a bill's transaction details in a database. It validates the reference ID, checks for amount consistency, updates the database with the new amount, and updates the transaction record. If all steps succeed, it returns a success status with the transaction ID; otherwise, it returns ... | def updateBill(data:dict) -> dict:
is_reqid_added = checkReqIdAdded(data['refID'])
if is_reqid_added:
check_amount = checkAmount(data['transaction']['amountPaid'], data['refID'])
if check_amount:
update_amount = updateAmount(data['refID'], data['transaction']['amountPaid'])
update_data = updateDb(data['refI... |
def _update_relation_data(self):
"""Update the relation data with the current state of the unit."""
# save local user list in the peer relation data
source_unix_group = self.model.config["source-unix-group"]
current_linux_users = get_linux_group_users(source_unix_group)
self._set... | The code handles configuration changes by updating relation data, setting up cron jobs, and assessing the charm's status. It includes a placeholder for future config validation. | def _on_config_changed(self, event: ops.charm.ConfigChangedEvent):
# FIXME: validate config
self._update_relation_data()
self._setup_cron()
self._assess_status() |
def create_dirs(target, user):
"""Create parent directories at the target location, if necessary."""
target_dir = os.path.dirname(target)
first_existing_dir = target_dir
while not os.path.isdir(first_existing_dir):
first_existing_dir = os.path.split(first_existing_dir)[0]
# only create direc... | This function synchronizes files from a source to a destination using rsync, creates necessary directories at the destination, and sets appropriate ownership for the destination files or directories based on the provided user. | def sync_path(source, destination, user):
"""Sync files from source to destination."""
create_dirs(destination, user)
cmd = ["rsync", "-avz", source, destination]
subprocess.check_call(cmd)
if os.path.isdir(destination):
recursive_chown(destination, user)
else:
shutil.chown(desti... |
def prime_gen(bits, factor=0):
"""Prime number generator with option of adding list of unwanted values
takes integer bits determining the bitsize of the prime to be generated and optional list of unwanted values to avoid
returns a likely prime integer
"""
s = s_generator(bits)
p = random.randra... | The function `rsa_key_gen` generates RSA public and private keys. It creates primes `p` and `q` (or reuses provided ones), computes modulus `n` and Euler's totient `phi_n`, then selects a public exponent `e` coprime to `phi_n` while avoiding values in `prev_exp`. It calculates the private exponent `d` as the modular in... | def rsa_key_gen(bits, prev_exp=[], p=0, q=0, n=0, phi_n=0):
"""RSA setup function
takes in integer bits determining the bitsize of the encryption session and optional list for values to avoid
and integers p, q, n, phi_n for already calculated setup if wanting to reuse with different exponents
returns pu... |
def waitFor(self,waitingByte):
status = COM_ERROR
#Wait for Ack or 'C' */
if (self.canbus.receive(self.a_rx_ctrl, 1) == COM_OK):
if (self.a_rx_ctrl[0] == waitingByte):
# if(waitingByte==ACK):
# print("[INFO]get ACK")
status = COM_OK
elif (self.a_rx_ctrl[0] == CA):
... | This code implements a CAN-based firmware flashing utility. It reads a file, configures the CAN ID, sends a flash request, transmits initialization and data packets with error handling, and concludes with an end-of-transmission signal. The process involves waiting for ACK/CRC16 responses, retrying on failures, and mana... | def Flash(self,targetCANID,filePath):
p_file_name=os.path.basename(filePath)
p_file_content = open(filePath, 'rb').read()
file_size=len(p_file_content)
#set Tx ID to P2P ID,
id=self.CAN_ID_P2P_MASK | targetCANID
self.canbus.setCANID(self.CAN_ID_P2P_MASK | targetCANID)
print("[INFO]Set CAN ... |
def _adj(w):
"""Convert doubled variables ([2 d^2] array) back to original variables ([d, d] matrix)."""
return reconstruct_W(w, schema=data_schema())
def _loss(W):
"""Evaluate value and gradient of loss."""
# M = X @ W
M = torch.matmul(X, W)
# M = torch.matmul(X, W * mas... | The function evaluates the augmented Lagrangian objective for doubled variables by combining a loss term, quadratic and linear terms in constraint violation `h`, and an L1 regularization penalty on the variables, returning the computed objective value. | def _func(w):
"""Evaluate value and gradient of augmented Lagrangian for doubled variables ([2 d^2] array)."""
W = _adj(w)
# loss, G_loss = _loss(W)
loss = _loss(W)
# h, G_h = _h(W)
h = _h(W)
obj = loss + 0.5 * rho * h * h + alpha * h + lambda1 * torch.abs(w).sum(... |
def _adj(w):
"""Convert doubled variables ([2 d^2] array) back to original variables ([d, d] matrix)."""
return reconstruct_W(w, schema=data_schema())
def _loss(W):
"""Evaluate value and gradient of loss."""
# M = X @ W
M = torch.matmul(X, W)
# M = torch.matmul(X, W * mas... | The main task of the code is to compute the augmented Lagrangian objective function for doubled variables by combining a loss term, quadratic and linear penalty terms for constraints, and an L1 regularization term. It constructs the objective value `obj` using `_loss(W)`, `_h(W)`, and regularization parameters `rho`, `... | def _func(w):
"""Evaluate value and gradient of augmented Lagrangian for doubled variables ([2 d^2] array)."""
W = _adj(w)
# loss, G_loss = _loss(W)
loss = _loss(W)
# h, G_h = _h(W)
h = _h(W)
obj = loss + 0.5 * rho * h * h + alpha * h + lambda1 * torch.abs(w).sum(... |
def make_contact(contact):
fn = contact.get("fn", "")
email = contact.get("hasEmail", "")
return [fn, email]
def publish(self, ds, publisher):
path = tuple(reversed(self.publisher_path(publisher)))
self.by_publisher[path].append(ds)
def msg(self, *s, **kwargs):
indent = kwargs.get("i... | The code analyzes a dataset by counting attributes like license, program code, bureau code, access level, and keywords. It categorizes datasets by identifier/title, checks landing page links if enabled, logs metadata, and publishes the dataset. It also tracks contact details and uses `analyze_distributions` for further... | def analyze_dataset(self, ds, label):
title = ds["title"]
identifier = ds.get("identifier", "NONE")
license = ds.get("license", "NONE")
self.license_counts[license] += 1
program = ds.get("programCode", ["NONE"])
self.program_counts[tuple(program)] += 1
bureau = ds... |
def msg(self, *s, **kwargs):
indent = kwargs.get("indent", 0)
self.messages.append((" " * indent) + " ".join(str(s0) for s0 in s))
def nl(self):
self.messages.append("")
def analyze_dataset(self, ds, label):
title = ds["title"]
identifier = ds.get("identifier", "NONE")
l... | The code analyzes a data.json object by counting datasets and distributions, checking for enhanced metadata (sources/collections) from scraped data, and logging results with a progress bar for dataset analysis. | def analyze(self, dj):
"""Analyze a data.json object"""
datasets = dj["dataset"]
n_datasets = len(datasets)
n_distributions = sum(len(ds.get("distribution", [])) for ds in datasets)
# check for "ED CKAN" scraped metadata additions
self.msg("Analysis of", dj.get("@id", "... |
def read_in_tissue_splice_data(tissue_file):
dic ={}
df= pd.read_csv(tissue_file, sep="\t", header=0)
for entry in df.itertuples():
gene = entry[1]
sites=np.array(eval(entry[3]))
reads=np.array(eval(entry[4]))
#if theres actually data for this gene in GTEx
if(len(site... | The code processes each tissue file in the specified directory by reading splicing data, generating gene labels, and writing them to files. It skips hidden files, extracts tissue names, and applies functions to process and save labeled data for each tissue. | def run():
#for every tissue file in the directory, execute this script
input_dir="./output/ss_reads_by_tissue/"
for entry in os.listdir(input_dir):
#trying to ignore hidden files
if(entry[0]!="."):
tissue = entry[:-4]
tissue_splicing_data = read_in_tissue_splice_data... |
def read_in_genes_to_consider():
df = pd.read_csv('../output/100k_gene_ss_info.txt', sep = "\t",usecols=[0,3])
return df.set_index('Gene ID')['Strand'].to_dict()
def read_in_sample_attributes():
print("Reading in GTEx sample annotations")
sampID_df = pd.read_csv(sample_annotation_file, sep="\t",usecols=... | The code processes biological data by reading gene and sample information, counting tissue-specific samples, parsing junction reads, and generating output files for junction positions and statistics. It initializes global variables, processes gene strands, creates augmented headers, and writes parsed data to files. The... | def run():
global samples_header
global counts_per_tissue
gene_strand_dict= read_in_genes_to_consider()
genes=list(gene_strand_dict.keys())
sampID_dict=read_in_sample_attributes()
counts_per_tissue=count_samples_per_tissue(sampID_dict)
samples_header=create_augmented_header(sampID_dict)
... |
def _evaluate(self):
if self.metric == 'auc':
self._predict()
self._evaluate_auc()
elif self.metric == 'acc':
self._predict(use_threshold=True)
self._evaluate_acc()
elif self.metric == 'loss':
self._evaluate_loss()
else:
... | This code initializes a distributed learning model by setting parameters (n, epsilon, l, dim, lamb), loading training/test data, partitioning data across nodes, copying initial network states, and preparing evaluation metrics. It sets up structures for tracking training/test predictions, iteration counts, and initializ... | def __init__(self, n, epsilon, l, dim, lamb, train_data, test_data,
init_network_state, step_size_scale, eval_period,
metric):
self.n = n
self.epsilon = epsilon
self.l = l
self.dim = dim
self.lamb = lamb
self.train_data = train_data ... |
def _iterate(self):
pass
def _evaluate(self):
if self.metric == 'auc':
self._predict()
self._evaluate_auc()
elif self.metric == 'acc':
self._predict(use_threshold=True)
self._evaluate_acc()
elif self.metric == 'loss':
self._eval... | The code runs a loop for a specified number of iterations (`self.l`), performing an iteration step (`_iterate`), incrementing the iteration counter, and printing progress. Every `eval_period` iterations, it evaluates performance (`_evaluate`). Finally, it saves collected metrics (`save_metric`). The main task is to exe... | def run(self):
while self.iteration < self.l:
self._iterate()
self.iteration += 1
print("{}'s {}-eps iter: {}".format(self.algorithm_name, self.epsilon, self.iteration))
if self.iteration % self.eval_period == 0:
self._evaluate()
# self._... |
def _compute_delta_sharp(self):
self.delta_sharp = (self.delta + np.exp(self.epsilon)) ** (1 / self.l) - np.exp(self.epsilon / self.l)
def _compute_stsigma(self):
"""
Compute S, T, sigma_gamma, for multi-gossip
:return:
"""
# S
self.s = (np.log(1 - np.power(self.p... | This code initializes the PPSC algorithm, a graph-based optimization method, by configuring parameters for training/test data, network structure (with predefined connected components), and hyperparameters like regularization (lambda), precision thresholds (delta, r_precision), and dynamic adjustment rules (mu, xi_m). I... | def __init__(self, train_data, test_data, n, epsilon, l, dim, lamb, init_network_state, step_size_scale,
eval_period, metric,
mu=1, delta=1e-6, p0=1e-3, xi_m=0.2, g_dagger=1, r_presicion=1e-1, lambda_a=2, p1=0.95, v=1e-1,
p2=0.95, q=3, n_max=4, r_dagger=0.5, lambda_pps... |
def set_env_variables(env, variables):
"""Set the given environment variables in `env` if not already set, merging special variables."""
for name, value in variables:
if name not in env:
env[name] = value
elif name in ("PATH", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"):
if s... | The main task of the code is to return an environment dictionary with OS-specific variables set by copying the current environment and applying platform-specific configurations using `set_env_variables` for Linux, macOS, or Windows, or raising an error for unsupported platforms. | def get_env():
"""Returns the environment with the variables set."""
env = os.environ.copy()
if sys.platform in ("linux", "linux2"):
# Linux
set_env_variables(env, get_linux_env())
elif sys.platform == "darwin":
# Mac
set_env_variables(env, get_mac_env())
elif sys.pla... |
def error(template, *args, **kwargs):
"""Print the error and exit the program."""
print(template.format(*args, **kwargs))
sys.exit(1)
def select_newest_file(paths):
"""Select a file that exists and has the newest modification timestamp."""
existing_paths = [
(os.path.getmtime(path), path)
... | (The main task of the code is to execute Prusti on specified Rust test files by parsing command-line arguments, locating the Prusti binary, resolving test file paths, collecting compile flags from comments, configuring environment variables for overflow checks, and running the tool with appropriate settings. It ensures... | def verify_test(args):
"""Runs prusti on the specified files."""
test = None
compile_flags = []
for arg in args:
if arg.startswith('-'):
compile_flags.append(arg)
else:
if test is None:
test = arg
else:
error("Expected a... |
def get_prusti_server_path_for_benchmark():
project_root_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
if sys.platform in ("linux", "linux2"):
return os.path.join(project_root_dir, 'target', 'release', 'prusti-server-driver')
else:
error("unsupported platform for benchmarks: {}",... | The code runs benchmarks on Rust files using the Prusti server, measuring execution times after warming up the server. It reads benchmark file paths from a CSV, executes each file multiple times, records timings in a JSON file with a timestamp, and ensures the Prusti server is properly terminated afterward. | def run_benchmarks(args):
"""Run the benchmarks and report the time in a json file"""
warmup_iterations = 6
bench_iterations = 10
warmup_path = "prusti-tests/tests/verify/pass/quick/fibonacci.rs"
prusti_server_exe = get_prusti_server_path_for_benchmark()
server_port = "12345"
output_dir = "b... |
def pause_stopwatch(self):
if self.stopwatch.running:
self.stopwatch.pause()
title = self.title_entry.get()
self.stopwatch.add_title(title)
self.display_titles()
self.update_time()
self.last_dialog_time = datetime.now()
self.... | The main task of the code is to restart a stopwatch by first pausing it, prompting user confirmation via a dialog, resetting the stopwatch's time, updating the display, redisplaying titles, and saving the updated state. This ensures controlled restarts with user validation and interface synchronization. | def restart_stopwatch(self):
self.pause_stopwatch()
response = messagebox.askyesno("Confirm Restart", "Are you sure you want to restart the stopwatch?")
if response:
self.stopwatch.reset()
self.update_time()
self.display_titles()
self.save_stopwatc... |
def load_stopwatch_state(self):
try:
state = read_stopwatch_state()
if state:
self.stopwatch.from_state(state)
except FileNotFoundError:
pass
def create_ui(self):
self.create_labels()
self.create_buttons()
self.create_textfield(... | The code initializes a stopwatch application by setting up the GUI window, creating a Stopwatch instance, loading saved state, building the user interface, handling window closure events, and initiating timer checks to resume functionality. | def __init__(self, window):
self.window = window
self.window.title("Stopwatch")
self.stopwatch = Stopwatch()
self.last_dialog_time = None
self.load_stopwatch_state() # Load stopwatch state when the app starts
self.create_ui()
self.display_titles()
self.... |
def _search(self) -> List[Dict[str, str]]:
""" Use alpha vantage search api and display the result
:return:
"""
keyword = input("Enter a keyword\n")
result = self.alpha_vantage.search(keyword=keyword, force_json=True)
if len(result) == 0:
print('No match found... | The code runs an interactive CLI application allowing users to search for companies, select a company, and perform financial analyses such as displaying details, historical prices, current quotes, and exponential moving averages. It loops until the user exits, providing a menu-driven interface for data retrieval and an... | def run(self):
""" Run the interactive cli applciation.
:return:
"""
while True:
# first, search companies
result = self._search()
print('{:*^40}'.format('Search Result'))
for i, entry in enumerate(result):
print('{:>2}.{:<2... |
def TSNE_DR(X_train, X_test = None, Y_train = None, **kwargs):
clf = sklearn.manifold.TSNE(**kwargs)
Z = clf.fit_transform(X_train)
return Z
def gen_W(X, Y):
np.random.seed(3334)
# Num of samples and dimensions
N = X.shape[0]
dim_X, dim_Y = X.shape[1], Y.shape[1]
# Parameters to control the ... | The main task of the code is to estimate mutual information (MI) between two datasets X and Y using a hashing-based approach with adjustable parameters for dimensionality reduction, smoothing, and ensemble estimation. It applies transformations (e.g., TSNE or p-stable hashing), computes MI across an epsilon range, and ... | def EDGE(X, Y, U = 10, gamma = [1, 1], epsilon = [0, 0], epsilon_vector = 'range', eps_range_factor = 0.1, normalize_epsilon = True,
ensemble_estimation = 'median', L_ensemble = 10, hashing = 'p-stable', stochastic = False):
# print('checkpoint 1, data transformed using TSNE')
gamma = np.array(gamma)
g... |
def _check_fleet_edges(self):
"""Reacting when alien reaches edge of the screen"""
for alien in self.aliens.sprites():
if alien._check_edges():
self.change_fleet_direction()
break
def _ship_hit(self):
"""Taking one life of the ship"""
if self.s... | This method updates alien movement by checking fleet edges, updates their positions, detects collisions with the player's ship to trigger a hit response, and checks if any aliens have reached the bottom of the screen to handle game-ending conditions. | def _update_aliens(self):
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom() |
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(ev... | The `run_game` method controls the main game loop, continuously checking for events, updating game elements (ship, bullets, aliens) if the game is active, and rendering the screen to maintain gameplay and user interaction until the game ends. | def run_game(self):
"""Run game"""
while True:
self._check_events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self.update_screen() |
def extractFromMoodle(fileName):
"""Check that the current directory contains no subdirectories.
Extract the zip file fileName into the subdirectory 'submissions'.
Check that the name of every file in 'submissions" is a valid moodle submission
(this should be always OK, unless something changed in Moodl... | The main task of the code is to process Moodle submissions by extracting files, creating result directories, handling individual submission files or directories, and checking for plagiarism based on specified options. It navigates submission entries, applies extraction or post-processing steps, and executes plagiarism ... | def homeworkCheckerMain(assignment, fileName, options):
"""Main function for a moodle file"""
if options["extractMoodle"]:
extractFromMoodle(fileName)
if options["extractStudent"] or options["afterExtract"]:
assignment.createResultFiles()
os.chdir("submissions")
for dirEntr... |
def getCommandLineArguments():
parser = argparse.ArgumentParser(description='Homework File Checker')
parser.add_argument('fileName', help='Submission File Name')
group=parser.add_mutually_exclusive_group()
group.add_argument('--extractMoodle', action="store_true", help='Extract individual submission fil... | The main task of the code is to parse a file name to extract course, homework, and student IDs, load course and assignment data, validate IDs, and determine whether to process a single student submission file or a Moodle file containing multiple submissions based on the presence of IDs. It handles errors and uses globa... | def main():
"""Parse the arguments. It should contain exactly one argument which is a file name.
Parse the file name and get the triple (courseId, hwName, ids).
Load the instructor, course and assignments data.
Check the course, assignment and student ids.
Check the file as a student file ot Moodle ... |
def removeOutputFiles(self):
for f in self.OutputFiles:
if os.path.isfile(f):
os.remove(f)
def _junitResults(self, fileName):
for line in reversed(fileContents(fileName)):
if line.strip() != "":
print(line)
if line.startswith("OK"):... | The `runTest` method executes a program with a specified input file, captures its standard output and error, and compares them against expected results. It logs test details, sets up symbolic links for input/output files, runs the program, checks if outputs match expected files, and determines test outcomes (tests, fai... | def runTest(self):
"""Test prog by supplying it inputFileName as input,
and checking whether the standardOutput and standard error match those supplied by the test."""
print("Running Test:", self.name)
tests_obj[self.name].log += "Running Test:" + self.name + "\n"
for li... |
def modify_dataframe(original_filename: str, updated_filename: str):
try:
dataframe = pd.read_csv(updated_filename)
print("Updated dataframe loaded from memory!")
except:
print("Updating dataframe!")
dataframe = pd.read_csv(original_filename, sep="|")
gloss = []
t... | The main task of the code is to evaluate a transformer-based model for sequence prediction using either a development or test dataset. It loads hyperparameters from a JSON file, prepares data with spaCy, constructs a vocabulary, initializes a pretrained or custom embedding matrix, builds a MultiContextTransformer model... | def main():
if len(sys.argv) != 2:
print("Pass JSON file of model as argument!")
sys.exit()
filename = sys.argv[1]
with open(filename, "rt") as fjson:
hyper_params = json.load(fjson)
if torch.cuda.is_available():
device = torch.device("cuda")
print("GPU")
el... |
def deal_community_cards(self):
if not self.hand_over():
main_logs = [('flop', (0, 3)), ('turn', (3, 4)), ('river', (4, 5))]
cards_down = len(self.community_cards)
cards_to_deal = 5 - cards_down if len(self.active_players()) < 2 else 3 if self.round == 0 else 1 if self.round ... | This function manages a betting round in a card game by dealing community cards, tracking bets, updating player statuses, adjusting balances based on bet differences, and preparing for the next player's turn. It handles showdown logic, resets betting parameters, and increments the round, potentially ending the round if... | def new_round(self):
self.deal_community_cards()
max_bet, max_better, bets = 0, None, []
show_all = len(self.live_players()) > 1 and len(self.active_players()) < 2
for player in self.players:
self.score(player)
player.moved = False
player.next_move = ... |
def round_over(self):
return all(player.moved for player in self.players)
def new_round(self):
self.deal_community_cards()
max_bet, max_better, bets = 0, None, []
show_all = len(self.live_players()) > 1 and len(self.active_players()) < 2
for player in self.players:
s... | The code's main task is to check if the current round has ended using `self.round_over()`, and if true, initiate a new round via `self.new_round()`. It also checks if the hand phase has concluded with `self.hand_over()`, and if so, distributes the pot using `self.distribute_pot()`. This ensures game progression by tran... | def handle_round_over(self):
if self.round_over():
self.new_round()
if self.hand_over():
self.distribute_pot() |
def current_player(self):
return self.players[self.turn]
def place_bet(self, player, amount):
player.bets[self.round] += amount
player.balance -= amount
self.pot += amount
def set_turn_next(self):
self.turn = self.get_active_ind(self.turn + 1)
def handle_round_over(self):
... | This method processes a player's 'call' or 'check' action in a game, updates their status, calculates and places a bet, logs the action, and advances the game state. | def check(self):
player = self.current_player()
player.moved = True
call_amount = min(player.balance, self.current_bet - player.bets[self.round])
self.place_bet(player, call_amount)
if call_amount > 0:
main_log = 'all_in' if player.balance == 0 else 'call'
... |
def current_player(self):
return self.players[self.turn]
def place_bet(self, player, amount):
player.bets[self.round] += amount
player.balance -= amount
self.pot += amount
def set_turn_next(self):
self.turn = self.get_active_ind(self.turn + 1)
def handle_round_over(self):
... | This function handles a player's betting action in a game, updating game state variables like current bet, min raise, and player status. It logs the bet as a raise, all-in, or blind, adjusts the player's balance, and progresses the game turn. The function ensures proper betting limits, tracks the last bettor, and check... | def bet(self, amount, blind = 0):
for p in self.players:
p.moved = False
player = self.current_player()
player.moved = blind == 0
amount = min(player.balance, amount)
self.last_better_id = player.id
self.min_raise = max(self.min_raise, amount - self.current_b... |
def current_player(self):
return self.players[self.turn]
def set_turn_next(self):
self.turn = self.get_active_ind(self.turn + 1)
def handle_round_over(self):
if self.round_over():
self.new_round()
if self.hand_over():
self.distribute_pot() | The code handles a player's fold action in a game: it marks the player as non-live, records their move, logs the fold event, advances to the next player's turn, and checks if the round is over. | def fold(self):
player = self.current_player()
player.live = False
player.moved = True
self.log.append(('fold', player.name))
self.set_turn_next()
self.handle_round_over() |
def score(self, player):
all_cards = player.hand + self.community_cards
all_ranks = [card[0] for card in all_cards]
all_suits = [card[1] for card in all_cards]
all_cards_sorted = sorted(all_cards, reverse=True)
all_ranks_set = sorted(set(all_ranks), reverse=True)
player.b... | This function initializes a new poker hand by resetting game state variables, shuffling the deck, dealing cards to active players, updating player statuses, and setting initial betting parameters including blinds. It also logs the action, filters out inactive players, and prepares the game for the next round of betting... | def new_hand(self):
self.round, self.pot, self.community_cards = 0, 0, []
self.live = True
self.hand += 1
self.log.append(['new_hand'])
self.deck = [(rank, suit) for suit in range(4) for rank in range(2, 15)]
random.shuffle(self.deck)
for player in self.players:
... |
def getAccess():
df = pd.read_excel('data/event_type/event_type.xlsx',sheet_name= "event_type")
dic = dict(zip(df['event_type'],df['access']))
special_permissions = []
divide_permissions = []
for key in dic.keys():
if dic[key] in ['maintain access','write access','triage access','onwer acces... | The function `calEntropy` calculates entropy from a timeline list by first gathering access permissions, special users, and collection data. It processes the timeline using `timelstToEntropy`, extracts keys and values from the result, and returns them as lists. | def calEntropy(repo,timelst):
global special_permissions
global divide_permissions
special_permissions,divide_permissions = getAccess()
global special_user_dic
special_user_dic = get_special_user(repo)
global collection_issues
global collection_timeline
collection_issues,collection_timel... |
def draw_line(num = 120):
print("="*num)
def align_left(str, num = 45):
print(" " * num, str)
def get_fruit_type(default_dataset_folder_path = "Dataset"):
arr = glob(f'{default_dataset_folder_path}/*/')
arr = [tmp_str.split("\\")[1] for tmp_str in arr]
arr += ["Exit"]
return arr
def pipeline_fin... | The code generates a balanced dataset of color, texture, and shape features from images in a directory. It calculates the minimum number of images per category, extracts features using a pipeline, constructs a DataFrame with labeled entries, fills missing values, shuffles data, and exports it as a CSV file named "Image... | def gen_dataset():
print("")
draw_line(screen_size)
# Get Minimum Number of Images
num_image_arr = []
for folder_path in glob(f'{default_dataset_folder_path}/*/'):
folder_name = folder_path.split("\\")[1]
all_images = glob(folder_path + "*.jpg")
num_image_arr.append(len(all_i... |
def load_autocomplete(self):
try:
conn = sqlite3.connect('./resource/data/stu_info.db')
cursor = conn.cursor()
sql_query = "SELECT DISTINCT name FROM std_details"
cursor.execute(sql_query)
# fetch all data from database
data = cursor.fetcha... | This code initializes a GUI window for managing student information, setting up window properties, styling elements, creating layout frames for input fields, data display (Treeview), and control buttons. It includes input validation, keyboard shortcuts, tooltips, and loads data for display, enabling user interactions l... | def __init__(self, window):
super().__init__()
self.window = window
window.title("Student Info")
f_w = 1280
f_h = 830
window.iconbitmap(window, r"./resource/microsoft.ico")
window.config(bg="#B0D9B1")
screen_w = window.winfo_screenwidth()
screen_h ... |
def start_query(self, query: str, database: str) -> str:
"""
Start a Query and return queryId
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/athena.html#Athena.Client.start_query_execution
"""
queryStart = self.athena.start_query_execution(
... | The main task of the code is to execute a query on a specified database, wait for its completion, and transfer the resulting output to a designated location if the query succeeds. It initiates the query, monitors its status, and handles output movement and compression, printing a confirmation upon successful completion... | def execute_query(self, query: str, database: str, output: str):
"""
This is the interface function that
1. start query
2. wait for output to materialize
3. move output to target location
"""
queryId, queryLoc, queryMetadata = self.start_query(query, database)
... |
def player_move(self, direction):
"""
Tries to move the player's molecule in the given direction.
Then connects the molecules in the level.
Args:
direction (str): The direction in which the player's molecule should move.
"""
playerMolecule = self.mode... | This function handles AI-driven gameplay events by moving the player's molecule in the specified direction, connecting molecules in the level, and checking if the player has won. It executes three key actions: player movement, molecule connection, and win condition verification to progress the game state. | def handle_AIevents(self, move):
"""
Handles the events of the level when the AI is playing.
The player's molecule is moved in the given direction.
Then the molecules in the level are connected.
Finally, it checks if the player has won the level.
Args:
... |
def move_up(self):
"""
Generates a new Sokobond_State object by moving the player's molecule up.
Returns:
Sokobond_State: The new Sokobond_State object.
"""
copy_level = copy.deepcopy(self.level)
controller = Level_Controller(copy_level)
controller.p... | The main task of the code is to generate all possible child states of the current state by applying valid movement operators (up, right, left, down). It checks each directional move, creates a new state if the move is possible, and returns a list of tuples containing the direction and corresponding new state. | def child_states(self):
"""
Generates all possible child states of the current state with the possible operators.
Returns:
list: A list of tuples, where each tuple contains the direction of the operator and the new state.
"""
new_states = []
if self.move_up()... |
def get_closest_cell(self) -> Cell:
cell = self.base.game.map.get_cell(self.base.game.map.pos_to_index(self.get_center()))
if self.closest_cell is not None:
self.closest_cell.linked_tanks.remove(self)
self.closest_cell = cell
cell.linked_tanks.append(self)
return ... | The code updates an object's movement and rotation toward a target, checks proximity to adjust position, handles auto-pathfinding for destructible cells, updates the turret, manages projectiles by removing expired ones, and decrements a fire timer for shooting logic. | def update(self):
self.get_closest_cell()
self.get_closest_target()
if self.moving:
sin = math.sin(math.radians(self.target_angle - self.angle))
targeted = round(sin * 20) / 20 == 0
if targeted:
self.rotate_instant(self.target_angle)
... |
def get_cell(self, index: int) -> Cell:
pos = self.index_to_rect(index)
return self.grid[pos[0]][pos[1]]
def neighbors(self, pos: tuple[int, int], include_diagonals: bool = False) -> list[int, int, int, int]:
x = pos[0]
y = pos[1]
out = [None if x - 1 < 0 else self.rect_to_index(... | This function performs a flood fill algorithm to determine if there's a path from the end cell to the start cell, considering movement rules based on the team's type (water or not). It uses BFS to explore cells, updating their values and checking connectivity, returning True if the start cell is reachable from the end ... | def flood_fill(self, start: int, end: int, team: Team) -> bool:
reached_start = False
water = team == Team.RED_WATER or team == Team.GREEN_WATER
team = team.value
ending_cell = self.get_cell(end)
end_cell_blocked = ending_cell.state != State.OPEN
if not end_cell_blocked:
... |
def get_cell(self, index: int) -> Cell:
pos = self.index_to_rect(index)
return self.grid[pos[0]][pos[1]]
def neighbors(self, pos: tuple[int, int], include_diagonals: bool = False) -> list[int, int, int, int]:
x = pos[0]
y = pos[1]
out = [None if x - 1 < 0 else self.rect_to_index(... | This function finds a path from a start cell to an end cell on a grid, prioritizing cells with lower values for the specified team. It selects valid neighbors (open or water-friendly cells) and chooses the one closest to the end using Euclidean distance. The path stops when reaching the end, hitting the max_range limit... | def traverse(self, start: int, end: int, team: Team, max_range: int = -1) -> list[Cell]:
water = team == Team.RED_WATER or team == Team.GREEN_WATER
team = team.value
start_cell = self.get_cell(start)
end_cell = self.get_cell(end)
path: list[Cell] = [start_cell]
while Tr... |
def range_test(self, smooth_beta: float = 0.8,
check_early_stopping: bool = True,
early_stopping_mult_factor: float = 3,
**_ignored):
"""Runs learning rate range test.
Trains model on data from given `DataLoader` with applying new learning rate b... | This code executes an LR range test to determine the optimal learning rate boundaries. It runs the test, identifies minimum and maximum optimal learning rates, calculates a median optimal value, and returns these three values as a tuple. | def __call__(self, **kwargs) -> 'Tuple[float, float, float]':
"""Runs LR range test and tries to find borders of optimal lr.
Args:
**kwargs: dict, which used as kwargs in all LRFinder methods
Returns:
Min/max borders of optimal lr and one median value of optimal lr
... |
def pretrain_routine(self):
self.model.train_preps(self)
if self.is_find_lr:
self.run_find_lr()
self.batches_per_epoch = len(self.train_loader) # it is needed for cyclic schedulers
self.lr_scheduler = LRSchedulerFactory.get_scheduler(
optimizer=self.optimizer,
... | This code trains a machine learning model for a specified number of epochs, performing training and validation phases. It updates model parameters using training data, evaluates performance on validation data, tracks the best validation loss/metrics, and saves model states (last and best). The function logs hyperparame... | def fit(self):
self.pretrain_routine()
epoch_tqdm = tqdm(total=self.num_epochs, desc='epochs', leave=True)
for self.epoch in range(self.num_epochs):
# train part
self.model.train()
for batch_idx, batch in tqdm(enumerate(self.train_loader),
... |
def find_det(matrix):
if matrix.shape[0] == 1:
return matrix[0][0]
elif matrix.shape[0] == 2:
return matrix[0][0]*matrix[1][1] - matrix[1][0]*matrix[0][1]
else:
row_with_most_zeros = _find_row_with_most_zeros(matrix)
det = 0
for j in range(matrix.shape[1]):
... | The code computes the inverse of a matrix using the Laplace expansion method by calculating the determinant, transposing the matrix of cofactors (complementary minors), and dividing by the determinant to return the inverse matrix. | def inv_laplace_method(matrix):
det = find_det(matrix)
transposed_complementary = transpose(find_complementary(matrix))
inversed = transposed_complementary / det
return inversed |
def read_data_to_dataframe(path):
'''
Method to read the data in to DataFrame
'''
if path is None:
raise ValueError('Need Path as argument !')
files = glob.glob(os.path.join(path, '*'))
data = pd.concat([pd.read_csv(file, sep=',', index_col=None, header=None) for file in files], ignore_i... | The main task of the code is to process input data by applying the Jenks natural breaks algorithm for classification, generate visualizations (scatter plots and pie charts), and save results including statistical summaries and classified data to a timestamped output directory. It reads data, executes classification, wr... | def main(input_path, output_path, num_classes):
output_path = os.path.join(os.getcwd(), "Output/{}".format(dt.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')))
os.makedirs(output_path)
data = read_data_to_dataframe(input_path)
with open(output_path + '/stats.txt', 'w') as f:
print('Plotting Scatter... |
def education_score(edu_list,param):
education_score={}
incomplete_edu={}
for i in candidates_qualifications:
education_score[i["name"]],incomplete_edu[i["name"]]=evaluate_education(i,edu_list,param)
incomplete_edu[i["name"]]=100-incomplete_edu[i["name"]]
return education_score,incomplet... | The code calculates weighted scores for education, skills, and work experience from input lists, aggregates them into total scores, sorts candidates by total score, and returns a structured result with individual scores and completeness metrics for each candidate. | def scores(edu_list,work_list,work_skill_list,data):
ttl={}
es,complete_edu=education_score(edu_list,data["parameters"]["eduparameters"])
ss,complete_ss=skill_score(data["parameters"]["skillparameters"])
ws,complete_ws=samp.work_exp(work_list,data["parameters"]["weparameters"],r_path)
wss=work_skill... |
def squareUnderAttack(self, r, c):
self.whiteToMove = not self.whiteToMove # switch to opponent's point of view
oppMoves = self.getAllPossibleMoves()
self.whiteToMove = not self.whiteToMove
for move in oppMoves:
if move.endRow == r and move.endCol == c: # square is under at... | This function generates valid castling moves for the king. It first checks if the king is in check, returning early if so. Depending on the player's turn and castling rights (kingside/queenside), it calls corresponding methods to add legal castling moves to the provided list. | def getCastleMoves(self, r, c, moves):
if self.squareUnderAttack(r, c):
return # Can't castle while in check
if (self.whiteToMove and self.currentCastlingRights.wks) or (not self.whiteToMove and self.currentCastlingRights.bks):
self.getKingsideCastleMoves(r, c, moves)
if ... |
def checkForPinsAndChecks(self):
pins = [] # Squares where the allied pinned piece is
checks = [] # Squares where enemy is applying the check
in_Check = False
if self.whiteToMove:
enemyColor = "b"
allyColor = "w"
startRow = self.whiteKingLocation[0]
... | This function generates valid chess moves considering checks, pins, and castling. It checks if the king is in check, handles single/double checks by blocking or moving the king, adds castling moves when not in check, and determines checkmate/stalemate. It returns the list of valid moves after processing all constraints... | def getValidMoves(self):
tempCastleRights = CastleRights(self.currentCastlingRights.wks, self.currentCastlingRights.bks, self.currentCastlingRights.wqs, self.currentCastlingRights)
moves = []
self.in_Check, self.pins, self.checks = self.checkForPinsAndChecks()
if self.whiteToMove:
... |
def loadZIPData(self, file_name, date_range):
"""
Load Google location data from a "takeout-*.zip" file.
"""
from bs4 import BeautifulSoup
"""
<div class="service_name">
<h1 class="data-folder-name" data-english-name="LOCATION_HISTORY" data-folder-name="Locati... | The code processes input data files (ZIP, JSON, KML) containing location data, loads them into a heatmap map, generates a map using specified tiles, and saves the resulting heatmap to an output file. | def run(self, data_files, output_file, date_range, tiles):
"""Load the data, generate the heatmap and save it.
Arguments:
data_files {list} -- List of names of the data files with the Google
location data or the Goole takeout ZIP archive.
output_file {string} -- ... |
def addressing(self, horizontal=True):
# vertical or horizontal addressing
if horizontal:
self.fn &= ~ADDRESSING_VERT
else:
self.fn |= ADDRESSING_VERT
self.cmd(self.fn)
def contrast(self, contrast=0x3f, bias=BIAS_1_40, temp=TEMP_COEFF_2):
for cmd in (
... | This code initializes a display device by configuring its settings: setting the function mode, enabling horizontal addressing, adjusting contrast with specified bias and temperature coefficients, activating normal display mode, and clearing the screen. | def init(self, horizontal=True, contrast=0x3f, bias=BIAS_1_40, temp=TEMP_COEFF_2):
# power up, horizontal addressing, basic instruction set
self.fn = FUNCTION_SET
self.addressing(horizontal)
self.contrast(contrast, bias, temp)
self.cmd(DISPLAY_NORMAL)
self.clear() |
def __repr__(self, connections=False) -> str:
return f"Waypoint(uuid={self.uuid}, hash={self.__hash__()}, _i={self._index}, i={self.index()}, pos={self.position}, conns={self.connections_str() if connections else len(self.connections)}, type={self.type.name}, angle={self.angle}, target={self.target})"
def to_st... | This method prints the object's string representations, including its `__repr__` (with a True flag), `to_str()`, `to_row()`, and `hashstr()` outputs, likely for debugging or inspection purposes. | def str(self) -> str:
print("self:",self)
print("__repr__:",self.__repr__(True))
print("to_str:",self.to_str())
print("to_row:",self.to_row())
print("hashstr:",self.hashstr()) |
def letterFrequency(cipher, shouldPrint="false"):
# (string) -> dict
# For a given string, returns a dictionary with keys being alphabet letters,
# and values their frequency in a given string, sorted by frequency
frequency = {}
for letter in alphabet:
frequency[letter] = cipher.count(lette... | This function decrypts a Caesar cipher by guessing the shift key using frequency analysis. It compares the most frequent letter in the cipher text with frequent letters in the specified language, applies the calculated shift to decode the message, and iteratively checks user confirmation for correctness. | def guessSingleKeyCaesar(cipher, language="english"):
# Encoding cipher in a given language
frequentLettersInLanguage = mostFrequentLetters[language]
frequentLettersInCipher = letterFrequency(cipher)
pivotLetter = frequentLettersInCipher[0][0]
guessed = "no"
currentIndex = 0
while (curr... |
def sendCmdHelper(s, cmd):
sendCommand(s, cmd)
time.sleep(0.5)
echo = s.recv(689)
echo = convertToString(echo[0:-2])
print(str(echo))
# If response not received, try again
# If received, go to the next button
while echo != cmd:
# sendCommand(s, cmd)
echo = s.recv(689)
... | The main task of the code is to initiate a trade process by navigating through a menu, inputting a 4-digit passcode (or generating one), confirming the code, and executing memory modifications to ensure successful trade execution. It involves sequential button clicks, passcode handling, and specific memory address mani... | def initiateTrade():
global code
# Gets to the code input menu
sendCmdHelper(s, "click Y")
time.sleep(0.55)
sendCmdHelper(s, "click A")
time.sleep(0.55)
sendCmdHelper(s, "click DDOWN")
time.sleep(0.55)
sendCmdHelper(s, "click A")
time.sleep(0.55)
sendCmdHelper(s, "click A")
... |
def showGreeting():
clear()
print("Welcome to Terminal War!")
print("This is a simple text based battle between several players.")
print("As your host, I will pick random numbers for each Player and we shall see who wins!")
def askPlayerCount():
print("How many players?")
players = input()
i... | The main task of the code is to run a multiplayer game by initializing player count, executing game rounds repeatedly until the player chooses to stop, and displaying the final win summary. It orchestrates greeting display, player input collection, round execution, and result presentation in a loop structure. | def RunGame():
showGreeting()
global numberPlayers
numberPlayers = askPlayerCount()
getPlayers()
runAgain = runRound()
while runAgain:
runAgain = runRound()
showWinSummary() |
def create_deck(self):
if self.number_of_players == 2:
self.colors = ['Red', 'Bleu']
if self.number_of_players == 3:
self.colors = ['Red', 'Bleu', 'Green']
numbers = [1]*3 + [2]*2 + [3]*2 + [4]*2 + [5]
deck = [s.Card(color, number) for color in self.colors for nu... | The code initializes a multiplayer card game by setting up players' hands, a deck of cards, information/fuse tokens, and a victory pool. It then enters a loop where each player takes turns performing actions, viewing their current state, and checking for game-ending conditions. The game continues until a termination co... | def __init__(self, number_of_players):
#init game
self.number_of_players = number_of_players
self.players_hands = [s.PlayerHand() for _ in range(number_of_players)]
self.played_cards = []
self.deck = self.create_deck()
self.information_tokens, self.fuse_tokens = self.crea... |
def broadcast(self, message):
encoded_message = f"Broadcast: {message}".encode()
for conn in self.client_connections:
try:
conn.sendall(encoded_message)
except socket.error as e:
print(f"Error sending message to client: {e}")
def show_sight(self,pl... | This code manages a player's turn in a multiplayer game by initializing threads, waiting for turn signals, broadcasting actions, handling card interactions, checking game-over conditions, and coordinating turn progression. It ensures synchronization between players using barriers and flags, processes player moves, and ... | def player_action(self, player_index):
#initialisation
listen_thread = threading.Thread(target=self.listen_to_main, args=(player_index,))
listen_thread.start()
self.init_barrier.wait()
#loop to break game
while not self.game_over.is_set():
self.turn_start[pl... |
def deal(deck, players): #function to help deal the cards to all the players
random.shuffle(deck)
numPlayers = len(players) #alias
count = 0 #alias
for card in deck:
players[count].append(card)
count = (count + 1)%numPlayers
def wh... | The code simulates a card game where the CPU and player take turns playing cards from their hands. The game continues until one player holds all 52 cards, winning. Players can choose to shuffle their hand or play a card. Face cards trigger special "PlayTillLim" duels. The game alternates turns, checks card values, and ... | def playGame():
global turn #by default the cpu goes first and they have turn 0
global you
global cpu
global pile
players = [cpu, you] #shallow copy
random.shuffle(deck)
deal(deck, players) ... |
def output_fn(ref, query, tabu_list):
if query is None:
return tf.zeros([max_length], tf.float32)
else:
query = glimpse(ref, query, tabu_list, "glimpse_{}".format(1))
return attention(ref, query, tabu_list, with_softmax=False, scope="attention")
de... | This function implements a decoder step in a sequence-to-sequence model. It generates the next input using sampled indices from the cell output, updates context states, and manages termination based on time limits. It handles both initial state setup and iterative decoding, returning updated states, inputs, and a termi... | def decoder_fn(time, cell_state, cell_input, cell_output, context_state):
cell_output = output_fn(enc_outputs, cell_output, context_state)
if cell_state is None:
cell_state = enc_final_states
next_input = cell_input
done = tf.zeros([batch_size, ], ... |
def output_fn(ref, query, tabu_list):
"""
:param ref: encoder_outputs,shape: [batch_size, max_length, hidden_dim]
:param query: the output of current cell, shape: [batch_size, beam_size, hidden_dim]
:param tabu_list: the list of items that have been fixed in a sequence
... | The function `beam_search_loop` performs one iteration of beam search for sequence generation. It calculates log probabilities from the cell output, combines them with prior beam probabilities, and selects top candidates using `top_k`. It updates beam states, symbols, and context states, then constructs the next loop s... | def beam_search_loop(time, cell_output, cell_state, loop_state):
"""
the loop of beam search
:param time:
:param cell_output: output of cell
:param cell_state: state of cell
:param loop_state: state of loop
:return:
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.